SpyBara
Go Premium

Documentation 2026-07-27 21:02 UTC to 2026-07-28 23:57 UTC

76 files changed +3,238 −2,246. View all changes and history on the product overview
2026
Wed 29 07:01 Tue 28 23:57 Mon 27 21:02 Sun 26 19:02 Sat 25 21:59 Fri 24 23:01 Thu 23 23:57 Wed 22 23:59 Tue 21 23:00 Mon 20 23:01 Sat 18 16:02 Fri 17 22:57 Thu 16 22:59 Wed 15 22:00 Tue 14 23:01 Mon 13 23:57 Sat 11 19:03 Fri 10 17:00 Thu 9 23:58 Wed 8 16:02 Tue 7 16:02 Mon 6 23:57 Sat 4 03:01 Fri 3 23:00 Thu 2 23:59 Wed 1 21:01

admin-setup.md +1 −1

Details

99 99 

100Organizations whose members authenticate through claude.ai or the Anthropic API can also govern models without deploying settings: [organization model restrictions](/docs/en/model-config#organization-model-restrictions) disable individual models, an [organization default model](/docs/en/model-config#organization-default-model) sets which model new sessions start on, and [organization effort limits](/docs/en/model-config#organization-effort-limits) cap effort levels per role. All three controls require a Claude Enterprise plan. Model restrictions and effort limits are enforced server-side; the default model is a starting point that users can change, unless the organization enforces it. Enforcement is available to a limited set of organizations; ask your Anthropic account team about availability. None of these controls reach sessions on Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, or [Claude Platform on AWS](/docs/en/claude-platform-on-aws); on those providers, use `availableModels` above for restrictions and the `model` key in managed settings for a default.100Organizations whose members authenticate through claude.ai or the Anthropic API can also govern models without deploying settings: [organization model restrictions](/docs/en/model-config#organization-model-restrictions) disable individual models, an [organization default model](/docs/en/model-config#organization-default-model) sets which model new sessions start on, and [organization effort limits](/docs/en/model-config#organization-effort-limits) cap effort levels per role. All three controls require a Claude Enterprise plan. Model restrictions and effort limits are enforced server-side; the default model is a starting point that users can change, unless the organization enforces it. Enforcement is available to a limited set of organizations; ask your Anthropic account team about availability. None of these controls reach sessions on Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, or [Claude Platform on AWS](/docs/en/claude-platform-on-aws); on those providers, use `availableModels` above for restrictions and the `model` key in managed settings for a default.

101 101 

102[Claude Code on the web](/docs/en/claude-code-on-the-web) has its own admin surface: on the Cloud environments page in admin settings, owners and admins create [organization-shared environments](/docs/en/claude-code-on-the-web#organization-shared-environments) that set the [network access level](/docs/en/claude-code-on-the-web#network-access), environment variables, and setup script for members' cloud sessions, and choose the organization's default environment.102[Claude Code on the web](/docs/en/claude-code-on-the-web) has its own admin surface: on the Cloud environments page in admin settings, owners and admins create [organization-shared environments](/docs/en/cloud-environments#organization-shared-environments) that set the [network access level](/docs/en/cloud-environments#network-access), environment variables, and setup script for members' cloud sessions. Owners and admins choose the organization's default environment separately, at [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code).

103 103 

104Permission rules and sandboxing cover different layers. Denying WebFetch blocks Claude's fetch tool, but if Bash is allowed, `curl` and `wget` can still reach any URL. Sandboxing closes that gap with a network domain allowlist enforced at the OS level.104Permission rules and sandboxing cover different layers. Denying WebFetch blocks Claude's fetch tool, but if Bash is allowed, `curl` and `wget` can still reach any URL. Sandboxing closes that gap with a network domain allowlist enforced at the OS level.

105 105 

advisor.md +1 −1

Details

85 85 

86Fable 5 requires Claude Code v2.1.170 or later and Fable 5 access, whether it acts as the main model or the advisor.86Fable 5 requires Claude Code v2.1.170 or later and Fable 5 access, whether it acts as the main model or the advisor.

87 87 

88Set the advisor as `opus` or `sonnet`, or as `fable` once the rollout returns it as an option. These aliases resolve to the latest version of each model. You can also pass a full model ID such as `claude-opus-5`.88Set the advisor as `opus` or `sonnet`, or as `fable` once the rollout returns it as an option. These aliases resolve to Claude Code's built-in default version for each model family, which advances with new Claude Code releases. You can also pass a full model ID such as `claude-opus-5`.

89 89 

90Subagents inherit the configured advisor and apply the same pairing check against their own model.90Subagents inherit the configured advisor and apply the same pairing check against their own model.

91 91 

Details

201If you don't set `effort`, both SDKs leave the parameter unset and defer to the model's default behavior.201If you don't set `effort`, both SDKs leave the parameter unset and defer to the model's default behavior.

202 202 

203<Note>203<Note>

204 `effort` trades latency and token cost for reasoning depth within each response. [Extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) is a separate feature that produces visible chain-of-thought blocks in the output. They are independent: you can set `effort: "low"` with extended thinking enabled, or `effort: "max"` without it.204 `effort` trades latency and token cost for reasoning depth within each response. [Extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) is a separate feature that produces `thinking` blocks in the output, and the `display` field on `ThinkingConfig` for [Python](/docs/en/agent-sdk/python#thinkingconfig) or [TypeScript](/docs/en/agent-sdk/typescript#thinkingconfig) controls whether you receive their text. They are independent: you can set `effort: "low"` with extended thinking enabled, or `effort: "max"` without it.

205</Note>205</Note>

206 206 

207Use lower effort for agents doing simple, well-scoped tasks (like listing files or running a single grep) to reduce cost and latency. Set `effort` in the top-level `query()` options for the whole session, or per subagent with the `effort` field on [`AgentDefinition`](/docs/en/agent-sdk/subagents#agentdefinition-configuration) to override the session level.207Use lower effort for agents doing simple, well-scoped tasks (like listing files or running a single grep) to reduce cost and latency. Set `effort` in the top-level `query()` options for the whole session, or per subagent with the `effort` field on [`AgentDefinition`](/docs/en/agent-sdk/subagents#agentdefinition-configuration) to override the session level.


234Here's how each component affects context in the SDK:234Here's how each component affects context in the SDK:

235 235 

236| Source | When it loads | Impact |236| Source | When it loads | Impact |

237| :----------------------- | :------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |237| :----------------------- | :------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

238| **System prompt** | Every request | Small fixed cost, always present |238| **System prompt** | Every request | Small fixed cost, always present |

239| **CLAUDE.md files** | Session start, via [`settingSources`](/docs/en/agent-sdk/claude-code-features) | Full content in every request (but prompt-cached, so only the first request pays full cost) |239| **CLAUDE.md files** | Session start, via [`settingSources`](/docs/en/agent-sdk/claude-code-features) | Full content in every request (but prompt-cached, so only the first request pays full cost) |

240| **Tool definitions** | Every request; MCP schemas deferred by default | Built-in tool schemas load every request. [Tool search](/docs/en/agent-sdk/mcp#mcp-tool-search) defers MCP tool schemas by default, falling back to upfront loading on Google Cloud's Agent Platform or a non-first-party `ANTHROPIC_BASE_URL`. See [Configure tool search](/docs/en/agent-sdk/tool-search#configure-tool-search) for the full matrix |240| **Tool definitions** | Every request; MCP schemas deferred by default | Built-in tool schemas load every request. [Tool search](/docs/en/agent-sdk/mcp#mcp-tool-search) defers MCP tool schemas by default, falling back to upfront loading on Google Cloud's Agent Platform, a non-first-party `ANTHROPIC_BASE_URL`, or a Microsoft Foundry deployment hosted on Azure. See [Configure tool search](/docs/en/agent-sdk/tool-search#configure-tool-search) for the full matrix |

241| **Conversation history** | Accumulates over turns | Grows with each turn: prompts, responses, tool inputs, tool outputs |241| **Conversation history** | Accumulates over turns | Grows with each turn: prompts, responses, tool inputs, tool outputs |

242| **Skill descriptions** | Session start, via setting sources | Short summaries; full content loads only when invoked |242| **Skill descriptions** | Session start, via setting sources | Short summaries; full content loads only when invoked |

243 243 


275 275 

276* **Use subagents for subtasks.** Each subagent starts with a fresh conversation (no prior message history, though it does load its own system prompt and project-level context like CLAUDE.md). It does not see the parent's turns, and only its final response returns to the parent as a tool result. The main agent's context grows by that summary, not by the full subtask transcript. See [What subagents inherit](/docs/en/agent-sdk/subagents#what-subagents-inherit) for details.276* **Use subagents for subtasks.** Each subagent starts with a fresh conversation (no prior message history, though it does load its own system prompt and project-level context like CLAUDE.md). It does not see the parent's turns, and only its final response returns to the parent as a tool result. The main agent's context grows by that summary, not by the full subtask transcript. See [What subagents inherit](/docs/en/agent-sdk/subagents#what-subagents-inherit) for details.

277* **Be selective with tools.** Every tool definition takes context space. Use the `tools` field on [`AgentDefinition`](/docs/en/agent-sdk/subagents#agentdefinition-configuration) to scope subagents to the minimum set they need.277* **Be selective with tools.** Every tool definition takes context space. Use the `tools` field on [`AgentDefinition`](/docs/en/agent-sdk/subagents#agentdefinition-configuration) to scope subagents to the minimum set they need.

278* **Watch MCP server costs.** [MCP tool search](/docs/en/agent-sdk/mcp#mcp-tool-search) defers MCP tool schemas by default and loads them on demand. When tool search is off, on Google Cloud's Agent Platform, or behind a non-first-party `ANTHROPIC_BASE_URL`, each MCP server adds all its tool schemas to every request, so a few servers with many tools can consume significant context before the agent does any work.278* **Watch MCP server costs.** [MCP tool search](/docs/en/agent-sdk/mcp#mcp-tool-search) defers MCP tool schemas by default and loads them on demand. When tool search is off or has fallen back to upfront loading, each MCP server adds all its tool schemas to every request, so a few servers with many tools can consume significant context before the agent does any work. The fallback applies on Google Cloud's Agent Platform, behind a non-first-party `ANTHROPIC_BASE_URL`, and on a Microsoft Foundry deployment hosted on Azure.

279* **Use lower effort for routine tasks.** Set [effort](#effort-level) to `"low"` for agents that only need to read files or list directories. This reduces token usage and cost.279* **Use lower effort for routine tasks.** Set [effort](#effort-level) to `"low"` for agents that only need to read files or list directories. This reduces token usage and cost.

280 280 

281For a detailed breakdown of per-feature context costs, see [Understand context costs](/docs/en/features-overview#understand-context-costs).281For a detailed breakdown of per-feature context costs, see [Understand context costs](/docs/en/features-overview#understand-context-costs).


434 ```434 ```

435</CodeGroup>435</CodeGroup>

436 436 

437When the agent finishes successfully, the example prints a `Done:` line with the agent's summary of the fix, then a line like `Cost: $0.0312`.

438 

437## Next steps439## Next steps

438 440 

439Now that you understand the loop, here's where to go depending on what you're building:441Now that you understand the loop, here's where to go depending on what you're building:

Details

15* **Recover from errors** when the agent makes incorrect modifications15* **Recover from errors** when the agent makes incorrect modifications

16 16 

17<Warning>17<Warning>

18 Only changes made through the Write, Edit, and NotebookEdit tools are tracked. Changes made through Bash commands (like `echo > file.txt` or `sed -i`) are not captured by the checkpoint system.18 Only changes made through the Write, Edit, and NotebookEdit tools are tracked. Changes made through Bash commands (like `echo > file.txt` or `sed -i`) are not captured by the checkpoint system, and neither are edits a [subagent](/docs/en/agent-sdk/subagents) applies, except a [skill with `context: fork`](/docs/en/skills#run-skills-in-a-subagent) that runs in the foreground.

19</Warning>19</Warning>

20 20 

21## How checkpointing works21## How checkpointing works


40* Files modified during the session40* Files modified during the session

41* The original content of modified files41* The original content of modified files

42 42 

43When you rewind to a checkpoint, created files are deleted and modified files are restored to their content at that point.43When you rewind to a checkpoint, Claude Code deletes the files it created and restores the files it modified to their content at that point. {/* min-version: 2.1.216 */}Claude Code skips a tracked path that is a symlink, hard link, or other non-regular file. It also skips a tracked file whose parent directory no longer resolves to its checkpoint-time location, or whose backup it can't read safely. [`RewindFilesResult`](/docs/en/agent-sdk/typescript#rewindfilesresult) counts every skipped path in its `skippedLinks` field. Skipping requires Claude Code v2.1.216 or later; before v2.1.216, a rewind wrote and deleted through links at tracked paths.

44 44 

45## Implement checkpointing45## Implement checkpointing

46 46 


191 <Step title="Capture checkpoint UUID and session ID">191 <Step title="Capture checkpoint UUID and session ID">

192 With the `replay-user-messages` option set (shown above), each user message in the response stream has a UUID that serves as a checkpoint.192 With the `replay-user-messages` option set (shown above), each user message in the response stream has a UUID that serves as a checkpoint.

193 193 

194 For most use cases, capture the first user message UUID (`message.uuid`); rewinding to it restores all files to their original state. To store multiple checkpoints and rewind to intermediate states, see [Multiple restore points](#multiple-restore-points).194 For most use cases, capture the first user message UUID (`message.uuid`); rewinding to it restores the tracked files to their original state. To store multiple checkpoints and rewind to intermediate states, see [Multiple restore points](#multiple-restore-points).

195 195 

196 Capturing the session ID (`message.session_id`) is optional; you only need it if you want to rewind later, after the stream completes. If you're calling `rewindFiles()` immediately while still processing messages (as the example in [Checkpoint before risky operations](#checkpoint-before-risky-operations) does), you can skip capturing the session ID.196 Capturing the session ID (`message.session_id`) is optional; you only need it if you want to rewind later, after the stream completes. If you're calling `rewindFiles()` immediately while still processing messages (as the example in [Checkpoint before risky operations](#checkpoint-before-risky-operations) does), you can skip capturing the session ID.

197 197 


257 ```257 ```

258 </CodeGroup>258 </CodeGroup>

259 259 

260 If you capture the session ID and checkpoint ID, you can also rewind from the CLI. This command requires the `claude` executable, which comes from [installing Claude Code](/en/setup) and is not installed by the SDK package. The SDK enables checkpointing for you, but when you run `claude -p` directly you must set the `CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING` environment variable:260 If you capture the session ID and checkpoint ID, you can also rewind from the CLI. This command requires the `claude` executable, which comes from [installing Claude Code](/docs/en/setup) and is not installed by the SDK package. The SDK enables checkpointing for you, but when you run `claude -p` directly you must set the `CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING` environment variable:

261 261 

262 ```bash theme={null}262 ```bash theme={null}

263 CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING=true claude -p --resume <session-id> --rewind-files <checkpoint-uuid>263 CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING=true claude -p --resume <session-id> --rewind-files <checkpoint-uuid>


486 486 

487This complete example creates a small utility file, has the agent add documentation comments, shows you the changes, then asks if you want to rewind.487This complete example creates a small utility file, has the agent add documentation comments, shows you the changes, then asks if you want to rewind.

488 488 

489Before you begin, make sure you have the [Claude Agent SDK installed](/en/agent-sdk/quickstart).489Before you begin, make sure you have the [Claude Agent SDK installed](/docs/en/agent-sdk/quickstart).

490 490 

491<Steps>491<Steps>

492 <Step title="Create a test file">492 <Step title="Create a test file">


725File checkpointing has the following limitations:725File checkpointing has the following limitations:

726 726 

727| Limitation | Description |727| Limitation | Description |

728| ---------------------------------- | -------------------------------------------------------------------- |728| ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

729| Write/Edit/NotebookEdit tools only | Changes made through Bash commands are not tracked |729| Write/Edit/NotebookEdit tools only | Changes made through Bash commands are not tracked |

730| Subagent edits | Edits a [subagent](/docs/en/agent-sdk/subagents) applies aren't tracked or restored, except a skill with `context: fork` running in the foreground; use git to revert untracked edits |

730| Same session | Checkpoints are tied to the session that created them |731| Same session | Checkpoints are tied to the session that created them |

731| File content only | Creating, moving, or deleting directories is not undone by rewinding |732| File content only | Creating, moving, or deleting directories is not undone by rewinding |

732| Local files | Remote or network files are not tracked |733| Local files | Remote or network files are not tracked |


816 817 

817## Next steps818## Next steps

818 819 

819* **[Sessions](/en/agent-sdk/sessions)**: learn how to resume sessions, which is required for rewinding after the stream completes. Covers session IDs, resuming conversations, and session forking.820* **[Sessions](/docs/en/agent-sdk/sessions)**: learn how to resume sessions, which is required for rewinding after the stream completes. Covers session IDs, resuming conversations, and session forking.

820* **[Permissions](/en/agent-sdk/permissions)**: configure which tools Claude can use and how file modifications are approved. Useful if you want more control over when edits happen.821* **[Permissions](/docs/en/agent-sdk/permissions)**: configure which tools Claude can use and how file modifications are approved. Useful if you want more control over when edits happen.

821* **[TypeScript SDK reference](/en/agent-sdk/typescript)**: complete API reference including all options for `query()` and the `rewindFiles()` method.822* **[TypeScript SDK reference](/docs/en/agent-sdk/typescript)**: complete API reference including all options for `query()` and the `rewindFiles()` method.

822* **[Python SDK reference](/en/agent-sdk/python)**: complete API reference including all options for `ClaudeAgentOptions` and the `rewind_files()` method.823* **[Python SDK reference](/docs/en/agent-sdk/python)**: complete API reference including all options for `ClaudeAgentOptions` and the `rewind_files()` method.

agent-sdk/hooks.md +46 −30

Details

24 </Step>24 </Step>

25 25 

26 <Step title="The SDK collects registered hooks">26 <Step title="The SDK collects registered hooks">

27 The SDK checks for hooks registered for that event type. This includes callback hooks you pass in `options.hooks` and shell command hooks from settings files when the corresponding [`settingSources`](/en/agent-sdk/typescript#settingsource) or [`setting_sources`](/en/agent-sdk/python#settingsource) entry is enabled, which it is for default `query()` options.27 The SDK checks for hooks registered for that event type. This includes callback hooks you pass in `options.hooks` and shell command hooks from settings files when the corresponding [`settingSources`](/docs/en/agent-sdk/typescript#settingsource) or [`setting_sources`](/docs/en/agent-sdk/python#settingsource) entry is enabled, which it is for default `query()` options.

28 </Step>28 </Step>

29 29 

30 <Step title="Matchers filter which hooks run">30 <Step title="Matchers filter which hooks run">


153| `PostToolUseFailure` | Yes | Yes | Tool execution failure | Handle or log tool errors |153| `PostToolUseFailure` | Yes | Yes | Tool execution failure | Handle or log tool errors |

154| `PostToolBatch` | No | Yes | A full batch of tool calls resolves, once per batch before the next model call | Inject conventions once for the whole batch |154| `PostToolBatch` | No | Yes | A full batch of tool calls resolves, once per batch before the next model call | Inject conventions once for the whole batch |

155| `UserPromptSubmit` | Yes | Yes | User prompt submission | Inject additional context into prompts |155| `UserPromptSubmit` | Yes | Yes | User prompt submission | Inject additional context into prompts |

156| [`UserPromptExpansion`](/en/hooks#userpromptexpansion) | No | Yes | A user-typed command, or an MCP prompt, expands into a prompt before it reaches Claude. Doesn't fire when Claude invokes a skill itself | Block a command from direct invocation or add context when a skill is typed |156| [`UserPromptExpansion`](/docs/en/hooks#userpromptexpansion) | No | Yes | A user-typed command, or an MCP prompt, expands into a prompt before it reaches Claude. Doesn't fire when Claude invokes a skill itself | Block a command from direct invocation or add context when a skill is typed |

157| `MessageDisplay` | No | Yes | An assistant message with text completes, once per message with the full message text | Redact or reformat the displayed text without changing the transcript |157| `MessageDisplay` | No | Yes | An assistant message with text completes, once per message with the full message text | Redact or reformat the displayed text without changing the transcript |

158| `Stop` | Yes | Yes | Agent execution stop | Save session state before exit |158| `Stop` | Yes | Yes | Agent execution stop | Save session state before exit |

159| `StopFailure` | No | Yes | The turn ends with an API error instead of a normal stop | Log failures or send alerts |159| `StopFailure` | No | Yes | The turn ends with an API error instead of a normal stop | Log failures or send alerts |


161| `SubagentStop` | Yes | Yes | Subagent completion | Aggregate results from parallel tasks |161| `SubagentStop` | Yes | Yes | Subagent completion | Aggregate results from parallel tasks |

162| `PreCompact` | Yes | Yes | Conversation compaction request | Archive full transcript before summarizing |162| `PreCompact` | Yes | Yes | Conversation compaction request | Archive full transcript before summarizing |

163| `PostCompact` | No | Yes | Conversation compaction completes | Log the generated summary |163| `PostCompact` | No | Yes | Conversation compaction completes | Log the generated summary |

164| `PermissionRequest` | Yes | Yes | Permission dialog would be displayed | Custom permission handling |164| `PermissionRequest` | Yes | Yes | A tool call needs a permission decision | Custom permission handling |

165| `PermissionDenied` | No | Yes | The auto mode classifier denies a tool call | Log classifier denials or tell the model it may retry |165| `PermissionDenied` | No | Yes | The auto mode classifier denies a tool call | Log classifier denials or tell the model it may retry |

166| `SessionStart` | No | Yes | Session initialization | Initialize logging and telemetry |166| `SessionStart` | No | Yes | Session initialization | Initialize logging and telemetry |

167| `SessionEnd` | No | Yes | Session termination | Clean up temporary resources |167| `SessionEnd` | No | Yes | Session termination | Clean up temporary resources |


178| `WorktreeRemove` | No | Yes | Git worktree removed | Clean up workspace resources |178| `WorktreeRemove` | No | Yes | Git worktree removed | Clean up workspace resources |

179| `CwdChanged` | No | Yes | The working directory changes during a session | Reload environment variables per directory |179| `CwdChanged` | No | Yes | The working directory changes during a session | Reload environment variables per directory |

180| `FileChanged` | No | Yes | A watched file is modified, created, or deleted | Reload configuration when project files change |180| `FileChanged` | No | Yes | A watched file is modified, created, or deleted | Reload configuration when project files change |

181| `DirectoryAdded` | No | Yes | A working directory is added during a session | Install dependencies for a repository added mid-session |

181 182 

182## Configure hooks183## Configure hooks

183 184 


216 217 

217### Matchers218### Matchers

218 219 

219Use matchers to filter when your callbacks fire. The `matcher` field matches against a different value depending on the hook event type. For example, tool-based hooks match against the tool name, while `Notification` hooks match against the notification type. See the [Claude Code hooks reference](/en/hooks#matcher-patterns) for the full list of matcher values for each event type.220Use matchers to filter when your callbacks fire. The `matcher` field matches against a different value depending on the hook event type. For example, tool-based hooks match against the tool name, while `Notification` hooks match against the notification type. See the [Claude Code hooks reference](/docs/en/hooks#matcher-patterns) for the full list of matcher values for each event type.

220 221 

221SDK matchers follow the same rules as [matchers in settings files](/en/hooks#matcher-patterns). A matcher containing only letters, digits, `_`, `-`, spaces, `,`, and `|` is compared as an exact string, with alternatives separated by `|` or `,` and optional surrounding whitespace, so `Write|Edit` and `Write, Edit` each match exactly those two tools and `code-reviewer` matches only that agent type. A matcher of `*`, an empty string, or omitting the matcher entirely matches every occurrence of the event.222SDK matchers follow the same rules as [matchers in settings files](/docs/en/hooks#matcher-patterns). A matcher containing only letters, digits, `_`, `-`, spaces, `,`, and `|` is compared as an exact string, with alternatives separated by `|` or `,` and optional surrounding whitespace, so `Write|Edit` and `Write, Edit` each match exactly those two tools and `code-reviewer` matches only that agent type. A matcher of `*`, an empty string, or omitting the matcher entirely matches every occurrence of the event.

222 223 

223A matcher containing any other character is evaluated as an unanchored regular expression, so `^mcp__` matches every MCP tool and `Edit.*` matches both `Edit` and `NotebookEdit`. Wrap a regular expression in `^` and `$` when you need a whole-string match.224A matcher containing any other character is evaluated as an unanchored regular expression, so `^mcp__` matches every MCP tool and `Edit.*` matches both `Edit` and `NotebookEdit`. Wrap a regular expression in `^` and `$` when you need a whole-string match.

224 225 


226 227 

227Hyphens in the exact-match set require a Claude Code runtime of v2.1.195 or later. On earlier versions a hyphenated name like `code-reviewer` is evaluated as an unanchored regular expression and must be anchored as `^code-reviewer$` to match exactly.228Hyphens in the exact-match set require a Claude Code runtime of v2.1.195 or later. On earlier versions a hyphenated name like `code-reviewer` is evaluated as an unanchored regular expression and must be anchored as `^code-reviewer$` to match exactly.

228 229 

229`StopFailure` and `FileChanged` use a narrower exact-match set of letters, digits, `_`, and `|` only. A hyphen, space, or comma in a matcher for those two events keeps it on the regular-expression path, and only `|` separates alternatives, so write `rate_limit|overloaded`, not `rate_limit, overloaded`. `FileChanged` additionally uses its matcher to build the watch list of literal filenames; see [FileChanged in the hooks reference](/en/hooks#filechanged).230`StopFailure` and `FileChanged` use a narrower exact-match set of letters, digits, `_`, and `|` only. A hyphen, space, or comma in a matcher for those two events keeps it on the regular-expression path, and only `|` separates alternatives, so write `rate_limit|overloaded`, not `rate_limit, overloaded`. `FileChanged` additionally uses its matcher to build the watch list of literal filenames; see [FileChanged in the hooks reference](/docs/en/hooks#filechanged).

230 231 

231| Option | Type | Default | Description |232| Option | Type | Default | Description |

232| --------- | ---------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |233| --------- | ---------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

233| `matcher` | `string` | `undefined` | Pattern matched against the event's filter field, following the comparison rules above. For tool hooks, this is the tool name. Built-in tools include `Bash`, `Read`, `Write`, `Edit`, `Glob`, `Grep`, `WebFetch`, `Agent`, and others (see [Tool Input Types](/en/agent-sdk/typescript#tool-input-types) for the full list). MCP tools use the pattern `mcp__<server>__<action>`. |234| `matcher` | `string` | `undefined` | Pattern matched against the event's filter field, following the comparison rules above. For tool hooks, this is the tool name. Built-in tools include `Bash`, `Read`, `Write`, `Edit`, `Glob`, `Grep`, `WebFetch`, `Agent`, and others (see [Tool Input Types](/docs/en/agent-sdk/typescript#tool-input-types) for the full list). MCP tools use the pattern `mcp__<server>__<action>`. |

234| `hooks` | `HookCallback[]` | - | Required. Array of callback functions to execute when the pattern matches |235| `hooks` | `HookCallback[]` | - | Required. Array of callback functions to execute when the pattern matches |

235| `timeout` | `number` | `undefined` | Timeout in seconds. When omitted, the per-event default applies: 10 minutes for most events, 30 seconds for `UserPromptSubmit`. A few events run with shorter limits, such as 10 seconds for `MessageDisplay` |236| `timeout` | `number` | `undefined` | Timeout in seconds. When omitted, Claude Code applies the [event's default timeout](#hook-timeout): 10 minutes for most events, 30 seconds for `UserPromptSubmit`. Claude Code uses shorter limits for a few events, such as 10 seconds for `MessageDisplay` and a 1.5-second default [budget](/docs/en/hooks#sessionend-input) for `SessionEnd`. Your SDK callbacks follow the `command` hook defaults |

236 237 

237Use the `matcher` pattern to target specific tools whenever possible. A matcher with `'Bash'` only runs for Bash commands, while omitting the pattern runs your callbacks for every occurrence of the event.238Use the `matcher` pattern to target specific tools whenever possible. A matcher with `'Bash'` only runs for Bash commands, while omitting the pattern runs your callbacks for every occurrence of the event.

238 239 

239For tool-based hooks, matchers only filter by tool name, not by file paths or other arguments. To filter by file path, check `tool_input.file_path` inside your callback.240For tool-based hooks, matchers only filter by tool name, not by file paths or other arguments. To filter by file path, check `tool_input.file_path` inside your callback.

240 241 

241<Tip>242<Tip>

242 **Discovering tool names:** See [Tool Input Types](/en/agent-sdk/typescript#tool-input-types) for the full list of built-in tool names, or add a hook without a matcher to log all tool calls your session makes.243 **Discovering tool names:** See [Tool Input Types](/docs/en/agent-sdk/typescript#tool-input-types) for the full list of built-in tool names, or add a hook without a matcher to log all tool calls your session makes.

243 244 

244 **MCP tool naming:** MCP tools always start with `mcp__` followed by the server name and action: `mcp__<server>__<action>`. For example, if you configure a server named `playwright`, its tools are named `mcp__playwright__browser_screenshot`, `mcp__playwright__browser_click`, and so on. The server name comes from the key you use in the `mcpServers` configuration.245 **MCP tool naming:** MCP tools always start with `mcp__` followed by the server name and action: `mcp__<server>__<action>`. For example, if you configure a server named `playwright`, its tools are named `mcp__playwright__browser_screenshot`, `mcp__playwright__browser_click`, and so on. The server name comes from the key you use in the `mcpServers` configuration.

245</Tip>246</Tip>


250 251 

251Every hook callback receives three arguments:252Every hook callback receives three arguments:

252 253 

253* **Input data:** a typed object containing event details. Each hook type has its own input shape. For example, `PreToolUseHookInput` includes `tool_name` and `tool_input`, while `NotificationHookInput` includes `message`. See the full type definitions in the [TypeScript](/en/agent-sdk/typescript#hookinput) and [Python](/en/agent-sdk/python#hookinput) SDK references.254* **Input data:** a typed object containing event details. Each hook type has its own input shape. For example, `PreToolUseHookInput` includes `tool_name` and `tool_input`, while `NotificationHookInput` includes `message`. See the full type definitions in the [TypeScript](/docs/en/agent-sdk/typescript#hookinput) and [Python](/docs/en/agent-sdk/python#hookinput) SDK references.

254 * All hook inputs share `session_id`, `cwd`, and `hook_event_name`.255 * All hook inputs share `session_id`, `cwd`, and `hook_event_name`.

255 * `agent_id` and `agent_type` are populated when the hook fires inside a subagent. In TypeScript, these are on the base hook input and available to all hook types. In Python, they are optional fields on `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, and `PermissionRequest`, and required fields on `SubagentStart` and `SubagentStop`.256 * `agent_id` and `agent_type` are populated when the hook fires inside a subagent. In TypeScript, these are on the base hook input and available to all hook types. In Python, they are optional fields on `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, and `PermissionRequest`, and required fields on `SubagentStart` and `SubagentStop`.

256* **Tool use ID** (`str | None` / `string | undefined`): correlates `PreToolUse` and `PostToolUse` events for the same tool call.257* **Tool use ID** (`str | None` / `string | undefined`): correlates `PreToolUse` and `PostToolUse` events for the same tool call.


261Your callback returns an object with two categories of fields:262Your callback returns an object with two categories of fields:

262 263 

263* **Top-level fields** work the same on every event: `systemMessage` shows a message to the user, and `continue` (`continue_` in Python) determines whether the agent keeps running after this hook.264* **Top-level fields** work the same on every event: `systemMessage` shows a message to the user, and `continue` (`continue_` in Python) determines whether the agent keeps running after this hook.

264* **`hookSpecificOutput`** controls the current operation. The fields inside depend on the hook event type. For `PreToolUse` hooks, this is where you set `permissionDecision` (`"allow"`, `"deny"`, `"ask"`, or `"defer"`), `permissionDecisionReason`, and `updatedInput`. Returning `"defer"` ends the query so you can [resume it later](/en/hooks#defer-a-tool-call-for-later). For `PostToolUse` hooks, you can set `additionalContext` to append information to the tool result. To replace the tool's output before Claude sees it, set `updatedToolOutput`, which works for any tool in both SDKs. The older `updatedMCPToolOutput` field replaces MCP tool output only and is deprecated.265* **`hookSpecificOutput`** controls the current operation. The fields inside depend on the hook event type. For `PreToolUse` hooks, this is where you set `permissionDecision` (`"allow"`, `"deny"`, `"ask"`, or `"defer"`), `permissionDecisionReason`, and `updatedInput`. Returning `"defer"` ends the query so you can [resume it later](/docs/en/hooks#defer-a-tool-call-for-later). For `PostToolUse` hooks, you can set `additionalContext` to append information to the tool result. To replace the tool's output before Claude sees it, set `updatedToolOutput`, which works for any tool in both SDKs. The older `updatedMCPToolOutput` field replaces MCP tool output only and is deprecated.

265 266 

266Return `{}` to allow the operation without changes. SDK callback hooks use the same JSON output format as [Claude Code shell command hooks](/en/hooks#json-output), which documents every field and event-specific option. For the SDK type definitions, see the [TypeScript](/en/agent-sdk/typescript#synchookjsonoutput) and [Python](/en/agent-sdk/python#synchookjsonoutput) SDK references.267Return `{}` to allow the operation without changes. SDK callback hooks use the same JSON output format as [Claude Code shell command hooks](/docs/en/hooks#json-output), which documents every field and event-specific option. For the SDK type definitions, see the [TypeScript](/docs/en/agent-sdk/typescript#synchookjsonoutput) and [Python](/docs/en/agent-sdk/python#synchookjsonoutput) SDK references.

267 268 

268<Note>269<Note>

269 When multiple hooks or permission rules apply, `deny` takes priority over `defer`, which takes priority over `ask`, which takes priority over `allow`. If any hook returns `deny`, the operation is blocked regardless of other hooks.270 When multiple hooks or permission rules apply, `deny` takes priority over `defer`, which takes priority over `ask`, which takes priority over `allow`. If any hook returns `deny`, the operation is blocked regardless of other hooks.


353</CodeGroup>354</CodeGroup>

354 355 

355<Note>356<Note>

356 When using `updatedInput`, you must also include `permissionDecision: 'allow'` to auto-approve the modified input or `permissionDecision: 'ask'` to show it to the user. With `'defer'`, `updatedInput` is ignored. Always return a new object rather than mutating the original `tool_input`.357 Pair `updatedInput` with `permissionDecision: 'allow'` to auto-approve the modified input, or `permissionDecision: 'ask'` to show it to the user. If you omit `permissionDecision`, the modified input still applies and flows through the normal permission evaluation. With `'defer'`, `updatedInput` is ignored. Always return a new object rather than mutating the original `tool_input`.

357</Note>358</Note>

358 359 

360To confirm the redirect, set the prefix to a path you can write to, such as `./sandbox` or `/tmp/sandbox` (macOS doesn't allow creating a root-level `/sandbox` directory), then ask the agent to write a file: the Write tool's result in the message stream names the path with your sandbox prefix rather than the one Claude requested.

361 

359### Add context and block a tool362### Add context and block a tool

360 363 

361This example blocks writes to the `/etc` directory and explains why to both the model and the user:364This example blocks writes to the `/etc` directory and explains why to both the model and the user:


524 527 

525### Track subagent activity528### Track subagent activity

526 529 

527Use `SubagentStop` hooks to monitor when subagents finish their work. See the full input type in the [TypeScript](/en/agent-sdk/typescript#hookinput) and [Python](/en/agent-sdk/python#hookinput) SDK references. This example logs a summary each time a subagent completes:530Use `SubagentStop` hooks to monitor when subagents finish their work. See the full input type in the [TypeScript](/docs/en/agent-sdk/typescript#hookinput) and [Python](/docs/en/agent-sdk/python#hookinput) SDK references. This example logs a summary each time a subagent completes:

528 531 

529<CodeGroup>532<CodeGroup>

530 ```python Python theme={null}533 ```python Python theme={null}


654 ```657 ```

655</CodeGroup>658</CodeGroup>

656 659 

660To confirm the hook fires, point the webhook URL at an endpoint you can watch and send a prompt that uses a tool: the hook sends a POST with the tool name and timestamp after each tool completes.

661 

657### Forward notifications to Slack662### Forward notifications to Slack

658 663 

659Use `Notification` hooks to receive system notifications from the agent and forward them to external services. Notifications fire for event types such as:664Use `Notification` hooks to receive system notifications from the agent and forward them to external services. Notifications fire for event types such as:


663* `auth_success` when authentication completes668* `auth_success` when authentication completes

664* `elicitation_dialog`, `elicitation_complete`, and `elicitation_response` for user-prompt elicitation flows669* `elicitation_dialog`, `elicitation_complete`, and `elicitation_response` for user-prompt elicitation flows

665 670 

671In headless SDK sessions, only the elicitation events `elicitation_complete` and `elicitation_response` fire this hook; the other types are emitted by interactive UI that SDK sessions don't run. Permission requests, for example, go to the `canUseTool` callback instead.

672 

666Each notification includes a `message` field with a human-readable description and optionally a `title`.673Each notification includes a `message` field with a human-readable description and optionally a `title`.

667 674 

668This example forwards every notification to a Slack channel. It requires a [Slack incoming webhook URL](https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/), which you create by adding an app to your Slack workspace and enabling incoming webhooks:675This example forwards every notification to a Slack channel. It requires a [Slack incoming webhook URL](https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/), which you create by adding an app to your Slack workspace and enabling incoming webhooks:


761 ```768 ```

762</CodeGroup>769</CodeGroup>

763 770 

771When a `Notification` event fires, the hook posts the notification's `message`, prefixed with `Agent status:`, to the channel your webhook targets.

772 

764## Fix common issues773## Fix common issues

765 774 

766### Hook not firing775### Hook not firing


768* Verify the hook event name is correct and case-sensitive (`PreToolUse`, not `preToolUse`)777* Verify the hook event name is correct and case-sensitive (`PreToolUse`, not `preToolUse`)

769* Check that your matcher pattern matches the tool name exactly778* Check that your matcher pattern matches the tool name exactly

770* Ensure the hook is under the correct event type in `options.hooks`779* Ensure the hook is under the correct event type in `options.hooks`

771* For non-tool hooks that support matchers, like `Notification` and `SubagentStop`, matchers match against different fields, and `Stop` ignores matchers entirely (see [matcher patterns](/en/hooks#matcher-patterns))780* For non-tool hooks that support matchers, like `Notification` and `SubagentStop`, matchers match against different fields, and `Stop` ignores matchers entirely (see [matcher patterns](/docs/en/hooks#matcher-patterns))

772* Hooks may not fire when the agent hits the [`max_turns`](/en/agent-sdk/python#claudeagentoptions) limit because the session ends before hooks can execute781* Hooks may not fire when the agent hits the [`max_turns`](/docs/en/agent-sdk/python#claudeagentoptions) limit because the session ends before hooks can execute

773 782 

774### Matcher not filtering as expected783### Matcher not filtering as expected

775 784 


788 797 

789### Hook timeout798### Hook timeout

790 799 

791* Increase the `timeout` value in the `HookMatcher` configuration800Claude Code runs each callback with a timeout, which you set in seconds with the `timeout` field on its `HookMatcher`. When you don't set one, Claude Code uses the event's default: 600 seconds for most events, 30 seconds for `UserPromptSubmit`, and 10 seconds for `MessageDisplay`. Claude Code runs `SessionEnd` callbacks during shutdown under the shorter [SessionEnd timeout budget](/docs/en/hooks#sessionend-input).

792* Use the `AbortSignal` from the third callback argument to handle cancellation gracefully in TypeScript801 

802When a callback exceeds its timeout, Claude Code cancels it and treats it as a failed hook: it discards the callback's output and the session continues rather than hanging. What happens next depends on the event:

803 

804* `PreToolUse`: {/* min-version: 2.1.210 */}Claude Code doesn't run the tool call, Claude receives a tool result stating the hook didn't respond before its timeout, and the turn continues. If another `PreToolUse` hook returned an explicit deny, Claude receives that denial instead of the timeout error. Before v2.1.210, Claude Code reported the timeout to Claude as a user rejection, which made unattended sessions stop and wait for input.

805* `PostToolUse` and `PostToolUseFailure`: Claude Code keeps the tool result and the turn continues.

806* `UserPromptSubmit` and [`UserPromptExpansion`](/docs/en/hooks#userpromptexpansion): {/* min-version: 2.1.208 */}Claude Code blocks the prompt with a message naming the hook and the timeout, and the session continues. Because a callback on these events can act as a policy gate, Claude Code never lets a timed-out prompt through unscreened. Before v2.1.208, Claude Code ended the query with `error_during_execution` when a callback on these events timed out.

807* `Stop` and `SubagentStop`: Claude Code shows a warning and the agent stops normally.

808* Other events, such as `Notification` and `PreCompact`: Claude Code logs the failure and continues.

793 809 

794{/* min-version: 2.1.208 */}A `UserPromptSubmit` or [`UserPromptExpansion`](/en/hooks#userpromptexpansion) callback that exceeds its timeout blocks that prompt with a timeout message and the session continues. Interrupting the query while a callback is pending cancels the pending tool call. Before v2.1.208, a callback timeout on those events ended the query with `error_during_execution`, and an interrupt during a pending `PreToolUse` callback could let the tool call proceed.810{/* min-version: 2.1.208 */}If you interrupt the query while a callback is pending, Claude Code cancels the pending tool call. Before v2.1.208, the tool call could still proceed if you interrupted during a pending `PreToolUse` callback.

795 811 

796{/* min-version: 2.1.210 */}A `PreToolUse` callback that exceeds its timeout blocks the tool call, and Claude receives an error result naming the timeout. If another `PreToolUse` hook returned an explicit deny, Claude receives that denial instead. Before v2.1.210, Claude Code reported the timeout to Claude as if the user had rejected the tool call, so an unattended session stopped and waited for input.812If your callback needs more time, set a higher `timeout` on its `HookMatcher`. In TypeScript, use the `AbortSignal` from the third callback argument to handle cancellation gracefully when the timeout fires.

797 813 

798### Tool blocked unexpectedly814### Tool blocked unexpectedly

799 815 


815 };831 };

816 ```832 ```

817 833 

818* Return `permissionDecision: 'allow'` to auto-approve the modified input, or `'ask'` to show it to the user for approval834* Don't pair `updatedInput` with `permissionDecision: 'defer'`, which drops the modified input. Omitting `permissionDecision` is fine: the modified input still applies through the normal permission evaluation. You can also return `'allow'` to auto-approve the modified input or `'ask'` to show it to the user for approval

819 835 

820* Include `hookEventName` in `hookSpecificOutput` to identify which hook type the output is for836* Include `hookEventName` in `hookSpecificOutput` to identify which hook type the output is for

821 837 

822### Session hooks not available in Python838### Session hooks not available in Python

823 839 

824`SessionStart` and `SessionEnd` can be registered as SDK callback hooks in TypeScript, but aren't available in the Python SDK because its `HookEvent` type omits them. In Python, they are only available as [shell command hooks](/en/hooks#hook-events) defined in settings files such as `.claude/settings.json`. To load shell command hooks from your SDK application, include the appropriate setting source with [`setting_sources`](/en/agent-sdk/python#settingsource) or [`settingSources`](/en/agent-sdk/typescript#settingsource):840`SessionStart` and `SessionEnd` can be registered as SDK callback hooks in TypeScript, but aren't available in the Python SDK because its `HookEvent` type omits them. In Python, they are only available as [shell command hooks](/docs/en/hooks#hook-events) defined in settings files such as `.claude/settings.json`. To load shell command hooks from your SDK application, include the appropriate setting source with [`setting_sources`](/docs/en/agent-sdk/python#settingsource) or [`settingSources`](/docs/en/agent-sdk/typescript#settingsource):

825 841 

826<CodeGroup>842<CodeGroup>

827 ```python Python theme={null}843 ```python Python theme={null}


853 869 

854### systemMessage not appearing in output870### systemMessage not appearing in output

855 871 

856The `systemMessage` field shows a message to the user, not the model. By default the SDK surfaces hook output in the message stream only for `SessionStart` and `Setup` hooks, so a message from any other hook event doesn't appear unless you set `includeHookEvents` (`include_hook_events` in Python). To pass context to the model instead, return [`additionalContext`](/en/hooks#add-context-for-claude).872The `systemMessage` field shows a message to the user, not the model. By default the SDK surfaces hook output in the message stream only for `SessionStart` and `Setup` hooks, so a message from any other hook event doesn't appear unless you set `includeHookEvents` (`include_hook_events` in Python). To pass context to the model instead, return [`additionalContext`](/docs/en/hooks#add-context-for-claude).

857 873 

858If you need to surface hook decisions to your application reliably, log them separately or use a dedicated output channel.874If you need to surface hook decisions to your application reliably, log them separately or use a dedicated output channel.

859 875 

860## Related resources876## Related resources

861 877 

862* [Claude Code hooks reference](/en/hooks): full JSON input/output schemas, event documentation, and matcher patterns878* [Claude Code hooks reference](/docs/en/hooks): full JSON input/output schemas, event documentation, and matcher patterns

863* [Claude Code hooks guide](/en/hooks-guide): shell command hook examples and walkthroughs879* [Claude Code hooks guide](/docs/en/hooks-guide): shell command hook examples and walkthroughs

864* [TypeScript SDK reference](/en/agent-sdk/typescript): hook types, input/output definitions, and configuration options880* [TypeScript SDK reference](/docs/en/agent-sdk/typescript): hook types, input/output definitions, and configuration options

865* [Python SDK reference](/en/agent-sdk/python): hook types, input/output definitions, and configuration options881* [Python SDK reference](/docs/en/agent-sdk/python): hook types, input/output definitions, and configuration options

866* [Permissions](/en/agent-sdk/permissions): control what your agent can do882* [Permissions](/docs/en/agent-sdk/permissions): control what your agent can do

867* [Custom tools](/en/agent-sdk/custom-tools): build tools to extend agent capabilities883* [Custom tools](/docs/en/agent-sdk/custom-tools): build tools to extend agent capabilities

Details

13If you do not need infrastructure control, custom isolation, or your own data plane, consider [Managed Agents](https://platform.claude.com/docs/en/managed-agents/overview) instead: a hosted REST API where Anthropic runs the agent and the sandbox, so your application sends events and streams back results with no hosting infrastructure to operate.13If you do not need infrastructure control, custom isolation, or your own data plane, consider [Managed Agents](https://platform.claude.com/docs/en/managed-agents/overview) instead: a hosted REST API where Anthropic runs the agent and the sandbox, so your application sends events and streams back results with no hosting infrastructure to operate.

14 14 

15<Info>15<Info>

16 For security hardening beyond basic sandboxing, including network controls, credential management, and isolation options, see [Secure Deployment](/en/agent-sdk/secure-deployment).16 For security hardening beyond basic sandboxing, including network controls, credential management, and isolation options, see [Secure Deployment](/docs/en/agent-sdk/secure-deployment).

17</Info>17</Info>

18 18 

19## The subprocess model19## The subprocess model


44| `CLAUDE.md` memory files | `~/.claude/CLAUDE.md` for the user tier and the session's working directory for the project tier |44| `CLAUDE.md` memory files | `~/.claude/CLAUDE.md` for the user tier and the session's working directory for the project tier |

45| Working-directory artifacts | The session's working directory |45| Working-directory artifacts | The session's working directory |

46 46 

47To persist transcripts across hosts, configure a [`SessionStore` adapter](/en/agent-sdk/session-storage). Memory files and other working-directory artifacts need their own storage strategy, such as a mounted volume or an object-store sync.47To persist transcripts across hosts, configure a [`SessionStore` adapter](/docs/en/agent-sdk/session-storage). Memory files and other working-directory artifacts need their own storage strategy, such as a mounted volume or an object-store sync.

48 48 

49For how sessions, resumption, and forking work at the API level, see [Sessions](/en/agent-sdk/sessions).49For how sessions, resumption, and forking work at the API level, see [Sessions](/docs/en/agent-sdk/sessions).

50 50 

51## Choose a session pattern51## Choose a session pattern

52 52 


58 58 

59Example workloads include bug investigation and fix, invoice and receipt extraction, document translation, and media transformation.59Example workloads include bug investigation and fix, invoice and receipt extraction, document translation, and media transformation.

60 60 

61The container runs a one-shot entrypoint that calls the SDK and exits. The example below shows a minimal TypeScript version. Save it as `entrypoint.mts` or set `"type": "module"` in `package.json` so top-level `await` is available.61The container runs a one-shot entrypoint that calls the SDK and exits. In TypeScript, save the file as `entrypoint.mts` or set `"type": "module"` in `package.json` so top-level `await` is available.

62 62 

63```typescript theme={null}63<CodeGroup>

64import { query } from "@anthropic-ai/claude-agent-sdk";64 ```typescript TypeScript theme={null}

65 import { query } from "@anthropic-ai/claude-agent-sdk";

65 66 

66const prompt = process.env.TASK_PROMPT!;67 const prompt = process.env.TASK_PROMPT!;

67for await (const message of query({ prompt, options: { maxTurns: 20 } })) {68 for await (const message of query({ prompt, options: { maxTurns: 20 } })) {

68 console.log(message);69 console.log(message);

69}70 }

70```71 ```

72 

73 ```python Python theme={null}

74 import asyncio

75 import os

76 

77 from claude_agent_sdk import ClaudeAgentOptions, query

78 

79 

80 async def main():

81 async for message in query(

82 prompt=os.environ["TASK_PROMPT"],

83 options=ClaudeAgentOptions(max_turns=20),

84 ):

85 print(message)

86 

87 

88 asyncio.run(main())

89 ```

90</CodeGroup>

71 91 

72### Long-running sessions92### Long-running sessions

73 93 


75 95 

76Example workloads include an email agent that triages and responds to incoming mail, a site builder that hosts a per-user editable site through container ports, and a chat bot that handles continuous traffic from a platform like Slack.96Example workloads include an email agent that triages and responds to incoming mail, a site builder that hosts a per-user editable site through container ports, and a chat bot that handles continuous traffic from a platform like Slack.

77 97 

78The container exposes an HTTP or WebSocket endpoint and maps each active session to a long-lived query and the subprocess behind it. In TypeScript, use [`streamInput()`](/en/agent-sdk/typescript#query-object) to add turns to an active session and [`startup()`](/en/agent-sdk/typescript#startup) to pre-warm subprocesses ahead of incoming traffic. In Python, use [`ClaudeSDKClient`](/en/agent-sdk/python#claudesdkclient) to hold a session open across turns. Size the container so it can hold the maximum number of concurrent sessions in memory.98The container exposes an HTTP or WebSocket endpoint and maps each active session to a long-lived query and the subprocess behind it. In TypeScript, use [`streamInput()`](/docs/en/agent-sdk/typescript#query-object) to add turns to an active session and [`startup()`](/docs/en/agent-sdk/typescript#startup) to pre-warm subprocesses ahead of incoming traffic. In Python, use [`ClaudeSDKClient`](/docs/en/agent-sdk/python#claudesdkclient) to hold a session open across turns. Size the container so it can hold the maximum number of concurrent sessions in memory.

79 99 

80### Hybrid sessions100### Hybrid sessions

81 101 

82Ephemeral containers that hydrate from a [`SessionStore`](/en/agent-sdk/session-storage) on startup and persist updates back. Best for sessions that span many interactions but sit idle between them. The container spins down during idle periods and spins back up when the user returns.102Ephemeral containers that hydrate from a [`SessionStore`](/docs/en/agent-sdk/session-storage) on startup and persist updates back. Best for sessions that span many interactions but sit idle between them. The container spins down during idle periods and spins back up when the user returns.

83 103 

84Example workloads include a personal project manager with intermittent check-ins, deep research that pauses and resumes over hours, and a customer support agent that loads ticket history across interactions.104Example workloads include a personal project manager with intermittent check-ins, deep research that pauses and resumes over hours, and a customer support agent that loads ticket history across interactions.

85 105 


127 ```147 ```

128</CodeGroup>148</CodeGroup>

129 149 

130See [Session storage](/en/agent-sdk/session-storage) for the full `SessionStore` interface and reference adapters.150See [Session storage](/docs/en/agent-sdk/session-storage) for the full `SessionStore` interface and reference adapters.

131 151 

132### Multi-agent container152### Multi-agent container

133 153 


158* [Fly Machines](https://fly.io/docs/machines/)178* [Fly Machines](https://fly.io/docs/machines/)

159* [Vercel Sandbox](https://vercel.com/docs/functions/sandbox)179* [Vercel Sandbox](https://vercel.com/docs/functions/sandbox)

160 180 

161For self-hosted options such as Docker, gVisor, and Firecracker, and detailed isolation configuration, see [Isolation Technologies](/en/agent-sdk/secure-deployment#isolation-technologies).181For self-hosted options such as Docker, gVisor, and Firecracker, and detailed isolation configuration, see [Isolation Technologies](/docs/en/agent-sdk/secure-deployment#isolation-technologies).

162 182 

163### Runtime dependencies183### Runtime dependencies

164 184 


175 195 

176### Network196### Network

177 197 

178The SDK needs outbound HTTPS to `api.anthropic.com`, or to your provider's regional endpoint when running on Amazon Bedrock or Google Cloud's Agent Platform. If your agents use [MCP servers](/en/agent-sdk/mcp) or external tools, they need outbound access to those endpoints as well. For production, route outbound traffic through an egress proxy that enforces domain allowlists, injects credentials, and logs requests. See [Secure Deployment](/en/agent-sdk/secure-deployment) for the full pattern.198The SDK needs outbound HTTPS to `api.anthropic.com`, or to your provider's regional endpoint when running on Amazon Bedrock or Google Cloud's Agent Platform. If your agents use [MCP servers](/docs/en/agent-sdk/mcp) or external tools, they need outbound access to those endpoints as well. For production, route outbound traffic through an egress proxy that enforces domain allowlists, injects credentials, and logs requests. See [Secure Deployment](/docs/en/agent-sdk/secure-deployment) for the full pattern.

179 199 

180For inbound traffic, expose an HTTP or WebSocket port on the container. Your application handles client requests on that port and calls the SDK internally; the subprocess itself does not listen on the network.200For inbound traffic, expose an HTTP or WebSocket port on the container. Your application handles client requests on that port and calls the SDK internally; the subprocess itself does not listen on the network.

181 201 


185 205 

186### Session and state persistence206### Session and state persistence

187 207 

188Default local disk is lost on restart, scale-down, or a move to a different node. For any session a user expects to resume, mirror the transcript to durable storage with a [`SessionStore` adapter](/en/agent-sdk/session-storage). See [Reference implementations](/en/agent-sdk/session-storage#reference-implementations) for S3, Redis, and Postgres adapters and a conformance suite for your own.208Default local disk is lost on restart, scale-down, or a move to a different node. For any session a user expects to resume, mirror the transcript to durable storage with a [`SessionStore` adapter](/docs/en/agent-sdk/session-storage). See [Reference implementations](/docs/en/agent-sdk/session-storage#reference-implementations) for S3, Redis, and Postgres adapters and a conformance suite for your own.

189 209 

190Three things to know about how `SessionStore` behaves:210Three things to know about how `SessionStore` behaves:

191 211 


209OTEL_EXPORTER_OTLP_ENDPOINT=http://collector.example.com:4318229OTEL_EXPORTER_OTLP_ENDPOINT=http://collector.example.com:4318

210```230```

211 231 

212Prompt text and tool inputs are not included in exports by default. See [Control sensitive data in exports](/en/agent-sdk/observability#control-sensitive-data-in-exports) for the opt-in flags, and [Observability](/en/agent-sdk/observability) for the full signal catalog.232Prompt text and tool inputs are not included in exports by default. See [Control sensitive data in exports](/docs/en/agent-sdk/observability#control-sensitive-data-in-exports) for the opt-in flags, and [Observability](/docs/en/agent-sdk/observability) for the full signal catalog.

213 233 

214### Auth and secrets234### Auth and secrets

215 235 

216Three auth concerns matter at hosting time:236Three auth concerns matter at hosting time:

217 237 

218* **Anthropic API**: the subprocess reads `ANTHROPIC_API_KEY` from its environment. Supply it from your secret manager, or set `ANTHROPIC_BASE_URL` to route model calls through a proxy that injects the key outside the container. See [Credential management](/en/agent-sdk/secure-deployment#credential-management) for the proxy pattern and the [SDK overview](/en/agent-sdk/overview#get-started) for supported authentication methods.238* **Anthropic API**: the subprocess reads `ANTHROPIC_API_KEY` from its environment. Supply it from your secret manager, or set `ANTHROPIC_BASE_URL` to route model calls through a proxy that injects the key outside the container. See [Credential management](/docs/en/agent-sdk/secure-deployment#credential-management) for the proxy pattern and [Setup in the SDK quickstart](/docs/en/agent-sdk/quickstart#setup) for supported authentication methods.

219* **Inbound**: put authentication at a gateway in front of the agent container. The agent should receive pre-authenticated requests and should not be the component that validates user tokens.239* **Inbound**: put authentication at a gateway in front of the agent container. The agent should receive pre-authenticated requests and should not be the component that validates user tokens.

220* **Outbound tools**: keep tool credentials out of the agent environment. Route outbound calls through a proxy that injects API keys after the request leaves the container. The agent makes the call; the proxy adds the credential.240* **Outbound tools**: keep tool credentials out of the agent environment. Route outbound calls through a proxy that injects API keys after the request leaves the container. The agent makes the call; the proxy adds the credential.

221 241 


233 253 

234Horizontal-scale routing depends on your pattern. For long-running sessions, where containers hold many sessions, run a pool of containers behind a load balancer and pin each session to one container using consistent hashing on `sessionId`. A pinned session keeps hitting the same container, and therefore the same running subprocess, until it is evicted or the container restarts.254Horizontal-scale routing depends on your pattern. For long-running sessions, where containers hold many sessions, run a pool of containers behind a load balancer and pin each session to one container using consistent hashing on `sessionId`. A pinned session keeps hitting the same container, and therefore the same running subprocess, until it is evicted or the container restarts.

235 255 

236Large fanouts of concurrent [subagents](/en/agent-sdk/subagents) from a single session can hit API rate limits. Break the work into smaller batches rather than issuing one wide dispatch.256Large fanouts of concurrent [subagents](/docs/en/agent-sdk/subagents) from a single session can hit API rate limits. Break the work into smaller batches rather than issuing one wide dispatch.

237 257 

238### Cost258### Cost

239 259 

240Anthropic token cost typically dominates container infrastructure cost by an order of magnitude or more. A minimally provisioned container runs roughly \$0.05 per hour, while a single long agent session can spend dollars in tokens. See [Cost tracking](/en/agent-sdk/cost-tracking) for per-session token accounting.260Anthropic token cost typically dominates container infrastructure cost by an order of magnitude or more. A minimally provisioned container runs roughly \$0.05 per hour, while a single long agent session can spend dollars in tokens. See [Cost tracking](/docs/en/agent-sdk/cost-tracking) for per-session token accounting.

241 261 

242### Multi-tenant isolation262### Multi-tenant isolation

243 263 


246To isolate tenants inside a shared container:266To isolate tenants inside a shared container:

247 267 

248* Pass `settingSources: []` in TypeScript or `setting_sources=[]` in Python so no filesystem settings load.268* Pass `settingSources: []` in TypeScript or `setting_sources=[]` in Python so no filesystem settings load.

249* Set `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` in `env`. [Auto memory](/en/memory#auto-memory) at `~/.claude/projects/<project>/memory/` loads into the system prompt regardless of `settingSources`. See [What settingSources does not control](/en/agent-sdk/claude-code-features#what-settingsources-does-not-control) for the other inputs that load unconditionally.269* Set `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` in `env`. [Auto memory](/docs/en/memory#auto-memory) at `~/.claude/projects/<project>/memory/` loads into the system prompt regardless of `settingSources`. See [What settingSources does not control](/docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control) for the other inputs that load unconditionally.

250* Point `CLAUDE_CONFIG_DIR` at a per-tenant directory so tenants do not share the `~/.claude.json` global config.270* Point `CLAUDE_CONFIG_DIR` at a per-tenant directory so tenants do not share the `~/.claude.json` global config.

251* Use a per-tenant working directory. Pass `cwd` explicitly on every `query()` call.271* Use a per-tenant working directory. Pass `cwd` explicitly on every `query()` call.

252* Apply per-tenant egress rules at your proxy, such as distinct outbound IPs, credentials, or domain allowlists, so a compromised tenant cannot exfiltrate data via another tenant's outbound policy.272* Apply per-tenant egress rules at your proxy, such as distinct outbound IPs, credentials, or domain allowlists, so a compromised tenant cannot exfiltrate data via another tenant's outbound policy.


305 ```325 ```

306</CodeGroup>326</CodeGroup>

307 327 

308For per-tenant network controls, see [Secure Deployment](/en/agent-sdk/secure-deployment).328For per-tenant network controls, see [Secure Deployment](/docs/en/agent-sdk/secure-deployment).

309 329 

310## Known limitations330## Known limitations

311 331 


316| No top-level session timeout | A session does not time out on its own. Set `maxTurns` in `Options` to bound how many tool-use round trips the agent takes before stopping. |336| No top-level session timeout | A session does not time out on its own. Set `maxTurns` in `Options` to bound how many tool-use round trips the agent takes before stopping. |

317| Memory growth over long sessions | Cap session length or recycle subprocesses periodically. See [Scaling and concurrency](#scaling-and-concurrency). |337| Memory growth over long sessions | Cap session length or recycle subprocesses periodically. See [Scaling and concurrency](#scaling-and-concurrency). |

318| Large parallel-subagent fanouts can hit rate limits | Break work into smaller batches rather than issuing one wide dispatch. |338| Large parallel-subagent fanouts can hit rate limits | Break work into smaller batches rather than issuing one wide dispatch. |

319| No per-subagent wall-clock deadline | Cap each [subagent](/en/agent-sdk/subagents) with `maxTurns` in its `AgentDefinition`. For background subagents only, `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS` sets a stall watchdog that fires when a `run_in_background` subagent stops producing output; it is not a total-runtime deadline. |339| No per-subagent wall-clock deadline | Cap each [subagent](/docs/en/agent-sdk/subagents) with `maxTurns` in its `AgentDefinition`. For background subagents only, `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS` sets a stall watchdog that fires when a `run_in_background` subagent stops producing output; it is not a total-runtime deadline. |

320 340 

321## Next steps341## Next steps

322 342 

323* [Hosting cookbook](https://github.com/anthropics/claude-cookbooks/blob/main/claude_agent_sdk/07_Hosting_the_agent.ipynb): notebook walkthrough with [deployable code](https://github.com/anthropics/claude-cookbooks/tree/main/claude_agent_sdk/hosting) for Docker, Modal, and Kubernetes.343* [Hosting cookbook](https://github.com/anthropics/claude-cookbooks/blob/main/claude_agent_sdk/07_Hosting_the_agent.ipynb): notebook walkthrough with [deployable code](https://github.com/anthropics/claude-cookbooks/tree/main/claude_agent_sdk/hosting) for Docker, Modal, and Kubernetes.

324* [Session storage](/en/agent-sdk/session-storage): persist transcripts across hosts with a `SessionStore` adapter.344* [Session storage](/docs/en/agent-sdk/session-storage): persist transcripts across hosts with a `SessionStore` adapter.

325* [Observability](/en/agent-sdk/observability): export OTEL traces, metrics, and logs to your collector.345* [Observability](/docs/en/agent-sdk/observability): export OTEL traces, metrics, and logs to your collector.

326* [Secure deployment](/en/agent-sdk/secure-deployment): network controls, credential management, and isolation hardening.346* [Secure deployment](/docs/en/agent-sdk/secure-deployment): network controls, credential management, and isolation hardening.

327* [Cost tracking](/en/agent-sdk/cost-tracking): per-session token and cost accounting.347* [Cost tracking](/docs/en/agent-sdk/cost-tracking): per-session token and cost accounting.

Details

45 45 

46## Customize agent behavior46## Customize agent behavior

47 47 

48Output styles, `append`, and a custom prompt string each change the system prompt directly. CLAUDE.md takes a different path: the SDK reads it and injects its content into the conversation as project context, not into the system prompt, so it shapes behavior alongside whichever system prompt you choose. [Skills](/en/agent-sdk/skills), [hooks](/en/agent-sdk/hooks), and [permissions](/en/agent-sdk/permissions) also shape behavior outside the system prompt and are covered on their own pages.48Output styles, `append`, and a custom prompt string each change the system prompt directly. CLAUDE.md takes a different path: the SDK reads it and injects its content into the conversation as project context, not into the system prompt, so it shapes behavior alongside whichever system prompt you choose. [Skills](/docs/en/agent-sdk/skills), [hooks](/docs/en/agent-sdk/hooks), and [permissions](/docs/en/agent-sdk/permissions) also shape behavior outside the system prompt and are covered on their own pages.

49 49 

50### CLAUDE.md files for project-level instructions50### CLAUDE.md files for project-level instructions

51 51 

52CLAUDE.md files give Claude persistent project context and instructions. The SDK injects their content into the conversation, not into the system prompt, so they work with any system prompt configuration. For what to put in CLAUDE.md, where to place it, and how to write effective instructions, see [How Claude remembers your project](/en/memory). This section covers what's specific to the SDK: how CLAUDE.md loads.52CLAUDE.md files give Claude persistent project context and instructions. The SDK injects their content into the conversation, not into the system prompt, so they work with any system prompt configuration. For what to put in CLAUDE.md, where to place it, and how to write effective instructions, see [How Claude remembers your project](/docs/en/memory). This section covers what's specific to the SDK: how CLAUDE.md loads.

53 53 

54The SDK reads CLAUDE.md when the matching setting source is enabled: `'project'` loads `CLAUDE.md` or `.claude/CLAUDE.md` from the working directory, and `'user'` loads `~/.claude/CLAUDE.md`. Default `query()` options enable both sources, so CLAUDE.md loads automatically. If you set `settingSources` in TypeScript or `setting_sources` in Python explicitly, include the sources you need. CLAUDE.md loading is controlled by setting sources, not by the `claude_code` preset.54The SDK reads CLAUDE.md when the matching setting source is enabled: `'project'` loads `CLAUDE.md` or `.claude/CLAUDE.md` from the working directory, and `'user'` loads `~/.claude/CLAUDE.md`. Default `query()` options enable both sources, so CLAUDE.md loads automatically. If you set `settingSources` in TypeScript or `setting_sources` in Python explicitly, include the sources you need. CLAUDE.md loading is controlled by setting sources, not by the `claude_code` preset.

55 55 


80 ```80 ```

81 81 

82 ```python Python theme={null}82 ```python Python theme={null}

83 import asyncio

84 

83 from claude_agent_sdk import query, ClaudeAgentOptions85 from claude_agent_sdk import query, ClaudeAgentOptions

84 86 

85 messages = []87 messages = []

86 88 

89 

90 async def main():

87 async for message in query(91 async for message in query(

88 prompt="Add a new React component for user profiles",92 prompt="Add a new React component for user profiles",

89 options=ClaudeAgentOptions(93 options=ClaudeAgentOptions(


96 ):100 ):

97 messages.append(message)101 messages.append(message)

98 102 

103 

104 asyncio.run(main())

105 

99 # Now Claude has access to your project guidelines from CLAUDE.md106 # Now Claude has access to your project guidelines from CLAUDE.md

100 ```107 ```

101</CodeGroup>108</CodeGroup>

102 109 

110When you run either example, the SDK streams messages as Claude works: a system init message, assistant messages, user messages carrying tool results, and a final result message with the session outcome.

111 

103CLAUDE.md is persistent across all sessions in a project, shared with your team through git, and discovered automatically without code changes. It is not loaded if you pass an empty `settingSources` array.112CLAUDE.md is persistent across all sessions in a project, shared with your team through git, and discovered automatically without code changes. It is not loaded if you pass an empty `settingSources` array.

104 113 

105### Output styles for persistent configurations114### Output styles for persistent configurations


108 117 

109#### Create an output style118#### Create an output style

110 119 

111An output style is a markdown file with [frontmatter](/en/output-styles#frontmatter) for metadata, followed by the prompt content. Save it to `~/.claude/output-styles/` for a user-level style available in every project, or `.claude/output-styles/` in your repository for a project-level style you can commit and share with your team.120An output style is a markdown file with [frontmatter](/docs/en/output-styles#frontmatter) for metadata, followed by the prompt content. Save it to `~/.claude/output-styles/` for a user-level style available in every project, or `.claude/output-styles/` in your repository for a project-level style you can commit and share with your team.

112 121 

113By default, a custom output style replaces the `claude_code` preset's software engineering instructions with your own. To keep them and layer your instructions on top, set `keep-coding-instructions: true` in the frontmatter. Keep them when your agent is still doing software engineering work. Leave them out when you're replacing the role entirely.122By default, a custom output style replaces the `claude_code` preset's software engineering instructions with your own. To keep them and layer your instructions on top, set `keep-coding-instructions: true` in the frontmatter. Keep them when your agent is still doing software engineering work. Leave them out when you're replacing the role entirely.

114 123 


174 ```183 ```

175 184 

176 ```python Python theme={null}185 ```python Python theme={null}

186 import asyncio

187 

177 from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage188 from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage

178 189 

179 messages = []190 messages = []

180 191 

192 

193 async def main():

181 async for message in query(194 async for message in query(

182 prompt="Help me write a Python function to calculate fibonacci numbers",195 prompt="Help me write a Python function to calculate fibonacci numbers",

183 options=ClaudeAgentOptions(196 options=ClaudeAgentOptions(


191 messages.append(message)204 messages.append(message)

192 if isinstance(message, AssistantMessage):205 if isinstance(message, AssistantMessage):

193 print(message.content)206 print(message.content)

207 

208 

209 asyncio.run(main())

194 ```210 ```

195</CodeGroup>211</CodeGroup>

196 212 


226 ```242 ```

227 243 

228 ```python Python theme={null}244 ```python Python theme={null}

245 import asyncio

246 

229 from claude_agent_sdk import query, ClaudeAgentOptions247 from claude_agent_sdk import query, ClaudeAgentOptions

230 248 

249 

250 async def main():

231 async for message in query(251 async for message in query(

232 prompt="Triage the open issues in this repo",252 prompt="Triage the open issues in this repo",

233 options=ClaudeAgentOptions(253 options=ClaudeAgentOptions(


240 ),260 ),

241 ):261 ):

242 ...262 ...

263 

264 

265 asyncio.run(main())

243 ```266 ```

244</CodeGroup>267</CodeGroup>

245 268 

246**Tradeoffs:** the working directory, the git-repo flag, the platform, the active shell, the OS version, and auto-memory paths still reach Claude, but as part of the first user message rather than the system prompt. Instructions in the user message carry marginally less weight than the same text in the system prompt, so Claude may rely on them less strongly when reasoning about the current directory or auto-memory paths. Enable this option when cross-session cache reuse matters more than maximally authoritative environment context.269**Tradeoffs:** the working directory, the git-repo flag, the platform, the active shell, the OS version, and auto-memory paths still reach Claude, but as part of the first user message rather than the system prompt. Instructions in the user message carry marginally less weight than the same text in the system prompt, so Claude may rely on them less strongly when reasoning about the current directory or auto-memory paths. Enable this option when cross-session cache reuse matters more than maximally authoritative environment context.

247 270 

248For the equivalent flag in non-interactive CLI mode, see [`--exclude-dynamic-system-prompt-sections`](/en/cli-reference).271For the equivalent flag in non-interactive CLI mode, see [`--exclude-dynamic-system-prompt-sections`](/docs/en/cli-reference).

249 272 

250### Custom system prompts273### Custom system prompts

251 274 


279 ```302 ```

280 303 

281 ```python Python theme={null}304 ```python Python theme={null}

305 import asyncio

306 

282 from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage307 from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage

283 308 

284 custom_prompt = """You are a Python coding specialist.309 custom_prompt = """You are a Python coding specialist.


291 316 

292 messages = []317 messages = []

293 318 

319 

320 async def main():

294 async for message in query(321 async for message in query(

295 prompt="Create a data processing pipeline",322 prompt="Create a data processing pipeline",

296 options=ClaudeAgentOptions(system_prompt=custom_prompt),323 options=ClaudeAgentOptions(system_prompt=custom_prompt),


298 messages.append(message)325 messages.append(message)

299 if isinstance(message, AssistantMessage):326 if isinstance(message, AssistantMessage):

300 print(message.content)327 print(message.content)

328 

329 

330 asyncio.run(main())

301 ```331 ```

302</CodeGroup>332</CodeGroup>

303 333 

334In Python, load a large custom prompt from a file with `system_prompt={"type": "file", "path": "..."}` instead of passing it as a string. The Python SDK passes a string prompt as one command-line argument to the CLI subprocess, so a prompt that exceeds the OS argument-length limit fails at process spawn before any API request is sent. On Linux the error is `Argument list too long`. See [`SystemPromptFile`](/docs/en/agent-sdk/python#systempromptfile) for the platform thresholds and the Windows behavior.

335 

304## Compare the four approaches336## Compare the four approaches

305 337 

306The four customization methods differ in where they live, how they're shared, and what they preserve from the `claude_code` preset.338The four customization methods differ in where they live, how they're shared, and what they preserve from the `claude_code` preset.


323 355 

324### When to use CLAUDE.md356### When to use CLAUDE.md

325 357 

326Use CLAUDE.md for instructions that should apply to every session in a project, regardless of which system prompt the session uses: coding standards, common commands, architecture context, and team conventions. CLAUDE.md is committed to your repository, so it stays in sync with the code it describes. See [When to add to CLAUDE.md](/en/memory#when-to-add-to-claude-md) for full guidance.358Use CLAUDE.md for instructions that should apply to every session in a project, regardless of which system prompt the session uses: coding standards, common commands, architecture context, and team conventions. CLAUDE.md is committed to your repository, so it stays in sync with the code it describes. See [When to add to CLAUDE.md](/docs/en/memory#when-to-add-to-claude-md) for full guidance.

327 359 

328CLAUDE.md files load when the `project` setting source is enabled, which it is for default `query()` options. If you set `settingSources` in TypeScript or `setting_sources` in Python explicitly, include `'project'` to keep loading project-level CLAUDE.md.360CLAUDE.md files load when the `project` setting source is enabled, which it is for default `query()` options. If you set `settingSources` in TypeScript or `setting_sources` in Python explicitly, include `'project'` to keep loading project-level CLAUDE.md.

329 361 


404 ```436 ```

405 437 

406 ```python Python theme={null}438 ```python Python theme={null}

439 import asyncio

440 

407 from claude_agent_sdk import query, ClaudeAgentOptions441 from claude_agent_sdk import query, ClaudeAgentOptions

408 442 

409 # Assuming "Code Reviewer" output style is active (via /config or settings)443 # Assuming "Code Reviewer" output style is active (via /config or settings)

410 # Add session-specific focus areas444 # Add session-specific focus areas

411 messages = []445 messages = []

412 446 

447 

448 async def main():

413 async for message in query(449 async for message in query(

414 prompt="Review this authentication module",450 prompt="Review this authentication module",

415 options=ClaudeAgentOptions(451 options=ClaudeAgentOptions(


426 ),462 ),

427 ):463 ):

428 messages.append(message)464 messages.append(message)

465 

466 

467 asyncio.run(main())

429 ```468 ```

430</CodeGroup>469</CodeGroup>

431 470 

432## See also471## See also

433 472 

434* [Output styles](/en/output-styles): create, manage, and share output styles for the CLI, including the file format and storage locations473* [Output styles](/docs/en/output-styles): create, manage, and share output styles for the CLI, including the file format and storage locations

435* [How Claude remembers your project](/en/memory): what to put in CLAUDE.md, where to place it, and how to write effective project instructions474* [How Claude remembers your project](/docs/en/memory): what to put in CLAUDE.md, where to place it, and how to write effective project instructions

436* [TypeScript SDK reference](/en/agent-sdk/typescript): the full `Options` type, including `systemPrompt`, `settingSources`, and `settings`475* [TypeScript SDK reference](/docs/en/agent-sdk/typescript): the full `Options` type, including `systemPrompt`, `settingSources`, and `settings`

437* [Python SDK reference](/en/agent-sdk/python): the full `ClaudeAgentOptions` type, including `system_prompt` and `setting_sources`476* [Python SDK reference](/docs/en/agent-sdk/python): the full `ClaudeAgentOptions` type, including `system_prompt` and `setting_sources`

438* [Settings](/en/settings): the `settings.json` reference, including where output styles and other configuration are stored477* [Settings](/docs/en/settings): the `settings.json` reference, including where output styles and other configuration are stored

Details

103 103 

104Because the child process inherits your application's environment by default, you can achieve the same result by exporting these variables in a Dockerfile, Kubernetes manifest, or shell profile and omitting `options.env` entirely.104Because the child process inherits your application's environment by default, you can achieve the same result by exporting these variables in a Dockerfile, Kubernetes manifest, or shell profile and omitting `options.env` entirely.

105 105 

106To confirm that export is working, check your collector's logs for incoming spans, metrics, and log events after the task completes. The CLI fails silently on export errors by default: if the endpoint is unreachable or rejects the data, the agent still runs normally and the CLI drops the telemetry without surfacing an error in your application. To surface exporter errors, set [`CLAUDE_CODE_OTEL_DIAG_STDERR=1`](/docs/en/env-vars) alongside the exporter variables and read the diagnostics through the SDK's `stderr` callback (Python) or `stderr` option (TypeScript). {/* min-version: 2.1.179 */}Requires Claude Code v2.1.179 or later.

107 

106<Note>108<Note>

107 The `console` exporter writes telemetry to standard output, which the SDK uses109 The `console` exporter writes telemetry to standard output, which the SDK uses

108 as its message channel. Do not set `console` as an exporter value when running110 as its message channel. Do not set `console` as an exporter value when running


176 ```python Python theme={null}178 ```python Python theme={null}

177 options = ClaudeAgentOptions(179 options = ClaudeAgentOptions(

178 env={180 env={

179 # ... exporter configuration ...181 # ... exporter configuration from the Enable telemetry export example ...

180 "OTEL_SERVICE_NAME": "support-triage-agent",182 "OTEL_SERVICE_NAME": "support-triage-agent",

181 "OTEL_RESOURCE_ATTRIBUTES": "service.version=1.4.0,deployment.environment=production",183 "OTEL_RESOURCE_ATTRIBUTES": "service.version=1.4.0,deployment.environment=production",

182 },184 },


187 const options = {189 const options = {

188 env: {190 env: {

189 ...process.env,191 ...process.env,

190 // ... exporter configuration ...192 // ... exporter configuration from the Enable telemetry export example ...

191 OTEL_SERVICE_NAME: "support-triage-agent",193 OTEL_SERVICE_NAME: "support-triage-agent",

192 OTEL_RESOURCE_ATTRIBUTES:194 OTEL_RESOURCE_ATTRIBUTES:

193 "service.version=1.4.0,deployment.environment=production",195 "service.version=1.4.0,deployment.environment=production",


208 210 

209 options = ClaudeAgentOptions(211 options = ClaudeAgentOptions(

210 env={212 env={

211 # ... exporter configuration ...213 # ... exporter configuration from the Enable telemetry export example ...

214 # request is the incoming request object from your web framework.

212 "OTEL_RESOURCE_ATTRIBUTES": f"enduser.id={quote(request.user_id)},tenant.id={quote(request.tenant_id)}",215 "OTEL_RESOURCE_ATTRIBUTES": f"enduser.id={quote(request.user_id)},tenant.id={quote(request.tenant_id)}",

213 },216 },

214 )217 )


218 const options = {221 const options = {

219 env: {222 env: {

220 ...process.env,223 ...process.env,

221 // ... exporter configuration ...224 // ... exporter configuration from the Enable telemetry export example ...

225 // request is the incoming request object from your web framework.

222 OTEL_RESOURCE_ATTRIBUTES: `enduser.id=${encodeURIComponent(request.userId)},tenant.id=${encodeURIComponent(request.tenantId)}`,226 OTEL_RESOURCE_ATTRIBUTES: `enduser.id=${encodeURIComponent(request.userId)},tenant.id=${encodeURIComponent(request.tenantId)}`,

223 },227 },

224 };228 };

Details

6 6 

7> Build production AI agents with Claude Code as a library7> Build production AI agents with Claude Code as a library

8 8 

9Build AI agents that autonomously read files, run commands, search the web, edit code, and more. The Agent SDK gives you the same tools, agent loop, and context management that power Claude Code, programmable in Python and TypeScript. For other languages, [run the CLI programmatically](/en/headless) with the `-p` flag and `--output-format json`. For the thinking behind agent harness design, see [A harness for every task: dynamic workflows in Claude Code](https://claude.com/blog/a-harness-for-every-task-dynamic-workflows-in-claude-code) on the blog. To run the example below, install the SDK first by following the steps in [Get started](#get-started).9An agent is an application that completes a task by planning its own steps and calling tools that read files, run commands, or edit code. The Agent SDK gives you the same tools, [agent loop](/docs/en/agent-sdk/agent-loop), and context management that power Claude Code, programmable in Python and TypeScript.

10 

11<CodeGroup>

12 ```python Python theme={null}

13 import asyncio

14 from claude_agent_sdk import query, ClaudeAgentOptions

15 

16 

17 async def main():

18 async for message in query(

19 prompt="Find and fix the bug in auth.py",

20 options=ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Bash"]),

21 ):

22 print(message) # Claude reads the file, finds the bug, edits it

23 

24 

25 asyncio.run(main())

26 ```

27 

28 ```typescript TypeScript theme={null}

29 import { query } from "@anthropic-ai/claude-agent-sdk";

30 

31 for await (const message of query({

32 prompt: "Find and fix the bug in auth.ts",

33 options: { allowedTools: ["Read", "Edit", "Bash"] }

34 })) {

35 console.log(message); // Claude reads the file, finds the bug, edits it

36 }

37 ```

38</CodeGroup>

39 

40The Agent SDK includes built-in tools for reading files, running commands, and editing code, so your agent can start working immediately without you implementing tool execution. Dive into the quickstart or explore real agents built with the SDK:

41 

42<CardGroup cols={2}>

43 <Card title="Quickstart" icon="play" href="/en/agent-sdk/quickstart">

44 Build a bug-fixing agent in minutes

45 </Card>

46 

47 <Card title="Example agents" icon="star" href="https://github.com/anthropics/claude-agent-sdk-demos">

48 Email assistant, research agent, and more

49 </Card>

50</CardGroup>

51 

52## Get started

53 

54<Steps>

55 <Step title="Install the SDK">

56 <Tabs>

57 <Tab title="TypeScript">

58 ```bash theme={null}

59 npm init -y

60 npm pkg set type=module

61 npm install @anthropic-ai/claude-agent-sdk

62 npm install --save-dev tsx

63 ```

64 

65 Setting `"type": "module"` in `package.json` lets your agent script use top-level `await`, and [tsx](https://tsx.is) runs TypeScript files directly. In an existing CommonJS project, skip the first two commands and name your script `agent.mts` instead of `agent.ts`.

66 </Tab>

67 

68 <Tab title="Python (uv)">

69 [uv](https://docs.astral.sh/uv/) is a fast Python package manager that handles virtual environments automatically:

70 

71 ```bash theme={null}

72 uv init

73 uv add claude-agent-sdk

74 ```

75 </Tab>

76 

77 <Tab title="Python (pip)">

78 Create and activate a virtual environment, then install the package. Installing into a virtual environment avoids the `error: externally-managed-environment` failure that system Python on recent Debian, Ubuntu, and Homebrew installs returns for `pip install` outside a venv.

79 

80 On macOS or Linux:

81 

82 ```bash theme={null}

83 python3 -m venv .venv

84 source .venv/bin/activate

85 pip install claude-agent-sdk

86 ```

87 

88 On Windows:

89 

90 ```powershell theme={null}

91 py -m venv .venv

92 .venv\Scripts\Activate.ps1

93 pip install claude-agent-sdk

94 ```

95 

96 If PowerShell blocks `Activate.ps1` with an execution policy error, run `Set-ExecutionPolicy -Scope Process RemoteSigned` first.

97 

98 The Python package requires Python 3.10 or later. If pip reports `No matching distribution found for claude-agent-sdk`, your interpreter is older than 3.10. Run `python3 --version` on macOS or Linux, or `py --version` on Windows, to check.

99 </Tab>

100 </Tabs>

101 

102 <Note>

103 Both the TypeScript and Python SDKs bundle a native Claude Code binary for your platform, so you don't need to install Claude Code separately.

104 </Note>

105 </Step>

106 

107 <Step title="Set your API key">

108 Get an API key from the [Console](https://platform.claude.com/), then set it as an environment variable.

109 

110 On macOS or Linux:

111 

112 ```bash theme={null}

113 export ANTHROPIC_API_KEY=sk-ant-xxxxx

114 ```

115 

116 On Windows PowerShell:

117 

118 ```powershell theme={null}

119 $env:ANTHROPIC_API_KEY = "sk-ant-xxxxx"

120 ```

121 

122 The SDK also supports authentication via third-party API providers:

123 

124 * **Amazon Bedrock**: set `CLAUDE_CODE_USE_BEDROCK=1` environment variable and configure AWS credentials

125 * **Claude Platform on AWS**: set `CLAUDE_CODE_USE_ANTHROPIC_AWS=1` and `ANTHROPIC_AWS_WORKSPACE_ID`, then configure AWS credentials

126 * **Google Cloud's Agent Platform**: set `CLAUDE_CODE_USE_VERTEX=1` environment variable and configure Google Cloud credentials

127 * **Microsoft Foundry**: set `CLAUDE_CODE_USE_FOUNDRY=1` environment variable and configure Azure credentials

128 

129 See the setup guides for [Amazon Bedrock](/en/amazon-bedrock), [Claude Platform on AWS](/en/claude-platform-on-aws), [Google Cloud's Agent Platform](/en/google-vertex-ai), or [Microsoft Foundry](/en/microsoft-foundry) for details.

130 

131 <Note>

132 Unless previously approved, Anthropic does not allow third party developers to offer claude.ai login or rate limits for their products, including agents built on the Claude Agent SDK. Please use the API key authentication methods described in this document instead.

133 </Note>

134 </Step>

135 

136 <Step title="Run your first agent">

137 This example creates an agent that lists files in your current directory using built-in tools.

138 

139 <CodeGroup>

140 ```python Python theme={null}

141 import asyncio

142 from claude_agent_sdk import query, ClaudeAgentOptions

143 

144 

145 async def main():

146 async for message in query(

147 prompt="What files are in this directory?",

148 options=ClaudeAgentOptions(allowed_tools=["Bash", "Glob"]),

149 ):

150 if hasattr(message, "result"):

151 print(message.result)

152 

153 

154 asyncio.run(main())

155 ```

156 

157 ```typescript TypeScript theme={null}

158 import { query } from "@anthropic-ai/claude-agent-sdk";

159 

160 for await (const message of query({

161 prompt: "What files are in this directory?",

162 options: { allowedTools: ["Bash", "Glob"] }

163 })) {

164 if ("result" in message) console.log(message.result);

165 }

166 ```

167 </CodeGroup>

168 

169 Save the example as `agent.py` or `agent.ts`, then run it. The agent prints a short summary of the files in the directory.

170 

171 <Tabs>

172 <Tab title="TypeScript">

173 ```bash theme={null}

174 npx tsx agent.ts

175 ```

176 

177 If you named your script `agent.mts` for a CommonJS project, run `npx tsx agent.mts` instead.

178 </Tab>

179 

180 <Tab title="Python (uv)">

181 ```bash theme={null}

182 uv run agent.py

183 ```

184 </Tab>

185 

186 <Tab title="Python (pip)">

187 With the virtual environment activated, on macOS or Linux:

188 

189 ```bash theme={null}

190 python3 agent.py

191 ```

192 

193 On Windows, run `python agent.py`.

194 </Tab>

195 </Tabs>

196 </Step>

197</Steps>

198 

199**Ready to build?** Follow the [Quickstart](/en/agent-sdk/quickstart) to create an agent that finds and fixes bugs in minutes.

200 

201## Capabilities

202 

203Everything that makes Claude Code powerful is available in the SDK:

204 

205<Tabs>

206 <Tab title="Built-in tools">

207 Your agent can read files, run commands, and search codebases out of the box. Key tools include:

208 

209 | Tool | What it does |

210 | --------------------------------------------------------------------------- | ------------------------------------------------------------------- |

211 | **Read** | Read any file in the working directory |

212 | **Write** | Create new files |

213 | **Edit** | Make precise edits to existing files |

214 | **Bash** | Run terminal commands, scripts, git operations |

215 | **Monitor** | Watch a background script and react to each output line as an event |

216 | **Glob** | Find files by pattern (`**/*.ts`, `src/**/*.py`) |

217 | **Grep** | Search file contents with regex |

218 | **WebSearch** | Search the web for current information |

219 | **WebFetch** | Fetch and parse web page content |

220 | **[AskUserQuestion](/en/agent-sdk/user-input#handle-clarifying-questions)** | Ask the user clarifying questions with multiple choice options |

221 

222 For the full list, including scheduling and worktree tools, see the [tools reference](/en/tools-reference).

223 

224 This example creates an agent that searches your codebase for TODO comments:

225 

226 <CodeGroup>

227 ```python Python theme={null}

228 import asyncio

229 from claude_agent_sdk import query, ClaudeAgentOptions

230 

231 

232 async def main():

233 async for message in query(

234 prompt="Find all TODO comments and create a summary",

235 options=ClaudeAgentOptions(allowed_tools=["Read", "Glob", "Grep"]),

236 ):

237 if hasattr(message, "result"):

238 print(message.result)

239 

240 

241 asyncio.run(main())

242 ```

243 

244 ```typescript TypeScript theme={null}

245 import { query } from "@anthropic-ai/claude-agent-sdk";

246 

247 for await (const message of query({

248 prompt: "Find all TODO comments and create a summary",

249 options: { allowedTools: ["Read", "Glob", "Grep"] }

250 })) {

251 if ("result" in message) console.log(message.result);

252 }

253 ```

254 </CodeGroup>

255 </Tab>

256 

257 <Tab title="Hooks">

258 Run custom code at key points in the agent lifecycle. SDK hooks use callback functions to validate, log, block, or transform agent behavior.

259 

260 **Available hooks:** `PreToolUse`, `PostToolUse`, `Stop`, `SessionStart`, `SessionEnd`, `UserPromptSubmit`, and more.

261 

262 This example logs all file changes to an audit file:

263 

264 <CodeGroup>

265 ```python Python theme={null}

266 import asyncio

267 from datetime import datetime

268 from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher

269 

270 

271 async def log_file_change(input_data, tool_use_id, context):

272 file_path = input_data.get("tool_input", {}).get("file_path", "unknown")

273 with open("./audit.log", "a") as f:

274 f.write(f"{datetime.now()}: modified {file_path}\n")

275 return {}

276 

277 

278 async def main():

279 async for message in query(

280 prompt="Create a file named hello.py that prints a greeting",

281 options=ClaudeAgentOptions(

282 allowed_tools=["Read", "Edit"],

283 permission_mode="acceptEdits",

284 hooks={

285 "PostToolUse": [

286 HookMatcher(matcher="Edit|Write", hooks=[log_file_change])

287 ]

288 },

289 ),

290 ):

291 if hasattr(message, "result"):

292 print(message.result)

293 

294 

295 asyncio.run(main())

296 ```

297 

298 ```typescript TypeScript theme={null}

299 import { query, HookCallback } from "@anthropic-ai/claude-agent-sdk";

300 import { appendFile } from "fs/promises";

301 

302 const logFileChange: HookCallback = async (input) => {

303 const filePath = (input as any).tool_input?.file_path ?? "unknown";

304 await appendFile("./audit.log", `${new Date().toISOString()}: modified ${filePath}\n`);

305 return {};

306 };

307 

308 for await (const message of query({

309 prompt: "Create a file named hello.ts that prints a greeting",

310 options: {

311 allowedTools: ["Read", "Edit"],

312 permissionMode: "acceptEdits",

313 hooks: {

314 PostToolUse: [{ matcher: "Edit|Write", hooks: [logFileChange] }]

315 }

316 }

317 })) {

318 if ("result" in message) console.log(message.result);

319 }

320 ```

321 </CodeGroup>

322 

323 After the agent finishes, run `cat audit.log` to see the recorded file changes.

324 

325 [Learn more about hooks →](/en/agent-sdk/hooks)

326 </Tab>

327 

328 <Tab title="Subagents">

329 Spawn specialized agents to handle focused subtasks. Your main agent delegates work, and subagents report back with results.

330 

331 Define custom agents with specialized instructions. Subagents are invoked via the Agent tool, so include `Agent` in `allowedTools` to auto-approve those invocations:

332 

333 <CodeGroup>

334 ```python Python theme={null}

335 import asyncio

336 from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition

337 

338 

339 async def main():

340 async for message in query(

341 prompt="Use the code-reviewer agent to review this codebase",

342 options=ClaudeAgentOptions(

343 allowed_tools=["Read", "Glob", "Grep", "Agent"],

344 agents={

345 "code-reviewer": AgentDefinition(

346 description="Expert code reviewer for quality and security reviews.",

347 prompt="Analyze code quality and suggest improvements.",

348 tools=["Read", "Glob", "Grep"],

349 )

350 },

351 ),

352 ):

353 if hasattr(message, "result"):

354 print(message.result)

355 

356 

357 asyncio.run(main())

358 ```

359 

360 ```typescript TypeScript theme={null}

361 import { query } from "@anthropic-ai/claude-agent-sdk";

362 

363 for await (const message of query({

364 prompt: "Use the code-reviewer agent to review this codebase",

365 options: {

366 allowedTools: ["Read", "Glob", "Grep", "Agent"],

367 agents: {

368 "code-reviewer": {

369 description: "Expert code reviewer for quality and security reviews.",

370 prompt: "Analyze code quality and suggest improvements.",

371 tools: ["Read", "Glob", "Grep"]

372 }

373 }

374 }

375 })) {

376 if ("result" in message) console.log(message.result);

377 }

378 ```

379 </CodeGroup>

380 

381 Messages from within a subagent's context include a `parent_tool_use_id` field, letting you track which messages belong to which subagent execution.

382 

383 [Learn more about subagents →](/en/agent-sdk/subagents)

384 </Tab>

385 

386 <Tab title="MCP">

387 Connect to external systems via the Model Context Protocol: databases, browsers, APIs, and [hundreds more](https://github.com/modelcontextprotocol/servers).

388 

389 This example connects the [Playwright MCP server](https://github.com/microsoft/playwright-mcp) to give your agent browser automation capabilities:

390 

391 <CodeGroup>

392 ```python Python theme={null}

393 import asyncio

394 from claude_agent_sdk import query, ClaudeAgentOptions

395 

396 

397 async def main():

398 async for message in query(

399 prompt="Open example.com and describe what you see",

400 options=ClaudeAgentOptions(

401 mcp_servers={

402 "playwright": {"command": "npx", "args": ["@playwright/mcp@latest"]}

403 },

404 allowed_tools=["mcp__playwright__*"],

405 ),

406 ):

407 if hasattr(message, "result"):

408 print(message.result)

409 

410 

411 asyncio.run(main())

412 ```

413 

414 ```typescript TypeScript theme={null}

415 import { query } from "@anthropic-ai/claude-agent-sdk";

416 

417 for await (const message of query({

418 prompt: "Open example.com and describe what you see",

419 options: {

420 mcpServers: {

421 playwright: { command: "npx", args: ["@playwright/mcp@latest"] }

422 },

423 allowedTools: ["mcp__playwright__*"]

424 }

425 })) {

426 if ("result" in message) console.log(message.result);

427 }

428 ```

429 </CodeGroup>

430 

431 [Learn more about MCP →](/en/agent-sdk/mcp)

432 </Tab>

433 

434 <Tab title="Permissions">

435 Control exactly which tools your agent can use. Allow safe operations, block dangerous ones, or require approval for sensitive actions.

436 

437 <Note>

438 For interactive approval prompts and the `AskUserQuestion` tool, see [Handle approvals and user input](/en/agent-sdk/user-input).

439 </Note>

440 

441 This example creates a read-only agent that can analyze but not modify code. `allowed_tools` pre-approves `Read`, `Glob`, and `Grep` so they run without prompting. Tools not listed are still available but fall through to the permission mode; to block tools entirely, use `disallowed_tools`.

442 

443 <CodeGroup>

444 ```python Python theme={null}

445 import asyncio

446 from claude_agent_sdk import query, ClaudeAgentOptions

447 

448 

449 async def main():

450 async for message in query(

451 prompt="Review this code for best practices",

452 options=ClaudeAgentOptions(

453 allowed_tools=["Read", "Glob", "Grep"],

454 ),

455 ):

456 if hasattr(message, "result"):

457 print(message.result)

458 

459 

460 asyncio.run(main())

461 ```

462 

463 ```typescript TypeScript theme={null}

464 import { query } from "@anthropic-ai/claude-agent-sdk";

465 

466 for await (const message of query({

467 prompt: "Review this code for best practices",

468 options: {

469 allowedTools: ["Read", "Glob", "Grep"]

470 }

471 })) {

472 if ("result" in message) console.log(message.result);

473 }

474 ```

475 </CodeGroup>

476 

477 [Learn more about permissions →](/en/agent-sdk/permissions)

478 </Tab>

479 

480 <Tab title="Sessions">

481 Maintain context across multiple exchanges. Claude remembers files read, analysis done, and conversation history. Resume sessions later, or fork them to explore different approaches.

482 

483 This example captures the session ID from the first query, then resumes to continue with full context:

484 

485 <CodeGroup>

486 ```python Python theme={null}

487 import asyncio

488 from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage, ResultMessage

489 

490 

491 async def main():

492 session_id = None

493 

494 # First query: capture the session ID

495 try:

496 async for message in query(

497 prompt="Read the authentication module",

498 options=ClaudeAgentOptions(allowed_tools=["Read", "Glob"]),

499 ):

500 if isinstance(message, SystemMessage) and message.subtype == "init":

501 session_id = message.data["session_id"]

502 except Exception as error:

503 # A single-shot query() raises after yielding an error result. If

504 # the failure was an error result, session_id was already captured

505 # by the loop above; connection or process failures yield no

506 # result message.

507 print(f"Session ended with an error: {error}")

508 

509 # Resume with full context from the first query

510 async for message in query(

511 prompt="Now find all places that call it", # "it" = auth module

512 options=ClaudeAgentOptions(resume=session_id),

513 ):

514 if isinstance(message, ResultMessage):

515 print(message.result)

516 

517 

518 asyncio.run(main())

519 ```

520 

521 ```typescript TypeScript theme={null}

522 import { query } from "@anthropic-ai/claude-agent-sdk";

523 

524 let sessionId: string | undefined;

525 

526 // First query: capture the session ID

527 try {

528 for await (const message of query({

529 prompt: "Read the authentication module",

530 options: { allowedTools: ["Read", "Glob"] }

531 })) {

532 if (message.type === "system" && message.subtype === "init") {

533 sessionId = message.session_id;

534 }

535 }

536 } catch (error) {

537 // A single-shot query() throws after yielding an error result. If the

538 // failure was an error result, sessionId was already captured by the

539 // loop above; connection or process failures yield no result message.

540 console.error(`Session ended with an error: ${error}`);

541 }

542 

543 // Resume with full context from the first query

544 for await (const message of query({

545 prompt: "Now find all places that call it", // "it" = auth module

546 options: { resume: sessionId }

547 })) {

548 if ("result" in message) console.log(message.result);

549 }

550 ```

551 </CodeGroup>

552 

553 [Learn more about sessions →](/en/agent-sdk/sessions)

554 </Tab>

555</Tabs>

556 

557### Claude Code features

558 

559The SDK also supports Claude Code's filesystem-based configuration. With default options the SDK loads these from `.claude/` in your working directory and `~/.claude/`. To restrict which sources load, set `setting_sources` (Python) or `settingSources` (TypeScript) in your options.

560 

561| Feature | Description | Location |

562| ------------------------------------------------ | ----------------------------------------------------------------------------- | ---------------------------------- |

563| [Skills](/en/agent-sdk/skills) | Specialized capabilities Claude uses automatically or you invoke with `/name` | `.claude/skills/*/SKILL.md` |

564| [Commands](/en/agent-sdk/slash-commands) | Custom commands in the legacy format. Use skills for new custom commands | `.claude/commands/*.md` |

565| [Memory](/en/agent-sdk/modifying-system-prompts) | Project context and instructions | `CLAUDE.md` or `.claude/CLAUDE.md` |

566| [Plugins](/en/agent-sdk/plugins) | Extend with skills, agents, hooks, and MCP servers | Programmatic via `plugins` option |

567 10 

568## Compare the Agent SDK to other Claude tools11## Compare the Agent SDK to other Claude tools

569 12 

570The Claude Platform offers multiple ways to build with Claude. Here's how the Agent SDK fits in:13The Agent SDK, the CLI, the Client SDK, and Managed Agents each fit different needs. Use the table to find the one that matches what you're building.

571 14 

572<Tabs>15| If you're... | Use | Why |

573 <Tab title="Agent SDK vs Client SDK">16| ------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |

574 The [Anthropic Client SDK](https://platform.claude.com/docs/en/api/client-sdks) gives you direct API access: you send prompts and implement tool execution yourself. The **Agent SDK** gives you Claude with built-in tool execution.17| Building an agent without implementing the tool loop yourself | **Agent SDK** | A library that runs the agent loop in your own process, in Python or TypeScript. |

18| Doing interactive development or running one-off tasks from a terminal | [**Claude Code CLI**](/docs/en/overview) | The terminal interface, built for daily interactive use. |

19| Calling the API directly and implementing the tool loop yourself | [**Client SDK**](https://platform.claude.com/docs/en/api/client-sdks) | Direct access to the Anthropic API rather than to Claude Code. You implement the tool loop yourself. |

20| Running long-running or asynchronous agents without managing your own sandbox or session infrastructure | [**Managed Agents**](https://platform.claude.com/docs/en/managed-agents/overview) | Hosted REST API, a separate product from the Agent SDK. Anthropic runs the agent and the sandbox. |

575 21 

576 With the Client SDK, you implement a tool loop. With the Agent SDK, Claude handles it. This simplified pseudocode shows the difference:22The SDK is available as a library for Python and TypeScript only. To drive the same agent loop from another language, [run the CLI as a subprocess](/docs/en/headless) with the `-p` flag and `--output-format json`.

577 23 

578 <CodeGroup>24## Capabilities

579 ```python Python theme={null}

580 # Client SDK: You implement the tool loop

581 response = client.messages.create(...)

582 while response.stop_reason == "tool_use":

583 result = your_tool_executor(response.tool_use)

584 response = client.messages.create(tool_result=result, **params)

585 

586 # Agent SDK: Claude handles tools autonomously

587 async for message in query(prompt="Fix the bug in auth.py"):

588 print(message)

589 ```

590 

591 ```typescript TypeScript theme={null}

592 // Client SDK: You implement the tool loop

593 let response = await client.messages.create({ ...params });

594 while (response.stop_reason === "tool_use") {

595 const result = yourToolExecutor(response.tool_use);

596 response = await client.messages.create({ tool_result: result, ...params });

597 }

598 

599 // Agent SDK: Claude handles tools autonomously

600 for await (const message of query({ prompt: "Fix the bug in auth.ts" })) {

601 console.log(message);

602 }

603 ```

604 </CodeGroup>

605 </Tab>

606 

607 <Tab title="Agent SDK vs Claude Code CLI">

608 Same capabilities, different interface:

609 25 

610 | Use case | Best choice |26Everything that makes Claude Code powerful is available in the SDK.

611 | ----------------------- | ----------- |

612 | Interactive development | CLI |

613 | CI/CD pipelines | SDK |

614 | Custom applications | SDK |

615 | One-off tasks | CLI |

616 | Production automation | SDK |

617 27 

618 Many teams use both: CLI for daily development, SDK for production. Workflows translate directly between them.28| Capability | What it does | Learn more |

619 </Tab>29| ---------------------------- | -------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

30| Built-in tools | Read, write, edit files, run commands, and search the web | [Tools reference](/docs/en/tools-reference) |

31| Hooks | Run custom code at key points in the agent lifecycle | [Hooks](/docs/en/agent-sdk/hooks) |

32| Subagents | Spawn specialized agents for focused subtasks | [Subagents](/docs/en/agent-sdk/subagents) |

33| MCP | Connect external tools and data sources via the Model Context Protocol | [MCP](/docs/en/agent-sdk/mcp) |

34| Permissions | Control which tools run automatically, which need approval | [Permissions](/docs/en/agent-sdk/permissions) |

35| Sessions | Maintain context across exchanges, resume or fork later | [Sessions](/docs/en/agent-sdk/sessions) |

36| Skills, commands, and memory | Load automatically from your project's `.claude/` and from `~/.claude/`, same as Claude Code | [Skills](/docs/en/agent-sdk/skills), [Commands](/docs/en/agent-sdk/slash-commands), [Memory](/docs/en/agent-sdk/modifying-system-prompts), [Configuration loading](/docs/en/agent-sdk/claude-code-features) |

37| Plugins | Package skills, agents, hooks, and MCP servers, and load them by local path | [Plugins](/docs/en/agent-sdk/plugins) |

620 38 

621 <Tab title="Agent SDK vs Managed Agents">39## Get started

622 [Managed Agents](https://platform.claude.com/docs/en/managed-agents/overview) is a hosted REST API: Anthropic runs the agent and the sandbox, and your application sends events and streams back results. The **Agent SDK** is a library that runs the agent loop inside your own process.

623 40 

624 | | Agent SDK | Managed Agents |41Follow the [Quickstart](/docs/en/agent-sdk/quickstart) to install the SDK, set your API key, and build your first agent, one that finds and fixes bugs in existing code.

625 | ------------------ | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |

626 | **Runs in** | Your process, your infrastructure | Anthropic-managed infrastructure |

627 | **Interface** | Python or TypeScript library | REST API |

628 | **Agent works on** | Files on your infrastructure | A managed sandbox per session |

629 | **Session state** | JSONL on your filesystem | Anthropic-hosted event log |

630 | **Custom tools** | In-process Python or TypeScript functions | Claude triggers the tool; you execute and return results |

631 | **Best for** | Local prototyping, agents that work directly on your filesystem and services | Production agents without operating sandbox or session infrastructure, long-running and asynchronous sessions |

632 42 

633 A common path is to prototype with the Agent SDK locally, then move to Managed Agents for production.43<Note>

634 </Tab>44 Unless previously approved, Anthropic does not allow third party developers to offer claude.ai login or rate limits for their products, including agents built on the Claude Agent SDK. Use the API key authentication methods described in the [Quickstart](/docs/en/agent-sdk/quickstart) instead.

635</Tabs>45</Note>

636 46 

637## Changelog47## Changelog

638 48 


641* **TypeScript SDK**: [view CHANGELOG.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/CHANGELOG.md)51* **TypeScript SDK**: [view CHANGELOG.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/CHANGELOG.md)

642* **Python SDK**: [view CHANGELOG.md](https://github.com/anthropics/claude-agent-sdk-python/blob/main/CHANGELOG.md)52* **Python SDK**: [view CHANGELOG.md](https://github.com/anthropics/claude-agent-sdk-python/blob/main/CHANGELOG.md)

643 53 

644## Reporting bugs54## Report bugs

645 55 

646If you encounter bugs or issues with the Agent SDK:56If you encounter bugs or issues with the Agent SDK:

647 57 


654 64 

655**Allowed:**65**Allowed:**

656 66 

657* "Claude Agent" (preferred for dropdown menus)67* "Claude Agent", preferred for dropdown menus

658* "Claude" (when within a menu already labeled "Agents")68* "Claude", when within a menu already labeled "Agents"

659* "{YourAgentName} Powered by Claude" (if you have an existing agent name)69* "\{YourAgentName} Powered by Claude", if you have an existing agent name

660 70 

661**Not permitted:**71**Not permitted:**

662 72 


671 81 

672## Next steps82## Next steps

673 83 

674<CardGroup cols={2}>84These resources cover deeper technical detail and example projects for building with the Agent SDK.

675 <Card title="Quickstart" icon="play" href="/en/agent-sdk/quickstart">

676 Build an agent that finds and fixes bugs in minutes

677 </Card>

678 

679 <Card title="Example agents" icon="star" href="https://github.com/anthropics/claude-agent-sdk-demos">

680 Email assistant, research agent, and more

681 </Card>

682 

683 <Card title="TypeScript SDK" icon="code" href="/en/agent-sdk/typescript">

684 Full TypeScript API reference and examples

685 </Card>

686 85 

687 <Card title="Python SDK" icon="code" href="/en/agent-sdk/python">86* [Quickstart](/docs/en/agent-sdk/quickstart): build your first agent that finds and fixes bugs

688 Full Python API reference and examples87* [Agent loop](/docs/en/agent-sdk/agent-loop): how Claude plans, calls tools, and decides when a task is done

689 </Card>88* [Example agents](https://github.com/anthropics/claude-agent-sdk-demos): demo apps for local development

690</CardGroup>89* [TypeScript SDK](/docs/en/agent-sdk/typescript): full TypeScript API reference and examples

90* [Python SDK](/docs/en/agent-sdk/python): full Python API reference and examples

91* [Agent harness design](https://claude.com/blog/a-harness-for-every-task-dynamic-workflows-in-claude-code): how the Claude Code team uses dynamic workflows to orchestrate subagents at scale

Details

21 The `commands/` directory is a legacy format. Use `skills/` for new plugins. Claude Code continues to support both formats for backward compatibility.21 The `commands/` directory is a legacy format. Use `skills/` for new plugins. Claude Code continues to support both formats for backward compatibility.

22</Note>22</Note>

23 23 

24For complete information on plugin structure and how to create plugins, see [Plugins](/en/plugins).24For complete information on plugin structure and how to create plugins, see [Plugins](/docs/en/plugins).

25 25 

26## Loading plugins26## Loading plugins

27 27 

28Load plugins by providing their local file system paths in your options configuration. The `type` field must be `"local"`, the only value the SDK accepts. To use a plugin distributed through a [marketplace](/en/plugin-marketplaces) or remote repository, download it first and provide the local directory path. The SDK supports loading multiple plugins from different locations.28Load plugins by providing their local file system paths in your options configuration. The `type` field must be `"local"`, the only value the SDK accepts. The SDK supports loading multiple plugins from different locations.

29 

30To use a plugin distributed through a [marketplace](/docs/en/plugin-marketplaces) or remote repository, download it first and provide the local directory path. For the directory layout a plugin needs, see the [Plugin structure reference](#plugin-structure-reference) below.

29 31 

30<CodeGroup>32<CodeGroup>

31 ```typescript TypeScript theme={null}33 ```typescript TypeScript theme={null}


95 if (message.type === "system" && message.subtype === "init") {97 if (message.type === "system" && message.subtype === "init") {

96 // Check loaded plugins98 // Check loaded plugins

97 console.log("Plugins:", message.plugins);99 console.log("Plugins:", message.plugins);

98 // Example: [{ name: "my-plugin", path: "./my-plugin" }]100 // Example: [{ name: "my-plugin", path: "/absolute/path/to/my-plugin" }]

99 101 

100 // Plugin skills appear with the plugin name as a prefix102 // Plugin skills appear with the plugin name as a prefix

101 console.log("Skills:", message.skills);103 console.log("Skills:", message.skills);


123 if isinstance(message, SystemMessage) and message.subtype == "init":125 if isinstance(message, SystemMessage) and message.subtype == "init":

124 # Check loaded plugins126 # Check loaded plugins

125 print("Plugins:", message.data.get("plugins"))127 print("Plugins:", message.data.get("plugins"))

126 # Example: [{"name": "my-plugin", "path": "./my-plugin"}]128 # Example: [{"name": "my-plugin", "path": "/absolute/path/to/my-plugin"}]

127 129 

128 # Plugin skills appear with the plugin name as a prefix130 # Plugin skills appear with the plugin name as a prefix

129 print("Skills:", message.data.get("skills"))131 print("Skills:", message.data.get("skills"))


168 async def main():170 async def main():

169 # Load a plugin with a custom /greet skill171 # Load a plugin with a custom /greet skill

170 async for message in query(172 async for message in query(

171 prompt="/demo-plugin:greet", # Use plugin skill with namespace173 prompt="/my-plugin:greet", # Use plugin skill with namespace

172 options=ClaudeAgentOptions(174 options=ClaudeAgentOptions(

173 plugins=[{"type": "local", "path": "./plugins/demo-plugin"}]175 plugins=[{"type": "local", "path": "./my-plugin"}]

174 ),176 ),

175 ):177 ):

176 # Claude executes the custom greeting skill from the plugin178 # Claude executes the custom greeting skill from the plugin


195<CodeGroup>197<CodeGroup>

196 ```typescript TypeScript theme={null}198 ```typescript TypeScript theme={null}

197 import { query } from "@anthropic-ai/claude-agent-sdk";199 import { query } from "@anthropic-ai/claude-agent-sdk";

198 import * as path from "path";200 import { fileURLToPath } from "node:url";

199 201 

200 async function runWithPlugin() {202 async function runWithPlugin() {

201 const pluginPath = path.join(__dirname, "plugins", "my-plugin");203 const pluginPath = fileURLToPath(new URL("./plugins/my-plugin", import.meta.url));

202 204 

203 console.log("Loading plugin from:", pluginPath);205 console.log("Loading plugin from:", pluginPath);

204 206 


228 #!/usr/bin/env python3230 #!/usr/bin/env python3

229 """Example demonstrating how to use plugins with the Agent SDK."""231 """Example demonstrating how to use plugins with the Agent SDK."""

230 232 

233 import asyncio

231 from pathlib import Path234 from pathlib import Path

232 import anyio235 

233 from claude_agent_sdk import (236 from claude_agent_sdk import (

234 AssistantMessage,237 AssistantMessage,

235 ClaudeAgentOptions,238 ClaudeAgentOptions,


241 244 

242 async def run_with_plugin():245 async def run_with_plugin():

243 """Example using a custom plugin."""246 """Example using a custom plugin."""

244 plugin_path = Path(__file__).parent / "plugins" / "demo-plugin"247 plugin_path = Path(__file__).parent / "plugins" / "my-plugin"

245 248 

246 print(f"Loading plugin from: {plugin_path}")249 print(f"Loading plugin from: {plugin_path}")

247 250 


265 268 

266 269 

267 if __name__ == "__main__":270 if __name__ == "__main__":

268 anyio.run(run_with_plugin)271 asyncio.run(run_with_plugin())

269 ```272 ```

270</CodeGroup>273</CodeGroup>

271 274 


291 294 

292For detailed information on creating plugins, see:295For detailed information on creating plugins, see:

293 296 

294* [Plugins](/en/plugins) - Complete plugin development guide297* [Plugins](/docs/en/plugins) - Complete plugin development guide

295* [Plugins reference](/en/plugins-reference) - Technical specifications and schemas298* [Plugins reference](/docs/en/plugins-reference) - Technical specifications and schemas

296 299 

297## Common use cases300## Common use cases

298 301 


317Combine plugins from different locations:320Combine plugins from different locations:

318 321 

319```typescript theme={null}322```typescript theme={null}

323import * as os from "node:os";

324import * as path from "node:path";

325 

320plugins: [326plugins: [

321 { type: "local", path: "./local-plugin" },327 { type: "local", path: "./local-plugin" },

322 { type: "local", path: "~/.claude/custom-plugins/shared-plugin" }328 {

329 type: "local",

330 path: path.join(os.homedir(), ".claude", "custom-plugins", "shared-plugin")

331 }

323];332];

324```333```

325 334 

335<Note>

336 The SDK doesn't expand tilde paths like `~/plugins`. If a plugin path doesn't exist, the SDK skips that plugin and the session continues, so check the `plugins` list in the init message to confirm each plugin loaded.

337</Note>

338 

326## Troubleshooting339## Troubleshooting

327 340 

328### Plugin not loading341### Plugin not loading


3321. **Check the path**: ensure the path points to the plugin root directory, the parent of `skills/`, `agents/`, `hooks/`, `commands/` (legacy), or `.claude-plugin/`3451. **Check the path**: ensure the path points to the plugin root directory, the parent of `skills/`, `agents/`, `hooks/`, `commands/` (legacy), or `.claude-plugin/`

3332. **Validate plugin.json**: if your plugin includes a manifest, ensure it has valid JSON syntax3462. **Validate plugin.json**: if your plugin includes a manifest, ensure it has valid JSON syntax

3343. **Check file permissions**: ensure the plugin directory is readable3473. **Check file permissions**: ensure the plugin directory is readable

3484. **Confirm the directory exists**: the SDK skips a nonexistent path, and the plugin doesn't appear in the init message's `plugins` list

335 349 

336### Skills not appearing350### Skills not appearing

337 351 


351 365 

352## See also366## See also

353 367 

354* [Plugins](/en/plugins) - Complete plugin development guide368* [Plugins](/docs/en/plugins) - Complete plugin development guide

355* [Plugins reference](/en/plugins-reference) - Technical specifications369* [Plugins reference](/docs/en/plugins-reference) - Technical specifications

356* [Commands](/en/agent-sdk/slash-commands) - Using commands in the SDK370* [Commands](/docs/en/agent-sdk/slash-commands) - Using commands in the SDK

357* [Subagents](/en/agent-sdk/subagents) - Working with specialized agents371* [Subagents](/docs/en/agent-sdk/subagents) - Working with specialized agents

358* [Skills](/en/agent-sdk/skills) - Using Agent Skills372* [Skills](/docs/en/agent-sdk/skills) - Using Agent Skills

Details

16pip install claude-agent-sdk16pip install claude-agent-sdk

17```17```

18 18 

19For uv, Windows PowerShell, and API key setup, see [Get started in the Agent SDK overview](/docs/en/agent-sdk/overview#get-started).19For uv, Windows PowerShell, and API key setup, see [Setup in the Agent SDK quickstart](/docs/en/agent-sdk/quickstart#setup).

20 20 

21## Choosing between `query()` and `ClaudeSDKClient`21## Choosing between `query()` and `ClaudeSDKClient`

22 22 


624 # Drain the interrupted task's messages (including its ResultMessage)624 # Drain the interrupted task's messages (including its ResultMessage)

625 async for message in client.receive_response():625 async for message in client.receive_response():

626 if isinstance(message, ResultMessage):626 if isinstance(message, ResultMessage):

627 print(f"Interrupted task finished with subtype={message.subtype!r}")627 print(f"Interrupted task: terminal_reason={message.terminal_reason!r}")

628 # subtype is "error_during_execution" for interrupted tasks628 # terminal_reason is "aborted_streaming" or "aborted_tools"

629 # for interrupted turns

629 630 

630 # Send a new command631 # Send a new command

631 await client.query("Just say hello instead")632 await client.query("Just say hello instead")


640```641```

641 642 

642<Note>643<Note>

643 **Buffer behavior after interrupt:** `interrupt()` sends a stop signal but does not clear the message buffer. Messages already produced by the interrupted task, including its `ResultMessage` (with `subtype="error_during_execution"`), remain in the stream. You must drain them with `receive_response()` before reading the response to a new query. If you send a new query immediately after `interrupt()` and call `receive_response()` only once, you'll receive the interrupted task's messages, not the new query's response.644 **Buffer behavior after interrupt:** `interrupt()` sends a stop signal but does not clear the message buffer. Messages already produced by the interrupted task, including its `ResultMessage`, remain in the stream. You must drain them with `receive_response()` before reading the response to a new query. If you send a new query immediately after `interrupt()` and call `receive_response()` only once, you'll receive the interrupted task's messages, not the new query's response.

644</Note>645</Note>

645 646 

646#### Example - Advanced permission control647#### Example - Advanced permission control


886* `API_TIMEOUT_MS`: per-request timeout on the Anthropic client, in milliseconds. Default `600000`. Applies to the main loop and all subagents.887* `API_TIMEOUT_MS`: per-request timeout on the Anthropic client, in milliseconds. Default `600000`. Applies to the main loop and all subagents.

887* `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff. For unattended runs that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG=1`: it retries capacity errors indefinitely, and {/* min-version: 2.1.199 */}as of Claude Code v2.1.199 raises the default for other transient errors to `300` and removes the cap on this variable.888* `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff. For unattended runs that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG=1`: it retries capacity errors indefinitely, and {/* min-version: 2.1.199 */}as of Claude Code v2.1.199 raises the default for other transient errors to `300` and removes the cap on this variable.

888* `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents launched with `run_in_background`. Default `600000`. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents.889* `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents launched with `run_in_background`. Default `600000`. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents.

889* `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. The aborted request goes through the normal retry path.890* `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. After the abort, Claude Code retries the request at most once, and only before Claude has started a block of text or a tool call in the response; once Claude has completed a block of text or a tool call, Claude Code keeps the completed output, appends an [incomplete-response notice](/docs/en/errors#the-response-above-may-be-incomplete) instead of retrying, and still runs any completed tool call.

890 891 

891### `OutputFormat`892### `OutputFormat`

892 893 


948```949```

949 950 

950| Value | Description | Location |951| Value | Description | Location |

951| :---------- | :---------------------------------------------- | :---------------------------- |952| :---------- | :------------------------------------------------------------------------ | :---------------------------- |

952| `"user"` | Global user settings | `~/.claude/settings.json` |953| `"user"` | Global user settings | `~/.claude/settings.json` |

953| `"project"` | Shared project settings (version controlled) | `.claude/settings.json` |954| `"project"` | Shared project settings (version controlled) | `.claude/settings.json` |

954| `"local"` | Local project settings (not version controlled) | `.claude/settings.local.json` |955| `"local"` | Local project settings, gitignored when Claude Code saves a setting to it | `.claude/settings.local.json` |

955 956 

956#### Default behavior957#### Default behavior

957 958 


1365| `enabled` | `type`, `budget_tokens`, `display` | Enable thinking with a specific token budget |1366| `enabled` | `type`, `budget_tokens`, `display` | Enable thinking with a specific token budget |

1366| `disabled` | `type` | Disable thinking |1367| `disabled` | `type` | Disable thinking |

1367 1368 

1368The optional `display` field controls whether thinking text is returned `"summarized"` or `"omitted"`. On Claude Opus 4.7 and later, the API default is `"omitted"`, so set `"summarized"` to receive thinking content in [`ThinkingBlock`](#thinkingblock) outputs.1369The optional `display` field controls whether thinking text is returned `"summarized"` or `"omitted"`. On Claude Opus 4.7 and later, the API default is `"omitted"`, so set `"summarized"` to receive thinking content in [`ThinkingBlock`](#thinkingblock) outputs. Claude Code doesn't send `display` to Amazon Bedrock or Google Cloud's Agent Platform, so on those providers Opus 4.7 and later return empty `ThinkingBlock` outputs even when you set `display` to `"summarized"`.

1369 1370 

1370Because these are `TypedDict` classes, they're plain dicts at runtime. Either construct them as dict literals or call the class like a constructor; both produce a `dict`. Access fields with `config["budget_tokens"]`, not `config.budget_tokens`:1371Because these are `TypedDict` classes, they're plain dicts at runtime. Either construct them as dict literals or call the class like a constructor; both produce a `dict`. Access fields with `config["budget_tokens"]`, not `config.budget_tokens`:

1371 1372 


1407Use with the `betas` field in `ClaudeAgentOptions` to enable beta features.1408Use with the `betas` field in `ClaudeAgentOptions` to enable beta features.

1408 1409 

1409<Warning>1410<Warning>

1410 The `context-1m-2025-08-07` beta is retired as of April 30, 2026. Passing this header with Claude Sonnet 4.5 or Sonnet 4 has no effect, and requests that exceed the standard 200k-token context window return an error. To use a 1M-token context window, migrate to [Claude Sonnet 5, Claude Sonnet 4.6, Claude Opus 4.6, Claude Opus 4.7, or Claude Opus 4.8](https://platform.claude.com/docs/en/about-claude/models/overview), which include 1M context at standard pricing with no beta header required.1411 The `context-1m-2025-08-07` beta is retired as of April 30, 2026. Passing this header with Claude Sonnet 4.5 or Sonnet 4 has no effect, and requests that exceed the standard 200k-token context window return an error. To use a 1M-token context window, migrate to [Claude Opus 5, Claude Sonnet 5, Claude Sonnet 4.6, Claude Opus 4.6, Claude Opus 4.7, or Claude Opus 4.8](https://platform.claude.com/docs/en/about-claude/models/overview), which include 1M context at standard pricing with no beta header required.

1411</Warning>1412</Warning>

1412 1413 

1413### `McpSdkServerConfig`1414### `McpSdkServerConfig`


1613 "rate_limit",1614 "rate_limit",

1614 "invalid_request",1615 "invalid_request",

1615 "server_error",1616 "server_error",

1616 "max_output_tokens",

1617 "unknown",1617 "unknown",

1618]1618]

1619```1619```

1620 1620 

1621The underlying CLI process can emit error types this Literal doesn't list, such as `max_output_tokens`. The SDK passes the value through unmodified, so treat strings outside this list the way you treat `unknown`. The TypeScript [`SDKAssistantMessageError`](/docs/en/agent-sdk/typescript#sdkassistantmessage) type lists the full set of values the CLI can emit.

1622 

1621### `SystemMessage`1623### `SystemMessage`

1622 1624 

1623System message with metadata.1625System message with metadata.


1664* `api_error_status`: the HTTP status code of the terminating API error. `None` when the turn ended without one. Populated only on `subtype="success"`.1666* `api_error_status`: the HTTP status code of the terminating API error. `None` when the turn ended without one. Populated only on `subtype="success"`.

1665* `result`: text of the final assistant message on `subtype="success"`, or `None` on the `error_*` subtypes. When `subtype="success"` and `is_error=True`, this holds the API error string if one is available but can be empty, so check `api_error_status` and the preceding `AssistantMessage` content for detail.1667* `result`: text of the final assistant message on `subtype="success"`, or `None` on the `error_*` subtypes. When `subtype="success"` and `is_error=True`, this holds the API error string if one is available but can be empty, so check `api_error_status` and the preceding `AssistantMessage` content for detail.

1666* `errors`: loop-level error strings such as the max-turns message. Populated only on the `error_*` subtypes.1668* `errors`: loop-level error strings such as the max-turns message. Populated only on the `error_*` subtypes.

1667* `terminal_reason`: why the query loop terminated, such as `"completed"`, `"max_turns"`, or `"aborted_streaming"`. A value of `"aborted_streaming"` or `"aborted_tools"` means the turn was cancelled by an interrupt. `None` when the CLI didn't report a terminal reason, such as with an older CLI version. See [`SDKResultMessage`](/docs/en/agent-sdk/typescript#sdkresultmessage) for the full list of values.1669* `terminal_reason`: why the query loop ended, such as `"completed"`, `"max_turns"`, `"api_error"`, `"aborted_streaming"`, or `"aborted_tools"`. A value of `"aborted_streaming"` or `"aborted_tools"` means the turn was aborted before completing. Common causes are [`interrupt()`](#claudesdkclient) and a permission callback returning [`PermissionResultDeny`](#permissionresultdeny) with `interrupt=True`. `None` on CLI versions that predate the field, on results that bypassed the query loop such as local slash commands, or on synthesized error results emitted when the session fails fatally. Mirrors the TypeScript SDK's [`SDKResultMessage.terminal_reason`](/docs/en/agent-sdk/typescript#sdkresultmessage), which lists the full set of values.

1668 1670 

1669The `usage` dict contains the following keys when present:1671The `usage` dict contains the following keys when present:

1670 1672 


1917 """Base error for Claude SDK."""1919 """Base error for Claude SDK."""

1918```1920```

1919 1921 

1922When a single-shot `query()` ends with an error result, for example a turn-limit error, the SDK raises a plain `Exception` after yielding the final result message, not a `ClaudeSDKError` subclass.

1923 

1920### `CLINotFoundError`1924### `CLINotFoundError`

1921 1925 

1922Raised when Claude Code CLI is not installed or not found.1926Raised when Claude Code CLI is not installed or not found.


2041 default_factory=list2045 default_factory=list

2042 ) # List of callbacks to execute2046 ) # List of callbacks to execute

2043 timeout: float | None = (2047 timeout: float | None = (

2044 None # Timeout in seconds. When omitted, the per-event default applies2048 None # Timeout in seconds. When omitted, the per-event default applies:

2049 # 600 for most events, 30 for UserPromptSubmit

2045 )2050 )

2046```2051```

2047 2052 


3412 print(f"Process failed with exit code: {e.exit_code}")3417 print(f"Process failed with exit code: {e.exit_code}")

3413 except CLIJSONDecodeError as e:3418 except CLIJSONDecodeError as e:

3414 print(f"Failed to parse response: {e}")3419 print(f"Failed to parse response: {e}")

3420 # A single-shot query() raises a plain Exception after yielding an error result

3421 except Exception as e:

3422 print(f"Query ended with an error result: {e}")

3415 3423 

3416 3424 

3417asyncio.run(main())3425asyncio.run(main())


3554```python theme={null}3562```python theme={null}

3555import asyncio3563import asyncio

3556 3564 

3557from claude_agent_sdk import query, ClaudeAgentOptions, SandboxSettings3565from claude_agent_sdk import query, ClaudeAgentOptions

3558 3566 

3559sandbox_settings: SandboxSettings = {3567sandbox_settings = {

3560 "enabled": True,3568 "enabled": True,

3561 "autoAllowBashIfSandboxed": True,3569 "autoAllowBashIfSandboxed": True,

3570 "failIfUnavailable": True,

3562 "network": {"allowLocalBinding": True},3571 "network": {"allowLocalBinding": True},

3563}3572}

3564 3573 

Details

17## Prerequisites17## Prerequisites

18 18 

19* **Node.js 18+** or **Python 3.10+**19* **Node.js 18+** or **Python 3.10+**

20* An **Anthropic account** ([sign up here](https://platform.claude.com/))20* An **Anthropic account**. If you don't have one, [sign up here](https://platform.claude.com/).

21 21 

22## Setup22## Setup

23 23 


120 * **Google Cloud's Agent Platform**: set `CLAUDE_CODE_USE_VERTEX=1` environment variable and configure Google Cloud credentials120 * **Google Cloud's Agent Platform**: set `CLAUDE_CODE_USE_VERTEX=1` environment variable and configure Google Cloud credentials

121 * **Microsoft Foundry**: set `CLAUDE_CODE_USE_FOUNDRY=1` environment variable and configure Azure credentials121 * **Microsoft Foundry**: set `CLAUDE_CODE_USE_FOUNDRY=1` environment variable and configure Azure credentials

122 122 

123 See the setup guides for [Amazon Bedrock](/en/amazon-bedrock), [Claude Platform on AWS](/en/claude-platform-on-aws), [Google Cloud's Agent Platform](/en/google-vertex-ai), or [Microsoft Foundry](/en/microsoft-foundry) for details.123 See the setup guides for [Amazon Bedrock](/docs/en/amazon-bedrock), [Claude Platform on AWS](/docs/en/claude-platform-on-aws), [Google Cloud's Agent Platform](/docs/en/google-vertex-ai), or [Microsoft Foundry](/docs/en/microsoft-foundry) for details.

124 124 

125 <Note>125 <Note>

126 Unless previously approved, Anthropic does not allow third party developers to offer claude.ai login or rate limits for their products, including agents built on the Claude Agent SDK. Please use the API key authentication methods described in this document instead.126 Unless previously approved, Anthropic does not allow third party developers to offer claude.ai login or rate limits for their products, including agents built on the Claude Agent SDK. Please use the API key authentication methods described in this document instead.


211 211 

212This code has three main parts:212This code has three main parts:

213 213 

2141. **`query`**: the main entry point that creates the agentic loop. It returns an async iterator, so you use `async for` to stream messages as Claude works. See the full API in the [Python](/en/agent-sdk/python#query) or [TypeScript](/en/agent-sdk/typescript#query) SDK reference.2141. **`query`**: the main entry point that creates the agentic loop. It returns an async iterator, so you use `async for` to stream messages as Claude works. See the full API in the [Python](/docs/en/agent-sdk/python#query) or [TypeScript](/docs/en/agent-sdk/typescript#query) SDK reference.

215 215 

2162. **`prompt`**: what you want Claude to do. Claude figures out which tools to use based on the task.2162. **`prompt`**: what you want Claude to do. Claude figures out which tools to use based on the task.

217 217 

2183. **`options`**: configuration for the agent. This example uses `allowedTools` to pre-approve `Read`, `Edit`, and `Glob`, and `permissionMode: "acceptEdits"` to auto-approve file changes. Other options include `systemPrompt`, `mcpServers`, and more. See all options for [Python](/en/agent-sdk/python#claudeagentoptions) or [TypeScript](/en/agent-sdk/typescript#options).2183. **`options`**: configuration for the agent. This example uses `allowedTools` to pre-approve `Read`, `Edit`, and `Glob`, and `permissionMode: "acceptEdits"` to auto-approve file changes. Other options include `systemPrompt`, `mcpServers`, and more. See all options for [Python](/docs/en/agent-sdk/python#claudeagentoptions) or [TypeScript](/docs/en/agent-sdk/typescript#options).

219 219 

220The `async for` loop keeps running as Claude thinks, calls tools, observes results, and decides what to do next. Each iteration yields a message: Claude's reasoning, a tool call, a tool result, or the final outcome. The SDK handles the orchestration (tool execution, context management, retries) so you just consume the stream. The loop ends when Claude finishes the task or hits an error.220The `async for` loop keeps running as Claude thinks, calls tools, observes results, and decides what to do next. Each iteration yields a message: Claude's reasoning, a tool call, a tool result, or the final outcome. The SDK handles the orchestration, tool execution, context management, and retries, so you consume the stream. The loop ends when Claude finishes the task or hits an error.

221 221 

222The message handling inside the loop filters for human-readable output. Without filtering, you'd see raw message objects including system initialization and internal state, which is useful for debugging but noisy otherwise.222The message handling inside the loop filters for human-readable output. Without filtering, you'd see raw message objects including system initialization and internal state, which is useful for debugging but noisy otherwise.

223 223 

224<Note>224<Note>

225 This example uses streaming to show progress in real-time. If you don't need live output (e.g., for background jobs or CI pipelines), you can collect all messages at once. See [Streaming vs. single-turn mode](/en/agent-sdk/streaming-vs-single-mode) for details.225 This example uses streaming to show progress in real-time. If you don't need live output (e.g., for background jobs or CI pipelines), you can collect all messages at once. See [Streaming vs. single-turn mode](/docs/en/agent-sdk/streaming-vs-single-mode) for details.

226</Note>226</Note>

227 227 

228### Run your agent228### Run your agent


262This is what makes the Agent SDK different: Claude executes tools directly instead of asking you to implement them.262This is what makes the Agent SDK different: Claude executes tools directly instead of asking you to implement them.

263 263 

264<Note>264<Note>

265 If you see "API key not found", make sure you've set the `ANTHROPIC_API_KEY` environment variable in the shell where you run your agent. The SDK doesn't load `.env` files automatically. See the [full troubleshooting guide](/en/troubleshooting) for more help.265 If you see "API key not found", make sure you've set the `ANTHROPIC_API_KEY` environment variable in the shell where you run your agent. The SDK doesn't load `.env` files automatically. See the [full troubleshooting guide](/docs/en/troubleshooting) for more help.

266</Note>266</Note>

267 267 

268### Try other prompts268### Try other prompts


355| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------- |355| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------- |

356| `acceptEdits` | Auto-approves file edits and common filesystem commands, asks for other actions | Trusted development workflows |356| `acceptEdits` | Auto-approves file edits and common filesystem commands, asks for other actions | Trusted development workflows |

357| `plan` | Runs read-only tools; file edits are never auto-approved and reach your `canUseTool` callback | Scoping a task before approving execution |357| `plan` | Runs read-only tools; file edits are never auto-approved and reach your `canUseTool` callback | Scoping a task before approving execution |

358| `dontAsk` | Denies anything not in `allowedTools`; connector tools [your organization set to `ask`](/en/mcp#organization-controls-on-connector-tools) and tools that require user interaction are denied even if you've listed them | Locked-down headless agents |358| `dontAsk` | Denies anything not in `allowedTools`; connector tools [your organization set to `ask`](/docs/en/mcp#organization-controls-on-connector-tools) and tools that require user interaction are denied even if you've listed them | Locked-down headless agents |

359| `auto` | A model classifier approves or denies permission prompts | Autonomous agents with safety guardrails |359| `auto` | A model classifier approves or denies permission prompts | Autonomous agents with safety guardrails |

360| `bypassPermissions` | Runs every tool without prompting, except tools matched by an explicit [`ask` rule](/en/agent-sdk/permissions#how-permissions-are-evaluated), connector tools [your organization set to `ask`](/en/mcp#organization-controls-on-connector-tools), and tools that require user interaction. In the TypeScript SDK, also requires `allowDangerouslySkipPermissions: true` in `options` | Sandboxed CI, fully trusted environments |360| `bypassPermissions` | Runs every tool without prompting, except tools matched by an explicit [`ask` rule](/docs/en/agent-sdk/permissions#how-permissions-are-evaluated), connector tools [your organization set to `ask`](/docs/en/mcp#organization-controls-on-connector-tools), and tools that require user interaction. In the TypeScript SDK, also requires `allowDangerouslySkipPermissions: true` in `options` | Sandboxed CI, fully trusted environments |

361| `default` | Requires a `canUseTool` callback to handle approval | Custom approval flows |361| `default` | Requires a `canUseTool` callback to handle approval | Custom approval flows |

362 362 

363The example above uses `acceptEdits` mode, which auto-approves file operations so the agent can run without interactive prompts. If you want to prompt users for approval, use `default` mode and provide a [`canUseTool` callback](/en/agent-sdk/user-input) that collects user input. For more control, see [Permissions](/en/agent-sdk/permissions).363[Building an agent that finds and fixes bugs](#build-an-agent-that-finds-and-fixes-bugs) uses `acceptEdits` mode, which auto-approves file operations so the agent can run without interactive prompts. If you want to prompt users for approval, use `default` mode and provide a [`canUseTool` callback](/docs/en/agent-sdk/user-input) that collects user input. For more control, see [Permissions](/docs/en/agent-sdk/permissions).

364 364 

365## Next steps365## Next steps

366 366 

367Now that you've created your first agent, learn how to extend its capabilities and tailor it to your use case:367Now that you've created your first agent, learn how to extend its capabilities and tailor it to your use case:

368 368 

369* **[Permissions](/en/agent-sdk/permissions)**: control what your agent can do and when it needs approval369* **[Permissions](/docs/en/agent-sdk/permissions)**: control what your agent can do and when it needs approval

370* **[Hooks](/en/agent-sdk/hooks)**: run custom code before or after tool calls370* **[Hooks](/docs/en/agent-sdk/hooks)**: run custom code before or after tool calls

371* **[Sessions](/en/agent-sdk/sessions)**: build multi-turn agents that maintain context371* **[Sessions](/docs/en/agent-sdk/sessions)**: build multi-turn agents that maintain context

372* **[MCP servers](/en/agent-sdk/mcp)**: connect to databases, browsers, APIs, and other external systems372* **[MCP servers](/docs/en/agent-sdk/mcp)**: connect to databases, browsers, APIs, and other external systems

373* **[Hosting](/en/agent-sdk/hosting)**: deploy agents to Docker, cloud, and CI/CD373* **[Hosting](/docs/en/agent-sdk/hosting)**: deploy agents to Docker, cloud, and CI/CD

374* **[Example agents](https://github.com/anthropics/claude-agent-sdk-demos)**: see complete examples: email assistant, research agent, and more374* **[Example agents](https://github.com/anthropics/claude-agent-sdk-demos)**: see complete examples: email assistant, research agent, and more

Details

232 232 

233Both SDKs ship a conformance suite that asserts the behavioral contract `append`, `load`, and the optional methods must satisfy. Tests for optional methods skip automatically when those methods are not implemented.233Both SDKs ship a conformance suite that asserts the behavioral contract `append`, `load`, and the optional methods must satisfy. Tests for optional methods skip automatically when those methods are not implemented.

234 234 

235In TypeScript, copy [`shared/conformance.ts`](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/shared/conformance.ts) from the example directory into your test suite. In Python, the suite ships in the package:235In TypeScript, copy [`shared/conformance.ts`](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/shared/conformance.ts) from the example directory into your test suite. In Python, the suite ships in the package. To run it with pytest, which isn't an SDK dependency, install pytest first:

236 

237```bash theme={null}

238pip install pytest

239```

240 

241Then pass your adapter to the suite in a test file as a zero-argument factory, which `run_session_store_conformance` calls once per contract to build a fresh store:

236 242 

237```python Python theme={null}243```python Python theme={null}

238import pytest244import pytest

239from claude_agent_sdk.testing import run_session_store_conformance245from claude_agent_sdk.testing import run_session_store_conformance

240 246 

241 247 

242@pytest.mark.asyncio248@pytest.mark.anyio

243async def test_my_store_conformance():249async def test_my_store_conformance():

244 await run_session_store_conformance(MyRedisStore) # Your adapter class250 await run_session_store_conformance(MyRedisStore)

245```251```

246 252 

253Passing the `MyRedisStore` class itself, as this example does, works when the constructor takes no arguments. For an adapter that takes a pre-configured client, pass a lambda that constructs the store instead. Because the contracts reuse the same session keys, each store the factory returns must start with empty storage, so have the lambda provision isolated backing storage per call, such as a fresh in-memory fake, a unique key prefix, or a new test database.

254 

247## Behavior notes255## Behavior notes

248 256 

249### Dual-write architecture257### Dual-write architecture


276 284 

277The following TypeScript SDK functions accept a `sessionStore` option and operate against the store instead of the local filesystem when it is provided:285The following TypeScript SDK functions accept a `sessionStore` option and operate against the store instead of the local filesystem when it is provided:

278 286 

279* [`query()`](/en/agent-sdk/typescript#query)287* [`query()`](/docs/en/agent-sdk/typescript#query)

280* [`startup()`](/en/agent-sdk/typescript#startup)288* [`startup()`](/docs/en/agent-sdk/typescript#startup)

281* [`listSessions()`](/en/agent-sdk/typescript#listsessions)289* [`listSessions()`](/docs/en/agent-sdk/typescript#listsessions)

282* [`getSessionInfo()`](/en/agent-sdk/typescript#getsessioninfo)290* [`getSessionInfo()`](/docs/en/agent-sdk/typescript#getsessioninfo)

283* [`getSessionMessages()`](/en/agent-sdk/typescript#getsessionmessages)291* [`getSessionMessages()`](/docs/en/agent-sdk/typescript#getsessionmessages)

284* [`renameSession()`](/en/agent-sdk/typescript#renamesession)292* [`renameSession()`](/docs/en/agent-sdk/typescript#renamesession)

285* [`tagSession()`](/en/agent-sdk/typescript#tagsession)293* [`tagSession()`](/docs/en/agent-sdk/typescript#tagsession)

286* [`deleteSession()`](/en/agent-sdk/typescript)294* [`deleteSession()`](/docs/en/agent-sdk/typescript)

287* [`forkSession()`](/en/agent-sdk/typescript)295* [`forkSession()`](/docs/en/agent-sdk/typescript)

288* [`listSubagents()`](/en/agent-sdk/typescript)296* [`listSubagents()`](/docs/en/agent-sdk/typescript)

289* [`getSubagentMessages()`](/en/agent-sdk/typescript)297* [`getSubagentMessages()`](/docs/en/agent-sdk/typescript)

290 298 

291In the Python SDK, set `session_store` in [`ClaudeAgentOptions`](/en/agent-sdk/python#claudeagentoptions) to run `query()` against a store. The remaining operations each have a store-backed Python function that takes the store as an argument: `list_sessions_from_store()`, `get_session_info_from_store()`, `get_session_messages_from_store()`, `list_subagents_from_store()`, `get_subagent_messages_from_store()`, `rename_session_via_store()`, `tag_session_via_store()`, `delete_session_via_store()`, and `fork_session_via_store()`. `startup()` has no Python equivalent. The standalone functions documented in the [Python SDK reference](/en/agent-sdk/python#functions), such as `list_sessions()`, read local session files.299In the Python SDK, set `session_store` in [`ClaudeAgentOptions`](/docs/en/agent-sdk/python#claudeagentoptions) to run `query()` against a store. The remaining operations each have a store-backed Python function that takes the store as an argument: `list_sessions_from_store()`, `get_session_info_from_store()`, `get_session_messages_from_store()`, `list_subagents_from_store()`, `get_subagent_messages_from_store()`, `rename_session_via_store()`, `tag_session_via_store()`, `delete_session_via_store()`, and `fork_session_via_store()`. `startup()` has no Python equivalent. The standalone functions documented in the [Python SDK reference](/docs/en/agent-sdk/python#functions), such as `list_sessions()`, read local session files.

292 300 

293## Related resources301## Related resources

294 302 

295* [Work with sessions](/en/agent-sdk/sessions): Continue, resume, and fork without a custom store303* [Work with sessions](/docs/en/agent-sdk/sessions): Continue, resume, and fork without a custom store

296* [Host the SDK](/en/agent-sdk/hosting): Deployment patterns for multi-host environments304* [Host the SDK](/docs/en/agent-sdk/hosting): Deployment patterns for multi-host environments

297* [TypeScript `Options`](/en/agent-sdk/typescript#options): Full option reference305* [TypeScript `Options`](/docs/en/agent-sdk/typescript#options): Full option reference

298* [`examples/session-stores/`](https://github.com/anthropics/claude-agent-sdk-typescript/tree/main/examples/session-stores): Runnable S3, Redis, and Postgres reference adapters306* [`examples/session-stores/`](https://github.com/anthropics/claude-agent-sdk-typescript/tree/main/examples/session-stores): Runnable S3, Redis, and Postgres reference adapters

Details

25Unlike subagents (which can be defined programmatically), Skills must be created as filesystem artifacts. The SDK does not provide a programmatic API for registering Skills.25Unlike subagents (which can be defined programmatically), Skills must be created as filesystem artifacts. The SDK does not provide a programmatic API for registering Skills.

26 26 

27<Note>27<Note>

28 Skills are discovered through the filesystem setting sources. With default `query()` options, the SDK loads user and project sources, so skills in `~/.claude/skills/`, `<cwd>/.claude/skills/`, and `.claude/skills/` in any parent directory of `<cwd>` up to the repository root are available. If you set `settingSources` explicitly, include `'user'` or `'project'` to keep skill discovery, or use the [`plugins` option](/en/agent-sdk/plugins) to load skills from a specific path.28 Skills are discovered through the filesystem setting sources. With default `query()` options, the SDK loads user and project sources, so skills in `~/.claude/skills/`, `<cwd>/.claude/skills/`, and `.claude/skills/` in any parent directory of `<cwd>` up to the repository root are available. If you set `settingSources` explicitly, include `'user'` or `'project'` to keep skill discovery, or use the [`plugins` option](/docs/en/agent-sdk/plugins) to load skills from a specific path.

29</Note>29</Note>

30 30 

31## Using Skills with the SDK31## Using Skills with the SDK


34 34 

35Once configured, Claude automatically discovers Skills from the filesystem and invokes them when relevant to the user's request.35Once configured, Claude automatically discovers Skills from the filesystem and invokes them when relevant to the user's request.

36 36 

37The following example sets `cwd` to the process's current working directory, so run it from inside a project that has a `.claude/skills/` directory in the current directory or any parent up to the repository root:

38 

37<CodeGroup>39<CodeGroup>

38 ```python Python theme={null}40 ```python Python theme={null}

39 import asyncio41 import asyncio

42 import os

43 

40 from claude_agent_sdk import query, ClaudeAgentOptions44 from claude_agent_sdk import query, ClaudeAgentOptions

41 45 

42 46 

43 async def main():47 async def main():

44 options = ClaudeAgentOptions(48 options = ClaudeAgentOptions(

45 cwd="/path/to/project", # Project with .claude/skills/49 cwd=os.getcwd(), # .claude/skills/ here or in a parent directory

46 setting_sources=["user", "project"], # Load Skills from filesystem50 setting_sources=["user", "project"], # Load Skills from filesystem

47 skills="all", # Enable every discovered Skill51 skills="all", # Enable every discovered Skill

48 allowed_tools=["Read", "Write", "Bash"],52 allowed_tools=["Read", "Write", "Bash"],


63 for await (const message of query({67 for await (const message of query({

64 prompt: "Help me process this PDF document",68 prompt: "Help me process this PDF document",

65 options: {69 options: {

66 cwd: "/path/to/project", // Project with .claude/skills/70 cwd: process.cwd(), // .claude/skills/ here or in a parent directory

67 settingSources: ["user", "project"], // Load Skills from filesystem71 settingSources: ["user", "project"], // Load Skills from filesystem

68 skills: "all", // Enable every discovered Skill72 skills: "all", // Enable every discovered Skill

69 allowedTools: ["Read", "Write", "Bash"]73 allowedTools: ["Read", "Write", "Bash"]


74 ```78 ```

75</CodeGroup>79</CodeGroup>

76 80 

81Near the start of the stream, the SDK yields a system message with subtype `init`. Check its `skills` array to confirm your Skills loaded before Claude starts working. The array lists user-invocable Skills only. A Skill with [`user-invocable: false`](/docs/en/skills#control-who-invokes-a-skill) in its frontmatter loads and remains available to Claude but doesn't appear in the array.

82 

77To enable only specific Skills, pass their names. Names match the `name` field in `SKILL.md` or the Skill's directory name. Use `plugin:skill` for plugin-provided Skills.83To enable only specific Skills, pass their names. Names match the `name` field in `SKILL.md` or the Skill's directory name. Use `plugin:skill` for plugin-provided Skills.

78 84 

85<Note>

86 Import statements from the first example are assumed in the following code snippets.

87</Note>

88 

79<CodeGroup>89<CodeGroup>

80 ```python Python theme={null}90 ```python Python theme={null}

81 options = ClaudeAgentOptions(skills=["pdf", "docx"])91 options = ClaudeAgentOptions(skills=["pdf", "docx"])


102 112 

103**Example directory structure**:113**Example directory structure**:

104 114 

105```bash theme={null}115```text theme={null}

106.claude/skills/processing-pdfs/116.claude/skills/processing-pdfs/

107└── SKILL.md117└── SKILL.md

108```118```

109 119 

110For complete guidance on creating Skills, including SKILL.md structure, multi-file Skills, and examples, see:120For complete guidance on creating Skills, including SKILL.md structure, multi-file Skills, and examples, see:

111 121 

112* [Agent Skills in Claude Code](/en/skills): Complete guide with examples122* [Agent Skills in Claude Code](/docs/en/skills): Complete guide with examples

113* [Agent Skills Best Practices](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices): Authoring guidelines and naming conventions123* [Agent Skills Best Practices](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices): Authoring guidelines and naming conventions

114 124 

115## Tool Restrictions125## Tool Restrictions


122 132 

123To control tool access for Skills in SDK applications, use `allowedTools` to pre-approve specific tools. Without a `canUseTool` callback, anything not in the list is denied:133To control tool access for Skills in SDK applications, use `allowedTools` to pre-approve specific tools. Without a `canUseTool` callback, anything not in the list is denied:

124 134 

125<Note>

126 Import statements from the first example are assumed in the following code snippets.

127</Note>

128 

129<CodeGroup>135<CodeGroup>

130 ```python Python theme={null}136 ```python Python theme={null}

131 options = ClaudeAgentOptions(137 options = ClaudeAgentOptions(

132 setting_sources=["user", "project"], # Load Skills from filesystem138 setting_sources=["user", "project"], # Load Skills from filesystem

133 skills="all",139 skills="all",

134 allowed_tools=["Read", "Grep", "Glob"],140 allowed_tools=["Read", "Grep", "Glob"],

141 permission_mode="dontAsk", # Deny anything not pre-approved instead of prompting

135 )142 )

136 143 

144 

145 async def main():

137 async for message in query(prompt="Analyze the codebase structure", options=options):146 async for message in query(prompt="Analyze the codebase structure", options=options):

138 print(message)147 print(message)

148 

149 

150 asyncio.run(main())

139 ```151 ```

140 152 

141 ```typescript TypeScript theme={null}153 ```typescript TypeScript theme={null}


145 settingSources: ["user", "project"], // Load Skills from filesystem157 settingSources: ["user", "project"], // Load Skills from filesystem

146 skills: "all",158 skills: "all",

147 allowedTools: ["Read", "Grep", "Glob"],159 allowedTools: ["Read", "Grep", "Glob"],

148 permissionMode: "dontAsk" // Deny anything not in allowedTools160 permissionMode: "dontAsk" // Deny anything not pre-approved instead of prompting

149 }161 }

150 })) {162 })) {

151 console.log(message);163 console.log(message);


155 167 

156## Discovering Available Skills168## Discovering Available Skills

157 169 

158To see which Skills are available in your SDK application, simply ask Claude:170To see which Skills are available in your SDK application, ask Claude. The example below sets only the `skills` option and omits `settingSources`/`setting_sources`. When you leave `settingSources`/`setting_sources` unset, the SDK still loads Skills from the user and project sources, so the `skills` option set to `"all"` on its own makes them available to list.

159 171 

160<CodeGroup>172<CodeGroup>

161 ```python Python theme={null}173 ```python Python theme={null}

162 options = ClaudeAgentOptions(174 options = ClaudeAgentOptions(skills="all")

163 setting_sources=["user", "project"], # Load Skills from filesystem175 

164 skills="all",

165 )

166 176 

177 async def main():

167 async for message in query(prompt="What Skills are available?", options=options):178 async for message in query(prompt="What Skills are available?", options=options):

168 print(message)179 print(message)

180 

181 

182 asyncio.run(main())

169 ```183 ```

170 184 

171 ```typescript TypeScript theme={null}185 ```typescript TypeScript theme={null}

172 for await (const message of query({186 for await (const message of query({

173 prompt: "What Skills are available?",187 prompt: "What Skills are available?",

174 options: {188 options: {

175 settingSources: ["user", "project"], // Load Skills from filesystem

176 skills: "all"189 skills: "all"

177 }190 }

178 })) {191 })) {


190<CodeGroup>203<CodeGroup>

191 ```python Python theme={null}204 ```python Python theme={null}

192 options = ClaudeAgentOptions(205 options = ClaudeAgentOptions(

193 cwd="/path/to/project",206 cwd=os.getcwd(),

194 setting_sources=["user", "project"], # Load Skills from filesystem207 setting_sources=["user", "project"], # Load Skills from filesystem

195 skills="all",208 skills="all",

196 allowed_tools=["Read", "Bash"],209 allowed_tools=["Read", "Bash"],

197 )210 )

198 211 

212 

213 async def main():

199 async for message in query(prompt="Extract text from invoice.pdf", options=options):214 async for message in query(prompt="Extract text from invoice.pdf", options=options):

200 print(message)215 print(message)

216 

217 

218 asyncio.run(main())

201 ```219 ```

202 220 

203 ```typescript TypeScript theme={null}221 ```typescript TypeScript theme={null}

204 for await (const message of query({222 for await (const message of query({

205 prompt: "Extract text from invoice.pdf",223 prompt: "Extract text from invoice.pdf",

206 options: {224 options: {

207 cwd: "/path/to/project",225 cwd: process.cwd(),

208 settingSources: ["user", "project"], // Load Skills from filesystem226 settingSources: ["user", "project"], // Load Skills from filesystem

209 skills: "all",227 skills: "all",

210 allowedTools: ["Read", "Bash"]228 allowedTools: ["Read", "Bash"]


237 255 

238 ```typescript TypeScript theme={null}256 ```typescript TypeScript theme={null}

239 // Skills not loaded: settingSources excludes user and project257 // Skills not loaded: settingSources excludes user and project

240 const options = {258 const optionsWithoutSkills = {

241 settingSources: [],259 settingSources: [],

242 skills: "all"260 skills: "all"

243 };261 };

244 262 

245 // Skills loaded: user and project sources included263 // Skills loaded: user and project sources included

246 const options = {264 const optionsWithSkills = {

247 settingSources: ["user", "project"],265 settingSources: ["user", "project"],

248 skills: "all"266 skills: "all"

249 };267 };

250 ```268 ```

251</CodeGroup>269</CodeGroup>

252 270 

253For more details on `settingSources`/`setting_sources`, see the [TypeScript SDK reference](/en/agent-sdk/typescript#settingsource) or [Python SDK reference](/en/agent-sdk/python#settingsource).271For more details on `settingSources`/`setting_sources`, see the [TypeScript SDK reference](/docs/en/agent-sdk/typescript#settingsource) or [Python SDK reference](/docs/en/agent-sdk/python#settingsource).

254 272 

255**Check working directory**: The SDK loads Skills from `.claude/skills/` in the `cwd` option and in every parent directory up to the repository root. Ensure `cwd` points at or below the directory containing `.claude/skills/`, within the same repository:273**Check working directory**: The SDK loads Skills from `.claude/skills/` in the `cwd` option and in every parent directory up to the repository root. Ensure `cwd` points at or below the directory containing `.claude/skills/`, within the same repository:

256 274 


294 312 

295### Additional Troubleshooting313### Additional Troubleshooting

296 314 

297For general Skills troubleshooting (YAML syntax, debugging, etc.), see the [Claude Code Skills troubleshooting section](/en/skills#troubleshooting).315For general Skills troubleshooting (YAML syntax, debugging, etc.), see the [Claude Code Skills troubleshooting section](/docs/en/skills#troubleshooting).

298 316 

299## Related Documentation317## Related Documentation

300 318 

301### Skills Guides319### Skills Guides

302 320 

303* [Agent Skills in Claude Code](/en/skills): Complete Skills guide with creation, examples, and troubleshooting321* [Agent Skills in Claude Code](/docs/en/skills): Complete Skills guide with creation, examples, and troubleshooting

304* [Agent Skills Overview](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview): Conceptual overview, benefits, and architecture322* [Agent Skills Overview](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview): Conceptual overview, benefits, and architecture

305* [Agent Skills Best Practices](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices): Authoring guidelines for effective Skills323* [Agent Skills Best Practices](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices): Authoring guidelines for effective Skills

306* [Agent Skills Cookbook](https://platform.claude.com/cookbook/skills-notebooks-01-skills-introduction): Example Skills and templates324* [Agent Skills Cookbook](https://platform.claude.com/cookbook/skills-notebooks-01-skills-introduction): Example Skills and templates

307 325 

308### SDK Resources326### SDK Resources

309 327 

310* [Subagents in the SDK](/en/agent-sdk/subagents): Similar filesystem-based agents with programmatic options328* [Subagents in the SDK](/docs/en/agent-sdk/subagents): Similar filesystem-based agents with programmatic options

311* [Slash Commands in the SDK](/en/agent-sdk/slash-commands): User-invoked commands329* [Slash Commands in the SDK](/docs/en/agent-sdk/slash-commands): User-invoked commands

312* [SDK Overview](/en/agent-sdk/overview): General SDK concepts330* [SDK Overview](/docs/en/agent-sdk/overview): General SDK concepts

313* [TypeScript SDK Reference](/en/agent-sdk/typescript): Complete API documentation331* [TypeScript SDK Reference](/docs/en/agent-sdk/typescript): Complete API documentation

314* [Python SDK Reference](/en/agent-sdk/python): Complete API documentation332* [Python SDK Reference](/docs/en/agent-sdk/python): Complete API documentation

Details

119 119 

120 After yielding that final result message, the SDK raises an error, because the CLI process exits with a non-zero code.120 After yielding that final result message, the SDK raises an error, because the CLI process exits with a non-zero code.

121 121 

122 Wrap the loop in a `try`/`catch` in TypeScript or `try`/`except` in Python if your command might hit the limit, as shown in [Single Message Input](/en/agent-sdk/streaming-vs-single-mode#single-message-input), or set `maxTurns` high enough for the work to complete. In Python, catch `Exception`: the SDK surfaces error results as a plain `Exception`.122 Wrap the loop in a `try`/`catch` in TypeScript or `try`/`except` in Python if your command might hit the limit, as shown in [Single Message Input](/docs/en/agent-sdk/streaming-vs-single-mode#single-message-input), or set `maxTurns` high enough for the work to complete. In Python, catch `Exception`: the SDK surfaces error results as a plain `Exception`.

123</Note>123</Note>

124 124 

125## Common Slash Commands125## Common Slash Commands


204</CodeGroup>204</CodeGroup>

205 205 

206<Note>206<Note>

207 A `compact_boundary` message only arrives when compaction ran. With nothing to summarize, `/compact` reports the reason instead of raising: the run still ends with a `success` result, no `compact_boundary` message is emitted, and the result text carries the message, for example `Not enough messages to compact.` after a single short exchange. A fresh one-shot `query()` call starts with empty context, so use this pattern in a session with prior turns, for example in [streaming input mode](/en/agent-sdk/streaming-vs-single-mode) or when resuming a session.207 A `compact_boundary` message only arrives when compaction ran. With nothing to summarize, `/compact` reports the reason instead of raising: the run still ends with a `success` result, no `compact_boundary` message is emitted, and the result text carries the message, for example `Not enough messages to compact.` after a single short exchange. A fresh one-shot `query()` call starts with empty context, so use this pattern in a session with prior turns, for example in [streaming input mode](/docs/en/agent-sdk/streaming-vs-single-mode) or when resuming a session.

208</Note>208</Note>

209 209 

210### `/clear` - Reset conversation context210### `/clear` - Reset conversation context

211 211 

212The `/clear` command resets the conversation to an empty context, so subsequent prompts start with no prior conversation history. The previous conversation remains on disk and can be returned to by passing its session ID to the [`resume` option](/en/agent-sdk/sessions#resume-by-id).212The `/clear` command resets the conversation to an empty context, so subsequent prompts start with no prior conversation history. The previous conversation remains on disk and can be returned to by passing its session ID to the [`resume` option](/docs/en/agent-sdk/sessions#resume-by-id).

213 213 

214This is useful in [streaming input mode](/en/agent-sdk/streaming-vs-single-mode), where you send multiple prompts over a single connection. For one-shot `query()` calls, each call already starts with empty context, so sending `/clear` has no practical effect; start a new `query()` instead.214This is useful in [streaming input mode](/docs/en/agent-sdk/streaming-vs-single-mode), where you send multiple prompts over a single connection. For one-shot `query()` calls, each call already starts with empty context, so sending `/clear` has no practical effect; start a new `query()` instead.

215 215 

216<Note>216<Note>

217 `/clear` in the SDK requires Claude Code v2.1.117 or later. In earlier versions it is omitted from `slash_commands`.217 `/clear` in the SDK requires Claude Code v2.1.117 or later. In earlier versions it is omitted from `slash_commands`.


222In addition to using built-in slash commands, you can create your own custom commands that are available through the SDK. Custom commands are defined as markdown files in specific directories, similar to how subagents are configured.222In addition to using built-in slash commands, you can create your own custom commands that are available through the SDK. Custom commands are defined as markdown files in specific directories, similar to how subagents are configured.

223 223 

224<Note>224<Note>

225 The `.claude/commands/` directory is the legacy format. The recommended format is `.claude/skills/<name>/SKILL.md`, which supports the same slash-command invocation (`/name`) plus autonomous invocation by Claude. See [Skills](/en/agent-sdk/skills) for the current format. The CLI continues to support both formats, and the examples below remain accurate for `.claude/commands/`.225 The `.claude/commands/` directory is the legacy format. The recommended format is `.claude/skills/<name>/SKILL.md`, which supports the same slash-command invocation (`/name`) plus autonomous invocation by Claude. See [Skills](/docs/en/agent-sdk/skills) for the current format. The CLI continues to support both formats, and the examples below remain accurate for `.claude/commands/`.

226</Note>226</Note>

227 227 

228### File Locations228### File Locations


400 ```400 ```

401</CodeGroup>401</CodeGroup>

402 402 

403If the prompt passes fewer arguments than the placeholders reference, unmatched indexed placeholders such as `$1` stay in the command text verbatim. For the full substitution behavior, including named arguments, see [available string substitutions](/docs/en/skills#available-string-substitutions).

404 

403#### Bash Command Execution405#### Bash Command Execution

404 406 

405Custom commands can execute bash commands and include their output:407Custom commands can execute bash commands and include their output:


568 570 

569## See Also571## See Also

570 572 

571* [Slash Commands](/en/skills) - Complete slash command documentation573* [Slash Commands](/docs/en/skills) - Complete slash command documentation

572* [Subagents in the SDK](/en/agent-sdk/subagents) - Similar filesystem-based configuration for subagents574* [Subagents in the SDK](/docs/en/agent-sdk/subagents) - Similar filesystem-based configuration for subagents

573* [TypeScript SDK reference](/en/agent-sdk/typescript) - Complete API documentation575* [TypeScript SDK reference](/docs/en/agent-sdk/typescript) - Complete API documentation

574* [SDK overview](/en/agent-sdk/overview) - General SDK concepts576* [SDK overview](/docs/en/agent-sdk/overview) - General SDK concepts

575* [CLI reference](/en/cli-reference) - Command-line interface577* [CLI reference](/docs/en/cli-reference) - Command-line interface

Details

380 380 

381#### Example381#### Example

382 382 

383The example below resolves settings for a project directory and prints the source that controls the cleanup period.383The example below resolves settings for a project directory and prints the source that controls the cleanup period. On a machine where no settings file sets `cleanupPeriodDays`, both printed lines show `undefined` for the value, which is the expected output rather than an error.

384 384 

385```typescript theme={null}385```typescript theme={null}

386import { resolveSettings } from "@anthropic-ai/claude-agent-sdk";386import { resolveSettings } from "@anthropic-ai/claude-agent-sdk";


424| `extraArgs` | `Record<string, string \| null>` | `{}` | Additional arguments |424| `extraArgs` | `Record<string, string \| null>` | `{}` | Additional arguments |

425| `fallbackModel` | `string` | `undefined` | Model to use if primary fails |425| `fallbackModel` | `string` | `undefined` | Model to use if primary fails |

426| `forkSession` | `boolean` | `false` | When resuming with `resume`, fork to a new session ID instead of continuing the original session |426| `forkSession` | `boolean` | `false` | When resuming with `resume`, fork to a new session ID instead of continuing the original session |

427| `forwardSubagentText` | `boolean` | `false` | Forward subagent text and thinking blocks as assistant and user messages with `parent_tool_use_id` set, so consumers can render a nested transcript. By default only `tool_use` and `tool_result` blocks from subagents are emitted |427| `forwardSubagentText` | `boolean` | `false` | Forward subagent text and thinking blocks as assistant and user messages with `parent_tool_use_id` set, so consumers can render a nested transcript. By default only `tool_use` and `tool_result` blocks from subagents are emitted. {/* min-version: 2.1.219 */}Messages from subagents at every nesting depth are forwarded on Claude Code v2.1.219 and later; before v2.1.219, only messages from depth-1 subagents appeared |

428| `hooks` | `Partial<Record<`[`HookEvent`](#hookevent)`, `[`HookCallbackMatcher`](#hookcallbackmatcher)`[]>>` | `{}` | Hook callbacks for events |428| `hooks` | `Partial<Record<`[`HookEvent`](#hookevent)`, `[`HookCallbackMatcher`](#hookcallbackmatcher)`[]>>` | `{}` | Hook callbacks for events |

429| `includeHookEvents` | `boolean` | `false` | Include hook lifecycle events for every hook event in the message stream as [`SDKHookStartedMessage`](#sdkhookstartedmessage), [`SDKHookProgressMessage`](#sdkhookprogressmessage), and [`SDKHookResponseMessage`](#sdkhookresponsemessage). Lifecycle events for `SessionStart` and `Setup` hooks are always included and don't need this option |429| `includeHookEvents` | `boolean` | `false` | Include hook lifecycle events for every hook event in the message stream as [`SDKHookStartedMessage`](#sdkhookstartedmessage), [`SDKHookProgressMessage`](#sdkhookprogressmessage), and [`SDKHookResponseMessage`](#sdkhookresponsemessage). Lifecycle events for `SessionStart` and `Setup` hooks are always included and don't need this option |

430| `includePartialMessages` | `boolean` | `false` | Include partial message events |430| `includePartialMessages` | `boolean` | `false` | Include partial message events |


470The CLI subprocess reads several environment variables that control API timeouts and stall detection. Pass them through the `env` option:470The CLI subprocess reads several environment variables that control API timeouts and stall detection. Pass them through the `env` option:

471 471 

472```typescript theme={null}472```typescript theme={null}

473import { query } from "@anthropic-ai/claude-agent-sdk";

474 

473const result = query({475const result = query({

474 prompt: "Analyze this code",476 prompt: "Analyze this code",

475 options: {477 options: {


486* `API_TIMEOUT_MS`: per-request timeout on the Anthropic client, in milliseconds. Default `600000`. Applies to the main loop and all subagents.488* `API_TIMEOUT_MS`: per-request timeout on the Anthropic client, in milliseconds. Default `600000`. Applies to the main loop and all subagents.

487* `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff. For unattended runs that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG=1`: it retries capacity errors indefinitely, and {/* min-version: 2.1.199 */}as of Claude Code v2.1.199 raises the default for other transient errors to `300` and removes the cap on this variable.489* `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff. For unattended runs that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG=1`: it retries capacity errors indefinitely, and {/* min-version: 2.1.199 */}as of Claude Code v2.1.199 raises the default for other transient errors to `300` and removes the cap on this variable.

488* `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents launched with `run_in_background`. Default `600000`. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents.490* `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents launched with `run_in_background`. Default `600000`. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents.

489* `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. The aborted request goes through the normal retry path.491* `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. After the abort, Claude Code retries the request at most once, and only before Claude has started a block of text or a tool call in the response; once Claude has completed a block of text or a tool call, Claude Code keeps the completed output, appends an [incomplete-response notice](/docs/en/errors#the-response-above-may-be-incomplete) instead of retrying, and still runs any completed tool call.

490 492 

491### `Query` object493### `Query` object

492 494 


509 supportedModels(): Promise<ModelInfo[]>;511 supportedModels(): Promise<ModelInfo[]>;

510 supportedAgents(): Promise<AgentInfo[]>;512 supportedAgents(): Promise<AgentInfo[]>;

511 mcpServerStatus(): Promise<McpServerStatus[]>;513 mcpServerStatus(): Promise<McpServerStatus[]>;

514 getContextUsage(): Promise<SDKControlGetContextUsageResponse>;

512 accountInfo(): Promise<AccountInfo>;515 accountInfo(): Promise<AccountInfo>;

513 reconnectMcpServer(serverName: string): Promise<void>;516 reconnectMcpServer(serverName: string): Promise<void>;

514 toggleMcpServer(serverName: string, enabled: boolean): Promise<void>;517 toggleMcpServer(serverName: string, enabled: boolean): Promise<void>;


526| `interrupt()` | Interrupts the query. Only available in streaming input mode. {/* min-version: 2.1.205 */}When the CLI advertises the `interrupt_receipt_v1` capability in [`SDKSystemMessage.capabilities`](#sdksystemmessage), resolves with an [`SDKControlInterruptResponse`](#sdkcontrolinterruptresponse) listing the queued messages that survive the interrupt. Resolves `undefined` on CLIs before v2.1.205 |529| `interrupt()` | Interrupts the query. Only available in streaming input mode. {/* min-version: 2.1.205 */}When the CLI advertises the `interrupt_receipt_v1` capability in [`SDKSystemMessage.capabilities`](#sdksystemmessage), resolves with an [`SDKControlInterruptResponse`](#sdkcontrolinterruptresponse) listing the queued messages that survive the interrupt. Resolves `undefined` on CLIs before v2.1.205 |

527| `rewindFiles(userMessageId, options?)` | Restores files to their state at the specified user message. Pass `{ dryRun: true }` to preview changes. Requires `enableFileCheckpointing: true`. See [File checkpointing](/docs/en/agent-sdk/file-checkpointing) |530| `rewindFiles(userMessageId, options?)` | Restores files to their state at the specified user message. Pass `{ dryRun: true }` to preview changes. Requires `enableFileCheckpointing: true`. See [File checkpointing](/docs/en/agent-sdk/file-checkpointing) |

528| `setPermissionMode()` | Changes the permission mode (only available in streaming input mode) |531| `setPermissionMode()` | Changes the permission mode (only available in streaming input mode) |

529| `setModel()` | Changes the model (only available in streaming input mode) |532| `setModel()` | Changes the model (only available in streaming input mode). Passing `undefined` or the string `"default"` resets to the session default model |

530| `setMaxThinkingTokens()` | *Deprecated:* Use the `thinking` option instead. Changes the maximum thinking tokens. Passing `null` resets thinking to the session default: a mid-session override is cleared, and thinking stays off for sessions that have it disabled |533| `setMaxThinkingTokens()` | *Deprecated:* Use the `thinking` option instead. Changes the maximum thinking tokens. Passing `null` resets thinking to the session default: a mid-session override is cleared, and thinking stays off for sessions that have it disabled |

531| `applyFlagSettings(settings)` | Merges settings into the session's flag settings layer at runtime (only available in streaming input mode). See [`applyFlagSettings()`](#applyflagsettings) |534| `applyFlagSettings(settings)` | Merges settings into the session's flag settings layer at runtime (only available in streaming input mode). See [`applyFlagSettings()`](#applyflagsettings) |

532| `initializationResult()` | Returns the full initialization result including supported commands, models, account info, and output style configuration |535| `initializationResult()` | Returns the full initialization result including supported commands, models, account info, and output style configuration |

533| `reinitialize()` | {/* min-version: 2.1.195 */}Re-sends the `initialize` control request to the running CLI and returns a fresh result instead of the cached first-connect result. Use it after a transport gap, such as reattaching to a session after a disconnect, so pending permission requests reach your `canUseTool` callback again. Make the callback idempotent per request ID, because a request whose response was lost is dispatched again. Requires Claude Code v2.1.195 or later |536| `reinitialize()` | {/* min-version: 2.1.195 */}Re-sends the `initialize` control request to the running CLI and returns a fresh result instead of the cached first-connect result. Use it after a transport gap, such as reattaching to a session after a disconnect, so pending permission requests reach your `canUseTool` callback again. Make the callback idempotent per request ID, because a request whose response was lost is dispatched again. Requires Claude Code v2.1.195 or later |

534| `supportedCommands()` | Returns available slash commands |537| `supportedCommands()` | Returns available slash commands. {/* min-version: agent-sdk@0.3.216 */}From Agent SDK v0.3.216 the list reflects mid-session command changes; see [`SDKCommandsChangedMessage`](#sdkcommandschangedmessage) |

535| `supportedModels()` | Returns available models with display info |538| `supportedModels()` | Returns available models with display info |

536| `supportedAgents()` | Returns available subagents as [`AgentInfo`](#agentinfo)`[]` |539| `supportedAgents()` | Returns available subagents as [`AgentInfo`](#agentinfo)`[]` |

537| `mcpServerStatus()` | Returns status of connected MCP servers |540| `mcpServerStatus()` | Returns status of connected MCP servers |

541| `getContextUsage()` | Returns an [`SDKControlGetContextUsageResponse`](#sdkcontrolgetcontextusageresponse) breaking down the session's context window usage by category, skill, and tool. The same data `/context` shows in an interactive session |

538| `accountInfo()` | Returns account information |542| `accountInfo()` | Returns account information |

539| `reconnectMcpServer(serverName)` | Reconnect an MCP server by name |543| `reconnectMcpServer(serverName)` | Reconnect an MCP server by name |

540| `toggleMcpServer(serverName, enabled)` | Enable or disable an MCP server by name |544| `toggleMcpServer(serverName, enabled)` | Enable or disable an MCP server by name |


564The example below switches the active model mid-session, then clears the override so the model falls back to whatever the user or project settings specify.568The example below switches the active model mid-session, then clears the override so the model falls back to whatever the user or project settings specify.

565 569 

566```typescript theme={null}570```typescript theme={null}

571import { query } from "@anthropic-ai/claude-agent-sdk";

572 

567const q = query({ prompt: messageStream });573const q = query({ prompt: messageStream });

568 574 

569// Override the model for the rest of the session575// Override the model for the rest of the session


610 models: ModelInfo[];616 models: ModelInfo[];

611 account: AccountInfo;617 account: AccountInfo;

612 fast_mode_state?: "off" | "cooldown" | "on";618 fast_mode_state?: "off" | "cooldown" | "on";

619 fast_mode_disabled_reason?: FastModeDisabledReason;

613};620};

614```621```

615 622 

623{/* min-version: 2.1.219 */}The response always reports `fast_mode_state`, and when something blocks [fast mode](/docs/en/fast-mode), `fast_mode_disabled_reason` carries the reason code alongside it, so you can explain the blocked state instead of re-deriving availability. Both behaviors require Claude Code v2.1.219 or later. Before v2.1.219, the response omitted `fast_mode_state` when fast mode wasn't available and never carried a reason. For the reason codes and their meanings, see [`fast_mode_disabled_reason`](#sdkresultmessage) on the result message.

624 

616When a client sends `initialize` to a session that is already running, the control-response wrapper also carries an optional `pending_permission_requests` array. The field is on the response wrapper itself, not in the `SDKControlInitializeResponse` payload above. Each entry is a complete `control_request` message with the same `{ type: "control_request", request_id, request }` shape the session streams for permission requests while running.625When a client sends `initialize` to a session that is already running, the control-response wrapper also carries an optional `pending_permission_requests` array. The field is on the response wrapper itself, not in the `SDKControlInitializeResponse` payload above. Each entry is a complete `control_request` message with the same `{ type: "control_request", request_id, request }` shape the session streams for permission requests while running.

617 626 

618These are requests that were issued before the client connected and are still awaiting a reply. The SDK reads the array for you and dispatches each entry to your [`canUseTool`](#canusetool) callback, the same redelivery that [`reinitialize()`](#query-object) triggers after a transport gap. Handle repeated request IDs idempotently, because an entry can repeat a request the callback already received before the connection dropped.627These are requests that were issued before the client connected and are still awaiting a reply. The SDK reads the array for you and dispatches each entry to your [`canUseTool`](#canusetool) callback, the same redelivery that [`reinitialize()`](#query-object) triggers after a transport gap. Handle repeated request IDs idempotently, because an entry can repeat a request the callback already received before the connection dropped.


624```typescript theme={null}633```typescript theme={null}

625type SDKControlInterruptResponse = {634type SDKControlInterruptResponse = {

626 still_queued: string[];635 still_queued: string[];

636 cancelled?: string[];

627};637};

628```638```

629 639 


635* Only main-thread messages are listed. Messages addressed to a subagent are out of scope.645* Only main-thread messages are listed. Messages addressed to a subagent are out of scope.

636* The list can include UUIDs your client never sent, such as [scheduled task](/docs/en/scheduled-tasks) triggers. Ignore UUIDs you don't recognize instead of treating them as an error.646* The list can include UUIDs your client never sent, such as [scheduled task](/docs/en/scheduled-tasks) triggers. Ignore UUIDs you don't recognize instead of treating them as an error.

637 647 

648{/* min-version: 2.1.219 */}A client that drives the CLI's control protocol directly, rather than through `interrupt()`, can set `cancel_queued: true` on the `interrupt` control request. Claude Code v2.1.219 and later advertises support with the `interrupt_cancel_queued_v1` capability in [`SDKSystemMessage.capabilities`](#sdksystemmessage); older CLIs ignore the field and leave queued messages to run as usual. Such an interrupt also cancels every message that would otherwise be listed under `still_queued`: the receipt lists them under `cancelled` instead, `still_queued` is empty, and none of them run.

649 

650The `cancelled` list carries the same caveats as `still_queued`. The `interrupt()` method never sends `cancel_queued`, so receipts it resolves with don't carry `cancelled`.

651 

638The receipt is a snapshot taken at the moment the interrupt is processed, and on a clean interrupt it arrives before the interrupted turn's [`SDKResultMessage`](#sdkresultmessage). Read the receipt rather than inspecting the queue after that result: the loop starts the next queued turn immediately, so the queue you inspect after the result has already changed.652The receipt is a snapshot taken at the moment the interrupt is processed, and on a clean interrupt it arrives before the interrupted turn's [`SDKResultMessage`](#sdkresultmessage). Read the receipt rather than inspecting the queue after that result: the loop starts the next queued turn immediately, so the queue you inspect after the result has already changed.

639 653 

654### `SDKControlGetContextUsageResponse`

655 

656Return type of [`getContextUsage()`](#query-object). This is the same payload the `/context` command renders in an interactive session, so alongside the token counts it carries display fields such as `color`, `gridRows`, and `percentage` that `/context` uses to draw its usage grid.

657 

658```typescript theme={null}

659type SDKControlGetContextUsageResponse = {

660 categories: {

661 name: string;

662 tokens: number;

663 color: string;

664 isDeferred?: boolean;

665 }[];

666 totalTokens: number;

667 maxTokens: number;

668 rawMaxTokens: number;

669 percentage: number;

670 gridRows: {

671 color: string;

672 isFilled: boolean;

673 categoryName: string;

674 tokens: number;

675 percentage: number;

676 squareFullness: number;

677 }[][];

678 model: string;

679 memoryFiles: {

680 path: string;

681 type: string;

682 tokens: number;

683 }[];

684 mcpTools: {

685 name: string;

686 serverName: string;

687 tokens: number;

688 isLoaded?: boolean;

689 }[];

690 deferredBuiltinTools?: {

691 name: string;

692 tokens: number;

693 isLoaded: boolean;

694 }[];

695 systemTools?: {

696 name: string;

697 tokens: number;

698 }[];

699 systemPromptSections?: {

700 name: string;

701 tokens: number;

702 }[];

703 agents: {

704 agentType: string;

705 source: string;

706 tokens: number;

707 }[];

708 slashCommands?: {

709 totalCommands: number;

710 includedCommands: number;

711 tokens: number;

712 };

713 skills?: {

714 totalSkills: number;

715 includedSkills: number;

716 tokens: number;

717 skillFrontmatter: {

718 name: string;

719 source: string;

720 tokens: number;

721 }[];

722 };

723 autoCompactThreshold?: number;

724 isAutoCompactEnabled: boolean;

725 messageBreakdown?: {

726 toolCallTokens: number;

727 toolResultTokens: number;

728 attachmentTokens: number;

729 assistantMessageTokens: number;

730 userMessageTokens: number;

731 redirectedContextTokens: number;

732 unattributedTokens: number;

733 toolCallsByType: {

734 name: string;

735 callTokens: number;

736 resultTokens: number;

737 }[];

738 attachmentsByType: {

739 name: string;

740 tokens: number;

741 }[];

742 };

743 apiUsage: {

744 input_tokens: number;

745 output_tokens: number;

746 cache_creation_input_tokens: number;

747 cache_read_input_tokens: number;

748 } | null;

749};

750```

751 

752Read token attribution from the collection fields:

753 

754* `categories` holds the per-category totals.

755* `mcpTools` and `agents` attribute tokens to individual MCP tools and subagents.

756* `memoryFiles` lists each loaded memory file with its cost.

757* `skills.skillFrontmatter` attributes the skill listing's tokens to each included skill. The per-skill counts measure each skill's listing entry as Claude Code actually sends it, which can be shorter than the skill's full frontmatter. Compare `skills.totalSkills` with `skills.includedSkills` to see whether every discovered skill made it into the listing.

758 

759`totalTokens` is the session's current context usage, and `maxTokens` is the window that usage is measured against. That window is the model's context window, or the lower auto-compaction window when one applies. Claude Code leaves the optional `deferredBuiltinTools`, `systemTools`, and `systemPromptSections` diagnostics unset, so expect them to be absent even though the type declares them.

760 

640### `AgentDefinition`761### `AgentDefinition`

641 762 

642Configuration for a subagent defined programmatically.763Configuration for a subagent defined programmatically.


696```817```

697 818 

698| Value | Description | Location |819| Value | Description | Location |

699| :---------- | :---------------------------------------------- | :---------------------------- |820| :---------- | :------------------------------------------------------------------------ | :---------------------------- |

700| `'user'` | Global user settings | `~/.claude/settings.json` |821| `'user'` | Global user settings | `~/.claude/settings.json` |

701| `'project'` | Shared project settings (version controlled) | `.claude/settings.json` |822| `'project'` | Shared project settings (version controlled) | `.claude/settings.json` |

702| `'local'` | Local project settings (not version controlled) | `.claude/settings.local.json` |823| `'local'` | Local project settings, gitignored when Claude Code saves a setting to it | `.claude/settings.local.json` |

703 824 

704#### Default behavior825#### Default behavior

705 826 


710**Disable filesystem settings:**831**Disable filesystem settings:**

711 832 

712```typescript theme={null}833```typescript theme={null}

834import { query } from "@anthropic-ai/claude-agent-sdk";

835 

713// Do not load user, project, or local settings from disk836// Do not load user, project, or local settings from disk

714const result = query({837const result = query({

715 prompt: "Analyze this code",838 prompt: "Analyze this code",


720**Load all filesystem settings explicitly:**843**Load all filesystem settings explicitly:**

721 844 

722```typescript theme={null}845```typescript theme={null}

846import { query } from "@anthropic-ai/claude-agent-sdk";

847 

723const result = query({848const result = query({

724 prompt: "Analyze this code",849 prompt: "Analyze this code",

725 options: {850 options: {


731**Load only specific setting sources:**856**Load only specific setting sources:**

732 857 

733```typescript theme={null}858```typescript theme={null}

859import { query } from "@anthropic-ai/claude-agent-sdk";

860 

734// Load only project settings, ignore user and local861// Load only project settings, ignore user and local

735const result = query({862const result = query({

736 prompt: "Run CI checks",863 prompt: "Run CI checks",


743**Testing and CI environments:**870**Testing and CI environments:**

744 871 

745```typescript theme={null}872```typescript theme={null}

873import { query } from "@anthropic-ai/claude-agent-sdk";

874 

746// Ensure consistent behavior in CI by excluding local settings875// Ensure consistent behavior in CI by excluding local settings

747const result = query({876const result = query({

748 prompt: "Run tests",877 prompt: "Run tests",

749 options: {878 options: {

750 settingSources: ["project"], // Only team-shared settings879 settingSources: ["project"], // Only team-shared settings

751 permissionMode: "bypassPermissions"880 permissionMode: "bypassPermissions",

881 allowDangerouslySkipPermissions: true

752 }882 }

753});883});

754```884```


756**SDK-only applications:**886**SDK-only applications:**

757 887 

758```typescript theme={null}888```typescript theme={null}

889import { query } from "@anthropic-ai/claude-agent-sdk";

890 

759// Define everything programmatically.891// Define everything programmatically.

760// Pass [] to opt out of filesystem setting sources.892// Pass [] to opt out of filesystem setting sources.

761const result = query({893const result = query({


776**Loading CLAUDE.md project instructions:**908**Loading CLAUDE.md project instructions:**

777 909 

778```typescript theme={null}910```typescript theme={null}

911import { query } from "@anthropic-ai/claude-agent-sdk";

912 

779// Load project settings to include CLAUDE.md files913// Load project settings to include CLAUDE.md files

780const result = query({914const result = query({

781 prompt: "Add a new feature following project conventions",915 prompt: "Add a new feature following project conventions",


1036 message: BetaMessage; // From Anthropic SDK1170 message: BetaMessage; // From Anthropic SDK

1037 parent_tool_use_id: string | null;1171 parent_tool_use_id: string | null;

1038 error?: SDKAssistantMessageError;1172 error?: SDKAssistantMessageError;

1173 aborted?: true;

1039 timestamp?: string;1174 timestamp?: string;

1040};1175};

1041```1176```


1044 1179 

1045`SDKAssistantMessageError` is one of: `'authentication_failed'`, `'oauth_org_not_allowed'`, `'billing_error'`, `'rate_limit'`, `'overloaded'`, `'invalid_request'`, `'model_not_found'`, `'server_error'`, `'max_output_tokens'`, or `'unknown'`. `'model_not_found'` means the selected model doesn't exist or isn't available to your account or deployment. `'overloaded'` means the API returned a 529 because the server is at capacity, as opposed to `'rate_limit'`, which is a 429 against your quota.1180`SDKAssistantMessageError` is one of: `'authentication_failed'`, `'oauth_org_not_allowed'`, `'billing_error'`, `'rate_limit'`, `'overloaded'`, `'invalid_request'`, `'model_not_found'`, `'server_error'`, `'max_output_tokens'`, or `'unknown'`. `'model_not_found'` means the selected model doesn't exist or isn't available to your account or deployment. `'overloaded'` means the API returned a 529 because the server is at capacity, as opposed to `'rate_limit'`, which is a 429 against your quota.

1046 1181 

1182`aborted` is `true` when an interrupt or abort truncated the assistant message before the stream completed: the message has no `stop_reason` and the content may end mid-word. The field is absent on normally completed messages. It requires Agent SDK v0.3.214 or later.

1183 

1047`timestamp` is the ISO 8601 time when the message's content finished generating on the process that produced it. The value comes from that machine's clock, so use it for display only and don't order messages by it. One API turn can produce several assistant messages that share a `message.id`, each with its own `timestamp`. When the field is absent, fall back to the time you received the message.1184`timestamp` is the ISO 8601 time when the message's content finished generating on the process that produced it. The value comes from that machine's clock, so use it for display only and don't order messages by it. One API turn can produce several assistant messages that share a `message.id`, each with its own `timestamp`. When the field is absent, fall back to the time you received the message.

1048 1185 

1049### `SDKUserMessage`1186### `SDKUserMessage`


1110 stop_reason: string | null;1247 stop_reason: string | null;

1111 ttft_ms?: number;1248 ttft_ms?: number;

1112 ttft_stream_ms?: number;1249 ttft_stream_ms?: number;

1250 user_message_uuid?: string;

1251 request_sent_wall_ms?: number;

1113 total_cost_usd: number;1252 total_cost_usd: number;

1114 usage: NonNullableUsage;1253 usage: NonNullableUsage;

1115 modelUsage: { [modelName: string]: ModelUsage };1254 modelUsage: { [modelName: string]: ModelUsage };


1118 deferred_tool_use?: { id: string; name: string; input: Record<string, unknown> };1257 deferred_tool_use?: { id: string; name: string; input: Record<string, unknown> };

1119 terminal_reason?: TerminalReason;1258 terminal_reason?: TerminalReason;

1120 fast_mode_state?: FastModeState;1259 fast_mode_state?: FastModeState;

1260 fast_mode_disabled_reason?: FastModeDisabledReason;

1121 origin?: SDKMessageOrigin;1261 origin?: SDKMessageOrigin;

1122 }1262 }

1123 | {1263 | {


1141 errors: string[];1281 errors: string[];

1142 terminal_reason?: TerminalReason;1282 terminal_reason?: TerminalReason;

1143 fast_mode_state?: FastModeState;1283 fast_mode_state?: FastModeState;

1284 fast_mode_disabled_reason?: FastModeDisabledReason;

1144 origin?: SDKMessageOrigin;1285 origin?: SDKMessageOrigin;

1145 };1286 };

1146```1287```


1150* `api_error_status`: the HTTP status code of the API error that terminated the conversation. Absent or `null` when the turn ended without an API error.1291* `api_error_status`: the HTTP status code of the API error that terminated the conversation. Absent or `null` when the turn ended without an API error.

1151* `ttft_ms`: time to first token in milliseconds, measured when the first complete assistant message arrives. Present on the success arm only.1292* `ttft_ms`: time to first token in milliseconds, measured when the first complete assistant message arrives. Present on the success arm only.

1152* `ttft_stream_ms`: time in milliseconds until the first `message_start` stream event, when the response stream opens. Lower than `ttft_ms`; the gap between the two is time spent streaming the first message. Present on the success arm only.1293* `ttft_stream_ms`: time in milliseconds until the first `message_start` stream event, when the response stream opens. Lower than `ttft_ms`; the gap between the two is time spent streaming the first message. Present on the success arm only.

1294* {/* min-version: 2.1.216 */}`user_message_uuid`: the `uuid` of the [`SDKUserMessage`](#sdkusermessage) that started this turn, echoed back so you can match the result to the message you sent. Requires Claude Code v2.1.216 or later. Present on the success arm only, together with `request_sent_wall_ms`; absent on API-error results, subagent calls, and synthetic turns such as scheduled ones.

1295* `request_sent_wall_ms`: epoch milliseconds at which Claude Code dispatched the API request, for joins against server-side timestamps. Present only together with `user_message_uuid`.

1153* `terminal_reason`: why the loop ended. One of `"completed"`, `"max_turns"`, `"tool_deferred"`, `"aborted_streaming"`, `"aborted_tools"`, `"hook_stopped"`, `"stop_hook_prevented"`, `"background_requested"`, `"blocking_limit"`, `"rapid_refill_breaker"`, `"prompt_too_long"`, `"image_error"`, `"model_error"`, `"api_error"`, `"malformed_tool_use_exhausted"`, `"budget_exhausted"`, `"structured_output_retry_exhausted"`, `"tool_deferred_unavailable"`, or `"turn_setup_failed"`.1296* `terminal_reason`: why the loop ended. One of `"completed"`, `"max_turns"`, `"tool_deferred"`, `"aborted_streaming"`, `"aborted_tools"`, `"hook_stopped"`, `"stop_hook_prevented"`, `"background_requested"`, `"blocking_limit"`, `"rapid_refill_breaker"`, `"prompt_too_long"`, `"image_error"`, `"model_error"`, `"api_error"`, `"malformed_tool_use_exhausted"`, `"budget_exhausted"`, `"structured_output_retry_exhausted"`, `"tool_deferred_unavailable"`, or `"turn_setup_failed"`.

1154* `fast_mode_state`: one of `"on"`, `"off"`, or `"cooldown"`.1297* `fast_mode_state`: one of `"on"`, `"off"`, or `"cooldown"`.

1298* `fast_mode_disabled_reason`: {/* min-version: 2.1.219 */}why [fast mode](/docs/en/fast-mode) isn't available right now. Absent when nothing blocks fast mode, though a request may still run at standard speed. During the cooldown after a fast mode rate limit, Claude Code reports `fast_mode_state: "cooldown"` with no reason code and re-enables fast mode when the cooldown expires. Requires Claude Code v2.1.219 or later.

1299 

1300Use the reason code to explain why fast mode is off in your own UI instead of re-deriving availability. Each code names the check that blocked fast mode:

1301 

1302| Reason code | Meaning |

1303| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |

1304| `free` | The account doesn't have the paid subscription or usage credits fast mode requires |

1305| `preference` | The organization has disabled fast mode |

1306| `extra_usage_disabled` | Usage credits are turned off for the account |

1307| `network_error` | The [availability check](/docs/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways) couldn't reach `api.anthropic.com` |

1308| `unknown` | Claude Code couldn't determine availability |

1309| `not_first_party` | The session uses a provider other than the Anthropic API |

1310| `disabled_by_env` | [`CLAUDE_CODE_DISABLE_FAST_MODE`](/docs/en/env-vars) is set |

1311| `model_not_allowed` | The fast mode Opus model isn't in the organization's [`availableModels`](/docs/en/model-config#restrict-model-selection) allowlist |

1312| `sdk_opt_in_required` | The session hasn't opted in to fast mode: pass `fastMode: true` in the [`settings`](#options) option or through [`applyFlagSettings()`](#applyflagsettings) |

1313| `pending` | The availability check hasn't completed yet |

1314 

1315The same pair of fields appears on [`SDKSystemMessage`](#sdksystemmessage) and on the [`SDKControlInitializeResponse`](#sdkcontrolinitializeresponse), so you can read the fast mode state before the first turn.

1155 1316 

1156The `origin` field forwards the [`SDKMessageOrigin`](#sdkmessageorigin) of the user message that triggered this result. When a background task finishes and the SDK injects a synthetic follow-up turn, the resulting `SDKResultMessage` carries `origin: { kind: "task-notification" }`. Check this field to distinguish results that answer your prompt from results emitted for background-task follow-ups, so you can route or suppress the latter. The field is absent for results emitted before any user turn, such as startup errors.1317The `origin` field forwards the [`SDKMessageOrigin`](#sdkmessageorigin) of the user message that triggered this result. When a background task finishes and the SDK injects a synthetic follow-up turn, the resulting `SDKResultMessage` carries `origin: { kind: "task-notification" }`. Check this field to distinguish results that answer your prompt from results emitted for background-task follow-ups, so you can route or suppress the latter. The field is absent for results emitted before any user turn, such as startup errors.

1157 1318 


1183 output_style: string;1344 output_style: string;

1184 skills: string[];1345 skills: string[];

1185 plugins: { name: string; path: string }[];1346 plugins: { name: string; path: string }[];

1347 fast_mode_state?: FastModeState;

1348 fast_mode_disabled_reason?: FastModeDisabledReason;

1186 capabilities?: string[];1349 capabilities?: string[];

1187};1350};

1188```1351```

1189 1352 

1190{/* min-version: 2.1.205 */}1353`fast_mode_state` reports the session's [fast mode](/docs/en/fast-mode) state. {/* min-version: 2.1.219 */}When something blocks fast mode, `fast_mode_disabled_reason` names the check that blocked it; the field requires Claude Code v2.1.219 or later. For the reason codes and their meanings, see [`fast_mode_disabled_reason`](#sdkresultmessage) on the result message.

1191 1354 

1192The `capabilities` array names the protocol behaviors this CLI implements, so you can feature-detect instead of comparing `claude_code_version` strings. It is an open set: ignore values you don't recognize, and check for the specific capability whose behavior you rely on. The field requires Claude Code v2.1.205 or later and is absent on earlier CLIs.1355The `capabilities` array names the protocol behaviors this CLI implements, so you can feature-detect instead of comparing `claude_code_version` strings. It is an open set: ignore values you don't recognize, and check for the specific capability whose behavior you rely on. The field requires Claude Code v2.1.205 or later and is absent on earlier CLIs.

1193 1356 

1194| Capability | Meaning |1357| Capability | Meaning |

1195| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |1358| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

1196| `interrupt_receipt_v1` | [`interrupt()`](#query-object) resolves with an [`SDKControlInterruptResponse`](#sdkcontrolinterruptresponse) receipt naming the queued messages that survive the interrupt |1359| `interrupt_receipt_v1` | [`interrupt()`](#query-object) resolves with an [`SDKControlInterruptResponse`](#sdkcontrolinterruptresponse) receipt naming the queued messages that survive the interrupt |

1360| `interrupt_cancel_queued_v1` | {/* min-version: 2.1.219 */}The `interrupt` control request honors `cancel_queued: true`, cancelling the queued messages that would otherwise survive the interrupt and listing them on the receipt's `cancelled` field. See [`SDKControlInterruptResponse`](#sdkcontrolinterruptresponse). Requires Claude Code v2.1.219 or later |

1197 1361 

1198### `SDKPartialAssistantMessage`1362### `SDKPartialAssistantMessage`

1199 1363 


1328 kind: "peer";1492 kind: "peer";

1329 from: string;1493 from: string;

1330 name?: string;1494 name?: string;

1495 fromSession?: string;

1331 senderTaskId?: string;1496 senderTaskId?: string;

1332 body?: string;1497 body?: string;

1498 verifiedPeerPid?: number;

1333 }1499 }

1334 | { kind: "task-notification" }1500 | { kind: "task-notification" }

1335 | { kind: "coordinator" }1501 | { kind: "coordinator" }


1337```1503```

1338 1504 

1339| `kind` | Meaning |1505| `kind` | Meaning |

1340| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |1506| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

1341| `human` | Direct input from the end user. If your application forwards what the user typed as a user message, set its `origin` to `{ kind: "human" }` explicitly: {/* min-version: 2.1.210 */}Claude Code treats a user message with no `origin` as unattributed, and checks that require a human-typed prompt, such as the [`ultracode` workflow keyword](/docs/en/workflows#ask-for-a-workflow-in-your-prompt), don't accept it. Before v2.1.210, Claude Code treated an absent `origin` on a user message as human input. |1507| `human` | Direct input from the end user. If your application forwards what the user typed as a user message, set its `origin` to `{ kind: "human" }` explicitly: {/* min-version: 2.1.210 */}Claude Code treats a user message with no `origin` as unattributed, and checks that require a human-typed prompt, such as the [`ultracode` workflow keyword](/docs/en/workflows#ask-for-a-workflow-in-your-prompt), don't accept it. Before v2.1.210, Claude Code treated an absent `origin` on a user message as human input. |

1342| `channel` | Message arriving on a [channel](/docs/en/channels). `server` is the source MCP server name. |1508| `channel` | Message arriving on a [channel](/docs/en/channels). `server` is the source MCP server name. |

1343| `peer` | Message from another agent. For an in-process [teammate](/docs/en/agent-teams) sending to `main` via `SendMessage`, `from` is the teammate's name and `senderTaskId` is its task ID. For a cross-session peer such as another local Claude Code process, `from` is the sender address and `senderTaskId` is absent. {/* min-version: 2.1.205 */}`name` and `body` require Claude Code v2.1.205 or later. `name` is the sender's display name, normalized by Claude Code: it strips Unicode control, format, surrogate, and line or paragraph separator code points, then trims the result and caps it at 64 code points with an ellipsis. `body` is the decoded message body with the peer envelope stripped, byte-exact with what the model sees. For a teammate message `body` is always present; for a cross-session peer it is present only when the turn is exactly one peer envelope formed by Claude Code. Render `name` and `body` instead of re-parsing the message text. |1509| `peer` | Message from another agent: an in-process [teammate](/docs/en/agent-teams) or a cross-session peer such as another local Claude Code process. See [Peer origin fields](#peer-origin-fields) for the per-field semantics and the trust model. |

1344| `task-notification` | Synthetic turn injected after a background task finished. See [`SDKTaskNotificationMessage`](#sdktasknotificationmessage). |1510| `task-notification` | Synthetic turn injected after a background task finished. See [`SDKTaskNotificationMessage`](#sdktasknotificationmessage). |

1345| `coordinator` | Message from a team coordinator in an [agent team](/docs/en/agent-teams). |1511| `coordinator` | Message from a team coordinator in an [agent team](/docs/en/agent-teams). |

1346| `auto-continuation` | Synthetic turn injected when the session continues without fresh user input, such as a command result that triggers a follow-up prompt. |1512| `auto-continuation` | Synthetic turn injected when the session continues without fresh user input, such as a command result that triggers a follow-up prompt. |

1347 1513 

1514### Peer origin fields

1515 

1516A `peer` origin identifies which agent sent the message: an in-process [teammate](/docs/en/agent-teams) sending to `main` with `SendMessage`, or a cross-session peer such as another local Claude Code process. The two kinds of sender fill the fields differently:

1517 

1518* `from`: the teammate's name, or the sender address for a cross-session peer. The value is sender-authored; `verifiedPeerPid` is the verified identity.

1519* `senderTaskId`: the teammate's task ID. Absent for a cross-session peer.

1520* {/* min-version: 2.1.205 */}`name`: the sender's display name, normalized by Claude Code: it strips Unicode control, format, surrogate, and line or paragraph separator code points, then trims the result and caps it at 64 code points with an ellipsis. Requires Claude Code v2.1.205 or later.

1521* {/* min-version: 2.1.205 */}`body`: the decoded message body with the peer envelope stripped, byte-exact with what the model sees. Always present for a teammate message; for a cross-session peer, present only when the turn is exactly one peer envelope formed by Claude Code. Render `name` and `body` instead of re-parsing the message text. Requires Claude Code v2.1.205 or later.

1522* {/* min-version: 2.1.216 */}`fromSession`: the sender's host-openable session ID, set by the sender's host so your UI can link back to the sending session. Like `from`, it is sender-asserted: use it as a navigation target only, and don't treat it as proof of the sender's identity. Requires Claude Code v2.1.216 or later.

1523* {/* min-version: 2.1.216 */}`verifiedPeerPid`: the process ID of the process that connected to this session's cross-session messaging socket, verified by the kernel and read from the connection itself, never from the payload. Use it, not `from`, to identify the sender: `from` is forgeable by any same-user process. The field is absent when Claude Code can't verify it, such as on Windows or non-socket ingress, so an absent value means the sender is unverified. For relayed traffic it identifies the relay rather than the message's author, and process IDs are recyclable, so treat it as provenance rather than an authentication token. Requires Claude Code v2.1.216 or later.

1524 

1348## Hook Types1525## Hook Types

1349 1526 

1350For a comprehensive guide on using hooks with examples and common patterns, see the [Hooks guide](/docs/en/agent-sdk/hooks).1527For a comprehensive guide on using hooks with examples and common patterns, see the [Hooks guide](/docs/en/agent-sdk/hooks).


1365 | "SessionStart"1542 | "SessionStart"

1366 | "SessionEnd"1543 | "SessionEnd"

1367 | "Stop"1544 | "Stop"

1545 | "StopFailure"

1368 | "SubagentStart"1546 | "SubagentStart"

1369 | "SubagentStop"1547 | "SubagentStop"

1370 | "PreCompact"1548 | "PreCompact"

1549 | "PostCompact"

1371 | "PermissionRequest"1550 | "PermissionRequest"

1551 | "PermissionDenied"

1372 | "Setup"1552 | "Setup"

1373 | "TeammateIdle"1553 | "TeammateIdle"

1554 | "TaskCreated"

1374 | "TaskCompleted"1555 | "TaskCompleted"

1556 | "Elicitation"

1557 | "ElicitationResult"

1375 | "ConfigChange"1558 | "ConfigChange"

1559 | "DirectoryAdded"

1376 | "WorktreeCreate"1560 | "WorktreeCreate"

1377 | "WorktreeRemove"1561 | "WorktreeRemove"

1562 | "InstructionsLoaded"

1563 | "CwdChanged"

1564 | "FileChanged"

1378 | "MessageDisplay";1565 | "MessageDisplay";

1379```1566```

1380 1567 


1412 | PostToolUseHookInput1599 | PostToolUseHookInput

1413 | PostToolUseFailureHookInput1600 | PostToolUseFailureHookInput

1414 | PostToolBatchHookInput1601 | PostToolBatchHookInput

1602 | PermissionDeniedHookInput

1415 | NotificationHookInput1603 | NotificationHookInput

1416 | UserPromptSubmitHookInput1604 | UserPromptSubmitHookInput

1605 | UserPromptExpansionHookInput

1417 | SessionStartHookInput1606 | SessionStartHookInput

1418 | SessionEndHookInput1607 | SessionEndHookInput

1419 | StopHookInput1608 | StopHookInput

1609 | StopFailureHookInput

1420 | SubagentStartHookInput1610 | SubagentStartHookInput

1421 | SubagentStopHookInput1611 | SubagentStopHookInput

1422 | PreCompactHookInput1612 | PreCompactHookInput

1613 | PostCompactHookInput

1423 | PermissionRequestHookInput1614 | PermissionRequestHookInput

1424 | SetupHookInput1615 | SetupHookInput

1425 | TeammateIdleHookInput1616 | TeammateIdleHookInput

1617 | TaskCreatedHookInput

1426 | TaskCompletedHookInput1618 | TaskCompletedHookInput

1619 | ElicitationHookInput

1620 | ElicitationResultHookInput

1427 | ConfigChangeHookInput1621 | ConfigChangeHookInput

1622 | InstructionsLoadedHookInput

1623 | DirectoryAddedHookInput

1428 | WorktreeCreateHookInput1624 | WorktreeCreateHookInput

1429 | WorktreeRemoveHookInput1625 | WorktreeRemoveHookInput

1626 | CwdChangedHookInput

1627 | FileChangedHookInput

1430 | MessageDisplayHookInput;1628 | MessageDisplayHookInput;

1431```1629```

1432 1630 


1505};1703};

1506```1704```

1507 1705 

1706#### `PermissionDeniedHookInput`

1707 

1708```typescript theme={null}

1709type PermissionDeniedHookInput = BaseHookInput & {

1710 hook_event_name: "PermissionDenied";

1711 tool_name: string;

1712 tool_input: unknown;

1713 tool_use_id: string;

1714 reason: string;

1715};

1716```

1717 

1508#### `NotificationHookInput`1718#### `NotificationHookInput`

1509 1719 

1510```typescript theme={null}1720```typescript theme={null}


1522type UserPromptSubmitHookInput = BaseHookInput & {1732type UserPromptSubmitHookInput = BaseHookInput & {

1523 hook_event_name: "UserPromptSubmit";1733 hook_event_name: "UserPromptSubmit";

1524 prompt: string;1734 prompt: string;

1735 session_title?: string;

1736};

1737```

1738 

1739#### `UserPromptExpansionHookInput`

1740 

1741```typescript theme={null}

1742type UserPromptExpansionHookInput = BaseHookInput & {

1743 hook_event_name: "UserPromptExpansion";

1744 expansion_type: "slash_command" | "mcp_prompt";

1745 command_name: string;

1746 command_args: string;

1747 command_source?: string;

1748 prompt: string;

1525};1749};

1526```1750```

1527 1751 


1530```typescript theme={null}1754```typescript theme={null}

1531type SessionStartHookInput = BaseHookInput & {1755type SessionStartHookInput = BaseHookInput & {

1532 hook_event_name: "SessionStart";1756 hook_event_name: "SessionStart";

1533 source: "startup" | "resume" | "clear" | "compact";1757 source: "startup" | "resume" | "clear" | "compact" | "fork";

1534 agent_type?: string;1758 agent_type?: string;

1535 model?: string;1759 model?: string;

1760 session_title?: string;

1536};1761};

1537```1762```

1538 1763 


1557};1782};

1558```1783```

1559 1784 

1785#### `StopFailureHookInput`

1786 

1787```typescript theme={null}

1788type StopFailureHookInput = BaseHookInput & {

1789 hook_event_name: "StopFailure";

1790 error: SDKAssistantMessageError;

1791 error_details?: string;

1792 last_assistant_message?: string;

1793};

1794```

1795 

1560#### `SubagentStartHookInput`1796#### `SubagentStartHookInput`

1561 1797 

1562```typescript theme={null}1798```typescript theme={null}


1611};1847};

1612```1848```

1613 1849 

1850#### `PostCompactHookInput`

1851 

1852```typescript theme={null}

1853type PostCompactHookInput = BaseHookInput & {

1854 hook_event_name: "PostCompact";

1855 trigger: "manual" | "auto";

1856 compact_summary: string;

1857};

1858```

1859 

1614#### `PermissionRequestHookInput`1860#### `PermissionRequestHookInput`

1615 1861 

1616```typescript theme={null}1862```typescript theme={null}


1642};1888};

1643```1889```

1644 1890 

1891#### `TaskCreatedHookInput`

1892 

1893```typescript theme={null}

1894type TaskCreatedHookInput = BaseHookInput & {

1895 hook_event_name: "TaskCreated";

1896 task_id: string;

1897 task_subject: string;

1898 task_description?: string;

1899 teammate_name?: string;

1900 /** @deprecated since v2.1.178. Carries the session-derived team name; will be removed. */

1901 team_name?: string;

1902};

1903```

1904 

1645#### `TaskCompletedHookInput`1905#### `TaskCompletedHookInput`

1646 1906 

1647```typescript theme={null}1907```typescript theme={null}


1656};1916};

1657```1917```

1658 1918 

1919#### `ElicitationHookInput`

1920 

1921```typescript theme={null}

1922type ElicitationHookInput = BaseHookInput & {

1923 hook_event_name: "Elicitation";

1924 mcp_server_name: string;

1925 message: string;

1926 mode?: "form" | "url";

1927 url?: string;

1928 elicitation_id?: string;

1929 requested_schema?: Record<string, unknown>;

1930};

1931```

1932 

1933#### `ElicitationResultHookInput`

1934 

1935```typescript theme={null}

1936type ElicitationResultHookInput = BaseHookInput & {

1937 hook_event_name: "ElicitationResult";

1938 mcp_server_name: string;

1939 elicitation_id?: string;

1940 mode?: "form" | "url";

1941 action: "accept" | "decline" | "cancel";

1942 content?: Record<string, unknown>;

1943};

1944```

1945 

1659#### `ConfigChangeHookInput`1946#### `ConfigChangeHookInput`

1660 1947 

1661```typescript theme={null}1948```typescript theme={null}


1671};1958};

1672```1959```

1673 1960 

1961#### `InstructionsLoadedHookInput`

1962 

1963```typescript theme={null}

1964type InstructionsLoadedHookInput = BaseHookInput & {

1965 hook_event_name: "InstructionsLoaded";

1966 file_path: string;

1967 memory_type: "User" | "Project" | "Local" | "Managed";

1968 load_reason:

1969 | "session_start"

1970 | "nested_traversal"

1971 | "path_glob_match"

1972 | "include"

1973 | "compact";

1974 globs?: string[];

1975 trigger_file_path?: string;

1976 parent_file_path?: string;

1977};

1978```

1979 

1980#### `DirectoryAddedHookInput`

1981 

1982```typescript theme={null}

1983type DirectoryAddedHookInput = BaseHookInput & {

1984 hook_event_name: "DirectoryAdded";

1985 directory: string;

1986 source: "slash_command" | "register_repo_root";

1987};

1988```

1989 

1990`directory` is the absolute path of the directory that was added. `source` is `"slash_command"` when `/add-dir` added it and `"register_repo_root"` when the SDK control request did.

1991 

1674#### `WorktreeCreateHookInput`1992#### `WorktreeCreateHookInput`

1675 1993 

1676```typescript theme={null}1994```typescript theme={null}


1689};2007};

1690```2008```

1691 2009 

2010#### `CwdChangedHookInput`

2011 

2012```typescript theme={null}

2013type CwdChangedHookInput = BaseHookInput & {

2014 hook_event_name: "CwdChanged";

2015 old_cwd: string;

2016 new_cwd: string;

2017};

2018```

2019 

2020#### `FileChangedHookInput`

2021 

2022```typescript theme={null}

2023type FileChangedHookInput = BaseHookInput & {

2024 hook_event_name: "FileChanged";

2025 file_path: string;

2026 event: "change" | "add" | "unlink";

2027};

2028```

2029 

1692#### `MessageDisplayHookInput`2030#### `MessageDisplayHookInput`

1693 2031 

1694```typescript theme={null}2032```typescript theme={null}


1728 stopReason?: string;2066 stopReason?: string;

1729 decision?: "approve" | "block";2067 decision?: "approve" | "block";

1730 systemMessage?: string;2068 systemMessage?: string;

2069 /**

2070 * A terminal escape sequence (e.g. OSC 9 / OSC 777 desktop-notification)

2071 * for Claude Code to emit on your behalf. Only notification/title OSCs

2072 * (0, 1, 2, 9, 99, 777) and BEL are permitted; a value containing

2073 * anything else is ignored as a whole.

2074 */

2075 terminalSequence?: string;

1731 reason?: string;2076 reason?: string;

1732 hookSpecificOutput?:2077 hookSpecificOutput?:

1733 | {2078 | {


1740 | {2085 | {

1741 hookEventName: "UserPromptSubmit";2086 hookEventName: "UserPromptSubmit";

1742 additionalContext?: string;2087 additionalContext?: string;

2088 sessionTitle?: string;

2089 /** When decision is "block", omit the original prompt from the block message. */

2090 suppressOriginalPrompt?: boolean;

2091 }

2092 | {

2093 hookEventName: "UserPromptExpansion";

2094 additionalContext?: string;

1743 }2095 }

1744 | {2096 | {

1745 hookEventName: "SessionStart";2097 hookEventName: "SessionStart";

1746 additionalContext?: string;2098 additionalContext?: string;

2099 initialUserMessage?: string;

2100 sessionTitle?: string;

2101 watchPaths?: string[];

2102 /**

2103 * Re-scan skill and command directories after SessionStart hooks

2104 * complete, so skills installed by the hook are available in the

2105 * same session.

2106 */

2107 reloadSkills?: boolean;

1747 }2108 }

1748 | {2109 | {

1749 hookEventName: "Setup";2110 hookEventName: "Setup";


1768 hookEventName: "PostToolBatch";2129 hookEventName: "PostToolBatch";

1769 additionalContext?: string;2130 additionalContext?: string;

1770 }2131 }

2132 | {

2133 hookEventName: "Stop";

2134 additionalContext?: string;

2135 }

2136 | {

2137 hookEventName: "SubagentStop";

2138 additionalContext?: string;

2139 }

2140 | {

2141 hookEventName: "PermissionDenied";

2142 retry?: boolean;

2143 }

1771 | {2144 | {

1772 hookEventName: "Notification";2145 hookEventName: "Notification";

1773 additionalContext?: string;2146 additionalContext?: string;


1785 message?: string;2158 message?: string;

1786 interrupt?: boolean;2159 interrupt?: boolean;

1787 };2160 };

2161 }

2162 | {

2163 hookEventName: "Elicitation";

2164 action?: "accept" | "decline" | "cancel";

2165 content?: Record<string, unknown>;

2166 }

2167 | {

2168 hookEventName: "ElicitationResult";

2169 action?: "accept" | "decline" | "cancel";

2170 content?: Record<string, unknown>;

2171 }

2172 | {

2173 hookEventName: "CwdChanged";

2174 watchPaths?: string[];

2175 }

2176 | {

2177 hookEventName: "FileChanged";

2178 watchPaths?: string[];

2179 }

2180 | {

2181 hookEventName: "WorktreeCreate";

2182 worktreePath: string;

2183 }

2184 | {

2185 hookEventName: "MessageDisplay";

2186 /** Text displayed in place of the delta. Omit (or return the delta unchanged) to display the original. */

2187 displayContent?: string;

1788 };2188 };

1789};2189};

1790```2190```


1795 2195 

1796### `ToolInputSchemas`2196### `ToolInputSchemas`

1797 2197 

1798Union of all tool input types, exported from `@anthropic-ai/claude-agent-sdk`.2198Union of tool input types exported from `@anthropic-ai/claude-agent-sdk`; members include:

1799 2199 

1800```typescript theme={null}2200```typescript theme={null}

1801type ToolInputSchemas =2201type ToolInputSchemas =

1802 | AgentInput2202 | AgentInput

2203 | ArtifactInput

1803 | AskUserQuestionInput2204 | AskUserQuestionInput

1804 | BashInput2205 | BashInput

1805 | TaskOutputInput2206 | CronCreateInput

2207 | CronDeleteInput

2208 | CronListInput

2209 | EnterPlanModeInput

1806 | EnterWorktreeInput2210 | EnterWorktreeInput

1807 | ExitPlanModeInput2211 | ExitPlanModeInput

2212 | ExitWorktreeInput

1808 | FileEditInput2213 | FileEditInput

1809 | FileReadInput2214 | FileReadInput

1810 | FileWriteInput2215 | FileWriteInput


1814 | McpInput2219 | McpInput

1815 | MonitorInput2220 | MonitorInput

1816 | NotebookEditInput2221 | NotebookEditInput

2222 | ProjectsInput

2223 | PushNotificationInput

2224 | ReadMcpResourceDirInput

1817 | ReadMcpResourceInput2225 | ReadMcpResourceInput

1818 | SubscribeMcpResourceInput2226 | RefreshMcpToolsInput

1819 | SubscribePollingInput2227 | RemoteTriggerInput

2228 | REPLInput

2229 | ReportFindingsInput

2230 | ScheduleWakeupInput

2231 | ShowOnboardingRolePickerInput

1820 | TaskCreateInput2232 | TaskCreateInput

1821 | TaskGetInput2233 | TaskGetInput

1822 | TaskListInput2234 | TaskListInput

2235 | TaskOutputInput

1823 | TaskStopInput2236 | TaskStopInput

1824 | TaskUpdateInput2237 | TaskUpdateInput

1825 | TodoWriteInput2238 | TodoWriteInput

1826 | UnsubscribeMcpResourceInput

1827 | UnsubscribePollingInput

1828 | WebFetchInput2239 | WebFetchInput

1829 | WebSearchInput2240 | WebSearchInput

1830 | WorkflowInput;2241 | WorkflowInput;


1832 2243 

1833### Agent2244### Agent

1834 2245 

1835**Tool name:** `Agent` (previously `Task`, which is still accepted as an alias)2246**Tool name:** `Agent`. The previous name `Task` is still accepted as an alias, and the `tools` array in the [`SDKSystemMessage`](#sdksystemmessage) init message currently lists this tool as `Task` for backward compatibility.

1836 2247 

1837<Note>2248<Note>

1838 {/* min-version: 2.1.212 */}The `mode` field is deprecated and ignored on Claude Code v2.1.212 or later: subagents [inherit the parent session's permission mode](/docs/en/agent-sdk/permissions#available-modes), and a subagent definition's [`permissionMode`](#agentdefinition) can override it, except when the parent uses `bypassPermissions`, `acceptEdits`, or `auto`.2249 {/* min-version: 2.1.212 */}The `mode` field is deprecated and ignored on Claude Code v2.1.212 or later: subagents [inherit the parent session's permission mode](/docs/en/agent-sdk/permissions#available-modes), and a subagent definition's [`permissionMode`](#agentdefinition) can override it, except when the parent uses `bypassPermissions`, `acceptEdits`, or `auto`.


1846 model?: "sonnet" | "opus" | "haiku" | "fable";2257 model?: "sonnet" | "opus" | "haiku" | "fable";

1847 run_in_background?: boolean;2258 run_in_background?: boolean;

1848 name?: string;2259 name?: string;

1849 mode?: "acceptEdits" | "auto" | "bypassPermissions" | "default" | "dontAsk" | "plan";2260 team_name?: string; // Deprecated; ignored

2261 mode?: "acceptEdits" | "auto" | "bypassPermissions" | "default" | "dontAsk" | "plan"; // Deprecated; ignored. Subagents inherit the parent session's permission mode; agent-definition frontmatter may override it

1850 isolation?: "worktree" | "remote";2262 isolation?: "worktree" | "remote";

1851};2263};

1852```2264```


1865 options: Array<{ label: string; description: string; preview?: string }>;2277 options: Array<{ label: string; description: string; preview?: string }>;

1866 multiSelect: boolean;2278 multiSelect: boolean;

1867 }>;2279 }>;

2280 answers?: Record<string, string>;

2281 annotations?: Record<string, { preview?: string; notes?: string }>;

2282 metadata?: { source?: string };

1868};2283};

1869```2284```

1870 2285 


1898 protocols?: string[];2313 protocols?: string[];

1899 };2314 };

1900 description: string;2315 description: string;

1901 timeout_ms?: number;2316 timeout_ms: number;

1902 persistent?: boolean;2317 persistent: boolean;

1903};2318};

1904```2319```

1905 2320 

1906Runs a background source and delivers each event to Claude so it can react without polling: `command` runs a script and emits one event per stdout line, and `ws` opens a WebSocket and emits one event per text frame. Provide exactly one of `command` or `ws`. {/* min-version: 2.1.195 */}The `ws` source requires Claude Code v2.1.195 or later.2321Runs a background source and delivers each event to Claude so it can react without polling: `command` runs a script and emits one event per stdout line, and `ws` opens a WebSocket and emits one event per text frame. Provide exactly one of `command` or `ws`. {/* min-version: 2.1.195 */}The `ws` source requires Claude Code v2.1.195 or later.

1907 2322 

1908Set `persistent: true` for session-length watches such as log tails. When Monitor runs a command, it follows the same permission rules as Bash; a WebSocket watch prompts for approval separately. See the [Monitor tool reference](/docs/en/tools-reference#monitor-tool) for behavior and provider availability.2323Set `persistent: true` for session-length watches such as log tails. When Monitor runs a command, it follows the same permission rules as Bash; a WebSocket watch prompts for approval separately. See the [Monitor tool reference](/docs/en/tools-reference#monitor-tool) for behavior and provider availability. The exported type marks `timeout_ms` and `persistent` as required because the schema fills in their defaults, 300000 and `false`; a call that omits them validates.

1909 2324 

1910### TaskOutput2325### TaskOutput

1911 2326 

1912**Tool name:** `TaskOutput`2327**Tool name:** `TaskOutput`

1913 2328 

2329<Note>`TaskOutput` is deprecated; prefer `Read` on the task's output file path. {/* min-version: 2.1.83 */}Deprecated since Claude Code v2.1.83. The schemas below remain valid for hooks and permission handlers that encounter the tool.</Note>

2330 

1914```typescript theme={null}2331```typescript theme={null}

1915type TaskOutputInput = {2332type TaskOutputInput = {

1916 task_id: string;2333 task_id: string;


1989 type?: string;2406 type?: string;

1990 output_mode?: "content" | "files_with_matches" | "count";2407 output_mode?: "content" | "files_with_matches" | "count";

1991 "-i"?: boolean;2408 "-i"?: boolean;

2409 "-o"?: boolean; // print only the matched parts of each line; requires output_mode: "content"

1992 "-n"?: boolean;2410 "-n"?: boolean;

1993 "-B"?: number;2411 "-B"?: number;

1994 "-A"?: number;2412 "-A"?: number;


2067 script?: string;2485 script?: string;

2068 name?: string;2486 name?: string;

2069 scriptPath?: string;2487 scriptPath?: string;

2070 args?: unknown;2488 args?: unknown; // any JSON value; the published typings render this as an object map

2071 resumeFromRunId?: string;2489 resumeFromRunId?: string;

2490 title?: string; // ignored; the script's meta block sets the title

2491 description?: string; // ignored; the script's meta block sets the description

2072};2492};

2073```2493```

2074 2494 


2081| `scriptPath` | `string` | Path to a workflow script file on disk. Takes precedence over `script` and `name`. Every invocation persists its script and returns the path in the result, so you can edit that file and re-invoke with the same `scriptPath` to iterate |2501| `scriptPath` | `string` | Path to a workflow script file on disk. Takes precedence over `script` and `name`. Every invocation persists its script and returns the path in the result, so you can edit that file and re-invoke with the same `scriptPath` to iterate |

2082| `args` | `unknown` | Input value exposed to the script as the global `args`, for parameterized named workflows such as a research question or a list of file paths. Pass arrays and objects as actual JSON values, not as a JSON-encoded string |2502| `args` | `unknown` | Input value exposed to the script as the global `args`, for parameterized named workflows such as a research question or a list of file paths. Pass arrays and objects as actual JSON values, not as a JSON-encoded string |

2083| `resumeFromRunId` | `string` | Run ID of a prior `Workflow` invocation to resume. Completed `agent()` calls with unchanged inputs return cached results; only changed or new calls run live. Same session only |2503| `resumeFromRunId` | `string` | Run ID of a prior `Workflow` invocation to resume. Completed `agent()` calls with unchanged inputs return cached results; only changed or new calls run live. Same session only |

2504| `title` | `string` | Ignored; the script's `meta` block sets the title |

2505| `description` | `string` | Ignored; the script's `meta` block sets the description |

2506 

2507The schema accepts any JSON value for `args`; the exported type marks it `unknown`, but the published typings render the field as an object map.

2084 2508 

2085### TodoWrite2509### TodoWrite

2086 2510 


2170 tool: "Bash";2594 tool: "Bash";

2171 prompt: string;2595 prompt: string;

2172 }>;2596 }>;

2597 [k: string]: unknown;

2173};2598};

2174```2599```

2175 2600 


2213 2638 

2214Creates and enters a temporary git worktree for isolated work. Pass `path` to switch into an existing worktree instead of creating a new one. On first entry the target must be a registered worktree of the current repository or, in a multi-repo workspace, of a repository nested inside it; from within a worktree session it must be under `.claude/worktrees/` of the session's repository. `name` and `path` are mutually exclusive.2639Creates and enters a temporary git worktree for isolated work. Pass `path` to switch into an existing worktree instead of creating a new one. On first entry the target must be a registered worktree of the current repository or, in a multi-repo workspace, of a repository nested inside it; from within a worktree session it must be under `.claude/worktrees/` of the session's repository. `name` and `path` are mutually exclusive.

2215 2640 

2641### ExitWorktree

2642 

2643**Tool name:** `ExitWorktree`

2644 

2645```typescript theme={null}

2646type ExitWorktreeInput = {

2647 action: "keep" | "remove";

2648 discard_changes?: boolean;

2649};

2650```

2651 

2652Exits the current git worktree and returns to the original working directory. The `keep` action leaves the worktree and branch on disk, while `remove` deletes both. `discard_changes` must be `true` when removing a worktree that has uncommitted files or unmerged commits.

2653 

2654### EnterPlanMode

2655 

2656**Tool name:** `EnterPlanMode`

2657 

2658```typescript theme={null}

2659type EnterPlanModeInput = {};

2660```

2661 

2662Enters plan mode, where Claude researches and presents a plan before making changes.

2663 

2664### CronCreate

2665 

2666**Tool name:** `CronCreate`

2667 

2668```typescript theme={null}

2669type CronCreateInput = {

2670 cron: string;

2671 prompt: string;

2672 recurring?: boolean;

2673 durable?: boolean;

2674};

2675```

2676 

2677Schedules a prompt to run on a 5-field cron schedule in local time. Set `recurring` to `false` to fire once at the next match. Jobs are session-scoped by default: starting a fresh conversation clears them, and resuming with `--resume` or `--continue` restores jobs that haven't expired. See [Scheduled tasks](/docs/en/scheduled-tasks).

2678 

2679Setting `durable` to `true` requests persistence to `.claude/scheduled_tasks.json` so the job survives restarts. Durable scheduling isn't available in every session: when it isn't, Claude Code accepts `durable: true` but creates the job session-only. Read the output's `durable` field to see whether the job persisted.

2680 

2681### CronDelete

2682 

2683**Tool name:** `CronDelete`

2684 

2685```typescript theme={null}

2686type CronDeleteInput = {

2687 id: string;

2688};

2689```

2690 

2691Deletes a scheduled cron job by the ID returned from `CronCreate`.

2692 

2693### CronList

2694 

2695**Tool name:** `CronList`

2696 

2697```typescript theme={null}

2698type CronListInput = {};

2699```

2700 

2701Lists the scheduled cron jobs: durable jobs from `.claude/scheduled_tasks.json` and session-only jobs from the current session.

2702 

2703### ScheduleWakeup

2704 

2705**Tool name:** `ScheduleWakeup`

2706 

2707```typescript theme={null}

2708type ScheduleWakeupInput = {

2709 delaySeconds?: number;

2710 reason?: string;

2711 prompt?: string;

2712 stop?: boolean;

2713};

2714```

2715 

2716Schedules a one-shot wake-up that fires the given prompt after a delay. This tool backs the self-paced `/loop` command. The runtime clamps `delaySeconds` to between 60 and 3600 seconds. The `delaySeconds`, `reason`, and `prompt` fields are required unless `stop` is true. {/* min-version: 2.1.202 */}Setting `stop: true` cancels the pending wakeup and ends the self-paced `/loop`. The `stop` field requires Claude Code v2.1.202 or later. See the [ScheduleWakeup row in the tools reference](/docs/en/tools-reference) for provider availability; it isn't available on Amazon Bedrock, Claude Platform on AWS, Google Cloud's Agent Platform, or Microsoft Foundry.

2717 

2718### RemoteTrigger

2719 

2720**Tool name:** `RemoteTrigger`

2721 

2722```typescript theme={null}

2723type RemoteTriggerInput = {

2724 action: "list" | "get" | "create" | "update" | "run";

2725 trigger_id?: string;

2726 body?: {

2727 [k: string]: unknown;

2728 };

2729};

2730```

2731 

2732Manages [Routines](/docs/en/routines), the scheduled and triggered Claude Code runs hosted on Anthropic-managed cloud infrastructure. This tool backs the `/schedule` command. `trigger_id` is required for the `get`, `update`, and `run` actions. `body` is required for `create` and `update`, and optional for `run`.

2733 

2734This tool is available only when the session is authenticated with a claude.ai account on a plan with Routines enabled.

2735 

2736### PushNotification

2737 

2738**Tool name:** `PushNotification`

2739 

2740```typescript theme={null}

2741type PushNotificationInput = {

2742 message: string;

2743 status: "proactive";

2744};

2745```

2746 

2747Sends a proactive push notification to the user. Keep `message` under 200 characters because mobile operating systems truncate longer text. See the [PushNotification row in the tools reference](/docs/en/tools-reference) for provider availability; push delivery runs through Anthropic-hosted infrastructure that isn't accessible from Amazon Bedrock, Claude Platform on AWS, Google Cloud's Agent Platform, or Microsoft Foundry.

2748 

2749### REPL

2750 

2751**Tool name:** `REPL`

2752 

2753```typescript theme={null}

2754type REPLInput = {

2755 code: string;

2756 description?: string;

2757 timeout?: number;

2758};

2759```

2760 

2761Executes JavaScript code in a persistent REPL. State persists across calls and top-level await is supported. `timeout` is in milliseconds, with a default of 30000 and a maximum of 600000.

2762 

2763The types are exported, but the tool is off in SDK sessions unless you set `CLAUDE_CODE_REPL=1` in the [`env` option](#options). It also requires the Bun-based `claude` executable that the native installer provides.

2764 

2765### ReportFindings

2766 

2767**Tool name:** `ReportFindings`

2768 

2769```typescript theme={null}

2770type ReportFindingsInput = {

2771 level?: "low" | "medium" | "high" | "xhigh" | "max";

2772 findings: Array<{

2773 file: string;

2774 line?: number;

2775 summary: string;

2776 failure_scenario: string;

2777 short_summary?: string;

2778 category?: string;

2779 verdict?: "CONFIRMED" | "PLAUSIBLE";

2780 outcome?: "fixed" | "skipped" | "no_change_needed";

2781 }>;

2782};

2783```

2784 

2785Reports code-review findings as a structured list so Claude Code can render them instead of printing them as text. `level` is the effort level the review ran at. Findings are ordered most-severe first, with at most 32 per call, and the array is empty when none survived. Requires Claude Code v2.1.196 or later.

2786 

2787Each finding carries these fields:

2788 

2789* `file`: repo-relative path the finding is in. The optional `line` is the 1-indexed line it anchors to.

2790* `summary`: one-sentence statement of the defect. `failure_scenario` describes the concrete inputs and state that lead to the wrong output or crash.

2791* `short_summary`: optional compressed label of at most 60 characters for compact display. {/* min-version: 2.1.212 */}Requires Claude Code v2.1.212 or later.

2792* `category`: optional short kebab-case slug of the finding type, such as `correctness` or `test-coverage`. {/* min-version: 2.1.199 */}Requires Claude Code v2.1.199 or later.

2793* `verdict`: set when a verify pass ran; absent on inline-only reviews.

2794* `outcome`: set only when re-reporting after applying fixes.

2795 

2796### Artifact

2797 

2798**Tool name:** `Artifact`

2799 

2800```typescript theme={null}

2801type ArtifactInput = {

2802 action?: "publish" | "list";

2803 file_path?: string;

2804 favicon?: string;

2805 limit?: number;

2806 scope?: "mine" | "shared" | "all";

2807 title?: string;

2808 description?: string;

2809 label?: string;

2810 url?: string;

2811 force?: boolean;

2812};

2813```

2814 

2815Publishes a local `.html` or `.md` file as a hosted artifact page, or lists the user's published artifacts. Omit `action` or pass `"publish"` to publish `file_path`, which is required for the publish action along with `favicon`, one or two emoji for the browser tab. `title` names the published page in the browser tab and gallery when the HTML file has no `<title>` tag. `url` targets an existing artifact to update in place instead of minting a new one, and `force` is a last-resort overwrite that discards another session's published version; on a 409 conflict the normal fix is to re-read, merge, and publish again rather than pass `force`.

2816 

2817Pass `"list"` to enumerate the user's published artifacts; only `limit` and `scope` may accompany it. `scope` defaults to `"mine"`, which lists artifacts the user owns; `"shared"` lists artifacts other people shared with the user, and `"all"` lists both.

2818 

2819The types are exported, but the tool is off by default in Agent SDK sessions. Publishing also requires every condition in the [artifacts availability table](/docs/en/artifacts#availability), which sessions authenticated with an API key don't meet.

2820 

2821### Projects

2822 

2823**Tool name:** `Projects`

2824 

2825```typescript theme={null}

2826type ProjectsInput = {

2827 method:

2828 | "project_info"

2829 | "project_read"

2830 | "project_search"

2831 | "project_write"

2832 | "project_delete";

2833 path?: string;

2834 content?: string;

2835 local_path?: string;

2836 present_to_user?: boolean;

2837 query?: string;

2838 n?: number;

2839};

2840```

2841 

2842Reads and writes the claude.ai Project attached to the session. Dispatches on `method`:

2843 

2844* `project_info`: returns project metadata and the doc list.

2845* `project_read`: reads one doc by `path`.

2846* `project_search`: queries the project's knowledge base with `query`. `n` caps the hits and defaults to 5.

2847* `project_write`: creates or replaces a doc at `path` from exactly one of `content`, which carries inline text, or `local_path`, which names a file inside the working directory. `present_to_user: true` marks the written doc as the deliverable the user needs to see.

2848* `project_delete`: deletes a doc by `path`.

2849 

2850### ReadMcpResourceDir

2851 

2852**Tool name:** `ReadMcpResourceDirTool`

2853 

2854```typescript theme={null}

2855type ReadMcpResourceDirInput = {

2856 server: string;

2857 uri: string;

2858};

2859```

2860 

2861Lists the direct children of a directory resource on an MCP server. Only usable against a server that has declared support for directory listing; the listing isn't recursive. Directory listing isn't enabled in every session: when it's off, the call returns an empty `resources` list and the `error` field reports that directory listing isn't enabled.

2862 

2863### RefreshMcpTools

2864 

2865**Tool name:** `RefreshMcpTools`

2866 

2867```typescript theme={null}

2868type RefreshMcpToolsInput = {

2869 server?: string; // refresh only this server; omit to refresh all connected servers

2870};

2871```

2872 

2873Re-queries the tool list of connected MCP servers and applies any changes. The types are exported, but Claude Code registers the tool only when you set `CLAUDE_CODE_ENABLE_REFRESH_MCP_TOOLS=1` in the [`env` option](#options), and only in sessions with at least one MCP server. {/* min-version: 2.1.211 */}Requires Claude Code v2.1.211 or later.

2874 

2875### ShowOnboardingRolePicker

2876 

2877**Tool name:** `ShowOnboardingRolePicker`

2878 

2879```typescript theme={null}

2880type ShowOnboardingRolePickerInput = {};

2881```

2882 

2883Renders a clickable role-picker chip row during Cowork onboarding so the user can pick their role and get a matching plugin installed. Takes no arguments; the role list is defined by the client. The call blocks until the user responds.

2884 

2885### McpInput

2886 

2887**Tool name:** dynamic MCP tool names of the form `mcp__<server>__<tool>`

2888 

2889```typescript theme={null}

2890type McpInput = {

2891 [k: string]: unknown;

2892};

2893```

2894 

2895MCP tool arguments are an open object: each server defines its own parameters, so the type places no constraints on field names or values. Consult the server's own tool schema for the fields a specific tool accepts.

2896 

2216## Tool Output Types2897## Tool Output Types

2217 2898 

2218Documentation of output schemas for all built-in Claude Code tools. These types are exported from `@anthropic-ai/claude-agent-sdk` and represent the actual response data returned by each tool.2899Documentation of output schemas for all built-in Claude Code tools. These types are exported from `@anthropic-ai/claude-agent-sdk` and represent the actual response data returned by each tool.

2219 2900 

2220### `ToolOutputSchemas`2901### `ToolOutputSchemas`

2221 2902 

2222Union of all tool output types.2903Union of tool output types exported from `@anthropic-ai/claude-agent-sdk`; members include:

2223 2904 

2224```typescript theme={null}2905```typescript theme={null}

2225type ToolOutputSchemas =2906type ToolOutputSchemas =

2226 | AgentOutput2907 | AgentOutput

2908 | ArtifactOutput

2227 | AskUserQuestionOutput2909 | AskUserQuestionOutput

2228 | BashOutput2910 | BashOutput

2911 | CronCreateOutput

2912 | CronDeleteOutput

2913 | CronListOutput

2914 | EnterPlanModeOutput

2229 | EnterWorktreeOutput2915 | EnterWorktreeOutput

2230 | ExitPlanModeOutput2916 | ExitPlanModeOutput

2917 | ExitWorktreeOutput

2231 | FileEditOutput2918 | FileEditOutput

2232 | FileReadOutput2919 | FileReadOutput

2233 | FileWriteOutput2920 | FileWriteOutput

2234 | GlobOutput2921 | GlobOutput

2235 | GrepOutput2922 | GrepOutput

2236 | ListMcpResourcesOutput2923 | ListMcpResourcesOutput

2924 | McpOutput

2237 | MonitorOutput2925 | MonitorOutput

2238 | NotebookEditOutput2926 | NotebookEditOutput

2927 | ProjectsOutput

2928 | PushNotificationOutput

2929 | ReadMcpResourceDirOutput

2239 | ReadMcpResourceOutput2930 | ReadMcpResourceOutput

2931 | RefreshMcpToolsOutput

2932 | RemoteTriggerOutput

2933 | REPLOutput

2934 | ReportFindingsOutput

2935 | ScheduleWakeupOutput

2936 | ShowOnboardingRolePickerOutput

2240 | TaskCreateOutput2937 | TaskCreateOutput

2241 | TaskGetOutput2938 | TaskGetOutput

2242 | TaskListOutput2939 | TaskListOutput


2250 2947 

2251### Agent2948### Agent

2252 2949 

2253**Tool name:** `Agent` (previously `Task`, which is still accepted as an alias)2950**Tool name:** `Agent`. The previous name `Task` is still accepted as an alias, and the `tools` array in the [`SDKSystemMessage`](#sdksystemmessage) init message currently lists this tool as `Task` for backward compatibility.

2254 2951 

2255```typescript theme={null}2952```typescript theme={null}

2256type AgentOutput =2953type AgentOutput =


2319 3016 

2320Returns the result from the subagent. Discriminated on the `status` field: `"completed"` for finished tasks, `"async_launched"` for background tasks, and `"remote_launched"` for tasks Claude Code dispatched to a remote cloud session, where `sessionUrl` links to that session and `taskId` identifies it.3017Returns the result from the subagent. Discriminated on the `status` field: `"completed"` for finished tasks, `"async_launched"` for background tasks, and `"remote_launched"` for tasks Claude Code dispatched to a remote cloud session, where `sessionUrl` links to that session and `taskId` identifies it.

2321 3018 

2322The `resolvedModel` field on the `completed` and `async_launched` variants names the model the subagent actually ran on, which can differ from the requested `model` input when [`availableModels`](/docs/en/model-config#restrict-model-selection) or another override applies. {/* min-version: 2.1.174 */}This field requires Claude Code v2.1.174 or later. {/* min-version: 2.1.212 */}On `async_launched`, it names the model in use when the task moved to the background.3019On the `completed` variant, `resolvedModel` names the model the subagent started on, which can differ from the requested `model` input when [`availableModels`](/docs/en/model-config#restrict-model-selection) or another override applies. {/* min-version: 2.1.174 */}This field requires Claude Code v2.1.174 or later. {/* min-version: 2.1.212 */}On `async_launched`, it names the model in use when the task moved to the background.

2323 3020 

2324`modelsUsed` lists the models the subagent used, in order. The field is present only when a mid-run swap happened, and a model appears again when the run swapped back to it. On `async_launched`, the list covers the models used before backgrounding. {/* min-version: 2.1.212 */}Both `modelsUsed` and the backgrounding behavior of `resolvedModel` require Claude Code v2.1.212 or later.3021`modelsUsed` lists the models the subagent used, in order. The field is present only when a mid-run swap happened, and a model appears again when the run swapped back to it. On `async_launched`, the list covers the models used before backgrounding. {/* min-version: 2.1.212 */}Both `modelsUsed` and the backgrounding behavior of `resolvedModel` require Claude Code v2.1.212 or later.

2325 3022 


2341 }>;3038 }>;

2342 answers: Record<string, string>;3039 answers: Record<string, string>;

2343 response?: string;3040 response?: string;

3041 annotations?: Record<string, { preview?: string; notes?: string }>;

3042 afkTimeoutMs?: number;

2344};3043};

2345```3044```

2346 3045 


2363 backgroundCwdHint?: string;3062 backgroundCwdHint?: string;

2364 dangerouslyDisableSandbox?: boolean;3063 dangerouslyDisableSandbox?: boolean;

2365 returnCodeInterpretation?: string;3064 returnCodeInterpretation?: string;

3065 noOutputExpected?: boolean;

2366 structuredContent?: unknown[];3066 structuredContent?: unknown[];

2367 persistedOutputPath?: string;3067 persistedOutputPath?: string;

2368 persistedOutputSize?: number;3068 persistedOutputSize?: number;

3069 staleReadFileStateHint?: string;

3070 ghRateLimitHint?: string;

3071 gitOperation?: {

3072 commit?: { sha: string; kind: "committed" | "amended" | "cherry-picked" };

3073 push?: { branch: string };

3074 branch?: { ref: string; action: "merged" | "rebased" };

3075 pr?: {

3076 number: number;

3077 url?: string;

3078 action: "created" | "edited" | "merged" | "commented" | "closed" | "ready" | "draft" | "auto-merge-enabled" | "auto-merge-disabled";

3079 };

3080 };

2369};3081};

2370```3082```

2371 3083 


2396 filePath: string;3108 filePath: string;

2397 oldString: string;3109 oldString: string;

2398 newString: string;3110 newString: string;

2399 originalFile: string;3111 originalFile: string | null;

2400 structuredPatch: Array<{3112 structuredPatch: Array<{

2401 oldStart: number;3113 oldStart: number;

2402 oldLines: number;3114 oldLines: number;


2413 deletions: number;3125 deletions: number;

2414 changes: number;3126 changes: number;

2415 patch: string;3127 patch: string;

3128 repository?: string | null;

2416 };3129 };

2417};3130};

2418```3131```


2433 numLines: number;3146 numLines: number;

2434 startLine: number;3147 startLine: number;

2435 totalLines: number;3148 totalLines: number;

3149 /** True when a whole-file read was auto-paginated because it exceeded the token cap (the content is a partial first page). */

3150 truncatedByTokenCap?: boolean;

2436 };3151 };

2437 }3152 }

2438 | {3153 | {


2472 count: number;3187 count: number;

2473 outputDir: string;3188 outputDir: string;

2474 };3189 };

3190 }

3191 | {

3192 type: "file_unchanged";

3193 file: {

3194 filePath: string;

3195 };

3196 /** Set when the dedup matched a startup-seeded entry (CLAUDE.md / nested memory) rather than a prior Read tool_result. */

3197 source?: "seeded";

2475 };3198 };

2476```3199```

2477 3200 


2501 deletions: number;3224 deletions: number;

2502 changes: number;3225 changes: number;

2503 patch: string;3226 patch: string;

3227 repository?: string | null;

2504 };3228 };

3229 userModified?: boolean;

2505};3230};

2506```3231```

2507 3232 


2571```typescript theme={null}3296```typescript theme={null}

2572type NotebookEditOutput = {3297type NotebookEditOutput = {

2573 new_source: string;3298 new_source: string;

3299 old_source?: string;

2574 cell_id?: string;3300 cell_id?: string;

2575 cell_type: "code" | "markdown";3301 cell_type: "code" | "markdown";

2576 language: string;3302 language: string;


2596 result: string;3322 result: string;

2597 durationMs: number;3323 durationMs: number;

2598 url: string;3324 url: string;

3325 artifactRead?: {

3326 slug: string;

3327 ver?: string;

3328 };

2599};3329};

2600```3330```

2601 3331 


2616 | string3346 | string

2617 >;3347 >;

2618 durationSeconds: number;3348 durationSeconds: number;

3349 searchCount?: number;

2619};3350};

2620```3351```

2621 3352 


2627 3358 

2628```typescript theme={null}3359```typescript theme={null}

2629type WorkflowOutput = {3360type WorkflowOutput = {

2630 status: "async_launched";3361 status: "async_launched" | "remote_launched";

2631 taskId: string;3362 taskId: string;

3363 taskType?: "local_workflow" | "remote_agent";

3364 workflowName?: string;

2632 runId?: string;3365 runId?: string;

2633 summary?: string;3366 summary?: string;

2634 transcriptDir?: string;3367 transcriptDir?: string;

2635 scriptPath?: string;3368 scriptPath?: string;

3369 sessionUrl?: string; // set when the workflow launched as a remote session

3370 warning?: string;

2636 error?: string;3371 error?: string;

2637};3372};

2638```3373```


2640Returns immediately after the tool accepts the invocation. The final result arrives later as a task completion. Check `error` before treating the run as started: a script that fails its syntax check returns `status: "async_launched"` with `error` set, and never runs.3375Returns immediately after the tool accepts the invocation. The final result arrives later as a task completion. Check `error` before treating the run as started: a script that fails its syntax check returns `status: "async_launched"` with `error` set, and never runs.

2641 3376 

2642| Field | Type | Description |3377| Field | Type | Description |

2643| --------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------- |3378| --------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

2644| `status` | `"async_launched"` | The tool accepted the invocation. This is the only value the field takes |3379| `status` | `"async_launched" \| "remote_launched"` | The tool accepted the invocation. `"async_launched"` for in-process runs, `"remote_launched"` for runs dispatched to a remote session instead of running in-process |

2645| `taskId` | `string` | Background task identifier for the run |3380| `taskId` | `string` | Background task identifier for the run |

2646| `runId` | `string` | Workflow run identifier to pass as `resumeFromRunId` on a later invocation |3381| `taskType` | `"local_workflow" \| "remote_agent"` | Task type of the registered background task, matching the `status` arm |

3382| `workflowName` | `string` | The `meta.name` from the workflow script |

3383| `runId` | `string` | Workflow run identifier to pass as `resumeFromRunId` on a later invocation. Absent for `remote_launched` runs, where the cloud session URL is the resume handle |

2647| `summary` | `string` | One-line description of what the workflow does |3384| `summary` | `string` | One-line description of what the workflow does |

2648| `transcriptDir` | `string` | Directory where subagent transcripts are written during execution |3385| `transcriptDir` | `string` | Directory where subagent transcripts are written during execution |

2649| `scriptPath` | `string` | Path to the persisted workflow script for this run. Edit it and pass back as `scriptPath` to rerun without resending the script |3386| `scriptPath` | `string` | Path to the persisted workflow script for this run. Edit it and pass back as `scriptPath` to rerun without resending the script |

2650| `error` | `string` | Set when the script fails its syntax check. When present, the run did not start despite the `async_launched` status |3387| `sessionUrl` | `string` | Cloud session URL, set when `status` is `"remote_launched"` |

3388| `warning` | `string` | Non-blocking heads-up, such as local git state diverging from the pushed branch a cloud session will clone |

3389| `error` | `string` | Set when the script fails its syntax check. When present, the run did not start despite the launched status |

2651 3390 

2652### TodoWrite3391### TodoWrite

2653 3392 


2755 isAgent: boolean;3494 isAgent: boolean;

2756 filePath?: string;3495 filePath?: string;

2757 hasTaskTool?: boolean;3496 hasTaskTool?: boolean;

3497 planWasEdited?: boolean;

2758 awaitingLeaderApproval?: boolean;3498 awaitingLeaderApproval?: boolean;

2759 requestId?: string;3499 requestId?: string;

2760};3500};


2788 uri: string;3528 uri: string;

2789 mimeType?: string;3529 mimeType?: string;

2790 text?: string;3530 text?: string;

3531 blobSavedTo?: string;

2791 }>;3532 }>;

3533 error?: string;

2792};3534};

2793```3535```

2794 3536 


2808 3550 

2809Returns information about the git worktree.3551Returns information about the git worktree.

2810 3552 

3553### ExitWorktree

3554 

3555**Tool name:** `ExitWorktree`

3556 

3557```typescript theme={null}

3558type ExitWorktreeOutput = {

3559 action: "keep" | "remove";

3560 originalCwd: string;

3561 worktreePath: string;

3562 worktreeBranch?: string;

3563 tmuxSessionName?: string;

3564 discardedFiles?: number;

3565 discardedCommits?: number;

3566 message: string;

3567};

3568```

3569 

3570Returns the action taken and details about the worktree that was exited.

3571 

3572### EnterPlanMode

3573 

3574**Tool name:** `EnterPlanMode`

3575 

3576```typescript theme={null}

3577type EnterPlanModeOutput = {

3578 message: string;

3579};

3580```

3581 

3582Returns a confirmation that plan mode was entered.

3583 

3584### CronCreate

3585 

3586**Tool name:** `CronCreate`

3587 

3588```typescript theme={null}

3589type CronCreateOutput = {

3590 id: string;

3591 humanSchedule: string;

3592 recurring: boolean;

3593 durable?: boolean; // true when persisted to .claude/scheduled_tasks.json; false when session-only

3594};

3595```

3596 

3597Returns the job ID and a human-readable description of the schedule.

3598 

3599### CronDelete

3600 

3601**Tool name:** `CronDelete`

3602 

3603```typescript theme={null}

3604type CronDeleteOutput = {

3605 id: string;

3606};

3607```

3608 

3609Returns the ID of the deleted job.

3610 

3611### CronList

3612 

3613**Tool name:** `CronList`

3614 

3615```typescript theme={null}

3616type CronListOutput = {

3617 jobs: {

3618 id: string;

3619 cron: string;

3620 humanSchedule: string;

3621 prompt: string;

3622 recurring?: boolean;

3623 durable?: boolean;

3624 }[];

3625};

3626```

3627 

3628Returns the scheduled cron jobs: durable jobs from `.claude/scheduled_tasks.json` and session-only jobs from the current session. A session-only job carries `durable: false`; jobs read from disk omit the field.

3629 

3630### ScheduleWakeup

3631 

3632**Tool name:** `ScheduleWakeup`

3633 

3634```typescript theme={null}

3635type ScheduleWakeupOutput = {

3636 scheduledFor: number;

3637 clampedDelaySeconds: number;

3638 wasClamped: boolean;

3639 stopped?: boolean;

3640 cancelledWakeups?: number;

3641};

3642```

3643 

3644Returns when the wake-up will fire as an epoch millisecond timestamp, the delay actually used, and whether the requested delay was clamped. {/* min-version: 2.1.202 */}The `stopped` field is `true` when the call ended the loop with `stop: true`. It requires Claude Code v2.1.202 or later. {/* min-version: 2.1.206 */}The `cancelledWakeups` field counts how many pending wakeups a `stop: true` call cancelled. A value of 0 means nothing was pending, and a recurring `/loop` cron isn't cancelled by `stop: true`. It requires Claude Code v2.1.206 or later.

3645 

3646### RemoteTrigger

3647 

3648**Tool name:** `RemoteTrigger`

3649 

3650```typescript theme={null}

3651type RemoteTriggerOutput = {

3652 status: number;

3653 json: string;

3654 summary?: string;

3655};

3656```

3657 

3658Returns the API response status and body for the trigger operation.

3659 

3660### PushNotification

3661 

3662**Tool name:** `PushNotification`

3663 

3664```typescript theme={null}

3665type PushNotificationOutput = {

3666 message: string;

3667 pushSent?: boolean;

3668 localSent?: boolean;

3669 disabledReason?: "config_off" | "user_present" | "no_transport";

3670 sentAt?: string;

3671};

3672```

3673 

3674Returns delivery details, including whether a push or local notification was sent and why delivery was skipped.

3675 

3676### REPL

3677 

3678**Tool name:** `REPL`

3679 

3680```typescript theme={null}

3681type REPLOutput = {

3682 code: string;

3683 result: {

3684 [k: string]: unknown;

3685 };

3686 stdout: string;

3687 stderr: string;

3688 error?: string;

3689 registeredTools?: string[];

3690 images?: {

3691 base64: string;

3692 mediaType: string;

3693 }[];

3694 documents?: {

3695 base64: string;

3696 }[];

3697};

3698```

3699 

3700Returns the execution result, captured console output, and any images or documents surfaced by inner `Read` calls.

3701 

3702### ReportFindings

3703 

3704**Tool name:** `ReportFindings`

3705 

3706```typescript theme={null}

3707type ReportFindingsOutput = {

3708 count: number;

3709 level?: "low" | "medium" | "high" | "xhigh" | "max";

3710 findings: Array<{

3711 file: string;

3712 line?: number;

3713 summary: string;

3714 failure_scenario: string;

3715 short_summary?: string;

3716 category?: string;

3717 verdict?: "CONFIRMED" | "PLAUSIBLE";

3718 outcome?: "fixed" | "skipped" | "no_change_needed";

3719 }>;

3720};

3721```

3722 

3723Returns the number of findings reported, the effort level the review ran at, and the findings echoed back for the result body. Requires Claude Code v2.1.196 or later. {/* min-version: 2.1.212 */}The echoed `short_summary` field requires Claude Code v2.1.212 or later.

3724 

3725### Artifact

3726 

3727**Tool name:** `Artifact`

3728 

3729```typescript theme={null}

3730type ArtifactOutput =

3731 | {

3732 url: string;

3733 path: string;

3734 title?: string;

3735 version?: string;

3736 capabilities?: unknown;

3737 stored?: {

3738 contract: string;

3739 capabilities?: Record<string, unknown>;

3740 };

3741 warnings?: string[];

3742 contract?: string;

3743 updated?: boolean;

3744 liveSubscription?: string;

3745 }

3746 | {

3747 artifacts: Array<{

3748 title: string;

3749 url: string;

3750 updatedAt?: string;

3751 rel?: "mine" | "shared";

3752 }>;

3753 truncated?: boolean;

3754 scope?: "shared" | "all";

3755 };

3756```

3757 

3758Returns the published page's `url` and the local `path` that was published for the publish action, with `updated` set to true when the publish redeployed an existing artifact, and `warnings` carrying any publish-time advisories. The list action returns the `artifacts` rows instead, with `truncated` set when more artifacts exist than the requested limit. On listings whose scope isn't `"mine"`, each row carries `rel` marking whether the user owns the artifact or it was shared with them, and the output's `scope` records which non-default scope produced the listing; both are absent on default listings.

3759 

3760### Projects

3761 

3762**Tool name:** `Projects`

3763 

3764```typescript theme={null}

3765type ProjectsOutput =

3766 | {

3767 method: "project_info";

3768 notice?: string;

3769 name: string;

3770 description: string;

3771 instructions: string;

3772 docs: Array<{ path: string; created_at: string | null }>;

3773 files?: Array<{

3774 path: string;

3775 file_kind: string;

3776 created_at: string | null;

3777 }>;

3778 sync_sources?: Array<{

3779 type: string | null;

3780 config: Record<string, unknown>;

3781 }>;

3782 knowledge: {

3783 knowledge_size: number;

3784 max_knowledge_size: number;

3785 };

3786 }

3787 | {

3788 method: "project_read";

3789 notice?: string;

3790 path: string;

3791 file_kind?: string;

3792 content?: string;

3793 local_file?: string;

3794 created_at: string | null;

3795 }

3796 | {

3797 method: "project_search";

3798 notice?: string;

3799 rag: boolean;

3800 hits?: Array<{ name?: string; doc_uuid?: string; text?: string }>;

3801 docs?: string[];

3802 }

3803 | {

3804 method: "project_write";

3805 notice?: string;

3806 path: string;

3807 doc_uuid: string;

3808 replaced: boolean;

3809 present_to_user?: boolean;

3810 local_path?: string;

3811 }

3812 | {

3813 method: "project_delete";

3814 notice?: string;

3815 path: string;

3816 deleted: boolean;

3817 };

3818```

3819 

3820Discriminated on the `method` field, mirroring the input. `project_read` returns small text docs inline in `content` and writes larger docs to a `local_file` path instead; `project_search` returns RAG `hits` with `rag: true` when the project's index is available and falls back to a `docs` path list otherwise.

3821 

3822### ReadMcpResourceDir

3823 

3824**Tool name:** `ReadMcpResourceDirTool`

3825 

3826```typescript theme={null}

3827type ReadMcpResourceDirOutput = {

3828 resources: Array<{

3829 uri: string;

3830 name: string;

3831 mimeType?: string;

3832 }>;

3833 error?: string;

3834};

3835```

3836 

3837Returns the direct children of the directory resource. Subdirectories appear with mimeType `"inode/directory"`; `error` carries a human-readable message when the server couldn't list the directory.

3838 

3839### RefreshMcpTools

3840 

3841**Tool name:** `RefreshMcpTools`

3842 

3843```typescript theme={null}

3844type RefreshMcpToolsOutput = Array<{

3845 server: string;

3846 status: "refreshed" | "error" | "not_connected";

3847 toolCount?: number; // tools now available from this server

3848 added?: string[]; // tool names this refresh added

3849 removed?: string[]; // tool names this refresh removed

3850 error?: string; // why the refresh failed or the server was unavailable

3851}>;

3852```

3853 

3854Returns one entry per server: `refreshed` means the re-queried tool list was applied, `error` means the re-query failed and the previous tool set was kept, and `not_connected` means the server has no live connection to query.

3855 

3856### ShowOnboardingRolePicker

3857 

3858**Tool name:** `ShowOnboardingRolePicker`

3859 

3860```typescript theme={null}

3861type ShowOnboardingRolePickerOutput = {

3862 role?: string;

3863 dismissed?: boolean;

3864};

3865```

3866 

3867Returns the user's selection: `role` when they picked a role chip or typed one, and `dismissed: true` when they closed the picker. An empty object means the user approved the call without picking a role.

3868 

3869### McpOutput

3870 

3871**Tool name:** dynamic MCP tool names of the form `mcp__<server>__<tool>`

3872 

3873```typescript theme={null}

3874type McpOutput =

3875 | string

3876 | {

3877 type: string;

3878 [k: string]: unknown;

3879 }[]

3880 | {

3881 [k: string]: unknown;

3882 };

3883```

3884 

3885MCP tool results are returned as a string or an array of content blocks, depending on the server. The trailing plain-object branch in the exported type is a schema-generation artifact: the SDK doesn't return a bare object, because a server's structured output is serialized to a JSON string before being returned. At runtime the value may also be `undefined`, although the exported type doesn't model this.

3886 

2811## Permission Types3887## Permission Types

2812 3888 

2813### `PermissionUpdate`3889### `PermissionUpdate`


2885type ApiKeySource = "user" | "project" | "org" | "temporary" | "oauth";3961type ApiKeySource = "user" | "project" | "org" | "temporary" | "oauth";

2886```3962```

2887 3963 

3964<Note>

3965 At runtime, the `apiKeySource` field on the [`SDKSystemMessage`](#sdksystemmessage) init message can also be the string `"none"` when no API key is in use, for example when the session authenticates with an OAuth token. Handle values outside this union defensively.

3966</Note>

3967 

2888### `SdkBeta`3968### `SdkBeta`

2889 3969 

2890Available beta features that can be enabled via the `betas` option. See [Beta headers](https://platform.claude.com/docs/en/api/beta-headers) for more information.3970Available beta features that can be enabled via the `betas` option. See [Beta headers](https://platform.claude.com/docs/en/api/beta-headers) for more information.


2894```3974```

2895 3975 

2896<Warning>3976<Warning>

2897 The `context-1m-2025-08-07` beta is retired as of April 30, 2026. Passing this value with Claude Sonnet 4.5 or Sonnet 4 has no effect, and requests that exceed the standard 200k-token context window return an error. To use a 1M-token context window, migrate to [Claude Sonnet 5, Claude Sonnet 4.6, Claude Opus 4.6, Claude Opus 4.7, or Claude Opus 4.8](https://platform.claude.com/docs/en/about-claude/models/overview), which include 1M context at standard pricing with no beta header required.3977 The `context-1m-2025-08-07` beta is retired as of April 30, 2026. Passing this value with Claude Sonnet 4.5 or Sonnet 4 has no effect, and requests that exceed the standard 200k-token context window return an error. To use a 1M-token context window, migrate to [Claude Opus 5, Claude Sonnet 5, Claude Sonnet 4.6, Claude Opus 4.6, Claude Opus 4.7, or Claude Opus 4.8](https://platform.claude.com/docs/en/about-claude/models/overview), which include 1M context at standard pricing with no beta header required.

2898</Warning>3978</Warning>

2899 3979 

2900### `SlashCommand`3980### `SlashCommand`


3028 costUSD: number;4108 costUSD: number;

3029 contextWindow: number;4109 contextWindow: number;

3030 maxOutputTokens: number;4110 maxOutputTokens: number;

4111 canonicalModel?: string;

4112 provider?: string;

3031};4113};

3032```4114```

3033 4115 

4116{/* min-version: 2.1.218 */}The `canonicalModel` and `provider` fields require Claude Code v2.1.218 or later. `canonicalModel` is the canonical model ID that the pricing lookup uses; it can differ from the raw model string that keys the entry, for example when that string is a provider-specific ID or an alias.

4117 

4118`provider` names the API backend that served the model, such as `firstParty`, `bedrock`, `vertex`, `foundry`, `anthropicAws`, `mantle`, or `gateway`.

4119 

3034### `ConfigScope`4120### `ConfigScope`

3035 4121 

3036```typescript theme={null}4122```typescript theme={null}


3099 | { type: "disabled" }; // No extended thinking4185 | { type: "disabled" }; // No extended thinking

3100```4186```

3101 4187 

3102The optional `display` field controls whether thinking text is returned `"summarized"` or `"omitted"`. On Claude Opus 4.7 and later, the API default is `"omitted"`, so set `"summarized"` to receive thinking content in `thinking` blocks.4188The optional `display` field controls whether thinking text is returned `"summarized"` or `"omitted"`. On Claude Opus 4.7 and later, the API default is `"omitted"`, so set `"summarized"` to receive thinking content in `thinking` blocks. Claude Code doesn't send `display` to Amazon Bedrock or Google Cloud's Agent Platform, so on those providers Opus 4.7 and later return empty `thinking` blocks even when you set `display` to `"summarized"`.

3103 4189 

3104### `SpawnedProcess`4190### `SpawnedProcess`

3105 4191 


3173 filesChanged?: string[];4259 filesChanged?: string[];

3174 insertions?: number;4260 insertions?: number;

3175 deletions?: number;4261 deletions?: number;

4262 skippedLinks?: number;

3176};4263};

3177```4264```

3178 4265 

4266{/* min-version: 2.1.216 */}`skippedLinks` counts the tracked paths the rewind refused to restore or delete for link safety: a symlink, hard link, or other non-regular file at the tracked path, a parent directory that no longer resolves to where it pointed when the checkpoint was taken, or a backup that couldn't be read safely. The field requires Claude Code v2.1.216 or later. A preview call with `rewindFiles(userMessageId, { dryRun: true })` never sets it.

4267 

3179### `SDKStatusMessage`4268### `SDKStatusMessage`

3180 4269 

3181Status update message (e.g., compacting).4270Status update message (e.g., compacting).


3298 parent_tool_use_id: string | null;4387 parent_tool_use_id: string | null;

3299 elapsed_time_seconds: number;4388 elapsed_time_seconds: number;

3300 task_id?: string;4389 task_id?: string;

4390 heartbeat?: boolean;

4391 subagent_type?: string;

4392 subagent_retry?: {

4393 agent_id: string;

4394 attempt: number;

4395 max_retries: number;

4396 retry_delay_ms: number;

4397 error_status: number | null;

4398 error_category: string;

4399 };

3301 uuid: UUID;4400 uuid: UUID;

3302 session_id: string;4401 session_id: string;

3303};4402};

3304```4403```

3305 4404 

4405While a tool call runs in the main conversation, Claude Code emits a `tool_progress` message every 30 seconds with `heartbeat: true`. Each heartbeat carries the tool name and elapsed seconds, so you can distinguish a long-running call from a stalled session. Claude Code doesn't emit heartbeats for the Agent tool, whose subagents stream their own progress, or for tool calls inside a subagent. The `heartbeat` field requires Agent SDK v0.3.214 or later.

4406 

4407On `tool_progress` messages for the Agent tool, `subagent_type` names the running subagent type, such as `general-purpose`. `subagent_retry` is present while that subagent waits out an API error backoff, such as a rate limit or overload, with one message per retry attempt. Both fields require Agent SDK v0.3.214 or later.

4408 

4409To render a retry indicator from `subagent_retry`:

4410 

4411* Track the indicator by `parent_tool_use_id`, which is unique per subagent. `tool_use_id` is shared by parallel subagents from one assistant turn, so tracking by it would let one subagent's update clear another's indicator.

4412* Clear the indicator when a later `tool_progress` for the same `parent_tool_use_id` arrives without the field, or when the tool's result message arrives. `attempt` can exceed `max_retries` under persistent retry, so don't derive clearing from the counters.

4413* Treat `error_category` as a closed set of tokens for choosing your own message text, not as display text: `rate_limit`, `overloaded`, `authentication_failed`, `server_error`, or `unknown`.

4414 

3306### `SDKAuthStatusMessage`4415### `SDKAuthStatusMessage`

3307 4416 

3308Emitted during authentication flows.4417Emitted during authentication flows.


3476 4585 

3477### `SDKCommandsChangedMessage`4586### `SDKCommandsChangedMessage`

3478 4587 

3479Emitted when the set of available commands changes mid-session, such as when skills are discovered as the agent enters a subdirectory. The `commands` array is the full updated list, so replace any cached command list with this payload. Calling `supportedCommands()` again is not equivalent: that method returns the snapshot captured at initialization and does not reflect mid-session changes.4588Emitted when the set of available commands changes mid-session, such as when Claude Code discovers skills as the agent enters a subdirectory. The `commands` array is the full updated list, so replace any cached command list with this payload. {/* min-version: agent-sdk@0.3.216 */}Calling [`supportedCommands()`](#query-object) after this message returns the same updated list, because the method tracks the latest push; this requires Agent SDK v0.3.216 or later. In earlier SDK versions, `supportedCommands()` returns the snapshot captured at initialization and never reflects mid-session changes.

3480 4589 

3481```typescript theme={null}4590```typescript theme={null}

3482type SDKCommandsChangedMessage = {4591type SDKCommandsChangedMessage = {


3603type SandboxNetworkConfig = {4712type SandboxNetworkConfig = {

3604 allowedDomains?: string[];4713 allowedDomains?: string[];

3605 deniedDomains?: string[];4714 deniedDomains?: string[];

4715 strictAllowlist?: boolean;

3606 allowManagedDomainsOnly?: boolean;4716 allowManagedDomainsOnly?: boolean;

3607 allowLocalBinding?: boolean;4717 allowLocalBinding?: boolean;

3608 allowUnixSockets?: string[];4718 allowUnixSockets?: string[];


3613```4723```

3614 4724 

3615| Property | Type | Default | Description |4725| Property | Type | Default | Description |

3616| :------------------------ | :--------- | :---------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |4726| :------------------------ | :--------- | :---------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

3617| `allowedDomains` | `string[]` | `[]` | Domain names that sandboxed processes can access |4727| `allowedDomains` | `string[]` | `[]` | Domain names that sandboxed processes can access |

3618| `deniedDomains` | `string[]` | `[]` | Domain names that sandboxed processes cannot access. Takes precedence over `allowedDomains` |4728| `deniedDomains` | `string[]` | `[]` | Domain names that sandboxed processes cannot access. Takes precedence over `allowedDomains` |

4729| `strictAllowlist` | `boolean` | `false` | {/* min-version: 2.1.219 */}Deny sandboxed commands access to hosts not in `allowedDomains` instead of prompting. Enforced for sandboxed commands only; in-process tools such as WebFetch aren't gated by it. Only honored from user, managed, or CLI `--settings` settings; project settings are ignored. Requires Claude Code v2.1.219 or later |

3619| `allowManagedDomainsOnly` | `boolean` | `false` | Managed-settings only. When set in [managed settings](/docs/en/permissions#managed-settings), only `allowedDomains` entries from managed settings are honored and entries from user, project, or local settings are ignored. Has no effect when set via SDK options |4730| `allowManagedDomainsOnly` | `boolean` | `false` | Managed-settings only. When set in [managed settings](/docs/en/permissions#managed-settings), only `allowedDomains` entries from managed settings are honored and entries from user, project, or local settings are ignored. Has no effect when set via SDK options |

3620| `allowLocalBinding` | `boolean` | `false` | Allow processes to bind to local ports (e.g., for dev servers) |4731| `allowLocalBinding` | `boolean` | `false` | Allow processes to bind to local ports (e.g., for dev servers) |

3621| `allowUnixSockets` | `string[]` | `[]` | Unix socket paths that processes can access (e.g., Docker socket) |4732| `allowUnixSockets` | `string[]` | `[]` | Unix socket paths that processes can access (e.g., Docker socket) |

Details

9<Warning>9<Warning>

10 The V2 session API is no longer supported. TypeScript Agent SDK 0.3.142 removes `unstable_v2_createSession`, `unstable_v2_resumeSession`, `unstable_v2_prompt`, and the `SDKSession` and `SDKSessionOptions` types.10 The V2 session API is no longer supported. TypeScript Agent SDK 0.3.142 removes `unstable_v2_createSession`, `unstable_v2_resumeSession`, `unstable_v2_prompt`, and the `SDKSession` and `SDKSessionOptions` types.

11 11 

12 To migrate, use the [`query()` API](/en/agent-sdk/typescript) and the [session options](/en/agent-sdk/sessions) it accepts. Pass an `AsyncIterable<SDKUserMessage>` for multi-turn conversations, or `options.resume` to continue a saved session. This page is kept for reference if you maintain code on Agent SDK 0.2.x or earlier.12 To migrate, use the [`query()` API](/docs/en/agent-sdk/typescript) and the [session options](/docs/en/agent-sdk/sessions) it accepts. Pass an `AsyncIterable<SDKUserMessage>` for multi-turn conversations, or `options.resume` to continue a saved session. This page is kept for reference if you maintain code on Agent SDK 0.2.x or earlier.

13</Warning>13</Warning>

14 14 

15V2 was an experimental session API that removed the need for async generators and yield coordination. Instead of managing generator state across turns, each turn was a separate `send()`/`stream()` cycle. The API surface reduced to three concepts:15V2 was an experimental session API that removed the need for async generators and yield coordination. Instead of managing generator state across turns, each turn was a separate `send()`/`stream()` cycle. The API surface reduced to three concepts:


305 305 

306Sessions can be closed manually or automatically using [`await using`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management), a TypeScript 5.2+ feature for automatic resource cleanup. If you're using an older TypeScript version or encounter compatibility issues, use manual cleanup instead.306Sessions can be closed manually or automatically using [`await using`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management), a TypeScript 5.2+ feature for automatic resource cleanup. If you're using an older TypeScript version or encounter compatibility issues, use manual cleanup instead.

307 307 

308The examples below show only the cleanup pattern and don't send any messages, so running them produces no output.

309 

308**Automatic cleanup (TypeScript 5.2+):**310**Automatic cleanup (TypeScript 5.2+):**

309 311 

310```typescript theme={null}312```typescript theme={null}


382 384 

383## Feature availability385## Feature availability

384 386 

385The V2 session API does not support every V1 feature. The following require the [V1 SDK](/en/agent-sdk/typescript):387The V2 session API does not support every V1 feature. The following require the [V1 SDK](/docs/en/agent-sdk/typescript):

386 388 

387* Session forking (`forkSession` option)389* Session forking (`forkSession` option)

388* Some advanced streaming input patterns390* Some advanced streaming input patterns

389 391 

390## See also392## See also

391 393 

392* [TypeScript SDK reference (V1)](/en/agent-sdk/typescript) - Full V1 SDK documentation394* [TypeScript SDK reference (V1)](/docs/en/agent-sdk/typescript) - Full V1 SDK documentation

393* [SDK overview](/en/agent-sdk/overview) - General SDK concepts395* [SDK overview](/docs/en/agent-sdk/overview) - General SDK concepts

394* [V2 examples on GitHub](https://github.com/anthropics/claude-agent-sdk-demos/tree/main/hello-world-v2) - Working code examples396* [V2 examples on GitHub](https://github.com/anthropics/claude-agent-sdk-demos/tree/main/hello-world-v2) - Working code examples

Details

12 12 

13For clarifying questions, Claude generates the questions and options. Your role is to present them to users and return their selections. You can't add your own questions to this flow; if you need to ask users something yourself, do that separately in your application logic.13For clarifying questions, Claude generates the questions and options. Your role is to present them to users and return their selections. You can't add your own questions to this flow; if you need to ask users something yourself, do that separately in your application logic.

14 14 

15The callback can stay pending indefinitely. Execution remains paused until your callback returns, and the SDK only cancels the wait when the query itself is cancelled. If a user might take longer to respond than your process can reasonably stay running, return the [`defer` hook decision](/en/hooks#defer-a-tool-call-for-later), which lets the process exit and resume later from the persisted session.15The callback can stay pending indefinitely. Execution remains paused until your callback returns, and the SDK only cancels the wait when the query itself is cancelled. If a user might take longer to respond than your process can reasonably stay running, return the [`defer` hook decision](/docs/en/hooks#defer-a-tool-call-for-later), which lets the process exit and resume later from the persisted session.

16 16 

17This guide shows you how to detect each type of request and respond appropriately.17This guide shows you how to detect each type of request and respond appropriately.

18 18 


22 22 

23<CodeGroup>23<CodeGroup>

24 ```python Python theme={null}24 ```python Python theme={null}

25 from claude_agent_sdk import ClaudeAgentOptions

26 

27 

25 async def handle_tool_request(tool_name, input_data, context):28 async def handle_tool_request(tool_name, input_data, context):

26 # Prompt user and return allow or deny29 # Prompt user and return allow or deny

27 ...30 ...


42 45 

43The callback fires in two cases:46The callback fires in two cases:

44 47 

451. **Tool needs approval**: Claude wants to use a tool that isn't auto-approved by a [permission rule](/en/agent-sdk/permissions) or permission mode. Check `tool_name` for the tool (e.g., `"Bash"`, `"Write"`).481. **Tool needs approval**: Claude wants to use a tool that isn't auto-approved by a [permission rule](/docs/en/agent-sdk/permissions) or permission mode. Check `tool_name` for the tool (e.g., `"Bash"`, `"Write"`).

462. **Claude asks a question**: Claude calls the `AskUserQuestion` tool. Check if `tool_name == "AskUserQuestion"` to handle it differently. If you specify a `tools` array, include `AskUserQuestion` for this to work. See [Handle clarifying questions](#handle-clarifying-questions) for details.492. **Claude asks a question**: Claude calls the `AskUserQuestion` tool. Check if `tool_name == "AskUserQuestion"` to handle it differently. If you specify a `tools` array, include `AskUserQuestion` for this to work. See [Handle clarifying questions](#handle-clarifying-questions) for details.

47 50 

48<Warning>51<Warning>

49 **The callback never fires for auto-approved tools.** Any approval earlier in the [permission evaluation flow](/en/agent-sdk/permissions#how-permissions-are-evaluated), an allow rule or a mode like `acceptEdits` or `bypassPermissions`, resolves the call before `canUseTool` is consulted. If you list a tool bare in `allowed_tools`, a `canUseTool` check for that tool never runs unless an ask rule or `plan` mode routes the call back to a prompt. For logic that must apply to every tool call, use a [`PreToolUse` hook](/en/agent-sdk/hooks), which executes before the rest of the flow and can allow, deny, or modify requests.52 **The callback never fires for auto-approved tools.** Any approval earlier in the [permission evaluation flow](/docs/en/agent-sdk/permissions#how-permissions-are-evaluated), an allow rule or a mode like `acceptEdits` or `bypassPermissions`, resolves the call before `canUseTool` is consulted. If you list a tool bare in `allowed_tools`, a `canUseTool` check for that tool never runs unless an ask rule or `plan` mode routes the call back to a prompt. For logic that must apply to every tool call, use a [`PreToolUse` hook](/docs/en/agent-sdk/hooks), which executes before the rest of the flow and can allow, deny, or modify requests.

50 53 

51 `AskUserQuestion`, MCP tools marked [`requiresUserInteraction`](/en/mcp#require-approval-for-a-specific-tool), and connector tools [your organization set to `ask`](/en/mcp#organization-controls-on-connector-tools) reach the callback even when an allow rule matches. In `dontAsk` mode these calls are denied instead, without invoking the callback.54 `AskUserQuestion`, MCP tools marked [`requiresUserInteraction`](/docs/en/mcp#require-approval-for-a-specific-tool), and connector tools [your organization set to `ask`](/docs/en/mcp#organization-controls-on-connector-tools) reach the callback even when an allow rule matches. In `dontAsk` mode these calls are denied instead, without invoking the callback.

52</Warning>55</Warning>

53 56 

54You can also use the [`PermissionRequest` hook](/en/agent-sdk/hooks#available-hooks) to send external notifications (Slack, email, push) when Claude is waiting for approval.57You can also use the [`PermissionRequest` hook](/docs/en/agent-sdk/hooks#available-hooks) to send external notifications (Slack, email, push) when Claude is waiting for approval.

55 58 

56## Handle tool approval requests59## Handle tool approval requests

57 60 


61| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |64| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

62| `toolName` | The name of the tool Claude wants to use (e.g., `"Bash"`, `"Write"`, `"Edit"`) |65| `toolName` | The name of the tool Claude wants to use (e.g., `"Bash"`, `"Write"`, `"Edit"`) |

63| `input` | The parameters Claude is passing to the tool. Contents vary by tool. |66| `input` | The parameters Claude is passing to the tool. Contents vary by tool. |

64| `options` (TS) / `context` (Python) | Additional context including optional `suggestions` (proposed `PermissionUpdate` entries to avoid re-prompting) and a cancellation signal. In TypeScript, `signal` is an `AbortSignal`; in Python, the signal field is reserved for future use. See [`ToolPermissionContext`](/en/agent-sdk/python#toolpermissioncontext) for Python. |67| `options` (TS) / `context` (Python) | Additional context including optional `suggestions` (proposed `PermissionUpdate` entries to avoid re-prompting) and a cancellation signal. In TypeScript, `signal` is an `AbortSignal`; in Python, the signal field is reserved for future use. See [`ToolPermissionContext`](/docs/en/agent-sdk/python#toolpermissioncontext) for Python. |

65 68 

66The `input` object contains tool-specific parameters. Common examples:69The `input` object contains tool-specific parameters. Common examples:

67 70 


72| `Edit` | `file_path`, `old_string`, `new_string` |75| `Edit` | `file_path`, `old_string`, `new_string` |

73| `Read` | `file_path`, `offset`, `limit` |76| `Read` | `file_path`, `offset`, `limit` |

74 77 

75See the SDK reference for complete input schemas: [Python](/en/agent-sdk/python#tool-input%2Foutput-types) | [TypeScript](/en/agent-sdk/typescript#tool-input-types).78See the SDK reference for complete input schemas: [Python](/docs/en/agent-sdk/python#tool-input%2Foutput-types) | [TypeScript](/docs/en/agent-sdk/typescript#tool-input-types).

76 79 

77You can display this information to the user so they can decide whether to allow or reject the action, then return the appropriate response.80You can display this information to the user so they can decide whether to allow or reject the action, then return the appropriate response.

78 81 


196</CodeGroup>199</CodeGroup>

197 200 

198<Note>201<Note>

199 In Python, `can_use_tool` requires [streaming mode](/en/agent-sdk/streaming-vs-single-mode). When you pass a finite message stream through `query(prompt=generator)` or `ClaudeSDKClient.connect(prompt=async_iterable)`, the SDK closes the input stream after the last message, before the permission callback can be invoked, unless a registered hook or in-process MCP server is keeping it open. The example above keeps it open with a `PreToolUse` hook that returns `{"continue_": True}`. Connecting with no prompt and sending messages through `ClaudeSDKClient.query()` keeps the stream open on its own and needs no hook.202 In Python, `can_use_tool` requires [streaming mode](/docs/en/agent-sdk/streaming-vs-single-mode). When you pass a finite message stream through `query(prompt=generator)` or `ClaudeSDKClient.connect(prompt=async_iterable)`, the SDK closes the input stream after the last message, before the permission callback can be invoked, unless a registered hook or in-process MCP server is keeping it open. The example above keeps it open with a `PreToolUse` hook that returns `{"continue_": True}`. Connecting with no prompt and sending messages through `ClaudeSDKClient.query()` keeps the stream open on its own and needs no hook.

200</Note>203</Note>

201 204 

202This example uses a `y/n` flow where any input other than `y` is treated as a denial. In practice, you might build a richer UI that lets users modify the request, provide feedback, or redirect Claude entirely. See [Respond to tool requests](#respond-to-tool-requests) for all the ways you can respond.205This example uses a `y/n` flow where any input other than `y` is treated as a denial. In practice, you might build a richer UI that lets users modify the request, provide feedback, or redirect Claude entirely. See [Respond to tool requests](#respond-to-tool-requests) for all the ways you can respond.


241* **Approve and remember**: echo a suggested permission rule back so matching calls skip the prompt next time244* **Approve and remember**: echo a suggested permission rule back so matching calls skip the prompt next time

242* **Reject**: block the tool and tell Claude why245* **Reject**: block the tool and tell Claude why

243* **Suggest alternative**: block but guide Claude toward what the user wants instead246* **Suggest alternative**: block but guide Claude toward what the user wants instead

244* **Redirect entirely**: use [streaming input](/en/agent-sdk/streaming-vs-single-mode) to send Claude a completely new instruction247* **Redirect entirely**: use [streaming input](/docs/en/agent-sdk/streaming-vs-single-mode) to send Claude a completely new instruction

248 

249The `ask_user` and `askUser` helpers in the following snippets stand in for your application's own prompt UI.

245 250 

246<Tabs>251<Tabs>

247 <Tab title="Approve">252 <Tab title="Approve">


305 </Tab>310 </Tab>

306 311 

307 <Tab title="Approve and remember">312 <Tab title="Approve and remember">

308 The user approves and doesn't want to be asked again for this kind of call. The third callback argument carries `suggestions`, an array of ready-made [`PermissionUpdate`](/en/agent-sdk/typescript#permissionupdate) entries. Echo one back in `updatedPermissions` to apply it. A suggestion with the `localSettings` destination writes the rule to `.claude/settings.local.json` so future sessions skip the prompt for matching calls.313 The user approves and doesn't want to be asked again for this kind of call. The third callback argument carries `suggestions`, an array of ready-made [`PermissionUpdate`](/docs/en/agent-sdk/typescript#permissionupdate) entries. Echo one back in `updatedPermissions` to apply it. A suggestion with the `localSettings` destination writes the rule to `.claude/settings.local.json` so future sessions skip the prompt for matching calls.

309 314 

310 The Python example requires `claude-agent-sdk` 0.1.80 or later.315 The Python example requires `claude-agent-sdk` 0.1.80 or later.

311 316 


409 </Tab>414 </Tab>

410 415 

411 <Tab title="Redirect entirely">416 <Tab title="Redirect entirely">

412 For a complete change of direction (not just a nudge), use [streaming input](/en/agent-sdk/streaming-vs-single-mode) to send Claude a new instruction directly. This bypasses the current tool request and gives Claude entirely new instructions to follow.417 For a complete change of direction (not just a nudge), use [streaming input](/docs/en/agent-sdk/streaming-vs-single-mode) to send Claude a new instruction directly. This bypasses the current tool request and gives Claude entirely new instructions to follow.

413 </Tab>418 </Tab>

414</Tabs>419</Tabs>

415 420 


418When Claude needs more direction on a task with multiple valid approaches, it calls the `AskUserQuestion` tool. This triggers your `canUseTool` callback with `toolName` set to `AskUserQuestion`. The input contains Claude's questions as multiple-choice options, which you display to the user and return their selections.423When Claude needs more direction on a task with multiple valid approaches, it calls the `AskUserQuestion` tool. This triggers your `canUseTool` callback with `toolName` set to `AskUserQuestion`. The input contains Claude's questions as multiple-choice options, which you display to the user and return their selections.

419 424 

420<Tip>425<Tip>

421 Clarifying questions are especially common in [`plan` mode](/en/agent-sdk/permissions#plan-mode-plan), where Claude explores the codebase and asks questions before proposing a plan. This makes plan mode ideal for interactive workflows where you want Claude to gather requirements before making changes.426 Clarifying questions are especially common in [`plan` mode](/docs/en/agent-sdk/permissions#plan-mode-plan), where Claude explores the codebase and asks questions before proposing a plan. This makes plan mode ideal for interactive workflows where you want Claude to gather requirements before making changes.

422</Tip>427</Tip>

423 428 

424The following steps show how to handle clarifying questions:429The following steps show how to handle clarifying questions:


840 845 

841### Streaming input846### Streaming input

842 847 

843Use [streaming input](/en/agent-sdk/streaming-vs-single-mode) when you need to:848Use [streaming input](/docs/en/agent-sdk/streaming-vs-single-mode) when you need to:

844 849 

845* **Interrupt the agent mid-task**: send a cancel signal or change direction while Claude is working850* **Interrupt the agent mid-task**: send a cancel signal or change direction while Claude is working

846* **Provide additional context**: add information Claude needs without waiting for it to ask851* **Provide additional context**: add information Claude needs without waiting for it to ask


850 855 

851### Custom tools856### Custom tools

852 857 

853Use [custom tools](/en/agent-sdk/custom-tools) when you need to:858Use [custom tools](/docs/en/agent-sdk/custom-tools) when you need to:

854 859 

855* **Collect structured input**: build forms, wizards, or multi-step workflows that go beyond `AskUserQuestion`'s multiple-choice format860* **Collect structured input**: build forms, wizards, or multi-step workflows that go beyond `AskUserQuestion`'s multiple-choice format

856* **Integrate external approval systems**: connect to existing ticketing, workflow, or approval platforms861* **Integrate external approval systems**: connect to existing ticketing, workflow, or approval platforms


860 865 

861## Related resources866## Related resources

862 867 

863* [Configure permissions](/en/agent-sdk/permissions): set up permission modes and rules868* [Configure permissions](/docs/en/agent-sdk/permissions): set up permission modes and rules

864* [Control execution with hooks](/en/agent-sdk/hooks): run custom code at key points in the agent lifecycle869* [Control execution with hooks](/docs/en/agent-sdk/hooks): run custom code at key points in the agent lifecycle

865* [TypeScript SDK reference](/en/agent-sdk/typescript#canusetool): full canUseTool API documentation870* [TypeScript SDK reference](/docs/en/agent-sdk/typescript#canusetool): full canUseTool API documentation

agent-teams.md +28 −28

Details

7> Coordinate multiple Claude Code instances working together as a team, with shared tasks, inter-agent messaging, and centralized management.7> Coordinate multiple Claude Code instances working together as a team, with shared tasks, inter-agent messaging, and centralized management.

8 8 

9<Warning>9<Warning>

10 Agent teams are experimental and disabled by default. Enable them by setting `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` in your [settings.json](/en/settings) or environment. Without that variable, no team is set up at session start, no team directories are written, and Claude does not spawn or propose teammates. Agent teams have [known limitations](#limitations) around session resumption, task coordination, and shutdown behavior.10 Agent teams are experimental and disabled by default. Enable them by setting `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` in your [settings.json](/docs/en/settings) or environment. Without that variable, no team is set up at session start, no team directories are written, and Claude does not spawn or propose teammates. Agent teams have [known limitations](#limitations) around session resumption, task coordination, and shutdown behavior.

11</Warning>11</Warning>

12 12 

13Agent teams let you coordinate multiple Claude Code instances working together. One session acts as the team lead, coordinating work, assigning tasks, and synthesizing results. Teammates work independently, each in its own context window, and communicate directly with each other.13Agent teams let you coordinate multiple Claude Code instances working together. One session acts as the team lead, coordinating work, assigning tasks, and synthesizing results. Teammates work independently, each in its own context window, and communicate directly with each other.

14 14 

15Unlike [subagents](/en/sub-agents), which run within a single session and can only report back to the main agent, you can also interact with individual teammates directly without going through the lead.15Unlike [subagents](/docs/en/sub-agents), which run within a single session and can only report back to the main agent, you can also interact with individual teammates directly without going through the lead.

16 16 

17<Note>17<Note>

18 This page describes agent teams as of v2.1.178. With `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` set, spawning a teammate no longer needs a setup step, and cleanup happens automatically when the session exits. Before v2.1.178, you asked Claude to create and name a team first, and Claude used the `TeamCreate` and `TeamDelete` tools to set it up and remove it. Both tools no longer exist. The `team_name` input on the Agent tool is accepted but ignored, and the `team_name` field in `TaskCreated`, `TaskCompleted`, and `TeammateIdle` [hook payloads](/en/hooks#taskcreated) carries the session-derived name and is deprecated.18 This page describes agent teams as of v2.1.178. With `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` set, spawning a teammate no longer needs a setup step, and cleanup happens automatically when the session exits. Before v2.1.178, you asked Claude to create and name a team first, and Claude used the `TeamCreate` and `TeamDelete` tools to set it up and remove it. Both tools no longer exist. The `team_name` input on the Agent tool is accepted but ignored, and the `team_name` field in `TaskCreated`, `TaskCompleted`, and `TeammateIdle` [hook payloads](/docs/en/hooks#taskcreated) carries the session-derived name and is deprecated.

19</Note>19</Note>

20 20 

21## When to use agent teams21## When to use agent teams


27* **Debugging with competing hypotheses**: teammates test different theories in parallel and converge on the answer faster27* **Debugging with competing hypotheses**: teammates test different theories in parallel and converge on the answer faster

28* **Cross-layer coordination**: changes that span frontend, backend, and tests, each owned by a different teammate28* **Cross-layer coordination**: changes that span frontend, backend, and tests, each owned by a different teammate

29 29 

30Agent teams add coordination overhead and use significantly more tokens than a single session. They work best when teammates can operate independently. For sequential tasks, same-file edits, or work with many dependencies, a single session or [subagents](/en/sub-agents) are more effective.30Agent teams add coordination overhead and use significantly more tokens than a single session. They work best when teammates can operate independently. For sequential tasks, same-file edits, or work with many dependencies, a single session or [subagents](/docs/en/sub-agents) are more effective.

31 31 

32### Compare with subagents32### Compare with subagents

33 33 

34Both agent teams and [subagents](/en/sub-agents) let you parallelize work, but they operate differently. Choose based on whether your workers need to communicate with each other:34Both agent teams and [subagents](/docs/en/sub-agents) let you parallelize work, but they operate differently. Choose based on whether your workers need to communicate with each other:

35 35 

36<Frame caption="Subagents only report results back to the main agent and never talk to each other. In agent teams, teammates share a task list, claim work, and communicate directly with each other.">36<Frame caption="Subagents only report results back to the main agent and never talk to each other. In agent teams, teammates share a task list, claim work, and communicate directly with each other.">

37 <img src="https://mintcdn.com/claude-code/nsvRFSDNfpSU5nT7/images/subagents-vs-agent-teams-light.png?fit=max&auto=format&n=nsvRFSDNfpSU5nT7&q=85&s=2f8db9b4f3705dd3ab931fbe2d96e42a" className="dark:hidden" alt="Diagram comparing subagent and agent team architectures. Subagents are spawned by the main agent, do work, and report results back. Agent teams coordinate through a shared task list, with teammates communicating directly with each other." width="4245" height="1615" data-path="images/subagents-vs-agent-teams-light.png" />37 <img src="https://mintcdn.com/claude-code/nsvRFSDNfpSU5nT7/images/subagents-vs-agent-teams-light.png?fit=max&auto=format&n=nsvRFSDNfpSU5nT7&q=85&s=2f8db9b4f3705dd3ab931fbe2d96e42a" className="dark:hidden" alt="Diagram comparing subagent and agent team architectures. Subagents are spawned by the main agent, do work, and report results back. Agent teams coordinate through a shared task list, with teammates communicating directly with each other." width="4245" height="1615" data-path="images/subagents-vs-agent-teams-light.png" />


51 51 

52## Enable agent teams52## Enable agent teams

53 53 

54Agent teams are disabled by default. Enable them by setting the `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` environment variable to `1`, either in your shell environment or through [settings.json](/en/settings):54Agent teams are disabled by default. Enable them by setting the `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` environment variable to `1`, either in your shell environment or through [settings.json](/docs/en/settings):

55 55 

56```json settings.json theme={null}56```json settings.json theme={null}

57{57{


73one on UX, one on technical architecture, one playing devil's advocate.73one on UX, one on technical architecture, one playing devil's advocate.

74```74```

75 75 

76From there, Claude populates a [shared task list](/en/interactive-mode#task-list), spawns teammates for each perspective, has them explore the problem, and synthesizes findings when finished.76From there, Claude populates a [shared task list](/docs/en/interactive-mode#task-list), spawns teammates for each perspective, has them explore the problem, and synthesizes findings when finished.

77 77 

78Claude may sometimes use [subagents](/en/sub-agents) instead of creating a team. Subagents appear in the same agent panel as teammates, so the panel alone doesn't confirm a team formed. If Claude spawned subagents instead, ask again and explicitly request an agent team.78Claude may sometimes use [subagents](/docs/en/sub-agents) instead of creating a team. Subagents appear in the same agent panel as teammates, so the panel alone doesn't confirm a team formed. If Claude spawned subagents instead, ask again and explicitly request an agent team.

79 79 

80The lead's terminal lists teammates in the agent panel below the prompt input. From the panel:80The lead's terminal lists teammates in the agent panel below the prompt input. From the panel:

81 81 


108 108 

109{/* min-version: 2.1.186 */}As of v2.1.186, set `"iterm2"` to use iTerm2 native split panes explicitly. This mode requires the [`it2` CLI](https://github.com/mkusaka/it2) and shows an error with the install command if `it2` is missing. The setup prompt that offers to install `it2` or switch to tmux appears under `"auto"` or `"tmux"` when your terminal is iTerm2 and tmux is available as a fallback.109{/* min-version: 2.1.186 */}As of v2.1.186, set `"iterm2"` to use iTerm2 native split panes explicitly. This mode requires the [`it2` CLI](https://github.com/mkusaka/it2) and shows an error with the install command if `it2` is missing. The setup prompt that offers to install `it2` or switch to tmux appears under `"auto"` or `"tmux"` when your terminal is iTerm2 and tmux is available as a fallback.

110 110 

111To override the default, set [`teammateMode`](/en/settings#available-settings) in `~/.claude/settings.json`:111To override the default, set [`teammateMode`](/docs/en/settings#available-settings) in `~/.claude/settings.json`:

112 112 

113```json theme={null}113```json theme={null}

114{114{


140 140 

141Teammates don't inherit the lead's `/model` selection by default. To change the model used when the prompt doesn't specify one, set **Default teammate model** in `/config`. Pick **Default (leader's model)** to have teammates follow the lead's current model.141Teammates don't inherit the lead's `/model` selection by default. To change the model used when the prompt doesn't specify one, set **Default teammate model** in `/config`. Pick **Default (leader's model)** to have teammates follow the lead's current model.

142 142 

143{/* min-version: 2.1.186 */}Teammates inherit the lead's [effort level](/en/model-config#adjust-effort-level). In split-pane mode this applies from v2.1.186; earlier versions did not pass the lead's session effort to split-pane teammates.143{/* min-version: 2.1.186 */}Teammates inherit the lead's [effort level](/docs/en/model-config#adjust-effort-level). In split-pane mode this applies from v2.1.186; earlier versions did not pass the lead's session effort to split-pane teammates.

144 144 

145### Require plan approval for teammates145### Require plan approval for teammates

146 146 


162* **In-process mode**: use the up and down arrow keys in the agent panel to select a teammate, then press Enter to view its session and type to send it a message. Press `x` on a selected teammate to stop it. Press Ctrl+T to toggle the task list.162* **In-process mode**: use the up and down arrow keys in the agent panel to select a teammate, then press Enter to view its session and type to send it a message. Press `x` on a selected teammate to stop it. Press Ctrl+T to toggle the task list.

163* **Split-pane mode**: click into a teammate's pane to interact with their session directly. Each teammate has a full view of their own terminal.163* **Split-pane mode**: click into a teammate's pane to interact with their session directly. Each teammate has a full view of their own terminal.

164 164 

165While you're viewing an in-process teammate, plain text and [skills](/en/skills) go to that teammate, but built-in commands still run in the lead's session.165While you're viewing an in-process teammate, plain text and [skills](/docs/en/skills) go to that teammate, but built-in commands still run in the lead's session.

166 166 

167A teammate's model and fast mode are fixed when it spawns, so `/model` and `/fast` only change the lead's settings. {/* min-version: 2.1.199 */}As of v2.1.199, typing either command while viewing a teammate shows a notice that the change applies to the lead; earlier versions applied it to the lead with no indication. `/effort` still applies to the viewed teammate's later turns, because teammates follow the lead's [effort level](/en/model-config#adjust-effort-level).167A teammate's model and fast mode are fixed when it spawns, so `/model` and `/fast` only change the lead's settings. {/* min-version: 2.1.199 */}As of v2.1.199, typing either command while viewing a teammate shows a notice that the change applies to the lead; earlier versions applied it to the lead with no indication. `/effort` still applies to the viewed teammate's later turns, because teammates follow the lead's [effort level](/docs/en/model-config#adjust-effort-level).

168 168 

169### Assign and claim tasks169### Assign and claim tasks

170 170 


191 191 

192### Enforce quality gates with hooks192### Enforce quality gates with hooks

193 193 

194Use [hooks](/en/hooks) to enforce rules when teammates finish work or tasks are created or completed:194Use [hooks](/docs/en/hooks) to enforce rules when teammates finish work or tasks are created or completed:

195 195 

196* [`TeammateIdle`](/en/hooks#teammateidle): runs when a teammate is about to go idle. Exit with code 2 to send feedback and keep the teammate working.196* [`TeammateIdle`](/docs/en/hooks#teammateidle): runs when a teammate is about to go idle. Exit with code 2 to send feedback and keep the teammate working.

197* [`TaskCreated`](/en/hooks#taskcreated): runs when a task is being created. Exit with code 2 to prevent creation and send feedback.197* [`TaskCreated`](/docs/en/hooks#taskcreated): runs when a task is being created. Exit with code 2 to prevent creation and send feedback.

198* [`TaskCompleted`](/en/hooks#taskcompleted): runs when a task is being marked complete. Exit with code 2 to prevent completion and send feedback.198* [`TaskCompleted`](/docs/en/hooks#taskcompleted): runs when a task is being marked complete. Exit with code 2 to prevent completion and send feedback.

199 199 

200## How agent teams work200## How agent teams work

201 201 


232* **Team config**: `~/.claude/teams/{team-name}/config.json`232* **Team config**: `~/.claude/teams/{team-name}/config.json`

233* **Task list**: `~/.claude/tasks/{team-name}/`233* **Task list**: `~/.claude/tasks/{team-name}/`

234 234 

235Claude Code generates both of these automatically at session startup and updates them as teammates join, go idle, or leave. The team config directory is removed when the session ends. The task list directory persists locally and is never uploaded, so resumed sessions keep their tasks. Retention is governed by the same [`cleanupPeriodDays`](/en/settings#available-settings) you already control for session transcripts.235Claude Code generates both of these automatically at session startup and updates them as teammates join, go idle, or leave. The team config directory is removed when the session ends. The task list directory persists locally and is never uploaded, so resumed sessions keep their tasks. Retention is governed by the same [`cleanupPeriodDays`](/docs/en/settings#available-settings) you already control for session transcripts.

236 236 

237The team config holds runtime state such as session IDs and tmux pane IDs, so don't edit it by hand or pre-author it: your changes are overwritten on the next state update.237The team config holds runtime state such as session IDs and tmux pane IDs, so don't edit it by hand or pre-author it: your changes are overwritten on the next state update.

238 238 

239To define reusable teammate roles, use [subagent definitions](#use-subagent-definitions-for-teammates) instead.239To define reusable teammate roles, use [subagent definitions](#use-subagent-definitions-for-teammates) instead.

240 240 

241The team config contains a `members` array with each member's name and agent ID. The lead's entry always carries the agent type `team-lead`; a teammate's entry includes an agent type only when the teammate was spawned from a [subagent definition](#use-subagent-definitions-for-teammates). Teammates can read this file to discover other team members.241The team config contains a `members` array with each member's name and agent ID. The lead's entry always carries the agent type `team-lead`. A teammate's entry carries whatever agent type the lead named when spawning it, whether a [built-in type](/docs/en/sub-agents#built-in-subagents) or a [subagent definition](#use-subagent-definitions-for-teammates), and omits the field when the lead named none. Teammates can read this file to discover other team members.

242 242 

243There is no project-level equivalent of the team config. A file like `.claude/teams/teams.json` in your project directory is not recognized as configuration; Claude treats it as an ordinary file.243There is no project-level equivalent of the team config. A file like `.claude/teams/teams.json` in your project directory is not recognized as configuration; Claude treats it as an ordinary file.

244 244 

245### Use subagent definitions for teammates245### Use subagent definitions for teammates

246 246 

247When spawning a teammate, you can reference a [subagent](/en/sub-agents) type from any [subagent scope](/en/sub-agents#choose-the-subagent-scope): project, user, plugin, or CLI-defined. This lets you define a role once, such as a security-reviewer or test-runner, and reuse it both as a delegated subagent and as an agent team teammate.247When spawning a teammate, you can reference a [subagent](/docs/en/sub-agents) type from any [subagent scope](/docs/en/sub-agents#choose-the-subagent-scope): project, user, plugin, or CLI-defined. This lets you define a role once, such as a security-reviewer or test-runner, and reuse it both as a delegated subagent and as an agent team teammate.

248 248 

249To use a subagent definition, mention it by name when asking Claude to spawn the teammate:249To use a subagent definition, mention it by name when asking Claude to spawn the teammate:

250 250 


262 262 

263Teammates start with the lead's permission settings. If the lead runs with `--dangerously-skip-permissions`, all teammates do too. After spawning, you can change individual teammate modes, but you can't set per-teammate modes at spawn time.263Teammates start with the lead's permission settings. If the lead runs with `--dangerously-skip-permissions`, all teammates do too. After spawning, you can change individual teammate modes, but you can't set per-teammate modes at spawn time.

264 264 

265When one agent sends another a message over `SendMessage`, the receiving agent is told it came from another Claude session, not from you. A teammate cannot approve a permission prompt or supply consent on your behalf, and a teammate that was denied an action cannot relay it to another teammate to bypass the check. In [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode), the classifier treats an approval claim relayed from another agent as untrusted input rather than confirmation from you.265When one agent sends another a message over `SendMessage`, the receiving agent is told it came from another Claude session, not from you. A teammate cannot approve a permission prompt or supply consent on your behalf, and a teammate that was denied an action cannot relay it to another teammate to bypass the check. In [auto mode](/docs/en/permission-modes#eliminate-prompts-with-auto-mode), the classifier treats an approval claim relayed from another agent as untrusted input rather than confirmation from you.

266 266 

267Teammate permission prompts appear in the lead session, so approve them there yourself. [Plan approval](#require-plan-approval-for-teammates) is the designed exception: the lead session grants teammate plan approvals without a separate prompt to you.267Teammate permission prompts appear in the lead session, so approve them there yourself. [Plan approval](#require-plan-approval-for-teammates) is the designed exception: the lead session grants teammate plan approvals without a separate prompt to you.

268 268 


281 281 

282### Token usage282### Token usage

283 283 

284Agent teams use significantly more tokens than a single session. Each teammate has its own context window, and token usage scales with the number of active teammates. For research, review, and new feature work, the extra tokens are usually worthwhile. For routine tasks, a single session is more cost-effective. See [agent team token costs](/en/costs#agent-team-token-costs) for usage guidance.284Agent teams use significantly more tokens than a single session. Each teammate has its own context window, and token usage scales with the number of active teammates. For research, review, and new feature work, the extra tokens are usually worthwhile. For routine tasks, a single session is more cost-effective. See [agent team token costs](/docs/en/costs#agent-team-token-costs) for usage guidance.

285 285 

286## Use case examples286## Use case examples

287 287 


333 333 

334There's no hard limit on the number of teammates, but practical constraints apply:334There's no hard limit on the number of teammates, but practical constraints apply:

335 335 

336* **Token costs scale linearly**: each teammate has its own context window and consumes tokens independently. See [agent team token costs](/en/costs#agent-team-token-costs) for details.336* **Token costs scale linearly**: each teammate has its own context window and consumes tokens independently. See [agent team token costs](/docs/en/costs#agent-team-token-costs) for details.

337* **Coordination overhead increases**: more teammates means more communication, task coordination, and potential for conflicts337* **Coordination overhead increases**: more teammates means more communication, task coordination, and potential for conflicts

338* **Diminishing returns**: beyond a certain point, additional teammates don't speed up work proportionally338* **Diminishing returns**: beyond a certain point, additional teammates don't speed up work proportionally

339 339 

340Start with 3-5 teammates for most workflows. This balances parallel work with manageable coordination. The examples in this guide use 3-5 teammates because that range works well across different task types.340Start with 3-5 teammates for most workflows. This balances parallel work with manageable coordination. The examples in this guide use 3-5 teammates because that range works well across different task types.

341 341 

342Having 5-6 [tasks](/en/agent-teams#architecture) per teammate keeps everyone productive without excessive context switching. If you have 15 independent tasks, 3 teammates is a good starting point.342Having 5-6 [tasks](/docs/en/agent-teams#architecture) per teammate keeps everyone productive without excessive context switching. If you have 15 independent tasks, 3 teammates is a good starting point.

343 343 

344Scale up only when the work genuinely benefits from having teammates work simultaneously. Three focused teammates often outperform five scattered ones.344Scale up only when the work genuinely benefits from having teammates work simultaneously. Three focused teammates often outperform five scattered ones.

345 345 


390 390 

391### Too many permission prompts391### Too many permission prompts

392 392 

393Teammate permission requests bubble up to the lead, which can create friction. Pre-approve common operations in your [permission settings](/en/permissions) before spawning teammates to reduce interruptions.393Teammate permission requests bubble up to the lead, which can create friction. Pre-approve common operations in your [permission settings](/docs/en/permissions) before spawning teammates to reduce interruptions.

394 394 

395### Teammates stopping on errors395### Teammates stopping on errors

396 396 


423* **Shutdown can be slow**: teammates finish their current request or tool call before shutting down, which can take time.423* **Shutdown can be slow**: teammates finish their current request or tool call before shutting down, which can take time.

424* **One team per session**: a session has exactly one team, scoped to that session. You can't create additional named teams or share a team across sessions.424* **One team per session**: a session has exactly one team, scoped to that session. You can't create additional named teams or share a team across sessions.

425* **No nested teams**: teammates cannot spawn their own teammates. Only the lead can manage the team.425* **No nested teams**: teammates cannot spawn their own teammates. Only the lead can manage the team.

426* **No background subagents from in-process teammates**: an in-process teammate's own subagents run in the foreground. Asking for a background one, whether with `run_in_background` or a subagent definition that sets `background: true`, returns an error, because a teammate's background work can't outlive the lead's process. Subagents launched from the main conversation follow the [background default](/en/sub-agents#run-subagents-in-foreground-or-background).426* **No background subagents from in-process teammates**: an in-process teammate's own subagents run in the foreground. Asking for a background one, whether with `run_in_background` or a subagent definition that sets `background: true`, returns an error, because a teammate's background work can't outlive the lead's process. Subagents launched from the main conversation follow the [background default](/docs/en/sub-agents#run-subagents-in-foreground-or-background).

427* **Lead is fixed**: the main session is the lead for its lifetime. You can't promote a teammate to lead or transfer leadership.427* **Lead is fixed**: the main session is the lead for its lifetime. You can't promote a teammate to lead or transfer leadership.

428* **Permissions set at spawn**: all teammates start with the lead's permission mode. You can change individual teammate modes after spawning, but you can't set per-teammate modes at spawn time.428* **Permissions set at spawn**: all teammates start with the lead's permission mode. You can change individual teammate modes after spawning, but you can't set per-teammate modes at spawn time.

429* **Split panes require tmux or iTerm2**: the default in-process mode works in any terminal. Split-pane mode isn't supported in VS Code's integrated terminal, Windows Terminal, or Ghostty.429* **Split panes require tmux or iTerm2**: the default in-process mode works in any terminal. Split-pane mode isn't supported in VS Code's integrated terminal, Windows Terminal, or Ghostty.


436 436 

437Explore related approaches for parallel work and delegation:437Explore related approaches for parallel work and delegation:

438 438 

439* **Lightweight delegation**: [subagents](/en/sub-agents) spawn helper agents for research or verification within your session, better for tasks that don't need inter-agent coordination439* **Lightweight delegation**: [subagents](/docs/en/sub-agents) spawn helper agents for research or verification within your session, better for tasks that don't need inter-agent coordination

440* **Manual parallel sessions**: [Git worktrees](/en/worktrees) let you run multiple Claude Code sessions yourself without automated team coordination440* **Manual parallel sessions**: [Git worktrees](/docs/en/worktrees) let you run multiple Claude Code sessions yourself without automated team coordination

441* **Compare approaches**: see the [subagent vs agent team](/en/features-overview#compare-similar-features) comparison for a side-by-side breakdown441* **Compare approaches**: see the [subagent vs agent team](/docs/en/features-overview#compare-similar-features) comparison for a side-by-side breakdown

Details

10 10 

11## Log in to Claude Code11## Log in to Claude Code

12 12 

13After [installing Claude Code](/docs/en/setup#install-claude-code), run `claude` in your terminal. On first launch, Claude Code opens a browser window for you to log in.13After [installing Claude Code](/docs/en/setup#install-claude-code), run `claude` in your terminal. On first launch, Claude Code opens a browser window for you to log in. If you've set the `ANTHROPIC_API_KEY` environment variable, Claude Code skips the login prompt and asks you to approve the key instead.

14 14 

15If the browser doesn't open automatically, press `c` to copy the login URL to your clipboard, then paste it into your browser.15If the browser doesn't open automatically, press `c` to copy the login URL to your clipboard, then paste it into your browser.

16 16 

best-practices.md +35 −35

Details

12 12 

13But this autonomy still comes with a learning curve. Claude works within certain constraints you need to understand.13But this autonomy still comes with a learning curve. Claude works within certain constraints you need to understand.

14 14 

15This 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](/en/how-claude-code-works).15This 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](/docs/en/how-claude-code-works).

16 16 

17***17***

18 18 


20 20 

21Claude'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.21Claude'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.

22 22 

23This 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](/en/context-window) of what loads at startup and what each file read costs. Track context usage continuously with a [custom status line](/en/statusline), and see [Reduce token usage](/en/costs#reduce-token-usage) for strategies on reducing token usage.23This 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](/docs/en/context-window) of what loads at startup and what each file read costs. Track context usage continuously with a [custom status line](/docs/en/statusline), and see [Reduce token usage](/docs/en/costs#reduce-token-usage) for strategies on reducing token usage.

24 24 

25***25***

26 26 


32 32 

33Claude stops when the work looks done. Without a check it can run, "looks done" is the only signal available, and you become the verification loop: every mistake waits for you to notice it. Give Claude something that produces a pass or fail, and the loop closes on its own. Claude does the work, runs the check, reads the result, and iterates until the check passes.33Claude stops when the work looks done. Without a check it can run, "looks done" is the only signal available, and you become the verification loop: every mistake waits for you to notice it. Give Claude something that produces a pass or fail, and the loop closes on its own. Claude does the work, runs the check, reads the result, and iterates until the check passes.

34 34 

35The check is anything that returns a signal Claude can read in the conversation: a test suite, a build exit code, a linter, a script that diffs output against a fixture, or a [browser screenshot](/en/chrome) compared against a design.35The check is anything that returns a signal Claude can read in the conversation: a test suite, a build exit code, a linter, a script that diffs output against a fixture, or a [browser screenshot](/docs/en/chrome) compared against a design.

36 36 

37| Strategy | Before | After |37| Strategy | Before | After |

38| ------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |38| ------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |


43Once the check exists, decide how hard it gates the stop:43Once the check exists, decide how hard it gates the stop:

44 44 

45* **In one prompt**: ask Claude to run the check and iterate in the same message, as in the table above.45* **In one prompt**: ask Claude to run the check and iterate in the same message, as in the table above.

46* **Across a session**: set the check as a [`/goal` condition](/en/goal). A separate evaluator re-checks it after every turn and Claude keeps working until it holds.46* **Across a session**: set the check as a [`/goal` condition](/docs/en/goal). A separate evaluator re-checks it after every turn and Claude keeps working until it holds.

47* **As a deterministic gate**: a [Stop hook](/en/hooks#stop) runs your check as a script and blocks the turn from ending until it passes. Claude Code overrides the hook and ends the turn after 8 consecutive blocks.47* **As a deterministic gate**: a [Stop hook](/docs/en/hooks#stop) runs your check as a script and blocks the turn from ending until it passes. Claude Code overrides the hook and ends the turn after 8 consecutive blocks.

48* **By a second opinion**: a [verification subagent](/en/sub-agents) or a [dynamic workflow](/en/workflows) that checks its own findings has a fresh model try to refute the result, so the agent doing the work isn't the one grading it.48* **By a second opinion**: a [verification subagent](/docs/en/sub-agents) or a [dynamic workflow](/docs/en/workflows) that checks its own findings has a fresh model try to refute the result, so the agent doing the work isn't the one grading it.

49 49 

50Each step trades setup for attention. The prompt version works on any task today. The `/goal` and Stop hook versions are what let an unattended run finish correctly without you.50Each step trades setup for attention. The prompt version works on any task today. The `/goal` and Stop hook versions are what let an unattended run finish correctly without you.

51 51 


59 Separate research and planning from implementation to avoid solving the wrong problem.59 Separate research and planning from implementation to avoid solving the wrong problem.

60</Tip>60</Tip>

61 61 

62Letting Claude jump straight to coding can produce code that solves the wrong problem. Use [plan mode](/en/permission-modes#analyze-before-you-edit-with-plan-mode) to separate exploration from execution.62Letting Claude jump straight to coding can produce code that solves the wrong problem. Use [plan mode](/docs/en/permission-modes#analyze-before-you-edit-with-plan-mode) to separate exploration from execution.

63 63 

64The recommended workflow has four phases:64The recommended workflow has four phases:

65 65 


147 147 

148## Configure your environment148## Configure your environment

149 149 

150A 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](/en/features-overview).150A 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](/docs/en/features-overview).

151 151 

152### Write an effective CLAUDE.md152### Write an effective CLAUDE.md

153 153 


171- Prefer running single tests, and not the whole test suite, for performance171- Prefer running single tests, and not the whole test suite, for performance

172```172```

173 173 

174Run `/context` to confirm Claude loaded the file. 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](/en/skills) instead. Claude loads them on demand without bloating every conversation.174Run `/context` to confirm Claude loaded the file. 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](/docs/en/skills) instead. Claude loads them on demand without bloating every conversation.

175 175 

176Keep 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!176Keep 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!

177 177 


210### Configure permissions210### Configure permissions

211 211 

212<Tip>212<Tip>

213 Use [auto mode](/en/permission-modes#eliminate-prompts-with-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.213 Use [auto mode](/docs/en/permission-modes#eliminate-prompts-with-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.

214</Tip>214</Tip>

215 215 

216By 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:216By 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:


219* **Permission allowlists**: permit specific tools you know are safe, like `npm run lint` or `git commit`219* **Permission allowlists**: permit specific tools you know are safe, like `npm run lint` or `git commit`

220* **Sandboxing**: enable OS-level isolation that restricts filesystem and network access, allowing Claude to work more freely within defined boundaries220* **Sandboxing**: enable OS-level isolation that restricts filesystem and network access, allowing Claude to work more freely within defined boundaries

221 221 

222Read more about [permission modes](/en/permission-modes), [permission rules](/en/permissions), and [sandboxing](/en/sandboxing).222Read more about [permission modes](/docs/en/permission-modes), [permission rules](/docs/en/permissions), and [sandboxing](/docs/en/sandboxing).

223 223 

224### Use CLI tools224### Use CLI tools

225 225 


237 Run `claude mcp add` to connect external tools like Notion, Figma, or your database.237 Run `claude mcp add` to connect external tools like Notion, Figma, or your database.

238</Tip>238</Tip>

239 239 

240With [MCP servers](/en/mcp), you can ask Claude to implement features from issue trackers, query databases, analyze monitoring data, integrate designs from Figma, and automate workflows.240With [MCP servers](/docs/en/mcp), you can ask Claude to implement features from issue trackers, query databases, analyze monitoring data, integrate designs from Figma, and automate workflows.

241 241 

242### Set up hooks242### Set up hooks

243 243 


245 Use hooks for actions that must happen every time with zero exceptions.245 Use hooks for actions that must happen every time with zero exceptions.

246</Tip>246</Tip>

247 247 

248[Hooks](/en/hooks-guide) 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.248[Hooks](/docs/en/hooks-guide) 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.

249 249 

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

251 251 


255 Create `SKILL.md` files in `.claude/skills/` to give Claude domain knowledge and reusable workflows.255 Create `SKILL.md` files in `.claude/skills/` to give Claude domain knowledge and reusable workflows.

256</Tip>256</Tip>

257 257 

258[Skills](/en/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`.258[Skills](/docs/en/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`.

259 259 

260Create a skill by adding a directory with a `SKILL.md` to `.claude/skills/`:260Create a skill by adding a directory with a `SKILL.md` to `.claude/skills/`:

261 261 


299 Define specialized assistants in `.claude/agents/` that Claude can delegate to for isolated tasks.299 Define specialized assistants in `.claude/agents/` that Claude can delegate to for isolated tasks.

300</Tip>300</Tip>

301 301 

302[Subagents](/en/sub-agents) 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.302[Subagents](/docs/en/sub-agents) 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.

303 303 

304```markdown .claude/agents/security-reviewer.md theme={null}304```markdown .claude/agents/security-reviewer.md theme={null}

305---305---


325 Run `/plugin` to browse the marketplace. Plugins add skills, tools, and integrations without configuration.325 Run `/plugin` to browse the marketplace. Plugins add skills, tools, and integrations without configuration.

326</Tip>326</Tip>

327 327 

328[Plugins](/en/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](/en/discover-plugins#code-intelligence) to give Claude precise symbol navigation and automatic error detection after edits.328[Plugins](/docs/en/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](/docs/en/discover-plugins#code-intelligence) to give Claude precise symbol navigation and automatic error detection after edits.

329 329 

330For guidance on choosing between skills, subagents, hooks, and MCP, see [Extend Claude Code](/en/features-overview#match-features-to-your-goal).330For guidance on choosing between skills, subagents, hooks, and MCP, see [Extend Claude Code](/docs/en/features-overview#match-features-to-your-goal).

331 331 

332***332***

333 333 


405* Use `/clear` frequently between tasks to reset the context window entirely405* Use `/clear` frequently between tasks to reset the context window entirely

406* When auto compaction triggers, Claude summarizes what matters most, including code patterns, file states, and key decisions406* When auto compaction triggers, Claude summarizes what matters most, including code patterns, file states, and key decisions

407* For more control, run `/compact <instructions>`, like `/compact Focus on the API changes`407* For more control, run `/compact <instructions>`, like `/compact Focus on the API changes`

408* To compact only part of the conversation, use `Esc + Esc` or `/rewind`, select a message checkpoint, and choose **Summarize from here** or **Summarize up to here**. The first condenses messages from that point forward while keeping earlier context intact; the second condenses earlier messages while keeping recent ones in full. See [Restore vs. summarize](/en/checkpointing#restore-vs-summarize).408* To compact only part of the conversation, use `Esc + Esc` or `/rewind`, select a message checkpoint, and choose **Summarize from here** or **Summarize up to here**. The first condenses messages from that point forward while keeping earlier context intact; the second condenses earlier messages while keeping recent ones in full. See [the rewind menu's summarize options](/docs/en/checkpointing#rewind-and-summarize).

409* Customize compaction behavior in CLAUDE.md with instructions like `"When compacting, always preserve the full list of modified files and any test commands"` to ensure critical context survives summarization409* Customize compaction behavior in CLAUDE.md with instructions like `"When compacting, always preserve the full list of modified files and any test commands"` to ensure critical context survives summarization

410* For quick questions that don't need to stay in context, use [`/btw`](/en/interactive-mode#side-questions-with-%2Fbtw). The answer appears in a dismissible overlay and never enters conversation history, so you can check a detail without growing context.410* For quick questions that don't need to stay in context, use [`/btw`](/docs/en/interactive-mode#side-questions-with-%2Fbtw). The answer appears in a dismissible overlay and never enters conversation history, so you can check a detail without growing context.

411 411 

412### Use subagents for investigation412### Use subagents for investigation

413 413 


436 Every prompt you send creates a checkpoint. You can restore conversation, code, or both to any previous checkpoint.436 Every prompt you send creates a checkpoint. You can restore conversation, code, or both to any previous checkpoint.

437</Tip>437</Tip>

438 438 

439Claude automatically snapshots files before each change so a checkpoint can restore them. 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](/en/checkpointing) for details.439Claude automatically snapshots files before each change so a checkpoint can restore them. 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](/docs/en/checkpointing) for details.

440 440 

441Instead 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 are saved with the conversation, so you can close your terminal, resume the session later, and still rewind.441Instead 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 are saved with the conversation, so you can close your terminal, resume the session later, and still rewind.

442 442 


450 Name sessions with `/rename` and treat them like branches: each workstream gets its own persistent context.450 Name sessions with `/rename` and treat them like branches: each workstream gets its own persistent context.

451</Tip>451</Tip>

452 452 

453Claude Code saves conversations locally, so when a task spans multiple sittings you don't have to re-explain the context. Run `claude --continue` to pick up the most recent session, or `claude --resume` to choose from a list. Give sessions descriptive names like `oauth-migration` so you can find them later. See [Manage sessions](/en/sessions) for the full set of resume, branch, and naming controls.453Claude Code saves conversations locally, so when a task spans multiple sittings you don't have to re-explain the context. Run `claude --continue` to pick up the most recent session, or `claude --resume` to choose from a list. Give sessions descriptive names like `oauth-migration` so you can find them later. See [Manage sessions](/docs/en/sessions) for the full set of resume, branch, and naming controls.

454 454 

455***455***

456 456 


466 Use `claude -p "prompt"` in CI, pre-commit hooks, or scripts. Add `--output-format stream-json --verbose` for streaming JSON output.466 Use `claude -p "prompt"` in CI, pre-commit hooks, or scripts. Add `--output-format stream-json --verbose` for streaming JSON output.

467</Tip>467</Tip>

468 468 

469With `claude -p "your prompt"`, you can run Claude non-interactively, without an interactive prompt. The run still creates a resumable session unless you pass `--no-session-persistence`. [Non-interactive mode](/en/headless) 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.469With `claude -p "your prompt"`, you can run Claude non-interactively, without an interactive prompt. The run still creates a resumable session unless you pass `--no-session-persistence`. [Non-interactive mode](/docs/en/headless) 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.

470 470 

471```bash theme={null}471```bash theme={null}

472# One-off queries472# One-off queries


489 489 

490Pick the parallel approach that fits how much coordination you want to do yourself:490Pick the parallel approach that fits how much coordination you want to do yourself:

491 491 

492* [Worktrees](/en/worktrees): run separate CLI sessions in isolated git checkouts so edits don't collide492* [Worktrees](/docs/en/worktrees): run separate CLI sessions in isolated git checkouts so edits don't collide

493* [Desktop app](/en/desktop#work-in-parallel-with-sessions): manage multiple local sessions visually, each in its own worktree493* [Desktop app](/docs/en/desktop#work-in-parallel-with-sessions): manage multiple local sessions visually, each in its own worktree

494* [Claude Code on the web](/en/claude-code-on-the-web): run sessions on Anthropic-managed cloud infrastructure in isolated VMs494* [Claude Code on the web](/docs/en/claude-code-on-the-web): run sessions on Anthropic-managed cloud infrastructure in isolated VMs

495* [Agent teams](/en/agent-teams): automated coordination of multiple sessions with shared tasks, messaging, and a team lead495* [Agent teams](/docs/en/agent-teams): automated coordination of multiple sessions with shared tasks, messaging, and a team lead

496 496 

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

498 498 


543 543 

544### Run autonomously with auto mode544### Run autonomously with auto mode

545 545 

546For uninterrupted execution with background safety checks, use [auto mode](/en/permission-modes#eliminate-prompts-with-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.546For uninterrupted execution with background safety checks, use [auto mode](/docs/en/permission-modes#eliminate-prompts-with-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.

547 547 

548```bash theme={null}548```bash theme={null}

549claude --permission-mode auto -p "fix all lint errors"549claude --permission-mode auto -p "fix all lint errors"

550```550```

551 551 

552For 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](/en/permission-modes#when-auto-mode-falls-back) for thresholds.552For 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](/docs/en/permission-modes#when-auto-mode-falls-back) for thresholds.

553 553 

554### Add an adversarial review step554### Add an adversarial review step

555 555 


557 Before treating a task as done, have a subagent review the diff in a fresh context and report gaps.557 Before treating a task as done, have a subagent review the diff in a fresh context and report gaps.

558</Tip>558</Tip>

559 559 

560The longer Claude works unattended, the more an independent check matters before you count the work as done. A reviewer running in a fresh [subagent](/en/sub-agents) context sees only the diff and the criteria you give it, not the reasoning that produced the change, so it evaluates the result on its own terms.560The longer Claude works unattended, the more an independent check matters before you count the work as done. A reviewer running in a fresh [subagent](/docs/en/sub-agents) context sees only the diff and the criteria you give it, not the reasoning that produced the change, so it evaluates the result on its own terms.

561 561 

562For a correctness check, run the bundled [`/code-review` skill](/en/commands), which reviews the current diff for bugs in a fresh subagent and returns findings to the session. To check the diff against your plan instead, write the review prompt yourself. Name the work to check, the plan to check it against, and what counts as a finding:562For a correctness check, run the bundled [`/code-review` skill](/docs/en/commands), which reviews the current diff for bugs in a fresh subagent and returns findings to the session. To check the diff against your plan instead, write the review prompt yourself. Name the work to check, the plan to check it against, and what counts as a finding:

563 563 

564```text theme={null}564```text theme={null}

565Use a subagent to review the rate limiter diff against PLAN.md. Check that565Use a subagent to review the rate limiter diff against PLAN.md. Check that


567nothing outside the task's scope changed. Report gaps, not style preferences.567nothing outside the task's scope changed. Report gaps, not style preferences.

568```568```

569 569 

570Because the reviewer runs as a subagent, the implementing session receives the gaps directly and can fix them and re-review without you copying findings between windows. For longer autonomous runs, an [agent team](/en/agent-teams) can keep this loop going across many tasks while you spot-check the recorded findings.570Because the reviewer runs as a subagent, the implementing session receives the gaps directly and can fix them and re-review without you copying findings between windows. For longer autonomous runs, an [agent team](/docs/en/agent-teams) can keep this loop going across many tasks while you spot-check the recorded findings.

571 571 

572<Callout>572<Callout>

573 A reviewer prompted to find gaps will usually report some, even when the work is sound, because that is what it was asked to do. Chasing every finding leads to over-engineering: extra abstraction layers, defensive code, and tests for cases that can't happen. Tell the reviewer to flag only gaps that affect correctness or the stated requirements, and treat the rest as optional.573 A reviewer prompted to find gaps will usually report some, even when the work is sound, because that is what it was asked to do. Chasing every finding leads to over-engineering: extra abstraction layers, defensive code, and tests for cases that can't happen. Tell the reviewer to flag only gaps that affect correctness or the stated requirements, and treat the rest as optional.


604 604 

605## Related resources605## Related resources

606 606 

607* [How Claude Code works](/en/how-claude-code-works): the agentic loop, tools, and context management607* [How Claude Code works](/docs/en/how-claude-code-works): the agentic loop, tools, and context management

608* [Extend Claude Code](/en/features-overview): skills, hooks, MCP, subagents, and plugins608* [Extend Claude Code](/docs/en/features-overview): skills, hooks, MCP, subagents, and plugins

609* [Common workflows](/en/common-workflows): step-by-step recipes for debugging, testing, PRs, and more609* [Common workflows](/docs/en/common-workflows): step-by-step recipes for debugging, testing, PRs, and more

610* [CLAUDE.md](/en/memory): store project conventions and persistent context610* [CLAUDE.md](/docs/en/memory): store project conventions and persistent context

Details

48 48 

49If you ran `/clear` earlier in the same Claude Code process, the rewind menu shows an additional entry at the top of the list labeled `/resume <session-id> (previous session)`. Select it to resume the conversation that was active before `/clear` ran. The entry is available until you exit Claude Code or resume a different session, and requires Claude Code v2.1.191 or later. On earlier versions, run `/resume` and pick the previous session from the list instead.49If you ran `/clear` earlier in the same Claude Code process, the rewind menu shows an additional entry at the top of the list labeled `/resume <session-id> (previous session)`. Select it to resume the conversation that was active before `/clear` ran. The entry is available until you exit Claude Code or resume a different session, and requires Claude Code v2.1.191 or later. On earlier versions, run `/resume` and pick the previous session from the list instead.

50 50 

51#### Restore vs. summarize51#### Guide a summary

52 52 

53The restore options revert state: they undo code changes, conversation history, or both. The summarize options compress part of the conversation into an AI-generated summary without changing files on disk:53Summarizing doesn't change files on disk, and the original messages stay in the session transcript, so Claude can still reference the details. To guide what the summary focuses on, highlight a **Summarize** option with the arrow keys and type instructions where the row reads **add context (optional)**, then press `Enter`. Selecting the option with its number key summarizes immediately without instructions.

54 

55* **Summarize from here**: messages before the selected message stay intact. The selected message and everything after it are replaced with a summary. Use this to discard a side discussion while keeping early context in full detail.

56* **Summarize up to here**: messages before the selected message are replaced with a summary. The selected message and everything after it stay intact, and you remain at the end of the conversation. Use this to compress early setup discussion while keeping recent work in full detail.

57 

58In both cases the original messages are preserved in the session transcript, so Claude can reference the details if needed. To guide what the summary focuses on, highlight a **Summarize** option with the arrow keys and type instructions inline where the row reads **add context (optional)**, then press `Enter` to summarize; selecting the option by its number key summarizes immediately without instructions. This is similar to `/compact`, but targeted: instead of summarizing the entire conversation, you choose which side of the selected message to compress.

59 54 

60<Note>55<Note>

61 Summarize keeps you in the same session and compresses context. If you want to branch off and try a different approach while preserving the original session intact, use [`/branch`](/docs/en/sessions#branch-a-session) or `claude --continue --fork-session` instead.56 Summarize keeps you in the same session and compresses context, like a targeted `/compact`. To branch off and try a different approach while preserving the original session intact, use [`/branch`](/docs/en/sessions#branch-a-session) or `claude --continue --fork-session` instead.

62</Note>57</Note>

63 58 

64## Common use cases59## Common use cases

Details

613 Enable logs and traces only on destinations with the access controls and retention policy that data warrants.613 Enable logs and traces only on destinations with the access controls and retention policy that data warrants.

614</Warning>614</Warning>

615 615 

616Telemetry is off in the CLI by default. Configuring `telemetry.forward_to` together with `listen.public_url` turns it on. The gateway pushes five env vars to every connected client through `/managed/settings`:616Telemetry is off in the CLI by default. Configuring `telemetry.forward_to` together with `listen.public_url` turns it on. The gateway pushes six env vars to every connected client through `/managed/settings`:

617 617 

618* `CLAUDE_CODE_ENABLE_TELEMETRY=1`618* `CLAUDE_CODE_ENABLE_TELEMETRY=1`

619* `OTEL_METRICS_EXPORTER=otlp`619* `OTEL_METRICS_EXPORTER=otlp`

620* `OTEL_LOGS_EXPORTER=otlp`620* `OTEL_LOGS_EXPORTER=otlp`

621* `OTEL_TRACES_EXPORTER=otlp`621* `OTEL_TRACES_EXPORTER=otlp`

622* `OTEL_EXPORTER_OTLP_ENDPOINT=<public_url>`622* `OTEL_EXPORTER_OTLP_ENDPOINT=<public_url>`

623* `OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf`

623 624 

624The pushed endpoint is built from the public URL, so metrics and logs need no OTEL configuration from developers or policies. The pushed configuration is applied at the managed tier, overriding `OTEL_*` variables a developer sets locally.625The pushed endpoint is built from the public URL, so metrics and logs need no OTEL configuration from developers or policies. The pushed configuration is applied at the managed tier, overriding `OTEL_*` variables a developer sets locally.

625 626 

Details

4 4 

5# Use Claude Code on the web5# Use Claude Code on the web

6 6 

7> Configure cloud environments, setup scripts, network access, and Docker in Anthropic's sandbox. Move sessions between web and terminal with `--cloud` and `--teleport`.7> Move sessions between web and terminal with `--cloud` and `--teleport`, manage and share sessions, and auto-fix pull requests from Anthropic's cloud infrastructure.

8 8 

9<Note>9<Note>

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


16 New to Claude Code on the web? Start with [Get started](/docs/en/web-quickstart) to connect your GitHub account and submit your first task.16 New to Claude Code on the web? Start with [Get started](/docs/en/web-quickstart) to connect your GitHub account and submit your first task.

17</Tip>17</Tip>

18 18 

19This page covers:19This page covers the web product itself:

20 20 

21* [Cloud environments](#cloud-environments): where sessions run, and where to configure that

21* [GitHub authentication options](#github-authentication-options): two ways to connect GitHub22* [GitHub authentication options](#github-authentication-options): two ways to connect GitHub

22* [The cloud environment](#the-cloud-environment): what config carries over, what tools are installed, and how to configure environments

23* [Setup scripts](#setup-scripts) and dependency management

24* [Network access](#network-access): levels, proxies, and the default allowlist

25* [Move tasks between web and terminal](#move-tasks-between-web-and-terminal) with `--cloud` and `--teleport`23* [Move tasks between web and terminal](#move-tasks-between-web-and-terminal) with `--cloud` and `--teleport`

26* [Work with sessions](#work-with-sessions): reviewing, sharing, archiving, deleting24* [Work with sessions](#work-with-sessions): reviewing, sharing, archiving, deleting

27* [Auto-fix pull requests](#auto-fix-pull-requests): respond automatically to CI failures and review comments25* [Auto-fix pull requests](#auto-fix-pull-requests): respond automatically to CI failures and review comments

28* [Security and isolation](#security-and-isolation): how sessions are isolated26* [Security and isolation](#security-and-isolation): how sessions are isolated

29* [Limitations](#limitations): rate limits and platform restrictions27* [Limitations](#limitations): rate limits and platform restrictions

30 28 

29## Cloud environments

30 

31Every cloud session runs in a [cloud environment](/docs/en/cloud-environments), the saved configuration that controls network access, environment variables, and setup scripts. When you onboard, Claude Code sets up a **Default** environment with [**Trusted** network access](/docs/en/cloud-environments#access-levels). See [The Default environment](/docs/en/cloud-environments#the-default-environment) for how it's created and how sessions choose an environment when you have more than one.

32 

33The same environments apply wherever you start a cloud session: the web, the terminal, [Claude Tag](https://claude.com/docs/claude-tag/overview), [routines](/docs/en/routines), and the mobile and Desktop apps. Claude Tag channel sessions use [organization-shared environments](/docs/en/cloud-environments#organization-shared-environments) only.

34 

35See [Configure cloud environments](/docs/en/cloud-environments) to change what an environment allows, set variables, or add a setup script, and [Installed tools](/docs/en/cloud-environments#installed-tools) for what sessions include without any configuration.

36 

31## GitHub authentication options37## GitHub authentication options

32 38 

33Cloud sessions need access to your GitHub repositories to clone code and push branches. You can grant access in two ways:39Cloud sessions need access to your GitHub repositories to clone code and push branches. You can grant access in two ways:


51 Organizations with [Zero Data Retention](/docs/en/zero-data-retention) enabled can't use `/web-setup` or other cloud session features.57 Organizations with [Zero Data Retention](/docs/en/zero-data-retention) enabled can't use `/web-setup` or other cloud session features.

52</Note>58</Note>

53 59 

54## The cloud environment

55 

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

57 

58### What's available in cloud sessions

59 

60Cloud 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 isn't available in the session. Your organization's policy arrives separately through [server-managed settings](/docs/en/server-managed-settings).

61 

62| | Available in cloud sessions | Why |

63| :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

64| Your repo's `CLAUDE.md` | Yes | Part of the clone |

65| Your repo's `.claude/settings.json` hooks | Yes | Part of the clone |

66| Your repo's `.mcp.json` MCP servers | Yes | Part of the clone |

67| Your repo's `.claude/rules/` | Yes | Part of the clone |

68| Your repo's `.claude/skills/`, `.claude/agents/`, `.claude/commands/` | Yes | Part of the clone |

69| Plugins declared in `.claude/settings.json` | Yes | Installed at session start from the [marketplace](/docs/en/plugin-marketplaces) you declared. Requires network access to reach the marketplace source |

70| Your organization's [server-managed settings](/docs/en/server-managed-settings) | Yes | Fetched from Anthropic's servers when the session starts. See [Surface coverage](/docs/en/model-config#surface-coverage) for how `availableModels` is enforced in cloud sessions. Settings deployed to your device through MDM or managed settings files don't apply, because the session runs on an Anthropic-managed VM |

71| Your user `~/.claude/CLAUDE.md` | No | Lives on your machine, not in the repo |

72| Your user `~/.claude/skills/`, `~/.claude/agents/`, `~/.claude/commands/` | No | Live on your machine, not in the repo. Commit them to the repo's `.claude/` directory instead. Skills you enable on claude.ai are loaded into cloud sessions automatically |

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

74| 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`](/docs/en/mcp#project-scope) instead |

75| Transport variables in your repo's `.claude/settings.json` `env` block, such as `NODE_EXTRA_CA_CERTS` and the [mTLS client certificate variables](/docs/en/network-config#mtls-authentication) | No | The hosting environment manages the session's API connection, so Claude Code ignores these keys and notes each ignored key in the session's debug log |

76| Static API tokens and credentials | No | No dedicated secrets store exists yet. See below |

77| Interactive auth like AWS SSO | No | Not supported. SSO requires browser-based login that can't run in a cloud session |

78 

79To make your own configuration available in cloud sessions, commit it to the repo; organization policy arrives separately through [server-managed settings](/docs/en/server-managed-settings).

80 

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

82 

83### Installed tools

84 

85Cloud sessions come with common language runtimes, build tools, and databases pre-installed. The table below summarizes what's included by category.

86 

87| Category | Included |

88| :------------ | :--------------------------------------------------------------------------------- |

89| **Python** | Python 3.x with pip, poetry, uv, black, mypy, pytest, ruff |

90| **Node.js** | 20, 21, and 22 via nvm, with npm, yarn, pnpm, bun¹, eslint, prettier, chromedriver |

91| **Ruby** | 3.1, 3.2, 3.3 with gem, bundler, rbenv |

92| **PHP** | 8.4 with Composer |

93| **Java** | OpenJDK 21 with Maven and Gradle |

94| **Go** | latest stable with module support |

95| **Rust** | rustc and cargo |

96| **C/C++** | GCC, Clang, cmake, ninja, conan |

97| **Docker** | docker, dockerd, docker compose |

98| **Databases** | PostgreSQL 16, Redis 7.0 |

99| **Utilities** | git, jq, yq, ripgrep, tmux, vim, nano |

100 

101¹ Bun is installed but has known [proxy compatibility issues](#install-dependencies-with-a-sessionstart-hook) for package fetching.

102 

103For exact versions, ask Claude to run `check-tools` in a cloud session. This command only exists in cloud sessions.

104 

105### Work with GitHub issues and pull requests

106 

107Cloud 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](#github-proxy) using whichever method you configured under [GitHub authentication options](#github-authentication-options), so your token never enters the container.

108 

109You can set `GH_TOKEN` or `GITHUB_TOKEN` yourself in [environment settings](#configure-your-environment), or leave both unset and let the [GitHub proxy](#github-proxy) authenticate for you:

110 

111* If you set a token, it passes through to the container unchanged, so `gh` and your scripts use it directly.

112* If you set neither, the container sets both variables to the placeholder string `proxy-injected` and the proxy substitutes your real credentials on outbound GitHub requests. `gh` works without a token of your own, but a script that reads `GITHUB_TOKEN` directly gets the placeholder, not a usable token.

113 

114To check which case applies to your session, ask Claude to run `echo $GH_TOKEN`.

115 

116The `gh` CLI isn't 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:

117 

118<Steps>

119 <Step title="Install gh in your setup script">

120 Add `apt update && apt install -y gh` to your [setup script](#setup-scripts).

121 </Step>

122 

123 <Step title="Provide a token if the proxy is not handling authentication">

124 If `echo $GH_TOKEN` prints `proxy-injected`, the [GitHub proxy](#github-proxy) authenticates `gh` for you and this step is unnecessary. Otherwise, add a `GH_TOKEN` environment variable to your [environment settings](#configure-your-environment) with a GitHub personal access token. `gh` reads `GH_TOKEN` automatically, so no `gh auth login` step is needed.

125 </Step>

126</Steps>

127 

128### Link output back to the session

129 

130Each cloud session has a transcript URL on claude.ai, and the session can read its own ID from the `CLAUDE_CODE_REMOTE_SESSION_ID` environment variable. Use this to put a traceable link in PR bodies, commit messages, Slack posts, or generated reports so a reviewer can open the run that produced them.

131 

132As of v2.1.179, commits that Claude creates in a web session include a `Claude-Session: <url>` git trailer, and PR bodies include the session URL on its own line. {/* min-version: 2.1.182 */}From v2.1.182, set [`attribution.sessionUrl`](/docs/en/settings#attribution-settings) to `false` to omit the trailer and the PR-body link.

133 

134To include the session link in something other than a commit or PR, such as a Slack message Claude posts or a report file it writes, have Claude run the following command and use its output. The command converts the `cse_` prefix in the environment variable's value to the `session_` prefix that the transcript URL expects:

135 

136```bash theme={null}

137echo "https://claude.ai/code/${CLAUDE_CODE_REMOTE_SESSION_ID/#cse_/session_}"

138```

139 

140### Run tests, start services, and add packages

141 

142Claude 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 are pre-installed and work without additional setup.

143 

144PostgreSQL and Redis are pre-installed but not running by default. Ask Claude to start each one during the session:

145 

146```bash theme={null}

147service postgresql start

148```

149 

150```bash theme={null}

151service redis-server start

152```

153 

154Docker is available for running containerized services. Ask Claude to run `docker compose up` to start your project's services. Network access to pull images follows your environment's [access level](#access-levels), and the [Trusted defaults](#default-allowed-domains) include Docker Hub and other common registries.

155 

156If your images are large or slow to pull, add `docker compose pull` or `docker compose build` to your [setup script](#setup-scripts). The pulled images are saved in the [cached environment](#environment-caching), so each new session has them on disk. The cache stores files only, not running processes, so Claude still starts the containers each session.

157 

158To add packages that aren't pre-installed, use a [setup script](#setup-scripts). The script's output is [cached](#environment-caching), so packages you install there are available at the start of every session without reinstalling each time. You can also ask Claude to install packages mid-session, but those installs don't carry over to other sessions.

159 

160### Resource limits

161 

162Cloud sessions run with approximate resource ceilings that may change over time:

163 

164* 4 vCPUs

165* 16 GB of RAM

166* 30 GB of disk

167 

168Tasks 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](/docs/en/remote-control) to run Claude Code on your own hardware.

169 

170### Configure your environment

171 

172Environments control [network access](#network-access), environment variables, and the [setup script](#setup-scripts) that runs before a session starts. See [Installed tools](#installed-tools) for what's available without any configuration. You can manage environments from the web interface or the terminal:

173 

174| Action | How |

175| :------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

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

177| Edit an environment | Select the cloud icon showing the current environment's name to open the selector, hover over an environment, and click the settings icon that appears on the right. |

178| Archive an environment | Open the environment for editing and select **Archive**. Archived environments are hidden from the selector but existing sessions keep running. |

179| Set the default environment for CLI cloud sessions | 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. |

180 

181Environment 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. This example defines three variables:

182 

183```text theme={null}

184NODE_ENV=development

185LOG_LEVEL=debug

186DATABASE_URL=postgres://localhost:5432/myapp

187```

188 

189### Organization-shared environments

190 

191Owners and admins on Team and Enterprise plans can create cloud environments that are shared with every member of the organization. Shared environments appear in each member's environment selector alongside their personal ones, so a team can standardize on one configuration instead of each member recreating it.

192 

193Manage shared environments from the **Cloud environments** page in [admin settings](https://claude.ai/admin-settings). From there you can:

194 

195* Create, edit, and archive shared environments. Each one has the same fields as a personal environment: a name, a [network access level](#access-levels), [environment variables](#configure-your-environment) in `.env` format, and a [setup script](#setup-scripts).

196* Set the default environment for the organization.

197 

198Values in a shared environment reach every member's sessions in that environment. Like personal environments, shared environments have no dedicated secrets store, so don't include secrets.

199 

200## Setup scripts

201 

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

203 

204Scripts run as root on Ubuntu 24.04, so `apt install` and most language package managers work.

205 

206To add a setup script, open the environment settings dialog and enter your script in the **Setup script** field.

207 

208This example installs the `gh` CLI, which isn't pre-installed:

209 

210```bash theme={null}

211#!/bin/bash

212apt update && apt install -y gh

213```

214 

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

216 

217Keep the script's total runtime under roughly five minutes so the [environment cache](#environment-caching) can build. Run independent installs in parallel with `&` and `wait`. If a single download won't fit in the five-minute limit, move it to a [SessionStart hook](#setup-scripts-vs-sessionstart-hooks) that launches it in the background.

218 

219<Note>

220 Setup scripts that install packages need network access to reach registries. The default **Trusted** network access allows connections to [common package registries](#default-allowed-domains) including npm, PyPI, RubyGems, and crates.io. Scripts fail to install packages if your environment uses **None** network access.

221</Note>

222 

223### Environment caching

224 

225The setup script runs the first time you start a session in an environment. After it completes, Anthropic snapshots the filesystem and reuses that snapshot as the starting point for later sessions. New sessions start with your dependencies, tools, and Docker images already on disk, and the setup script step is skipped. This keeps startup fast even when the script installs large toolchains or pulls container images.

226 

227The cache captures files, not running processes. Anything the setup script writes to disk carries over. Services or containers it starts don't, so start those per session by asking Claude or with a [SessionStart hook](#setup-scripts-vs-sessionstart-hooks).

228 

229The setup script runs again to rebuild the cache when you change the environment's setup script or allowed network hosts, and when the cache reaches its expiry after roughly seven days. Resuming an existing session never re-runs the setup script.

230 

231You don't need to enable caching or manage snapshots yourself.

232 

233### Setup scripts vs. SessionStart hooks

234 

235Use 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](/docs/en/hooks#sessionstart) for project setup that should run everywhere, cloud and local, like `npm install`.

236 

237Both run at the start of a session, but they belong to different places:

238 

239| | Setup scripts | SessionStart hooks |

240| ------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |

241| Attached to | The cloud environment | Your repository |

242| Configured in | Cloud environment UI | `.claude/settings.json` in your repo |

243| Runs | Before Claude Code launches, when no [cached environment](#environment-caching) is available | After Claude Code launches, on every session including resumed |

244| Scope | Cloud environments only | Both local and cloud |

245 

246SessionStart 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, hooks come from the repo and from your organization's [server-managed settings](/docs/en/server-managed-settings).

247 

248### Install dependencies with a SessionStart hook

249 

250To install dependencies only in cloud sessions, add a SessionStart hook to your repo's `.claude/settings.json`:

251 

252```json theme={null}

253{

254 "hooks": {

255 "SessionStart": [

256 {

257 "matcher": "startup|resume",

258 "hooks": [

259 {

260 "type": "command",

261 "command": "\"$CLAUDE_PROJECT_DIR\"/scripts/install_pkgs.sh"

262 }

263 ]

264 }

265 ]

266 }

267}

268```

269 

270Create the script at `scripts/install_pkgs.sh`. The `CLAUDE_CODE_REMOTE` environment variable is set to `true` in cloud sessions, so you can use it to skip local execution:

271 

272```bash theme={null}

273#!/bin/bash

274 

275if [ "$CLAUDE_CODE_REMOTE" != "true" ]; then

276 exit 0

277fi

278 

279npm install

280pip install -r requirements.txt

281exit 0

282```

283 

284Then make the script executable:

285 

286```bash theme={null}

287chmod +x scripts/install_pkgs.sh

288```

289 

290SessionStart hooks have some limitations in cloud sessions:

291 

292* **No cloud-only scoping**: hooks run in both local and cloud sessions. To skip local execution, check the `CLAUDE_CODE_REMOTE` environment variable as shown above.

293* **Requires network access**: install commands need to reach package registries. If your environment uses **None** network access, these hooks fail. The [default allowlist](#default-allowed-domains) under **Trusted** covers npm, PyPI, RubyGems, and crates.io.

294* **Proxy compatibility**: all outbound traffic passes through a [security proxy](#security-proxy). Some package managers don't work correctly with this proxy. Bun is a known example.

295* **Adds startup latency**: hooks run each time a session starts or resumes, unlike setup scripts which benefit from [environment caching](#environment-caching). Keep install scripts fast by checking whether dependencies are already present before reinstalling.

296 

297To persist environment variables for subsequent Bash commands, write to the file at `$CLAUDE_ENV_FILE`. See [SessionStart hooks](/docs/en/hooks#sessionstart) for details.

298 

299Replacing the base image with your own Docker image is not yet supported. Use a setup script to install what you need on top of the [provided image](#installed-tools), or run your image as a container alongside Claude with `docker compose`.

300 

301## Network access

302 

303Network 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](#default-allowed-domains).

304 

305To change an environment's network access, [open it for editing](#configure-your-environment) and use the **Network access** selector in the dialog. There is no separate Environments page. The cloud icon appears wherever you start a cloud session or configure a [routine](/docs/en/routines#environments-and-network-access).

306 

307<Note>

308 MCP connector traffic is routed through Anthropic's servers, so the connectors you enable on a session or routine work without adding their hosts to **Allowed domains**. Connectors are configured per session or per routine; remove any you don't need to limit which tools Claude can reach. This relies on the same Anthropic-bound channel noted under [Security and isolation](#security-and-isolation).

309</Note>

310 

311### Access levels

312 

313Choose an access level when you create or edit an environment:

314 

315| Level | Outbound connections |

316| :---------- | :------------------------------------------------------------------------------------------- |

317| **None** | No outbound network access |

318| **Trusted** | [Allowlisted domains](#default-allowed-domains) only: package registries, GitHub, cloud SDKs |

319| **Full** | Any domain |

320| **Custom** | Your own allowlist, optionally including the defaults |

321 

322GitHub operations use a [separate proxy](#github-proxy) that is independent of this setting.

323 

324### Allow specific domains

325 

326To 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:

327 

328```text theme={null}

329api.example.com

330*.internal.example.com

331registry.example.com

332```

333 

334Use `*.` for wildcard subdomain matching. Check **Also include default list of common package managers** to keep the [Trusted domains](#default-allowed-domains) alongside your custom entries, or leave it unchecked to allow only what you list.

335 

336Allowed domains are configured per environment. There's no organization-level allowlist that Owners can push to all users' environments; [server-managed settings](/docs/en/server-managed-settings) can restrict cloud sessions but can't add allowed domains.

337 

338### GitHub proxy

339 

340For security, all GitHub operations go through a dedicated proxy service that keeps your real GitHub credentials outside the sandbox. The proxy authenticates two kinds of traffic:

341 

342* Git interactions: the git client inside the sandbox uses a custom-built scoped credential, which the proxy verifies and translates to your actual GitHub authentication token

343* GitHub API requests: the proxy substitutes your real credentials on requests from the built-in GitHub tools, and from `gh` when your session sets the `proxy-injected` placeholder described in [Work with GitHub issues and pull requests](#work-with-github-issues-and-pull-requests)

344 

345The proxy also restricts git push operations to the current working branch for safety, and enables cloning, fetching, and PR operations while maintaining security boundaries.

346 

347The proxy limits GitHub API and release-asset requests to repositories attached to the session, regardless of the environment's [network access level](#access-levels). Setup scripts that download release assets from unattached repositories return a 403. Committed files from public repositories are fetched through `raw.githubusercontent.com`, which the [security proxy](#security-proxy) handles instead. That domain is in the default [Trusted list](#default-allowed-domains), so the files stay reachable unless the environment's [access level](#access-levels) excludes it.

348 

349### Security proxy

350 

351Environments run behind an HTTP/HTTPS network proxy for security and abuse prevention purposes. All outbound internet traffic passes through this proxy, which provides:

352 

353* Protection against malicious requests

354* Rate limiting and abuse prevention

355* Content filtering for enhanced security

356* A DNS-level audit trail of requested hostnames

357 

358### Default allowed domains

359 

360When 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`.

361 

362<AccordionGroup>

363 <Accordion title="Anthropic services">

364 * api.anthropic.com

365 * statsig.anthropic.com

366 * docs.claude.com

367 * platform.claude.com

368 * code.claude.com

369 * claude.ai

370 </Accordion>

371 

372 <Accordion title="Version control">

373 * github.com

374 * [www.github.com](http://www.github.com)

375 * api.github.com

376 * npm.pkg.github.com

377 * raw\.githubusercontent.com

378 * pkg-npm.githubusercontent.com

379 * objects.githubusercontent.com

380 * release-assets.githubusercontent.com

381 * codeload.github.com

382 * avatars.githubusercontent.com

383 * camo.githubusercontent.com

384 * gist.github.com

385 * gitlab.com

386 * [www.gitlab.com](http://www.gitlab.com)

387 * registry.gitlab.com

388 * bitbucket.org

389 * [www.bitbucket.org](http://www.bitbucket.org)

390 * api.bitbucket.org

391 </Accordion>

392 

393 <Accordion title="Container registries">

394 * registry-1.docker.io

395 * auth.docker.io

396 * index.docker.io

397 * hub.docker.com

398 * [www.docker.com](http://www.docker.com)

399 * production.cloudflare.docker.com

400 * download.docker.com

401 * gcr.io

402 * \*.gcr.io

403 * ghcr.io

404 * mcr.microsoft.com

405 * \*.data.mcr.microsoft.com

406 * public.ecr.aws

407 </Accordion>

408 

409 <Accordion title="Cloud platforms">

410 * cloud.google.com

411 * accounts.google.com

412 * gcloud.google.com

413 * \*.googleapis.com

414 * storage.googleapis.com

415 * compute.googleapis.com

416 * container.googleapis.com

417 * azure.com

418 * portal.azure.com

419 * microsoft.com

420 * [www.microsoft.com](http://www.microsoft.com)

421 * \*.microsoftonline.com

422 * packages.microsoft.com

423 * dotnet.microsoft.com

424 * dot.net

425 * visualstudio.com

426 * dev.azure.com

427 * \*.amazonaws.com

428 * \*.api.aws

429 * oracle.com

430 * [www.oracle.com](http://www.oracle.com)

431 * java.com

432 * [www.java.com](http://www.java.com)

433 * java.net

434 * [www.java.net](http://www.java.net)

435 * download.oracle.com

436 * yum.oracle.com

437 </Accordion>

438 

439 <Accordion title="JavaScript and Node package managers">

440 * registry.npmjs.org

441 * [www.npmjs.com](http://www.npmjs.com)

442 * [www.npmjs.org](http://www.npmjs.org)

443 * npmjs.com

444 * npmjs.org

445 * yarnpkg.com

446 * registry.yarnpkg.com

447 </Accordion>

448 

449 <Accordion title="Python package managers">

450 * pypi.org

451 * [www.pypi.org](http://www.pypi.org)

452 * files.pythonhosted.org

453 * pythonhosted.org

454 * test.pypi.org

455 * pypi.python.org

456 * pypa.io

457 * [www.pypa.io](http://www.pypa.io)

458 </Accordion>

459 

460 <Accordion title="Ruby package managers">

461 * rubygems.org

462 * [www.rubygems.org](http://www.rubygems.org)

463 * api.rubygems.org

464 * index.rubygems.org

465 * ruby-lang.org

466 * [www.ruby-lang.org](http://www.ruby-lang.org)

467 * rubyforge.org

468 * [www.rubyforge.org](http://www.rubyforge.org)

469 * rubyonrails.org

470 * [www.rubyonrails.org](http://www.rubyonrails.org)

471 * rvm.io

472 * get.rvm.io

473 </Accordion>

474 

475 <Accordion title="Rust package managers">

476 * crates.io

477 * [www.crates.io](http://www.crates.io)

478 * index.crates.io

479 * static.crates.io

480 * rustup.rs

481 * static.rust-lang.org

482 * [www.rust-lang.org](http://www.rust-lang.org)

483 </Accordion>

484 

485 <Accordion title="Go package managers">

486 * proxy.golang.org

487 * sum.golang.org

488 * index.golang.org

489 * golang.org

490 * [www.golang.org](http://www.golang.org)

491 * goproxy.io

492 * pkg.go.dev

493 </Accordion>

494 

495 <Accordion title="JVM package managers">

496 * maven.org

497 * repo.maven.org

498 * central.maven.org

499 * repo1.maven.org

500 * repo.maven.apache.org

501 * jcenter.bintray.com

502 * gradle.org

503 * [www.gradle.org](http://www.gradle.org)

504 * services.gradle.org

505 * plugins.gradle.org

506 * kotlinlang.org

507 * [www.kotlinlang.org](http://www.kotlinlang.org)

508 * spring.io

509 * repo.spring.io

510 </Accordion>

511 

512 <Accordion title="Other package managers">

513 * packagist.org (PHP Composer)

514 * [www.packagist.org](http://www.packagist.org)

515 * repo.packagist.org

516 * nuget.org (.NET NuGet)

517 * [www.nuget.org](http://www.nuget.org)

518 * api.nuget.org

519 * pub.dev (Dart/Flutter)

520 * api.pub.dev

521 * hex.pm (Elixir/Erlang)

522 * [www.hex.pm](http://www.hex.pm)

523 * cpan.org (Perl CPAN)

524 * [www.cpan.org](http://www.cpan.org)

525 * metacpan.org

526 * [www.metacpan.org](http://www.metacpan.org)

527 * api.metacpan.org

528 * cocoapods.org (iOS/macOS)

529 * [www.cocoapods.org](http://www.cocoapods.org)

530 * cdn.cocoapods.org

531 * haskell.org

532 * [www.haskell.org](http://www.haskell.org)

533 * hackage.haskell.org

534 * swift.org

535 * [www.swift.org](http://www.swift.org)

536 </Accordion>

537 

538 <Accordion title="Linux distributions">

539 * archive.ubuntu.com

540 * security.ubuntu.com

541 * ubuntu.com

542 * [www.ubuntu.com](http://www.ubuntu.com)

543 * \*.ubuntu.com

544 * ppa.launchpad.net

545 * launchpad.net

546 * [www.launchpad.net](http://www.launchpad.net)

547 * \*.nixos.org

548 </Accordion>

549 

550 <Accordion title="Development tools and platforms">

551 * dl.k8s.io (Kubernetes)

552 * pkgs.k8s.io

553 * k8s.io

554 * [www.k8s.io](http://www.k8s.io)

555 * releases.hashicorp.com (HashiCorp)

556 * apt.releases.hashicorp.com

557 * rpm.releases.hashicorp.com

558 * archive.releases.hashicorp.com

559 * hashicorp.com

560 * [www.hashicorp.com](http://www.hashicorp.com)

561 * repo.anaconda.com (Anaconda/Conda)

562 * conda.anaconda.org

563 * anaconda.org

564 * [www.anaconda.com](http://www.anaconda.com)

565 * anaconda.com

566 * continuum.io

567 * apache.org (Apache)

568 * [www.apache.org](http://www.apache.org)

569 * archive.apache.org

570 * downloads.apache.org

571 * eclipse.org (Eclipse)

572 * [www.eclipse.org](http://www.eclipse.org)

573 * download.eclipse.org

574 * nodejs.org (Node.js)

575 * [www.nodejs.org](http://www.nodejs.org)

576 * developer.apple.com

577 * developer.android.com

578 * pkg.stainless.com

579 * binaries.prisma.sh

580 </Accordion>

581 

582 <Accordion title="Cloud services and monitoring">

583 * statsig.com

584 * [www.statsig.com](http://www.statsig.com)

585 * api.statsig.com

586 * sentry.io

587 * \*.sentry.io

588 * downloads.sentry-cdn.com

589 * http-intake.logs.datadoghq.com

590 * browser-intake-us5-datadoghq.com

591 * \*.datadoghq.com

592 * \*.datadoghq.eu

593 * api.honeycomb.io

594 </Accordion>

595 

596 <Accordion title="Content delivery and mirrors">

597 * sourceforge.net

598 * \*.sourceforge.net

599 * packagecloud.io

600 * \*.packagecloud.io

601 * fonts.googleapis.com

602 * fonts.gstatic.com

603 </Accordion>

604 

605 <Accordion title="Schema and configuration">

606 * json-schema.org

607 * [www.json-schema.org](http://www.json-schema.org)

608 * json.schemastore.org

609 * [www.schemastore.org](http://www.schemastore.org)

610 </Accordion>

611 

612 <Accordion title="Model Context Protocol">

613 * \*.modelcontextprotocol.io

614 </Accordion>

615</AccordionGroup>

616 

617## Move tasks between web and terminal60## Move tasks between web and terminal

618 61 

619These workflows require the [Claude Code CLI](/docs/en/quickstart) 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. The `--cloud` and `--teleport` flags don't appear in `claude --help` output, but the CLI accepts them as shown below.62These workflows require the [Claude Code CLI](/docs/en/quickstart) 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. The `--cloud` and `--teleport` flags don't appear in `claude --help` output, but the CLI accepts them as shown below.


632 75 

633This 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. `--cloud` works with a single repository at a time. The task runs in the cloud while you continue working locally. The older `--remote` spelling still works as a deprecated alias for `--cloud`.76This 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. `--cloud` works with a single repository at a time. The task runs in the cloud while you continue working locally. The older `--remote` spelling still works as a deprecated alias for `--cloud`.

634 77 

635{/* min-version: 2.1.195 */}As of v2.1.195, the CLI shows a live checklist of setup steps, such as cloning the repository and running your [setup script](#setup-scripts), while the cloud container starts. Messages you type while the container is provisioning are queued and sent once the session is ready.78{/* min-version: 2.1.195 */}As of v2.1.195, the CLI shows a live checklist of setup steps, such as cloning the repository and running your [setup script](/docs/en/cloud-environments#setup-scripts), while the cloud container starts. Messages you type while the container is provisioning are queued and sent once the session is ready.

636 79 

637<Note>80<Note>

638 `--cloud` creates cloud sessions. `--remote-control` is unrelated: it exposes a local CLI session for monitoring from the web. See [Remote Control](/docs/en/remote-control).81 `--cloud` creates cloud sessions. `--remote-control` is unrelated: it exposes a local CLI session for monitoring from the web. See [Remote Control](/docs/en/remote-control).


724Cloud sessions support [built-in commands](/docs/en/commands) that produce text output. Commands that only run in the terminal interface, such as `/plugin` or `/resume`, aren't available. Commands that open a picker or panel in the terminal behave differently in cloud sessions:167Cloud sessions support [built-in commands](/docs/en/commands) that produce text output. Commands that only run in the terminal interface, such as `/plugin` or `/resume`, aren't available. Commands that open a picker or panel in the terminal behave differently in cloud sessions:

725 168 

726* {/* min-version: 2.1.205 */}**`/model`, `/effort`, `/fast`, `/color`, and `/rename`**: pass the value as an argument, for example `/model sonnet`, instead of opening the terminal picker or slider. The argument forms require Claude Code v2.1.205 or later in the session's environment and follow each command's [availability notes](/docs/en/commands#all-commands): `/effort` reports `Not applied` while a model's [launch-default effort hold](/docs/en/model-config#adjust-effort-level) is in force, and `/fast` works only in a session that started with fast mode turned on.169* {/* min-version: 2.1.205 */}**`/model`, `/effort`, `/fast`, `/color`, and `/rename`**: pass the value as an argument, for example `/model sonnet`, instead of opening the terminal picker or slider. The argument forms require Claude Code v2.1.205 or later in the session's environment and follow each command's [availability notes](/docs/en/commands#all-commands): `/effort` reports `Not applied` while a model's [launch-default effort hold](/docs/en/model-config#adjust-effort-level) is in force, and `/fast` works only in a session that started with fast mode turned on.

727* **`/config`**: on the web, opens the Claude Code section of your settings instead of setting a value, and text after the command, including `key=value`, is ignored. To change settings for a cloud session, use [environment variables](#configure-your-environment) or commit [settings files](/docs/en/settings) to the repository.170* **`/config`**: on the web, opens the Claude Code section of your settings instead of setting a value, and text after the command, including `key=value`, is ignored. To change settings for a cloud session, use [environment variables](/docs/en/cloud-environments#set-environment-variables) or commit [settings files](/docs/en/settings) to the repository.

728 171 

729For context management specifically:172For context management specifically:

730 173 


734| `/context` | Yes | Shows what's currently in the context window |177| `/context` | Yes | Shows what's currently in the context window |

735| `/clear` | No | Start a new session from the sidebar instead |178| `/clear` | No | Start a new session from the sidebar instead |

736 179 

737Auto-compaction runs automatically when the context window approaches capacity. To trigger it earlier, set [`CLAUDE_AUTOCOMPACT_PCT_OVERRIDE`](/docs/en/env-vars) in your [environment variables](#configure-your-environment). For example, `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=70` compacts at 70% capacity instead of waiting until the window is nearly full. To change the effective window size for compaction calculations, use [`CLAUDE_CODE_AUTO_COMPACT_WINDOW`](/docs/en/env-vars).180Auto-compaction runs automatically when the context window approaches capacity. To trigger it earlier, set [`CLAUDE_AUTOCOMPACT_PCT_OVERRIDE`](/docs/en/env-vars) in your [environment variables](/docs/en/cloud-environments#set-environment-variables). For example, `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=70` compacts at 70% capacity instead of waiting until the window is nearly full. To change the effective window size for compaction calculations, use [`CLAUDE_CODE_AUTO_COMPACT_WINDOW`](/docs/en/env-vars).

738 181 

739[Subagents](/docs/en/sub-agents) 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.182[Subagents](/docs/en/sub-agents) 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.

740 183 

741[Agent teams](/docs/en/agent-teams) are off by default but can be enabled by adding `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` to your [environment variables](#configure-your-environment).184[Agent teams](/docs/en/agent-teams) are off by default but can be enabled by adding `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` to your [environment variables](/docs/en/cloud-environments#set-environment-variables).

742 185 

743### Review changes186### Review changes

744 187 


782Claude 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.225Claude 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.

783 226 

784<Note>227<Note>

785 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](https://github.com/apps/claude) or when prompted during [setup](/docs/en/web-quickstart#connect-github-and-create-an-environment).228 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](https://github.com/apps/claude) or when prompted during [setup](/docs/en/web-quickstart#connect-github).

786</Note>229</Note>

787 230 

788There are a few ways to turn on auto-fix depending on where the PR came from and what device you're using:231There are a few ways to turn on auto-fix depending on where the PR came from and what device you're using:


825 268 

826### Session creation failed269### Session creation failed

827 270 

828If a new session fails to start with `Session creation failed` or stalls at provisioning, Claude Code could not allocate a cloud environment.271If a new session fails to start with `Session creation failed` or stalls at provisioning, Claude Code could not allocate a VM for the session.

829 272 

830* Check [status.claude.com](https://status.claude.com) for cloud session incidents273* Check [status.claude.com](https://status.claude.com) for cloud session incidents

831* Retry after a minute, as capacity is provisioned on demand274* Retry after a minute, as capacity is provisioned on demand


849 292 

850### Environment expired293### Environment expired

851 294 

852Cloud sessions stop after a period of inactivity and the underlying environment is reclaimed. From a local terminal, this surfaces as `Could not resume session ... its environment has expired. Creating a fresh session instead.` On the web, the session is marked expired in the session list.295Cloud sessions stop after a period of inactivity and the session's VM is reclaimed. On the web, the session is marked expired in the session list.

853 296 

854Reopen the session from [claude.ai/code](https://claude.ai/code) to provision a fresh environment with your conversation history restored.297Reopen the session from [claude.ai/code](https://claude.ai/code) to provision a fresh VM with your conversation history restored.

855 298 

856## Limitations299## Limitations

857 300 


864 307 

865## Related resources308## Related resources

866 309 

310* [Cloud environments](/docs/en/cloud-environments): configure network access, environment variables, and setup scripts for cloud sessions

867* [Ultraplan](/docs/en/ultraplan): draft a plan in a cloud session and review it in your browser311* [Ultraplan](/docs/en/ultraplan): draft a plan in a cloud session and review it in your browser

868* [Ultrareview](/docs/en/ultrareview): run a deep multi-agent code review in a cloud sandbox312* [Ultrareview](/docs/en/ultrareview): run a deep multi-agent code review in a cloud sandbox

869* [Routines](/docs/en/routines): automate work on a schedule, via API call, or in response to GitHub events313* [Routines](/docs/en/routines): automate work on a schedule, via API call, or in response to GitHub events


871* [Settings reference](/docs/en/settings): all configuration options315* [Settings reference](/docs/en/settings): all configuration options

872* [Security](/docs/en/security): isolation guarantees and data handling316* [Security](/docs/en/security): isolation guarantees and data handling

873* [Data usage](/docs/en/data-usage): what Anthropic retains from cloud sessions317* [Data usage](/docs/en/data-usage): what Anthropic retains from cloud sessions

874* [Claude Tag](https://claude.com/docs/claude-tag/overview): an organization-managed @Claude in Slack that runs on the same cloud environment318* [Claude Tag](https://claude.com/docs/claude-tag/overview): an organization-managed @Claude in Slack that runs on the same cloud infrastructure

Details

20 background: 'var(--ce-surface)',20 background: 'var(--ce-surface)',

21 border: '0.5px solid var(--ce-border-subtle)'21 border: '0.5px solid var(--ce-border-subtle)'

22 }}>{children}</code>, []);22 }}>{children}</code>, []);

23 const commandsNote = useMemo(() => <>Commands and skills are now the same mechanism. For new workflows, use <A href="/en/skills">skills/</A> instead: same <C>/name</C> invocation, plus you can bundle supporting files.</>, []);23 const commandsNote = useMemo(() => <>Commands and skills are now the same mechanism. For new workflows, use <A href="/docs/en/skills">skills/</A> instead: same <C>/name</C> invocation, plus you can bundle supporting files.</>, []);

24 const FILE_TREE = useMemo(() => ({24 const FILE_TREE = useMemo(() => ({

25 project: {25 project: {

26 label: 'your-project/',26 label: 'your-project/',


34 oneLiner: 'Project instructions Claude reads every session',34 oneLiner: 'Project instructions Claude reads every session',

35 when: 'Loaded into context at the start of every session',35 when: 'Loaded into context at the start of every session',

36 description: 'Project-specific instructions that shape how Claude works in this repository. Put your conventions, common commands, and architectural context here so Claude operates with the same assumptions your team does.',36 description: 'Project-specific instructions that shape how Claude works in this repository. Put your conventions, common commands, and architectural context here so Claude operates with the same assumptions your team does.',

37 tips: ['Target under 200 lines. Longer files still load in full but may reduce adherence', <>CLAUDE.md loads into every session. If something only matters for specific tasks, move it to a <A href="/en/skills">skill</A> or a path-scoped <A href="/en/memory#organize-rules-with-claude/rules/">rule</A> so it loads only when needed</>, 'List the commands you run most, like build, test, and format, so Claude knows them without you spelling them out each time', <>Run <C>/memory</C> to open and edit CLAUDE.md from within a session</>, <>Also works at <C>.claude/CLAUDE.md</C> if you prefer to keep the project root clean</>],37 tips: ['Target under 200 lines. Longer files still load in full but may reduce adherence', <>CLAUDE.md loads into every session. If something only matters for specific tasks, move it to a <A href="/docs/en/skills">skill</A> or a path-scoped <A href="/docs/en/memory#organize-rules-with-claude/rules/">rule</A> so it loads only when needed</>, 'List the commands you run most, like build, test, and format, so Claude knows them without you spelling them out each time', <>Run <C>/memory</C> to open and edit CLAUDE.md from within a session</>, <>Also works at <C>.claude/CLAUDE.md</C> if you prefer to keep the project root clean</>],

38 exampleIntro: 'This example is for a TypeScript and React project. It lists the build and test commands, the framework conventions Claude should follow, and project-specific rules like export style and file layout.',38 exampleIntro: 'This example is for a TypeScript and React project. It lists the build and test commands, the framework conventions Claude should follow, and project-specific rules like export style and file layout.',

39 example: `# Project conventions39 example: `# Project conventions

40 40 


60 color: '#9B7BC4',60 color: '#9B7BC4',

61 badge: 'committed',61 badge: 'committed',

62 oneLiner: 'Project-scoped MCP servers, shared with your team',62 oneLiner: 'Project-scoped MCP servers, shared with your team',

63 when: <>Servers connect when the session begins. Tool schemas are deferred by default and load on demand via <A href="/en/mcp#scale-with-mcp-tool-search">tool search</A></>,63 when: <>Servers connect when the session begins. Tool schemas are deferred by default and load on demand via <A href="/docs/en/mcp#scale-with-mcp-tool-search">tool search</A></>,

64 description: <>Configures Model Context Protocol (MCP) servers that give Claude access to external tools: databases, APIs, browsers, and more. This file holds the project-scoped servers your whole team uses. Personal servers you want to keep to yourself go in <C>~/.claude.json</C> instead.</>,64 description: <>Configures Model Context Protocol (MCP) servers that give Claude access to external tools: databases, APIs, browsers, and more. This file holds the project-scoped servers your whole team uses. Personal servers you want to keep to yourself go in <C>~/.claude.json</C> instead.</>,

65 tips: [<>Use environment variable references for secrets: <C>{'${NOTION_TOKEN}'}</C></>, <>Lives at the project root, not inside <C>.claude/</C></>, <>For servers only you need, run <C>claude mcp add --scope user</C>. This writes to <C>~/.claude.json</C> instead of <C>.mcp.json</C></>],65 tips: [<>Use environment variable references for secrets: <C>{'${NOTION_TOKEN}'}</C></>, <>Lives at the project root, not inside <C>.claude/</C></>, <>For servers only you need, run <C>claude mcp add --scope user</C>. This writes to <C>~/.claude.json</C> instead of <C>.mcp.json</C></>],

66 exampleIntro: <>This example configures the Notion MCP server so Claude can read and update pages in your workspace. The <C>{'${NOTION_TOKEN}'}</C> reference is read from your shell environment when Claude Code starts the server, so the token never lands in the file.</>,66 exampleIntro: <>This example configures the Notion MCP server so Claude can read and update pages in your workspace. The <C>{'${NOTION_TOKEN}'}</C> reference is read from your shell environment when Claude Code starts the server, so the token never lands in the file.</>,


86 oneLiner: 'Gitignored files to copy into new worktrees',86 oneLiner: 'Gitignored files to copy into new worktrees',

87 when: <>Read when Claude creates a git worktree via <C>--worktree</C>, the <C>EnterWorktree</C> tool, or subagent <C>isolation: worktree</C></>,87 when: <>Read when Claude creates a git worktree via <C>--worktree</C>, the <C>EnterWorktree</C> tool, or subagent <C>isolation: worktree</C></>,

88 description: <>Lists gitignored files to copy from your main repository into each new worktree. Worktrees are fresh checkouts, so untracked files like <C>.env</C> are missing by default. Patterns here use <C>.gitignore</C> syntax. Only files that match a pattern and are also gitignored get copied, so tracked files are never duplicated.</>,88 description: <>Lists gitignored files to copy from your main repository into each new worktree. Worktrees are fresh checkouts, so untracked files like <C>.env</C> are missing by default. Patterns here use <C>.gitignore</C> syntax. Only files that match a pattern and are also gitignored get copied, so tracked files are never duplicated.</>,

89 tips: [<>Lives at the project root, not inside <C>.claude/</C></>, <>Git-only: if you configure a <A href="/en/hooks#worktreecreate">WorktreeCreate hook</A> for a different VCS, this file is not read. Copy files inside your hook script instead</>, <>Also applies to parallel sessions in the <A href="/en/desktop#work-in-parallel-with-sessions">desktop app</A></>],89 tips: [<>Lives at the project root, not inside <C>.claude/</C></>, <>Git-only: if you configure a <A href="/docs/en/hooks#worktreecreate">WorktreeCreate hook</A> for a different VCS, this file is not read. Copy files inside your hook script instead</>, <>Also applies to parallel sessions in the <A href="/docs/en/desktop#work-in-parallel-with-sessions">desktop app</A></>],

90 exampleIntro: 'This example copies your local environment files and a secrets config into every worktree Claude creates. Comments start with # and blank lines are ignored, same as .gitignore.',90 exampleIntro: 'This example copies your local environment files and a secrets config into every worktree Claude creates. Comments start with # and blank lines are ignored, same as .gitignore.',

91 example: `# Local environment91 example: `# Local environment

92.env92.env


102 icon: 'folder',102 icon: 'folder',

103 color: 'var(--ce-accent)',103 color: 'var(--ce-accent)',

104 oneLiner: 'Project-level configuration, rules, and extensions',104 oneLiner: 'Project-level configuration, rules, and extensions',

105 description: 'Everything Claude Code reads that is specific to this project. If you use git, commit most files here so your team shares them; a few, like settings.local.json, are automatically gitignored. Each file badge shows which.',105 description: 'Everything Claude Code reads that is specific to this project. If you use git, commit most files here so your team shares them; a few, like settings.local.json, are gitignored when Claude Code saves settings to them. Each file badge shows which.',

106 children: [{106 children: [{

107 id: 'settings-json',107 id: 'settings-json',

108 label: 'settings.json',108 label: 'settings.json',


113 oneLiner: 'Permissions, hooks, and configuration',113 oneLiner: 'Permissions, hooks, and configuration',

114 when: <>Overrides global <C>~/.claude/settings.json</C>. Local settings, CLI flags, and managed settings override this</>,114 when: <>Overrides global <C>~/.claude/settings.json</C>. Local settings, CLI flags, and managed settings override this</>,

115 description: 'Settings that Claude Code applies directly. Permissions control which commands and tools Claude can use; hooks run your scripts at specific points in a session. Unlike CLAUDE.md, which Claude reads as guidance, these are enforced whether Claude follows them or not.',115 description: 'Settings that Claude Code applies directly. Permissions control which commands and tools Claude can use; hooks run your scripts at specific points in a session. Unlike CLAUDE.md, which Claude reads as guidance, these are enforced whether Claude follows them or not.',

116 contains: [<><A href="/en/permissions">permissions</A>: allow, deny, or prompt before Claude uses specific tools or commands</>, <><A href="/en/hooks">hooks</A>: run your own scripts on events like before a tool call or after a file edit</>, <><A href="/en/statusline">statusLine</A>: customize the line shown at the bottom while Claude works</>, <><A href="/en/settings#available-settings">model</A>: pick a default model for this project</>, <><A href="/en/settings#environment-variables">env</A>: environment variables set in every session</>, <><A href="/en/output-styles">outputStyle</A>: select a custom system-prompt style from output-styles/</>],116 contains: [<><A href="/docs/en/permissions">permissions</A>: allow, deny, or prompt before Claude uses specific tools or commands</>, <><A href="/docs/en/hooks">hooks</A>: run your own scripts on events like before a tool call or after a file edit</>, <><A href="/docs/en/statusline">statusLine</A>: customize the line shown at the bottom while Claude works</>, <><A href="/docs/en/settings#available-settings">model</A>: pick a default model for this project</>, <><A href="/docs/en/settings#environment-variables">env</A>: environment variables set in every session</>, <><A href="/docs/en/output-styles">outputStyle</A>: select a custom system-prompt style from output-styles/</>],

117 tips: [<>Bash permission patterns support wildcards: <C>Bash(npm test *)</C> matches any command starting with <C>npm test</C></>, <>Array settings like <C>permissions.allow</C> combine across all scopes; scalar settings like <C>model</C> use the most specific value</>],117 tips: [<>Bash permission patterns support wildcards: <C>Bash(npm test *)</C> matches any command starting with <C>npm test</C></>, <>Array settings like <C>permissions.allow</C> combine across all scopes; scalar settings like <C>model</C> use the most specific value</>],

118 exampleIntro: <>This example allows <C>npm test</C> and <C>npm run</C> commands without prompting, blocks <C>rm -rf</C>, and runs Prettier on files after Claude edits or writes them.</>,118 exampleIntro: <>This example allows <C>npm test</C> and <C>npm run</C> commands without prompting, blocks <C>rm -rf</C>, and runs Prettier on files after Claude edits or writes them.</>,

119 example: `{119 example: `{


146 badge: 'gitignored',146 badge: 'gitignored',

147 oneLiner: 'Your personal settings overrides for this project',147 oneLiner: 'Your personal settings overrides for this project',

148 when: 'Highest of the user-editable settings files; CLI flags and managed settings still take precedence',148 when: 'Highest of the user-editable settings files; CLI flags and managed settings still take precedence',

149 description: 'Personal settings that take precedence over the project defaults. Same JSON format as settings.json, but not committed. Use this when you need different permissions or defaults than the team config.',149 description: 'Personal settings that take precedence over the project defaults. Same JSON format as settings.json, gitignored when Claude Code saves a setting to it. Use this when you need different permissions or defaults than the team config.',

150 tips: [<>Same schema as settings.json. Array settings like <C>permissions.allow</C> combine across scopes; scalar settings like <C>model</C> use the local value</>, <>Claude Code adds this file to <C>~/.config/git/ignore</C> the first time it writes one. If you use a custom <C>core.excludesFile</C>, add the pattern there too. To share the ignore rule with your team, also add it to the project <C>.gitignore</C></>],150 tips: [<>Same schema as settings.json. Array settings like <C>permissions.allow</C> combine across scopes; scalar settings like <C>model</C> use the local value</>, <>When Claude Code saves a setting to this file in a repository that doesn't already ignore it, it adds <C>**/.claude/settings.local.json</C> to your global git excludes file: <C>core.excludesFile</C> from your global git config when it's set to an absolute or <C>~</C>-prefixed path, otherwise <C>$XDG_CONFIG_HOME/git/ignore</C>, or <C>~/.config/git/ignore</C>. To share the ignore rule with your team, also add it to the project <C>.gitignore</C></>],

151 exampleIntro: 'This example adds Docker permissions on top of whatever the team settings.json allows.',151 exampleIntro: 'This example adds Docker permissions on top of whatever the team settings.json allows.',

152 example: `{152 example: `{

153 "permissions": {153 "permissions": {


165 color: '#9B7BC4',165 color: '#9B7BC4',

166 oneLiner: 'Topic-scoped instructions, optionally gated by file paths',166 oneLiner: 'Topic-scoped instructions, optionally gated by file paths',

167 when: <>Rules without <C>paths:</C> load at session start. Rules with <C>paths:</C> load when a matching file enters context</>,167 when: <>Rules without <C>paths:</C> load at session start. Rules with <C>paths:</C> load when a matching file enters context</>,

168 description: [<>Project instructions split into topic files that can load conditionally based on file paths. A rule without <C>paths:</C> frontmatter loads at session start like CLAUDE.md; a rule with <C>paths:</C> loads only when Claude reads a matching file.</>, <>Like CLAUDE.md, rules are guidance Claude reads, not configuration Claude Code enforces. For guaranteed behavior use <A href="/en/hooks">hooks</A> or <A href="/en/permissions">permissions</A>.</>],168 description: [<>Project instructions split into topic files that can load conditionally based on file paths. A rule without <C>paths:</C> frontmatter loads at session start like CLAUDE.md; a rule with <C>paths:</C> loads only when Claude reads a matching file.</>, <>Like CLAUDE.md, rules are guidance Claude reads, not configuration Claude Code enforces. For guaranteed behavior use <A href="/docs/en/hooks">hooks</A> or <A href="/docs/en/permissions">permissions</A>.</>],

169 tips: [<>Use <C>paths:</C> frontmatter with globs to scope rules to directories or file types</>, <>Subdirectories work: <C>.claude/rules/frontend/react.md</C> is discovered automatically</>, 'When CLAUDE.md approaches 200 lines, start splitting into rules'],169 tips: [<>Use <C>paths:</C> frontmatter with globs to scope rules to directories or file types</>, <>Subdirectories work: <C>.claude/rules/frontend/react.md</C> is discovered automatically</>, 'When CLAUDE.md approaches 200 lines, start splitting into rules'],

170 docsLink: '/en/memory#organize-rules-with-claude/rules/',170 docsLink: '/en/memory#organize-rules-with-claude/rules/',

171 children: [{171 children: [{


369 color: '#C46686',369 color: '#C46686',

370 oneLiner: 'Dynamic workflow scripts that orchestrate many subagents',370 oneLiner: 'Dynamic workflow scripts that orchestrate many subagents',

371 when: 'Loaded at startup; each file becomes a /<name> command',371 when: 'Loaded at startup; each file becomes a /<name> command',

372 description: <>Each <C>.js</C> file is a <A href="/en/workflows">dynamic workflow</A>: a script the runtime executes to spawn and coordinate many subagents. Workflows are written by Claude and saved here from <C>/workflows</C> rather than authored from scratch.</>,372 description: <>Each <C>.js</C> file is a <A href="/docs/en/workflows">dynamic workflow</A>: a script the runtime executes to spawn and coordinate many subagents. Workflows are written by Claude and saved here from <C>/workflows</C> rather than authored from scratch.</>,

373 tips: [<>Save a run from <C>/workflows</C> with <C>s</C> to create one of these</>, <>A project workflow takes precedence over a personal one in <C>~/.claude/workflows/</C> with the same name</>],373 tips: [<>Save a run from <C>/workflows</C> with <C>s</C> to create one of these</>, <>A project workflow takes precedence over a personal one in <C>~/.claude/workflows/</C> with the same name</>],

374 docsLink: '/en/workflows'374 docsLink: '/en/workflows'

375 }, {375 }, {


382 autogen: true,382 autogen: true,

383 oneLiner: 'Subagent persistent memory, separate from your main session auto memory',383 oneLiner: 'Subagent persistent memory, separate from your main session auto memory',

384 when: 'First 200 lines (capped at 25KB) of MEMORY.md loaded into the subagent system prompt when it runs',384 when: 'First 200 lines (capped at 25KB) of MEMORY.md loaded into the subagent system prompt when it runs',

385 description: <>Subagents with <C>memory: project</C> in their frontmatter get a dedicated memory directory here. This is distinct from your <A href="/en/memory#auto-memory">main session auto memory</A> at <C>~/.claude/projects/</C>: each subagent reads and writes its own MEMORY.md, not yours.</>,385 description: <>Subagents with <C>memory: project</C> in their frontmatter get a dedicated memory directory here. This is distinct from your <A href="/docs/en/memory#auto-memory">main session auto memory</A> at <C>~/.claude/projects/</C>: each subagent reads and writes its own MEMORY.md, not yours.</>,

386 tips: [<>Only created for subagents that set the <C>memory:</C> frontmatter field</>, <>This directory holds project-scoped subagent memory, meant to be shared with your team. To keep memory out of version control use <C>memory: local</C>, which writes to <C>.claude/agent-memory-local/</C> instead. For cross-project memory use <C>memory: user</C>, which writes to <C>~/.claude/agent-memory/</C></>, <>The main session auto memory is a different feature; see <C>~/.claude/projects/</C> in the Global tab</>],386 tips: [<>Only created for subagents that set the <C>memory:</C> frontmatter field</>, <>This directory holds project-scoped subagent memory, meant to be shared with your team. To keep memory out of version control use <C>memory: local</C>, which writes to <C>.claude/agent-memory-local/</C> instead. For cross-project memory use <C>memory: user</C>, which writes to <C>~/.claude/agent-memory/</C></>, <>The main session auto memory is a different feature; see <C>~/.claude/projects/</C> in the Global tab</>],

387 docsLink: '/en/sub-agents#enable-persistent-memory',387 docsLink: '/en/sub-agents#enable-persistent-memory',

388 children: [{388 children: [{


402 autogen: true,402 autogen: true,

403 oneLiner: 'The subagent writes and maintains this file automatically',403 oneLiner: 'The subagent writes and maintains this file automatically',

404 when: 'Loaded into the subagent system prompt when the subagent starts',404 when: 'Loaded into the subagent system prompt when the subagent starts',

405 description: <>Works the same as your <A href="/en/memory#auto-memory">main auto memory</A>: the subagent creates and updates this file itself. You do not write it. The subagent reads it at the start of each task and writes back what it learns.</>,405 description: <>Works the same as your <A href="/docs/en/memory#auto-memory">main auto memory</A>: the subagent creates and updates this file itself. You do not write it. The subagent reads it at the start of each task and writes back what it learns.</>,

406 example: `# code-reviewer memory406 example: `# code-reviewer memory

407 407 

408## Patterns seen408## Patterns seen


1432 1432 

1433Claude Code reads instructions, settings, skills, subagents, and memory from your project directory and from `~/.claude` in your home directory. Commit project files to git to share them with your team; files in `~/.claude` are personal configuration that applies across all your projects.1433Claude Code reads instructions, settings, skills, subagents, and memory from your project directory and from `~/.claude` in your home directory. Commit project files to git to share them with your team; files in `~/.claude` are personal configuration that applies across all your projects.

1434 1434 

1435On Windows, `~/.claude` resolves to `%USERPROFILE%\.claude`. If you set [`CLAUDE_CONFIG_DIR`](/en/env-vars), every `~/.claude` path on this page lives under that directory instead.1435On Windows, `~/.claude` resolves to `%USERPROFILE%\.claude`. If you set [`CLAUDE_CONFIG_DIR`](/docs/en/env-vars), every `~/.claude` path on this page lives under that directory instead.

1436 1436 

1437Most users only edit `CLAUDE.md` and `settings.json`. The rest of the directory is optional: add skills, rules, or subagents as you need them.1437Most users only edit `CLAUDE.md` and `settings.json`. The rest of the directory is optional: add skills, rules, or subagents as you need them.

1438 1438 


1448 1448 

1449| File | Location | Purpose |1449| File | Location | Purpose |

1450| ----------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |1450| ----------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

1451| `managed-settings.json` | System-level, varies by OS | Enterprise-enforced settings that you can't override. See [server-managed settings](/en/server-managed-settings). |1451| `managed-settings.json` | System-level, varies by OS | Enterprise-enforced settings that you can't override. See [server-managed settings](/docs/en/server-managed-settings). |

1452| `CLAUDE.local.md` | Project root | Your private preferences for this project, loaded alongside CLAUDE.md. Create it manually and add it to `.gitignore`. |1452| `CLAUDE.local.md` | Project root | Your private preferences for this project, loaded alongside CLAUDE.md. Create it manually and add it to `.gitignore`. |

1453| Installed plugins | `~/.claude/plugins` | Cloned marketplaces, installed plugin versions, and per-plugin data, managed by `claude plugin` commands. Orphaned versions are deleted 14 days after a plugin update or uninstall. See [plugin caching](/en/plugins-reference#plugin-caching-and-file-resolution). |1453| Installed plugins | `~/.claude/plugins` | Cloned marketplaces, installed plugin versions, and per-plugin data, managed by `claude plugin` commands. Orphaned versions are deleted 14 days after a plugin update or uninstall. See [plugin caching](/docs/en/plugins-reference#plugin-caching-and-file-resolution). |

1454 1454 

1455`~/.claude` also holds data Claude Code writes as you work: transcripts, prompt history, file snapshots, caches, and logs. See [application data](#application-data) below.1455`~/.claude` also holds data Claude Code writes as you work: transcripts, prompt history, file snapshots, caches, and logs. See [application data](#application-data) below.

1456 1456 


1460 1460 

1461| You want to | Edit | Scope | Reference |1461| You want to | Edit | Scope | Reference |

1462| :------------------------------------------------- | :--------------------------------------- | :---------------- | :------------------------------------------------- |1462| :------------------------------------------------- | :--------------------------------------- | :---------------- | :------------------------------------------------- |

1463| Give Claude project context and conventions | `CLAUDE.md` | project or global | [Memory](/en/memory) |1463| Give Claude project context and conventions | `CLAUDE.md` | project or global | [Memory](/docs/en/memory) |

1464| Allow or block specific tool calls | `settings.json` `permissions` or `hooks` | project or global | [Permissions](/en/permissions), [Hooks](/en/hooks) |1464| Allow or block specific tool calls | `settings.json` `permissions` or `hooks` | project or global | [Permissions](/docs/en/permissions), [Hooks](/docs/en/hooks) |

1465| Run a script before or after tool calls | `settings.json` `hooks` | project or global | [Hooks](/en/hooks) |1465| Run a script before or after tool calls | `settings.json` `hooks` | project or global | [Hooks](/docs/en/hooks) |

1466| Set environment variables for the session | `settings.json` `env` | project or global | [Settings](/en/settings#available-settings) |1466| Set environment variables for the session | `settings.json` `env` | project or global | [Settings](/docs/en/settings#available-settings) |

1467| Keep personal overrides out of git | `settings.local.json` | project only | [Settings scopes](/en/settings#settings-files) |1467| Keep personal overrides out of git | `settings.local.json` | project only | [Settings scopes](/docs/en/settings#settings-files) |

1468| Add a prompt or capability you invoke with `/name` | `skills/<name>/SKILL.md` | project or global | [Skills](/en/skills) |1468| Add a prompt or capability you invoke with `/name` | `skills/<name>/SKILL.md` | project or global | [Skills](/docs/en/skills) |

1469| Define a specialized subagent with its own tools | `agents/*.md` | project or global | [Subagents](/en/sub-agents) |1469| Define a specialized subagent with its own tools | `agents/*.md` | project or global | [Subagents](/docs/en/sub-agents) |

1470| Orchestrate many subagents from a script | `workflows/*.js` | project or global | [Dynamic workflows](/en/workflows) |1470| Orchestrate many subagents from a script | `workflows/*.js` | project or global | [Dynamic workflows](/docs/en/workflows) |

1471| Connect external tools over MCP | `.mcp.json` | project only | [MCP](/en/mcp) |1471| Connect external tools over MCP | `.mcp.json` | project only | [MCP](/docs/en/mcp) |

1472| Change how Claude formats responses | `output-styles/*.md` | project or global | [Output styles](/en/output-styles) |1472| Change how Claude formats responses | `output-styles/*.md` | project or global | [Output styles](/docs/en/output-styles) |

1473 1473 

1474## File reference1474## File reference

1475 1475 


1478<Note>1478<Note>

1479 Several things can override what you put in these files:1479 Several things can override what you put in these files:

1480 1480 

1481 * [Managed settings](/en/server-managed-settings) deployed by your organization take precedence over everything1481 * [Managed settings](/docs/en/server-managed-settings) deployed by your organization take precedence over everything

1482 * CLI flags like `--permission-mode` or `--settings` override `settings.json` for that session1482 * CLI flags like `--permission-mode` or `--settings` override `settings.json` for that session

1483 * Some environment variables take precedence over their equivalent setting, but this varies: check the [environment variables reference](/en/env-vars) for each one1483 * Some environment variables take precedence over their equivalent setting, but this varies: check the [environment variables reference](/docs/en/env-vars) for each one

1484 1484 

1485 See [settings precedence](/en/settings#settings-precedence) for the full order.1485 See [settings precedence](/docs/en/settings#settings-precedence) for the full order.

1486</Note>1486</Note>

1487 1487 

1488Click a filename to open that node in the explorer above.1488Click a filename to open that node in the explorer above.

1489 1489 

1490| File | Scope | Commit | What it does | Reference |1490| File | Scope | Commit | What it does | Reference |

1491| --------------------------------------------------- | ------------------ | ------ | ------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |1491| --------------------------------------------------- | ------------------ | ------ | ------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |

1492| [`CLAUDE.md`](#ce-claude-md) | Project and global | ✓ | Instructions loaded every session | [Memory](/en/memory) |1492| [`CLAUDE.md`](#ce-claude-md) | Project and global | ✓ | Instructions loaded every session | [Memory](/docs/en/memory) |

1493| [`rules/*.md`](#ce-rules) | Project and global | ✓ | Topic-scoped instructions, optionally path-gated | [Rules](/en/memory#organize-rules-with-claude/rules/) |1493| [`rules/*.md`](#ce-rules) | Project and global | ✓ | Topic-scoped instructions, optionally path-gated | [Rules](/docs/en/memory#organize-rules-with-claude/rules/) |

1494| [`settings.json`](#ce-settings-json) | Project and global | ✓ | Permissions, hooks, env vars, model defaults | [Settings](/en/settings) |1494| [`settings.json`](#ce-settings-json) | Project and global | ✓ | Permissions, hooks, env vars, model defaults | [Settings](/docs/en/settings) |

1495| [`settings.local.json`](#ce-settings-local-json) | Project only | | Your personal overrides, gitignored when Claude Code creates it | [Settings scopes](/en/settings#settings-files) |1495| [`settings.local.json`](#ce-settings-local-json) | Project only | | Your personal overrides, gitignored when Claude Code saves a setting to it | [Settings scopes](/docs/en/settings#settings-files) |

1496| [`.mcp.json`](#ce-mcp-json) | Project only | ✓ | Team-shared MCP servers | [MCP scopes](/en/mcp#mcp-installation-scopes) |1496| [`.mcp.json`](#ce-mcp-json) | Project only | ✓ | Team-shared MCP servers | [MCP scopes](/docs/en/mcp#mcp-installation-scopes) |

1497| [`.worktreeinclude`](#ce-worktreeinclude) | Project only | ✓ | Gitignored files to copy into new worktrees | [Worktrees](/en/worktrees#copy-gitignored-files-into-worktrees) |1497| [`.worktreeinclude`](#ce-worktreeinclude) | Project only | ✓ | Gitignored files to copy into new worktrees | [Worktrees](/docs/en/worktrees#copy-gitignored-files-into-worktrees) |

1498| [`skills/<name>/SKILL.md`](#ce-skills) | Project and global | ✓ | Reusable prompts invoked with `/name` or auto-invoked | [Skills](/en/skills) |1498| [`skills/<name>/SKILL.md`](#ce-skills) | Project and global | ✓ | Reusable prompts invoked with `/name` or auto-invoked | [Skills](/docs/en/skills) |

1499| [`commands/*.md`](#ce-commands) | Project and global | ✓ | Single-file prompts; same mechanism as skills | [Skills](/en/skills) |1499| [`commands/*.md`](#ce-commands) | Project and global | ✓ | Single-file prompts; same mechanism as skills | [Skills](/docs/en/skills) |

1500| [`output-styles/*.md`](#ce-output-styles) | Project and global | ✓ | Custom system-prompt sections | [Output styles](/en/output-styles) |1500| [`output-styles/*.md`](#ce-output-styles) | Project and global | ✓ | Custom system-prompt sections | [Output styles](/docs/en/output-styles) |

1501| [`agents/*.md`](#ce-agents) | Project and global | ✓ | Subagent definitions with their own prompt and tools | [Subagents](/en/sub-agents) |1501| [`agents/*.md`](#ce-agents) | Project and global | ✓ | Subagent definitions with their own prompt and tools | [Subagents](/docs/en/sub-agents) |

1502| [`workflows/*.js`](#ce-workflows) | Project and global | ✓ | Dynamic workflow scripts written by Claude and saved from `/workflows`; each file becomes a `/<name>` command | [Dynamic workflows](/en/workflows) |1502| [`workflows/*.js`](#ce-workflows) | Project and global | ✓ | Dynamic workflow scripts written by Claude and saved from `/workflows`; each file becomes a `/<name>` command | [Dynamic workflows](/docs/en/workflows) |

1503| [`agent-memory/<name>/`](#ce-agent-memory) | Project and global | ✓ | Persistent memory for subagents | [Persistent memory](/en/sub-agents#enable-persistent-memory) |1503| [`agent-memory/<name>/`](#ce-agent-memory) | Project and global | ✓ | Persistent memory for subagents | [Persistent memory](/docs/en/sub-agents#enable-persistent-memory) |

1504| [`~/.claude.json`](#ce-claude-json) | Global only | | App state, OAuth, UI toggles, personal MCP servers | [Global config](/en/settings#global-config-settings) |1504| [`~/.claude.json`](#ce-claude-json) | Global only | | App state, OAuth, UI toggles, personal MCP servers | [Global config](/docs/en/settings#global-config-settings) |

1505| [`projects/<project>/memory/`](#ce-global-projects) | Global only | | Auto memory: Claude's notes to itself across sessions | [Auto memory](/en/memory#auto-memory) |1505| [`projects/<project>/memory/`](#ce-global-projects) | Global only | | Auto memory: Claude's notes to itself across sessions | [Auto memory](/docs/en/memory#auto-memory) |

1506| [`keybindings.json`](#ce-keybindings) | Global only | | Custom keyboard shortcuts | [Keybindings](/en/keybindings) |1506| [`keybindings.json`](#ce-keybindings) | Global only | | Custom keyboard shortcuts | [Keybindings](/docs/en/keybindings) |

1507| [`themes/*.json`](#ce-themes) | Global only | | Custom color themes | [Custom themes](/en/terminal-config#create-a-custom-theme) |1507| [`themes/*.json`](#ce-themes) | Global only | | Custom color themes | [Custom themes](/docs/en/terminal-config#create-a-custom-theme) |

1508 1508 

1509## Troubleshoot configuration1509## Troubleshoot configuration

1510 1510 

1511If a setting, hook, or file isn't taking effect, see [Debug your configuration](/en/debug-your-config) for the inspection commands and a symptom-first lookup table.1511If a setting, hook, or file isn't taking effect, see [Debug your configuration](/docs/en/debug-your-config) for the inspection commands and a symptom-first lookup table.

1512 1512 

1513## Application data1513## Application data

1514 1514 


1516 1516 

1517### Cleaned up automatically1517### Cleaned up automatically

1518 1518 

1519Files in the paths below are deleted on startup once they're older than [`cleanupPeriodDays`](/en/settings#available-settings). The default is 30 days.1519Files in the paths below are deleted on startup once they're older than [`cleanupPeriodDays`](/docs/en/settings#available-settings). The default is 30 days.

1520 1520 

1521| Path under `~/.claude/` | Contents |1521| Path under `~/.claude/` | Contents |

1522| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |1522| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

1523| `projects/<project>/<session>.jsonl` | Full conversation transcript: every message, tool call, and tool result |1523| `projects/<project>/<session>.jsonl` | Full conversation transcript: every message, tool call, and tool result |

1524| `projects/<project>/<session>/subagents/` | [Subagent](/en/sub-agents) conversation transcripts, removed with the parent session transcript when it ages out |1524| `projects/<project>/<session>/subagents/` | [Subagent](/docs/en/sub-agents) conversation transcripts, removed with the parent session transcript when it ages out |

1525| `projects/<project>/<session>/tool-results/` | Large tool outputs spilled to separate files |1525| `projects/<project>/<session>/tool-results/` | Large tool outputs spilled to separate files |

1526| `file-history/<session>/` | Pre-edit snapshots of files Claude changed, used for [checkpoint restore](/en/checkpointing). Holds snapshots for the 100 most recent checkpoints; snapshot files that no retained checkpoint references are deleted, except each file's first snapshot |1526| `file-history/<session>/` | Pre-edit snapshots of files Claude changed, used for [checkpoint restore](/docs/en/checkpointing). Holds snapshots for the 100 most recent checkpoints; snapshot files that no retained checkpoint references are deleted, except each file's first snapshot |

1527| `plans/` | Plan files written during [plan mode](/en/permission-modes#analyze-before-you-edit-with-plan-mode) |1527| `plans/` | Plan files written during [plan mode](/docs/en/permission-modes#analyze-before-you-edit-with-plan-mode) |

1528| `debug/` | Per-session debug logs, written only when you start with `--debug` or run `/debug` |1528| `debug/` | Per-session debug logs, written only when you start with `--debug` or run `/debug` |

1529| `paste-cache/`, `image-cache/` | Contents of large pastes and attached images |1529| `paste-cache/`, `image-cache/` | Contents of large pastes and attached images |

1530| `session-env/` | Per-session environment metadata |1530| `session-env/` | Per-session environment metadata |

1531| `tasks/` | Per-session task lists written by the task tools |1531| `tasks/` | Per-session task lists written by the task tools |

1532| `shell-snapshots/` | Aliases, functions, and shell options captured at startup and applied by the [Bash tool](/en/tools-reference#bash-tool-behavior) to each command. Removed on clean exit. The sweep clears any left after a crash. |1532| `shell-snapshots/` | Aliases, functions, and shell options captured at startup and applied by the [Bash tool](/docs/en/tools-reference#bash-tool-behavior) to each command. Removed on clean exit. The sweep clears any left after a crash. |

1533| `backups/` | Timestamped copies of `~/.claude.json` taken before config migrations |1533| `backups/` | Timestamped copies of `~/.claude.json` taken before config migrations |

1534| `feedback-bundles/` | Redacted transcript archives written by `/feedback` on third-party providers or when no Anthropic credentials are configured, for sending to your Anthropic account team |1534| `feedback-bundles/` | Redacted transcript archives written by `/feedback` on third-party providers or when no Anthropic credentials are configured, for sending to your Anthropic account team |

1535| `todos/`, `statsig/`, `logs/` | Legacy directories from older versions. No longer written. The sweep removes their contents and then the empty directory. |1535| `todos/`, `statsig/`, `logs/` | Legacy directories from older versions. No longer written. The sweep removes their contents and then the empty directory. |


1544| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |1544| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

1545| `history.jsonl` | Every prompt you've typed, with timestamp and project path. Used for up-arrow recall. |1545| `history.jsonl` | Every prompt you've typed, with timestamp and project path. Used for up-arrow recall. |

1546| `stats-cache.json` | Aggregated token and cost counts shown by `/usage` |1546| `stats-cache.json` | Aggregated token and cost counts shown by `/usage` |

1547| `remote-settings.json` | Cached copy of [server-managed settings](/en/server-managed-settings) for your organization. Only present when your organization has configured them. Refreshed on each launch. |1547| `remote-settings.json` | Cached copy of [server-managed settings](/docs/en/server-managed-settings) for your organization. Only present when your organization has configured them. Refreshed on each launch. |

1548| `cache/changelog.md` | Cached copy of the Claude Code changelog, used to show release notes after an update. Refreshed in the background. |1548| `cache/changelog.md` | Cached copy of the Claude Code changelog, used to show release notes after an update. Refreshed in the background. |

1549| `policy-limits.json` | Cached feature policy settings for your organization. Only present for some account types. Refreshed automatically. |1549| `policy-limits.json` | Cached feature policy settings for your organization. Only present for some account types. Refreshed automatically. |

1550 1550 


1555Transcripts and history are not encrypted at rest. OS file permissions are the only protection. If a tool reads a `.env` file or a command prints a credential, that value is written to `projects/<project>/<session>.jsonl`. To reduce exposure:1555Transcripts and history are not encrypted at rest. OS file permissions are the only protection. If a tool reads a `.env` file or a command prints a credential, that value is written to `projects/<project>/<session>.jsonl`. To reduce exposure:

1556 1556 

1557* Lower `cleanupPeriodDays` to shorten how long transcripts are kept1557* Lower `cleanupPeriodDays` to shorten how long transcripts are kept

1558* Set the [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](/en/env-vars) environment variable to skip writing transcripts and prompt history in any mode. In non-interactive mode, you can instead pass `--no-session-persistence` alongside `-p`, or set `persistSession: false` in the Agent SDK.1558* Set the [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](/docs/en/env-vars) environment variable to skip writing transcripts and prompt history in any mode. In non-interactive mode, you can instead pass `--no-session-persistence` alongside `-p`, or set `persistSession: false` in the Agent SDK.

1559* Use [permission rules](/en/permissions) to deny reads of credential files1559* Use [permission rules](/docs/en/permissions) to deny reads of credential files

1560 1560 

1561### Clear local data1561### Clear local data

1562 1562 


1632 1632 

1633## Related resources1633## Related resources

1634 1634 

1635* [Manage Claude's memory](/en/memory): write and organize CLAUDE.md, rules, and auto memory1635* [Manage Claude's memory](/docs/en/memory): write and organize CLAUDE.md, rules, and auto memory

1636* [Configure settings](/en/settings): set permissions, hooks, environment variables, and model defaults1636* [Configure settings](/docs/en/settings): set permissions, hooks, environment variables, and model defaults

1637* [Create skills](/en/skills): build reusable prompts and workflows1637* [Create skills](/docs/en/skills): build reusable prompts and workflows

1638* [Configure subagents](/en/sub-agents): define specialized agents with their own context1638* [Configure subagents](/docs/en/sub-agents): define specialized agents with their own context

Details

29/plugin install claude-security@claude-plugins-official29/plugin install claude-security@claude-plugins-official

30```30```

31 31 

32<Note>32If the install fails, the fix depends on which message Claude Code reports:

33 If Claude Code reports that the marketplace is not found, run `/plugin marketplace add anthropics/claude-plugins-official` first, then retry the install.33 

34</Note>34* If it reports `Marketplace "claude-plugins-official" not found`, add the marketplace with `/plugin marketplace add anthropics/claude-plugins-official`, then retry the install.

35* If it reports that it can't find the plugin in the marketplace, check the plugin name for a typo, then refresh your local copy of the marketplace with `/plugin marketplace update claude-plugins-official` and retry the install.

35 36 

36Then activate the plugin in the current session with `/reload-plugins`, which applies pending plugin changes without a restart:37Then activate the plugin in the current session with `/reload-plugins`, which applies pending plugin changes without a restart:

37 38 

cloud-environments.md +663 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Configure cloud environments

6 

7> Configure cloud environments for Claude Code cloud sessions: network access levels, environment variables, setup scripts, and environment caching.

8 

9<Note>

10 Cloud environments require [Claude Code on the web](/docs/en/claude-code-on-the-web), which is in research preview for Pro, Max, and Team users, and for Enterprise users with [premium seats or Chat + Claude Code seats](https://support.claude.com/en/articles/11845131-use-claude-code-with-your-team-or-enterprise-plan).

11</Note>

12 

13Each [cloud session](/docs/en/claude-code-on-the-web) runs in a cloud environment. You can configure an environment to allow or deny [network access](#access-levels), set environment variables for the session, and run a [setup script](#setup-scripts) before Claude starts working.

14 

15The same environments apply wherever you start a cloud session: [Claude Code on the web](/docs/en/claude-code-on-the-web), the terminal with [`claude --cloud`](/docs/en/claude-code-on-the-web#from-terminal-to-web), [Claude Tag](https://claude.com/docs/claude-tag/overview), [routines](/docs/en/routines), the [Claude mobile app](/docs/en/mobile), and the [Desktop app](/docs/en/desktop).

16 

17<Info>

18 [Remote Control](/docs/en/remote-control) sessions connect the web and mobile interfaces to a session on your own machine, which uses your machine's network and files, not a cloud environment. Claude Tag channel sessions use [shared environments](#organization-shared-environments) only.

19</Info>

20 

21## The Default environment

22 

23Onboarding sets up the **Default** environment for you, whether you connect through [the web](/docs/en/web-quickstart#connect-github) or a CLI flow such as `/web-setup`; if web onboarding shows an environment form instead of creating the environment, keep the form's defaults to get the same **Default** environment. **Default** carries no configuration of its own:

24 

25* [**Trusted** network access](#access-levels): sessions reach package registries and other [allowlisted domains](#default-allowed-domains), and nothing else through the session's network.

26* No other configuration: **Default** defines no environment variables or setup script, so sessions start with just the [pre-installed tools](#installed-tools).

27 

28With only **Default** available, every session runs in it. When you have more than one environment, sessions choose one per surface:

29 

30* On the web, the Desktop app, and the mobile app, sessions use the environment shown in the [selector](#configure-your-environment). An admin-set [organization default](#organization-shared-environments) fills the selection when you haven't picked one.

31* From the CLI, sessions use your [`/remote-env` pick](#select-an-environment-from-the-cli), or fall back to your first available cloud environment.

32 

33Configure an environment when the default isn't enough: when Claude needs to reach domains outside the [default allowlist](#default-allowed-domains), needs environment variables set for its sessions, or needs dependencies installed before it starts working.

34 

35## Configure your environment

36 

37Create, edit, and archive environments from the environment selector at [claude.ai/code](https://claude.ai/code), which you reach after [web onboarding](/docs/en/web-quickstart). Environments you create are personal to your account; [shared environments](#organization-shared-environments) created by your admins appear in the same selector. See [Installed tools](#installed-tools) for what's available without any configuration.

38 

39<Steps>

40 <Step title="Open the environment selector">

41 On [claude.ai/code](https://claude.ai/code), select the cloud icon showing the current environment's name, in the row above the message box. There's no settings page or direct URL for the selector.

42 

43 <Frame>

44 <img src="https://mintcdn.com/claude-code/ZFId6l95856c5LSw/images/cloud-environment-selector.png?fit=max&auto=format&n=ZFId6l95856c5LSw&q=85&s=cc2813a5664519eaf5a89d793ce5af26" alt="The environment selector open above the message box at claude.ai/code. The cloud button showing the environment name Default sits in the row above the message box. The open menu lists a Local row with Download and Desktop only labels, a Cloud section where the Default environment is selected with a checkmark and shows a settings gear icon on hover, an Add cloud environment option, and a Remote Control section with setup instructions." width="1672" height="682" data-path="images/cloud-environment-selector.png" />

45 </Frame>

46 </Step>

47 

48 <Step title="Add or edit an environment">

49 Select **Add cloud environment**, or hover over an existing environment and select the settings icon that appears on the right. The dialog includes the name, network access level, environment variables, and setup script.

50 

51 <Frame>

52 <img src="https://mintcdn.com/claude-code/ZFId6l95856c5LSw/images/cloud-environment-dialog.png?fit=max&auto=format&n=ZFId6l95856c5LSw&q=85&s=30d4478b31d1f879f7ee287ddab32505" alt="The New cloud environment dialog. A Name field with the placeholder Default, a Network access selector set to Trusted with links to the network policy and access levels, an Environment variables box showing .env-format placeholder text with a note that values are visible to anyone using the environment, a Setup script box described as a Bash script that runs when a new session starts before Claude Code launches, and Cancel and Create environment buttons." width="874" height="1372" data-path="images/cloud-environment-dialog.png" />

53 </Frame>

54 </Step>

55</Steps>

56 

57### Set environment variables

58 

59Environment variables use `.env` format, one `KEY=value` pair per line. Plain values don't need quotes, and if you quote a value with a matching pair, the quotes don't become part of the value. Quote a value that spans multiple lines or contains a `#`: in an unquoted value, `#` starts a comment and the rest of the line is dropped.

60 

61The following example defines three variables.

62 

63```text theme={null}

64NODE_ENV=development

65LOG_LEVEL=debug

66DATABASE_URL=postgres://localhost:5432/myapp

67```

68 

69Each session copies the environment's values once, at startup, into ordinary environment variables that any command Claude runs can read. Because running sessions don't re-read the configuration, editing or adding variables affects sessions you start afterward; sessions already running keep the values they started with.

70 

71Anyone who uses the environment can read the values, and cloud environments have no dedicated secrets store, so don't add API keys or other credentials. If a session needs a credential anyway, see [What carries over from your setup](#what-carries-over-from-your-setup).

72 

73### Select an environment from the CLI

74 

75Run `/remote-env` in your terminal to choose the default environment for cloud sessions you create from the CLI, such as [`claude --cloud`](/docs/en/claude-code-on-the-web#from-terminal-to-web). The command opens a picker of your existing environments and saves your choice to the `remote.defaultEnvironmentId` key in your [user settings](/docs/en/settings#settings-files), so it applies in every project on your machine until you change it, unless the same key is set at a higher-precedence [settings layer](/docs/en/settings#settings-precedence), such as a repo's project settings.

76 

77`/remote-env` only sets the default: it doesn't start a session, and it can't add or edit environments. Manage them at [claude.ai/code](https://claude.ai/code).

78 

79### Archive an environment

80 

81To archive an environment, open it for editing and select **Archive**. You can't delete an environment, only archive it.

82 

83Archiving affects new sessions, not running ones:

84 

85* Sessions already running in the environment continue to work.

86* The environment disappears from the selector and from `/remote-env`, so you can't pick it for new sessions.

87* No new session can start in an archived environment, on any surface. If the environment was your saved [CLI default](#select-an-environment-from-the-cli), CLI cloud sessions fall back to your first available cloud environment. Anything configured with the environment explicitly, such as a [routine](/docs/en/routines#environments-and-network-access), can't start new sessions in it; point it at another environment.

88 

89### Organization-shared environments

90 

91Owners and admins on Team and Enterprise plans can create cloud environments that are shared with every member of the organization. Shared environments appear in each member's environment selector alongside their personal ones, so a team can standardize on one configuration instead of each member recreating it.

92 

93Create, edit, and archive shared environments from the **Cloud environments** page in [admin settings](https://claude.ai/admin-settings). Each shared environment has a name, a [network access level](#access-levels), [environment variables](#set-environment-variables) in `.env` format, and a [setup script](#setup-scripts). Owners and admins choose the organization's [default environment](#the-default-environment) separately, at [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code).

94 

95Values in a shared environment reach every member's sessions in that environment. Like personal environments, shared environments have no dedicated secrets store, so don't include secrets.

96 

97In [Claude Tag](https://claude.com/docs/claude-tag/overview) channels, Claude works as your organization's shared identity, not as any member, so channel sessions use shared environments only. You can set the environment a channel uses in two ways:

98 

99* Set a shared environment as the organization's [default environment](#the-default-environment) at [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code).

100* [Pin one to a channel](https://claude.com/docs/claude-tag/admins/troubleshooting#channel-sessions-use-the-wrong-environment-or-can%E2%80%99t-find-one) in the Claude Tag admin settings.

101 

102Shared environments add to members' selectors rather than replacing them.

103 

104## Network access

105 

106Each environment sets one network access level, which controls the outbound connections its sessions can make. The default level, **Trusted**, allows package registries and other [allowlisted domains](#default-allowed-domains); **Custom** takes your own domain list.

107 

108To change an environment's network access, [open it for editing](#configure-your-environment) and use the **Network access** selector in the dialog. The cloud icon that opens the selector appears on the app surfaces listed under [The Default environment](#the-default-environment) and in the [routine editor](/docs/en/routines#environments-and-network-access); personal environments don't have a separate page in your claude.ai account settings.

109 

110<Note>

111 MCP connectors you enable on a session or routine work without adding their hosts to **Allowed domains**, because connector traffic travels through Anthropic's servers rather than the session's network. You configure connectors per session or per routine; remove any you don't need to limit which tools Claude can reach. This relies on the same Anthropic-bound channel noted under [Security and isolation](/docs/en/claude-code-on-the-web#security-and-isolation).

112</Note>

113 

114### Access levels

115 

116The **Network access** field in the [environment dialog](#configure-your-environment) takes one of four levels:

117 

118| Level | Outbound connections |

119| :---------- | :------------------------------------------------------------------------------------------- |

120| **None** | No outbound network access through the session's network |

121| **Trusted** | [Allowlisted domains](#default-allowed-domains) only: package registries, GitHub, cloud SDKs |

122| **Full** | Any domain |

123| **Custom** | Your own allowlist, optionally including the defaults |

124 

125GitHub operations use a [separate proxy](#github-proxy) that is independent of this setting, and Claude Code's connection to the Anthropic API still works at **None**, as noted under [Security and isolation](/docs/en/claude-code-on-the-web#security-and-isolation).

126 

127### Allow specific domains

128 

129To allow domains that aren't in the Trusted list, select **Custom** in the environment's network access settings, then list one domain per line in the **Allowed domains** field. This example allows three hosts an internal project might need.

130 

131```text theme={null}

132api.example.com

133*.internal.example.com

134registry.example.com

135```

136 

137Sessions in this environment can now reach `api.example.com`, any subdomain of `internal.example.com`, and `registry.example.com`, and no other domains through the session's network; [GitHub traffic](#github-proxy) and [MCP connector traffic](#network-access) don't go through this allowlist. A leading `*.` matches every subdomain. To keep the [Trusted domains](#default-allowed-domains) too, check **Also include default list of common package managers**; leave it unchecked to allow only what you list.

138 

139Each environment has its own allowed-domains list; there's no organization-level allowlist that admins can push to every member's environments. [Server-managed settings](/docs/en/server-managed-settings) still apply inside cloud sessions, but none of them adds domains to the environment's network allowlist.

140 

141### GitHub proxy

142 

143All GitHub operations go through a dedicated proxy that keeps your real GitHub credentials outside the session's VM, independent of the environment's [access level](#access-levels):

144 

145* **Git credentials**: the git client inside the VM uses a scoped credential, which the proxy verifies and swaps for your actual GitHub token.

146* **API requests**: requests from the built-in GitHub tools, and from `gh` under the [`proxy-injected` placeholder](#work-with-github-issues-and-pull-requests), go out with your real credentials substituted.

147* **Push protection**: `git push` works only against the session's current working branch; cloning, fetching, and PR operations work normally.

148* **Repository scope**: GitHub API and release-asset requests reach only repositories attached to the session, so a setup script that downloads release assets from an unattached repository gets a 403.

149 

150Committed files from public repositories arrive through `raw.githubusercontent.com`, which the [security proxy](#security-proxy) handles instead. That domain is in the default [Trusted list](#default-allowed-domains), so those files stay reachable unless the environment's [access level](#access-levels) excludes it.

151 

152### Security proxy

153 

154Cloud sessions run behind an HTTP/HTTPS network proxy for security and abuse prevention purposes. All outbound internet traffic passes through this proxy, which provides:

155 

156* Protection against malicious requests

157* Rate limiting and abuse prevention

158* Content filtering for enhanced security

159* A DNS-level audit trail of requested hostnames

160 

161## What's available in cloud sessions

162 

163Each session gets a fresh virtual machine (VM) running Ubuntu 24.04, regardless of your own operating system, with your repository cloned and common toolchains pre-installed. This section covers those defaults, the built-in GitHub tools, how to [run tests and services](#run-tests-start-services-and-add-packages), and the [resource limits](#resource-limits) each VM gets.

164 

165### What carries over from your setup

166 

167Cloud sessions start from a fresh clone of your repository. Anything you commit to the repo is available. Anything you've installed or configured only on your own machine isn't available in the session. Your organization's policy arrives separately through [server-managed settings](/docs/en/server-managed-settings).

168 

169| | Available in cloud sessions | Why |

170| :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

171| Your repo's `CLAUDE.md` | Yes | Part of the clone |

172| Your repo's `.claude/settings.json` hooks | Yes | Part of the clone |

173| Your repo's `.mcp.json` MCP servers | Yes | Part of the clone |

174| Your repo's `.claude/rules/` | Yes | Part of the clone |

175| Your repo's `.claude/skills/`, `.claude/agents/`, `.claude/commands/` | Yes | Part of the clone |

176| Plugins declared in `.claude/settings.json` | Yes | Installed at session start from the [marketplace](/docs/en/plugin-marketplaces) you declared. Requires network access to reach the marketplace source |

177| Your organization's [server-managed settings](/docs/en/server-managed-settings) | Yes | Fetched from Anthropic's servers when the session starts. See [Surface coverage](/docs/en/model-config#surface-coverage) for how `availableModels` is enforced in cloud sessions. Settings deployed to your device through MDM or managed settings files don't apply, because the session runs on an Anthropic-managed VM |

178| Your user `~/.claude/CLAUDE.md` | No | Lives on your machine, not in the repo |

179| Your user `~/.claude/skills/`, `~/.claude/agents/`, `~/.claude/commands/` | No | Live on your machine, not in the repo. Commit them to the repo's `.claude/` directory instead. Cloud sessions automatically load skills you enable on claude.ai |

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

181| MCP servers you added with `claude mcp add` at the default local scope or the user scope | No | Those write to `~/.claude.json` on your machine, not the repo. Add the server with `claude mcp add --scope project`, which writes the repo's [`.mcp.json`](/docs/en/mcp#project-scope), and commit that file |

182| Transport variables in your repo's `.claude/settings.json` `env` block, such as `NODE_EXTRA_CA_CERTS` and the [mTLS client certificate variables](/docs/en/network-config#mtls-authentication) | No | The hosting environment manages the session's API connection, so Claude Code ignores these keys and notes each ignored key in the session's debug log |

183| Static API tokens and credentials | No | No dedicated secrets store exists yet. See below |

184| Interactive auth like AWS SSO | No | Not supported. SSO requires browser-based login that can't run in a cloud session |

185 

186To make your own configuration available in cloud sessions, commit it to the repo.

187 

188A dedicated secrets store is not yet available, and the dialog warns against adding secrets or credentials: environment variables and setup scripts live in the environment configuration, where anyone who uses the environment can read them. If a session needs a credential anyway, add it with that visibility in mind.

189 

190### Installed tools

191 

192Cloud sessions come with common language runtimes, build tools, and databases pre-installed. The table below summarizes what's included by category.

193 

194| Category | Included |

195| :------------ | :--------------------------------------------------------------------------------- |

196| **Python** | Python 3.x with pip, poetry, uv, black, mypy, pytest, ruff |

197| **Node.js** | 20, 21, and 22 via nvm, with npm, yarn, pnpm, bun¹, eslint, prettier, chromedriver |

198| **Ruby** | 3.1, 3.2, 3.3 with gem, bundler, rbenv |

199| **PHP** | 8.4 with Composer |

200| **Java** | OpenJDK 21 with Maven and Gradle |

201| **Go** | latest stable with module support |

202| **Rust** | rustc and cargo |

203| **C/C++** | GCC, Clang, cmake, ninja, conan |

204| **Docker** | docker, dockerd, docker compose |

205| **Databases** | PostgreSQL 16, Redis 7.0 |

206| **Utilities** | git, jq, yq, ripgrep, tmux, vim, nano |

207 

208¹ Bun is installed but has known [proxy compatibility issues](#install-dependencies-with-a-sessionstart-hook) for package fetching.

209 

210For exact versions, ask Claude to run `check-tools` in a cloud session. It's a shell command installed on the session VM, not a slash command; you ask Claude because [Claude runs all VM commands for you](#run-tests-start-services-and-add-packages).

211 

212Toolchains outside this list, such as the .NET SDK, aren't pre-installed even when their package registries are on the [default allowlist](#default-allowed-domains). Install them with a [setup script](#setup-scripts).

213 

214### Work with GitHub issues and pull requests

215 

216Cloud 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](#github-proxy) using whichever method you configured under [GitHub authentication options](/docs/en/claude-code-on-the-web#github-authentication-options), so your token never enters the container.

217 

218You can set `GH_TOKEN` or `GITHUB_TOKEN` yourself in [environment settings](#set-environment-variables), or leave both unset and let the [GitHub proxy](#github-proxy) authenticate for you:

219 

220* If you set a token, it passes through to the container unchanged, so your scripts, and GitHub's [`gh` CLI](https://cli.github.com) if you install it, use it directly.

221* If you set neither and the [GitHub proxy](#github-proxy) is handling authentication for your session, both variables read as the placeholder string `proxy-injected` in the commands Claude runs, and the proxy substitutes your real credentials on outbound GitHub requests. `gh` works without a token of your own, but a script that reads `GITHUB_TOKEN` directly gets the placeholder, not a usable token.

222 

223A token you set is an ordinary environment variable, so anyone who uses the environment can read it; the proxy path keeps the credential out of the environment configuration and the session VM.

224 

225To check which case applies to your session, ask Claude to run `echo $GH_TOKEN`.

226 

227GitHub's [`gh` CLI](https://cli.github.com) isn't 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:

228 

229<Steps>

230 <Step title="Install gh in your setup script">

231 Add `apt update && apt install -y gh` to your [setup script](#setup-scripts).

232 </Step>

233 

234 <Step title="Provide a token if the proxy is not handling authentication">

235 If `echo $GH_TOKEN` prints `proxy-injected`, the [GitHub proxy](#github-proxy) authenticates `gh` for you and this step is unnecessary. Otherwise, add a `GH_TOKEN` environment variable to your [environment settings](#set-environment-variables) with a GitHub personal access token; like any environment variable, it's readable by anyone who uses the environment, so scope the token narrowly. `gh` reads `GH_TOKEN` automatically, so you don't need to run `gh auth login`.

236 </Step>

237</Steps>

238 

239### Link output back to the session

240 

241Each cloud session has a transcript URL on claude.ai, and the session can read its own ID from the `CLAUDE_CODE_REMOTE_SESSION_ID` environment variable. Use this to put a traceable link in PR bodies, commit messages, Slack posts, or generated reports so a reviewer can open the run that produced them.

242 

243Commits that Claude creates in a cloud session include a `Claude-Session: <url>` git trailer, and PR bodies include the session URL on its own line. This requires v2.1.179 or later. {/* min-version: 2.1.182 */}To omit the trailer and the PR-body link, set [`attribution.sessionUrl`](/docs/en/settings#attribution-settings) to `false`. The setting requires v2.1.182 or later.

244 

245To include the session link in something other than a commit or PR, such as a Slack message Claude posts or a report file it writes, have Claude run the following command and use its output. The command converts the `cse_` prefix in the environment variable's value to the `session_` prefix that the transcript URL expects:

246 

247```bash theme={null}

248echo "https://claude.ai/code/${CLAUDE_CODE_REMOTE_SESSION_ID/#cse_/session_}"

249```

250 

251### Run tests, start services, and add packages

252 

253You don't get a shell into the session VM. Claude runs every command for you, so phrase the tasks in this section as requests in your prompt.

254 

255#### Run tests

256 

257Claude 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 that come with the [pre-installed toolchains](#installed-tools), like pytest and cargo test, work without additional setup. A runner your project declares as a dependency, like jest, installs with your dependencies.

258 

259#### Start services

260 

261PostgreSQL and Redis are pre-installed but not running by default. Ask Claude to start whichever you need; the commands it runs are:

262 

263```bash theme={null}

264service postgresql start

265```

266 

267```bash theme={null}

268service redis-server start

269```

270 

271Docker is available for running containerized services. Ask Claude to run `docker compose up` to start your project's services. Network access to pull images follows your environment's [access level](#access-levels), and the [Trusted defaults](#default-allowed-domains) include Docker Hub and other common registries.

272 

273If your images are large or slow to pull, add `docker compose pull` or `docker compose build` to your [setup script](#setup-scripts). The [environment cache](#environment-caching) keeps the pulled images, so each new session has them on disk. The cache stores files only, not running processes, so Claude still starts the containers each session.

274 

275#### Add packages

276 

277To add packages that aren't pre-installed, use a [setup script](#setup-scripts). The [environment cache](#environment-caching) keeps what the script installs, so packages you install there are available at the start of every session without reinstalling each time. You can also ask Claude to install packages mid-session, but those installs don't carry over to other sessions.

278 

279### Resource limits

280 

281Cloud sessions run with approximate resource ceilings that may change over time:

282 

283* 4 vCPUs

284* 16 GB of RAM

285* 30 GB of disk

286 

287The VM may stop tasks that need significantly more memory, such as large build jobs or memory-intensive tests. For workloads beyond these limits, use [Remote Control](/docs/en/remote-control) to run Claude Code on your own hardware.

288 

289## Setup scripts

290 

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

292 

293Scripts run as root on Ubuntu 24.04, so `apt install` and most language package managers work.

294 

295To add a setup script, open the environment settings dialog and enter your script in the **Setup script** field.

296 

297This example installs GitHub's [`gh` CLI](https://cli.github.com), which isn't pre-installed.

298 

299```bash theme={null}

300#!/bin/bash

301apt update && apt install -y gh

302```

303 

304### Script requirements

305 

306A setup script has three constraints to write around:

307 

308* **Exit zero**: if the script exits non-zero, the session fails to start. Append `|| true` to non-critical commands so an intermittent install failure doesn't block the session.

309* **Finish within five minutes**: keep the script's total runtime under roughly five minutes so the [environment cache](#environment-caching) can build. Run independent installs in parallel with `&` and `wait`, and move any single download that won't fit into a [SessionStart hook](#setup-scripts-vs-sessionstart-hooks) that launches it in the background.

310* **Network access for installs**: package installs need to reach registries. The default **Trusted** level covers [common package registries](#default-allowed-domains) including npm, PyPI, RubyGems, and crates.io; with **None** network access, installs fail.

311 

312### Environment caching

313 

314The setup script runs the first time you start a session in an environment. After it completes, Anthropic snapshots the filesystem and reuses that snapshot as the starting point for later sessions. New sessions start with your dependencies, tools, and Docker images already on disk, and skip the setup script step. This keeps startup fast even when the script installs large toolchains or pulls container images.

315 

316The cache is a filesystem snapshot, so it keeps what the setup script writes to disk and loses anything that was only running. Packages you install, Docker images you pull, and files you write all carry over. A database the script started, a `docker compose up` stack, or any other background process doesn't; start those per session by asking Claude or with a [SessionStart hook](#setup-scripts-vs-sessionstart-hooks).

317 

318The setup script runs again to rebuild the cache when you change the environment's setup script or allowed network hosts, and when the cache reaches its expiry after roughly seven days. Resuming an existing session never re-runs the setup script.

319 

320You don't need to enable caching or manage snapshots yourself.

321 

322### Setup scripts vs. SessionStart hooks

323 

324Use a setup script to provision the VM itself: toolchains and CLI tools that aren't [pre-installed](#installed-tools). Use a [SessionStart hook](/docs/en/hooks#sessionstart) for project setup that should run everywhere, cloud and local, like `npm install`.

325 

326Setup scripts and SessionStart hooks run in a fixed order when a cloud session starts:

327 

3281. The setup script runs first, before Claude Code launches, and only when no [cached environment](#environment-caching) exists.

3292. Claude Code launches and runs your SessionStart hooks, as it does at the start of every session, local or cloud.

330 

331| | Setup scripts | SessionStart hooks |

332| ---------------------------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

333| **Where you configure them** | The environment dialog at [claude.ai/code](https://claude.ai/code) | A [settings file](/docs/en/settings#settings-files) such as your repo's `.claude/settings.json`; see [What carries over from your setup](#what-carries-over-from-your-setup) for which files reach a cloud session |

334| **When they run** | Before Claude Code launches, skipped when a [cached environment](#environment-caching) exists | After Claude Code launches, on every session including resumed |

335| **Where they run** | Cloud sessions only | Local and cloud sessions |

336 

337If you have SessionStart hooks in your user-level `~/.claude/settings.json`, don't expect them in the cloud: user-level settings stay on your machine. In a cloud session, Claude Code runs hooks from the repository and from your organization's [server-managed settings](/docs/en/server-managed-settings).

338 

339### Install dependencies with a SessionStart hook

340 

341To install dependencies only in cloud sessions, pair a SessionStart hook with a script that checks where it's running.

342 

343First, add a SessionStart hook to your repo's `.claude/settings.json`. This configuration tells Claude Code to run `scripts/install_pkgs.sh` from your repository whenever a session starts or resumes:

344 

345```json theme={null}

346{

347 "hooks": {

348 "SessionStart": [

349 {

350 "matcher": "startup|resume",

351 "hooks": [

352 {

353 "type": "command",

354 "command": "bash \"$CLAUDE_PROJECT_DIR\"/scripts/install_pkgs.sh"

355 }

356 ]

357 }

358 ]

359 }

360}

361```

362 

363The `matcher` limits the hook to the `startup` and `resume` events, and `$CLAUDE_PROJECT_DIR` resolves to the repository root, so the hook finds the script regardless of the session's working directory.

364 

365Next, create the script at `scripts/install_pkgs.sh`. It exits immediately outside the cloud, then installs your dependencies:

366 

367```bash theme={null}

368#!/bin/bash

369 

370if [ "$CLAUDE_CODE_REMOTE" != "true" ]; then

371 exit 0

372fi

373 

374npm install

375pip install -r requirements.txt

376exit 0

377```

378 

379The `CLAUDE_CODE_REMOTE` check is what scopes the install to cloud sessions: the session VM's environment carries that variable as `true`, it's never `true` locally, so on your laptop the script exits before installing anything.

380 

381Together, the two files give every cloud session a fresh `npm install` and `pip install` at startup while leaving local sessions untouched.

382 

383#### Limitations in cloud sessions

384 

385SessionStart hooks behave the same in the cloud as locally, with these caveats:

386 

387* **No cloud-only scoping**: hooks run in both local and cloud sessions. To skip local execution, check the `CLAUDE_CODE_REMOTE` environment variable as shown above.

388* **Requires network access**: install commands need to reach package registries. If your environment uses **None** network access, these hooks fail. The [default allowlist](#default-allowed-domains) under **Trusted** covers npm, PyPI, RubyGems, and crates.io.

389* **Proxy compatibility**: all outbound traffic passes through a [security proxy](#security-proxy). Some package managers don't work correctly with this proxy. Bun is a known example.

390* **Adds startup latency**: hooks run each time a session starts or resumes, unlike setup scripts which benefit from [environment caching](#environment-caching). Keep install scripts fast by checking whether dependencies are already present before reinstalling.

391 

392To persist environment variables for subsequent Bash commands, write to the file at `$CLAUDE_ENV_FILE`. See [SessionStart hooks](/docs/en/hooks#sessionstart) for details.

393 

394To customize the base image, use a setup script to install what you need on top of the [provided image](#installed-tools), or run your own image as a container alongside Claude with `docker compose`. Replacing the base image entirely isn't supported yet.

395 

396## Default allowed domains

397 

398With **Trusted** network access, sessions can reach the following domains by default. Domains marked with `*` indicate wildcard subdomain matching, so `*.gcr.io` allows any subdomain of `gcr.io`.

399 

400<AccordionGroup>

401 <Accordion title="Anthropic services">

402 * api.anthropic.com

403 * statsig.anthropic.com

404 * docs.claude.com

405 * platform.claude.com

406 * code.claude.com

407 * claude.ai

408 </Accordion>

409 

410 <Accordion title="Version control">

411 * github.com

412 * [www.github.com](http://www.github.com)

413 * api.github.com

414 * npm.pkg.github.com

415 * raw\.githubusercontent.com

416 * pkg-npm.githubusercontent.com

417 * objects.githubusercontent.com

418 * release-assets.githubusercontent.com

419 * codeload.github.com

420 * avatars.githubusercontent.com

421 * camo.githubusercontent.com

422 * gist.github.com

423 * gitlab.com

424 * [www.gitlab.com](http://www.gitlab.com)

425 * registry.gitlab.com

426 * bitbucket.org

427 * [www.bitbucket.org](http://www.bitbucket.org)

428 * api.bitbucket.org

429 </Accordion>

430 

431 <Accordion title="Container registries">

432 * registry-1.docker.io

433 * auth.docker.io

434 * index.docker.io

435 * hub.docker.com

436 * [www.docker.com](http://www.docker.com)

437 * production.cloudflare.docker.com

438 * download.docker.com

439 * gcr.io

440 * \*.gcr.io

441 * ghcr.io

442 * mcr.microsoft.com

443 * \*.data.mcr.microsoft.com

444 * public.ecr.aws

445 </Accordion>

446 

447 <Accordion title="Cloud platforms">

448 * cloud.google.com

449 * accounts.google.com

450 * gcloud.google.com

451 * \*.googleapis.com

452 * storage.googleapis.com

453 * compute.googleapis.com

454 * container.googleapis.com

455 * azure.com

456 * portal.azure.com

457 * microsoft.com

458 * [www.microsoft.com](http://www.microsoft.com)

459 * \*.microsoftonline.com

460 * packages.microsoft.com

461 * dotnet.microsoft.com

462 * dot.net

463 * visualstudio.com

464 * dev.azure.com

465 * \*.amazonaws.com

466 * \*.api.aws

467 * oracle.com

468 * [www.oracle.com](http://www.oracle.com)

469 * java.com

470 * [www.java.com](http://www.java.com)

471 * java.net

472 * [www.java.net](http://www.java.net)

473 * download.oracle.com

474 * yum.oracle.com

475 </Accordion>

476 

477 <Accordion title="JavaScript and Node package managers">

478 * registry.npmjs.org

479 * [www.npmjs.com](http://www.npmjs.com)

480 * [www.npmjs.org](http://www.npmjs.org)

481 * npmjs.com

482 * npmjs.org

483 * yarnpkg.com

484 * registry.yarnpkg.com

485 </Accordion>

486 

487 <Accordion title="Python package managers">

488 * pypi.org

489 * [www.pypi.org](http://www.pypi.org)

490 * files.pythonhosted.org

491 * pythonhosted.org

492 * test.pypi.org

493 * pypi.python.org

494 * pypa.io

495 * [www.pypa.io](http://www.pypa.io)

496 </Accordion>

497 

498 <Accordion title="Ruby package managers">

499 * rubygems.org

500 * [www.rubygems.org](http://www.rubygems.org)

501 * api.rubygems.org

502 * index.rubygems.org

503 * ruby-lang.org

504 * [www.ruby-lang.org](http://www.ruby-lang.org)

505 * rubyforge.org

506 * [www.rubyforge.org](http://www.rubyforge.org)

507 * rubyonrails.org

508 * [www.rubyonrails.org](http://www.rubyonrails.org)

509 * rvm.io

510 * get.rvm.io

511 </Accordion>

512 

513 <Accordion title="Rust package managers">

514 * crates.io

515 * [www.crates.io](http://www.crates.io)

516 * index.crates.io

517 * static.crates.io

518 * rustup.rs

519 * static.rust-lang.org

520 * [www.rust-lang.org](http://www.rust-lang.org)

521 </Accordion>

522 

523 <Accordion title="Go package managers">

524 * proxy.golang.org

525 * sum.golang.org

526 * index.golang.org

527 * golang.org

528 * [www.golang.org](http://www.golang.org)

529 * goproxy.io

530 * pkg.go.dev

531 </Accordion>

532 

533 <Accordion title="JVM package managers">

534 * maven.org

535 * repo.maven.org

536 * central.maven.org

537 * repo1.maven.org

538 * repo.maven.apache.org

539 * jcenter.bintray.com

540 * gradle.org

541 * [www.gradle.org](http://www.gradle.org)

542 * services.gradle.org

543 * plugins.gradle.org

544 * kotlinlang.org

545 * [www.kotlinlang.org](http://www.kotlinlang.org)

546 * spring.io

547 * repo.spring.io

548 </Accordion>

549 

550 <Accordion title="Other package managers">

551 * packagist.org (PHP Composer)

552 * [www.packagist.org](http://www.packagist.org)

553 * repo.packagist.org

554 * nuget.org (.NET NuGet)

555 * [www.nuget.org](http://www.nuget.org)

556 * api.nuget.org

557 * pub.dev (Dart/Flutter)

558 * api.pub.dev

559 * hex.pm (Elixir/Erlang)

560 * [www.hex.pm](http://www.hex.pm)

561 * cpan.org (Perl CPAN)

562 * [www.cpan.org](http://www.cpan.org)

563 * metacpan.org

564 * [www.metacpan.org](http://www.metacpan.org)

565 * api.metacpan.org

566 * cocoapods.org (iOS/macOS)

567 * [www.cocoapods.org](http://www.cocoapods.org)

568 * cdn.cocoapods.org

569 * haskell.org

570 * [www.haskell.org](http://www.haskell.org)

571 * hackage.haskell.org

572 * swift.org

573 * [www.swift.org](http://www.swift.org)

574 </Accordion>

575 

576 <Accordion title="Linux distributions">

577 * archive.ubuntu.com

578 * security.ubuntu.com

579 * ubuntu.com

580 * [www.ubuntu.com](http://www.ubuntu.com)

581 * \*.ubuntu.com

582 * ppa.launchpad.net

583 * launchpad.net

584 * [www.launchpad.net](http://www.launchpad.net)

585 * \*.nixos.org

586 </Accordion>

587 

588 <Accordion title="Development tools and platforms">

589 * dl.k8s.io (Kubernetes)

590 * pkgs.k8s.io

591 * k8s.io

592 * [www.k8s.io](http://www.k8s.io)

593 * releases.hashicorp.com (HashiCorp)

594 * apt.releases.hashicorp.com

595 * rpm.releases.hashicorp.com

596 * archive.releases.hashicorp.com

597 * hashicorp.com

598 * [www.hashicorp.com](http://www.hashicorp.com)

599 * repo.anaconda.com (Anaconda/Conda)

600 * conda.anaconda.org

601 * anaconda.org

602 * [www.anaconda.com](http://www.anaconda.com)

603 * anaconda.com

604 * continuum.io

605 * apache.org (Apache)

606 * [www.apache.org](http://www.apache.org)

607 * archive.apache.org

608 * downloads.apache.org

609 * eclipse.org (Eclipse)

610 * [www.eclipse.org](http://www.eclipse.org)

611 * download.eclipse.org

612 * nodejs.org (Node.js)

613 * [www.nodejs.org](http://www.nodejs.org)

614 * developer.apple.com

615 * developer.android.com

616 * pkg.stainless.com

617 * binaries.prisma.sh

618 </Accordion>

619 

620 <Accordion title="Cloud services and monitoring">

621 * statsig.com

622 * [www.statsig.com](http://www.statsig.com)

623 * api.statsig.com

624 * sentry.io

625 * \*.sentry.io

626 * downloads.sentry-cdn.com

627 * http-intake.logs.datadoghq.com

628 * browser-intake-us5-datadoghq.com

629 * \*.datadoghq.com

630 * \*.datadoghq.eu

631 * api.honeycomb.io

632 </Accordion>

633 

634 <Accordion title="Content delivery and mirrors">

635 * sourceforge.net

636 * \*.sourceforge.net

637 * packagecloud.io

638 * \*.packagecloud.io

639 * fonts.googleapis.com

640 * fonts.gstatic.com

641 </Accordion>

642 

643 <Accordion title="Schema and configuration">

644 * json-schema.org

645 * [www.json-schema.org](http://www.json-schema.org)

646 * json.schemastore.org

647 * [www.schemastore.org](http://www.schemastore.org)

648 </Accordion>

649 

650 <Accordion title="Model Context Protocol">

651 * \*.modelcontextprotocol.io

652 </Accordion>

653</AccordionGroup>

654 

655## Related resources

656 

657* [Claude Code on the web](/docs/en/claude-code-on-the-web): start, manage, and share cloud sessions

658* [Web quickstart](/docs/en/web-quickstart): connect GitHub and start your first cloud session

659* [Claude Tag](https://claude.com/docs/claude-tag/overview): sessions Claude starts from Slack run in the same environments

660* [Routines](/docs/en/routines): scheduled runs use the same environments and network access levels

661* [Remote Control](/docs/en/remote-control): run sessions on your own machine's network and files instead

662* [SessionStart hooks](/docs/en/hooks#sessionstart): repo-committed setup that runs in local and cloud sessions

663* [Server-managed settings](/docs/en/server-managed-settings): organization policy that reaches cloud sessions

code-review.md +6 −0

Details

309 </Step>309 </Step>

310</Steps>310</Steps>

311 311 

312{/* min-version: 2.1.218 */}When the host application requests it, Claude reports the review's findings through the [`ReportFindings` tool](/docs/en/tools-reference) instead of as text in its reply. Claude Code renders the report as a findings list, one entry per finding. Each entry shows the file location, a one-sentence summary, and a category tag such as `correctness` when the finding carries one. A host request applies at every effort level and requires Claude Code v2.1.218 or later.

313 

314{/* min-version: 2.1.218 */}In a terminal session, `/code-review` runs the review as a fork and reports the findings as text in the reply, and Claude reports as text in any `-p` run with text or JSON output, even when the host application requests the findings list. {/* max-version: 2.1.217 */}On v2.1.216 and v2.1.217, a terminal review at `medium` or higher effort reported the findings list instead.

315 

316When Claude fixes reported findings later in the session, it reports them again, and Claude Code marks each finding in the new list as fixed, skipped, or no change needed.

317 

312### What the review reads and edits318### What the review reads and edits

313 319 

314The review follows your `CLAUDE.md` like any Claude Code session, but it doesn't read [`REVIEW.md`](#review-md). {/* min-version: 2.1.218 */}A background review applies its `--fix` edits outside your session's [checkpoints](/docs/en/checkpointing#subagent-edits-not-restored), so `/rewind` doesn't undo them; use git to revert them. When the review [runs in the foreground](#run-in-the-foreground), it edits your working tree during your own turn, so `/rewind` restores its edits as usual.320The review follows your `CLAUDE.md` like any Claude Code session, but it doesn't read [`REVIEW.md`](#review-md). {/* min-version: 2.1.218 */}A background review applies its `--fix` edits outside your session's [checkpoints](/docs/en/checkpointing#subagent-edits-not-restored), so `/rewind` doesn't undo them; use git to revert them. When the review [runs in the foreground](#run-in-the-foreground), it edits your working tree during your own turn, so `/rewind` restores its edits as usual.

commands.md +4 −4

Details

43In the table below, `<arg>` indicates a required argument and `[arg]` indicates an optional one.43In the table below, `<arg>` indicates a required argument and `[arg]` indicates an optional one.

44 44 

45<Note>45<Note>

46 Not every command appears for every user. Availability depends on your platform, plan, and environment. For example, `/desktop` only shows on macOS and Windows when signed in with a Claude subscription, and `/upgrade` doesn't show on Enterprise plans.46 Not every command appears for every user. Availability depends on your platform, plan, and environment. For example, `/desktop` only shows on macOS and x64 Windows when signed in with a Claude subscription, and `/upgrade` doesn't show on Enterprise plans.

47</Note>47</Note>

48 48 

49| Command | Purpose |49| Command | Purpose |


73| `/deep-research <question>` | **[Workflow](/docs/en/workflows#bundled-workflows).** Fan out web searches on a question, fetch and cross-check sources, and synthesize a cited report |73| `/deep-research <question>` | **[Workflow](/docs/en/workflows#bundled-workflows).** Fan out web searches on a question, fetch and cross-check sources, and synthesize a cited report |

74| `/design-login` | Authorize design-system access for `/design-sync` with your claude.ai account |74| `/design-login` | Authorize design-system access for `/design-sync` with your claude.ai account |

75| `/design-sync [hint]` | **[Skill](/docs/en/skills#bundled-skills).** Convert your repo's React design system and upload it to [Claude Design](https://claude.ai/design), so designs it produces use your real components. Optionally name the design system, for example `/design-sync Acme DS`. A first-time sync verifies every component and can take a few hours on a large repo. Available on the Anthropic API; on Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, and Claude Platform on AWS the underlying tool can't reach claude.ai, so the command is unavailable |75| `/design-sync [hint]` | **[Skill](/docs/en/skills#bundled-skills).** Convert your repo's React design system and upload it to [Claude Design](https://claude.ai/design), so designs it produces use your real components. Optionally name the design system, for example `/design-sync Acme DS`. A first-time sync verifies every component and can take a few hours on a large repo. Available on the Anthropic API; on Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, and Claude Platform on AWS the underlying tool can't reach claude.ai, so the command is unavailable |

76| `/desktop` | Continue the current session in the Claude Code Desktop app. Requires macOS or Windows and a Claude subscription. Alias: `/app` |76| `/desktop` | Continue the current session in the Claude Code Desktop app. Requires macOS or x64 Windows and a Claude subscription. Alias: `/app` |

77| `/diff` | Open an interactive diff viewer showing uncommitted changes and per-turn diffs. Use left/right arrows to switch between the current git diff and individual Claude turns, and up/down to browse files. Press Enter to open the selected file's diff, scroll it with up/down or PageUp/PageDown, and press Esc to return to the file list. {/* min-version: 2.1.198 */}As of v2.1.198, the open viewer also refreshes automatically when the repository's git state changes outside the session, such as a branch switch or commit in another terminal |77| `/diff` | Open an interactive diff viewer showing uncommitted changes and per-turn diffs. Use left/right arrows to switch between the current git diff and individual Claude turns, and up/down to browse files. Press Enter to open the selected file's diff, scroll it with up/down or PageUp/PageDown, and press Esc to return to the file list. {/* min-version: 2.1.198 */}As of v2.1.198, the open viewer also refreshes automatically when the repository's git state changes outside the session, such as a branch switch or commit in another terminal |

78| `/doctor` | **[Skill](/docs/en/skills#bundled-skills).** Run a setup checkup that diagnoses issues and can fix them. Checks installation health, including duplicate or leftover installs, `PATH` problems, and unparseable settings files. Finds unused skills, MCP servers, and plugins versus their context cost, flags slow [hooks](/docs/en/hooks), and checks for a newer version on your release channel. Deduplicates local `CLAUDE.md` files against checked-in ones, trims checked-in [`CLAUDE.md`](/docs/en/memory) files by cutting content Claude could derive from the codebase, and migrates the always-loaded guidance that remains into [skills](/docs/en/skills) and nested `CLAUDE.md` files that load on demand. The trim cuts sections such as directory layouts, dependency lists, and architecture overviews, and keeps pitfalls, rationale, and conventions that differ from tool defaults. Also offers to make [auto mode](/docs/en/permissions#permission-modes) your default and to [pre-approve](/docs/en/permissions) frequently denied read-only commands. Reports findings first and asks for confirmation before changing anything. From the terminal, `claude doctor` prints read-only installation diagnostics without starting a session. Alias: `/checkup`. {/* min-version: 2.1.206 */}The `CLAUDE.md` trim check requires Claude Code v2.1.206 or later. Before v2.1.206, the version check compared Homebrew installs against the `autoUpdatesChannel` setting rather than the [installed cask's channel](/docs/en/setup#configure-release-channel). {/* min-version: 2.1.205 */}Before v2.1.205, `/doctor` opened a read-only diagnostics screen and pressing `f` sent the report to Claude |78| `/doctor` | **[Skill](/docs/en/skills#bundled-skills).** Run a setup checkup that diagnoses issues and can fix them. Checks installation health, including duplicate or leftover installs, `PATH` problems, and unparseable settings files. Finds unused skills, MCP servers, and plugins versus their context cost, flags slow [hooks](/docs/en/hooks), and checks for a newer version on your release channel. Deduplicates local `CLAUDE.md` files against checked-in ones, trims checked-in [`CLAUDE.md`](/docs/en/memory) files by cutting content Claude could derive from the codebase, and migrates the always-loaded guidance that remains into [skills](/docs/en/skills) and nested `CLAUDE.md` files that load on demand. The trim cuts sections such as directory layouts, dependency lists, and architecture overviews, and keeps pitfalls, rationale, and conventions that differ from tool defaults. Also offers to make [auto mode](/docs/en/permissions#permission-modes) your default and to [pre-approve](/docs/en/permissions) frequently denied read-only commands. Reports findings first and asks for confirmation before changing anything. From the terminal, `claude doctor` prints read-only installation diagnostics without starting a session. Alias: `/checkup`. {/* min-version: 2.1.206 */}The `CLAUDE.md` trim check requires Claude Code v2.1.206 or later. Before v2.1.206, the version check compared Homebrew installs against the `autoUpdatesChannel` setting rather than the [installed cask's channel](/docs/en/setup#configure-release-channel). {/* min-version: 2.1.205 */}Before v2.1.205, `/doctor` opened a read-only diagnostics screen and pressing `f` sent the report to Claude |

79| `/effort [level\|auto]` | Set the model [effort level](/docs/en/model-config#adjust-effort-level). Accepts `low`, `medium`, `high`, `xhigh`, `max`, or [`ultracode`](/docs/en/workflows#let-claude-decide-with-ultracode); available levels depend on the model, and `max` and `ultracode` are session-only. `auto` resets to the model default. Without an argument, opens an interactive slider. Takes effect immediately without waiting for the current response to finish. {/* min-version: 2.1.205 */}Also available in non-interactive mode (`-p`) with a level argument, where it applies to the current session only; requires Claude Code v2.1.205 or later. While the [model-default effort hold](/docs/en/model-config#adjust-effort-level) is in force, a non-interactive `/effort` reports `Not applied`, so pass `--effort` at launch instead |79| `/effort [level\|auto]` | Set the model [effort level](/docs/en/model-config#adjust-effort-level). Accepts `low`, `medium`, `high`, `xhigh`, `max`, or [`ultracode`](/docs/en/workflows#let-claude-decide-with-ultracode); available levels depend on the model, and `max` and `ultracode` are session-only. `auto` resets to the model default. Without an argument, opens an interactive slider. Takes effect immediately without waiting for the current response to finish. {/* min-version: 2.1.205 */}Also available in non-interactive mode (`-p`) with a level argument, where it applies to the current session only; requires Claude Code v2.1.205 or later. While the [model-default effort hold](/docs/en/model-config#adjust-effort-level) is in force, a non-interactive `/effort` reports `Not applied`, so pass `--effort` at launch instead |


114| `/reload-plugins [--force]` | Reload all active [plugins](/docs/en/plugins) to apply pending changes without restarting. Reports counts for each reloaded component and flags any load errors. When the reload would change which MCP tools are loaded and invalidate the prompt cache, the command warns and skips unless you pass `--force` |114| `/reload-plugins [--force]` | Reload all active [plugins](/docs/en/plugins) to apply pending changes without restarting. Reports counts for each reloaded component and flags any load errors. When the reload would change which MCP tools are loaded and invalidate the prompt cache, the command warns and skips unless you pass `--force` |

115| `/reload-skills` | {/* min-version: 2.1.152 */}Re-scan [skill](/docs/en/skills) and command directories so skills added or changed on disk during the session become available without restarting. Reports how many skills are available and how many were added or removed. Added in v2.1.152 |115| `/reload-skills` | {/* min-version: 2.1.152 */}Re-scan [skill](/docs/en/skills) and command directories so skills added or changed on disk during the session become available without restarting. Reports how many skills are available and how many were added or removed. Added in v2.1.152 |

116| `/remote-control` | Make this session available for [Remote Control](/docs/en/remote-control) from claude.ai. {/* min-version: 2.1.206 */}Running it while signed out prints that Remote Control requires a claude.ai subscription and tells you how to sign in; before v2.1.206 it reported `Unknown command: /remote-control`. Alias: `/rc` |116| `/remote-control` | Make this session available for [Remote Control](/docs/en/remote-control) from claude.ai. {/* min-version: 2.1.206 */}Running it while signed out prints that Remote Control requires a claude.ai subscription and tells you how to sign in; before v2.1.206 it reported `Unknown command: /remote-control`. Alias: `/rc` |

117| `/remote-env` | Choose the default environment for [cloud agents](/docs/en/claude-code-on-the-web#configure-your-environment) |117| `/remote-env` | Choose the default environment for [cloud agents](/docs/en/cloud-environments#select-an-environment-from-the-cli) |

118| `/rename [name]` | Rename the current session and show the name on the prompt bar. Without a name, auto-generates one from conversation history. {/* min-version: 2.1.205 */}Also available in non-interactive mode (`-p`); requires Claude Code v2.1.205 or later |118| `/rename [name]` | Rename the current session and show the name on the prompt bar. Without a name, auto-generates one from conversation history. {/* min-version: 2.1.205 */}Also available in non-interactive mode (`-p`); requires Claude Code v2.1.205 or later |

119| `/resume [session]` | Resume a conversation by ID or name, or open the session picker. As of v2.1.144, [background sessions](/docs/en/agent-view) appear in the picker marked with `bg`; one that is still running can't be resumed here, so attach to it from `claude agents` or stop it there first. Alias: `/continue` |119| `/resume [session]` | Resume a conversation by ID or name, or open the session picker. As of v2.1.144, [background sessions](/docs/en/agent-view) appear in the picker marked with `bg`; one that is still running can't be resumed here, so attach to it from `claude agents` or stop it there first. Alias: `/continue` |

120| `/review [PR]` | {/* min-version: 2.1.202 */}Run a fast single-pass, read-only review of a GitHub pull request by number. With no argument, lists open PRs to pick from; text after the PR number becomes additional review instructions. From v2.1.186 through v2.1.201, `/review` instead ran the same multi-agent engine as `/code-review medium`. For a multi-agent review at a chosen effort level, use [`/code-review <level> <pr#>`](/docs/en/code-review#review-a-diff-locally); for a cloud-based review, see [`/code-review ultra`](/docs/en/ultrareview) |120| `/review [PR]` | {/* min-version: 2.1.202 */}Run a fast single-pass, read-only review of a GitHub pull request by number. With no argument, lists open PRs to pick from; text after the PR number becomes additional review instructions. From v2.1.186 through v2.1.201, `/review` instead ran the same multi-agent engine as `/code-review medium`. For a multi-agent review at a chosen effort level, use [`/code-review <level> <pr#>`](/docs/en/code-review#review-a-diff-locally); for a cloud-based review, see [`/code-review ultra`](/docs/en/ultrareview) |


124| `/sandbox` | Toggle [sandbox mode](/docs/en/sandboxing). Available on supported platforms only |124| `/sandbox` | Toggle [sandbox mode](/docs/en/sandboxing). Available on supported platforms only |

125| `/schedule [description]` | Create, update, list, or run [routines](/docs/en/routines), which execute on Anthropic-managed cloud infrastructure. Claude walks you through the setup conversationally. Alias: `/routines` |125| `/schedule [description]` | Create, update, list, or run [routines](/docs/en/routines), which execute on Anthropic-managed cloud infrastructure. Claude walks you through the setup conversationally. Alias: `/routines` |

126| `/scroll-speed` | Adjust mouse wheel [scroll speed](/docs/en/fullscreen#mouse-wheel-scrolling) interactively, with a ruler you can scroll while the dialog is open to preview the change. Available in [fullscreen rendering](/docs/en/fullscreen) only and not in the JetBrains IDE terminal |126| `/scroll-speed` | Adjust mouse wheel [scroll speed](/docs/en/fullscreen#mouse-wheel-scrolling) interactively, with a ruler you can scroll while the dialog is open to preview the change. Available in [fullscreen rendering](/docs/en/fullscreen) only and not in the JetBrains IDE terminal |

127| `/security-review` | Analyze pending changes on the current branch for security vulnerabilities. Reviews the git diff and identifies risks like injection, auth issues, and data exposure |127| `/security-review` | Analyze the changes on your current branch for security vulnerabilities. Reviews the diff between your branch and origin's default branch, identifying risks like injection, auth issues, and data exposure. Needs an `origin` remote; if the review fails with an `ambiguous argument` error, see the [error reference](/docs/en/errors#security-review-fails-without-origin-head) |

128| `/setup-bedrock` | Configure [Amazon Bedrock](/docs/en/amazon-bedrock) authentication, region, and model pins through an interactive wizard. Only visible when `CLAUDE_CODE_USE_BEDROCK=1` is set. First-time Amazon Bedrock users can also access this wizard from the login screen |128| `/setup-bedrock` | Configure [Amazon Bedrock](/docs/en/amazon-bedrock) authentication, region, and model pins through an interactive wizard. Only visible when `CLAUDE_CODE_USE_BEDROCK=1` is set. First-time Amazon Bedrock users can also access this wizard from the login screen |

129| `/setup-vertex` | Configure [Google Cloud's Agent Platform](/docs/en/google-vertex-ai) authentication, project, region, and model pins through an interactive wizard. Only visible when `CLAUDE_CODE_USE_VERTEX=1` is set. First-time Google Cloud's Agent Platform users can also access this wizard from the login screen |129| `/setup-vertex` | Configure [Google Cloud's Agent Platform](/docs/en/google-vertex-ai) authentication, project, region, and model pins through an interactive wizard. Only visible when `CLAUDE_CODE_USE_VERTEX=1` is set. First-time Google Cloud's Agent Platform users can also access this wizard from the login screen |

130| `/simplify [target]` | {/* min-version: 2.1.154 */}**[Skill](/docs/en/skills#bundled-skills).** Review the changed code for cleanup opportunities and apply the fixes. Four review [agents](/docs/en/sub-agents) run in parallel, covering reuse of existing helpers, simplification, efficiency, and whether the change is at the right level of abstraction. From v2.1.154, the review doesn't look for correctness bugs. Use `/code-review` to find bugs. On earlier versions, `/simplify` is equivalent to `/code-review --fix`. Pass a path or PR reference to review a specific target |130| `/simplify [target]` | {/* min-version: 2.1.154 */}**[Skill](/docs/en/skills#bundled-skills).** Review the changed code for cleanup opportunities and apply the fixes. Four review [agents](/docs/en/sub-agents) run in parallel, covering reuse of existing helpers, simplification, efficiency, and whether the change is at the right level of abstraction. From v2.1.154, the review doesn't look for correctness bugs. Use `/code-review` to find bugs. On earlier versions, `/simplify` is equivalent to `/code-review --fix`. Pass a path or PR reference to review a specific target |

costs.md +2 −2

Details

271 271 

272A session that has been open for hours can use far more of your plan limits than your activity suggests, usually for one of these reasons:272A session that has been open for hours can use far more of your plan limits than your activity suggests, usually for one of these reasons:

273 273 

274* **Long context**: Claude Code sends your full conversation with every message, so a one-line question in a session that has been open all day uses tokens for the whole conversation, not just the one line. See [Manage context proactively](#manage-context-proactively) for ways to keep your context small274* **Long context**: Claude Code sends your full conversation with every request, and each time Claude uses tools it sends another request carrying that batch of tool results. With [prompt caching](/docs/en/prompt-caching), Claude Code re-reads that history at the [cached token rate](https://platform.claude.com/docs/en/about-claude/pricing), so a one-line question in a session that has been open all day still draws usage for the whole conversation. See [Manage context proactively](#manage-context-proactively) for ways to keep your context small

275* **Cache misses**: your first message after a break longer than the [cache lifetime](/docs/en/prompt-caching#cache-lifetime) misses the cache and reprocesses your full context. The lifetime is an hour on a subscription and drops to five minutes once you're drawing on [usage credits](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans); on an API key or cloud provider, it's five minutes by default275* **Cache misses**: your first message after a break longer than the [cache lifetime](/docs/en/prompt-caching#cache-lifetime) misses the cache and reprocesses your full context. The lifetime is an hour on a subscription and drops to five minutes once you're drawing on [usage credits](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans); on an API key or cloud provider, it's five minutes by default. On Pro and Max plans, when you resume a large session after a long break, Claude Code [offers to resume from a summary](/docs/en/sessions#resume-from-a-summary) so later requests don't carry the full history

276* **Scheduled tasks**: a [scheduled task](/docs/en/scheduled-tasks) fires on its interval even while the session is idle, sending your full context each time276* **Scheduled tasks**: a [scheduled task](/docs/en/scheduled-tasks) fires on its interval even while the session is idle, sending your full context each time

277* **Agent teammates**: each active [teammate](#agent-team-token-costs) keeps consuming tokens until it exits277* **Agent teammates**: each active [teammate](#agent-team-token-costs) keeps consuming tokens until it exits

278* **Compaction**: `/compact` reads the conversation it summarizes, so [compacting a large context](/docs/en/prompt-caching#compacting-the-conversation) is itself a large request. When you want a fresh start instead of continuity, `/clear` costs nothing278* **Compaction**: `/compact` reads the conversation it summarizes, so [compacting a large context](/docs/en/prompt-caching#compacting-the-conversation) is itself a large request. When you want a fresh start instead of continuity, `/clear` costs nothing

data-usage.md +15 −15

Details

29 29 

30After the rating prompt, you may see a separate follow-up asking "Can Anthropic look at your session transcript to help us improve Claude Code?". This is an optional second step distinct from the rating:30After the rating prompt, you may see a separate follow-up asking "Can Anthropic look at your session transcript to help us improve Claude Code?". This is an optional second step distinct from the rating:

31 31 

32* **Yes**: uploads your conversation transcript, any subagent transcripts, and the raw session log file from disk to Anthropic. Known API key and token patterns are redacted before upload. Source code, file contents, and other conversation content are uploaded as-is. Shared transcripts are retained for up to 6 months. On Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, and signed-in [Claude apps gateway](/en/claude-apps-gateway) sessions, Yes writes the same payload to a local archive under `~/.claude/feedback-bundles/` instead of uploading; nothing leaves your machine until you forward that file.32* **Yes**: uploads your conversation transcript, any subagent transcripts, and the raw session log file from disk to Anthropic. Known API key and token patterns are redacted before upload. Source code, file contents, and other conversation content are uploaded as-is. Shared transcripts are retained for up to 6 months. On Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, and signed-in [Claude apps gateway](/docs/en/claude-apps-gateway) sessions, Yes writes the same payload to a local archive under `~/.claude/feedback-bundles/` instead of uploading; nothing leaves your machine until you forward that file.

33* **No**: declines without sending anything33* **No**: declines without sending anything

34* **Don't ask again**: declines and stops this follow-up from appearing in future sessions34* **Don't ask again**: declines and stops this follow-up from appearing in future sessions

35 35 

36Nothing is uploaded unless you explicitly select **Yes**. Organizations with [zero data retention](/en/zero-data-retention), or where product feedback is disabled by organization policy, or where `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is set, never see this follow-up. Your responses to this survey, including session transcripts submitted after the rating prompt, do not impact your data training preferences and cannot be used to train our AI models.36Nothing is uploaded unless you explicitly select **Yes**. Organizations with [zero data retention](/docs/en/zero-data-retention), or where product feedback is disabled by organization policy, or where `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is set, never see this follow-up. Your responses to this survey, including session transcripts submitted after the rating prompt, do not impact your data training preferences and cannot be used to train our AI models.

37 37 

38To disable these surveys, set `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1`. The survey is also disabled when `DISABLE_TELEMETRY`, `DO_NOT_TRACK`, or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is set. Organizations that block nonessential traffic but capture survey responses through their own [OpenTelemetry collector](/en/monitoring-usage) can opt the survey back in by setting `CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL=1`. The survey then logs ratings to the configured collector only. The transcript-share follow-up and all other Anthropic-bound feedback traffic stay disabled. To control frequency instead of disabling, set [`feedbackSurveyRate`](/en/settings#available-settings) in your settings file to a probability between `0` and `1`.38To disable these surveys, set `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1`. The survey is also disabled when `DISABLE_TELEMETRY`, `DO_NOT_TRACK`, or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is set. Organizations that block nonessential traffic but capture survey responses through their own [OpenTelemetry collector](/docs/en/monitoring-usage) can opt the survey back in by setting `CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL=1`. The survey then logs ratings to the configured collector only. The transcript-share follow-up and all other Anthropic-bound feedback traffic stay disabled. To control frequency instead of disabling, set [`feedbackSurveyRate`](/docs/en/settings#available-settings) in your settings file to a probability between `0` and `1`.

39 39 

40### Data retention40### Data retention

41 41 


50**Commercial users (Team, Enterprise, and API)**:50**Commercial users (Team, Enterprise, and API)**:

51 51 

52* Standard: 30-day retention period52* Standard: 30-day retention period

53* [Zero data retention](/en/zero-data-retention): available to qualified accounts for Claude Code on Claude for Enterprise. ZDR is not included in the standard Enterprise plan; it is enabled on a per-organization basis by your account team after confirming eligibility53* [Zero data retention](/docs/en/zero-data-retention): available to qualified accounts for Claude Code on Claude for Enterprise. ZDR is not included in the standard Enterprise plan; it is enabled on a per-organization basis by your account team after confirming eligibility

54* Local caching: Claude Code clients store session transcripts locally in plaintext under `~/.claude/projects/` for 30 days by default to enable session resumption. Adjust the period with `cleanupPeriodDays`. See [application data](/en/claude-directory#application-data) for what's stored and how to clear it.54* Local caching: Claude Code clients store session transcripts locally in plaintext under `~/.claude/projects/` for 30 days by default to enable session resumption. Adjust the period with `cleanupPeriodDays`. See [application data](/docs/en/claude-directory#application-data) for what's stored and how to clear it.

55 55 

56You can delete individual Claude Code on the web sessions at any time. Deleting a session permanently removes the session's event data. For instructions on how to delete sessions, see [Delete sessions](/en/claude-code-on-the-web#delete-sessions).56You can delete individual Claude Code on the web sessions at any time. Deleting a session permanently removes the session's event data. For instructions on how to delete sessions, see [Delete sessions](/docs/en/claude-code-on-the-web#delete-sessions).

57 57 

58Learn more about data retention practices in our [Privacy Center](https://privacy.anthropic.com/).58Learn more about data retention practices in our [Privacy Center](https://privacy.anthropic.com/).

59 59 


61 61 

62## Data access62## Data access

63 63 

64For all first party users, you can learn more about what data is logged for [local Claude Code](#local-claude-code-data-flow-and-dependencies) and [remote Claude Code](#cloud-execution-data-flow-and-dependencies). [Remote Control](/en/remote-control) sessions follow the local data flow since all execution happens on your machine; while connected, the session transcript is also stored on Anthropic servers to sync the conversation across devices, as described in [Connection and security](/en/remote-control#connection-and-security). Note for remote Claude Code, Claude accesses the repository where you initiate your Claude Code session. Claude does not access repositories that you have connected but have not started a session in.64For all first party users, you can learn more about what data is logged for [local Claude Code](#local-claude-code-data-flow-and-dependencies) and [remote Claude Code](#cloud-execution-data-flow-and-dependencies). [Remote Control](/docs/en/remote-control) sessions follow the local data flow since all execution happens on your machine; while connected, the session transcript is also stored on Anthropic servers to sync the conversation across devices, as described in [Connection and security](/docs/en/remote-control#connection-and-security). Note for remote Claude Code, Claude accesses the repository where you initiate your Claude Code session. Claude does not access repositories that you have connected but have not started a session in.

65 65 

66## Local Claude Code: Data flow and dependencies66## Local Claude Code: Data flow and dependencies

67 67 


75 75 

76| Provider | Encryption at rest |76| Provider | Encryption at rest |

77| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |77| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

78| Anthropic API | Infrastructure-level disk encryption (AES-256). Enable [Zero Data Retention](/en/zero-data-retention) for no server-side persistence. |78| Anthropic API | Infrastructure-level disk encryption (AES-256). Enable [Zero Data Retention](/docs/en/zero-data-retention) for no server-side persistence. |

79| Amazon Bedrock | AES-256 with AWS-managed keys. Customer-managed keys available via AWS KMS. |79| Amazon Bedrock | AES-256 with AWS-managed keys. Customer-managed keys available via AWS KMS. |

80| Google Cloud's Agent Platform | Google-managed encryption keys. CMEK available. |80| Google Cloud's Agent Platform | Google-managed encryption keys. CMEK available. |

81| Microsoft Foundry | Depends on the deployment's [hosting option](https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry#hosting-options). For Hosted on Azure deployments, prompts and completions remain within Azure; only usage metadata and content flagged by Anthropic's safety systems egress to Anthropic. For Hosted on Anthropic deployments, requests route to Anthropic infrastructure with AES-256 disk encryption. |81| Microsoft Foundry | Depends on the deployment's [hosting option](https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry#hosting-options). For Hosted on Azure deployments, prompts and completions remain within Azure; only usage metadata and content flagged by Anthropic's safety systems egress to Anthropic. For Hosted on Anthropic deployments, requests route to Anthropic infrastructure with AES-256 disk encryption. |


84 84 

85### Cloud execution: Data flow and dependencies85### Cloud execution: Data flow and dependencies

86 86 

87When using [Claude Code on the web](/en/claude-code-on-the-web), sessions run in Anthropic-managed virtual machines instead of locally. In cloud environments:87When using [Claude Code on the web](/docs/en/claude-code-on-the-web), sessions run in Anthropic-managed virtual machines instead of locally. In cloud sessions:

88 88 

89* **Code and data storage:** Your repository is cloned to an isolated VM. Code and session data are subject to the retention and usage policies for your account type (see Data retention section above)89* **Code and data storage:** Your repository is cloned to an isolated VM. Code and session data are subject to the retention and usage policies for your account type (see Data retention section above)

90* **Credentials:** GitHub authentication is handled through a secure proxy; your GitHub credentials never enter the sandbox90* **Credentials:** GitHub authentication is handled through a secure proxy; your GitHub credentials never enter the sandbox

91* **Network traffic:** All outbound traffic goes through a security proxy for audit logging and abuse prevention91* **Network traffic:** All outbound traffic goes through a security proxy for audit logging and abuse prevention

92* **Session data:** Prompts, code changes, and outputs follow the same data policies as local Claude Code usage92* **Session data:** Prompts, code changes, and outputs follow the same data policies as local Claude Code usage

93 93 

94For security details about cloud execution, see [Security](/en/security#cloud-execution-security).94For security details about cloud execution, see [Security](/docs/en/security#cloud-execution-security).

95 95 

96## Telemetry services96## Telemetry services

97 97 

98Claude Code sends two kinds of operational telemetry: usage metrics and error reports. You can turn each off individually with the environment variables below, or disable all non-essential traffic at once by setting `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`.98Claude Code sends two kinds of operational telemetry: usage metrics and error reports. You can turn each off individually with the environment variables below, or disable all non-essential traffic at once by setting `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`. Setting `DISABLE_TELEMETRY` or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` also disables the feature-flag evaluation that [Remote Control](/docs/en/remote-control#requirements) depends on; `DISABLE_ERROR_REPORTING` doesn't.

99 99 

100**Metrics**: latency, reliability, and usage patterns, sent to Anthropic and to third-party logging infrastructure over TLS. Metrics never include your code, prompts, or file paths. Set `DISABLE_TELEMETRY=1` to opt out.100**Metrics**: latency, reliability, and usage patterns, sent to Anthropic and to third-party logging infrastructure over TLS. Metrics never include your code, prompts, or file paths. Set `DISABLE_TELEMETRY=1` to opt out.

101 101 


114 114 

115## Default behaviors by API provider115## Default behaviors by API provider

116 116 

117By default, error reporting, telemetry, and bug reporting are disabled when using Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, or Claude Platform on AWS. Session quality surveys and the WebFetch domain safety check are exceptions and run regardless of provider. On a signed-in [Claude apps gateway](/en/claude-apps-gateway) session, usage analytics, error reporting, and survey ratings to Anthropic are disabled by the gateway credential itself, with no setting to re-enable them. You can opt out of all non-essential traffic, including surveys, at once by setting `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`. This variable doesn't affect the WebFetch check or official plugin marketplace auto-install; each has its own opt-out: `skipWebFetchPreflight` in [settings](/en/settings) for WebFetch, and `CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL` for the marketplace. Here are the full default behaviors:117By default, error reporting, telemetry, and bug reporting are disabled when using Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, or Claude Platform on AWS. Session quality surveys and the WebFetch domain safety check are exceptions and run regardless of provider. On a signed-in [Claude apps gateway](/docs/en/claude-apps-gateway) session, usage analytics, error reporting, and survey ratings to Anthropic are disabled by the gateway credential itself, with no setting to re-enable them. You can opt out of all non-essential traffic, including surveys, at once by setting `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`. This variable doesn't affect the WebFetch check or official plugin marketplace auto-install; each has its own opt-out: `skipWebFetchPreflight` in [settings](/docs/en/settings) for WebFetch, and `CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL` for the marketplace. Here are the full default behaviors:

118 118 

119| Service | Claude API | Google Cloud's Agent Platform API | Amazon Bedrock API | Microsoft Foundry API | Claude Platform on AWS |119| Service | Claude API | Google Cloud's Agent Platform API | Amazon Bedrock API | Microsoft Foundry API | Claude Platform on AWS |

120| ------------------------------------ | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |120| ------------------------------------ | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |


122| **Error reports** | On for Pro and Max sign-ins on v2.1.198+, otherwise off.<br />`DISABLE_ERROR_REPORTING=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. | Default off.<br />`CLAUDE_CODE_USE_FOUNDRY` must be 1. | Default off.<br />`CLAUDE_CODE_USE_ANTHROPIC_AWS` must be 1. |122| **Error reports** | On for Pro and Max sign-ins on v2.1.198+, otherwise off.<br />`DISABLE_ERROR_REPORTING=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. | Default off.<br />`CLAUDE_CODE_USE_FOUNDRY` must be 1. | Default off.<br />`CLAUDE_CODE_USE_ANTHROPIC_AWS` must be 1. |

123| **Claude API (`/feedback` reports)** | Default on.<br />`DISABLE_FEEDBACK_COMMAND=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. | Default off.<br />`CLAUDE_CODE_USE_FOUNDRY` must be 1. | Default off.<br />`CLAUDE_CODE_USE_ANTHROPIC_AWS` must be 1. |123| **Claude API (`/feedback` reports)** | Default on.<br />`DISABLE_FEEDBACK_COMMAND=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. | Default off.<br />`CLAUDE_CODE_USE_FOUNDRY` must be 1. | Default off.<br />`CLAUDE_CODE_USE_ANTHROPIC_AWS` must be 1. |

124| **Session quality surveys** | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. |124| **Session quality surveys** | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. |

125| **WebFetch domain safety check** | Default on.<br />`skipWebFetchPreflight: true` in [settings](/en/settings) to disable. | Default on.<br />`skipWebFetchPreflight: true` in [settings](/en/settings) to disable. | Default on.<br />`skipWebFetchPreflight: true` in [settings](/en/settings) to disable. | Default on.<br />`skipWebFetchPreflight: true` in [settings](/en/settings) to disable. | Default on.<br />`skipWebFetchPreflight: true` in [settings](/en/settings) to disable. |125| **WebFetch domain safety check** | Default on.<br />`skipWebFetchPreflight: true` in [settings](/docs/en/settings) to disable. | Default on.<br />`skipWebFetchPreflight: true` in [settings](/docs/en/settings) to disable. | Default on.<br />`skipWebFetchPreflight: true` in [settings](/docs/en/settings) to disable. | Default on.<br />`skipWebFetchPreflight: true` in [settings](/docs/en/settings) to disable. | Default on.<br />`skipWebFetchPreflight: true` in [settings](/docs/en/settings) to disable. |

126 126 

127All environment variables can be checked into `settings.json` (see [settings reference](/en/settings)).127All environment variables can be checked into `settings.json` (see [settings reference](/docs/en/settings)).

128 128 

129As of v2.1.126, when a host platform sets `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST`, metrics default to on for Google Cloud's Agent Platform, Amazon Bedrock, and Microsoft Foundry, and follow the standard `DISABLE_TELEMETRY` opt-out. Error reporting and `/feedback` reports remain off by default on those providers.129As of v2.1.126, when a host platform sets `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST`, metrics default to on for Google Cloud's Agent Platform, Amazon Bedrock, and Microsoft Foundry, and follow the standard `DISABLE_TELEMETRY` opt-out. Error reporting and `/feedback` reports remain off by default on those providers.

130 130 


132 132 

133Before fetching a URL, the WebFetch tool sends the requested hostname to `api.anthropic.com` to check it against a safety blocklist maintained by Anthropic. Only the hostname is sent, not the full URL, path, or page contents. Results are cached per hostname for five minutes.133Before fetching a URL, the WebFetch tool sends the requested hostname to `api.anthropic.com` to check it against a safety blocklist maintained by Anthropic. Only the hostname is sent, not the full URL, path, or page contents. Results are cached per hostname for five minutes.

134 134 

135This check runs regardless of which model provider you use and is not affected by `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`. If your network blocks `api.anthropic.com`, WebFetch requests fail until you either allowlist the domain or set `skipWebFetchPreflight: true` in [settings](/en/settings). Disabling the check means WebFetch attempts to retrieve any URL without consulting the blocklist, so combine it with [`WebFetch` permission rules](/en/permissions#webfetch) if you need to restrict which domains Claude can reach.135This check runs regardless of which model provider you use and is not affected by `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`. If your network blocks `api.anthropic.com`, WebFetch requests fail until you either allowlist the domain or set `skipWebFetchPreflight: true` in [settings](/docs/en/settings). Disabling the check means WebFetch attempts to retrieve any URL without consulting the blocklist, so combine it with [`WebFetch` permission rules](/docs/en/permissions#webfetch) if you need to restrict which domains Claude can reach.

desktop.md +21 −8

Details

95 Start complex tasks in Plan so Claude maps out an approach before making changes. Once you approve the plan, switch to Accept edits or Manual to execute it. See [explore first, then plan, then code](/docs/en/best-practices#explore-first-then-plan-then-code) for more on this workflow.95 Start complex tasks in Plan so Claude maps out an approach before making changes. Once you approve the plan, switch to Accept edits or Manual to execute it. See [explore first, then plan, then code](/docs/en/best-practices#explore-first-then-plan-then-code) for more on this workflow.

96</Tip>96</Tip>

97 97 

98Cloud sessions support Accept edits, Plan, and Auto. Accept edits corresponds to `default` mode: cloud sessions pre-approve file edits, so the selector shows Accept edits instead of Manual. Bypass permissions is not available because the cloud environment is already sandboxed.98Cloud sessions support Accept edits, Plan, and Auto. Accept edits corresponds to `default` mode: cloud sessions pre-approve file edits, so the selector shows Accept edits instead of Manual. Bypass permissions is not available because cloud sessions already run in a sandboxed VM.

99 99 

100Enterprise admins can restrict which permission modes are available. See [enterprise configuration](#enterprise-configuration) for details.100Enterprise admins can restrict which permission modes are available. See [enterprise configuration](#enterprise-configuration) for details.

101 101 


328To include gitignored files like `.env` in new worktrees, create a [`.worktreeinclude` file](/docs/en/worktrees#copy-gitignored-files-into-worktrees) in your project root.328To include gitignored files like `.env` in new worktrees, create a [`.worktreeinclude` file](/docs/en/worktrees#copy-gitignored-files-into-worktrees) in your project root.

329 329 

330<Note>330<Note>

331 Session isolation requires [Git](https://git-scm.com/downloads). Most Macs include Git by default. Run `git --version` in Terminal to check. On Windows, Git is required for the Code tab to work: [download Git for Windows](https://git-scm.com/downloads/win), install it, and restart the app. If you run into Git errors, ask Claude in the [Cowork tab](https://claude.com/product/cowork) to help troubleshoot your setup.331 Session isolation requires [Git](https://git-scm.com/downloads). Most Macs include Git by default. Run `git --version` in Terminal to check; if it prints a version number, Git is installed. On Windows, Git is required for the Code tab to work: [download Git for Windows](https://git-scm.com/downloads/win), install it, and restart the app. If you run into Git errors, ask Claude in the [Cowork tab](https://claude.com/product/cowork) to help troubleshoot your setup.

332</Note>332</Note>

333 333 

334Use the controls at the top of the sidebar to filter sessions by status, project, or environment, and to group sessions by project. To rename a session, click the session title in the toolbar at the top of the active session. To check context usage, see [Check usage](#check-usage). When context fills up, Claude automatically summarizes the conversation and continues working. You can also type `/compact` to trigger summarization earlier and free up context space. See [the context window](/docs/en/how-claude-code-works#the-context-window) for details on how compaction works.334Use the controls at the top of the sidebar to filter sessions by status, project, or environment, and to group sessions by project. To rename a session, click the session title in the toolbar at the top of the active session. To check context usage, see [Check usage](#check-usage). When context fills up, Claude automatically summarizes the conversation and continues working. You can also type `/compact` to trigger summarization earlier and free up context space. See [the context window](/docs/en/how-claude-code-works#the-context-window) for details on how compaction works.


404 404 

405For local and [SSH](#ssh-sessions) sessions, click the **+** button next to the prompt box and select **Plugins** to see your installed plugins and their skills. To add a plugin, select **Add plugin** from the submenu to open the plugin browser, which shows available plugins from your configured [marketplaces](/docs/en/plugin-marketplaces) including the official Anthropic marketplace. Select **Manage plugins** to enable, disable, or uninstall plugins.405For local and [SSH](#ssh-sessions) sessions, click the **+** button next to the prompt box and select **Plugins** to see your installed plugins and their skills. To add a plugin, select **Add plugin** from the submenu to open the plugin browser, which shows available plugins from your configured [marketplaces](/docs/en/plugin-marketplaces) including the official Anthropic marketplace. Select **Manage plugins** to enable, disable, or uninstall plugins.

406 406 

407Plugins can be scoped to your user account, a specific project, or local-only. If your organization manages plugins centrally, those plugins are available in desktop sessions the same way they are in the CLI. The plugin browser is not available in cloud sessions, and plugins you install from the desktop app aren't available for cloud sessions; to use a plugin in a cloud session, declare it in the repository's `.claude/settings.json` under [`enabledPlugins`](/docs/en/settings#enabledplugins) so it [installs at session start](/docs/en/claude-code-on-the-web#what’s-available-in-cloud-sessions). Plugins aren't available in WSL sessions. For the full plugin reference including creating your own plugins, see [plugins](/docs/en/plugins).407Plugins can be scoped to your user account, a specific project, or local-only. If your organization manages plugins centrally, those plugins are available in desktop sessions the same way they are in the CLI. The plugin browser is not available in cloud sessions, and plugins you install from the desktop app aren't available for cloud sessions; to use a plugin in a cloud session, declare it in the repository's `.claude/settings.json` under [`enabledPlugins`](/docs/en/settings#enabledplugins) so it [installs at session start](/docs/en/cloud-environments#what-carries-over-from-your-setup). Plugins aren't available in WSL sessions. For the full plugin reference including creating your own plugins, see [plugins](/docs/en/plugins).

408 408 

409### Configure preview servers409### Configure preview servers

410 410 


438{438{

439 "version": "0.0.1",439 "version": "0.0.1",

440 "autoVerify": false,440 "autoVerify": false,

441 "configurations": [...]441 "configurations": [

442 {

443 "name": "my-app",

444 "runtimeExecutable": "npm",

445 "runtimeArgs": ["run", "dev"],

446 "port": 3000

447 }

448 ]

442}449}

443```450```

444 451 


612 619 

613Cloud sessions continue in the background even if you close the app. Usage counts toward your [subscription plan limits](/docs/en/costs) with no separate compute charges.620Cloud sessions continue in the background even if you close the app. Usage counts toward your [subscription plan limits](/docs/en/costs) with no separate compute charges.

614 621 

615You can create custom cloud environments with different network access levels and environment variables. Select the environment dropdown when starting a cloud session and choose **Add environment**. See [the cloud environment](/docs/en/claude-code-on-the-web#the-cloud-environment) for details on configuring network access and environment variables.622You can create custom cloud environments with different network access levels and environment variables. Select the environment dropdown when starting a cloud session and choose **Add cloud environment**. See [Configure cloud environments](/docs/en/cloud-environments) for details on configuring network access and environment variables.

616 623 

617### SSH sessions624### SSH sessions

618 625 


782 789 

783If you already use the Claude Code CLI, Desktop runs the same underlying engine with a graphical interface. You can run both simultaneously on the same machine, even on the same project. Each maintains separate session history, but they share configuration and project memory via CLAUDE.md files.790If you already use the Claude Code CLI, Desktop runs the same underlying engine with a graphical interface. You can run both simultaneously on the same machine, even on the same project. Each maintains separate session history, but they share configuration and project memory via CLAUDE.md files.

784 791 

785To move a CLI session into Desktop, run `/desktop` in the terminal. Claude saves your session and opens it in the desktop app, then exits the CLI. This command is available on macOS and Windows when you are signed in with a Claude subscription. It is not available with API key authentication or on Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry.792To move a CLI session into Desktop, run `/desktop` in the terminal. Claude saves your session and opens it in the desktop app, then exits the CLI. This command is available on macOS and x64 Windows when you are signed in with a Claude subscription. It is not available with API key authentication or on Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry.

786 793 

787<Tip>794<Tip>

788 When to use Desktop vs CLI: use Desktop when you want to manage parallel sessions in one window, arrange panes side by side, or review changes visually. Use the CLI when you need scripting, automation, or prefer a terminal workflow.795 When to use Desktop vs CLI: use Desktop when you want to manage parallel sessions in one window, arrange panes side by side, or review changes visually. Use the CLI when you need scripting, automation, or prefer a terminal workflow.


815* **[Settings](/docs/en/settings)** in `~/.claude.json` and `~/.claude/settings.json` are shared. Permission rules, allowed tools, and other settings in `settings.json` apply to Desktop sessions.822* **[Settings](/docs/en/settings)** in `~/.claude.json` and `~/.claude/settings.json` are shared. Permission rules, allowed tools, and other settings in `settings.json` apply to Desktop sessions.

816* **Models**: the same [models](/docs/en/model-config#available-models) are available in both. In Desktop, select the model from the dropdown next to the send button. You can change the model mid-session from the same dropdown.823* **Models**: the same [models](/docs/en/model-config#available-models) are available in both. In Desktop, select the model from the dropdown next to the send button. You can change the model mid-session from the same dropdown.

817 824 

818<Note>825#### MCP servers from the Claude Desktop chat app

819 **MCP servers from the Claude Desktop chat app**: the Desktop app loads MCP servers from `claude_desktop_config.json` into Code tab sessions, alongside servers from `~/.claude.json` and `.mcp.json`. A server defined in `claude_desktop_config.json` is available in both the Desktop chat surface and the Code tab.826 

827The Desktop app loads MCP servers from `claude_desktop_config.json` into local Code tab sessions, alongside servers from `~/.claude.json` and `.mcp.json`. A server you define in `claude_desktop_config.json` is available in both the Desktop chat surface and local Code tab sessions.

820 828 

829If you define the same server name in `claude_desktop_config.json` and in `~/.claude.json` or `.mcp.json`, the Code tab in local sessions connects once and uses the `claude_desktop_config.json` definition.

830 

831The app also re-delivers stdio servers from `~/.claude.json` to the embedded CLI in local sessions. When the top level of `~/.claude.json` (user scope) and `.mcp.json` define the same stdio server name, the Code tab uses the `~/.claude.json` definition, departing from the CLI [scope hierarchy](/docs/en/mcp#scope-hierarchy-and-precedence).

832 

833<Note>

821 The standalone CLI does not read `claude_desktop_config.json`. On macOS and WSL, run `claude mcp add-from-claude-desktop` to copy those servers into `~/.claude.json`. See [Import MCP servers from Claude Desktop](/docs/en/mcp#import-mcp-servers-from-claude-desktop) for the import flow and scope options.834 The standalone CLI does not read `claude_desktop_config.json`. On macOS and WSL, run `claude mcp add-from-claude-desktop` to copy those servers into `~/.claude.json`. See [Import MCP servers from Claude Desktop](/docs/en/mcp#import-mcp-servers-from-claude-desktop) for the import flow and scope options.

822</Note>835</Note>

823 836 

desktop-linux.md +15 −17

Details

10 Linux support for the Claude desktop app is in beta. The Chat, Cowork, and Code tabs are all available.10 Linux support for the Claude desktop app is in beta. The Chat, Cowork, and Code tabs are all available.

11</Note>11</Note>

12 12 

13The desktop app on Linux gives you the same Chat, Cowork, and Claude Code experience as macOS and Windows: parallel sessions, visual diff review, an integrated terminal and editor, and live app preview. See [Use Claude Code Desktop](/en/desktop) for the full feature reference.13The desktop app on Linux gives you the same Chat, Cowork, and Claude Code experience as macOS and Windows: parallel sessions, visual diff review, an integrated terminal and editor, and live app preview. See [Use Claude Code Desktop](/docs/en/desktop) for the full feature reference.

14 14 

15## Requirements15## Requirements

16 16 


25 25 

26<Steps>26<Steps>

27 <Step title="Add Anthropic's apt repository">27 <Step title="Add Anthropic's apt repository">

28 This step downloads the signing key with `curl`, which fresh Debian and Ubuntu installations may not include. If the download command fails with `sudo: curl: command not found`, install curl first:28 This step downloads the signing key with `curl` and verifies it with `gpg`, which fresh Debian and Ubuntu installations may not include. If either command reports `command not found`, install both first:

29 29 

30 ```bash theme={null}30 ```bash theme={null}

31 sudo apt install curl31 sudo apt install curl gnupg

32 ```32 ```

33 33 

34 Download Anthropic's signing key:34 Download Anthropic's signing key:


37 sudo curl -fsSLo /usr/share/keyrings/claude-desktop-archive-keyring.asc https://downloads.claude.ai/claude-desktop/key.asc37 sudo curl -fsSLo /usr/share/keyrings/claude-desktop-archive-keyring.asc https://downloads.claude.ai/claude-desktop/key.asc

38 ```38 ```

39 39 

40 If this download fails, `apt update` later fails with `NO_PUBKEY BAA929FF1A7ECACE`. Confirm the key downloaded and belongs to Anthropic before continuing:

41 

42 ```bash theme={null}

43 gpg --show-keys /usr/share/keyrings/claude-desktop-archive-keyring.asc

44 ```

45 

46 The fingerprint gpg prints should be `31DDDE24DDFAB679F42D7BD2BAA929FF1A7ECACE`. If gpg reports that the file can't be opened or contains no valid OpenPGP data, the download failed or returned the wrong content: confirm your network can reach `downloads.claude.ai`, then rerun the download command.

47 

40 Register the repository:48 Register the repository:

41 49 

42 ```bash theme={null}50 ```bash theme={null}


53 <Step title="Launch and sign in">61 <Step title="Launch and sign in">

54 Launch **Claude** from your application launcher, or run `claude-desktop` from a terminal, and sign in with your Anthropic account.62 Launch **Claude** from your application launcher, or run `claude-desktop` from a terminal, and sign in with your Anthropic account.

55 63 

56 The Linux app signs in the same way as on macOS and Windows: with a claude.ai subscription, or through your organization's SSO. Desktop doesn't accept a Claude Console API key directly; use the [CLI](/en/quickstart) for API-key authentication. For enterprise deployments that route Desktop to Google Cloud's Agent Platform or an LLM gateway, see [Claude Desktop on 3P](https://claude.com/docs/third-party/claude-desktop/overview) and [network configuration](/en/network-config).64 The Linux app signs in the same way as on macOS and Windows: with a claude.ai subscription, or through your organization's SSO. Desktop doesn't accept a Claude Console API key directly; use the [CLI](/docs/en/quickstart) for API-key authentication. For enterprise deployments that route Desktop to Google Cloud's Agent Platform or an LLM gateway, see [Claude Desktop on 3P](https://claude.com/docs/third-party/claude-desktop/overview) and [network configuration](/docs/en/network-config).

57 </Step>65 </Step>

58</Steps>66</Steps>

59 67 

60<Accordion title="Verify the signing key">

61 You can confirm the downloaded signing key belongs to Anthropic:

62 

63 ```bash theme={null}

64 gpg --show-keys /usr/share/keyrings/claude-desktop-archive-keyring.asc

65 ```

66 

67 The fingerprint should be `31DD DE24 DDFA B679 F42D 7BD2 BAA9 29FF 1A7E CACE`.

68</Accordion>

69 

70### Install from a downloaded file68### Install from a downloaded file

71 69 

72If you can't install through the apt repository, download the `.deb` package directly from the repository's package pool. This command looks up the newest package for your architecture in the repository index, then downloads it to the current directory:70If you can't install through the apt repository, download the `.deb` package directly from the repository's package pool. This command looks up the newest package for your architecture in the repository index, then downloads it to the current directory:


123 121 

124## What's not in the Linux beta yet122## What's not in the Linux beta yet

125 123 

126* **Computer Use**: [app and screen control](/en/desktop#let-claude-use-your-computer) isn't available on Linux.124* **Computer Use**: [app and screen control](/docs/en/desktop#let-claude-use-your-computer) isn't available on Linux.

127* **Dictation**: voice input isn't available in the Linux desktop app. Use [voice dictation](/en/voice-dictation) in the CLI instead.125* **Dictation**: voice input isn't available in the Linux desktop app. Use [voice dictation](/docs/en/voice-dictation) in the CLI instead.

128* **Quick Entry global hotkey**: works on X11. On native Wayland it requires your desktop environment's GlobalShortcuts portal.126* **Quick Entry global hotkey**: works on X11. On native Wayland it requires your desktop environment's GlobalShortcuts portal.

129* **Fedora and RHEL**: only Debian-based distributions are supported today. Support for additional distributions is coming in the future.127* **Fedora and RHEL**: only Debian-based distributions are supported today. Support for additional distributions is coming in the future.

130 128 

131For anything not yet available in the desktop app, the [CLI](/en/quickstart) runs the same Claude Code engine and supports a wider range of Linux distributions; see the [system requirements](/en/setup#system-requirements).129For anything not yet available in the desktop app, the [CLI](/docs/en/quickstart) runs the same Claude Code engine and supports a wider range of Linux distributions; see the [system requirements](/docs/en/setup#system-requirements).

devcontainer.md +35 −26

Details

12 12 

13<Warning>13<Warning>

14 While the dev container provides substantial protections, no system is completely immune to all attacks.14 While the dev container provides substantial protections, no system is completely immune to all attacks.

15 When executed with `--dangerously-skip-permissions`, dev containers do not prevent a malicious project from exfiltrating anything accessible inside the container, including the Claude Code credentials stored in [`~/.claude`](/en/claude-directory).15 When executed with `--dangerously-skip-permissions`, dev containers do not prevent a malicious project from exfiltrating anything accessible inside the container, including the Claude Code credentials stored in [`~/.claude`](/docs/en/claude-directory).

16 Only use dev containers when developing with trusted repositories, and monitor Claude's activities.16 Only use dev containers when developing with trusted repositories, and monitor Claude's activities.

17 Avoid mounting host secrets such as `~/.ssh` or cloud credential files into the container; prefer repository-scoped or short-lived tokens.17 Avoid mounting host secrets such as `~/.ssh` or cloud credential files into the container; prefer repository-scoped or short-lived tokens.

18</Warning>18</Warning>


24 24 

25 A dev container runs as a Docker container, either on your machine or on a cloud host such as GitHub Codespaces. An editor that supports the Dev Containers spec, such as VS Code, GitHub Codespaces, a JetBrains IDE, or Cursor, connects to that container: you browse and edit files in the editor as usual, but the integrated terminal, language servers, and build tools all run inside the container rather than on your host. Editors without dev container support, such as plain Vim, are not part of this workflow.25 A dev container runs as a Docker container, either on your machine or on a cloud host such as GitHub Codespaces. An editor that supports the Dev Containers spec, such as VS Code, GitHub Codespaces, a JetBrains IDE, or Cursor, connects to that container: you browse and edit files in the editor as usual, but the integrated terminal, language servers, and build tools all run inside the container rather than on your host. Editors without dev container support, such as plain Vim, are not part of this workflow.

26 26 

27 Claude Code runs inside the container, so it sees the same files, dependencies, and tools as the rest of your project's toolchain. In VS Code you can use either the [Claude Code extension panel](/en/vs-code) or run `claude` in the integrated terminal; both run inside the container and share the same `~/.claude` configuration.27 Claude Code runs inside the container, so it sees the same files, dependencies, and tools as the rest of your project's toolchain. In VS Code you can use either the [Claude Code extension panel](/docs/en/vs-code) or run `claude` in the integrated terminal; both run inside the container and share the same `~/.claude` configuration.

28</Accordion>28</Accordion>

29 29 

30## Add Claude Code to your dev container30## Add Claude Code to your dev container


57 ```57 ```

58 58 

59 Replace the `image` line with your project's base image or remove it if your existing file uses a Dockerfile.59 Replace the `image` line with your project's base image or remove it if your existing file uses a Dockerfile.

60 

61 The Claude Code feature installs Node.js itself when the base image doesn't provide it. If that install fails and the build stops with `Failed to install Node.js and npm`, add `"ghcr.io/devcontainers/features/node:1": {}` to the `features` block above the Claude Code feature and rebuild.

60 </Step>62 </Step>

61 63 

62 <Step title="Rebuild the container">64 <Step title="Rebuild the container">


73What you see at the authentication prompt depends on your provider:75What you see at the authentication prompt depends on your provider:

74 76 

75* **Anthropic**: sign in through a browser with your Claude or Anthropic Console account77* **Anthropic**: sign in through a browser with your Claude or Anthropic Console account

76* **[Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry](/en/third-party-integrations)**: Claude Code uses your cloud provider credentials, with no browser prompt78* **[Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry](/docs/en/third-party-integrations)**: Claude Code uses your cloud provider credentials, with no browser prompt

77 79 

78For cloud providers, pass credentials into the container as environment variables through `containerEnv`, a Codespaces secret, or your cloud's workload identity rather than mounting credential files from the host. See [Amazon Bedrock](/en/amazon-bedrock), [Google Cloud's Agent Platform](/en/google-vertex-ai), or [Microsoft Foundry](/en/microsoft-foundry) for the credential chain Claude Code reads.80For cloud providers, pass credentials into the container as environment variables through `containerEnv`, a Codespaces secret, or your cloud's workload identity rather than mounting credential files from the host. See [Amazon Bedrock](/docs/en/amazon-bedrock), [Google Cloud's Agent Platform](/docs/en/google-vertex-ai), or [Microsoft Foundry](/docs/en/microsoft-foundry) for the credential chain Claude Code reads.

79 81 

80See [Choose your API provider](/en/admin-setup#choose-your-api-provider) to decide which path fits your organization.82See [Choose your API provider](/docs/en/admin-setup#choose-your-api-provider) to decide which path fits your organization.

81 83 

82<Note>84<Note>

83 If the browser sign-in completes but the callback never reaches the container, copy the code shown in the browser and paste it at the `Paste code here if prompted` prompt in the terminal. This can happen when the editor's port forwarding doesn't route the localhost callback.85 If the browser sign-in completes but the callback never reaches the container, copy the code shown in the browser and paste it at the `Paste code here if prompted` prompt in the terminal. This can happen when the editor's port forwarding doesn't route the localhost callback.


85 87 

86## Persist authentication and settings across rebuilds88## Persist authentication and settings across rebuilds

87 89 

88By default, the container's home directory is discarded on rebuild, so engineers must sign in again each time. Claude Code stores its authentication token, user settings, and session history under [`~/.claude`](/en/claude-directory). Mount a named volume at that path to keep this state across rebuilds.90By default, the container's home directory is discarded on rebuild, so engineers must sign in again each time. Claude Code stores its authentication token, user settings, and session history under the [`~/.claude`](/docs/en/claude-directory) directory. It stores your OAuth account, personal MCP servers, and per-project trust in [`~/.claude.json`](/docs/en/settings#global-config-settings), a separate file outside that directory, so mounting a volume at `~/.claude` alone doesn't keep you signed in. Mount a named volume at `~/.claude` and set [`CLAUDE_CONFIG_DIR`](/docs/en/env-vars) to the same path so Claude Code writes `.claude.json` inside the volume.

89 91 

90The following example mounts a volume at the home directory of the `node` user:92The following example mounts the volume and sets `CLAUDE_CONFIG_DIR` for a container whose `remoteUser` is `node`:

91 93 

92```json devcontainer.json theme={null}94```json devcontainer.json theme={null}

93"mounts": [95"mounts": [

94 "source=claude-code-config,target=/home/node/.claude,type=volume"96 "source=claude-code-config,target=/home/node/.claude,type=volume"

95]97],

98"containerEnv": {

99 "CLAUDE_CONFIG_DIR": "/home/node/.claude"

100}

96```101```

97 102 

98Replace `/home/node` with the home directory of your container's `remoteUser`. If you mount the volume somewhere other than `~/.claude`, set [`CLAUDE_CONFIG_DIR`](/en/env-vars) to the mount path so Claude Code reads and writes there.103Replace `/home/node` with the home directory of your container's `remoteUser`. If you already set `containerEnv`, for example in [Enforce organization policy](#enforce-organization-policy), add `CLAUDE_CONFIG_DIR` to that object rather than adding a second one.

99 104 

100To isolate state per project rather than sharing one volume across all repositories, include the `${devcontainerId}` variable in the source name. The [reference configuration](https://github.com/anthropics/claude-code/blob/main/.devcontainer/devcontainer.json) uses `source=claude-code-config-${devcontainerId}` for this purpose.105To isolate state per project rather than sharing one volume across all repositories, include the `${devcontainerId}` variable in the source name. The [reference configuration](https://github.com/anthropics/claude-code/blob/main/.devcontainer/devcontainer.json) uses `source=claude-code-config-${devcontainerId}` for this purpose.

101 106 

102In GitHub Codespaces, `~/.claude` persists across stopping and starting a codespace, but is still cleared when you rebuild the container, so the volume mount above applies there too. To carry authentication across codespaces, store `ANTHROPIC_API_KEY` or a `CLAUDE_CODE_OAUTH_TOKEN` from [`claude setup-token`](/en/authentication#generate-a-long-lived-token) as a [Codespaces secret](https://docs.github.com/en/codespaces/managing-your-codespaces/managing-your-account-specific-secrets-for-github-codespaces); Codespaces makes secrets available as environment variables inside the container automatically.107In GitHub Codespaces, `~/.claude` persists when you stop and start a codespace but is cleared when you rebuild the container, so the configuration above applies there too.

108 

109To carry authentication across codespaces, store `ANTHROPIC_API_KEY` or a `CLAUDE_CODE_OAUTH_TOKEN` from [`claude setup-token`](/docs/en/authentication#generate-a-long-lived-token) as a [Codespaces secret](https://docs.github.com/en/codespaces/managing-your-codespaces/managing-your-account-specific-secrets-for-github-codespaces). Codespaces exposes secrets as environment variables inside the container automatically.

103 110 

104## Enforce organization policy111## Enforce organization policy

105 112 

106A dev container is a convenient place to apply organization policy, because the same image and configuration run on every engineer's machine.113A dev container is a convenient place to apply organization policy, because the same image and configuration run on every engineer's machine.

107 114 

108Claude Code reads `/etc/claude-code/managed-settings.json` on Linux and applies it at the highest precedence in the [settings hierarchy](/en/settings#how-scopes-interact), so values there override anything an engineer sets in `~/.claude` or the project's `.claude/` directory. Copy the file into place from your Dockerfile:115Claude Code reads `/etc/claude-code/managed-settings.json` on Linux and applies it at the highest precedence in the [settings hierarchy](/docs/en/settings#how-scopes-interact), so values there override anything an engineer sets in `~/.claude` or the project's `.claude/` directory. Copy the file into place from your Dockerfile:

109 116 

110```dockerfile Dockerfile theme={null}117```dockerfile Dockerfile theme={null}

111RUN mkdir -p /etc/claude-code118RUN mkdir -p /etc/claude-code

112COPY managed-settings.json /etc/claude-code/managed-settings.json119COPY managed-settings.json /etc/claude-code/managed-settings.json

113```120```

114 121 

115Because the Dockerfile lives in the repository, anyone with write access can change or remove this step. For policy that engineers cannot bypass by editing repository files, deliver managed settings through [server-managed settings](/en/server-managed-settings) or your MDM instead. See [managed settings files](/en/settings#settings-files) for the available keys and the other delivery paths.122Because the Dockerfile lives in the repository, anyone with write access can change or remove this step. For policy that engineers cannot bypass by editing repository files, deliver managed settings through [server-managed settings](/docs/en/server-managed-settings) or your MDM instead. See [managed settings files](/docs/en/settings#settings-files) for the available keys and the other delivery paths.

116 123 

117To set [environment variables](/en/env-vars) that apply to every Claude Code session in the container, add them to `containerEnv` in your `devcontainer.json`. The following example opts out of telemetry and error reporting and prevents Claude Code from auto-updating after install:124To set [environment variables](/docs/en/env-vars) that apply to every Claude Code session in the container, add them to `containerEnv` in your `devcontainer.json`. The following example opts out of telemetry and error reporting and prevents Claude Code from auto-updating after install:

118 125 

119```json devcontainer.json theme={null}126```json devcontainer.json theme={null}

120"containerEnv": {127"containerEnv": {


123}130}

124```131```

125 132 

133`CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` also disables the feature-flag evaluation that [Remote Control](/docs/en/remote-control#requirements) depends on, so sessions in the container can't use Remote Control.

134 

126The Dev Container Feature always installs the latest Claude Code release. To pin a specific Claude Code version for reproducible builds, install it from your Dockerfile with `npm install -g @anthropic-ai/claude-code@X.Y.Z` instead of using the feature, and set `DISABLE_AUTOUPDATER` as shown above.135The Dev Container Feature always installs the latest Claude Code release. To pin a specific Claude Code version for reproducible builds, install it from your Dockerfile with `npm install -g @anthropic-ai/claude-code@X.Y.Z` instead of using the feature, and set `DISABLE_AUTOUPDATER` as shown above.

127 136 

128For the full list of policy controls including permission rules, tool restrictions, and MCP server allowlists, see [Set up Claude Code for your organization](/en/admin-setup).137For the full list of policy controls including permission rules, tool restrictions, and MCP server allowlists, see [Set up Claude Code for your organization](/docs/en/admin-setup).

129 138 

130To make [MCP servers](/en/mcp) available inside the container, define them at [project scope](/en/mcp#mcp-installation-scopes) in a `.mcp.json` file at the repository root so they are checked in alongside your dev container configuration. Install any binaries that local stdio servers depend on in your Dockerfile, and add remote server domains to your network allowlist.139To make [MCP servers](/docs/en/mcp) available inside the container, define them at [project scope](/docs/en/mcp#mcp-installation-scopes) in a `.mcp.json` file at the repository root so they are checked in alongside your dev container configuration. Install any binaries that local stdio servers depend on in your Dockerfile, and add remote server domains to your network allowlist.

131 140 

132## Restrict network egress141## Restrict network egress

133 142 

134You can limit the container's outbound traffic to only the domains Claude Code needs. See [Network access requirements](/en/network-config#network-access-requirements) for the inference and authentication domains, and [Telemetry services](/en/data-usage#telemetry-services) for the optional telemetry and error reporting connections and how to disable them.143You can limit the container's outbound traffic to only the domains Claude Code needs. See [Network access requirements](/docs/en/network-config#network-access-requirements) for the inference and authentication domains, and [Telemetry services](/docs/en/data-usage#telemetry-services) for the optional telemetry and error reporting connections and how to disable them.

135 144 

136The reference container includes an [`init-firewall.sh`](https://github.com/anthropics/claude-code/blob/main/.devcontainer/init-firewall.sh) script that blocks all outbound traffic except the domains Claude Code and your development tools need. Running a firewall inside a container requires extra permissions, so the reference adds the `NET_ADMIN` and `NET_RAW` capabilities through `runArgs`. The firewall script and these capabilities are not required for Claude Code itself: you can leave them out and rely on your own network controls instead.145The reference container includes an [`init-firewall.sh`](https://github.com/anthropics/claude-code/blob/main/.devcontainer/init-firewall.sh) script that blocks all outbound traffic except the domains Claude Code and your development tools need. Running a firewall inside a container requires extra permissions, so the reference adds the `NET_ADMIN` and `NET_RAW` capabilities through `runArgs`. The firewall script and these capabilities are not required for Claude Code itself: you can leave them out and rely on your own network controls instead.

137 146 


141 150 

142Skipping permission prompts removes your opportunity to review tool calls before they run. Claude can still modify any file in the bind-mounted workspace, which appears directly on your host, and reach anything the container's network policy allows. Pair this flag with the [network egress restrictions](#restrict-network-egress) above to limit what a bypassed session can reach.151Skipping permission prompts removes your opportunity to review tool calls before they run. Claude can still modify any file in the bind-mounted workspace, which appears directly on your host, and reach anything the container's network policy allows. Pair this flag with the [network egress restrictions](#restrict-network-egress) above to limit what a bypassed session can reach.

143 152 

144If you want fewer prompts without disabling safety checks, consider [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) instead, which has a classifier review actions before they run. To prevent engineers from using `--dangerously-skip-permissions` at all, set `permissions.disableBypassPermissionsMode` to `"disable"` in [managed settings](/en/settings#permission-settings).153If you want fewer prompts without disabling safety checks, consider [auto mode](/docs/en/permission-modes#eliminate-prompts-with-auto-mode) instead, which has a classifier review actions before they run. To prevent engineers from using `--dangerously-skip-permissions` at all, set `permissions.disableBypassPermissionsMode` to `"disable"` in [managed settings](/docs/en/settings#permission-settings).

145 154 

146## Try the reference container155## Try the reference container

147 156 


179 188 

180Once Claude Code is running in your dev container, the pages below cover the rest of an organization rollout: choosing an authentication path, delivering managed policy outside the repository, monitoring usage, and understanding what Claude Code stores and sends.189Once Claude Code is running in your dev container, the pages below cover the rest of an organization rollout: choosing an authentication path, delivering managed policy outside the repository, monitoring usage, and understanding what Claude Code stores and sends.

181 190 

182* [Set up Claude Code for your organization](/en/admin-setup): choose an authentication provider, decide how policy reaches devices, and plan the rollout191* [Set up Claude Code for your organization](/docs/en/admin-setup): choose an authentication provider, decide how policy reaches devices, and plan the rollout

183* [Server-managed settings](/en/server-managed-settings): deliver managed policy from the Claude.ai admin console so engineers cannot bypass it by editing repository files192* [Server-managed settings](/docs/en/server-managed-settings): deliver managed policy from the Claude.ai admin console so engineers cannot bypass it by editing repository files

184* [Monitor usage and audit activity](/en/monitoring-usage): export OpenTelemetry metrics and review what your team is running193* [Monitor usage and audit activity](/docs/en/monitoring-usage): export OpenTelemetry metrics and review what your team is running

185* [Network access requirements](/en/network-config#network-access-requirements): the full domain allowlist for proxies and firewalls194* [Network access requirements](/docs/en/network-config#network-access-requirements): the full domain allowlist for proxies and firewalls

186* [Telemetry services and opt-out](/en/data-usage#telemetry-services): what Claude Code sends by default and the environment variables that disable it195* [Telemetry services and opt-out](/docs/en/data-usage#telemetry-services): what Claude Code sends by default and the environment variables that disable it

187* [Explore the `.claude` directory](/en/claude-directory): what the volume mount holds, including credentials, settings, and session history196* [Explore the `.claude` directory](/docs/en/claude-directory): what the volume mount holds, including credentials, settings, and session history

188* [Sandbox environments](/en/sandbox-environments): compare dev containers with the built-in Bash sandbox, custom containers, and VMs197* [Sandbox environments](/docs/en/sandbox-environments): compare dev containers with the built-in Bash sandbox, custom containers, and VMs

189* [Security model](/en/security): how Claude Code's permission system, sandboxing, and prompt-injection protections fit together198* [Security model](/docs/en/security): how Claude Code's permission system, sandboxing, and prompt-injection protections fit together

190* [Permission modes](/en/permission-modes): the full range from plan mode to auto mode to bypass, and when to use each199* [Permission modes](/docs/en/permission-modes): the full range from plan mode to auto mode to bypass, and when to use each

Details

28 28 

29## Official Anthropic marketplace29## Official Anthropic marketplace

30 30 

31The official Anthropic marketplace (`claude-plugins-official`) is automatically available when you start Claude Code. Run `/plugin` and go to the **Discover** tab to browse what's available, or view the catalog at [claude.com/plugins](https://claude.com/plugins).31Claude Code adds the official Anthropic marketplace (`claude-plugins-official`) automatically when you start it. If Claude Code can't add it, for example because your network blocks the download, add it yourself with `/plugin marketplace add anthropics/claude-plugins-official`.

32 

33To browse what's available, run `/plugin` and go to the **Discover** tab, or view the catalog at [claude.com/plugins](https://claude.com/plugins).

32 34 

33To install a plugin from the official marketplace, use `/plugin install <name>@claude-plugins-official`. For example, to install the GitHub integration:35To install a plugin from the official marketplace, use `/plugin install <name>@claude-plugins-official`. For example, to install the GitHub integration:

34 36 


76 78 

77Once a code intelligence plugin is installed and its language server binary is available, Claude gains two capabilities:79Once a code intelligence plugin is installed and its language server binary is available, Claude gains two capabilities:

78 80 

79* **Automatic diagnostics**: after every file edit Claude makes, the language server analyzes the changes and reports errors and warnings back automatically. Claude sees type errors, missing imports, and syntax issues without needing to run a compiler or linter. If Claude introduces an error, it notices and fixes the issue in the same turn. This requires no configuration beyond installing the plugin. You can see diagnostics inline by pressing **Ctrl+O** when the "diagnostics found" indicator appears.81* **Automatic diagnostics**: after every file edit Claude makes, the language server reports errors and warnings back, so Claude sees type errors, missing imports, and syntax issues without running a compiler or linter. If Claude introduces an error, it notices and fixes it in the same turn.

80* **Code navigation**: Claude can use the language server to jump to definitions, find references, get type info on hover, list symbols, find implementations, and trace call hierarchies. These operations give Claude more precise navigation than grep-based search, though availability may vary by language and environment.82* **Code navigation**: Claude can use the language server to jump to definitions, find references, get type info on hover, list symbols, find implementations, and trace call hierarchies. These operations give Claude more precise navigation than grep-based search, though availability may vary by language and environment.

81 83 

84You don't need to configure diagnostics beyond installing the plugin. To read them yourself, press **Ctrl+O** when Claude Code shows an indicator such as **Found 3 new diagnostic issues in 2 files**.

85 

82If you run into issues, see [Code intelligence troubleshooting](#code-intelligence-issues).86If you run into issues, see [Code intelligence troubleshooting](#code-intelligence-issues).

83 87 

84### External integrations88### External integrations


161 * {/* min-version: 2.1.144 */}The plugin's **Last updated** date (v2.1.144 and later)165 * {/* min-version: 2.1.144 */}The plugin's **Last updated** date (v2.1.144 and later)

162 * {/* min-version: 2.1.145 */}A **Will install** section listing the plugin's commands, agents, skills, hooks, and MCP and LSP servers, so you can review exactly what it adds before installing (v2.1.145 and later)166 * {/* min-version: 2.1.145 */}A **Will install** section listing the plugin's commands, agents, skills, hooks, and MCP and LSP servers, so you can review exactly what it adds before installing (v2.1.145 and later)

163 167 

168 Not every plugin provides the data behind these fields. For plugins from local or custom marketplaces, you may not see the **Context cost** and **Last updated** rows, and the **Will install** section may show **Components will be discovered at installation** instead.

169 

164 Choose an installation scope:170 Choose an installation scope:

165 171 

166 * **User scope**: install for yourself across all projects172 * **User scope**: install for yourself across all projects


270 276 

271## Install plugins277## Install plugins

272 278 

273Once you've added marketplaces, you can install plugins directly:279Once you've added marketplaces, you can install a plugin by name:

274 280 

275```shell theme={null}281```shell theme={null}

276/plugin install plugin-name@marketplace-name282/plugin install plugin-name@marketplace-name


321 327 

322When you install a plugin that declares dependencies, the install output lists which dependencies were auto-installed alongside it.328When you install a plugin that declares dependencies, the install output lists which dependencies were auto-installed alongside it.

323 329 

324You can also manage plugins with direct commands.330You can also manage plugins with direct commands:

331 

332* When you run `/plugin disable`, `/plugin enable`, or `/plugin uninstall`, Claude Code opens the plugin panel to apply the change and leaves it open. Press **Esc** to close the panel before typing another command.

333* For scripting, use the `claude plugin` shell commands instead, which don't open the panel.

325 334 

326List installed plugins without opening the menu:335List installed plugins without opening the menu:

327 336 


368/reload-plugins377/reload-plugins

369```378```

370 379 

371Claude Code reloads all active plugins and shows counts for plugins, skills, agents, hooks, plugin MCP servers, and plugin LSP servers.380Claude Code reloads all active plugins and shows counts for plugins, skills, agents, hooks, plugin MCP servers, and plugin LSP servers. The skills count covers only each plugin's `commands/` directory, not its `skills/` directory, so the summary can report `0 skills` even when the plugin's skills reloaded.

372 381 

373Reloading has a token cost on the next request: newly loaded components announce themselves in content appended to the conversation, while the existing history still reads from the prompt cache. A plugin that provides MCP servers costs more when its tools aren't deferred by [tool search](/docs/en/mcp#scale-with-mcp-tool-search): the change invalidates the cache and the next request re-reads the entire conversation. {/* min-version: 2.1.163 */}In that case `/reload-plugins` shows a warning and does not apply the reload; pass `--force` to apply anyway. See [enabling or disabling a plugin](/docs/en/prompt-caching#enabling-or-disabling-a-plugin) for details.382Reloading has a token cost on the next request: newly loaded components announce themselves in content appended to the conversation, while the existing history still reads from the prompt cache. A plugin that provides MCP servers costs more when its tools aren't deferred by [tool search](/docs/en/mcp#scale-with-mcp-tool-search): the change invalidates the cache and the next request re-reads the entire conversation. {/* min-version: 2.1.163 */}In that case `/reload-plugins` shows a warning and does not apply the reload; pass `--force` to apply anyway. See [enabling or disabling a plugin](/docs/en/prompt-caching#enabling-or-disabling-a-plugin) for details.

374 383 

env-vars.md +16 −14

Details

89The file you choose controls who the variables apply to:89The file you choose controls who the variables apply to:

90 90 

91| File | Applies to |91| File | Applies to |

92| :---------------------------- | :---------------------------------------------------------------------------- |92| :---------------------------- | :------------------------------------------------------------------------------------------------------------------------------ |

93| `~/.claude/settings.json` | You, in every project |93| `~/.claude/settings.json` | You, in every project |

94| `.claude/settings.json` | Everyone working in the project, checked into source control |94| `.claude/settings.json` | Everyone working in the project, checked into source control |

95| `.claude/settings.local.json` | You, in this project only (add it to your gitignore if you create it by hand) |95| `.claude/settings.local.json` | You, in this project only, gitignored when Claude Code saves a setting to it; add it to your gitignore if you create it by hand |

96| Managed settings | Everyone in your organization, deployed by an admin |96| Managed settings | Everyone in your organization, deployed by an admin |

97 97 

98See [Settings files](/docs/en/settings#settings-files) for where each file lives and [Settings precedence](/docs/en/settings#settings-precedence) for how they combine when more than one sets the same variable.98See [Settings files](/docs/en/settings#settings-files) for where each file lives and [Settings precedence](/docs/en/settings#settings-precedence) for how they combine when more than one sets the same variable.

99 99 

100## Precedence100## Precedence

101 101 

102Where the same behavior has both an environment variable and a settings field, the environment variable takes precedence. For example, `ANTHROPIC_MODEL` overrides the `model` setting, and `CLAUDE_CODE_AUTO_CONNECT_IDE` overrides `autoConnectIde`. The settings field applies when the environment variable is not set.102Some behaviors have both an environment variable and a dedicated settings key. If you set both, the environment variable takes precedence. For example, `ANTHROPIC_MODEL` overrides the `model` setting, and `CLAUDE_CODE_AUTO_CONNECT_IDE` overrides `autoConnectIde`. Claude Code uses the settings key only when the environment variable is unset.

103 103 

104When the same variable is set in both your shell and a settings file `env` block, the settings file value applies. Claude Code writes each `env` entry into the process environment at startup and again when the file changes, replacing the value inherited from the shell. A few variables are special-cased; the [`env` setting](/docs/en/settings#available-settings) lists the exceptions.104When the same variable is set in both your shell and a settings file `env` block, the settings file value applies. Claude Code writes each `env` entry into the process environment at startup and again when the file changes, replacing the value inherited from the shell. A few variables are special-cased; the [`env` setting](/docs/en/settings#available-settings) lists the exceptions.

105 105 

106In a settings file you can set a variable but you can't remove one. To override a variable you can't unset, such as a stale `CLAUDE_CODE_USE_VERTEX` exported by a shell profile you don't control, set it to an empty string in the `env` block: `"CLAUDE_CODE_USE_VERTEX": ""`. Claude Code treats the empty value as unset for provider selection. Subprocesses still inherit the empty value.

107 

106Between settings files, `env` values follow [settings precedence](/docs/en/settings#settings-precedence), so a managed settings entry overrides the same variable in user or project settings.108Between settings files, `env` values follow [settings precedence](/docs/en/settings#settings-precedence), so a managed settings entry overrides the same variable in user or project settings.

107 109 

108How an environment variable interacts with CLI flags and in-session commands varies per feature: `--model` and `/model` override `ANTHROPIC_MODEL`, while `CLAUDE_CODE_EFFORT_LEVEL` overrides `/effort`. When a variable interacts with another configuration source, its row in the [Variables](#variables) list states the precedence or links to the page that documents it.110How an environment variable interacts with CLI flags and in-session commands varies per feature: `--model` and `/model` override `ANTHROPIC_MODEL`, while `CLAUDE_CODE_EFFORT_LEVEL` overrides `/effort`. When a variable interacts with another configuration source, its row in the [Variables](#variables) list states the precedence or links to the page that documents it.


180| `CLAUDE_CODE_ALWAYS_ENABLE_EFFORT` | Set to `1` to send the [effort](/docs/en/model-config#adjust-effort-level) parameter with every request, even when Claude Code does not recognize the model ID as effort-capable. Use this when routing through an [LLM gateway](/docs/en/llm-gateway) or third-party provider that serves models under custom identifiers. Models that reject the effort parameter at the API, including Claude 3 models, Sonnet 4.0 and 4.5, Opus 4.0 and 4.1, and Haiku 4.5, are still excluded so requests do not fail |182| `CLAUDE_CODE_ALWAYS_ENABLE_EFFORT` | Set to `1` to send the [effort](/docs/en/model-config#adjust-effort-level) parameter with every request, even when Claude Code does not recognize the model ID as effort-capable. Use this when routing through an [LLM gateway](/docs/en/llm-gateway) or third-party provider that serves models under custom identifiers. Models that reject the effort parameter at the API, including Claude 3 models, Sonnet 4.0 and 4.5, Opus 4.0 and 4.1, and Haiku 4.5, are still excluded so requests do not fail |

181| `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` | Interval in milliseconds at which credentials should be refreshed (when using [`apiKeyHelper`](/docs/en/settings#available-settings)) |183| `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` | Interval in milliseconds at which credentials should be refreshed (when using [`apiKeyHelper`](/docs/en/settings#available-settings)) |

182| `CLAUDE_CODE_ARTIFACT_AUTO_OPEN` | Set to `0` to stop Claude Code from opening the browser automatically when a new [artifact](/docs/en/artifacts) is published. Republishing an existing artifact does not open the browser regardless of this setting |184| `CLAUDE_CODE_ARTIFACT_AUTO_OPEN` | Set to `0` to stop Claude Code from opening the browser automatically when a new [artifact](/docs/en/artifacts) is published. Republishing an existing artifact does not open the browser regardless of this setting |

183| `CLAUDE_CODE_ATTRIBUTION_HEADER` | Set to `0` to omit the attribution block (client version and prompt fingerprint) from the start of the system prompt. Disabling it improves prompt-cache hit rates when routing through an [LLM gateway](/docs/en/llm-gateway). Caching on a direct connection to the Anthropic API is unaffected either way |185| `CLAUDE_CODE_ATTRIBUTION_HEADER` | Set to `0` to omit the [attribution block](/docs/en/llm-gateway-protocol#system-prompt-attribution-block), which carries the client version and a prompt fingerprint, from the start of the system prompt. Caching on a direct connection to the Anthropic API is unaffected either way. {/* min-version: 2.1.181 */}Before v2.1.181 the block included a per-request token on custom base URLs and Microsoft Foundry connections, so on those versions set it to `0` when your [LLM gateway](/docs/en/llm-gateway) caches on the request body or forwards requests to a third-party provider, or when you connect to Microsoft Foundry directly |

184| `CLAUDE_CODE_AUTO_COMPACT_WINDOW` | Set the context capacity in tokens used for auto-compaction calculations. Defaults to the model's context window, 200K for standard models or 1M for [extended context](/docs/en/model-config#extended-context) models, except on Sonnet 5, which has its own [default threshold](/docs/en/model-config#sonnet-5-context-window). Use a lower value like `500000` on a 1M model to treat the window as 500K for compaction purposes. The value is capped at the model's actual context window. `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` is applied as a percentage of this value. Setting this variable decouples the compaction threshold from the status line's `used_percentage`, which always uses the model's full context window |186| `CLAUDE_CODE_AUTO_COMPACT_WINDOW` | Set the context capacity in tokens used for auto-compaction calculations. Defaults to the model's context window, 200K for standard models or 1M for [extended context](/docs/en/model-config#extended-context) models, except on Sonnet 5, which has its own [default threshold](/docs/en/model-config#sonnet-5-context-window). Use a lower value like `500000` on a 1M model to treat the window as 500K for compaction purposes. The value is capped at the model's actual context window. `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` is applied as a percentage of this value. Setting this variable decouples the compaction threshold from the status line's `used_percentage`, which always uses the model's full context window |

185| `CLAUDE_CODE_AUTO_CONNECT_IDE` | Override automatic [IDE connection](/docs/en/vs-code). By default, Claude Code connects automatically when launched inside a supported IDE's integrated terminal. Set to `false` to prevent this. Set to `true` to force a connection attempt when auto-detection fails, such as when tmux obscures the parent terminal. Takes precedence over the [`autoConnectIde`](/docs/en/settings#global-config-settings) global config setting |187| `CLAUDE_CODE_AUTO_CONNECT_IDE` | Override automatic [IDE connection](/docs/en/vs-code). By default, Claude Code connects automatically when launched inside a supported IDE's integrated terminal. Set to `false` to prevent this. Set to `true` to force a connection attempt when auto-detection fails, such as when tmux obscures the parent terminal. Takes precedence over the [`autoConnectIde`](/docs/en/settings#global-config-settings) global config setting |

186| `CLAUDE_CODE_AWS_CHAIN_RESOLVE_TIMEOUT_MS` | {/* min-version: 2.1.207 */}Time in milliseconds Claude Code waits for the AWS default credential provider chain to produce credentials before the request fails with [`AWS default-chain credential resolve timed out`](/docs/en/errors#aws-default-chain-credential-resolve-timed-out) (default: `60000`). Raise it when a step in your chain legitimately needs longer, such as a browser-based SSO sign-in with MFA through a wrapper like `aws-vault`. Applies wherever Claude Code signs with the default chain: [Amazon Bedrock](/docs/en/amazon-bedrock#credential-caching-and-resolution-timeout), [Claude Platform on AWS](/docs/en/claude-platform-on-aws), and the [Mantle endpoint](/docs/en/amazon-bedrock#use-the-mantle-endpoint). Requires Claude Code v2.1.207 or later |188| `CLAUDE_CODE_AWS_CHAIN_RESOLVE_TIMEOUT_MS` | {/* min-version: 2.1.207 */}Time in milliseconds Claude Code waits for the AWS default credential provider chain to produce credentials before the request fails with [`AWS default-chain credential resolve timed out`](/docs/en/errors#aws-default-chain-credential-resolve-timed-out) (default: `60000`). Raise it when a step in your chain legitimately needs longer, such as a browser-based SSO sign-in with MFA through a wrapper like `aws-vault`. Applies wherever Claude Code signs with the default chain: [Amazon Bedrock](/docs/en/amazon-bedrock#credential-caching-and-resolution-timeout), [Claude Platform on AWS](/docs/en/claude-platform-on-aws), and the [Mantle endpoint](/docs/en/amazon-bedrock#use-the-mantle-endpoint). Requires Claude Code v2.1.207 or later |


205| `CLAUDE_CODE_DISABLE_BEDROCK_CONTENT_TYPE_GUARD` | {/* min-version: 2.1.208 */}Set to `1` to skip the check that an [Amazon Bedrock](/docs/en/amazon-bedrock) streaming response carries the `application/vnd.amazon.eventstream` content-type. Without this variable, a response with a different content-type fails with an error naming that content-type, which means a [gateway or proxy is transforming the response](/docs/en/amazon-bedrock#streaming-errors-behind-a-gateway-or-proxy). Set it only when the gateway rewrites the `Content-Type` header but passes the binary event-stream body through unmodified; if the body itself was transformed, requests fail with `Truncated event message received` instead. Requires Claude Code v2.1.208 or later |207| `CLAUDE_CODE_DISABLE_BEDROCK_CONTENT_TYPE_GUARD` | {/* min-version: 2.1.208 */}Set to `1` to skip the check that an [Amazon Bedrock](/docs/en/amazon-bedrock) streaming response carries the `application/vnd.amazon.eventstream` content-type. Without this variable, a response with a different content-type fails with an error naming that content-type, which means a [gateway or proxy is transforming the response](/docs/en/amazon-bedrock#streaming-errors-behind-a-gateway-or-proxy). Set it only when the gateway rewrites the `Content-Type` header but passes the binary event-stream body through unmodified; if the body itself was transformed, requests fail with `Truncated event message received` instead. Requires Claude Code v2.1.208 or later |

206| `CLAUDE_CODE_DISABLE_BG_EXIT_HANDOFF` | {/* min-version: 2.1.196 */}Set to `1` to stop a [background session's](/docs/en/agent-view) running background shell commands, dynamic workflows, {/* min-version: 2.1.198 */}and, as of v2.1.198, background subagents when the [supervisor](/docs/en/agent-view#the-supervisor-process) stops, restarts, or updates that session's process, instead of handing them to the session's next process. Affects only that handoff: backgrounding a session with `←` or [`/background`](/docs/en/agent-view#from-inside-a-session) still carries in-flight work over, and `CLAUDE_DISABLE_ADOPT` turns off both. Requires Claude Code v2.1.196 or later |208| `CLAUDE_CODE_DISABLE_BG_EXIT_HANDOFF` | {/* min-version: 2.1.196 */}Set to `1` to stop a [background session's](/docs/en/agent-view) running background shell commands, dynamic workflows, {/* min-version: 2.1.198 */}and, as of v2.1.198, background subagents when the [supervisor](/docs/en/agent-view#the-supervisor-process) stops, restarts, or updates that session's process, instead of handing them to the session's next process. Affects only that handoff: backgrounding a session with `←` or [`/background`](/docs/en/agent-view#from-inside-a-session) still carries in-flight work over, and `CLAUDE_DISABLE_ADOPT` turns off both. Requires Claude Code v2.1.196 or later |

207| `CLAUDE_CODE_DISABLE_BG_SHELL_PRESSURE_REAP` | {/* min-version: 2.1.193 */}Set to `1` to stop Claude Code from terminating [background shell commands](/docs/en/interactive-mode#background-bash-commands) when the operating system reports memory pressure. By default, on macOS and Linux, Claude Code terminates a background shell started in the main session on a memory-pressure signal once the session has been idle for 30 minutes and no turn or subagent is running. Windows has no memory-pressure signal, so this variable has no effect there. Requires Claude Code v2.1.193 or later |209| `CLAUDE_CODE_DISABLE_BG_SHELL_PRESSURE_REAP` | {/* min-version: 2.1.193 */}Set to `1` to stop Claude Code from terminating [background shell commands](/docs/en/interactive-mode#background-bash-commands) when the operating system reports memory pressure. By default, on macOS and Linux, Claude Code terminates a background shell started in the main session on a memory-pressure signal once the session has been idle for 30 minutes and no turn or subagent is running. Windows has no memory-pressure signal, so this variable has no effect there. Requires Claude Code v2.1.193 or later |

208| `CLAUDE_CODE_DISABLE_BUNDLED_SKILLS` | Set to `1` to disable the [skills](/docs/en/skills) and workflows included with Claude Code: bundled skills and workflows are removed entirely, while built-in commands like `/init` stay typable but are hidden from the model. `/doctor` stays typable like the built-in commands; hide it with `DISABLE_DOCTOR_COMMAND` instead. Skills from plugins, `.claude/skills/`, and `.claude/commands/` are unaffected. Equivalent to the [`disableBundledSkills`](/docs/en/settings#available-settings) setting; `0` doesn't override it |210| `CLAUDE_CODE_DISABLE_BUNDLED_SKILLS` | Set to `1` to disable the [skills](/docs/en/skills) and workflows included with Claude Code: bundled skills and workflows are removed entirely, while built-in commands like `/init` stay typable but are hidden from the model. `/doctor` stays typable like the built-in commands; hide it with `DISABLE_DOCTOR_COMMAND` instead. Skills from plugins, `.claude/skills/`, and `.claude/commands/` are unaffected. Equivalent to the [`disableBundledSkills`](/docs/en/settings#available-settings) setting |

209| `CLAUDE_CODE_DISABLE_CLAUDE_MDS` | Set to `1` to prevent loading any CLAUDE.md memory files into context, including user, project, and auto-memory files |211| `CLAUDE_CODE_DISABLE_CLAUDE_MDS` | Set to `1` to prevent loading any CLAUDE.md memory files into context, including user, project, and auto-memory files |

210| `CLAUDE_CODE_DISABLE_CRON` | Set to `1` to disable [scheduled tasks](/docs/en/scheduled-tasks). The `/loop` skill and cron tools become unavailable and any already-scheduled tasks stop firing, including tasks that are already running mid-session |212| `CLAUDE_CODE_DISABLE_CRON` | Set to `1` to disable [scheduled tasks](/docs/en/scheduled-tasks). The `/loop` skill and cron tools become unavailable and any already-scheduled tasks stop firing, including tasks that are already running mid-session |

211| `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` | Set to `1` to strip Anthropic-specific `anthropic-beta` request headers and beta tool-schema fields (such as `defer_loading` and `eager_input_streaming`) from API requests. Use this when a proxy gateway rejects requests with errors like "Unexpected value(s) for the `anthropic-beta` header" or "Extra inputs are not permitted". Standard fields (`name`, `description`, `input_schema`, `cache_control`) are preserved. [MCP tool search](/docs/en/mcp#scale-with-mcp-tool-search) is disabled and all MCP tools load upfront, even when `ENABLE_TOOL_SEARCH` is set |213| `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` | Set to `1` to strip Anthropic-specific `anthropic-beta` request headers and beta tool-schema fields (such as `defer_loading` and `eager_input_streaming`) from API requests. Use this when a proxy gateway rejects requests with errors like "Unexpected value(s) for the `anthropic-beta` header" or "Extra inputs are not permitted". Standard fields (`name`, `description`, `input_schema`, `cache_control`) are preserved. [MCP tool search](/docs/en/mcp#scale-with-mcp-tool-search) is disabled and all MCP tools load upfront, even when `ENABLE_TOOL_SEARCH` is set |

212| `CLAUDE_CODE_DISABLE_EXPLORE_PLAN_AGENTS` | {/* min-version: 2.1.198 */}Set to `1` to disable the built-in [Explore and Plan subagents](/docs/en/sub-agents#built-in-subagents). Claude explores with its search tools or the general-purpose subagent instead, and [plan mode](/docs/en/permission-modes#analyze-before-you-edit-with-plan-mode) reads files directly rather than launching Explore and Plan agents. Custom subagents named `Explore` or `Plan` are unaffected. To remove every built-in subagent type in the Agent SDK or non-interactive mode, use `CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS` instead. Requires Claude Code v2.1.198 or later |214| `CLAUDE_CODE_DISABLE_EXPLORE_PLAN_AGENTS` | {/* min-version: 2.1.198 */}Set to `1` to disable the built-in [Explore and Plan subagents](/docs/en/sub-agents#built-in-subagents). Claude explores with its search tools or the general-purpose subagent instead, and [plan mode](/docs/en/permission-modes#analyze-before-you-edit-with-plan-mode) reads files directly rather than launching Explore and Plan agents. Custom subagents named `Explore` or `Plan` are unaffected. To remove every built-in subagent type in the Agent SDK or non-interactive mode, use `CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS` instead. Requires Claude Code v2.1.198 or later |

213| `CLAUDE_CODE_DISABLE_FAST_MODE` | Set to `1` to disable [fast mode](/docs/en/fast-mode) |215| `CLAUDE_CODE_DISABLE_FAST_MODE` | Set to `1` to disable [fast mode](/docs/en/fast-mode) |

214| `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY` | Set to `1` to disable the "How is Claude doing?" session quality surveys. Surveys are also disabled when `DISABLE_TELEMETRY`, `DO_NOT_TRACK`, or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is set, unless `CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL` opts back in. To set a sample rate instead of disabling outright, use the [`feedbackSurveyRate`](/docs/en/settings#available-settings) setting. See [Session quality surveys](/docs/en/data-usage#session-quality-surveys) |216| `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY` | Set to `1` to disable the "How is Claude doing?" session quality surveys. Surveys are also disabled when `DISABLE_TELEMETRY`, `DO_NOT_TRACK`, or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is set, unless `CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL` opts back in. To set a sample rate instead of disabling outright, use the [`feedbackSurveyRate`](/docs/en/settings#available-settings) setting. See [Session quality surveys](/docs/en/data-usage#session-quality-surveys) |

215| `CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING` | Set to `1` to disable file [checkpointing](/docs/en/checkpointing). The `/rewind` command will not be able to restore code changes |217| `CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING` | Set to `1` to disable file [checkpointing](/docs/en/checkpointing). The `/rewind` command will not be able to restore code changes. Overrides the [`fileCheckpointingEnabled`](/docs/en/settings#available-settings) setting |

216| `CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS` | Set to `1` to remove built-in commit and PR workflow instructions and the git status snapshot from Claude's system prompt. Useful when using your own git workflow skills. Takes precedence over the [`includeGitInstructions`](/docs/en/settings#available-settings) setting when set |218| `CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS` | Set to `1` to remove built-in commit and PR workflow instructions and the git status snapshot from Claude's system prompt. Useful when using your own git workflow skills. Takes precedence over the [`includeGitInstructions`](/docs/en/settings#available-settings) setting when set |

217| `CLAUDE_CODE_DISABLE_LEGACY_MODEL_REMAP` | Set to `1` to prevent automatic remapping of Opus 4.0 and 4.1 to the current Opus version on the Anthropic API. Use when you intentionally want to pin an older model. The remap does not run on Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry |219| `CLAUDE_CODE_DISABLE_LEGACY_MODEL_REMAP` | Set to `1` to prevent automatic remapping of Opus 4.0 and 4.1 to the current Opus version on the Anthropic API. Use when you intentionally want to pin an older model. The remap does not run on Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry |

218| `CLAUDE_CODE_DISABLE_MOUSE` | Set to `1` to disable mouse tracking in [fullscreen rendering](/docs/en/fullscreen). Keyboard scrolling with `PgUp` and `PgDn` still works. Use this to keep your terminal's native copy-on-select behavior |220| `CLAUDE_CODE_DISABLE_MOUSE` | Set to `1` to disable mouse tracking in [fullscreen rendering](/docs/en/fullscreen). Keyboard scrolling with `PgUp` and `PgDn` still works. Use this to keep your terminal's native copy-on-select behavior |

219| `CLAUDE_CODE_DISABLE_MOUSE_CLICKS` | {/* min-version: 2.1.195 */}Set to `1` to disable click, drag, and hover handling in [fullscreen rendering](/docs/en/fullscreen) while keeping mouse-wheel scrolling. Use this when you want wheel scroll to work inside Claude Code but don't want clicks to position the cursor, expand tool output, or open links. `CLAUDE_CODE_DISABLE_MOUSE` takes precedence when both are set. Requires Claude Code v2.1.195 or later |221| `CLAUDE_CODE_DISABLE_MOUSE_CLICKS` | {/* min-version: 2.1.195 */}Set to `1` to disable click, drag, and hover handling in [fullscreen rendering](/docs/en/fullscreen) while keeping mouse-wheel scrolling. Use this when you want wheel scroll to work inside Claude Code but don't want clicks to position the cursor, expand tool output, or open links. `CLAUDE_CODE_DISABLE_MOUSE` takes precedence when both are set. Requires Claude Code v2.1.195 or later |

220| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | Set to any non-empty value to disable nonessential network traffic: auto-updates, telemetry, error reporting, the `/feedback` command, release notes, [gateway model discovery](/docs/en/llm-gateway-connect#add-gateway-models-to-the-model-picker) refreshes, and availability checks such as the [fast mode](/docs/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways) check. Official plugin marketplace auto-install isn't covered; disable it with `CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL` |222| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | Set to any non-empty value to disable nonessential network traffic: auto-updates, telemetry, error reporting, the `/feedback` command, release notes, [gateway model discovery](/docs/en/llm-gateway-connect#add-gateway-models-to-the-model-picker) refreshes, and availability checks such as the [fast mode](/docs/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways) check. Also disables feature-flag fetching, which makes [Remote Control](/docs/en/remote-control#requirements) unavailable. Official plugin marketplace auto-install isn't covered; disable it with `CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL` |

221| `CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK` | Set to `1` to disable the non-streaming fallback when a streaming request fails mid-stream. Streaming errors propagate to the retry layer instead. Useful when a proxy or gateway causes the fallback to produce duplicate tool execution |223| `CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK` | Set to `1` to disable the non-streaming fallback when a streaming request fails mid-stream. Streaming errors propagate to the retry layer instead. Useful when a proxy or gateway causes the fallback to produce duplicate tool execution |

222| `CLAUDE_CODE_DISABLE_NOTIFICATION_PRESENCE_CHECK` | {/* min-version: 2.1.193 */}Set to `1` to send the `PushNotification` tool's desktop notification even while you are typing in or focused on the terminal. By default the tool skips both the desktop notification and the [mobile push](/docs/en/remote-control#mobile-push-notifications) when it detects recent keyboard activity or terminal focus. This variable disables only that local check, so the server can still suppress the mobile push when it detects that you are active. Requires Claude Code v2.1.193 or later |224| `CLAUDE_CODE_DISABLE_NOTIFICATION_PRESENCE_CHECK` | {/* min-version: 2.1.193 */}Set to `1` to send the `PushNotification` tool's desktop notification even while you are typing in or focused on the terminal. By default the tool skips both the desktop notification and the [mobile push](/docs/en/remote-control#mobile-push-notifications) when it detects recent keyboard activity or terminal focus. This variable disables only that local check, so the server can still suppress the mobile push when it detects that you are active. Requires Claude Code v2.1.193 or later |

223| `CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL` | Set to `1` to skip automatic addition of the official plugin marketplace on first run |225| `CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL` | Set to `1` to skip automatic addition of the official plugin marketplace on first run |


292| `CLAUDE_CODE_PROPAGATE_TRACEPARENT` | {/* min-version: 2.1.152 */}Set to `1` to propagate W3C trace context when `ANTHROPIC_BASE_URL` points at a custom proxy. Propagation covers the `traceparent` header on model and HTTP MCP requests and the `TRACEPARENT` environment variable for Bash, PowerShell, and hook subprocesses. By default, propagation is enabled only when connected directly to the Anthropic API. Added in v2.1.152. See [Traces (beta)](/docs/en/monitoring-usage#traces-beta) |294| `CLAUDE_CODE_PROPAGATE_TRACEPARENT` | {/* min-version: 2.1.152 */}Set to `1` to propagate W3C trace context when `ANTHROPIC_BASE_URL` points at a custom proxy. Propagation covers the `traceparent` header on model and HTTP MCP requests and the `TRACEPARENT` environment variable for Bash, PowerShell, and hook subprocesses. By default, propagation is enabled only when connected directly to the Anthropic API. Added in v2.1.152. See [Traces (beta)](/docs/en/monitoring-usage#traces-beta) |

293| `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST` | Set by host platforms that embed Claude Code and manage model provider routing on its behalf. When set, provider-selection, endpoint, and authentication variables such as `CLAUDE_CODE_USE_BEDROCK`, `ANTHROPIC_BASE_URL`, and `ANTHROPIC_API_KEY` in settings files are ignored so user settings cannot override the host's routing. The automatic telemetry opt-out for Amazon Bedrock, Google Cloud's Agent Platform, and Microsoft Foundry is also skipped, so telemetry follows the standard `DISABLE_TELEMETRY` opt-out. See [Default behaviors by API provider](/docs/en/data-usage#default-behaviors-by-api-provider) |295| `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST` | Set by host platforms that embed Claude Code and manage model provider routing on its behalf. When set, provider-selection, endpoint, and authentication variables such as `CLAUDE_CODE_USE_BEDROCK`, `ANTHROPIC_BASE_URL`, and `ANTHROPIC_API_KEY` in settings files are ignored so user settings cannot override the host's routing. The automatic telemetry opt-out for Amazon Bedrock, Google Cloud's Agent Platform, and Microsoft Foundry is also skipped, so telemetry follows the standard `DISABLE_TELEMETRY` opt-out. See [Default behaviors by API provider](/docs/en/data-usage#default-behaviors-by-api-provider) |

294| `CLAUDE_CODE_PROXY_RESOLVES_HOSTS` | Set to `1` to allow the proxy to perform DNS resolution instead of the caller. Opt-in for environments where the proxy should handle hostname resolution |296| `CLAUDE_CODE_PROXY_RESOLVES_HOSTS` | Set to `1` to allow the proxy to perform DNS resolution instead of the caller. Opt-in for environments where the proxy should handle hostname resolution |

295| `CLAUDE_CODE_REMOTE` | Set automatically to `true` when Claude Code is running as a [cloud session](/docs/en/claude-code-on-the-web). Read this from a hook or setup script to detect whether you are in a cloud environment |297| `CLAUDE_CODE_REMOTE` | Set automatically to `true` when Claude Code is running as a [cloud session](/docs/en/claude-code-on-the-web). Read this from a hook or setup script to detect whether you are in a cloud session |

296| `CLAUDE_CODE_REMOTE_SESSION_ID` | Set automatically in [cloud sessions](/docs/en/claude-code-on-the-web) to the current session's ID. Read this to construct a link back to the session transcript. See [Link output back to the session](/docs/en/claude-code-on-the-web#link-output-back-to-the-session) |298| `CLAUDE_CODE_REMOTE_SESSION_ID` | Set automatically in [cloud sessions](/docs/en/claude-code-on-the-web) to the current session's ID. Read this to construct a link back to the session transcript. See [Link output back to the session](/docs/en/cloud-environments#link-output-back-to-the-session) |

297| `CLAUDE_CODE_RESUME_INTERRUPTED_TURN` | Set to `1` to automatically resume if the previous session ended mid-turn. Used in SDK mode so the model continues without requiring the SDK to re-send the prompt |299| `CLAUDE_CODE_RESUME_INTERRUPTED_TURN` | Set to `1` to automatically resume if the previous session ended mid-turn. Used in SDK mode so the model continues without requiring the SDK to re-send the prompt |

298| `CLAUDE_CODE_RESUME_INTERRUPTED_TURN_MAX_AGE_MS` | {/* min-version: 2.1.211 */}Maximum age in milliseconds of the last transcript message for a session that ended mid-turn to continue automatically on resume. When the last message is older than this bound, Claude Code skips both the `CLAUDE_CODE_RESUME_INTERRUPTED_TURN` automatic resume and the injected `CLAUDE_CODE_RESUME_PROMPT` continuation message, and the session starts idle so you continue explicitly. Unset or `0` means no bound; a negative or non-numeric value applies a one-hour bound. Spawn scripts for long-running agents can set this so a restart against an old transcript doesn't re-run a stale prompt. Claude Code sets a one-hour bound itself when it restarts a crashed [agent view](/docs/en/agent-view) session that inherited its conversation from an interactive session. Requires Claude Code v2.1.211 or later |300| `CLAUDE_CODE_RESUME_INTERRUPTED_TURN_MAX_AGE_MS` | {/* min-version: 2.1.211 */}Maximum age in milliseconds of the last transcript message for a session that ended mid-turn to continue automatically on resume. When the last message is older than this bound, Claude Code skips both the `CLAUDE_CODE_RESUME_INTERRUPTED_TURN` automatic resume and the injected `CLAUDE_CODE_RESUME_PROMPT` continuation message, and the session starts idle so you continue explicitly. Unset or `0` means no bound; a negative or non-numeric value applies a one-hour bound. Spawn scripts for long-running agents can set this so a restart against an old transcript doesn't re-run a stale prompt. Claude Code sets a one-hour bound itself when it restarts a crashed [agent view](/docs/en/agent-view) session that inherited its conversation from an interactive session. Requires Claude Code v2.1.211 or later |

299| `CLAUDE_CODE_RESUME_PROMPT` | Override the continuation message injected when resuming a session that ended mid-turn. Defaults to `Continue from where you left off.`. Spawn scripts for long-running agents can set this to a more directive boot message. An empty string uses the default |301| `CLAUDE_CODE_RESUME_PROMPT` | Override the continuation message injected when resuming a session that ended mid-turn. Defaults to `Continue from where you left off.`. Spawn scripts for long-running agents can set this to a more directive boot message. An empty string uses the default |


348| `CLAUDE_STREAM_IDLE_TIMEOUT_MS` | Timeout in milliseconds before the streaming idle watchdog closes a stalled connection. When you set this variable explicitly, the minimum is `300000` (5 minutes); lower values are silently clamped to absorb extended thinking pauses and proxy buffering. When unset, the event-level watchdog defaults to 300 seconds and the byte-level watchdog defaults to 180 seconds on direct Anthropic API connections (300 seconds on Claude Platform on AWS and other providers). The unset 180-second byte-watchdog default is a separate value and is not subject to the 5-minute clamp. The body idle timeout described under `API_FORCE_IDLE_TIMEOUT` applies independently. On Amazon Bedrock, also applies when `CLAUDE_ENABLE_BYTE_WATCHDOG_BEDROCK=1` |350| `CLAUDE_STREAM_IDLE_TIMEOUT_MS` | Timeout in milliseconds before the streaming idle watchdog closes a stalled connection. When you set this variable explicitly, the minimum is `300000` (5 minutes); lower values are silently clamped to absorb extended thinking pauses and proxy buffering. When unset, the event-level watchdog defaults to 300 seconds and the byte-level watchdog defaults to 180 seconds on direct Anthropic API connections (300 seconds on Claude Platform on AWS and other providers). The unset 180-second byte-watchdog default is a separate value and is not subject to the 5-minute clamp. The body idle timeout described under `API_FORCE_IDLE_TIMEOUT` applies independently. On Amazon Bedrock, also applies when `CLAUDE_ENABLE_BYTE_WATCHDOG_BEDROCK=1` |

349| `DEBUG` | Set to `1` to enable debug mode, equivalent to launching with [`--debug`](/docs/en/cli-reference#cli-flags). Debug logs are written to `~/.claude/debug/<session-id>.txt`, or to the path set by `CLAUDE_CODE_DEBUG_LOGS_DIR`. Only the truthy values `1`, `true`, `yes`, and `on` enable debug mode, so namespace patterns like `DEBUG=express:*` set for other tools do not trigger it |351| `DEBUG` | Set to `1` to enable debug mode, equivalent to launching with [`--debug`](/docs/en/cli-reference#cli-flags). Debug logs are written to `~/.claude/debug/<session-id>.txt`, or to the path set by `CLAUDE_CODE_DEBUG_LOGS_DIR`. Only the truthy values `1`, `true`, `yes`, and `on` enable debug mode, so namespace patterns like `DEBUG=express:*` set for other tools do not trigger it |

350| `DISABLE_AUTOUPDATER` | Set to `1` to disable automatic background updates. Manual `claude update` still works. Use `DISABLE_UPDATES` to block both |352| `DISABLE_AUTOUPDATER` | Set to `1` to disable automatic background updates. Manual `claude update` still works. Use `DISABLE_UPDATES` to block both |

351| `DISABLE_AUTO_COMPACT` | Set to `1` to disable automatic compaction when approaching the context limit. The manual `/compact` command remains available. Use when you want explicit control over when compaction occurs |353| `DISABLE_AUTO_COMPACT` | Set to `1` to disable automatic compaction when approaching the context limit. The manual `/compact` command remains available. Use when you want explicit control over when compaction occurs. Overrides the [`autoCompactEnabled`](/docs/en/settings#available-settings) setting |

352| `DISABLE_COMPACT` | Set to `1` to disable all compaction: both automatic compaction and the manual `/compact` command |354| `DISABLE_COMPACT` | Set to `1` to disable all compaction: both automatic compaction and the manual `/compact` command |

353| `DISABLE_COST_WARNINGS` | Set to `1` to disable cost warning messages |355| `DISABLE_COST_WARNINGS` | Set to `1` to disable cost warning messages |

354| `DISABLE_DOCTOR_COMMAND` | Set to `1` to hide the [`/doctor`](/docs/en/commands#all-commands) setup checkup skill and its `/checkup` alias. Useful for managed deployments where users shouldn't run setup diagnostics from a session. Doesn't affect the `claude doctor` terminal command. {/* min-version: 2.1.205 */}Before v2.1.205, this variable hid the `/doctor` diagnostics screen command |356| `DISABLE_DOCTOR_COMMAND` | Set to `1` to hide the [`/doctor`](/docs/en/commands#all-commands) setup checkup skill and its `/checkup` alias. Useful for managed deployments where users shouldn't run setup diagnostics from a session. Doesn't affect the `claude doctor` terminal command. {/* min-version: 2.1.205 */}Before v2.1.205, this variable hid the `/doctor` diagnostics screen command |

355| `DISABLE_ERROR_REPORTING` | Set to `1` to opt out of error reporting |357| `DISABLE_ERROR_REPORTING` | Set to `1` to opt out of error reporting |

356| `DISABLE_EXTRA_USAGE_COMMAND` | Set to `1` to hide the `/usage-credits` command that lets users purchase additional usage beyond rate limits |358| `DISABLE_EXTRA_USAGE_COMMAND` | Set to `1` to hide the `/usage-credits` command that lets users purchase additional usage beyond rate limits |

357| `DISABLE_FEEDBACK_COMMAND` | Set to `1` to disable the `/feedback` command. {/* min-version: 2.1.212 */}Also disables `/bug` and `/share`, which report through the same path; before v2.1.212 they were aliases of `/feedback`, so the command was disabled under every name. The older name `DISABLE_BUG_COMMAND` is also accepted |359| `DISABLE_FEEDBACK_COMMAND` | Set to `1` to disable the `/feedback` command. {/* min-version: 2.1.212 */}Also disables `/bug` and `/share`, which report through the same path; before v2.1.212 they were aliases of `/feedback`, so the command was disabled under every name. The older name `DISABLE_BUG_COMMAND` is also accepted |

358| `DISABLE_GROWTHBOOK` | Set to `1` to disable GrowthBook feature-flag fetching and use code defaults for every flag. Telemetry event logging stays on unless `DISABLE_TELEMETRY` is also set |360| `DISABLE_GROWTHBOOK` | Set to `1` to disable GrowthBook feature-flag fetching and use code defaults for every flag. This makes [Remote Control](/docs/en/remote-control#requirements) unavailable. Telemetry event logging stays on unless `DISABLE_TELEMETRY` is also set |

359| `DISABLE_INSTALLATION_CHECKS` | Set to `1` to disable installation warnings. Use only when manually managing the installation location, as this can mask issues with standard installations |361| `DISABLE_INSTALLATION_CHECKS` | Set to `1` to disable installation warnings. Use only when manually managing the installation location, as this can mask issues with standard installations |

360| `DISABLE_INSTALL_GITHUB_APP_COMMAND` | Set to `1` to hide the `/install-github-app` command. Already hidden when using third-party providers (Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry) |362| `DISABLE_INSTALL_GITHUB_APP_COMMAND` | Set to `1` to hide the `/install-github-app` command. Already hidden when using third-party providers (Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry) |

361| `DISABLE_INTERLEAVED_THINKING` | Set to `1` to prevent sending the interleaved-thinking beta header. Useful when your LLM gateway or provider does not support [interleaved thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#interleaved-thinking) |363| `DISABLE_INTERLEAVED_THINKING` | Set to `1` to prevent sending the interleaved-thinking beta header. Useful when your LLM gateway or provider does not support [interleaved thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#interleaved-thinking) |


366| `DISABLE_PROMPT_CACHING_HAIKU` | Set to `1` to disable prompt caching for Haiku models |368| `DISABLE_PROMPT_CACHING_HAIKU` | Set to `1` to disable prompt caching for Haiku models |

367| `DISABLE_PROMPT_CACHING_OPUS` | Set to `1` to disable prompt caching for Opus models |369| `DISABLE_PROMPT_CACHING_OPUS` | Set to `1` to disable prompt caching for Opus models |

368| `DISABLE_PROMPT_CACHING_SONNET` | Set to `1` to disable prompt caching for Sonnet models |370| `DISABLE_PROMPT_CACHING_SONNET` | Set to `1` to disable prompt caching for Sonnet models |

369| `DISABLE_TELEMETRY` | Set to `1` to opt out of telemetry. Telemetry events do not include user data like code, file paths, or bash commands. Also disables feature-flag fetching with the same effect as `DISABLE_GROWTHBOOK`, so some flagged features may be unavailable |371| `DISABLE_TELEMETRY` | Set to `1` to opt out of telemetry. Telemetry events do not include user data like code, file paths, or bash commands. Also disables feature-flag fetching with the same effect as `DISABLE_GROWTHBOOK`, which makes [Remote Control](/docs/en/remote-control#requirements) unavailable |

370| `DISABLE_UPDATES` | Set to `1` to block all updates including manual `claude update` and `claude install`. Stricter than `DISABLE_AUTOUPDATER`. Use when distributing Claude Code through your own channels and users should not self-update |372| `DISABLE_UPDATES` | Set to `1` to block all updates including manual `claude update` and `claude install`. Stricter than `DISABLE_AUTOUPDATER`. Use when distributing Claude Code through your own channels and users should not self-update |

371| `DISABLE_UPGRADE_COMMAND` | Set to `1` to hide the `/upgrade` command |373| `DISABLE_UPGRADE_COMMAND` | Set to `1` to hide the `/upgrade` command |

372| `DO_NOT_TRACK` | Set to `1` to opt out of telemetry. Equivalent to setting `DISABLE_TELEMETRY`. Claude Code honors this as the cross-tool convention recognized by many developer CLIs |374| `DO_NOT_TRACK` | Set to `1` to opt out of telemetry. Equivalent to setting `DISABLE_TELEMETRY`, including its effect of making [Remote Control](/docs/en/remote-control#requirements) unavailable. Claude Code honors this as the cross-tool convention recognized by many developer CLIs |

373| `ENABLE_CLAUDEAI_MCP_SERVERS` | Set to `false` to disable [claude.ai MCP servers](/docs/en/mcp#use-mcp-servers-from-claude-ai) in Claude Code. Enabled by default for logged-in users. To disable per-project or per-org, set [`disableClaudeAiConnectors`](/docs/en/settings#available-settings) in settings instead |375| `ENABLE_CLAUDEAI_MCP_SERVERS` | Set to `false` to disable [claude.ai MCP servers](/docs/en/mcp#use-mcp-servers-from-claude-ai) in Claude Code. Enabled by default for logged-in users. To disable per-project or per-org, set [`disableClaudeAiConnectors`](/docs/en/settings#available-settings) in settings instead |

374| `ENABLE_PROMPT_CACHING_1H` | Set to `1` to request a 1-hour [prompt cache TTL](/docs/en/prompt-caching#cache-lifetime) instead of the default 5 minutes. Intended for API key, [Amazon Bedrock](/docs/en/amazon-bedrock), [Google Cloud's Agent Platform](/docs/en/google-vertex-ai), [Microsoft Foundry](/docs/en/microsoft-foundry), and [Claude Platform on AWS](/docs/en/claude-platform-on-aws) users. Subscription users within included usage receive 1-hour TTL automatically. 1-hour cache writes are billed at a higher rate |376| `ENABLE_PROMPT_CACHING_1H` | Set to `1` to request a 1-hour [prompt cache TTL](/docs/en/prompt-caching#cache-lifetime) instead of the default 5 minutes. Intended for API key, [Amazon Bedrock](/docs/en/amazon-bedrock), [Google Cloud's Agent Platform](/docs/en/google-vertex-ai), [Microsoft Foundry](/docs/en/microsoft-foundry), and [Claude Platform on AWS](/docs/en/claude-platform-on-aws) users. Subscription users within included usage receive 1-hour TTL automatically. 1-hour cache writes are billed at a higher rate |

375| `ENABLE_PROMPT_CACHING_1H_BEDROCK` | Deprecated. Use `ENABLE_PROMPT_CACHING_1H` instead |377| `ENABLE_PROMPT_CACHING_1H_BEDROCK` | Deprecated. Use `ENABLE_PROMPT_CACHING_1H` instead |

376| `ENABLE_TOOL_SEARCH` | Controls [MCP tool search](/docs/en/mcp#scale-with-mcp-tool-search). Unset: all MCP tools deferred by default, but loaded upfront on Google Cloud's Agent Platform or when `ANTHROPIC_BASE_URL` points to a non-first-party host. Values: `true` (always defer and send the beta header, requests fail on Google Cloud's Agent Platform models earlier than Sonnet 4.5 or Opus 4.5, or on proxies that do not support `tool_reference`), `auto` (threshold mode: load upfront if tools fit within 10% of context), `auto:N` (custom threshold, e.g., `auto:5` for 5%), `false` (load all upfront). Ignored when `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` is set, which forces all tools to load upfront |378| `ENABLE_TOOL_SEARCH` | Controls [MCP tool search](/docs/en/mcp#scale-with-mcp-tool-search). Unset: all MCP tools deferred by default, but loaded upfront on Google Cloud's Agent Platform, when `ANTHROPIC_BASE_URL` points to a non-first-party host, or on a Microsoft Foundry deployment hosted on Azure. Values: `true` (always defer and send the beta header, except on a Microsoft Foundry deployment hosted on Azure, where the server-side rejection still forces upfront loading; requests fail on Google Cloud's Agent Platform models earlier than Sonnet 4.5 or Opus 4.5, or on proxies that do not support `tool_reference`), `auto` (threshold mode: load upfront if tools fit within 10% of context), `auto:N` (custom threshold, e.g., `auto:5` for 5%), `false` (load all upfront). Ignored when `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` is set, which forces all tools to load upfront |

377| `FALLBACK_FOR_ALL_PRIMARY_MODELS` | Set to any non-empty value to make all models, not only Opus, stop retrying with a repeated-overload error when no fallback model is configured. {/* min-version: 2.1.160 */}As of v2.1.160, a configured [fallback model chain](/docs/en/model-config#fallback-model-chains) triggers on repeated overload errors for any primary model, so this variable does not affect switching to a fallback model |379| `FALLBACK_FOR_ALL_PRIMARY_MODELS` | Set to any non-empty value to make all models, not only Opus, stop retrying with a repeated-overload error when no fallback model is configured. {/* min-version: 2.1.160 */}As of v2.1.160, a configured [fallback model chain](/docs/en/model-config#fallback-model-chains) triggers on repeated overload errors for any primary model, so this variable does not affect switching to a fallback model |

378| `FORCE_AUTOUPDATE_PLUGINS` | Set to `1` to force plugin auto-updates even when the main auto-updater is disabled via `DISABLE_AUTOUPDATER` |380| `FORCE_AUTOUPDATE_PLUGINS` | Set to `1` to force plugin auto-updates even when the main auto-updater is disabled via `DISABLE_AUTOUPDATER` |

379| `FORCE_HYPERLINK` | Set to `1` to enable clickable OSC 8 hyperlinks when your terminal supports them but isn't auto-detected, or `0` to disable them |381| `FORCE_HYPERLINK` | Set to `1` to enable clickable OSC 8 hyperlinks when your terminal supports them but isn't auto-detected, or `0` to disable them |

errors.md +57 −19

Details

88| `Error: Workspace not trusted` when starting Remote Control | [Command-line errors](#workspace-not-trusted-when-starting-remote-control) |88| `Error: Workspace not trusted` when starting Remote Control | [Command-line errors](#workspace-not-trusted-when-starting-remote-control) |

89| `Could not import <server>: <reason>` | [Command-line errors](#could-not-import-a-server-from-claude-desktop) |89| `Could not import <server>: <reason>` | [Command-line errors](#could-not-import-a-server-from-claude-desktop) |

90| `Error: MCP tool <name> (passed via --permission-prompt-tool) not found` | [Command-line errors](#mcp-permission-prompt-tool-not-found) |90| `Error: MCP tool <name> (passed via --permission-prompt-tool) not found` | [Command-line errors](#mcp-permission-prompt-tool-not-found) |

91| ``Shell command failed for pattern "!`git ... origin/HEAD...`"`` | [Command-line errors](#security-review-fails-without-origin-head) |

91| `Input must be provided either through stdin or as a prompt argument when using --print` | [Command-line errors](#input-must-be-provided-when-using-print) |92| `Input must be provided either through stdin or as a prompt argument when using --print` | [Command-line errors](#input-must-be-provided-when-using-print) |

92| `Diff is too large for ultrareview` / `PR #<N> is too large for ultrareview` | [Command-line errors](#diff-is-too-large-for-ultrareview) |93| `Diff is too large for ultrareview` / `PR #<N> is too large for ultrareview` | [Command-line errors](#diff-is-too-large-for-ultrareview) |

93| `Failed to resume the conversation` | [Command-line errors](#failed-to-resume-the-conversation) |94| `Failed to resume the conversation` | [Command-line errors](#failed-to-resume-the-conversation) |


112 113 

113## Automatic retries114## Automatic retries

114 115 

115Claude Code retries transient failures before showing you an error. Server errors, overloaded responses, request timeouts, temporary 429 throttles, and dropped connections are all retried up to 10 times with exponential backoff. {/* min-version: 2.1.198 */}As of v2.1.198, this covers connections that drop in the middle of a response before any visible output has streamed: Claude Code re-issues the request with the same backoff and the turn continues instead of stopping with a connection error. {/* min-version: 2.1.199 */}As of v2.1.199, temporary 429 throttles that don't carry your plan's quota headers are also retried when you're signed in with a claude.ai subscription; earlier versions retried them only for API key and Enterprise sign-ins.116Claude Code retries transient failures up to 10 times with exponential backoff before showing you an error. It doesn't always retry a failure that arrives partway through Claude's response. When you see one of the errors on this page, Claude Code has already exhausted those retries, unless the failure is one it doesn't retry.

116 117 

117Some failure classes aren't retried, because a retry can't succeed:118Claude Code retries these failures:

118 119 

119* {/* min-version: 2.1.199 */}As of v2.1.199, a TLS certificate validation failure, such as a TLS-inspecting proxy, a missing `NODE_EXTRA_CA_CERTS` bundle, or an expired certificate, fails on the first attempt so the fix appears immediately instead of after the full retry budget. See [SSL certificate errors](#ssl-certificate-errors). Transient TLS conditions such as a handshake timeout still retry.120* Server errors, overloaded responses, and request timeouts.

120* {/* min-version: 2.1.199 */}As of v2.1.199, a server error that arrives after Claude has already streamed visible output keeps the partial response and appends an [incomplete-response notice](#the-response-above-may-be-incomplete) instead of retrying, since re-running the request could execute the same tools twice. Earlier versions discarded the partial output and reported the turn as an error.121* Dropped connections. {/* min-version: 2.1.198 */}This covers a connection that drops in the middle of a request, before any part of Claude's response has completed: Claude Code re-issues the request with the same backoff, and the turn continues. Before v2.1.198, Claude Code stopped the turn with a connection error when the connection dropped mid-response, before any visible output had streamed.

121* {/* min-version: 2.1.208 */}An [Amazon Bedrock streaming response with an unexpected content-type](#bedrock-streaming-response-has-an-unexpected-content-type) fails on the first attempt, because the gateway or proxy rewriting the response would rewrite the retry the same way. Requires Claude Code v2.1.208 or later.122* Temporary 429 throttles. {/* min-version: 2.1.199 */}When you're signed in with a claude.ai subscription, this includes 429 throttles that don't carry your plan's quota headers. Before v2.1.199, Claude Code retried those throttles only for API key and Enterprise sign-ins.

123 

124Claude Code doesn't retry these failures:

125 

126* {/* min-version: 2.1.199 */}A TLS certificate validation failure, such as a TLS-inspecting proxy, a missing `NODE_EXTRA_CA_CERTS` bundle, or an expired certificate. Claude Code reports the error on the first attempt, so you can fix the certificate setup right away; see [SSL certificate errors](#ssl-certificate-errors). Claude Code still retries transient TLS conditions such as a handshake timeout. Before v2.1.199, Claude Code retried certificate failures through the full retry budget before showing the error.

127* {/* min-version: 2.1.199 */}A server error, dropped connection, or stalled stream that arrives partway through a response, once Claude has completed a block of text or a tool call in that response: Claude Code could execute the same tool calls twice if it re-ran the request, so it keeps the completed output and ends the turn with an [incomplete-response notice](#the-response-above-may-be-incomplete). Before v2.1.199, Claude Code discarded the partial output and reported the whole turn as an error when a server error arrived mid-stream.

128* {/* min-version: 2.1.208 */}An [Amazon Bedrock streaming response with an unexpected content-type](#bedrock-streaming-response-has-an-unexpected-content-type), because the gateway or proxy rewriting the response would rewrite the retry the same way. Requires Claude Code v2.1.208 or later.

129 

130### What you see while Claude Code retries or waits

122 131 

123While retrying, the spinner shows a `Retrying in Ns · attempt x/y` countdown after an error label. The label names the specific reason from the first attempt for failures you can act on right away: the network is down, a TLS handshake failed, or you hit a rate limit. For other errors it reads `API error` at first. {/* min-version: 2.1.198 */}As of v2.1.198 it switches to the specific reason from the third attempt, or on the final attempt when `CLAUDE_CODE_MAX_RETRIES` allows fewer than three; earlier versions switch only on the final attempt.132While retrying, the spinner shows a `Retrying in Ns · attempt x/y` countdown after an error label. The label names the specific reason from the first attempt for failures you can act on right away: the network is down, a TLS handshake failed, or you hit a rate limit. For other errors it reads `API error` at first. {/* min-version: 2.1.198 */}As of v2.1.198 it switches to the specific reason from the third attempt, or on the final attempt when `CLAUDE_CODE_MAX_RETRIES` allows fewer than three; earlier versions switch only on the final attempt.

124 133 

125{/* min-version: 2.1.198 */}As of v2.1.198, the usual spinner tip is suppressed during retries. Once the error reason is revealed, if the failure is a 529 overload the line below the countdown also names where to check service status: `status.claude.com` on the Anthropic API, or the provider or gateway host named in the message on other configurations.134{/* min-version: 2.1.198 */}As of v2.1.198, the usual spinner tip is suppressed during retries. Once the error reason is revealed, if the failure is a 529 overload the line below the countdown also names where to check service status: `status.claude.com` on the Anthropic API, or the provider or gateway host named in the message on other configurations.

126 135 

127{/* min-version: 2.1.185 */}If no data arrives on the response stream for 20 seconds while a request is still pending, the spinner shows `Waiting for API response · will retry in … · check your network` before any retry has started. The request has not failed yet: the countdown runs to the point where Claude Code aborts the stalled connection and retries, so the banner clears on its own once data resumes or the retry succeeds. As of v2.1.185 the threshold is 20 seconds; earlier versions show the banner after 10 seconds with different wording. If it reappears on every attempt, treat it as a [network issue](#unable-to-connect-to-api).136{/* min-version: 2.1.185 */}If no data arrives on the response stream for 20 seconds while a request is still pending, the spinner shows `Waiting for API response · will retry in … · check your network` before any retry has started. The request has not failed yet: the countdown runs to the point where Claude Code aborts the stalled connection, after which the turn either retries or ends with an error such as [The response above may be incomplete](#the-response-above-may-be-incomplete). The banner clears on its own once data resumes or a retry succeeds; if it reappears on every attempt, treat it as a [network issue](#unable-to-connect-to-api). As of v2.1.185 the threshold is 20 seconds; earlier versions show the banner after 10 seconds with different wording.

128 137 

129{/* min-version: 2.1.214 */}While Claude is consulting the [advisor](/docs/en/advisor), the banner appears after 90 seconds without data instead of 20, because a long advisor review can send nothing for well over 20 seconds. Before v2.1.214, the 20-second threshold applied during advisor calls too, so the banner appeared during advisor reviews even when nothing was wrong.138{/* min-version: 2.1.214 */}While Claude is consulting the [advisor](/docs/en/advisor), the banner appears after 90 seconds without data instead of 20, because a long advisor review can send nothing for well over 20 seconds. Before v2.1.214, the 20-second threshold applied during advisor calls too, so the banner appeared during advisor reviews even when nothing was wrong.

130 139 

131When you see one of the errors on this page, those retries have already been exhausted, unless it belongs to a class that isn't retried, such as a certificate-validation failure. You can tune the behavior with these environment variables:140### Tune retry behavior

141 

142You can tune retry behavior with these environment variables:

132 143 

133| Variable | Default | Effect |144| Variable | Default | Effect |

134| :------------------------------------------- | :------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |145| :------------------------------------------- | :------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |


138 149 

139## Server errors150## Server errors

140 151 

141Most of these errors come from the inference provider's infrastructure: Anthropic's on the Anthropic API, and that provider's on Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, or a custom gateway. [Auto mode cannot determine the safety of an action](#auto-mode-cannot-determine-the-safety-of-an-action) and [Agent terminated early due to an API error](#agent-terminated-early-due-to-an-api-error) also cover causes on your side, such as an Amazon Bedrock account that can't invoke the classifier model or a subagent that hit a usage limit.152Most of these errors come from the inference provider: Anthropic's service on the Anthropic API, and the service behind that provider's endpoint on Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, or a custom gateway. [Auto mode cannot determine the safety of an action](#auto-mode-cannot-determine-the-safety-of-an-action) and [Agent terminated early due to an API error](#agent-terminated-early-due-to-an-api-error) also cover causes on your side, such as an Amazon Bedrock account that can't invoke the classifier model or a subagent that hit a usage limit.

142 153 

143### API Error: 500 Internal server error154### API Error: 500 Internal server error

144 155 


195 206 

196### The response above may be incomplete207### The response above may be incomplete

197 208 

198A streaming response failed after Claude had already produced visible output. Re-sending the request could run the same tool calls twice, so Claude Code keeps what already streamed and appends this notice instead of discarding the turn. Which variant you see names the cause:209A streaming request failed after Claude had started producing a response. Re-sending the request could run the same tool calls twice, so Claude Code keeps the output Claude completed and appends this notice instead of discarding the turn. Which variant you see names the cause:

199 210 

200```text theme={null}211```text theme={null}

201API Error: Server error mid-response. The response above may be incomplete.212API Error: Server error mid-response. The response above may be incomplete.


207* `Connection closed mid-response`: the connection dropped.218* `Connection closed mid-response`: the connection dropped.

208* `Response stalled mid-stream`: the stream stopped sending data.219* `Response stalled mid-stream`: the stream stopped sending data.

209 220 

221Claude Code never shows this notice for a failure that happens before Claude starts producing a response: at that point it either retries the failure or ends the turn with a different error. See [Automatic retries](#automatic-retries).

222 

210**What to do:**223**What to do:**

211 224 

212* Read the response that streamed. Nothing has been lost, but the final sentences or tool calls may be missing.225* In an interactive session, read the response that remains on screen: Claude Code keeps every block Claude completed before the error, but discards an interrupted final block when the turn ends, so the final sentences or tool calls may be missing. Reply with `continue` to have Claude pick up from its last completed block.

213* Reply with `continue` to have Claude pick up where it stopped226* In [non-interactive mode](/docs/en/headless) (`-p`):

214* If the same error appears before any visible output, Claude Code retries the request instead of finalizing it. See [Automatic retries](#automatic-retries).227 * {/* min-version: 2.1.219 */}With the default text output, Claude Code prints the last completed block of text it still holds from earlier in the turn, followed by this message. When it holds none, Claude Code prints this message alone, for example because Claude completed only tool calls before the error, or because Claude Code compacted the conversation mid-turn and cleared that text. Before v2.1.219, Claude Code printed only this message in `-p` text output and dropped the response it had already produced.

228 * With `--output-format json` or `stream-json`, Claude Code reports this message in the `result` field.

229 * To continue the turn, resume the session and send `continue` as described in [Continue conversations](/docs/en/headless#continue-conversations).

215 230 

216### Auto mode cannot determine the safety of an action231### Auto mode cannot determine the safety of an action

217 232 


432 447 

433* Upgrade to v2.1.174 or later if this appears in a background or cloud session and your credentials are already configured448* Upgrade to v2.1.174 or later if this appears in a background or cloud session and your credentials are already configured

434* Confirm `ANTHROPIC_API_KEY`, `CLAUDE_CODE_OAUTH_TOKEN`, or your cloud provider credentials are set in the environment that launches the worker, not only in your interactive shell449* Confirm `ANTHROPIC_API_KEY`, `CLAUDE_CODE_OAUTH_TOKEN`, or your cloud provider credentials are set in the environment that launches the worker, not only in your interactive shell

435* For the Agent SDK, see [authentication setup](/docs/en/agent-sdk/overview#get-started)450* For the Agent SDK, see [authentication setup in the quickstart](/docs/en/agent-sdk/quickstart#setup)

436* Run `/status` in an interactive session in the same environment to confirm which credential source resolves451* Run `/status` in an interactive session in the same environment to confirm which credential source resolves

437 452 

438### Invalid API key453### Invalid API key


721 736 

722### Socket is closed737### Socket is closed

723 738 

724The connection carrying a streaming response was closed while the response was still arriving, and the failure surfaced with the text `Socket is closed`. This happens almost exclusively on Windows behind a corporate proxy, when the proxy drops an established tunnel mid-response. Claude Code treats this as a dropped connection and [retries it automatically](#automatic-retries), so the turn continues. Before v2.1.214, the retry didn't cover this failure, and the turn stopped with an error containing `Socket is closed`.739`Socket is closed` means the connection carrying a streaming response was closed while the response was still arriving. The most common cause is a corporate proxy on Windows dropping an established tunnel mid-response.

740 

741When nothing in the interrupted response had completed yet, Claude Code treats this as a dropped connection and [retries it automatically](#automatic-retries), so the turn continues. Once Claude has completed a block of text or a tool call in the response, Claude Code keeps that output and ends the turn with an [incomplete-response notice](#the-response-above-may-be-incomplete) instead. Before v2.1.214, Claude Code didn't retry this failure, and the turn stopped with an error containing `Socket is closed`.

725 742 

726**What to do:**743**What to do:**

727 744 


775x-deny-reason: host_not_allowed792x-deny-reason: host_not_allowed

776```793```

777 794 

778You may also see a TLS certificate that doesn't match the destination's real certificate. The cloud environment routes outbound traffic through a proxy that enforces the network policy, so a mismatched certificate means the proxy terminated the connection, not the destination.795You may also see a TLS certificate that doesn't match the destination's real certificate. Cloud sessions route outbound traffic through a proxy that enforces the network policy, so a mismatched certificate means the proxy terminated the connection, not the destination.

779 796 

780This is not a client-side network problem. Cloud sessions and [routines](/docs/en/routines) run inside a sandboxed environment whose outbound traffic is filtered to the environment's allowlist. The **Default** environment uses **Trusted** access, which permits the [default allowlist](/docs/en/claude-code-on-the-web#default-allowed-domains) of package registries, cloud provider APIs, container registries, and common development domains but blocks everything else.797This is not a client-side network problem. Cloud sessions and [routines](/docs/en/routines) run inside a sandboxed VM whose outbound traffic through the session's network is filtered to the [cloud environment's](/docs/en/cloud-environments) allowlist; [GitHub operations](/docs/en/cloud-environments#github-proxy) and MCP connector traffic use separate channels, which is why they can keep working while other hosts are blocked. The **Default** environment uses **Trusted** access, which permits the [default allowlist](/docs/en/cloud-environments#default-allowed-domains) of package registries, cloud provider APIs, container registries, and common development domains and blocks other domains on that path.

781 798 

782**What to do:**799**What to do:**

783 800 

784* Open the routine for editing, or start a cloud session. Select the cloud icon showing your environment's name, such as **Default**, to open the selector. Hover over your environment and click the settings icon.801* Open the routine for editing, or start a cloud session. Select the cloud icon showing your environment's name, such as **Default**, to open the selector. Hover over your environment and click the settings icon.

785* In the **Update cloud environment** dialog, change **Network access** from **Trusted** to **Custom**, then add the blocked domain to **Allowed domains**. Enter one domain per line. Check **Also include default list of common package managers** to keep the [default allowlist](/docs/en/claude-code-on-the-web#default-allowed-domains) alongside your custom domains. Select **Full** instead if you want unrestricted access.802* In the **Update cloud environment** dialog, change **Network access** from **Trusted** to **Custom**, then add the blocked domain to **Allowed domains**. Enter one domain per line. Check **Also include default list of common package managers** to keep the [default allowlist](/docs/en/cloud-environments#default-allowed-domains) alongside your custom domains. Select **Full** instead if you want unrestricted access.

786* Click **Save changes**. The next run uses the updated allowlist.803* Click **Save changes**. The next run uses the updated allowlist.

787 804 

788See [Network access](/docs/en/claude-code-on-the-web#network-access) for access levels and the default allowlist. Local CLI sessions are not affected by this policy.805See [Network access](/docs/en/cloud-environments#network-access) for access levels and the default allowlist. Local CLI sessions are not affected by this policy.

789 806 

790<h3 id="couldnt-reconnect-to-your-remote-control-session">807<h3 id="couldnt-reconnect-to-your-remote-control-session">

791 Couldn't reconnect to your Remote Control session808 Couldn't reconnect to your Remote Control session


1161 1178 

1162## Command-line errors1179## Command-line errors

1163 1180 

1164These errors come from the `claude` command line and its subcommands. Claude Code prints them before running your prompt or sending any API request.1181These errors come from the `claude` command line, its subcommands, and commands such as `/security-review` that gather context by running shell commands before their prompt runs.

1165 1182 

1166### Conflict between --bg and --print1183### Conflict between --bg and --print

1167 1184 


1258* Confirm the tool name matches the `mcp__<server>__<tool>` name the server exposes1275* Confirm the tool name matches the `mcp__<server>__<tool>` name the server exposes

1259* If the server needs longer than 30 seconds to start, raise [`MCP_TIMEOUT`](/docs/en/env-vars)1276* If the server needs longer than 30 seconds to start, raise [`MCP_TIMEOUT`](/docs/en/env-vars)

1260 1277 

1278<h3 id="security-review-fails-without-origin-head">

1279 /security-review fails without origin/HEAD

1280</h3>

1281 

1282[`/security-review`](/docs/en/commands#all-commands) builds its review context by diffing your branch against `origin/HEAD`, the local ref that records which branch is the default on your `origin` remote. When that ref doesn't exist, the git commands that gather the diff fail and the review stops before it starts.

1283 

1284```text theme={null}

1285Error: Shell command failed for pattern "!`git diff --name-only origin/HEAD...`": [stderr]

1286fatal: ambiguous argument 'origin/HEAD...': unknown revision or path not in the working tree.

1287Use '--' to separate paths from revisions, like this:

1288'git <command> [<revision>...] -- [<file>...]'

1289```

1290 

1291The quoted command varies between runs: the review starts several `git` commands against `origin/HEAD` at once and reports whichever fails first, so you may see `git log` or a different `git diff` in its place. Git creates the ref only when the remote's default branch is both advertised by the remote and covered by your fetch refspec. A full `git clone` of a remote with commits meets both conditions. Single-branch and CI checkouts fetch too narrow a refspec, a server-side HEAD left pointing at a branch nobody pushed advertises no default, and a repository with no `origin` remote, or one you never fetched, provides neither.

1292 

1293**What to do:**

1294 

1295* Create the ref by naming your remote's default branch: `git remote set-head origin <default-branch>`. This works whenever the local tracking ref `origin/<default-branch>` exists. If it doesn't, as in single-branch clones, fetch the branch first: `git remote set-branches --add origin <branch> && git fetch origin`, then rerun the set-head command. Rerun `/security-review`.

1296* If you'd rather not name the branch, run `git fetch origin && git remote set-head origin --auto`, which asks the remote which branch is its default. It fails with `error: Cannot determine remote HEAD` when the remote advertises no default branch, because it is empty or its HEAD points at a branch nobody pushed; name the branch explicitly instead. It fails with `error: Not a valid ref` when your clone doesn't fetch that branch; widen the refspec as above first.

1297* If the repository has no remote, add one with `git remote add origin <url>` and fetch before creating the ref. If the remote is empty, push your branch first with `git push -u origin HEAD` and name that branch in the set-head command; `origin/HEAD` then points at the branch you just pushed, so `/security-review` sees an empty diff until the branch diverges from it.

1298 

1261<h3 id="input-must-be-provided-when-using-print">1299<h3 id="input-must-be-provided-when-using-print">

1262 Input must be provided when using --print1300 Input must be provided when using --print

1263</h3>1301</h3>

Details

19* **Amazon Bedrock**: you use Claude models from the Amazon Bedrock model catalog and set `CLAUDE_CODE_USE_BEDROCK`. The [Mantle endpoint](/docs/en/amazon-bedrock#use-the-mantle-endpoint) (`CLAUDE_CODE_USE_MANTLE`) is covered by this column19* **Amazon Bedrock**: you use Claude models from the Amazon Bedrock model catalog and set `CLAUDE_CODE_USE_BEDROCK`. The [Mantle endpoint](/docs/en/amazon-bedrock#use-the-mantle-endpoint) (`CLAUDE_CODE_USE_MANTLE`) is covered by this column

20* **Claude Platform on AWS**: you bought Claude through AWS Marketplace but call the Anthropic API, and set `CLAUDE_CODE_USE_ANTHROPIC_AWS`20* **Claude Platform on AWS**: you bought Claude through AWS Marketplace but call the Anthropic API, and set `CLAUDE_CODE_USE_ANTHROPIC_AWS`

21* **Google Cloud's Agent Platform**: Google-operated; you set `CLAUDE_CODE_USE_VERTEX`21* **Google Cloud's Agent Platform**: Google-operated; you set `CLAUDE_CODE_USE_VERTEX`

22* **Microsoft Foundry**: Anthropic-operated on Azure; you set `CLAUDE_CODE_USE_FOUNDRY`22* **Microsoft Foundry**: Anthropic-operated; you set `CLAUDE_CODE_USE_FOUNDRY`

23 23 

24### Features available on every provider24### Features available on every provider

25 25 


34 34 

35Three of these have provider-specific differences:35Three of these have provider-specific differences:

36 36 

37* **MCP servers**: [connectors from claude.ai](/docs/en/mcp#use-mcp-servers-from-claude-ai) load only when your claude.ai subscription is the active authentication method, and [tool search](/docs/en/mcp#configure-tool-search) is off by default on Google Cloud's Agent Platform and when `ANTHROPIC_BASE_URL` points to a non-first-party host37* **MCP servers**: [connectors from claude.ai](/docs/en/mcp#use-mcp-servers-from-claude-ai) load only when your claude.ai subscription is the active authentication method. [Tool search](/docs/en/mcp#configure-tool-search) is off by default on Google Cloud's Agent Platform and when `ANTHROPIC_BASE_URL` points to a non-first-party host, and isn't supported on Microsoft Foundry [deployments hosted on Azure](https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry#hosting-options)

38* **Subagents**: the built-in [Explore subagent](/docs/en/sub-agents#built-in-subagents) caps its inherited model at Opus on the Claude API, and inherits the main conversation's model directly on any other provider, including Claude Platform on AWS38* **Subagents**: the built-in [Explore subagent](/docs/en/sub-agents#built-in-subagents) caps its inherited model at Opus on the Claude API, and inherits the main conversation's model directly on any other provider, including Claude Platform on AWS

39* **[Commands](/docs/en/commands#all-commands)**: `/design-sync` and `/radio` are unavailable on Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, and Claude Platform on AWS, and `/voice` requires a claude.ai account39* **[Commands](/docs/en/commands#all-commands)**: `/design-sync` and `/radio` are unavailable on Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, and Claude Platform on AWS, and `/voice` requires a claude.ai account

40 40 


80 <td>✗</td>80 <td>✗</td>

81 <td>✓</td>81 <td>✓</td>

82 <td>See note <sup><a href="#fn1">1</a></sup></td>82 <td>See note <sup><a href="#fn1">1</a></sup></td>

83 <td>✓</td>83 <td>✓ ([deployments hosted on Anthropic](https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry#hosting-options))</td>

84 </tr>84 </tr>

85 85 

86 <tr>86 <tr>


255 **Partial support:**255 **Partial support:**

256 256 

257 * [Desktop](/docs/en/desktop): only via [Claude Desktop on 3P](https://claude.com/docs/third-party/claude-desktop/overview)257 * [Desktop](/docs/en/desktop): only via [Claude Desktop on 3P](https://claude.com/docs/third-party/claude-desktop/overview)

258 * [Web search](/docs/en/tools-reference#websearch-tool-behavior): [deployments hosted on Anthropic](https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry#hosting-options) only

258 * [Auto mode](/docs/en/auto-mode-config): Sonnet 5, Opus 4.7 or later, and Fable 5 only259 * [Auto mode](/docs/en/auto-mode-config): Sonnet 5, Opus 4.7 or later, and Fable 5 only

259 * [`/loop`](/docs/en/scheduled-tasks): explicit intervals only260 * [`/loop`](/docs/en/scheduled-tasks): explicit intervals only

260 * [Zero Data Retention](/docs/en/zero-data-retention): subject to your Azure agreement261 * [Zero Data Retention](/docs/en/zero-data-retention): subject to your Azure agreement

Details

12 12 

13GitHub 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 Owner connects your GHES instance, developers can run web sessions and get automated code reviews without any per-repository configuration. Plugin marketplaces hosted on your instance are also supported; credential requirements vary by surface, as described in [Plugin marketplaces on GHES](#plugin-marketplaces-on-ghes).13GitHub 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 Owner connects your GHES instance, developers can run web sessions and get automated code reviews without any per-repository configuration. Plugin marketplaces hosted on your instance are also supported; credential requirements vary by surface, as described in [Plugin marketplaces on GHES](#plugin-marketplaces-on-ghes).

14 14 

15For repositories on github.com, see [Claude Code on the web](/en/claude-code-on-the-web) and [Code Review](/en/code-review). To run Claude in your own CI infrastructure, see [GitHub Actions](/en/github-actions).15For repositories on github.com, see [Claude Code on the web](/docs/en/claude-code-on-the-web) and [Code Review](/docs/en/code-review). To run Claude in your own CI infrastructure, see [GitHub Actions](/docs/en/github-actions).

16 16 

17## What works with GitHub Enterprise Server17## What works with GitHub Enterprise Server

18 18 


25| Claude Security | ✅ Supported | Available in public beta for Enterprise plans at [claude.ai/security](https://claude.ai/security) |25| Claude Security | ✅ Supported | Available in public beta for Enterprise plans at [claude.ai/security](https://claude.ai/security) |

26| Teleport sessions | ✅ Supported | Move sessions between web and terminal with `--teleport` |26| Teleport sessions | ✅ Supported | Move sessions between web and terminal with `--teleport` |

27| Plugin marketplaces | ✅ Supported | Credential requirements differ by surface. See [Plugin marketplaces on GHES](#plugin-marketplaces-on-ghes) |27| Plugin marketplaces | ✅ Supported | Credential requirements differ by surface. See [Plugin marketplaces on GHES](#plugin-marketplaces-on-ghes) |

28| Contribution metrics | ✅ Supported | Delivered via webhooks to the [analytics dashboard](/en/analytics) |28| Contribution metrics | ✅ Supported | Delivered via webhooks to the [analytics dashboard](/docs/en/analytics) |

29| GitHub Actions | ✅ Supported | Requires manual workflow setup; `/install-github-app` is github.com only |29| GitHub Actions | ✅ Supported | Requires manual workflow setup; `/install-github-app` is github.com only |

30| GitHub MCP server | ❌ Not supported | The GitHub MCP server does not work with GHES instances |30| GitHub MCP server | ❌ Not supported | The GitHub MCP server does not work with GHES instances |

31 31 


53 </Step>53 </Step>

54 54 

55 <Step title="Enable features">55 <Step title="Enable features">

56 Return to [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code) and enable [Code Review](/en/code-review#set-up-code-review), Claude Security, and [contribution metrics](/en/analytics#enable-contribution-metrics) for your GHES repositories using the same configuration as github.com.56 Return to [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code) and enable [Code Review](/docs/en/code-review#set-up-code-review), Claude Security, and [contribution metrics](/docs/en/analytics#enable-contribution-metrics) for your GHES repositories using the same configuration as github.com.

57 </Step>57 </Step>

58</Steps>58</Steps>

59 59 


98claude --cloud "Add retry logic to the payment webhook handler"98claude --cloud "Add retry logic to the payment webhook handler"

99```99```

100 100 

101The 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](https://claude.ai/code). See [Claude Code on the web](/en/claude-code-on-the-web) for the full cloud session workflow including diff review, auto-fix, and routines.101The 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](https://claude.ai/code). See [Claude Code on the web](/docs/en/claude-code-on-the-web) for the full cloud session workflow including diff review, auto-fix, and routines.

102 102 

103### Teleport sessions to your terminal103### Teleport sessions to your terminal

104 104 

105Pull 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](/en/claude-code-on-the-web#teleport-requirements) for details.105Pull 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](/docs/en/claude-code-on-the-web#teleport-requirements) for details.

106 106 

107## Plugin marketplaces on GHES107## Plugin marketplaces on GHES

108 108 


136 136 

137Claude Code runs git non-interactively and rejects SSH connections to hosts that are not in the machine's `known_hosts` file. An HTTPS URL with a git credential helper avoids the `known_hosts` requirement.137Claude Code runs git non-interactively and rejects SSH connections to hosts that are not in the machine's `known_hosts` file. An HTTPS URL with a git credential helper avoids the `known_hosts` requirement.

138 138 

139See [Create and distribute a plugin marketplace](/en/plugin-marketplaces) for the full guide to building marketplaces.139See [Create and distribute a plugin marketplace](/docs/en/plugin-marketplaces) for the full guide to building marketplaces.

140 140 

141### Pre-register GHES marketplaces with managed settings141### Pre-register GHES marketplaces with managed settings

142 142 

143The `extraKnownMarketplaces` setting pre-registers a marketplace so developers get it without manual setup. It works from [any settings file](/en/settings#extraknownmarketplaces), including a repository's `.claude/settings.json`; managed settings deliver it organization-wide:143The `extraKnownMarketplaces` setting pre-registers a marketplace so developers get it without manual setup. It works from [any settings file](/docs/en/settings#extraknownmarketplaces), including a repository's `.claude/settings.json`; managed settings deliver it organization-wide:

144 144 

145```json theme={null}145```json theme={null}

146{146{


160* **Use a full git URL.** The `owner/repo` shorthand always resolves to github.com and cannot reference a GHES host.160* **Use a full git URL.** The `owner/repo` shorthand always resolves to github.com and cannot reference a GHES host.

161* **Prefer HTTPS URLs.** SSH clones fail on machines that do not already trust your GHES host key. An HTTPS URL with your organization's standard git credential helper works on any machine with credentials configured.161* **Prefer HTTPS URLs.** SSH clones fail on machines that do not already trust your GHES host key. An HTTPS URL with your organization's standard git credential helper works on any machine with credentials configured.

162* **Confirm each machine can clone from your GHES host.** If a machine lacks credentials, the marketplace is registered but never installed, and its plugins report as not found instead of prompting for credentials.162* **Confirm each machine can clone from your GHES host.** If a machine lacks credentials, the marketplace is registered but never installed, and its plugins report as not found instead of prompting for credentials.

163* **Confirm the setting reaches each machine.** A managed settings file only takes effect on machines it's deployed to, for example through your device management system. See [managed settings](/en/settings#settings-files) for file locations.163* **Confirm the setting reaches each machine.** A managed settings file only takes effect on machines it's deployed to, for example through your device management system. See [managed settings](/docs/en/settings#settings-files) for file locations.

164 164 

165### Allowlist GHES marketplaces in managed settings165### Allowlist GHES marketplaces in managed settings

166 166 

167If your organization uses [managed settings](/en/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:167If your organization uses [managed settings](/docs/en/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. See [settings files](/docs/en/settings#settings-files) for file locations on each platform. Add the JSON to your `managed-settings.json` file or equivalent MDM policy:

168 168 

169```json theme={null}169```json theme={null}

170{170{


177}177}

178```178```

179 179 

180See the [strictKnownMarketplaces](/en/settings#strictknownmarketplaces) and [extraKnownMarketplaces](/en/settings#extraknownmarketplaces) settings reference for the complete schema.180See the [strictKnownMarketplaces](/docs/en/settings#strictknownmarketplaces) and [extraKnownMarketplaces](/docs/en/settings#extraknownmarketplaces) settings reference for the complete schema.

181 181 

182## Limitations182## Limitations

183 183 


216 216 

217These pages cover the features referenced throughout this guide in more depth:217These pages cover the features referenced throughout this guide in more depth:

218 218 

219* [Claude Code on the web](/en/claude-code-on-the-web): run Claude Code sessions on cloud infrastructure219* [Claude Code on the web](/docs/en/claude-code-on-the-web): run Claude Code sessions on cloud infrastructure

220* [Code Review](/en/code-review): automated PR reviews220* [Code Review](/docs/en/code-review): automated PR reviews

221* [Plugin marketplaces](/en/plugin-marketplaces): build and distribute plugin catalogs221* [Plugin marketplaces](/docs/en/plugin-marketplaces): build and distribute plugin catalogs

222* [Analytics](/en/analytics): track usage and contribution metrics222* [Analytics](/docs/en/analytics): track usage and contribution metrics

223* [Managed settings](/en/settings): organization-wide policy configuration223* [Managed settings](/docs/en/settings): organization-wide policy configuration

224* [Network configuration](/en/network-config): firewall and IP allowlist requirements224* [Network configuration](/docs/en/network-config): firewall and IP allowlist requirements

glossary.md +52 −52

Details

14 14 

15Multiple independent Claude Code sessions coordinated by a team lead, with a shared task list and peer-to-peer messaging. Unlike [subagents](#subagent), which run within a single session and report only to the parent, teammates each have their own context window and you can interact with any of them directly. Agent teams are experimental and must be enabled by setting `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1`.15Multiple independent Claude Code sessions coordinated by a team lead, with a shared task list and peer-to-peer messaging. Unlike [subagents](#subagent), which run within a single session and report only to the parent, teammates each have their own context window and you can interact with any of them directly. Agent teams are experimental and must be enabled by setting `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1`.

16 16 

17Learn more: [Run agent teams](/en/agent-teams)17Learn more: [Run agent teams](/docs/en/agent-teams)

18 18 

19### Agentic coding19### Agentic coding

20 20 

21A workflow where the AI can read files, run commands, and make changes autonomously while you watch, redirect, or step away, as opposed to chat-based assistants that only respond with text you must apply yourself. Claude Code is agentic because it has [tools](#tool) that let it act, not just advise.21A workflow where the AI can read files, run commands, and make changes autonomously while you watch, redirect, or step away, as opposed to chat-based assistants that only respond with text you must apply yourself. Claude Code is agentic because it has [tools](#tool) that let it act, not just advise.

22 22 

23Learn more: [How Claude Code works](/en/how-claude-code-works)23Learn more: [How Claude Code works](/docs/en/how-claude-code-works)

24 24 

25### Agentic harness25### Agentic harness

26 26 

27The tools, context management, and execution environment that turn a language model into a capable coding agent. Claude Code is the harness; Claude is the model inside it. The harness supplies file access, shell execution, permission gating, memory loading, and the loop that chains actions together.27The tools, context management, and execution environment that turn a language model into a capable coding agent. Claude Code is the harness; Claude is the model inside it. The harness supplies file access, shell execution, permission gating, memory loading, and the loop that chains actions together.

28 28 

29Learn more: [How Claude Code works](/en/how-claude-code-works)29Learn more: [How Claude Code works](/docs/en/how-claude-code-works)

30 30 

31### Agentic loop31### Agentic loop

32 32 

33The cycle Claude works through for every task: gather context, take action, verify results, and repeat until done. Each tool use returns information that informs the next step. You can interrupt the loop at any point to redirect. Most extension points, including [hooks](#hook), [skills](#skill), and [MCP](#mcp-model-context-protocol), plug into specific phases of this loop.33The cycle Claude works through for every task: gather context, take action, verify results, and repeat until done. Each tool use returns information that informs the next step. You can interrupt the loop at any point to redirect. Most extension points, including [hooks](#hook), [skills](#skill), and [MCP](#mcp-model-context-protocol), plug into specific phases of this loop.

34 34 

35Learn more: [How Claude Code works](/en/how-claude-code-works#the-agentic-loop)35Learn more: [How Claude Code works](/docs/en/how-claude-code-works#the-agentic-loop)

36 36 

37### Artifact37### Artifact

38 38 

39A live, interactive web page Claude Code publishes from your session to a private URL on claude.ai, so you can see output visually or share it instead of reading terminal text. The page updates in place when the session republishes. Artifacts you create from Claude Code appear in the same gallery as artifacts created in claude.ai conversations. Sharing depends on your plan: on Pro and Max, a public link that anyone can open; on Team and Enterprise, sharing within your organization, plus public links once an Owner enables them.39A live, interactive web page Claude Code publishes from your session to a private URL on claude.ai, so you can see output visually or share it instead of reading terminal text. The page updates in place when the session republishes. Artifacts you create from Claude Code appear in the same gallery as artifacts created in claude.ai conversations. Sharing depends on your plan: on Pro and Max, a public link that anyone can open; on Team and Enterprise, sharing within your organization, plus public links once an Owner enables them.

40 40 

41Learn more: [Share session output as artifacts](/en/artifacts)41Learn more: [Share session output as artifacts](/docs/en/artifacts)

42 42 

43### Auto memory43### Auto memory

44 44 

45Notes Claude writes for itself based on your corrections and preferences, stored per git repository under `~/.claude/projects/`. All worktrees of the same repository share one auto memory directory. The first 200 lines or 25 KB of the `MEMORY.md` index loads at the start of every session. Auto memory is the Claude-written counterpart to [CLAUDE.md](#claude-md), which you write.45Notes Claude writes for itself based on your corrections and preferences, stored per git repository under `~/.claude/projects/`. All worktrees of the same repository share one auto memory directory. The first 200 lines or 25 KB of the `MEMORY.md` index loads at the start of every session. Auto memory is the Claude-written counterpart to [CLAUDE.md](#claude-md), which you write.

46 46 

47Learn more: [Auto memory](/en/memory#auto-memory)47Learn more: [Auto memory](/docs/en/memory#auto-memory)

48 48 

49### Auto mode49### Auto mode

50 50 

51A [permission mode](#permission-mode) where a separate classifier model reviews actions in the background, so most run without approval prompts; explicit ask rules still prompt. The classifier blocks scope escalation, untrusted infrastructure, and [prompt injection](#prompt-injection). It never sees tool results, so injected instructions cannot influence its decisions.51A [permission mode](#permission-mode) where a separate classifier model reviews actions in the background, so most run without approval prompts; explicit ask rules still prompt. The classifier blocks scope escalation, untrusted infrastructure, and [prompt injection](#prompt-injection). It never sees tool results, so injected instructions cannot influence its decisions.

52 52 

53Learn more: [Eliminate prompts with auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode)53Learn more: [Eliminate prompts with auto mode](/docs/en/permission-modes#eliminate-prompts-with-auto-mode)

54 54 

55## B55## B

56 56 


58 58 

59A startup flag, `--bare`, that skips auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md. Only flags you pass explicitly take effect. Recommended for CI and scripted calls where you need identical behavior across machines regardless of local configuration.59A startup flag, `--bare`, that skips auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md. Only flags you pass explicitly take effect. Recommended for CI and scripted calls where you need identical behavior across machines regardless of local configuration.

60 60 

61Learn more: [Start faster with bare mode](/en/headless#start-faster-with-bare-mode)61Learn more: [Start faster with bare mode](/docs/en/headless#start-faster-with-bare-mode)

62 62 

63### Bundled skills63### Bundled skills

64 64 

65Prompt-based playbooks included with Claude Code, such as `/batch`, `/code-review`, `/debug`, and `/loop`. Unlike built-in commands, which execute fixed logic, bundled skills give Claude a detailed prompt and let it orchestrate the work, so they can spawn agents, read files, and adapt to your codebase.65Prompt-based playbooks included with Claude Code, such as `/batch`, `/code-review`, `/debug`, and `/loop`. Unlike built-in commands, which execute fixed logic, bundled skills give Claude a detailed prompt and let it orchestrate the work, so they can spawn agents, read files, and adapt to your codebase.

66 66 

67Learn more: [Bundled skills](/en/skills#bundled-skills)67Learn more: [Bundled skills](/docs/en/skills#bundled-skills)

68 68 

69## C69## C

70 70 


72 72 

73An [MCP server](#mcp-model-context-protocol) that pushes events into your running session so Claude can react to things that happen while you're away from the terminal. Channels can be two-way: Claude reads an inbound event and replies back through the same channel. Telegram, Discord, and iMessage are included in the research preview.73An [MCP server](#mcp-model-context-protocol) that pushes events into your running session so Claude can react to things that happen while you're away from the terminal. Channels can be two-way: Claude reads an inbound event and replies back through the same channel. Telegram, Discord, and iMessage are included in the research preview.

74 74 

75Learn more: [Channels](/en/channels)75Learn more: [Channels](/docs/en/channels)

76 76 

77### Checkpoint77### Checkpoint

78 78 

79A restore point created at each prompt you send. Claude Code snapshots files before every edit so a checkpoint can revert them. Press `Esc` twice or run `/rewind` to restore code, conversation, or both to an earlier point, or to summarize part of the conversation from a selected message. Checkpoints are saved with the conversation, so a resumed session can still `/rewind` to them. They're separate from git and don't track changes made through the Bash tool.79A restore point created at each prompt you send. Claude Code snapshots files before every edit so a checkpoint can revert them. Press `Esc` twice or run `/rewind` to restore code, conversation, or both to an earlier point, or to summarize part of the conversation from a selected message. Checkpoints are saved with the conversation, so a resumed session can still `/rewind` to them. They're separate from git and don't track changes made through the Bash tool.

80 80 

81Learn more: [Checkpointing](/en/checkpointing)81Learn more: [Checkpointing](/docs/en/checkpointing)

82 82 

83### `.claude` directory83### `.claude` directory

84 84 

85The directory where Claude Code reads project-scoped configuration: settings, hooks, skills, subagents, rules, and auto memory. A project has `.claude/` at its root; your user-level defaults are at `~/.claude/`.85The directory where Claude Code reads project-scoped configuration: settings, hooks, skills, subagents, rules, and auto memory. A project has `.claude/` at its root; your user-level defaults are at `~/.claude/`.

86 86 

87Learn more: [The `.claude` directory](/en/claude-directory)87Learn more: [The `.claude` directory](/docs/en/claude-directory)

88 88 

89### CLAUDE.md89### CLAUDE.md

90 90 


92 92 

93You can place CLAUDE.md at project scope in `./CLAUDE.md` or `./.claude/CLAUDE.md`, at user scope in `~/.claude/CLAUDE.md`, or as [managed policy](#managed-settings) for your organization. All discovered files are concatenated into context rather than overriding each other, ordered from broadest scope to most specific.93You can place CLAUDE.md at project scope in `./CLAUDE.md` or `./.claude/CLAUDE.md`, at user scope in `~/.claude/CLAUDE.md`, or as [managed policy](#managed-settings) for your organization. All discovered files are concatenated into context rather than overriding each other, ordered from broadest scope to most specific.

94 94 

95Learn more: [CLAUDE.md files](/en/memory#claude-md-files)95Learn more: [CLAUDE.md files](/docs/en/memory#claude-md-files)

96 96 

97### Command97### Command

98 98 

99A reusable instruction you invoke by typing `/name` in the prompt. Built-in commands such as `/clear`, `/model`, and `/compact` control the session. You can define your own commands as files in `.claude/commands/`, or install them from a [plugin](#plugin). [Skills](#skill) are the recommended way to package multi-step commands.99A reusable instruction you invoke by typing `/name` in the prompt. Built-in commands such as `/clear`, `/model`, and `/compact` control the session. You can define your own commands as files in `.claude/commands/`, or install them from a [plugin](#plugin). [Skills](#skill) are the recommended way to package multi-step commands.

100 100 

101Two other uses of the word are unrelated: `claude` CLI subcommands such as `claude mcp add`, listed in the [CLI reference](/en/cli-reference#cli-commands), and the `command` field of a stdio [MCP server](#mcp-server) entry, which specifies the executable Claude Code launches to start the server.101Two other uses of the word are unrelated: `claude` CLI subcommands such as `claude mcp add`, listed in the [CLI reference](/docs/en/cli-reference#cli-commands), and the `command` field of a stdio [MCP server](#mcp-server) entry, which specifies the executable Claude Code launches to start the server.

102 102 

103Learn more: [Commands](/en/commands) · [Skills](/en/skills)103Learn more: [Commands](/docs/en/commands) · [Skills](/docs/en/skills)

104 104 

105### Compaction105### Compaction

106 106 

107Automatic summarization of your conversation when the [context window](#context-window) approaches its limit. Older tool outputs are cleared first, then the conversation is summarized. Project-root CLAUDE.md and auto memory survive compaction and reload from disk; instructions given only in conversation may be lost. Run `/compact` to trigger manually, optionally with a focus like `/compact focus on the API changes`.107Automatic summarization of your conversation when the [context window](#context-window) approaches its limit. Older tool outputs are cleared first, then the conversation is summarized. Project-root CLAUDE.md and auto memory survive compaction and reload from disk; instructions given only in conversation may be lost. Run `/compact` to trigger manually, optionally with a focus like `/compact focus on the API changes`.

108 108 

109Learn more: [What survives compaction](/en/context-window#what-survives-compaction) · [When context fills up](/en/how-claude-code-works#when-context-fills-up)109Learn more: [What survives compaction](/docs/en/context-window#what-survives-compaction) · [When context fills up](/docs/en/how-claude-code-works#when-context-fills-up)

110 110 

111### Connector111### Connector

112 112 

113An [MCP server](#mcp-server) added to your claude.ai account rather than configured in Claude Code. When you sign in to Claude Code with that account, your connectors appear in `/mcp` alongside the servers you added locally. Organizations can also provision connectors and set per-tool controls on them.113An [MCP server](#mcp-server) added to your claude.ai account rather than configured in Claude Code. When you sign in to Claude Code with that account, your connectors appear in `/mcp` alongside the servers you added locally. Organizations can also provision connectors and set per-tool controls on them.

114 114 

115Learn more: [Use MCP servers from claude.ai](/en/mcp#use-mcp-servers-from-claude-ai)115Learn more: [Use MCP servers from claude.ai](/docs/en/mcp#use-mcp-servers-from-claude-ai)

116 116 

117### Context window117### Context window

118 118 

119The working memory for a session, holding conversation history, file contents, command outputs, CLAUDE.md, auto memory, loaded skills, and system instructions. As you work, context fills up until [compaction](#compaction) summarizes it. Run `/context` to see what's using space. For the underlying model concept, see the [platform glossary](https://platform.claude.com/docs/en/about-claude/glossary#context-window).119The working memory for a session, holding conversation history, file contents, command outputs, CLAUDE.md, auto memory, loaded skills, and system instructions. As you work, context fills up until [compaction](#compaction) summarizes it. Run `/context` to see what's using space. For the underlying model concept, see the [platform glossary](https://platform.claude.com/docs/en/about-claude/glossary#context-window).

120 120 

121Learn more: [Explore the context window](/en/context-window)121Learn more: [Explore the context window](/docs/en/context-window)

122 122 

123## D123## D

124 124 


126 126 

127A phone-initiated task router that spawns a Claude Code session in the Desktop app when you send a coding task from the Claude mobile app. Your prompt routes to the right tool automatically. Available on Pro and Max plans.127A phone-initiated task router that spawns a Claude Code session in the Desktop app when you send a coding task from the Claude mobile app. Your prompt routes to the right tool automatically. Available on Pro and Max plans.

128 128 

129Learn more: [Sessions from Dispatch](/en/desktop#sessions-from-dispatch)129Learn more: [Sessions from Dispatch](/docs/en/desktop#sessions-from-dispatch)

130 130 

131## E131## E

132 132 


134 134 

135A setting that controls how much of the adaptive-reasoning thinking budget Claude uses on each turn. Higher effort means more thinking tokens and deeper reasoning; lower effort is faster and cheaper. Effort is supported on Fable 5, on Opus 4.6 and later, and on Sonnet 4.6 and later.135A setting that controls how much of the adaptive-reasoning thinking budget Claude uses on each turn. Higher effort means more thinking tokens and deeper reasoning; lower effort is faster and cheaper. Effort is supported on Fable 5, on Opus 4.6 and later, and on Sonnet 4.6 and later.

136 136 

137Learn more: [Adjust effort level](/en/model-config#adjust-effort-level)137Learn more: [Adjust effort level](/docs/en/model-config#adjust-effort-level)

138 138 

139### Extended thinking139### Extended thinking

140 140 

141Visible step-by-step reasoning the model performs before responding. You can adjust it with the [effort level](#effort-level), or cap thinking tokens with `MAX_THINKING_TOKENS` on models with a fixed thinking budget. Thinking appears in gray italic text in the terminal.141Visible step-by-step reasoning the model performs before responding. You can adjust it with the [effort level](#effort-level), or cap thinking tokens with `MAX_THINKING_TOKENS` on models with a fixed thinking budget. Thinking appears in gray italic text in the terminal.

142 142 

143Learn more: [Use extended thinking](/en/model-config#extended-thinking)143Learn more: [Use extended thinking](/docs/en/model-config#extended-thinking)

144 144 

145## H145## H

146 146 


154* **Matcher**: filters which events fire it154* **Matcher**: filters which events fire it

155* **Hook handler**: what runs155* **Hook handler**: what runs

156 156 

157Learn more: [Get started with hooks](/en/hooks-guide) · [Hooks reference](/en/hooks)157Learn more: [Get started with hooks](/docs/en/hooks-guide) · [Hooks reference](/docs/en/hooks)

158 158 

159## M159## M

160 160 

161### Managed settings161### Managed settings

162 162 

163Settings enforced org-wide by IT or DevOps, delivered from Anthropic's servers through the admin console or deployed to devices at an OS-level path outside `~/.claude`. User and project settings cannot override managed settings. Server-managed delivery applies on [eligible configurations](/en/server-managed-settings#platform-availability); see [Security considerations](/en/server-managed-settings#security-considerations). Use this for security policies, compliance requirements, or standardized tooling across a fleet.163Settings enforced org-wide by IT or DevOps, delivered from Anthropic's servers through the admin console or deployed to devices at an OS-level path outside `~/.claude`. User and project settings cannot override managed settings. Server-managed delivery applies on [eligible configurations](/docs/en/server-managed-settings#platform-availability); see [Security considerations](/docs/en/server-managed-settings#security-considerations). Use this for security policies, compliance requirements, or standardized tooling across a fleet.

164 164 

165Learn more: [Server-managed settings](/en/server-managed-settings) · [Settings files](/en/settings#settings-files)165Learn more: [Server-managed settings](/docs/en/server-managed-settings) · [Settings files](/docs/en/settings#settings-files)

166 166 

167### MCP (Model Context Protocol)167### MCP (Model Context Protocol)

168 168 

169An open standard for connecting AI tools to external data sources and services. MCP servers give Claude new tools for Slack, Jira, databases, browsers, and hundreds of other integrations. You connect servers via `/mcp` or by adding them to `.mcp.json`. For the protocol itself, see the [platform glossary](https://platform.claude.com/docs/en/about-claude/glossary#mcp-model-context-protocol).169An open standard for connecting AI tools to external data sources and services. MCP servers give Claude new tools for Slack, Jira, databases, browsers, and hundreds of other integrations. You connect servers via `/mcp` or by adding them to `.mcp.json`. For the protocol itself, see the [platform glossary](https://platform.claude.com/docs/en/about-claude/glossary#mcp-model-context-protocol).

170 170 

171Learn more: [Model Context Protocol](/en/mcp)171Learn more: [Model Context Protocol](/docs/en/mcp)

172 172 

173### MCP server173### MCP server

174 174 

175A program that gives Claude tools, prompts, or resources over [MCP](#mcp-model-context-protocol). You add servers with `claude mcp add`, in `.mcp.json`, through a [plugin](#plugin), or as a claude.ai [connector](#connector). A local stdio server runs as a process Claude Code starts from the `command` and `args` fields of its configuration, which have nothing to do with the [commands](#command) you type at the prompt.175A program that gives Claude tools, prompts, or resources over [MCP](#mcp-model-context-protocol). You add servers with `claude mcp add`, in `.mcp.json`, through a [plugin](#plugin), or as a claude.ai [connector](#connector). A local stdio server runs as a process Claude Code starts from the `command` and `args` fields of its configuration, which have nothing to do with the [commands](#command) you type at the prompt.

176 176 

177Learn more: [Model Context Protocol](/en/mcp)177Learn more: [Model Context Protocol](/docs/en/mcp)

178 178 

179### MCP Tool Search179### MCP Tool Search

180 180 

181A context-saving mechanism that defers MCP tool schemas until needed. Only tool names load at startup; Claude fetches the full schema on demand when it decides to use a specific tool. This keeps idle MCP servers from consuming much context.181A context-saving mechanism that defers MCP tool schemas until needed. Only tool names load at startup; Claude fetches the full schema on demand when it decides to use a specific tool. This keeps idle MCP servers from consuming much context.

182 182 

183Learn more: [Scale with MCP Tool Search](/en/mcp#scale-with-mcp-tool-search)183Learn more: [Scale with MCP Tool Search](/docs/en/mcp#scale-with-mcp-tool-search)

184 184 

185## N185## N

186 186 

187### Non-interactive mode187### Non-interactive mode

188 188 

189A mode that executes a single prompt and exits without an interactive prompt, invoked with `-p` or `--print`. Used for CI, scripts, and piping. The run is still saved as a resumable session unless you pass `--no-session-persistence`. The [Agent SDK](/en/agent-sdk/overview) is the Python and TypeScript equivalent. Formerly called headless mode.189A mode that executes a single prompt and exits without an interactive prompt, invoked with `-p` or `--print`. Used for CI, scripts, and piping. The run is still saved as a resumable session unless you pass `--no-session-persistence`. The [Agent SDK](/docs/en/agent-sdk/overview) is the Python and TypeScript equivalent. Formerly called headless mode.

190 190 

191Learn more: [Run Claude Code programmatically](/en/headless)191Learn more: [Run Claude Code programmatically](/docs/en/headless)

192 192 

193## O193## O

194 194 


196 196 

197A configuration that modifies Claude's system prompt to change response behavior, tone, or format. Output styles turn off the software-engineering-specific parts of the default system prompt, unlike [CLAUDE.md](#claude-md) which is delivered as a user message following the system prompt. Built-in styles include Default, Proactive, Explanatory, and Learning.197A configuration that modifies Claude's system prompt to change response behavior, tone, or format. Output styles turn off the software-engineering-specific parts of the default system prompt, unlike [CLAUDE.md](#claude-md) which is delivered as a user message following the system prompt. Built-in styles include Default, Proactive, Explanatory, and Learning.

198 198 

199Learn more: [Output styles](/en/output-styles)199Learn more: [Output styles](/docs/en/output-styles)

200 200 

201## P201## P

202 202 


206 206 

207The `default` mode is labeled Manual in the CLI, in the VS Code and JetBrains extensions, and in the desktop app, and Claude Code accepts `manual` as an alias for the value.207The `default` mode is labeled Manual in the CLI, in the VS Code and JetBrains extensions, and in the desktop app, and Claude Code accepts `manual` as an alias for the value.

208 208 

209Learn more: [Choose a permission mode](/en/permission-modes)209Learn more: [Choose a permission mode](/docs/en/permission-modes)

210 210 

211### Permission rule211### Permission rule

212 212 

213A settings entry that allows, asks about, or denies a tool invocation based on the tool name and argument pattern. Rules are evaluated deny→ask→allow, first match wins. Permission rules are fine-grained controls layered on top of the broader [permission mode](#permission-mode).213A settings entry that allows, asks about, or denies a tool invocation based on the tool name and argument pattern. Rules are evaluated deny→ask→allow, first match wins. Permission rules are fine-grained controls layered on top of the broader [permission mode](#permission-mode).

214 214 

215Learn more: [Configure permissions](/en/permissions)215Learn more: [Configure permissions](/docs/en/permissions)

216 216 

217### Plan mode217### Plan mode

218 218 

219A [permission mode](#permission-mode) where Claude researches and proposes changes without editing your source files. It can read, search, and run exploration commands, then presents a plan for approval before touching anything. Enter plan mode with `/plan` or by pressing `Shift+Tab`.219A [permission mode](#permission-mode) where Claude researches and proposes changes without editing your source files. It can read, search, and run exploration commands, then presents a plan for approval before touching anything. Enter plan mode with `/plan` or by pressing `Shift+Tab`.

220 220 

221Learn more: [Analyze before you edit with plan mode](/en/permission-modes#analyze-before-you-edit-with-plan-mode)221Learn more: [Analyze before you edit with plan mode](/docs/en/permission-modes#analyze-before-you-edit-with-plan-mode)

222 222 

223### Plugin223### Plugin

224 224 

225A bundle of skills, hooks, subagents, and MCP servers packaged as a single installable unit. Plugin skills are namespaced as `plugin-name:skill-name` so multiple plugins coexist. Distribute plugins across teams via a [marketplace](/en/plugin-marketplaces).225A bundle of skills, hooks, subagents, and MCP servers packaged as a single installable unit. Plugin skills are namespaced as `plugin-name:skill-name` so multiple plugins coexist. Distribute plugins across teams via a [marketplace](/docs/en/plugin-marketplaces).

226 226 

227Learn more: [Plugins](/en/plugins)227Learn more: [Plugins](/docs/en/plugins)

228 228 

229### Project trust229### Project trust

230 230 

231A dialog accepting a directory before Claude Code loads its configuration. Acceptance is saved per project directory, except your home directory, where trust is held for the current session only and the prompt reappears on each launch. Trust gates auto-installation of marketplace plugins and execution of project-defined hooks. Trusting a directory means its `.claude/settings.json`, `.mcp.json`, and other config files take effect.231A dialog accepting a directory before Claude Code loads its configuration. Acceptance is saved per project directory, except your home directory, where trust is held for the current session only and the prompt reappears on each launch. Trust gates auto-installation of marketplace plugins and execution of project-defined hooks. Trusting a directory means its `.claude/settings.json`, `.mcp.json`, and other config files take effect.

232 232 

233Learn more: [The `.claude` directory](/en/claude-directory)233Learn more: [The `.claude` directory](/docs/en/claude-directory)

234 234 

235### Prompt injection235### Prompt injection

236 236 

237Hostile instructions embedded in a file, web page, or tool result that attempt to redirect Claude toward actions you never asked for. Claude Code's defenses include the permission system, command injection detection, and trust verification. [Auto mode](#auto-mode) adds a server-side probe that scans tool results for suspicious content and a classifier that never sees tool results, so injected text cannot influence its approval decisions.237Hostile instructions embedded in a file, web page, or tool result that attempt to redirect Claude toward actions you never asked for. Claude Code's defenses include the permission system, command injection detection, and trust verification. [Auto mode](#auto-mode) adds a server-side probe that scans tool results for suspicious content and a classifier that never sees tool results, so injected text cannot influence its approval decisions.

238 238 

239Learn more: [Protect against prompt injection](/en/security#protect-against-prompt-injection)239Learn more: [Protect against prompt injection](/docs/en/security#protect-against-prompt-injection)

240 240 

241## R241## R

242 242 


244 244 

245A way to continue a local Claude Code session from your phone or browser via claude.ai. Your code execution and files stay on your machine; the interface is remote. Different from Claude Code on the web, which runs in a cloud sandbox.245A way to continue a local Claude Code session from your phone or browser via claude.ai. Your code execution and files stay on your machine; the interface is remote. Different from Claude Code on the web, which runs in a cloud sandbox.

246 246 

247Learn more: [Remote Control](/en/remote-control)247Learn more: [Remote Control](/docs/en/remote-control)

248 248 

249### Rules249### Rules

250 250 

251Modular instruction files in `.claude/rules/` that load alongside CLAUDE.md. A rule can be path-scoped with YAML `paths:` frontmatter so it only loads when Claude reads a matching file, keeping context lean until it's relevant.251Modular instruction files in `.claude/rules/` that load alongside CLAUDE.md. A rule can be path-scoped with YAML `paths:` frontmatter so it only loads when Claude reads a matching file, keeping context lean until it's relevant.

252 252 

253Learn more: [Organize rules with `.claude/rules/`](/en/memory#organize-rules-with-claude/rules/)253Learn more: [Organize rules with `.claude/rules/`](/docs/en/memory#organize-rules-with-claude/rules/)

254 254 

255## S255## S

256 256 


258 258 

259OS-level filesystem and network isolation for the Bash tool. Commands run inside a boundary you define upfront, so Claude can work freely within it without per-command approval prompts. Sandboxing is a separate layer from [permission rules](#permission-rule).259OS-level filesystem and network isolation for the Bash tool. Commands run inside a boundary you define upfront, so Claude can work freely within it without per-command approval prompts. Sandboxing is a separate layer from [permission rules](#permission-rule).

260 260 

261Learn more: [Sandboxing](/en/sandboxing)261Learn more: [Sandboxing](/docs/en/sandboxing)

262 262 

263### Session263### Session

264 264 

265A conversation tied to your current directory, with its own independent [context window](#context-window). Sessions can be resumed with `claude -c`, forked with `--fork-session` to preserve history under a new session ID, or run in parallel across terminals. Running `/clear` starts a new session; the previous one stays stored and is available via `/resume`. Each session's transcript is stored under `~/.claude/projects/`.265A conversation tied to your current directory, with its own independent [context window](#context-window). Sessions can be resumed with `claude -c`, forked with `--fork-session` to preserve history under a new session ID, or run in parallel across terminals. Running `/clear` starts a new session; the previous one stays stored and is available via `/resume`. Each session's transcript is stored under `~/.claude/projects/`.

266 266 

267Learn more: [Work with sessions](/en/how-claude-code-works#work-with-sessions)267Learn more: [Work with sessions](/docs/en/how-claude-code-works#work-with-sessions)

268 268 

269### Settings layers269### Settings layers

270 270 

271The hierarchy Claude Code reads configuration from, in precedence order from highest to lowest: [managed policy](#managed-settings), command-line arguments, local settings at `.claude/settings.local.json`, project settings at `.claude/settings.json`, then user settings at `~/.claude/settings.json`. Arrays merge across layers; scalars at a higher layer override lower ones.271The hierarchy Claude Code reads configuration from, in precedence order from highest to lowest: [managed policy](#managed-settings), command-line arguments, local settings at `.claude/settings.local.json`, project settings at `.claude/settings.json`, then user settings at `~/.claude/settings.json`. Arrays merge across layers; scalars at a higher layer override lower ones.

272 272 

273Learn more: [Settings files](/en/settings#settings-files)273Learn more: [Settings files](/docs/en/settings#settings-files)

274 274 

275### Skill275### Skill

276 276 


278 278 

279Skills are the recommended successor to custom commands. A file at `.claude/commands/deploy.md` and one at `.claude/skills/deploy/SKILL.md` both create `/deploy` and work the same way; existing command files continue to work.279Skills are the recommended successor to custom commands. A file at `.claude/commands/deploy.md` and one at `.claude/skills/deploy/SKILL.md` both create `/deploy` and work the same way; existing command files continue to work.

280 280 

281Learn more: [Extend Claude with skills](/en/skills)281Learn more: [Extend Claude with skills](/docs/en/skills)

282 282 

283### Subagent283### Subagent

284 284 


286 286 

287Built-in subagents include Explore, Plan, and general-purpose.287Built-in subagents include Explore, Plan, and general-purpose.

288 288 

289Learn more: [Create custom subagents](/en/sub-agents)289Learn more: [Create custom subagents](/docs/en/sub-agents)

290 290 

291### Surface291### Surface

292 292 

293Any place you access Claude Code: the CLI, VS Code, JetBrains, Desktop, or claude.ai. All surfaces share the same engine. Sessions on your machine read your local CLAUDE.md, settings, and skills; [cloud sessions](/en/claude-code-on-the-web#what’s-available-in-cloud-sessions) start from a fresh clone of your repository and don't read `~/.claude/` on your machine. Slack and the Chrome extension are integrations that connect to a surface rather than surfaces themselves.293Any place you access Claude Code: the CLI, VS Code, JetBrains, Desktop, or claude.ai. All surfaces share the same engine. Sessions on your machine read your local CLAUDE.md, settings, and skills; [cloud sessions](/docs/en/cloud-environments#what-carries-over-from-your-setup) start from a fresh clone of your repository and don't read `~/.claude/` on your machine. Slack and the Chrome extension are integrations that connect to a surface rather than surfaces themselves.

294 294 

295Learn more: [Platforms and integrations](/en/platforms)295Learn more: [Platforms and integrations](/docs/en/platforms)

296 296 

297## T297## T

298 298 


300 300 

301A command, `/teleport`, that pulls a cloud Claude Code session into your local terminal. Claude fetches the branch, loads the conversation history, and resumes from the web session's last state. The reverse direction is `--cloud`, which sends a local task to run on the web.301A command, `/teleport`, that pulls a cloud Claude Code session into your local terminal. Claude fetches the branch, loads the conversation history, and resumes from the web session's last state. The reverse direction is `--cloud`, which sends a local task to run on the web.

302 302 

303Learn more: [From web to terminal](/en/claude-code-on-the-web#from-web-to-terminal)303Learn more: [From web to terminal](/docs/en/claude-code-on-the-web#from-web-to-terminal)

304 304 

305### Tool305### Tool

306 306 

307An action Claude can take: read a file, edit code, run a shell command, search the web, spawn a subagent. Tools are what make Claude Code agentic. Without them, Claude can only respond with text. Each tool use returns a result that informs Claude's next decision in the [agentic loop](#agentic-loop).307An action Claude can take: read a file, edit code, run a shell command, search the web, spawn a subagent. Tools are what make Claude Code agentic. Without them, Claude can only respond with text. Each tool use returns a result that informs Claude's next decision in the [agentic loop](#agentic-loop).

308 308 

309Learn more: [Tools available to Claude](/en/tools-reference)309Learn more: [Tools available to Claude](/docs/en/tools-reference)

310 310 

311### Turn311### Turn

312 312 

313One complete response from Claude within a [session](#session). A turn begins when you send a message and ends when Claude finishes responding, with any number of [tool](#tool) calls in between. [Stop hooks](#hook) fire at the end of each turn. A session consists of many turns, and the [agentic loop](#agentic-loop) describes what happens inside one.313One complete response from Claude within a [session](#session). A turn begins when you send a message and ends when Claude finishes responding, with any number of [tool](#tool) calls in between. [Stop hooks](#hook) fire at the end of each turn. A session consists of many turns, and the [agentic loop](#agentic-loop) describes what happens inside one.

314 314 

315Learn more: [How Claude Code works](/en/how-claude-code-works#the-agentic-loop)315Learn more: [How Claude Code works](/docs/en/how-claude-code-works#the-agentic-loop)

316 316 

317## V317## V

318 318 

319### Verification loop319### Verification loop

320 320 

321How a session knows the work is actually done rather than just plausible. You give Claude a check it can run, such as a test suite, a build, or a screenshot comparison, and Claude iterates until the check passes instead of stopping after one attempt. A verification loop is the prerequisite for [`/goal`](/en/goal), unattended runs, and [dynamic workflows](/en/workflows): without one, the only thing deciding the agent is finished is the agent itself.321How a session knows the work is actually done rather than just plausible. You give Claude a check it can run, such as a test suite, a build, or a screenshot comparison, and Claude iterates until the check passes instead of stopping after one attempt. A verification loop is the prerequisite for [`/goal`](/docs/en/goal), unattended runs, and [dynamic workflows](/docs/en/workflows): without one, the only thing deciding the agent is finished is the agent itself.

322 322 

323Learn more: [Give Claude a way to verify its work](/en/best-practices#give-claude-a-way-to-verify-its-work)323Learn more: [Give Claude a way to verify its work](/docs/en/best-practices#give-claude-a-way-to-verify-its-work)

324 324 

325## W325## W

326 326 


328 328 

329An isolation mode that runs Claude in a separate git worktree under `.claude/worktrees/`, enabled with the `-w` flag or `isolation: worktree` in subagent config. Changes stay on a separate branch in a separate directory, so parallel agents don't overwrite each other's files.329An isolation mode that runs Claude in a separate git worktree under `.claude/worktrees/`, enabled with the `-w` flag or `isolation: worktree` in subagent config. Changes stay on a separate branch in a separate directory, so parallel agents don't overwrite each other's files.

330 330 

331Learn more: [Run parallel sessions with git worktrees](/en/worktrees)331Learn more: [Run parallel sessions with git worktrees](/docs/en/worktrees)

332 332 

333***333***

334 334 

goal.md +21 −12

Details

26| Approach | Next turn starts when | Stops when |26| Approach | Next turn starts when | Stops when |

27| :------------------------------------------------------------------ | :------------------------- | :---------------------------------------------- |27| :------------------------------------------------------------------ | :------------------------- | :---------------------------------------------- |

28| `/goal` | The previous turn finishes | A model confirms the condition is met |28| `/goal` | The previous turn finishes | A model confirms the condition is met |

29| [`/loop`](/en/scheduled-tasks#run-a-prompt-repeatedly-with-%2Floop) | A time interval elapses | You stop it, or Claude decides the work is done |29| [`/loop`](/docs/en/scheduled-tasks#run-a-prompt-repeatedly-with-%2Floop) | A time interval elapses | You stop it, or Claude decides the work is done |

30| [Stop hook](/en/hooks-guide#prompt-based-hooks) | The previous turn finishes | Your own script or prompt decides |30| [Stop hook](/docs/en/hooks-guide#prompt-based-hooks) | The previous turn finishes | Your own script or prompt decides |

31 31 

32`/goal` and a Stop hook both fire after every turn. `/goal` is a session-scoped shortcut: you type a condition and it's active for the current session only. A Stop hook lives in your settings file, applies to every session in its scope, and can run a script for deterministic checks or a prompt for model-evaluated ones.32`/goal` and a Stop hook both fire after every turn. `/goal` is a session-scoped shortcut: you type a condition and it's active for the current session only. A Stop hook lives in your settings file, applies to every session in its scope, and can run a script for deterministic checks or a prompt for model-evaluated ones.

33 33 

34[Auto mode](/en/auto-mode-config) on its own approves tool calls within a single turn but doesn't start a new one. Claude stops when it judges the work done. `/goal` adds a separate evaluator that checks your condition after every turn, so completion is decided by a fresh model rather than the one doing the work. The two are complementary: auto mode removes per-tool prompts, and `/goal` removes per-turn prompts.34[Auto mode](/docs/en/auto-mode-config) on its own approves tool calls within a single turn but doesn't start a new one. Claude stops when it judges the work done. `/goal` adds a separate evaluator that checks your condition after every turn, so completion is decided by a fresh model rather than the one doing the work. The two are complementary: auto mode removes per-tool prompts, and `/goal` removes per-turn prompts.

35 35 

36<Tip>36<Tip>

37 The approaches above keep the current session running. You can also schedule work that runs independent of any open session, such as nightly tests or morning triage. See [scheduling options](/en/scheduled-tasks#compare-scheduling-options) for cloud routines and desktop scheduled tasks.37 The approaches above keep the current session running. You can also schedule work that runs independent of any open session, such as nightly tests or morning triage. See [scheduling options](/docs/en/scheduled-tasks#compare-scheduling-options) for cloud routines and desktop scheduled tasks.

38</Tip>38</Tip>

39 39 

40## Use `/goal`40## Use `/goal`


51 51 

52Setting a goal starts a turn immediately, with the condition itself as the directive. You don't need to send a separate prompt. While the goal is active, a `◎ /goal active` indicator shows how long the goal has been running.52Setting a goal starts a turn immediately, with the condition itself as the directive. You don't need to send a separate prompt. While the goal is active, a `◎ /goal active` indicator shows how long the goal has been running.

53 53 

54A goal doesn't change permissions. In the default permission mode, Claude still asks before tool calls that your settings don't already allow, such as the test command above. To let goal turns run unattended, pair `/goal` with [auto mode](/en/auto-mode-config).54A goal doesn't change permissions. In the default permission mode, Claude still asks before tool calls that your settings don't already allow, such as the test command above. To let goal turns run unattended, pair `/goal` with [auto mode](/docs/en/auto-mode-config).

55 55 

56After each turn, the evaluator returns a short reason explaining why the condition is or isn't met. The most recent reason appears in the status view and in the transcript so you can see what Claude is working toward next.56After each turn, the evaluator returns a short reason explaining why the condition is or isn't met. The most recent reason appears in the status view and in the transcript so you can see what Claude is working toward next.

57 57 


111 111 

112### Run non-interactively112### Run non-interactively

113 113 

114`/goal` works in [non-interactive mode](/en/headless), in the [desktop app](/en/desktop), and through [Remote Control](/en/remote-control). Setting a goal with `-p` runs the loop to completion in a single invocation:114`/goal` works in [non-interactive mode](/docs/en/headless), in the [desktop app](/docs/en/desktop), and through [Remote Control](/docs/en/remote-control). Setting a goal with `-p` runs the loop to completion in a single invocation:

115 115 

116```bash theme={null}116```bash theme={null}

117claude -p "/goal CHANGELOG.md has an entry for every PR merged this week"117claude -p "/goal CHANGELOG.md has an entry for every PR merged this week"


123 123 

124## How evaluation works124## How evaluation works

125 125 

126`/goal` is a wrapper around a session-scoped [prompt-based Stop hook](/en/hooks#prompt-based-hooks). Each time Claude finishes a turn, the condition and the conversation so far are sent to your configured [small fast model](/en/model-config), which defaults to Haiku. The model returns a yes-or-no decision and a short reason. A "no" tells Claude to keep working and includes the reason as guidance for the next turn. A "yes" clears the goal and records an achieved entry in the transcript.126`/goal` is a wrapper around a session-scoped [prompt-based Stop hook](/docs/en/hooks#prompt-based-hooks). Each time Claude finishes a turn, the condition and the conversation so far are sent to your configured [small fast model](/docs/en/model-config), which defaults to Haiku on the Claude API; on a third-party provider, check your [provider page](/docs/en/third-party-integrations) for the platform's default. The model answers yes or no and gives a short reason.

127 

128* **No**: Claude keeps working and takes the reason as guidance for the next turn.

129* **Yes**: Claude Code clears the goal and records an achieved entry in the transcript.

130 

131To evaluate on a different model, set [`ANTHROPIC_DEFAULT_HAIKU_MODEL`](/docs/en/model-config#environment-variables).

132 

133<Warning>

134 Claude Code reads `ANTHROPIC_DEFAULT_HAIKU_MODEL` everywhere it uses the small fast model, not only for `/goal` evaluation. When you set it, Claude Code also resolves the [`haiku` alias](/docs/en/model-config#model-aliases) to that model and runs [background functionality](/docs/en/costs#background-token-usage), such as conversation summarization, on it.

135</Warning>

127 136 

128The evaluator runs on whichever provider your session is configured for. It does not call tools, so it can only judge what Claude has already surfaced in the conversation.137The evaluator runs on whichever provider your session is configured for. It does not call tools, so it can only judge what Claude has already surfaced in the conversation.

129 138 


133 142 

134## Requirements143## Requirements

135 144 

136`/goal` runs only in workspaces where you have accepted the trust dialog, because the evaluator is part of the hooks system. `/goal` is also unavailable when [`disableAllHooks`](/en/hooks#disable-or-remove-hooks) is set at any settings level or when [`allowManagedHooksOnly`](/en/settings#hook-configuration) is set in managed settings. In each case, the command tells you why instead of silently doing nothing.145`/goal` runs only in workspaces where you have accepted the trust dialog, because the evaluator is part of the hooks system. `/goal` is also unavailable when [`disableAllHooks`](/docs/en/hooks#disable-or-remove-hooks) is set at any settings level or when [`allowManagedHooksOnly`](/docs/en/settings#hook-configuration) is set in managed settings. In each case, the command tells you why instead of silently doing nothing.

137 146 

138## See also147## See also

139 148 

140* [Run a prompt repeatedly with `/loop`](/en/scheduled-tasks#run-a-prompt-repeatedly-with-%2Floop): re-run on a time interval instead of until a condition holds149* [Run a prompt repeatedly with `/loop`](/docs/en/scheduled-tasks#run-a-prompt-repeatedly-with-%2Floop): re-run on a time interval instead of until a condition holds

141* [Prompt-based hooks](/en/hooks-guide#prompt-based-hooks): write your own Stop hook when you need custom evaluation logic150* [Prompt-based hooks](/docs/en/hooks-guide#prompt-based-hooks): write your own Stop hook when you need custom evaluation logic

142* [Auto mode](/en/auto-mode-config): approve tool calls automatically so each goal turn runs unattended151* [Auto mode](/docs/en/auto-mode-config): approve tool calls automatically so each goal turn runs unattended

143* [Scheduling comparison](/en/scheduled-tasks#compare-scheduling-options): run work on a schedule independent of any open session152* [Scheduling comparison](/docs/en/scheduled-tasks#compare-scheduling-options): run work on a schedule independent of any open session

hooks.md +22 −15

Details

37| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |37| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |

38| `UserPromptExpansion` | When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion |38| `UserPromptExpansion` | When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion |

39| `PreToolUse` | Before a tool call executes. Can block it |39| `PreToolUse` | Before a tool call executes. Can block it |

40| `PermissionRequest` | When a permission dialog appears |40| `PermissionRequest` | When a tool call needs a permission decision |

41| `PermissionDenied` | When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call |41| `PermissionDenied` | When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call |

42| `PostToolUse` | After a tool call succeeds |42| `PostToolUse` | After a tool call succeeds |

43| `PostToolUseFailure` | After a tool call fails |43| `PostToolUseFailure` | After a tool call fails |


87}87}

88```88```

89 89 

90The script reads the JSON input from stdin, extracts the command, and returns a `permissionDecision` of `"deny"` if it contains `rm -rf`:90The script reads the JSON input from stdin, extracts the command, and returns a `permissionDecision` of `"deny"` if it contains `rm -rf`. Save it to `.claude/hooks/block-rm.sh` in your project:

91 91 

92```bash theme={null}92```bash theme={null}

93#!/bin/bash93#!/bin/bash


107fi107fi

108```108```

109 109 

110On macOS and Linux, make the script executable with `chmod +x .claude/hooks/block-rm.sh` so Claude Code can run it. On Windows, write the hook in PowerShell instead and register it with `"command": "powershell.exe"`, as shown in the [MessageDisplay example](#messagedisplay).

111 

110This script and the Bash examples on this page that parse JSON input use `jq`, so install `jq` and make sure it is on your `PATH` before trying them.112This script and the Bash examples on this page that parse JSON input use `jq`, so install `jq` and make sure it is on your `PATH` before trying them.

111 113 

112Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here's what happens:114Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here's what happens:


174Where you define a hook determines its scope:176Where you define a hook determines its scope:

175 177 

176| Location | Scope | Shareable |178| Location | Scope | Shareable |

177| :--------------------------------------------------------- | :---------------------------- | :----------------------------------------- |179| :--------------------------------------------------------- | :---------------------------- | :---------------------------------------------------- |

178| `~/.claude/settings.json` | All your projects | No, local to your machine |180| `~/.claude/settings.json` | All your projects | No, local to your machine |

179| `.claude/settings.json` | Single project | Yes, can be committed to the repo |181| `.claude/settings.json` | Single project | Yes, can be committed to the repo |

180| `.claude/settings.local.json` | Single project | No, gitignored when Claude Code creates it |182| `.claude/settings.local.json` | Single project | No, gitignored when Claude Code saves a setting to it |

181| Managed policy settings | Organization-wide | Yes, admin-controlled |183| Managed policy settings | Organization-wide | Yes, admin-controlled |

182| [Plugin](/docs/en/plugins) `hooks/hooks.json` | When plugin is enabled | Yes, bundled with the plugin |184| [Plugin](/docs/en/plugins) `hooks/hooks.json` | When plugin is enabled | Yes, bundled with the plugin |

183| [Skill](/docs/en/skills) or [agent](/docs/en/sub-agents) frontmatter | While the component is active | Yes, defined in the component file |185| [Skill](/docs/en/skills) or [agent](/docs/en/sub-agents) frontmatter | While the component is active | Yes, defined in the component file |


334| :-------------- | :------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |336| :-------------- | :------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

335| `type` | yes | `"command"`, `"http"`, `"mcp_tool"`, `"prompt"`, or `"agent"` |337| `type` | yes | `"command"`, `"http"`, `"mcp_tool"`, `"prompt"`, or `"agent"` |

336| `if` | no | Permission rule syntax to filter when this hook runs, such as `"Bash(git *)"` or `"Edit(*.ts)"`. The hook command only runs if the tool call matches the pattern. See the [Bash matching table](#bash-if-matching) below for how Bash patterns evaluate against subcommands, `$()`, and backticks. Only evaluated on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. On other events, a hook with `if` set never runs. Uses the same syntax as [permission rules](/docs/en/permissions) |338| `if` | no | Permission rule syntax to filter when this hook runs, such as `"Bash(git *)"` or `"Edit(*.ts)"`. The hook command only runs if the tool call matches the pattern. See the [Bash matching table](#bash-if-matching) below for how Bash patterns evaluate against subcommands, `$()`, and backticks. Only evaluated on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. On other events, a hook with `if` set never runs. Uses the same syntax as [permission rules](/docs/en/permissions) |

337| `timeout` | no | Seconds before canceling. Defaults: 600 for `command`, `http`, and `mcp_tool`; 30 for `prompt`; 60 for `agent`. [`UserPromptSubmit`](#userpromptsubmit) lowers the `command`, `http`, and `mcp_tool` default to 30, and [`MessageDisplay`](#messagedisplay) lowers it to 10 |339| `timeout` | no | Seconds before canceling. Defaults: 600 for `command`, `http`, and `mcp_tool`; 30 for `prompt`; 60 for `agent`. [`UserPromptSubmit`](#userpromptsubmit) lowers the `command`, `http`, and `mcp_tool` default to 30, and [`MessageDisplay`](#messagedisplay) lowers it to 10. [`SessionEnd`](#sessionend) hooks share a 1.5-second budget; if your settings set a longer per-hook `timeout`, Claude Code raises the budget to match, up to 60 seconds |

338| `statusMessage` | no | Custom spinner message displayed while the hook runs |340| `statusMessage` | no | Custom spinner message displayed while the hook runs |

339| `once` | no | If `true`, runs once per session then is removed. Only honored for hooks declared in [skill frontmatter](#hooks-in-skills-and-agents); ignored in settings files and agent frontmatter |341| `once` | no | If `true`, runs once per session then is removed. Only honored for hooks declared in [skill frontmatter](#hooks-in-skills-and-agents); ignored in settings files and agent frontmatter |

340 342 


590 592 

591The menu displays all five hook types: `command`, `prompt`, `agent`, `http`, and `mcp_tool`. Each hook is labeled with a `[type]` prefix and a source indicating where it was defined:593The menu displays all five hook types: `command`, `prompt`, `agent`, `http`, and `mcp_tool`. Each hook is labeled with a `[type]` prefix and a source indicating where it was defined:

592 594 

593* `User`: from `~/.claude/settings.json`595* `User Settings`: from `~/.claude/settings.json`

594* `Project`: from `.claude/settings.json`596* `Project Settings`: from `.claude/settings.json`

595* `Local`: from `.claude/settings.local.json`597* `Local Settings`: from `.claude/settings.local.json`

596* `Plugin`: from a plugin's `hooks/hooks.json`598* `Plugin Hooks`: from a plugin's `hooks/hooks.json`

597* `Session`: registered in memory for the current session599* `Session Hooks`: registered in memory for the current session

598* `Built-in`: registered internally by Claude Code600* `Built-in Hooks`: registered internally by Claude Code

599 601 

600Selecting a hook opens a detail view showing its event, matcher, type, source file, and the full command, prompt, or URL. The menu is read-only: to add, modify, or remove hooks, edit the settings JSON directly or ask Claude to make the change.602Selecting a hook opens a detail view showing its event, matcher, type, source file, and the full command, prompt, or URL. The menu is read-only: to add, modify, or remove hooks, edit the settings JSON directly or ask Claude to make the change.

601 603 


678```bash theme={null}680```bash theme={null}

679#!/bin/bash681#!/bin/bash

680# Reads JSON input from stdin, checks the command682# Reads JSON input from stdin, checks the command

681command=$(jq -r '.tool_input.command' < /dev/stdin)683input=$(cat)

684command=$(jq -r '.tool_input.command' <<<"$input")

682 685 

683if [[ "$command" == rm* ]]; then686if [[ "$command" == rm* ]]; then

684 echo "Blocked: rm commands are not allowed" >&2687 echo "Blocked: rm commands are not allowed" >&2


1060| `init` | `claude --init-only` or `claude -p --init` |1063| `init` | `claude --init-only` or `claude -p --init` |

1061| `maintenance` | `claude -p --maintenance` |1064| `maintenance` | `claude -p --maintenance` |

1062 1065 

1063`--init-only` runs Setup hooks and `SessionStart` hooks with the `startup` matcher, then exits without starting a conversation. `--init` and `--maintenance` fire Setup hooks only when combined with `-p`; in an interactive session those two flags don't currently fire Setup hooks.1066When you run `claude --init-only`, Claude Code runs Setup hooks and `SessionStart` hooks with the `startup` matcher, then exits without starting a conversation.

1067 

1068`--init` and `--maintenance` fire Setup hooks only when you combine them with `-p`. In an interactive session, those two flags don't currently fire Setup hooks.

1069 

1070When you start or continue a conversation with `-p`, you also need to supply a prompt, as an argument or piped on stdin. You can skip the prompt when a `SessionStart` hook supplies [`initialUserMessage`](#sessionstart-decision-control) or when you resume a session with a [deferred tool call](#defer-a-tool-call-for-later).

1064 1071 

1065On success, `--init-only` prints nothing to the terminal. To confirm the hooks ran, start with `claude --debug-file <path> --init-only`, replacing `<path>` with a log file location, and check the log for the Setup and SessionStart hook entries.1072On success, `--init-only` prints nothing to the terminal. To confirm the hooks ran, start with `claude --debug-file <path> --init-only`, replacing `<path>` with a log file location, and check the log for the Setup and SessionStart hook entries.

1066 1073 


1611 1618 

1612### PermissionRequest1619### PermissionRequest

1613 1620 

1614Runs when the user is shown a permission dialog.1621Runs when Claude Code is about to ask you for permission. In sessions that can't show a prompt, such as background subagents in [non-interactive mode](/docs/en/headless), Claude Code still runs these hooks, and if no hook returns a decision, it denies the tool call.

1615Use [PermissionRequest decision control](#permissionrequest-decision-control) to allow or deny on behalf of the user.1622Use [PermissionRequest decision control](#permissionrequest-decision-control) to allow or deny on behalf of the user.

1616 1623 

1617Matches on tool name, same values as PreToolUse.1624Matches on tool name, same values as PreToolUse.


1620 1627 

1621PermissionRequest hooks receive `tool_name` and `tool_input` fields like PreToolUse hooks, but without `tool_use_id`. An optional `permission_suggestions` array contains the "always allow" options the user would normally see in the permission dialog.1628PermissionRequest hooks receive `tool_name` and `tool_input` fields like PreToolUse hooks, but without `tool_use_id`. An optional `permission_suggestions` array contains the "always allow" options the user would normally see in the permission dialog.

1622 1629 

1623The difference from PreToolUse is when the hook fires: PermissionRequest hooks run when a permission dialog is about to be shown to the user, while PreToolUse hooks run before tool execution regardless of permission status. Neither event fires for [`EndConversation`](/docs/en/tools-reference#endconversation-tool-behavior).1630PreToolUse hooks run before every tool call, whether or not it needs permission. PermissionRequest hooks run only when Claude Code is about to ask you for permission, or when it would otherwise auto-deny a call that can't prompt. Neither event fires for [`EndConversation`](/docs/en/tools-reference#endconversation-tool-behavior).

1624 1631 

1625```json theme={null}1632```json theme={null}

1626{1633{

hooks-guide.md +17 −6

Details

206}206}

207```207```

208 208 

209To test the hook, ask Claude to add a line with single-quoted strings to a JavaScript file, then open the file: with Prettier's default settings, the hook rewrites them to double quotes.

210 

209On Claude Code v2.1.191 or later you can also write the matcher as `Edit,Write`, since `|` and `,` are interchangeable list separators for tool-name matchers on those versions.211On Claude Code v2.1.191 or later you can also write the matcher as `Edit,Write`, since `|` and `,` are interchangeable list separators for tool-name matchers on those versions.

210 212 

211<Note>213<Note>


271 }273 }

272 ```274 ```

273 </Step>275 </Step>

276 

277 <Step title="Test the hook">

278 Ask Claude to add a comment to your `.env` file. Claude Code blocks the edit before it runs and passes the script's `Blocked:` message to Claude as feedback.

279 </Step>

274</Steps>280</Steps>

275 281 

276### Re-inject context after compaction282### Re-inject context after compaction


325 331 

326The matcher filters by configuration type: `user_settings`, `project_settings`, `local_settings`, `policy_settings`, or `skills`. To block a change from taking effect, exit with code 2 or return `{"decision": "block"}`. See the [ConfigChange reference](/docs/en/hooks#configchange) for the full input schema.332The matcher filters by configuration type: `user_settings`, `project_settings`, `local_settings`, `policy_settings`, or `skills`. To block a change from taking effect, exit with code 2 or return `{"decision": "block"}`. See the [ConfigChange reference](/docs/en/hooks#configchange) for the full input schema.

327 333 

334To confirm the hook records changes, edit a settings file in another editor while a session is running, then open `~/claude-config-audit.log`: the hook appends one JSON line per change with the timestamp, source, and file path.

335 

328### Reload environment when directory or files change336### Reload environment when directory or files change

329 337 

330Some projects set different environment variables depending on which directory you are in. Tools like [direnv](https://direnv.net/) do this automatically in your shell, but Claude's Bash tool doesn't pick up those changes on its own.338Some projects set different environment variables depending on which directory you are in. Tools like [direnv](https://direnv.net/) do this automatically in your shell, but Claude's Bash tool doesn't pick up those changes on its own.


386 394 

387Skip the approval dialog for tool calls you always allow. This example auto-approves `ExitPlanMode`, the tool Claude calls when it finishes presenting a plan and asks to proceed, so you aren't prompted every time a plan is ready.395Skip the approval dialog for tool calls you always allow. This example auto-approves `ExitPlanMode`, the tool Claude calls when it finishes presenting a plan and asks to proceed, so you aren't prompted every time a plan is ready.

388 396 

389Unlike the exit-code examples above, auto-approval requires your hook to write a JSON decision to stdout. A `PermissionRequest` hook fires when Claude Code is about to show a permission dialog, and returning `"behavior": "allow"` answers it on your behalf.397Unlike the exit-code examples above, auto-approval requires your hook to write a JSON decision to stdout. A `PermissionRequest` hook fires when Claude Code is about to ask you for permission, and returning `"behavior": "allow"` answers the request on your behalf.

390 398 

391The matcher scopes the hook to `ExitPlanMode` only, so no other prompts are affected. Add this to `~/.claude/settings.json`:399The matcher scopes the hook to `ExitPlanMode` only, so no other prompts are affected. Add this to `~/.claude/settings.json`:

392 400 


445| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |453| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |

446| `UserPromptExpansion` | When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion |454| `UserPromptExpansion` | When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion |

447| `PreToolUse` | Before a tool call executes. Can block it |455| `PreToolUse` | Before a tool call executes. Can block it |

448| `PermissionRequest` | When a permission dialog appears |456| `PermissionRequest` | When a tool call needs a permission decision |

449| `PermissionDenied` | When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call |457| `PermissionDenied` | When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call |

450| `PostToolUse` | After a tool call succeeds |458| `PostToolUse` | After a tool call succeeds |

451| `PostToolUseFailure` | After a tool call fails |459| `PostToolUseFailure` | After a tool call fails |


768Where you add a hook determines its scope:776Where you add a hook determines its scope:

769 777 

770| Location | Scope | Shareable |778| Location | Scope | Shareable |

771| :--------------------------------------------------------- | :--------------------------------- | :----------------------------------------- |779| :--------------------------------------------------------- | :--------------------------------- | :---------------------------------------------------- |

772| `~/.claude/settings.json` | All your projects | No, local to your machine |780| `~/.claude/settings.json` | All your projects | No, local to your machine |

773| `.claude/settings.json` | Single project | Yes, can be committed to the repo |781| `.claude/settings.json` | Single project | Yes, can be committed to the repo |

774| `.claude/settings.local.json` | Single project | No, gitignored when Claude Code creates it |782| `.claude/settings.local.json` | Single project | No, gitignored when Claude Code saves a setting to it |

775| Managed policy settings | Organization-wide | Yes, admin-controlled |783| Managed policy settings | Organization-wide | Yes, admin-controlled |

776| [Plugin](/docs/en/plugins) `hooks/hooks.json` | When plugin is enabled | Yes, bundled with the plugin |784| [Plugin](/docs/en/plugins) `hooks/hooks.json` | When plugin is enabled | Yes, bundled with the plugin |

777| [Skill](/docs/en/skills) or [agent](/docs/en/sub-agents) frontmatter | While the skill or agent is active | Yes, defined in the component file |785| [Skill](/docs/en/skills) or [agent](/docs/en/sub-agents) frontmatter | While the skill or agent is active | Yes, defined in the component file |


896 * `command`, `http`, `mcp_tool`: 10 minutes. `UserPromptSubmit` lowers these to 30 seconds, and `MessageDisplay` lowers them to 10 seconds.904 * `command`, `http`, `mcp_tool`: 10 minutes. `UserPromptSubmit` lowers these to 30 seconds, and `MessageDisplay` lowers them to 10 seconds.

897 * `prompt`: 30 seconds.905 * `prompt`: 30 seconds.

898 * `agent`: 60 seconds.906 * `agent`: 60 seconds.

907 * [`SessionEnd`](/docs/en/hooks#sessionend) hooks of any type share a 1.5-second budget. If your settings set a longer per-hook `timeout`, Claude Code raises the budget to match, up to 60 seconds.

899* `PostToolUse` hooks can't undo actions since the tool has already executed.908* `PostToolUse` hooks can't undo actions since the tool has already executed.

900* `PermissionRequest` hooks don't fire in [non-interactive mode](/docs/en/headless) with the `-p` flag. Use `PreToolUse` hooks for automated permission decisions.909* `PermissionRequest` hooks fire when Claude Code is about to ask you for permission.

910 * In [non-interactive mode](/docs/en/headless) with the `-p` flag, that prompt only exists when the Agent SDK's [`canUseTool` callback](/docs/en/agent-sdk/permissions) supplies it. In plain `-p` runs or with `--permission-prompt-tool`, use `PreToolUse` hooks for automated permission decisions instead.

911 * Background subagents can't show a prompt in non-interactive mode. Claude Code still runs the hooks for their tool calls, and if no hook returns a decision, it denies the call. In an interactive session, background subagent prompts surface in your main session and the hooks fire as usual.

901* `Stop` hooks fire whenever Claude finishes responding, not only at task completion. They don't fire on user interrupts. API errors fire [StopFailure](/docs/en/hooks#stopfailure) instead.912* `Stop` hooks fire whenever Claude finishes responding, not only at task completion. They don't fire on user interrupts. API errors fire [StopFailure](/docs/en/hooks#stopfailure) instead.

902* When multiple `PreToolUse` hooks return [`updatedInput`](/docs/en/hooks#pretooluse) to rewrite a tool's arguments, the last one to finish takes effect. Since hooks run in parallel, the order is non-deterministic. Avoid having more than one hook modify the same tool's input.913* When multiple `PreToolUse` hooks return [`updatedInput`](/docs/en/hooks#pretooluse) to rewrite a tool's arguments, the last one to finish takes effect. Since hooks run in parallel, the order is non-deterministic. Avoid having more than one hook modify the same tool's input.

903 914 


914* Run `/hooks` and confirm the hook appears under the correct event925* Run `/hooks` and confirm the hook appears under the correct event

915* Check that the matcher pattern matches the tool name exactly. Matchers are case-sensitive926* Check that the matcher pattern matches the tool name exactly. Matchers are case-sensitive

916* Verify you're triggering the right event type: `PreToolUse` fires before tool execution, `PostToolUse` fires after927* Verify you're triggering the right event type: `PreToolUse` fires before tool execution, `PostToolUse` fires after

917* If using `PermissionRequest` hooks in non-interactive mode with the `-p` flag, switch to `PreToolUse` instead928* In non-interactive mode with the `-p` flag, `PermissionRequest` hooks fire only when the Agent SDK's `canUseTool` callback supplies the prompt, or for tool calls inside background subagents. In plain `-p` runs or with `--permission-prompt-tool`, use `PreToolUse` hooks instead

918 929 

919### Hook error in output930### Hook error in output

920 931 

large-codebases.md +34 −34

Details

30| Replace many per-directory CLAUDE.md files with one set of conventions everyone installs | A [plugin](#centralize-conventions-when-layering-stops-scaling) in an internal marketplace |30| Replace many per-directory CLAUDE.md files with one set of conventions everyone installs | A [plugin](#centralize-conventions-when-layering-stops-scaling) in an internal marketplace |

31 31 

32<Tip>32<Tip>

33 For workflow techniques that keep context small in any repository, such as [running exploration in a subagent](/en/best-practices#use-subagents-for-investigation) so file reads stay out of the main conversation, see [Best practices for Claude Code](/en/best-practices). To roll out a baseline configuration to every developer in your organization, see [Set up Claude Code for your organization](/en/admin-setup).33 For workflow techniques that keep context small in any repository, such as [running exploration in a subagent](/docs/en/best-practices#use-subagents-for-investigation) so file reads stay out of the main conversation, see [Best practices for Claude Code](/docs/en/best-practices). To roll out a baseline configuration to every developer in your organization, see [Set up Claude Code for your organization](/docs/en/admin-setup).

34</Tip>34</Tip>

35 35 

36### The example monorepo36### The example monorepo


71 71 

72In a large codebase, a single CLAUDE.md at the repository root tends to either grow to cover every subsystem's conventions, costing context on instructions unrelated to the current task, or stay too generic to be useful. Splitting instructions across per-directory files means Claude loads repository-wide rules plus only the conventions for the code you're working in.72In a large codebase, a single CLAUDE.md at the repository root tends to either grow to cover every subsystem's conventions, costing context on instructions unrelated to the current task, or stay too generic to be useful. Splitting instructions across per-directory files means Claude loads repository-wide rules plus only the conventions for the code you're working in.

73 73 

74Claude Code loads every [CLAUDE.md](/en/memory) file from your working directory and every parent directory at launch, then loads each subdirectory's file on demand when it reads files there. A root file sets repository-wide rules and each subdirectory adds its own.74Claude Code loads every [CLAUDE.md](/docs/en/memory) file from your working directory and every parent directory at launch, then loads each subdirectory's file on demand when it reads files there. A root file sets repository-wide rules and each subdirectory adds its own.

75 75 

76A common split is two levels:76A common split is two levels:

77 77 


113 113 

114* **Review in pull requests**: treat CLAUDE.md edits like any other documentation change so conventions track the code114* **Review in pull requests**: treat CLAUDE.md edits like any other documentation change so conventions track the code

115* **Revisit after major model releases**: instructions that worked around an older model's limitation may become overhead once a newer model handles the case on its own. For example, a rule that forces single-file refactors can be deleted once the limitation is gone115* **Revisit after major model releases**: instructions that worked around an older model's limitation may become overhead once a newer model handles the case on its own. For example, a rule that forces single-file refactors can be deleted once the limitation is gone

116* **Add a Stop hook that proposes updates**: a [`Stop` hook](/en/hooks#stop) receives the path to the session transcript when Claude finishes responding, so a script can review the session and propose CLAUDE.md updates while the gap it exposed is fresh116* **Add a Stop hook that proposes updates**: a [`Stop` hook](/docs/en/hooks#stop) receives the path to the session transcript when Claude finishes responding, so a script can review the session and propose CLAUDE.md updates while the gap it exposed is fresh

117 117 

118For more on how CLAUDE.md files load and interact, see [Memory and project instructions](/en/memory).118For more on how CLAUDE.md files load and interact, see [Memory and project instructions](/docs/en/memory).

119 119 

120### Choose between per-directory CLAUDE.md and path-scoped rules120### Choose between per-directory CLAUDE.md and path-scoped rules

121 121 

122Per-directory `CLAUDE.md` files and [path-scoped rules](/en/memory#path-specific-rules) under `.claude/rules/` both let you target instructions to part of the tree. They differ in where the file lives and when it loads.122Per-directory `CLAUDE.md` files and [path-scoped rules](/docs/en/memory#path-specific-rules) under `.claude/rules/` both let you target instructions to part of the tree. They differ in where the file lives and when it loads.

123 123 

124| Approach | File location | Loads when | Use when |124| Approach | File location | Loads when | Use when |

125| :----------------------------------- | :--------------------------------------- | :-------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------- |125| :----------------------------------- | :--------------------------------------- | :-------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------- |

126| Per-directory `CLAUDE.md` | Inside the directory, alongside its code | At launch when started from that directory, or on demand when Claude reads a file there | Directory owners maintain their own conventions; instructions are versioned with the code |126| Per-directory `CLAUDE.md` | Inside the directory, alongside its code | At launch when started from that directory, or on demand when Claude reads a file there | Directory owners maintain their own conventions; instructions are versioned with the code |

127| Path-scoped rule in `.claude/rules/` | Central `.claude/` at the repo root | When Claude works with a file matching the rule's `paths:` glob | You want all conventions in one place, or the same rule applies to many scattered paths |127| Path-scoped rule in `.claude/rules/` | Central `.claude/` at the repo root | When Claude works with a file matching the rule's `paths:` glob | You want all conventions in one place, or the same rule applies to many scattered paths |

128 128 

129For a comparison that also covers skills, see [Compare similar features](/en/features-overview#compare-similar-features).129For a comparison that also covers skills, see [Compare similar features](/docs/en/features-overview#compare-similar-features).

130 130 

131### Exclude irrelevant CLAUDE.md files131### Exclude irrelevant CLAUDE.md files

132 132 


134 134 

135Use this for directories you never work in, such as other teams' packages, legacy code, or vendored subtrees. The exclusion list is static, not a per-task switch. To focus on one package today and another tomorrow, [start Claude from that package's directory](#choose-where-to-start-claude) instead of editing exclusions.135Use this for directories you never work in, such as other teams' packages, legacy code, or vendored subtrees. The exclusion list is static, not a per-task switch. To focus on one package today and another tomorrow, [start Claude from that package's directory](#choose-where-to-start-claude) instead of editing exclusions.

136 136 

137If you only want these exclusions for yourself, put the setting in `.claude/settings.local.json`. Claude Code gitignores that file when it creates it; since you're creating it by hand here, add it to your gitignore. Patterns use glob syntax matched against absolute file paths, so start relative-style patterns with `**/` to match anywhere in the tree. The example below excludes a package owned by another team:137If you only want these exclusions for yourself, put the setting in `.claude/settings.local.json`. Claude Code adds that file to your global gitignore when it saves a setting there. Since you are creating it by hand here, add it to your gitignore yourself. Patterns use glob syntax matched against absolute file paths, so start relative-style patterns with `**/` to match anywhere in the tree. The example below excludes a package owned by another team:

138 138 

139```json .claude/settings.local.json theme={null}139```json .claude/settings.local.json theme={null}

140{140{


152* `"**/packages/legacy-*/**"`: excludes every package whose name matches the glob, including rules152* `"**/packages/legacy-*/**"`: excludes every package whose name matches the glob, including rules

153* `"/home/user/monorepo/legacy/CLAUDE.md"`: excludes one specific file by absolute path153* `"/home/user/monorepo/legacy/CLAUDE.md"`: excludes one specific file by absolute path

154 154 

155Managed policy CLAUDE.md files cannot be excluded, so organization-wide instructions always apply. You can set `claudeMdExcludes` at any [settings scope](/en/settings#configuration-scopes): user, project, local, or managed. Arrays merge across scopes, so a team can set project-level defaults while individuals add local overrides.155Managed policy CLAUDE.md files cannot be excluded, so organization-wide instructions always apply. You can set `claudeMdExcludes` at any [settings scope](/docs/en/settings#configuration-scopes): user, project, local, or managed. Arrays merge across scopes, so a team can set project-level defaults while individuals add local overrides.

156 156 

157For the full exclusion documentation, see [Exclude specific CLAUDE.md files](/en/memory#exclude-specific-claude-md-files).157For the full exclusion documentation, see [Exclude specific CLAUDE.md files](/docs/en/memory#exclude-specific-claude-md-files).

158 158 

159## Reduce what Claude reads159## Reduce what Claude reads

160 160 


169The deny rules can cover everyone working in the repository, only you, or every session on the machine, depending on which settings file you put them in:169The deny rules can cover everyone working in the repository, only you, or every session on the machine, depending on which settings file you put them in:

170 170 

171* **Everyone working in the repository**: commit the rules to `.claude/settings.json`. Like other project settings on this page, that file loads only from your starting directory, so place it at the repository root if you start Claude there, or in each package's `.claude/` if you start from subdirectories.171* **Everyone working in the repository**: commit the rules to `.claude/settings.json`. Like other project settings on this page, that file loads only from your starting directory, so place it at the repository root if you start Claude there, or in each package's `.claude/` if you start from subdirectories.

172* **Yourself only**: use `.claude/settings.local.json` at the repository root, which loads in every CLI session inside the repository regardless of starting directory. Relative patterns like the example's `Read(./vendor/**)` still [anchor at the directory you start Claude Code from](/en/permissions#read-and-edit), so if you start sessions from subdirectories, write the rules in this file as `//`-absolute paths, such as `Read(//absolute/path/to/repo/vendor/**)`. {/* min-version: 2.1.211 */}Before v2.1.211, `.claude/settings.local.json` also loaded only from the starting directory.172* **Yourself only**: use `.claude/settings.local.json` at the repository root, which loads in every CLI session inside the repository regardless of starting directory. Relative patterns like the example's `Read(./vendor/**)` still [anchor at the directory you start Claude Code from](/docs/en/permissions#read-and-edit), so if you start sessions from subdirectories, write the rules in this file as `//`-absolute paths, such as `Read(//absolute/path/to/repo/vendor/**)`. {/* min-version: 2.1.211 */}Before v2.1.211, `.claude/settings.local.json` also loaded only from the starting directory.

173* **Everyone, enforced in every session**: set the rules in [managed settings](/en/settings#settings-files), which user and project settings cannot override.173* **Everyone, enforced in every session**: set the rules in [managed settings](/docs/en/settings#settings-files), which user and project settings cannot override.

174 174 

175The example below blocks build artifacts and a vendored SDK:175The example below blocks build artifacts and a vendored SDK:

176 176 


187}187}

188```188```

189 189 

190Deny rules cover Claude's built-in file tools and recognized Bash file commands, including `cat`, `head`, `grep`, and `find`, when a denied path is passed as an argument. They do not filter denied paths out of a recursive search's output, and they do not cover arbitrary subprocesses that open files themselves. For the full pattern syntax, see [Read and Edit permission rules](/en/permissions#read-and-edit).190Deny rules cover Claude's built-in file tools and recognized Bash file commands, including `cat`, `head`, `grep`, and `find`, when a denied path is passed as an argument. They do not filter denied paths out of a recursive search's output, and they do not cover arbitrary subprocesses that open files themselves. For the full pattern syntax, see [Read and Edit permission rules](/docs/en/permissions#read-and-edit).

191 191 

192### Reduce file reads with code intelligence192### Reduce file reads with code intelligence

193 193 

194In a large codebase, finding where a symbol is defined or used can cost many file reads and grep calls. [Code intelligence plugins](/en/discover-plugins#code-intelligence) connect Claude to a language server so it can jump to definitions, find references, and surface type errors directly instead of scanning the tree.194In a large codebase, finding where a symbol is defined or used can cost many file reads and grep calls. [Code intelligence plugins](/docs/en/discover-plugins#code-intelligence) connect Claude to a language server so it can jump to definitions, find references, and surface type errors directly instead of scanning the tree.

195 195 

196The official marketplace has plugins for TypeScript, Python, Go, Rust, and other common languages. Run the command below inside a Claude Code session to install the TypeScript plugin:196The official marketplace has plugins for TypeScript, Python, Go, Rust, and other common languages. Run the command below inside a Claude Code session to install the TypeScript plugin:

197 197 


201 201 

202If Claude Code reports `Marketplace "claude-plugins-official" not found`, add the marketplace with `/plugin marketplace add anthropics/claude-plugins-official`. If it reports that the plugin is not found in the marketplace, your local copy is outdated: refresh it with `/plugin marketplace update claude-plugins-official`. Then retry the install.202If Claude Code reports `Marketplace "claude-plugins-official" not found`, add the marketplace with `/plugin marketplace add anthropics/claude-plugins-official`. If it reports that the plugin is not found in the marketplace, your local copy is outdated: refresh it with `/plugin marketplace update claude-plugins-official`. Then retry the install.

203 203 

204To enable a plugin for everyone in the repository rather than installing it yourself, add it to the [`enabledPlugins` project setting](/en/settings#plugin-settings).204To enable a plugin for everyone in the repository rather than installing it yourself, add it to the [`enabledPlugins` project setting](/docs/en/settings#plugin-settings).

205 205 

206Code intelligence plugins require the language's language server binary on each developer's machine. See [which binary each language requires](/en/discover-plugins#code-intelligence). Installing from the official marketplace requires network access to GitHub, where the marketplace is hosted. On a restricted network, [add the marketplace from an internal Git host or local path](/en/discover-plugins#add-from-other-git-hosts) instead.206Code intelligence plugins require the language's language server binary on each developer's machine. See [which binary each language requires](/docs/en/discover-plugins#code-intelligence). Installing from the official marketplace requires network access to GitHub, where the marketplace is hosted. On a restricted network, [add the marketplace from an internal Git host or local path](/docs/en/discover-plugins#add-from-other-git-hosts) instead.

207 207 

208This pairs well with `claudeMdExcludes` and the `Read` deny rules above. Those keep irrelevant content out of context, and code intelligence keeps Claude from reading through what remains to locate a definition.208This pairs well with `claudeMdExcludes` and the `Read` deny rules above. Those keep irrelevant content out of context, and code intelligence keeps Claude from reading through what remains to locate a definition.

209 209 


235 235 

236When Claude creates a worktree, it checks out only `.claude/`, `packages/api/`, and `packages/shared/` instead of the full tree. Paths in `sparsePaths` are relative to the repository root, regardless of which subdirectory you start Claude from. Any directory paths work here, not only package roots.236When Claude creates a worktree, it checks out only `.claude/`, `packages/api/`, and `packages/shared/` instead of the full tree. Paths in `sparsePaths` are relative to the repository root, regardless of which subdirectory you start Claude from. Any directory paths work here, not only package roots.

237 237 

238This is particularly useful for [subagent worktree isolation](/en/worktrees#isolate-subagents-with-worktrees). Subagents are parallel Claude instances spawned for subtasks, and each one that runs in a worktree gets a lightweight checkout instead of the full tree. All worktrees in a session share the same `sparsePaths`, so if one subagent needs `packages/api/` and another needs `packages/web/`, list both.238This is particularly useful for [subagent worktree isolation](/docs/en/worktrees#isolate-subagents-with-worktrees). Subagents are parallel Claude instances spawned for subtasks, and each one that runs in a worktree gets a lightweight checkout instead of the full tree. All worktrees in a session share the same `sparsePaths`, so if one subagent needs `packages/api/` and another needs `packages/web/`, list both.

239 239 

240List directories in `sparsePaths`, not individual files. Root-level files like `package.json`, `tsconfig.base.json`, and lock files are always checked out alongside the directories you list. Root-level directories are not, so include `.claude` in the list if you want the repository root's `.claude/settings.json`, `.claude/rules/`, or `.claude/skills/` available inside the worktree.240List directories in `sparsePaths`, not individual files. Root-level files like `package.json`, `tsconfig.base.json`, and lock files are always checked out alongside the directories you list. Root-level directories are not, so include `.claude` in the list if you want the repository root's `.claude/settings.json`, `.claude/rules/`, or `.claude/skills/` available inside the worktree.

241 241 


264 The `sparsePaths` and `symlinkDirectories` settings are read from your starting directory before the worktree is created. After creation, the session's working directory is the worktree root, not the subdirectory you launched from. Project settings inside the worktree therefore load from the worktree root's `.claude/settings.json`, the checked-out copy of the repository root's file. Put any other settings you need inside worktrees, such as permission rules or hooks, in the repository root's `.claude/settings.json`.264 The `sparsePaths` and `symlinkDirectories` settings are read from your starting directory before the worktree is created. After creation, the session's working directory is the worktree root, not the subdirectory you launched from. Project settings inside the worktree therefore load from the worktree root's `.claude/settings.json`, the checked-out copy of the repository root's file. Put any other settings you need inside worktrees, such as permission rules or hooks, in the repository root's `.claude/settings.json`.

265</Note>265</Note>

266 266 

267For the full worktree settings reference, see [Worktree settings](/en/settings#worktree-settings).267For the full worktree settings reference, see [Worktree settings](/docs/en/settings#worktree-settings).

268 268 

269### Grant access across packages or repositories269### Grant access across packages or repositories

270 270 


306CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1 claude --add-dir ../shared306CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1 claude --add-dir ../shared

307```307```

308 308 

309The environment variable has no effect on directories listed in the `additionalDirectories` setting. See [Load from additional directories](/en/memory#load-from-additional-directories) for details.309The environment variable has no effect on directories listed in the `additionalDirectories` setting. See [Load from additional directories](/docs/en/memory#load-from-additional-directories) for details.

310 310 

311For sibling directories that everyone in this area needs, commit `additionalDirectories` to `.claude/settings.json`. For a personal selection or one-off access, use `.claude/settings.local.json` or pass `--add-dir` at launch.311For sibling directories that everyone in this area needs, commit `additionalDirectories` to `.claude/settings.json`. For a personal selection or one-off access, use `.claude/settings.local.json` or pass `--add-dir` at launch.

312 312 

313## Add per-directory skills313## Add per-directory skills

314 314 

315Any subdirectory can define [skills](/en/skills) scoped to its own stack. A skill loads on demand when Claude determines it's relevant, so API-specific tooling doesn't consume context during frontend work.315Any subdirectory can define [skills](/docs/en/skills) scoped to its own stack. A skill loads on demand when Claude determines it's relevant, so API-specific tooling doesn't consume context during frontend work.

316 316 

317Skills live under `.claude/skills/` inside the directory. Commit them alongside that area's code so anyone who clones the repository gets them. In a monorepo this can be one set of skills per package. In a large single-tree codebase it's one set per subsystem such as `src/db/.claude/skills/`.317Skills live under `.claude/skills/` inside the directory. Commit them alongside that area's code so anyone who clones the repository gets them. In a monorepo this can be one set of skills per package. In a large single-tree codebase it's one set per subsystem such as `src/db/.claude/skills/`.

318 318 


355 355 

356A different subdirectory holds different skills the same way: `packages/web/.claude/skills/component-patterns/` describes the frontend's component conventions instead of testing. When Claude works on a file in `packages/api/`, it loads the api-testing skill. When it works in `packages/web/`, it loads component-patterns instead. Neither directory's skills load during the other's tasks.356A different subdirectory holds different skills the same way: `packages/web/.claude/skills/component-patterns/` describes the frontend's component conventions instead of testing. When Claude works on a file in `packages/api/`, it loads the api-testing skill. When it works in `packages/web/`, it loads component-patterns instead. Neither directory's skills load during the other's tasks.

357 357 

358You can also scope a skill by file pattern instead of by placement. The [`paths` frontmatter field](/en/skills#frontmatter-reference) takes glob patterns, and Claude loads the skill automatically only when it works with matching files. Use this for a skill that lives in the repository root's `.claude/skills/` but applies only to certain files wherever they appear, such as a database-migration skill scoped to `**/migrations/**`.358You can also scope a skill by file pattern instead of by placement. The [`paths` frontmatter field](/docs/en/skills#frontmatter-reference) takes glob patterns, and Claude loads the skill automatically only when it works with matching files. Use this for a skill that lives in the repository root's `.claude/skills/` but applies only to certain files wherever they appear, such as a database-migration skill scoped to `**/migrations/**`.

359 359 

360For more on creating and organizing skills, see [Skills](/en/skills).360For more on creating and organizing skills, see [Skills](/docs/en/skills).

361 361 

362### Keep skills discoverable362### Keep skills discoverable

363 363 


366Which skills are in scope depends on where you start Claude:366Which skills are in scope depends on where you start Claude:

367 367 

368* **From a subdirectory such as `packages/api/`**: skills from that directory, every parent up to the repository root, and the user and enterprise levels368* **From a subdirectory such as `packages/api/`**: skills from that directory, every parent up to the repository root, and the user and enterprise levels

369* **From the repository root**: skills from every subdirectory Claude touches during the session, which can accumulate into the hundreds369* **From the repository root**: root skills, plus skills from every subdirectory Claude touches during the session, which can accumulate into the hundreds

370* **After adding a sibling with [`--add-dir`](#grant-access-across-packages-or-repositories)**: that sibling's skills load too. The `additionalDirectories` setting grants file access only and does not load skills370* **After adding a sibling with [`--add-dir`](#grant-access-across-packages-or-repositories)**: that sibling's skills load too. The `additionalDirectories` setting grants file access only and does not load skills

371 371 

372Names always load, but [descriptions are shortened when there are many](/en/skills#skill-descriptions-are-cut-short), which can strip the keywords Claude uses to decide whether a skill applies. Keep descriptions short and lead with words a request would contain, like "writing or modifying tests in `packages/api/`".372Names always load, but [descriptions are shortened when there are many](/docs/en/skills#skill-descriptions-are-cut-short), which can strip the keywords Claude uses to decide whether a skill applies. Keep descriptions short and lead with words a request would contain, like "writing or modifying tests in `packages/api/`".

373 373 

374For skills that many directories share, such as PR conventions or a deploy checklist, place them in the repository root's `.claude/skills/` so they load from any starting directory. When shared skills need their own version history or must work across repositories, package them as a [plugin](/en/plugins) instead. Plugin skills use a `plugin-name:skill-name` namespace, so they never collide with per-directory skills. A platform team can version and update them in one place.374For skills that many directories share, such as PR conventions or a deploy checklist, place them in the repository root's `.claude/skills/` so they load from any starting directory. When shared skills need their own version history or must work across repositories, package them as a [plugin](/docs/en/plugins) instead. Plugin skills use a `plugin-name:skill-name` namespace, so they never collide with per-directory skills. A platform team can version and update them in one place.

375 375 

376To find which skills go unused, enable the OpenTelemetry [logs exporter](/en/monitoring-usage) and set `OTEL_LOG_TOOL_DETAILS=1` so skill names are recorded verbatim instead of redacted. The [`skill_activated` event](/en/monitoring-usage#skill-activated-event) records every invocation in its `skill.name` attribute, and `invocation_trigger` records whether a command, Claude, or a nested skill invoked it, which tells you what to consolidate or retire.376To find which skills go unused, enable the OpenTelemetry [logs exporter](/docs/en/monitoring-usage) and set `OTEL_LOG_TOOL_DETAILS=1` so skill names are recorded verbatim instead of redacted. The [`skill_activated` event](/docs/en/monitoring-usage#skill-activated-event) records every invocation in its `skill.name` attribute, and `invocation_trigger` records whether a command, Claude, or a nested skill invoked it, which tells you what to consolidate or retire.

377 377 

378## Centralize conventions when layering stops scaling378## Centralize conventions when layering stops scaling

379 379 


381 381 

382Move conventions and reference content out of always-loaded CLAUDE.md and into mechanisms that load on demand:382Move conventions and reference content out of always-loaded CLAUDE.md and into mechanisms that load on demand:

383 383 

384* [Skills](/en/skills): reference material Claude loads only when relevant to the task384* [Skills](/docs/en/skills): reference material Claude loads only when relevant to the task

385* [Plugins](/en/plugins): versioned bundles of skills, hooks, and commands that a platform team owns centrally385* [Plugins](/docs/en/plugins): versioned bundles of skills, hooks, and commands that a platform team owns centrally

386* [MCP servers](/en/mcp): if your organization already runs a code search or RAG index over the repository, expose it as an MCP tool so Claude queries it instead of reading files directly386* [MCP servers](/docs/en/mcp): if your organization already runs a code search or RAG index over the repository, expose it as an MCP tool so Claude queries it instead of reading files directly

387 387 

388See [server-managed or endpoint-managed settings](/en/server-managed-settings#choose-between-server-managed-and-endpoint-managed-settings) for how platform teams can enforce these centrally.388See [server-managed or endpoint-managed settings](/docs/en/server-managed-settings#choose-between-server-managed-and-endpoint-managed-settings) for how platform teams can enforce these centrally.

389 389 

390### Recommend the right plugin at session start390### Recommend the right plugin at session start

391 391 

392Once conventions live in plugins, a teammate starting Claude in an unfamiliar part of the tree has no signal about which plugin that area's owners maintain. A [`SessionStart` hook](/en/hooks#sessionstart) can close that gap, since anything the hook prints to stdout is added to Claude's context before the first prompt.392Once conventions live in plugins, a teammate starting Claude in an unfamiliar part of the tree has no signal about which plugin that area's owners maintain. A [`SessionStart` hook](/docs/en/hooks#sessionstart) can close that gap, since anything the hook prints to stdout is added to Claude's context before the first prompt.

393 393 

394For example, you can write a script that reads the launch directory from the [hook input](/en/hooks#common-input-fields), looks it up in a path-to-plugin map committed to the repository, and prints the recommendation for Claude to relay in its first reply. See [Automate actions with hooks](/en/hooks-guide) to write and register the hook.394For example, you can write a script that reads the launch directory from the [hook input](/docs/en/hooks#common-input-fields), looks it up in a path-to-plugin map committed to the repository, and prints the recommendation for Claude to relay in its first reply. See [Automate actions with hooks](/docs/en/hooks-guide) to write and register the hook.

395 395 

396## Put it together396## Put it together

397 397 


471Two techniques help keep a cross-package change consistent:471Two techniques help keep a cross-package change consistent:

472 472 

473* **Give Claude the whole change in one session**: handing over the shared edit and its call sites together keeps the decisions behind each edit consistent, rather than re-deriving them per package473* **Give Claude the whole change in one session**: handing over the shared edit and its call sites together keeps the decisions behind each edit consistent, rather than re-deriving them per package

474* **Save the plan to a file before editing**: [plan first](/en/best-practices#explore-first-then-plan-then-code) and ask Claude to write the plan to a markdown file in the repository. A long cross-package session [compacts its context](/en/context-window#what-survives-compaction) along the way, and the saved plan survives where conversation history may not474* **Save the plan to a file before editing**: [plan first](/docs/en/best-practices#explore-first-then-plan-then-code) and ask Claude to write the plan to a markdown file in the repository. A long cross-package session [compacts its context](/docs/en/context-window#what-survives-compaction) along the way, and the saved plan survives where conversation history may not

475 475 

476## Next steps476## Next steps

477 477 

478Once this configuration is in place, you can refine it:478Once this configuration is in place, you can refine it:

479 479 

480* Use [hooks](/en/hooks-guide) to run per-directory linters or type-checkers after Claude edits files480* Use [hooks](/docs/en/hooks-guide) to run per-directory linters or type-checkers after Claude edits files

481* Review [Manage costs effectively](/en/costs) to understand how codebase size affects token usage and how to set spend limits before a wider rollout481* Review [Manage costs effectively](/docs/en/costs) to understand how codebase size affects token usage and how to set spend limits before a wider rollout

482* Read [How Claude Code works in large codebases](https://claude.com/blog/how-claude-code-works-in-large-codebases-best-practices-and-where-to-start) on the Claude blog for organizational rollout patterns and ownership models that sit above the per-repository configuration on this page482* Read [How Claude Code works in large codebases](https://claude.com/blog/how-claude-code-works-in-large-codebases-best-practices-and-where-to-start) on the Claude blog for organizational rollout patterns and ownership models that sit above the per-repository configuration on this page

Details

6 6 

7> Point Claude Code at your organization's LLM gateway. Check whether your admin already configured it, or set the base URL and credential yourself, then verify the connection and fix gateway errors.7> Point Claude Code at your organization's LLM gateway. Check whether your admin already configured it, or set the base URL and credential yourself, then verify the connection and fix gateway errors.

8 8 

9An [LLM gateway](/en/llm-gateway) is a proxy your organization runs between Claude Code and the model provider. When your organization uses one, Claude Code authenticates to the gateway with a credential your organization issues instead of your personal claude.ai login.9An [LLM gateway](/docs/en/llm-gateway) is a proxy your organization runs between Claude Code and the model provider. When your organization uses one, Claude Code authenticates to the gateway with a credential your organization issues instead of your personal claude.ai login.

10 10 

11This page is for developers running Claude Code through a gateway their organization operates. It covers two paths: [checking whether your administrator already configured it for you](#check-for-an-existing-configuration), and [configuring it yourself](#configure-claude-code-yourself) when they haven't.11This page is for developers running Claude Code through a gateway their organization operates. It covers two paths: [checking whether your administrator already configured it for you](#check-for-an-existing-configuration), and [configuring it yourself](#configure-claude-code-yourself) when they haven't.

12 12 

13<Note>13<Note>

14 * To deploy a gateway for your organization, see [Roll out an LLM gateway](/en/llm-gateway-rollout)14 * To deploy a gateway for your organization, see [Roll out an LLM gateway](/docs/en/llm-gateway-rollout)

15 * For what Claude Code sends to a gateway, see the [gateway protocol reference](/en/llm-gateway-protocol)15 * For what Claude Code sends to a gateway, see the [gateway protocol reference](/docs/en/llm-gateway-protocol)

16</Note>16</Note>

17 17 

18## Check for an existing configuration18## Check for an existing configuration

19 19 

20Administrators can distribute the gateway address and credential through [managed settings](/en/settings#settings-files), device management, or an [`apiKeyHelper`](#rotate-credentials-with-apikeyhelper), so Claude Code picks them up at startup with nothing for you to set. To check whether your organization already did this:20Administrators can distribute the gateway address and credential through [managed settings](/docs/en/settings#settings-files), device management, or an [`apiKeyHelper`](#rotate-credentials-with-apikeyhelper), so Claude Code picks them up at startup with nothing for you to set. To check whether your organization already did this:

21 21 

22<Steps>22<Steps>

23 <Step title="Start Claude Code">23 <Step title="Start Claude Code">


93 93 

94Shell exports apply only to that terminal session and programs started from it. An editor launched from the dock or Start menu won't see them. To make the values persist across new terminals, add the same lines to your shell profile, such as `~/.zshrc`, `~/.bashrc`, or your PowerShell `$PROFILE`.94Shell exports apply only to that terminal session and programs started from it. An editor launched from the dock or Start menu won't see them. To make the values persist across new terminals, add the same lines to your shell profile, such as `~/.zshrc`, `~/.bashrc`, or your PowerShell `$PROFILE`.

95 95 

96If you export the gateway only in your shell, it doesn't reliably reach background agents hosted by the [supervisor](/en/agent-view#how-background-sessions-are-hosted); see [how each background session sources its gateway](/en/agent-view#the-supervisor-process). Use a settings file for any gateway that background agents must always route through.96If you export the gateway only in your shell, it doesn't reliably reach background agents hosted by the [supervisor](/docs/en/agent-view#how-background-sessions-are-hosted); see [how each background session sources its gateway](/docs/en/agent-view#the-supervisor-process). Use a settings file for any gateway that background agents must always route through.

97 97 

98#### Set in a settings file98#### Set in a settings file

99 99 

100To make the configuration apply everywhere Claude Code runs, including [background agents](/en/agent-view#how-background-sessions-are-hosted), set the variables in the `env` block of a [settings file](/en/settings) instead of relying on your shell. Settings files have different scopes:100To make the configuration apply everywhere Claude Code runs, including [background agents](/docs/en/agent-view#how-background-sessions-are-hosted), set the variables in the `env` block of a [settings file](/docs/en/settings) instead of relying on your shell. Settings files have different scopes:

101 101 

102* `~/.claude/settings.json` applies to all your projects. On Windows the path is `%USERPROFILE%\.claude\settings.json`102* `~/.claude/settings.json` applies to all your projects. On Windows the path is `%USERPROFILE%\.claude\settings.json`

103* `.claude/settings.local.json` applies to one project. Claude Code adds it to your gitignore when it creates the file; if you create it yourself, add it to your gitignore manually first so you don't accidentally commit your credential103* `.claude/settings.local.json` applies to one project. Claude Code adds it to your global gitignore when it saves a setting there; if you create it by hand or have Claude write it, add it to your gitignore yourself first so you don't accidentally commit your credential

104 104 

105<Warning>105<Warning>

106 Don't put the credential in a project's `.claude/settings.json`. That file is committed and shared with everyone who clones the repository.106 Don't put the credential in a project's `.claude/settings.json`. That file is committed and shared with everyone who clones the repository.


172 172 

173### VS Code extension173### VS Code extension

174 174 

175Set the gateway variables for the [VS Code extension](/en/vs-code) in `claudeCode.environmentVariables`, in VS Code's own user settings opened with the **Preferences: Open User Settings (JSON)** command. The extension checks credentials from this setting before launching, so it's the reliable place for the gateway credential; values in `~/.claude/settings.json` reach the spawned process but not the extension's own login check.175Set the gateway variables for the [VS Code extension](/docs/en/vs-code) in `claudeCode.environmentVariables`, in VS Code's own user settings opened with the **Preferences: Open User Settings (JSON)** command. The extension checks credentials from this setting before launching, so it's the reliable place for the gateway credential; values in `~/.claude/settings.json` reach the spawned process but not the extension's own login check.

176 176 

177```json theme={null}177```json theme={null}

178{178{


187 187 

188The desktop app reads gateway routing from its [third-party inference configuration](https://claude.com/docs/third-party/claude-desktop/gateway), not from `ANTHROPIC_BASE_URL` or `settings.json`. That configuration can come from your organization or from a form in the app itself:188The desktop app reads gateway routing from its [third-party inference configuration](https://claude.com/docs/third-party/claude-desktop/gateway), not from `ANTHROPIC_BASE_URL` or `settings.json`. That configuration can come from your organization or from a form in the app itself:

189 189 

190* **Distributed by an administrator**: if your organization has [deployed the configuration](/en/llm-gateway-rollout#distribute-through-managed-settings), the desktop app routes through the gateway with no setup on your part190* **Distributed by an administrator**: if your organization has [deployed the configuration](/docs/en/llm-gateway-rollout#distribute-through-managed-settings), the desktop app routes through the gateway with no setup on your part

191* **Configured locally**: for devices without an administrator-distributed configuration, open Help → Troubleshooting → Enable Developer Mode, which restarts the app with a Developer menu. Then open Developer → Configure Third-Party Inference and enter your gateway base URL. An administrator-distributed configuration takes precedence and makes this form read-only191* **Configured locally**: for devices without an administrator-distributed configuration, open Help → Troubleshooting → Enable Developer Mode, which restarts the app with a Developer menu. Then open Developer → Configure Third-Party Inference and enter your gateway base URL. An administrator-distributed configuration takes precedence and makes this form read-only

192 192 

193With the gateway configuration active, the desktop app runs sessions on your local machine only: the environment picker doesn't offer SSH sessions or Anthropic-hosted cloud environments, and [Remote Control](/en/remote-control) is unavailable. To use Claude Code on a remote host through the gateway, run the CLI on that host with [`ANTHROPIC_BASE_URL` and the gateway credential](#set-the-base-url-and-credential) set there.193With the gateway configuration active, the desktop app runs sessions on your local machine only: the environment picker doesn't offer SSH sessions or Anthropic-hosted cloud environments, and [Remote Control](/docs/en/remote-control) is unavailable. To use Claude Code on a remote host through the gateway, run the CLI on that host with [`ANTHROPIC_BASE_URL` and the gateway credential](#set-the-base-url-and-credential) set there.

194 194 

195If the desktop app shows `Gateway was unreachable`, the app couldn't reach the configured base URL at startup; check the URL and network path with the [curl test above](#verify-the-connection).195If the desktop app shows `Gateway was unreachable`, the app couldn't reach the configured base URL at startup; check the URL and network path with the [curl test above](#verify-the-connection).

196 196 

197### GitHub Actions197### GitHub Actions

198 198 

199[Claude Code GitHub Actions](/en/github-actions) reads `ANTHROPIC_BASE_URL` and `ANTHROPIC_CUSTOM_HEADERS` from the workflow's `env` block. Pass the credential as the action's `anthropic_api_key` input; the action sets it as `ANTHROPIC_API_KEY`, so it reaches the gateway in the `x-api-key` header.199[Claude Code GitHub Actions](/docs/en/github-actions) reads `ANTHROPIC_BASE_URL` and `ANTHROPIC_CUSTOM_HEADERS` from the workflow's `env` block. Pass the credential as the action's `anthropic_api_key` input; the action sets it as `ANTHROPIC_API_KEY`, so it reaches the gateway in the `x-api-key` header.

200 200 

201For an `x-api-key` gateway, set the base URL in `env` and pass the gateway key as the input:201For an `x-api-key` gateway, set the base URL in `env` and pass the gateway key as the input:

202 202 


223 anthropic_api_key: ${{ secrets.GATEWAY_API_KEY }}223 anthropic_api_key: ${{ secrets.GATEWAY_API_KEY }}

224```224```

225 225 

226For the action's other authentication options, including `CLAUDE_CODE_OAUTH_TOKEN` and workload identity federation, see [Claude Code GitHub Actions](/en/github-actions) and the action's [README](https://github.com/anthropics/claude-code-action#readme).226For the action's other authentication options, including `CLAUDE_CODE_OAUTH_TOKEN` and workload identity federation, see [Claude Code GitHub Actions](/docs/en/github-actions) and the action's [README](https://github.com/anthropics/claude-code-action#readme).

227 227 

228### Agent SDK228### Agent SDK

229 229 

230The [Agent SDK](/en/agent-sdk/overview) has no gateway-specific options; it passes environment variables to the Claude Code process it spawns. Each SDK accepts an `env` option that sets the spawned process's environment, and the TypeScript and Python SDKs treat it differently:230The [Agent SDK](/docs/en/agent-sdk/overview) has no gateway-specific options; it passes environment variables to the Claude Code process it spawns. Each SDK accepts an `env` option that sets the spawned process's environment, and the TypeScript and Python SDKs treat it differently:

231 231 

232* TypeScript: the spawned process inherits the parent environment by default, but setting `options.env` replaces the environment entirely. Spread `process.env` into it to keep your gateway variables.232* TypeScript: the spawned process inherits the parent environment by default, but setting `options.env` replaces the environment entirely. Spread `process.env` into it to keep your gateway variables.

233* Python: `ClaudeAgentOptions(env=...)` merges on top of the inherited environment, so gateway variables set in the parent process carry through without spreading.233* Python: `ClaudeAgentOptions(env=...)` merges on top of the inherited environment, so gateway variables set in the parent process carry through without spreading.


258 258 

259### Slack, web, and Remote Control259### Slack, web, and Remote Control

260 260 

261[Claude Code in Slack](/en/slack) and [Claude Code on the web](/en/claude-code-on-the-web) are Anthropic-hosted products that always use Anthropic's API; they aren't part of a gateway deployment. Gateway variables set in a cloud session's environment configuration are not applied. If your traffic must stay on the gateway, don't enable these surfaces for those users.261[Claude Code in Slack](/docs/en/slack) and [Claude Code on the web](/docs/en/claude-code-on-the-web) are Anthropic-hosted products that always use Anthropic's API; they aren't part of a gateway deployment. Gateway variables set in a cloud session's environment configuration are not applied. If your traffic must stay on the gateway, don't enable these surfaces for those users.

262 262 

263[Remote Control](/en/remote-control) and [voice dictation](/en/voice-dictation) both rely on a claude.ai identity: Remote Control to pair a live session with your account, and voice dictation to reach the claude.ai transcription endpoint. They are unavailable while `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or an `apiKeyHelper` is active. {/* min-version: 2.1.196 */}As of v2.1.196, Remote Control is also disabled while `ANTHROPIC_BASE_URL` points at a non-Anthropic host, so signing in with claude.ai isn't enough on its own.263[Remote Control](/docs/en/remote-control) and [voice dictation](/docs/en/voice-dictation) both rely on a claude.ai identity: Remote Control to pair a live session with your account, and voice dictation to reach the claude.ai transcription endpoint. They are unavailable while `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or an `apiKeyHelper` is active. {/* min-version: 2.1.196 */}As of v2.1.196, Remote Control is also disabled while `ANTHROPIC_BASE_URL` points at a non-Anthropic host, so signing in with claude.ai isn't enough on its own.

264 264 

265To restore either feature, log in with claude.ai and unset the gateway variables that feature checks. The Remote Control section of `claude doctor` names the credential variable to unset.265To restore either feature, log in with claude.ai and unset the gateway variables that feature checks. The Remote Control section of `claude doctor` names the credential variable to unset.

266 266 


273 273 

274### Send additional headers274### Send additional headers

275 275 

276Some gateways route or tag requests using a custom header in addition to the credential, for example a tenant identifier or a routing key. To send one, set [`ANTHROPIC_CUSTOM_HEADERS`](/en/env-vars) with one `Name: Value` pair per line. The example below adds a routing header named `X-Org-Route`:276Some gateways route or tag requests using a custom header in addition to the credential, for example a tenant identifier or a routing key. To send one, set [`ANTHROPIC_CUSTOM_HEADERS`](/docs/en/env-vars) with one `Name: Value` pair per line. The example below adds a routing header named `X-Org-Route`:

277 277 

278<Tabs>278<Tabs>

279 <Tab title="Bash or Zsh">279 <Tab title="Bash or Zsh">


307 307 

308To enable it, set `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1` in your shell or in the `env` block of `~/.claude/settings.json`. Discovery requires Claude Code v2.1.129 or later. {/* min-version: 2.1.129 */}308To enable it, set `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1` in your shell or in the `env` block of `~/.claude/settings.json`. Discovery requires Claude Code v2.1.129 or later. {/* min-version: 2.1.129 */}

309 309 

310Discovered models appear as additional `/model` entries labeled `From gateway`. To confirm discovery ran, start `claude --debug` and look for the `[gatewayDiscovery]` lines: a success logs how many models were cached, and a `404`, timeout, or redirect is recorded there too. For when discovery runs, what it filters, and the response format gateways serve, see the [model discovery reference](/en/llm-gateway-protocol#model-discovery).310Discovered models appear as additional `/model` entries labeled `From gateway`. To confirm discovery ran, start `claude --debug` and look for the `[gatewayDiscovery]` lines in the debug log at `~/.claude/debug/<session-id>.txt`: a success logs how many models were cached, and a `404`, timeout, or redirect is recorded there too. For when discovery runs, what it filters, and the response format gateways serve, see the [model discovery reference](/docs/en/llm-gateway-protocol#model-discovery).

311 311 

312### Rotate credentials with apiKeyHelper312### Rotate credentials with apiKeyHelper

313 313 


315 315 

316Use a helper when the credential expires on a schedule, comes from a vault or SSO command, or your administrator told you to configure one. If your credential is a fixed string you set once, the [credential variable](#set-the-credential-variable) is all you need and you can skip this section.316Use a helper when the credential expires on a schedule, comes from a vault or SSO command, or your administrator told you to configure one. If your credential is a fixed string you set once, the [credential variable](#set-the-credential-variable) is all you need and you can skip this section.

317 317 

318The helper is any shell command that prints the current credential to stdout. Claude Code runs it through your system shell, so on Windows it can be an executable or a PowerShell invocation. Write the script, make it executable, and reference it from `apiKeyHelper` in your [settings file](/en/settings):318The helper is any shell command that prints the current credential to stdout. Claude Code runs it through your system shell, so on Windows it can be an executable or a PowerShell invocation. Write the script, make it executable, and reference it from `apiKeyHelper` in your [settings file](/docs/en/settings):

319 319 

320<Tabs>320<Tabs>

321 <Tab title="Bash or Zsh">321 <Tab title="Bash or Zsh">


379Setting the variable has these effects and limits:379Setting the variable has these effects and limits:

380 380 

381* It disables auto-updates, so plan for another update path, such as your package manager or managed distribution.381* It disables auto-updates, so plan for another update path, such as your package manager or managed distribution.

382* It suppresses the [fast mode](/en/fast-mode) availability check. Unless a previous check already enabled fast mode on the machine, `/fast` reports that fast mode is unavailable.382* It suppresses the [fast mode](/docs/en/fast-mode) availability check. Unless a previous check already enabled fast mode on the machine, `/fast` reports that fast mode is unavailable.

383* It turns off [gateway model discovery](#add-gateway-models-to-the-model-picker), even though discovery queries the gateway itself. Previously discovered models stay available from the local cache, but the list isn't refreshed.383* It turns off [gateway model discovery](#add-gateway-models-to-the-model-picker), even though discovery queries the gateway itself. Previously discovered models stay available from the local cache, but the list isn't refreshed.

384* The WebFetch tool's [domain safety check](/en/data-usage#webfetch-domain-safety-check) isn't affected and still calls `api.anthropic.com`. Turn it off separately with `skipWebFetchPreflight: true` in [settings](/en/settings) if your network blocks that host.384* The WebFetch tool's [domain safety check](/docs/en/data-usage#webfetch-domain-safety-check) isn't affected and still calls `api.anthropic.com`. Turn it off separately with `skipWebFetchPreflight: true` in [settings](/docs/en/settings) if your network blocks that host.

385* For each telemetry stream and the variable that controls it, see [telemetry services](/en/data-usage#telemetry-services).385* For each telemetry stream and the variable that controls it, see [telemetry services](/docs/en/data-usage#telemetry-services).

386 386 

387### Route to a cloud provider through a gateway387### Route to a cloud provider through a gateway

388 388 


390 390 

391Use one only if your gateway team specifically named Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, or the Claude Platform on AWS. If the [verification request](#verify-the-connection) above returned JSON, you can skip this section.391Use one only if your gateway team specifically named Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, or the Claude Platform on AWS. If the [verification request](#verify-the-connection) above returned JSON, you can skip this section.

392 392 

393Set the block for the provider your gateway team named. The skip-auth variables tell Claude Code not to sign requests with provider credentials, since the gateway holds those. If the gateway needs its own token, add `ANTHROPIC_AUTH_TOKEN` after the block, except for Microsoft Foundry, which uses `ANTHROPIC_FOUNDRY_API_KEY` as shown. {/* min-version: 2.1.203 */}A Microsoft Foundry gateway that expects a bearer token can use [`ANTHROPIC_FOUNDRY_AUTH_TOKEN`](/en/env-vars) instead; it takes precedence over `ANTHROPIC_FOUNDRY_API_KEY` when both are set. `ANTHROPIC_FOUNDRY_AUTH_TOKEN` requires Claude Code v2.1.203 or later.393Set the block for the provider your gateway team named. The skip-auth variables tell Claude Code not to sign requests with provider credentials, since the gateway holds those. If the gateway needs its own token, add `ANTHROPIC_AUTH_TOKEN` after the block, except for Microsoft Foundry, which uses `ANTHROPIC_FOUNDRY_API_KEY` as shown. {/* min-version: 2.1.203 */}A Microsoft Foundry gateway that expects a bearer token can use [`ANTHROPIC_FOUNDRY_AUTH_TOKEN`](/docs/en/env-vars) instead; it takes precedence over `ANTHROPIC_FOUNDRY_API_KEY` when both are set. `ANTHROPIC_FOUNDRY_AUTH_TOKEN` requires Claude Code v2.1.203 or later.

394 394 

395#### Amazon Bedrock395#### Amazon Bedrock

396 396 


438 438 

439#### Microsoft Foundry439#### Microsoft Foundry

440 440 

441Put the gateway's credential in `ANTHROPIC_FOUNDRY_API_KEY`; it is sent to the gateway as the `x-api-key` header. {/* min-version: 2.1.203 */}A gateway that expects a bearer token can take [`ANTHROPIC_FOUNDRY_AUTH_TOKEN`](/en/env-vars) instead. Claude Code sends that value as the `Authorization: Bearer` header, and it takes precedence over `ANTHROPIC_FOUNDRY_API_KEY` when both are set. Requires Claude Code v2.1.203 or later.441Put the gateway's credential in `ANTHROPIC_FOUNDRY_API_KEY`; it is sent to the gateway as the `x-api-key` header. {/* min-version: 2.1.203 */}A gateway that expects a bearer token can take [`ANTHROPIC_FOUNDRY_AUTH_TOKEN`](/docs/en/env-vars) instead. Claude Code sends that value as the `Authorization: Bearer` header, and it takes precedence over `ANTHROPIC_FOUNDRY_API_KEY` when both are set. Requires Claude Code v2.1.203 or later.

442 442 

443For a gateway that injects its own `Authorization` header, set `CLAUDE_CODE_SKIP_FOUNDRY_AUTH=1` and leave both credential variables unset. Claude Code then sends requests without an Azure credential and preserves the `Authorization` header you supply, for example through `ANTHROPIC_CUSTOM_HEADERS`. {/* min-version: 2.1.203 */}Before v2.1.203, `CLAUDE_CODE_SKIP_FOUNDRY_AUTH` without an API key left the Microsoft Foundry client unable to send requests.443For a gateway that injects its own `Authorization` header, set `CLAUDE_CODE_SKIP_FOUNDRY_AUTH=1` and leave both credential variables unset. Claude Code then sends requests without an Azure credential and preserves the `Authorization` header you supply, for example through `ANTHROPIC_CUSTOM_HEADERS`. {/* min-version: 2.1.203 */}Before v2.1.203, `CLAUDE_CODE_SKIP_FOUNDRY_AUTH` without an API key left the Microsoft Foundry client unable to send requests.

444 444 


462 462 

463#### Claude Platform on AWS463#### Claude Platform on AWS

464 464 

465See [Claude Platform on AWS](/en/claude-platform-on-aws) for the workspace ID.465See [Claude Platform on AWS](/docs/en/claude-platform-on-aws) for the workspace ID.

466 466 

467<Tabs>467<Tabs>

468 <Tab title="Bash or Zsh">468 <Tab title="Bash or Zsh">


492| :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |492| :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

493| A startup warning naming two credential sources and ending in `auth may not work as expected`. Older versions show `Auth conflict: Both a token (SOURCE) and an API key (SOURCE) are set` instead. | A gateway credential and a saved login are both active; the variable is used for requests, but the stale login can cause unexpected auth behavior | Unset the variable to use the saved login, or run `/logout` to use the gateway credential |493| A startup warning naming two credential sources and ending in `auth may not work as expected`. Older versions show `Auth conflict: Both a token (SOURCE) and an API key (SOURCE) are set` instead. | A gateway credential and a saved login are both active; the variable is used for requests, but the stale login can cause unexpected auth behavior | Unset the variable to use the saved login, or run `/logout` to use the gateway credential |

494| `401` errors naming an invalid or unrecognized token | The credential isn't one the gateway issued, or it's in a header the gateway doesn't read | Confirm the variable matches your credential kind in the [credential table](#set-the-credential-variable), and regenerate the key at the gateway if it was revoked |494| `401` errors naming an invalid or unrecognized token | The credential isn't one the gateway issued, or it's in a header the gateway doesn't read | Confirm the variable matches your credential kind in the [credential table](#set-the-credential-variable), and regenerate the key at the gateway if it was revoked |

495| `Your apiKeyHelper script is failing` | The command in the [`apiKeyHelper`](/en/settings#available-settings) setting exited with an error, timed out, or printed nothing, so requests carry a placeholder key | Run the command directly to see why it fails, and re-authenticate with your credential provider if it reports an expired session; see [the error reference](/en/errors#your-apikeyhelper-script-is-failing) |495| `Your apiKeyHelper script is failing` | The command in the [`apiKeyHelper`](/docs/en/settings#available-settings) setting exited with an error, timed out, or printed nothing, so requests carry a placeholder key | Run the command directly to see why it fails, and re-authenticate with your credential provider if it reports an expired session; see [the error reference](/docs/en/errors#your-apikeyhelper-script-is-failing) |

496| `Unable to connect to API (ConnectionRefused)` when nothing answers at the address, `Unable to connect to API (FailedToOpenSocket)` when the hostname doesn't resolve, or `(ECONNREFUSED)` from npm installs, often after a silent pause while Claude Code [retries with backoff](/en/errors#automatic-retries) | Nothing answered at the base URL: the address is wrong, or a VPN or firewall blocks the path to the gateway | Run the [curl test above](#verify-the-connection), which fails immediately with the same cause, and confirm the URL and network path with your gateway team |496| `Unable to connect to API (ConnectionRefused)` when nothing answers at the address, `Unable to connect to API (FailedToOpenSocket)` when the hostname doesn't resolve, or `(ECONNREFUSED)` from npm installs, often after a silent pause while Claude Code [retries with backoff](/docs/en/errors#automatic-retries) | Nothing answered at the base URL: the address is wrong, or a VPN or firewall blocks the path to the gateway | Run the [curl test above](#verify-the-connection), which fails immediately with the same cause, and confirm the URL and network path with your gateway team |

497| `API returned an empty or malformed response (HTTP 200)` | The gateway or an intermediate proxy returned a non-API response, often an HTML error or login page | Test with the [curl request above](#verify-the-connection); fix the gateway route that returns non-JSON |497| `API returned an empty or malformed response (HTTP 200)` | The gateway or an intermediate proxy returned a non-API response, often an HTML error or login page | Test with the [curl request above](#verify-the-connection); fix the gateway route that returns non-JSON |

498| `400` errors naming `context_management`, `Extra inputs are not permitted`, or other unrecognized fields | The gateway forwards requests to an upstream that rejects fields Claude Code sends to Anthropic-format endpoints | Set `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`, which suppresses most pre-release fields; see [feature pass-through](/en/llm-gateway-protocol#feature-pass-through). Some betas aren't gated by this flag; for those, set the matching `CLAUDE_CODE_USE_*` provider variable so Claude Code sends only what that provider accepts |498| `400` errors naming `context_management`, `Extra inputs are not permitted`, or other unrecognized fields | The gateway forwards requests to an upstream that rejects fields Claude Code sends to Anthropic-format endpoints | Set `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`, which suppresses most pre-release fields; see [feature pass-through](/docs/en/llm-gateway-protocol#feature-pass-through). Some betas aren't gated by this flag; for those, set the matching `CLAUDE_CODE_USE_*` provider variable so Claude Code sends only what that provider accepts |

499| `400` errors naming `thinking` or `adaptive`, such as `Input tag 'adaptive' found` | The upstream model build doesn't accept adaptive reasoning, which Claude Code requests for Claude 4.6 and later models | Upgrade the gateway's upstream. On Opus 4.6 and Sonnet 4.6, `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1` works instead. The [model configuration](/en/model-config) capability variables apply only to the provider configurations, such as `CLAUDE_CODE_USE_BEDROCK` and `CLAUDE_CODE_USE_VERTEX`, not behind an `ANTHROPIC_BASE_URL` gateway |499| `400` errors naming `thinking` or `adaptive`, such as `Input tag 'adaptive' found` | The upstream model build doesn't accept adaptive reasoning, which Claude Code requests for Claude 4.6 and later models | Upgrade the gateway's upstream. On Opus 4.6 and Sonnet 4.6, `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1` works instead. The [model configuration](/docs/en/model-config) capability variables apply only to the provider configurations, such as `CLAUDE_CODE_USE_BEDROCK` and `CLAUDE_CODE_USE_VERTEX`, not behind an `ANTHROPIC_BASE_URL` gateway |

500| `400` errors stating a context or token limit in the gateway's own words, such as `ContextWindowExceededError` or `prompt token count of N exceeds the limit of M` | The gateway enforces a smaller context than the model's native window and rewrites the upstream error, so the automatic compact-and-retry, which matches Anthropic's `prompt is too long` wording, doesn't fire | Run `/compact` to recover the session. To prevent it, set `CLAUDE_CODE_AUTO_COMPACT_WINDOW` to the gateway's limit; the value is clamped to at least 100,000 tokens and at most the model's context window, so a gateway limit below 100,000 can't be matched and `/compact` remains the recovery there. Also set `CLAUDE_CODE_MAX_OUTPUT_TOKENS` below the gateway model's output limit |500| `400` errors stating a context or token limit in the gateway's own words, such as `ContextWindowExceededError` or `prompt token count of N exceeds the limit of M` | The gateway enforces a smaller context than the model's native window and rewrites the upstream error, so the automatic compact-and-retry, which matches Anthropic's `prompt is too long` wording, doesn't fire | Run `/compact` to recover the session. To prevent it, set `CLAUDE_CODE_AUTO_COMPACT_WINDOW` to the gateway's limit; the value is clamped to at least 100,000 tokens and at most the model's context window, so a gateway limit below 100,000 can't be matched and `/compact` remains the recovery there. Also set `CLAUDE_CODE_MAX_OUTPUT_TOKENS` below the gateway model's output limit |

501| Models missing from the `/model` picker | Gateway model names aren't in Claude Code's built-in list | Enable [gateway model discovery](#add-gateway-models-to-the-model-picker) or add names with the [model configuration](/en/model-config) variables |501| Models missing from the `/model` picker | Gateway model names aren't in Claude Code's built-in list | Enable [gateway model discovery](#add-gateway-models-to-the-model-picker) or add names with the [model configuration](/docs/en/model-config) variables |

502| `/fast` reports `Fast mode unavailable due to network connectivity issues` while inference requests work | The [fast mode](/en/fast-mode) availability check goes directly to `api.anthropic.com` and doesn't follow `ANTHROPIC_BASE_URL`, so blocked direct egress fails the check. The same message appears on an open network when the check presents a gateway-issued key from `ANTHROPIC_API_KEY` or an `apiKeyHelper` and Anthropic rejects it | Allowlist `api.anthropic.com` if egress is blocked, or set a skip variable; for a rejected gateway key only the skip variables help. See [use fast mode behind proxies and LLM gateways](/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways) |502| `/fast` reports `Fast mode unavailable due to network connectivity issues` while inference requests work | The [fast mode](/docs/en/fast-mode) availability check goes directly to `api.anthropic.com` and doesn't follow `ANTHROPIC_BASE_URL`, so blocked direct egress fails the check. The same message appears on an open network when the check presents a gateway-issued key from `ANTHROPIC_API_KEY` or an `apiKeyHelper` and Anthropic rejects it | Allowlist `api.anthropic.com` if egress is blocked, or set a skip variable; for a rejected gateway key only the skip variables help. See [use fast mode behind proxies and LLM gateways](/docs/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways) |

503| `/fast` reports `Fast mode has been disabled by your organization` in a session authenticated with `ANTHROPIC_AUTH_TOKEN`, even though the organization has fast mode enabled | The availability check requires a claude.ai login or an Anthropic API key; with only a bearer token, Claude Code treats fast mode as disabled without sending the check | Set `CLAUDE_CODE_SKIP_FAST_MODE_ORG_CHECK=1`; see [use fast mode behind proxies and LLM gateways](/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways) |503| `/fast` reports `Fast mode has been disabled by your organization` in a session authenticated with `ANTHROPIC_AUTH_TOKEN`, even though the organization has fast mode enabled | The availability check requires a claude.ai login or an Anthropic API key; with only a bearer token, Claude Code treats fast mode as disabled without sending the check | Set `CLAUDE_CODE_SKIP_FAST_MODE_ORG_CHECK=1`; see [use fast mode behind proxies and LLM gateways](/docs/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways) |

504| Claude Code asks you to log in even though the [curl test](#verify-the-connection) succeeds | The CLI has no credential of its own: a reachable base URL isn't one, and an `env` block in a project's `.claude/settings.json` or `.claude/settings.local.json` applies only after the first-run wizard and trust prompt | Set `ANTHROPIC_AUTH_TOKEN` somewhere Claude Code reads before first-run setup: a shell export, the `env` block in `~/.claude/settings.json`, or managed settings |504| Claude Code asks you to log in even though the [curl test](#verify-the-connection) succeeds | The CLI has no credential of its own: a reachable base URL isn't one, and an `env` block in a project's `.claude/settings.json` or `.claude/settings.local.json` applies only after the first-run wizard and trust prompt | Set `ANTHROPIC_AUTH_TOKEN` somewhere Claude Code reads before first-run setup: a shell export, the `env` block in `~/.claude/settings.json`, or managed settings |

505| `ANTHROPIC_API_KEY` is set but ignored, with no prompt | The key needs a one-time approval in interactive sessions, and a previously declined key is ignored without asking again | Enable it under `/config` with the `Use custom API key` option |505| `ANTHROPIC_API_KEY` is set but ignored, with no prompt | The key needs a one-time approval in interactive sessions, and a previously declined key is ignored without asking again | Enable it under `/config` with the `Use custom API key` option |

506| `This machine's managed settings require a first-party login` | Managed settings include `forceLoginMethod` or `forceLoginOrgUUID`, which on Claude Code v2.1.146 and later cannot coexist with `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or `apiKeyHelper` | Your administrator must remove `forceLoginMethod` and `forceLoginOrgUUID` from managed settings to use gateway credentials, or remove the gateway credential to use first-party login. The two cannot be combined |506| `This machine's managed settings require a first-party login` | Managed settings include `forceLoginMethod` or `forceLoginOrgUUID`, which on Claude Code v2.1.146 and later cannot coexist with `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or `apiKeyHelper` | Your administrator must remove `forceLoginMethod` and `forceLoginOrgUUID` from managed settings to use gateway credentials, or remove the gateway credential to use first-party login. The two cannot be combined |

507| `403` with an HTML body such as `403 Forbidden`, when the gateway's own logs show no request received | A web application firewall or reverse proxy in front of the gateway blocked the request body before it reached the gateway. Claude Code prompts include XML-style tags and source code that match cross-site-scripting body rules, so a short curl test passes while a real session doesn't | Exempt the gateway's `/v1/messages` path from request-body inspection. On AWS WAF this is the `CrossSiteScripting_Body` managed rule; on nginx with ModSecurity it is the equivalent OWASP CRS body rules |507| `403` with an HTML body such as `403 Forbidden`, when the gateway's own logs show no request received | A web application firewall or reverse proxy in front of the gateway blocked the request body before it reached the gateway. Claude Code prompts include XML-style tags and source code that match cross-site-scripting body rules, so a short curl test passes while a real session doesn't | Exempt the gateway's `/v1/messages` path from request-body inspection. On AWS WAF this is the `CrossSiteScripting_Body` managed rule; on nginx with ModSecurity it is the equivalent OWASP CRS body rules |

508| Certificate or TLS errors such as `SSL certificate verification failed` or `Self-signed certificate detected`, when the [curl test](#verify-the-connection) succeeds | Claude Code's runtime isn't trusting the same certificate authority that `curl` uses. Common behind corporate TLS-inspection proxies | Set `NODE_EXTRA_CA_CERTS` to the CA bundle path; see [CA certificate store](/en/network-config#ca-certificate-store) |508| Certificate or TLS errors such as `SSL certificate verification failed` or `Self-signed certificate detected`, when the [curl test](#verify-the-connection) succeeds | Claude Code's runtime isn't trusting the same certificate authority that `curl` uses. Common behind corporate TLS-inspection proxies | Set `NODE_EXTRA_CA_CERTS` to the CA bundle path; see [CA certificate store](/docs/en/network-config#ca-certificate-store) |

509 509 

510If Claude Code prompts you to log in repeatedly after removing gateway configuration, the cause is usually credential storage rather than the gateway; see [authentication errors](/en/errors#authentication-errors).510If Claude Code prompts you to log in repeatedly after removing gateway configuration, the cause is usually credential storage rather than the gateway; see [authentication errors](/docs/en/errors#authentication-errors).

511 511 

512## Related resources512## Related resources

513 513 

514* [LLM gateways overview](/en/llm-gateway): what a gateway is and how it interacts with claude.ai subscriptions514* [LLM gateways overview](/docs/en/llm-gateway): what a gateway is and how it interacts with claude.ai subscriptions

515* [Roll out an LLM gateway for your organization](/en/llm-gateway-rollout): the admin-facing checklist for deploying and distributing gateway configuration515* [Roll out an LLM gateway for your organization](/docs/en/llm-gateway-rollout): the admin-facing checklist for deploying and distributing gateway configuration

516* [Gateway protocol reference](/en/llm-gateway-protocol): what Claude Code sends to a gateway, including the headers and fields the gateway must forward516* [Gateway protocol reference](/docs/en/llm-gateway-protocol): what Claude Code sends to a gateway, including the headers and fields the gateway must forward

517* [Settings](/en/settings): where settings files live and how the `env` block is read517* [Settings](/docs/en/settings): where settings files live and how the `env` block is read

518* [Authentication](/en/authentication): how credential variables, `apiKeyHelper`, and OAuth login interact518* [Authentication](/docs/en/authentication): how credential variables, `apiKeyHelper`, and OAuth login interact

Details

8 8 

9This page documents the requests Claude Code sends to a gateway, including the endpoints it calls, the headers and body fields the gateway must forward, and which features stop working when it doesn't. It is written for operators configuring a gateway product to work with Claude Code.9This page documents the requests Claude Code sends to a gateway, including the endpoints it calls, the headers and body fields the gateway must forward, and which features stop working when it doesn't. It is written for operators configuring a gateway product to work with Claude Code.

10 10 

11A running [Claude apps gateway](/en/claude-apps-gateway) serves a machine-readable version of this contract at `GET /protocol`, covering the same forwarding requirements plus the Claude apps gateway-specific endpoints for SSO sign-in, managed-settings delivery, and telemetry. Claude apps gateway runs from the same `claude` binary as the CLI, so the [Claude apps gateway quickstart](/en/claude-apps-gateway#quickstart) is the shortest path to a running instance you can fetch the spec from.11A running [Claude apps gateway](/docs/en/claude-apps-gateway) serves a machine-readable version of this contract at `GET /protocol`, covering the same forwarding requirements plus the Claude apps gateway-specific endpoints for SSO sign-in, managed-settings delivery, and telemetry. Claude apps gateway runs from the same `claude` binary as the CLI, so the [Claude apps gateway quickstart](/docs/en/claude-apps-gateway#quickstart) is the shortest path to a running instance you can fetch the spec from.

12 12 

13<Note>13<Note>

14 * To roll out an existing or third-party gateway for your organization, see [Roll out an LLM gateway](/en/llm-gateway-rollout)14 * To roll out an existing or third-party gateway for your organization, see [Roll out an LLM gateway](/docs/en/llm-gateway-rollout)

15 * If you're an individual developer authenticating Claude Code to a gateway with a credential you were given, see [Connect Claude Code to an LLM gateway](/en/llm-gateway-connect)15 * If you're an individual developer authenticating Claude Code to a gateway with a credential you were given, see [Connect Claude Code to an LLM gateway](/docs/en/llm-gateway-connect)

16</Note>16</Note>

17 17 

18This page covers:18This page covers:


42 42 

43### Foundry and Claude Platform on AWS43### Foundry and Claude Platform on AWS

44 44 

45Microsoft Foundry and the [Claude Platform on AWS](/en/claude-platform-on-aws) implement the Anthropic Messages format. Claude Code routes to them through their own variables, `ANTHROPIC_FOUNDRY_BASE_URL` and `ANTHROPIC_AWS_BASE_URL`, but a gateway fronting either implements the Anthropic Messages row above. A gateway fronting the Claude Platform on AWS must also forward the `anthropic-workspace-id` header, which [that platform requires on every request](/en/claude-platform-on-aws).45Microsoft Foundry and the [Claude Platform on AWS](/docs/en/claude-platform-on-aws) implement the Anthropic Messages format. Claude Code routes to them through their own variables, `ANTHROPIC_FOUNDRY_BASE_URL` and `ANTHROPIC_AWS_BASE_URL`, but a gateway fronting either implements the Anthropic Messages row above. A gateway fronting the Claude Platform on AWS must also forward the `anthropic-workspace-id` header, which [that platform requires on every request](/docs/en/claude-platform-on-aws).

46 46 

47### Optional endpoints and startup traffic47### Optional endpoints and startup traffic

48 48 


50 50 

51A gateway also sees best-effort startup traffic it can reject without breaking anything: a `HEAD /` connectivity probe, and on Amazon Bedrock-format gateways a `GET /inference-profiles?type=SYSTEM_DEFINED` request.51A gateway also sees best-effort startup traffic it can reject without breaking anything: a `HEAD /` connectivity probe, and on Amazon Bedrock-format gateways a `GET /inference-profiles?type=SYSTEM_DEFINED` request.

52 52 

53The [fast mode](/en/fast-mode) availability check never appears in gateway logs: it calls `api.anthropic.com` directly rather than following `ANTHROPIC_BASE_URL`, so on a network that blocks direct egress to `api.anthropic.com`, fast mode can report a connectivity error while inference through the gateway keeps working. The [WebFetch domain safety check](/en/data-usage#webfetch-domain-safety-check) also calls `api.anthropic.com` directly. [Use fast mode behind proxies and LLM gateways](/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways) covers the variables that restore it.53The [fast mode](/docs/en/fast-mode) availability check never appears in gateway logs: it calls `api.anthropic.com` directly rather than following `ANTHROPIC_BASE_URL`, so on a network that blocks direct egress to `api.anthropic.com`, fast mode can report a connectivity error while inference through the gateway keeps working. The [WebFetch domain safety check](/docs/en/data-usage#webfetch-domain-safety-check) also calls `api.anthropic.com` directly. [Use fast mode behind proxies and LLM gateways](/docs/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways) covers the variables that restore it.

54 54 

55### Streaming55### Streaming

56 56 


67 67 

68## Request headers68## Request headers

69 69 

70Claude Code includes these headers on API requests. Header names are case-insensitive on the wire. Forward `anthropic-version` and `anthropic-beta` unchanged, plus `anthropic-workspace-id` when the upstream is the [Claude Platform on AWS](/en/claude-platform-on-aws); the rest the gateway may consume for routing, attribution, and tracing, and need not forward.70Claude Code includes these headers on API requests. Header names are case-insensitive on the wire. Forward `anthropic-version` and `anthropic-beta` unchanged, plus `anthropic-workspace-id` when the upstream is the [Claude Platform on AWS](/docs/en/claude-platform-on-aws); the rest the gateway may consume for routing, attribution, and tracing, and need not forward.

71 71 

72| Header | Description |72| Header | Description |

73| :------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |73| :------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

74| `Authorization`, `x-api-key` | The developer's gateway credential, in one or both headers depending on which [credential variable](/en/llm-gateway-connect#set-the-credential-variable) they set |74| `Authorization`, `x-api-key` | The developer's gateway credential, in one or both headers depending on which [credential variable](/docs/en/llm-gateway-connect#set-the-credential-variable) they set |

75| `anthropic-version` | API version, currently `2023-06-01`. Amazon Bedrock- and Google Cloud's Agent Platform-format requests also carry the `anthropic_version` body field, whose value is the provider dialect string, not this header's value |75| `anthropic-version` | API version, currently `2023-06-01`. Amazon Bedrock- and Google Cloud's Agent Platform-format requests also carry the `anthropic_version` body field, whose value is the provider dialect string, not this header's value |

76| `anthropic-beta` | Comma-separated capability values for the request. Forward the header verbatim; don't allowlist individual values, because the set changes with Claude Code releases. When the developer authenticates with a claude.ai login, which is possible when `ANTHROPIC_BASE_URL` is set without a gateway credential variable, this header also carries an OAuth capability that the upstream requires, and stripping it fails those requests with `401` |76| `anthropic-beta` | Comma-separated capability values for the request. Forward the header verbatim; don't allowlist individual values, because the set changes with Claude Code releases. When the developer authenticates with a claude.ai login, which is possible when `ANTHROPIC_BASE_URL` is set without a gateway credential variable, this header also carries an OAuth capability that the upstream requires, and stripping it fails those requests with `401` |

77| `x-claude-code-session-id` | A unique identifier for the current Claude Code session. Use it to aggregate all requests from one session without parsing request bodies |77| `x-claude-code-session-id` | A unique identifier for the current Claude Code session. Use it to aggregate all requests from one session without parsing request bodies |

78| `x-claude-code-agent-id` | Identifier of the [subagent](/en/sub-agents) that issued the request, present only on requests from an agent Claude Code spawned inside the session. Use it with the session ID to attribute cost to parallel agents |78| `x-claude-code-agent-id` | Identifier of the [subagent](/docs/en/sub-agents) that issued the request, present only on requests from an agent Claude Code spawned inside the session. Use it with the session ID to attribute cost to parallel agents |

79| `x-claude-code-parent-agent-id` | Identifier of the agent that spawned the requesting agent, present only for nested agents |79| `x-claude-code-parent-agent-id` | Identifier of the agent that spawned the requesting agent, present only for nested agents |

80 80 

81Subagent IDs are generated fresh for each spawn. Teammate agents, the named members of an [agent team](/en/agent-teams), reuse a stable name-based ID across reconnections. In both cases the ID identifies an agent, not a person or a device, so don't treat the agent ID header as a user identifier.81Subagent IDs are generated fresh for each spawn. Teammate agents, the named members of an [agent team](/docs/en/agent-teams), reuse a stable name-based ID across reconnections. In both cases the ID identifies an agent, not a person or a device, so don't treat the agent ID header as a user identifier.

82 82 

83If your developers set `ANTHROPIC_CUSTOM_HEADERS`, those headers appear on requests as well.83If your developers set `ANTHROPIC_CUSTOM_HEADERS`, those headers appear on requests as well.

84 84 


98 98 

99* Forward the `system` array exactly as received, keeping the block first: prepending another system block, reordering the array, or converting it to a single string defeats the strip, and the block then reaches the model and the prompt cache key.99* Forward the `system` array exactly as received, keeping the block first: prepending another system block, reordering the array, or converting it to a single string defeats the strip, and the block then reaches the model and the prompt cache key.

100* Keep the block in its own array entry: the endpoint treats a merged block that starts with the attribution header as attribution in its entirety and drops everything merged into it, including the rest of the system prompt.100* Keep the block in its own array entry: the endpoint treats a merged block that starts with the attribution header as attribution in its entirety and drops everything merged into it, including the rest of the system prompt.

101* If your gateway must reshape system content, set [`CLAUDE_CODE_ATTRIBUTION_HEADER=0`](/en/env-vars) so Claude Code omits the block. Anthropic and the cloud providers' Claude endpoints read the block for attribution, so omit it at the client rather than stripping or moving it in the gateway.101* If your gateway must reshape system content, set [`CLAUDE_CODE_ATTRIBUTION_HEADER=0`](/docs/en/env-vars) so Claude Code omits the block. Anthropic and the cloud providers' Claude endpoints read the block for attribution, so omit it at the client rather than stripping or moving it in the gateway.

102 102 

103Requests that reach the endpoint unmodified are unaffected.103Requests that reach the endpoint unmodified are unaffected.

104 104 

105{/* min-version: 2.1.181 */}From Claude Code v2.1.181, the block is stable for the lifetime of a conversation when requests route through a custom base URL, so a gateway-side prompt cache keyed on the full request body works without disabling it. Before v2.1.181 the block included a per-request token; on those versions, set `CLAUDE_CODE_ATTRIBUTION_HEADER=0` if your gateway implements such a cache.105{/* min-version: 2.1.181 */}From Claude Code v2.1.181, the block is stable for the lifetime of a conversation when requests route through a custom base URL, so a gateway-side prompt cache keyed on the full request body works without disabling it, and any provider your gateway forwards to receives a stable prompt prefix. Before v2.1.181 the block included a per-request token that changed the start of the system prompt on every request. On those versions, set `CLAUDE_CODE_ATTRIBUTION_HEADER=0` when your gateway does either of these:

106 

107* Implements a prompt cache keyed on the request body.

108* Forwards requests to a third-party provider such as Amazon Bedrock, Microsoft Foundry, or Google Cloud's Agent Platform, in the Anthropic Messages format or the provider's own, where the changing prefix reduces prompt-cache reuse on that provider.

106 109 

107## Feature pass-through110## Feature pass-through

108 111 


110 113 

111Capabilities that add body fields pair them with a beta header, and the pair travels together. A gateway that strips the header while passing the body, or forwards an Anthropic-format body to an upstream with a different schema, produces hard `400` errors; only when both halves are absent together does the feature turn off quietly. A gateway that rewrites or redacts request bodies for content inspection breaks the pairing the same way stripping does, so inspect without modifying. The table notes where a feature deviates from the pairing.114Capabilities that add body fields pair them with a beta header, and the pair travels together. A gateway that strips the header while passing the body, or forwards an Anthropic-format body to an upstream with a different schema, produces hard `400` errors; only when both halves are absent together does the feature turn off quietly. A gateway that rewrites or redacts request bodies for content inspection breaks the pairing the same way stripping does, so inspect without modifying. The table notes where a feature deviates from the pairing.

112 115 

113Fine-grained tool streaming is one of the direct-connection defaults: it is off by default whenever requests route through a custom base URL, and a gateway receives it when developers set [`CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING=1`](/en/env-vars).116Fine-grained tool streaming is one of the direct-connection defaults: it is off by default whenever requests route through a custom base URL, and a gateway receives it when developers set [`CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING=1`](/docs/en/env-vars).

114 117 

115| Feature | Header and body pair | Symptom when broken | Remediation |118| Feature | Header and body pair | Symptom when broken | Remediation |

116| :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------- |119| :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------- |

117| [Adaptive reasoning](/en/model-config#adjust-effort-level) | No beta header. Claude Code sends `thinking: {"type": "adaptive"}` for Claude 4.6 and later, and treats model names it doesn't recognize, such as gateway aliases, as current models that receive the field | `400` naming the `thinking` field or the `adaptive` tag when the upstream model build doesn't accept it | Upgrade the upstream. On Opus 4.6 and Sonnet 4.6, developers can set `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1` instead |120| [Adaptive reasoning](/docs/en/model-config#adjust-effort-level) | No beta header. Claude Code sends `thinking: {"type": "adaptive"}` for Claude 4.6 and later, and treats model names it doesn't recognize, such as gateway aliases, as current models that receive the field | `400` naming the `thinking` field or the `adaptive` tag when the upstream model build doesn't accept it | Upgrade the upstream. On Opus 4.6 and Sonnet 4.6, developers can set `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1` instead |

118| [Context management](https://platform.claude.com/docs/en/build-with-claude/context-editing) | Context management beta header pairs with the `context_management` body field | `400` with `Extra inputs are not permitted`. Common when a gateway accepts Anthropic-format requests but forwards them to Amazon Bedrock | Forward both, or [`CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`](/en/env-vars) |121| [Context management](https://platform.claude.com/docs/en/build-with-claude/context-editing) | Context management beta header pairs with the `context_management` body field | `400` with `Extra inputs are not permitted`. Common when a gateway accepts Anthropic-format requests but forwards them to Amazon Bedrock | Forward both, or [`CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`](/docs/en/env-vars) |

119| [Extended context](https://platform.claude.com/docs/en/build-with-claude/context-windows#context-window-sizes-by-model) and [interleaved thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#interleaved-thinking) | Beta headers only, no body field | Silently unavailable when the header is stripped; the upstream never sees the capability request | Forward `anthropic-beta` verbatim |122| [Extended context](https://platform.claude.com/docs/en/build-with-claude/context-windows#context-window-sizes-by-model) and [interleaved thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#interleaved-thinking) | Beta headers only, no body field | Silently unavailable when the header is stripped; the upstream never sees the capability request | Forward `anthropic-beta` verbatim |

120| Beta [tool fields](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview) | Tool-related beta headers pair with tool schema fields such as `strict` and `defer_loading` | `400` naming the unrecognized tool schema field when the body passes through without its header | Forward both, or `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1` |123| Beta [tool fields](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview) | Tool-related beta headers pair with tool schema fields such as `strict` and `defer_loading` | `400` naming the unrecognized tool schema field when the body passes through without its header | Forward both, or `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1` |

121| [Effort](https://platform.claude.com/docs/en/build-with-claude/effort) and [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs) | The `output_config` body field carries effort, structured-output format, and task budget settings; each pairs with its own beta header | `400` naming `output_config`, often `Extra inputs are not permitted`, on Amazon Bedrock and Google Cloud's Agent Platform upstreams | Forward the field and its headers together |124| [Effort](https://platform.claude.com/docs/en/build-with-claude/effort) and [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs) | The `output_config` body field carries effort, structured-output format, and task budget settings; each pairs with its own beta header | `400` naming `output_config`, often `Extra inputs are not permitted`, on Amazon Bedrock and Google Cloud's Agent Platform upstreams | Forward the field and its headers together |

122| [Token counting](https://platform.claude.com/docs/en/build-with-claude/token-counting) | No beta pairing; uses the `count_tokens` endpoint | Claude Code falls back to estimating context usage locally | Expose the endpoint if you want exact counts |125| [Token counting](https://platform.claude.com/docs/en/build-with-claude/token-counting) | No beta pairing; uses the `count_tokens` endpoint | Claude Code falls back to estimating context usage locally | Expose the endpoint if you want exact counts |

123 126 

124The `ANTHROPIC_DEFAULT_*_MODEL_SUPPORTED_CAPABILITIES` [variables](/en/model-config) declare model capabilities only in the provider configurations: `CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX`, `CLAUDE_CODE_USE_FOUNDRY`, and [`CLAUDE_CODE_USE_MANTLE`](/en/amazon-bedrock#use-the-mantle-endpoint). They have no effect behind an `ANTHROPIC_BASE_URL` gateway.127The `ANTHROPIC_DEFAULT_*_MODEL_SUPPORTED_CAPABILITIES` [variables](/docs/en/model-config) declare model capabilities only in the provider configurations: `CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX`, `CLAUDE_CODE_USE_FOUNDRY`, and [`CLAUDE_CODE_USE_MANTLE`](/docs/en/amazon-bedrock#use-the-mantle-endpoint). They have no effect behind an `ANTHROPIC_BASE_URL` gateway.

125 128 

126### Automatic retry and error forwarding129### Automatic retry and error forwarding

127 130 


139 142 

140When `ANTHROPIC_BASE_URL` points at a gateway that exposes the Anthropic Messages format, Claude Code can query the gateway's `/v1/models` endpoint at startup and add the returned models to the `/model` picker.143When `ANTHROPIC_BASE_URL` points at a gateway that exposes the Anthropic Messages format, Claude Code can query the gateway's `/v1/models` endpoint at startup and add the returned models to the `/model` picker.

141 144 

142Developers enable it by setting [`CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1`](/en/env-vars), in their own environment or through managed settings. Discovery is off by default so that gateways backed by a shared API key don't surface every model the key can access to every user. This requires Claude Code v2.1.129 or later.145Developers enable it by setting [`CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1`](/docs/en/env-vars), in their own environment or through managed settings. Discovery is off by default so that gateways backed by a shared API key don't surface every model the key can access to every user. This requires Claude Code v2.1.129 or later.

143 146 

144### When discovery runs147### When discovery runs

145 148 


147 150 

148* Any `CLAUDE_CODE_USE_*` provider variable is set, even if `ANTHROPIC_BASE_URL` is also set151* Any `CLAUDE_CODE_USE_*` provider variable is set, even if `ANTHROPIC_BASE_URL` is also set

149* `ANTHROPIC_BASE_URL` is unset or points at `api.anthropic.com`152* `ANTHROPIC_BASE_URL` is unset or points at `api.anthropic.com`

150* Nonessential traffic is disabled, through [`CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`](/en/env-vars) or organization policy153* Nonessential traffic is disabled, through [`CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`](/docs/en/env-vars) or organization policy

151 154 

152### Request and response155### Request and response

153 156 


156The discovery request sends exactly one credential header:159The discovery request sends exactly one credential header:

157 160 

158* `ANTHROPIC_AUTH_TOKEN` as a bearer token, when set161* `ANTHROPIC_AUTH_TOKEN` as a bearer token, when set

159* Otherwise the resolved API key, including an [`apiKeyHelper`](/en/llm-gateway-connect#rotate-credentials-with-apikeyhelper) value, in the `x-api-key` header162* Otherwise the resolved API key, including an [`apiKeyHelper`](/docs/en/llm-gateway-connect#rotate-credentials-with-apikeyhelper) value, in the `x-api-key` header

160 163 

161This differs from inference requests, which send a helper value in both headers. A gateway that authenticates `/v1/models` must accept `x-api-key` for helper deployments. Any headers from `ANTHROPIC_CUSTOM_HEADERS` are included as well.164This differs from inference requests, which send a helper value in both headers. A gateway that authenticates `/v1/models` must accept `x-api-key` for helper deployments. Any headers from `ANTHROPIC_CUSTOM_HEADERS` are included as well.

162 165 


173 176 

174### Picker entries and caching177### Picker entries and caching

175 178 

176The picker is the interactive model list that opens when a developer runs `/model` in Claude Code. Each discovered entry is labeled "From gateway" and uses `display_name` when provided. The [`availableModels` managed setting](/en/settings#available-settings) bounds what discovery can add.179The picker is the interactive model list that opens when a developer runs `/model` in Claude Code. Each discovered entry is labeled "From gateway" and uses `display_name` when provided. The [`availableModels` managed setting](/docs/en/settings#available-settings) bounds what discovery can add.

177 180 

178A discovered ID is skipped when it exactly matches a row already in the picker, or when both the discovered and existing IDs resolve to [Fable](/en/model-config#work-with-fable-5). {/* min-version: 2.1.197 */}As of Claude Code v2.1.197, a discovered explicit ID is also folded into a built-in entry when both resolve to the same model. Built-in rows are keyed on aliases such as `sonnet`, so a discovered explicit ID of the model the alias currently resolves to, such as `claude-sonnet-5`, collapses into the `sonnet` row, while an ID the alias doesn't resolve to, such as `claude-sonnet-4-6`, still adds its own "From gateway" row alongside the built-in entry.181A discovered ID is skipped when it exactly matches a row already in the picker, or when both the discovered and existing IDs resolve to [Fable](/docs/en/model-config#work-with-fable-5). {/* min-version: 2.1.197 */}As of Claude Code v2.1.197, a discovered explicit ID is also folded into a built-in entry when both resolve to the same model. Built-in rows are keyed on aliases such as `sonnet`, so a discovered explicit ID of the model the alias currently resolves to, such as `claude-sonnet-5`, collapses into the `sonnet` row, while an ID the alias doesn't resolve to, such as `claude-sonnet-4-6`, still adds its own "From gateway" row alongside the built-in entry.

179 182 

180Results are cached to `~/.claude/cache/gateway-models.json`, or `%USERPROFILE%\.claude\cache\gateway-models.json` on Windows, and refreshed on each startup. If the request fails or the gateway doesn't implement `/v1/models`, the picker falls back to the cached list from the previous startup or to the built-in model list. If your gateway serves Claude models under aliases that don't match the discovery filter, developers can add those aliases manually with the [model configuration](/en/model-config) variables.183Results are cached to `~/.claude/cache/gateway-models.json`, or `%USERPROFILE%\.claude\cache\gateway-models.json` on Windows, and refreshed on each startup. If you set [`CLAUDE_CONFIG_DIR`](/docs/en/env-vars), the cache lives under that directory instead. If the request fails or the gateway doesn't implement `/v1/models`, the picker falls back to the cached list from the previous startup or to the built-in model list. If your gateway serves Claude models under aliases that don't match the discovery filter, developers can add those aliases manually with the [model configuration](/docs/en/model-config) variables.

181 184 

182## Related resources185## Related resources

183 186 

184For the rest of the gateway documentation set and the underlying API references:187For the rest of the gateway documentation set and the underlying API references:

185 188 

186* [Gateway overview](/en/gateways): what a gateway is and how to choose between Claude apps gateway and another product189* [Gateway overview](/docs/en/gateways): what a gateway is and how to choose between Claude apps gateway and another product

187* [Other LLM gateways](/en/llm-gateway): how to roll out a gateway your organization runs and how it interacts with claude.ai subscriptions190* [Other LLM gateways](/docs/en/llm-gateway): how to roll out a gateway your organization runs and how it interacts with claude.ai subscriptions

188* [Roll out an LLM gateway for your organization](/en/llm-gateway-rollout): the admin checklist that uses this contract191* [Roll out an LLM gateway for your organization](/docs/en/llm-gateway-rollout): the admin checklist that uses this contract

189* [Connect Claude Code to an LLM gateway](/en/llm-gateway-connect): per-developer configuration and the troubleshooting table192* [Connect Claude Code to an LLM gateway](/docs/en/llm-gateway-connect): per-developer configuration and the troubleshooting table

190* [Beta headers reference](https://platform.claude.com/docs/en/api/beta-headers): the current set of `anthropic-beta` values193* [Beta headers reference](https://platform.claude.com/docs/en/api/beta-headers): the current set of `anthropic-beta` values

191* [Messages API](https://platform.claude.com/docs/en/api/messages): the API format an Anthropic-format gateway implements194* [Messages API](https://platform.claude.com/docs/en/api/messages): the API format an Anthropic-format gateway implements

mcp.md +34 −11

Details

85 The SSE (Server-Sent Events) transport is deprecated. Use HTTP servers instead, where available.85 The SSE (Server-Sent Events) transport is deprecated. Use HTTP servers instead, where available.

86</Warning>86</Warning>

87 87 

88Some services still expose only an SSE endpoint. Use the same command as the HTTP transport, with `--transport sse`:

89 

88```bash theme={null}90```bash theme={null}

89# Basic syntax91# Basic syntax

90claude mcp add --transport sse <name> <url>92claude mcp add --transport sse <name> <url>


153claude mcp list155claude mcp list

154 156 

155# Get details for a specific server157# Get details for a specific server

156claude mcp get github158claude mcp get notion

157 159 

158# Remove a server160# Remove a server

159claude mcp remove github161claude mcp remove notion

160 162 

161# (within Claude Code) Check server status163# (within Claude Code) Check server status

162/mcp164/mcp

163```165```

164 166 

167`claude mcp add` confirms a successful add by printing an `Added ...` line, which means the configuration was written. `claude mcp list` then shows a health status next to each server it lists, such as `✔ Connected`, `! Needs authentication`, or `✘ Failed to connect`. A failure status means Claude Code couldn't connect to that server, not that the list command failed.

168 

165Project-scoped servers from `.mcp.json` that are awaiting your approval appear in `claude mcp list` and `claude mcp get <name>` as ``⏸ Pending approval (run `claude` to approve)``. Run `claude` interactively to review and approve them. `claude mcp get <name>` shows rejected servers as `✘ Rejected (see disabledMcpjsonServers in settings)`.169Project-scoped servers from `.mcp.json` that are awaiting your approval appear in `claude mcp list` and `claude mcp get <name>` as ``⏸ Pending approval (run `claude` to approve)``. Run `claude` interactively to review and approve them. `claude mcp get <name>` shows rejected servers as `✘ Rejected (see disabledMcpjsonServers in settings)`.

166 170 

171WebSocket servers don't appear in `claude mcp list` output. Use `claude mcp get <name>` or the `/mcp` panel to check them.

172 

167As of v2.1.196, `claude mcp list` and `claude mcp get` read `.mcp.json` approvals only from settings files that aren't checked into the repository until you trust the workspace by running `claude` in it and accepting the workspace trust dialog. A cloned repository can't approve its own servers: [`enableAllProjectMcpServers` or `enabledMcpjsonServers`](/docs/en/settings#available-settings) committed to the project's `.claude/settings.json` is ignored in an untrusted folder, and the server stays at `⏸ Pending approval` instead of being connected and health-checked.173As of v2.1.196, `claude mcp list` and `claude mcp get` read `.mcp.json` approvals only from settings files that aren't checked into the repository until you trust the workspace by running `claude` in it and accepting the workspace trust dialog. A cloned repository can't approve its own servers: [`enableAllProjectMcpServers` or `enabledMcpjsonServers`](/docs/en/settings#available-settings) committed to the project's `.claude/settings.json` is ignored in an untrusted folder, and the server stays at `⏸ Pending approval` instead of being connected and health-checked.

168 174 

169Approvals from these sources still apply in an untrusted folder:175Approvals from these sources still apply in an untrusted folder:


180 186 

181A remote server whose configuration has an empty `url` shows as `not configured` in `/mcp`, in `claude mcp list`, and in the [`/plugin`](/docs/en/plugins) manager, and Claude Code doesn't attempt to connect to it. A plugin can include a placeholder entry like this for a connector you configure later, so Claude Code doesn't report it as an error or a setup issue. The server's detail view in `/mcp` reads `No URL configured for this server`; set the entry's `url` to connect it. Before v2.1.208, Claude Code reported an empty `url` as a configuration issue with a prompt to reconnect.187A remote server whose configuration has an empty `url` shows as `not configured` in `/mcp`, in `claude mcp list`, and in the [`/plugin`](/docs/en/plugins) manager, and Claude Code doesn't attempt to connect to it. A plugin can include a placeholder entry like this for a connector you configure later, so Claude Code doesn't report it as an error or a setup issue. The server's detail view in `/mcp` reads `No URL configured for this server`; set the entry's `url` to connect it. Before v2.1.208, Claude Code reported an empty `url` as a configuration issue with a prompt to reconnect.

182 188 

183If your request needs tools from a server that is still connecting in the background, Claude waits for that server before continuing. With [tool search](#scale-with-mcp-tool-search) enabled, which is the default, the wait happens inside the `ToolSearch` call. In configurations without tool search, such as Google Cloud's Agent Platform, a custom `ANTHROPIC_BASE_URL`, or `ENABLE_TOOL_SEARCH=false`, Claude uses the `WaitForMcpServers` tool instead.189If your request needs tools from a server that is still connecting in the background, Claude waits for that server before continuing. With [tool search](#scale-with-mcp-tool-search) enabled, which is the default, the wait happens inside the `ToolSearch` call. In configurations without tool search, such as Google Cloud's Agent Platform, a custom `ANTHROPIC_BASE_URL`, or `ENABLE_TOOL_SEARCH=false`, Claude uses the `WaitForMcpServers` tool instead. A Microsoft Foundry [deployment hosted on Azure](https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry#hosting-options) starts on the tool-search path rather than with `WaitForMcpServers`, since Claude Code discovers the deployment's server-side rejection only from the API; after Claude Code switches that deployment to [upfront loading](#scale-with-mcp-tool-search), tools from a server that finishes connecting become available on Claude's next request.

184 190 

185Some server names are reserved for Claude Code's built-in servers: `workspace`, `claude-in-chrome`, `computer-use`, `Claude Preview`, and `Claude Browser`. If your configuration defines a server with a reserved name, Claude Code skips it at load time and shows a warning asking you to rename it. `claude mcp add` rejects a reserved name with an error.191Some server names are reserved for Claude Code's built-in servers: `workspace`, `claude-in-chrome`, `computer-use`, `Claude Preview`, and `Claude Browser`. If your configuration defines a server with a reserved name, Claude Code skips it at load time and shows a warning asking you to rename it. `claude mcp add` rejects a reserved name with an error.

186 192 


393 399 

394```bash theme={null}400```bash theme={null}

395# Add a project-scoped server401# Add a project-scoped server

396claude mcp add --transport http paypal --scope project https://mcp.paypal.com/mcp402claude mcp add --transport http shared-server --scope project https://example.com/mcp

397```403```

398 404 

399The resulting `.mcp.json` file follows a standardized format:405The resulting `.mcp.json` file follows a standardized format:


402{408{

403 "mcpServers": {409 "mcpServers": {

404 "shared-server": {410 "shared-server": {

405 "command": "/path/to/server",411 "type": "http",

406 "args": [],412 "url": "https://example.com/mcp"

407 "env": {}

408 }413 }

409 }414 }

410}415}


433 438 

434The three scopes match duplicates by name. Plugins and connectors match by endpoint, so one that points at the same URL or command as a server above is treated as a duplicate.439The three scopes match duplicates by name. Plugins and connectors match by endpoint, so one that points at the same URL or command as a server above is treated as a duplicate.

435 440 

441If you open a local session in the [Desktop app's Code tab](/docs/en/desktop#mcp-servers-from-the-claude-desktop-chat-app) with the same stdio server name at the top level of `~/.claude.json` (user scope) and in `.mcp.json`, the Code tab uses the `~/.claude.json` definition.

442 

436### Environment variable expansion in `.mcp.json`443### Environment variable expansion in `.mcp.json`

437 444 

438Claude Code supports environment variable expansion in `.mcp.json` files, allowing teams to share configurations while maintaining flexibility for machine-specific paths and sensitive values like API keys.445Claude Code supports environment variable expansion in `.mcp.json` files, allowing teams to share configurations while maintaining flexibility for machine-specific paths and sensitive values like API keys.


473 480 

474### Example: Monitor errors with Sentry481### Example: Monitor errors with Sentry

475 482 

483Sentry's remote MCP server gives Claude access to the errors your applications report to Sentry. It authenticates through OAuth rather than an API key, so you don't pass a credential when you add it.

484 

485If you already added the `sentry` server in the [MCP quickstart](/docs/en/mcp-quickstart), skip this command: running `claude mcp add` again with the same server name at the same scope fails with `MCP server sentry already exists in local config`.

486 

476```bash theme={null}487```bash theme={null}

477claude mcp add --transport http sentry https://mcp.sentry.dev/mcp488claude mcp add --transport http sentry https://mcp.sentry.dev/mcp

478```489```


483/mcp494/mcp

484```495```

485 496 

497Follow the sign-in steps in your browser. Once you're signed in, the `sentry` server shows `connected` in the `/mcp` menu.

498 

486Then debug production issues:499Then debug production issues:

487 500 

488```text theme={null}501```text theme={null}


524 537 

525### Example: Query your PostgreSQL database538### Example: Query your PostgreSQL database

526 539 

540[DBHub](https://github.com/bytebase/dbhub), the `@bytebase/dbhub` package, is an MCP server that connects Claude to a relational database through the connection string you pass in `--dsn`. Use a read-only database user in the connection string so the queries Claude runs can't modify data:

541 

527```bash theme={null}542```bash theme={null}

528claude mcp add --transport stdio db -- npx -y @bytebase/dbhub \543claude mcp add --transport stdio db -- npx -y @bytebase/dbhub \

529 --dsn "postgresql://readonly:pass@prod.db.com:5432/analytics"544 --dsn "postgresql://readonly:pass@prod.db.com:5432/analytics"

530```545```

531 546 

547To confirm the server starts, run `/mcp` and check that `db` shows `connected`.

548 

532Then query your database naturally:549Then query your database naturally:

533 550 

534```text theme={null}551```text theme={null}


563 580 

564<Steps>581<Steps>

565 <Step title="Add the server that requires authentication">582 <Step title="Add the server that requires authentication">

566 For example:583 If you already added this server in the [Sentry example](#example-monitor-errors-with-sentry) or the [MCP quickstart](/docs/en/mcp-quickstart), skip this step: running `claude mcp add` again with the same server name at the same scope fails with `MCP server sentry already exists in local config`. Otherwise, run:

567 584 

568 ```bash theme={null}585 ```bash theme={null}

569 claude mcp add --transport http sentry https://mcp.sentry.dev/mcp586 claude mcp add --transport http sentry https://mcp.sentry.dev/mcp


944claude mcp serve961claude mcp serve

945```962```

946 963 

964The command prints nothing when it starts. A stdio MCP server communicates over stdin and stdout, so a silent, blocked terminal means the server is running and waiting for a client to connect.

965 

947You can use this in Claude Desktop by adding this configuration to claude\_desktop\_config.json:966You can use this in Claude Desktop by adding this configuration to claude\_desktop\_config.json:

948 967 

949```json theme={null}968```json theme={null}


1137 1156 

1138Tool search keeps MCP context usage low by deferring tool definitions until Claude needs them. Only tool names and server instructions load at session start, so adding more MCP servers has minimal impact on your context window. Claude Code doesn't impose a fixed per-server tool cap; the practical limit is your context window budget.1157Tool search keeps MCP context usage low by deferring tool definitions until Claude needs them. Only tool names and server instructions load at session start, so adding more MCP servers has minimal impact on your context window. Claude Code doesn't impose a fixed per-server tool cap; the practical limit is your context window budget.

1139 1158 

1159<Note>

1160 Tool search isn't supported on Microsoft Foundry [deployments hosted on Azure](https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry#hosting-options), which reject it server-side: Claude Code detects the rejection and loads MCP tools upfront for that deployment instead. [`ENABLE_TOOL_SEARCH`](#configure-tool-search) can't override this, since the rejection comes from the deployment itself.

1161</Note>

1162 

1140### How it works1163### How it works

1141 1164 

1142Tool search is enabled by default. MCP tools are deferred rather than loaded into context upfront, and Claude uses a search tool to discover relevant ones when a task needs them. Only the tools Claude actually uses enter context. From your perspective, MCP tools work exactly as before.1165Tool search is enabled by default. MCP tools are deferred rather than loaded into context upfront, and Claude uses a search tool to discover relevant ones when a task needs them. Only the tools Claude actually uses enter context. From your perspective, MCP tools work exactly as before.


1166Control tool search behavior with the `ENABLE_TOOL_SEARCH` environment variable:1189Control tool search behavior with the `ENABLE_TOOL_SEARCH` environment variable:

1167 1190 

1168| Value | Behavior |1191| Value | Behavior |

1169| :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |1192| :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

1170| (unset) | All MCP tools deferred and loaded on demand. Falls back to loading upfront on Google Cloud's Agent Platform or when `ANTHROPIC_BASE_URL` is a non-first-party host |1193| (unset) | All MCP tools deferred and loaded on demand. Falls back to loading upfront on Google Cloud's Agent Platform, when `ANTHROPIC_BASE_URL` is a non-first-party host, or on a Microsoft Foundry deployment hosted on Azure |

1171| `true` | All MCP tools deferred. Claude Code sends the beta header even on Google Cloud's Agent Platform and through proxies. Requests fail on Google Cloud's Agent Platform models earlier than Sonnet 4.5 or Opus 4.5, or on proxies that don't support `tool_reference` blocks |1194| `true` | All MCP tools deferred, except on a Microsoft Foundry deployment hosted on Azure, where the server-side rejection still forces upfront loading. Claude Code sends the beta header even on Google Cloud's Agent Platform and through proxies. Requests fail on Google Cloud's Agent Platform models earlier than Sonnet 4.5 or Opus 4.5, or on proxies that don't support `tool_reference` blocks |

1172| `auto` | Threshold mode: tools load upfront if they fit within 10% of the context window, deferred otherwise |1195| `auto` | Threshold mode: tools load upfront if they fit within 10% of the context window, deferred otherwise |

1173| `auto:N` | Threshold mode with a custom percentage, where `N` is 0-100. For example, `auto:5` for 5% |1196| `auto:N` | Threshold mode with a custom percentage, where `N` is 0-100. For example, `auto:5` for 5% |

1174| `false` | All MCP tools loaded upfront, no deferral |1197| `false` | All MCP tools loaded upfront, no deferral |

mobile.md +21 −20

Details

6 6 

7> Start, monitor, and steer Claude Code tasks from your phone with the Claude app for iOS and Android.7> Start, monitor, and steer Claude Code tasks from your phone with the Claude app for iOS and Android.

8 8 

9The Claude app for [iOS](https://apps.apple.com/us/app/claude-by-anthropic/id6473753684) and [Android](https://play.google.com/store/apps/details?id=com.anthropic.claude) is a client for Claude Code sessions rather than a place where code runs. From your phone you reach [cloud sessions](#start-and-monitor-cloud-sessions) on Anthropic-managed infrastructure, a session running on your own machine through [Remote Control](#continue-a-local-session-with-remote-control), or the Desktop app through [Dispatch](/en/desktop#sessions-from-dispatch).9The Claude app for [iOS](https://apps.apple.com/us/app/claude-by-anthropic/id6473753684) and [Android](https://play.google.com/store/apps/details?id=com.anthropic.claude) is a client for Claude Code sessions rather than a place where code runs. From your phone you reach [cloud sessions](#start-and-monitor-cloud-sessions) on Anthropic-managed infrastructure, a session running on your own machine through [Remote Control](#continue-a-local-session-with-remote-control), or the Desktop app through [Dispatch](/docs/en/desktop#sessions-from-dispatch).

10 10 

11<Note>11<Note>

12 Claude Code doesn't have a separate mobile app: cloud sessions and Remote Control both live in the **Code** tab in the Claude app, and Dispatch is a task you message in the app.12 Claude Code doesn't have a separate mobile app: cloud sessions and Remote Control both live in the **Code** tab in the Claude app, and Dispatch is a task you message in the app.


28 </Step>28 </Step>

29 29 

30 <Step title="Open the Code tab">30 <Step title="Open the Code tab">

31 Tap **Code** in the app's navigation to reach your sessions, or open [claude.ai/code/new](https://claude.ai/code/new) on your phone to start a new Code session in the app. If you don't see the Code tab, your plan or organization may not include these features; see [availability by subscription plan](/en/feature-availability#availability-by-subscription-plan).31 Tap **Code** in the app's navigation to reach your sessions, or open [claude.ai/code/new](https://claude.ai/code/new) on your phone to start a new Code session in the app. If you don't see the Code tab, your plan or organization may not include these features; see [availability by subscription plan](/docs/en/feature-availability#availability-by-subscription-plan).

32 </Step>32 </Step>

33</Steps>33</Steps>

34 34 


38 38 

39| Feature | What you connect to | When to use |39| Feature | What you connect to | When to use |

40| :--------------------------------------------------- | :-------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------- |40| :--------------------------------------------------- | :-------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------- |

41| [Claude Code on the web](/en/claude-code-on-the-web) | A cloud session on Anthropic-managed infrastructure | Your repository is on GitHub and the task should keep running after you put your phone away. See the [web quickstart](/en/web-quickstart) to set up. |41| [Claude Code on the web](/docs/en/claude-code-on-the-web) | A cloud session on Anthropic-managed infrastructure | Your repository is on GitHub and the task should keep running after you put your phone away. See the [web quickstart](/docs/en/web-quickstart) to set up. |

42| [Remote Control](/en/remote-control) | A Claude Code session running on your computer | The work needs your local filesystem, tools, or MCP servers. |42| [Remote Control](/docs/en/remote-control) | A Claude Code session running on your computer | The work needs your local filesystem, tools, or MCP servers. |

43| [Dispatch](/en/desktop#sessions-from-dispatch) | The Desktop app on your computer | You want to message a task and let Dispatch decide how to run it. Requires a Pro or Max plan. |43| [Dispatch](/docs/en/desktop#sessions-from-dispatch) | The Desktop app on your computer | You want to message a task and let Dispatch decide how to run it. Requires a Pro or Max plan. |

44 44 

45If your computer will be off, use cloud sessions: they run on Anthropic's infrastructure and continue with your laptop closed. Remote Control and Dispatch drive your own machine, so it needs to stay on with Claude Code or the Desktop app running. If your machine sleeps during a Remote Control session, the session reconnects when it comes back online.45If your computer will be off, use cloud sessions: they run on Anthropic's infrastructure and continue with your laptop closed. Remote Control and Dispatch drive your own machine, so it needs to stay on with Claude Code or the Desktop app running. If your machine sleeps during a Remote Control session, the session reconnects when it comes back online.

46 46 

47For a fuller comparison that also covers Channels, Slack, and scheduled tasks, see [work when you are away from your terminal](/en/platforms#work-when-you-are-away-from-your-terminal).47For a fuller comparison that also covers Channels, Slack, and scheduled tasks, see [work when you are away from your terminal](/docs/en/platforms#work-when-you-are-away-from-your-terminal).

48 48 

49Cloud sessions and Remote Control run from the **Code** tab and are covered below. For Dispatch, which you message as a task in the app, see [sessions from Dispatch](/en/desktop#sessions-from-dispatch).49Cloud sessions and Remote Control run from the **Code** tab and are covered below. For Dispatch, which you message as a task in the app, see [sessions from Dispatch](/docs/en/desktop#sessions-from-dispatch).

50 50 

51### Start and monitor cloud sessions51### Start and monitor cloud sessions

52 52 

53Claude Code on the web runs tasks on Anthropic-managed cloud infrastructure, so a session continues after you put your phone away. From the Code tab, select a repository and branch, describe the task, and submit it. Sessions persist across devices: a task you start on your laptop is ready to review from your phone, and one you start from your phone is waiting when you're back at your desk.53Claude Code on the web runs tasks on Anthropic-managed cloud infrastructure, so a session continues after you put your phone away. From the Code tab, select a repository and branch, describe the task, and submit it. Sessions persist across devices: a task you start on your laptop is ready to review from your phone, and one you start from your phone is waiting when you're back at your desk.

54 54 

55Open a session in the app to check progress, answer Claude's questions, or steer it in a new direction. You can also tell Claude to [watch a pull request](/en/claude-code-on-the-web#auto-fix-pull-requests) and fix CI failures or review comments as they arrive. To connect GitHub and create your first environment, follow the [web quickstart](/en/web-quickstart), and see [Claude Code on the web](/en/claude-code-on-the-web) for everything cloud sessions can do.55Open a session in the app to check progress, answer Claude's questions, or steer it in a new direction. You can also tell Claude to [watch a pull request](/docs/en/claude-code-on-the-web#auto-fix-pull-requests) and fix CI failures or review comments as they arrive. To connect GitHub and set up your environment, follow the [web quickstart](/docs/en/web-quickstart), and see [Claude Code on the web](/docs/en/claude-code-on-the-web) for everything cloud sessions can do.

56 56 

57### Continue a local session with Remote Control57### Continue a local session with Remote Control

58 58 

59Remote Control connects the Claude app to a Claude Code session running on your machine, so code execution and filesystem access stay local while you drive the session from your phone. Start the session on your computer with `claude remote-control`, or run `/remote-control` in a session that's already open. Then scan the session QR code the terminal can display, or open the Claude app, tap **Code**, and pick the session from the list. See [connect from another device](/en/remote-control#connect-from-another-device) for each option.59Remote Control connects the Claude app to a Claude Code session running on your machine, so code execution and filesystem access stay local while you drive the session from your phone. Start the session on your computer with `claude remote-control`, or run `/remote-control` in a session that's already open. Then scan the session QR code the terminal can display, or open the Claude app, tap **Code**, and pick the session from the list. See [connect from another device](/docs/en/remote-control#connect-from-another-device) for each option.

60 60 

61Attachments you add in the Claude app reach the local session too: Claude Code downloads the image or file to your machine and passes it to Claude as an `@` file reference. For requirements, invocation modes, and troubleshooting, see the [Remote Control overview](/en/remote-control).61Attachments you add in the Claude app reach the local session too: Claude Code downloads the image or file to your machine and passes it to Claude as an `@` file reference. For requirements, invocation modes, and troubleshooting, see the [Remote Control overview](/docs/en/remote-control).

62 62 

63### Get push notifications63### Get push notifications

64 64 

65When Remote Control is active, Claude can send push notifications to your phone, typically when a long-running task finishes or when it needs a decision from you. You can also ask for one in your prompt, such as `notify me when the tests finish`. See [mobile push notifications](/en/remote-control#mobile-push-notifications) for the two `/config` toggles and delivery troubleshooting.65When Remote Control is active, Claude can send push notifications to your phone, typically when a long-running task finishes or when it needs a decision from you. You can also ask for one in your prompt, such as `notify me when the tests finish`. See [mobile push notifications](/docs/en/remote-control#mobile-push-notifications) for the two `/config` toggles and delivery troubleshooting.

66 66 

67Dispatch sends its own notification when a Code session it spawned finishes or needs your approval, described in [sessions from Dispatch](/en/desktop#sessions-from-dispatch).67Dispatch sends its own notification when a Code session it spawned finishes or needs your approval, described in [sessions from Dispatch](/docs/en/desktop#sessions-from-dispatch).

68 68 

69## Limitations69## Limitations

70 70 

71The mobile client covers most of what a session needs, with a few limitations:71The mobile client covers most of what a session needs, with a few limitations:

72 72 

73* **Local-only commands**: commands that only run in the terminal interface, such as `/plugin` and `/resume`, don't work from the app. The [Remote Control limitations](/en/remote-control#limitations) list the commands that do work from mobile and how their behavior differs.73* **Local-only commands**: commands that only run in the terminal interface, such as `/plugin` and `/resume`, don't work from the app. The [Remote Control limitations](/docs/en/remote-control#limitations) list the commands that do work from mobile and how their behavior differs.

74* **Permission modes**: cloud sessions offer Accept edits, Plan, and Auto in the mode dropdown, and Remote Control sessions offer Manual, Accept edits, and Plan. You can't select Bypass permissions from the app in either case, and you can't select Auto for a Remote Control session. See [switch permission modes](/en/permission-modes#switch-permission-modes).74* **Permission modes**: cloud sessions offer Accept edits, Plan, and Auto in the mode dropdown, and Remote Control sessions offer Manual, Accept edits, and Plan. You can't select Bypass permissions from the app in either case, and you can't select Auto for a Remote Control session. See [switch permission modes](/docs/en/permission-modes#switch-permission-modes).

75* **Dispatch plans**: Dispatch requires a Pro or Max plan and isn't available on Team or Enterprise.75* **Dispatch plans**: Dispatch requires a Pro or Max plan and isn't available on Team or Enterprise.

76 76 

77## Related resources77## Related resources

78 78 

79* [Platforms and integrations](/en/platforms): compare every surface Claude Code runs on79* [Platforms and integrations](/docs/en/platforms): compare every surface Claude Code runs on

80* [Claude Code on the web](/en/claude-code-on-the-web): how cloud sessions run, network access, and moving work to and from your terminal80* [Claude Code on the web](/docs/en/claude-code-on-the-web): how cloud sessions run and how to move work to and from your terminal

81* [Remote Control](/en/remote-control): continue a local session from any device81* [Configure cloud environments](/docs/en/cloud-environments): network access levels, environment variables, and setup scripts for cloud sessions

82* [Sessions from Dispatch](/en/desktop#sessions-from-dispatch): how Dispatch tasks become Code sessions in the Desktop app82* [Remote Control](/docs/en/remote-control): continue a local session from any device

83* [Channels](/en/channels): ask Claude something from your phone via Telegram, Discord, or iMessage while the work runs on your machine83* [Sessions from Dispatch](/docs/en/desktop#sessions-from-dispatch): how Dispatch tasks become Code sessions in the Desktop app

84* [Claude Code in Slack](/en/slack): delegate coding tasks from your Slack workspace by mentioning `@Claude`84* [Channels](/docs/en/channels): ask Claude something from your phone via Telegram, Discord, or iMessage while the work runs on your machine

85* [Claude Code in Slack](/docs/en/slack): delegate coding tasks from your Slack workspace by mentioning `@Claude`

Details

68 68 

69Claude Code doesn't pass `OTEL_*` environment variables to the subprocesses it spawns, including the Bash tool, hooks, MCP servers, and language servers. An OpenTelemetry-instrumented application that you run through the Bash tool doesn't inherit Claude Code's exporter endpoint or headers, so set those variables directly in the command if that application needs to export its own telemetry.69Claude Code doesn't pass `OTEL_*` environment variables to the subprocesses it spawns, including the Bash tool, hooks, MCP servers, and language servers. An OpenTelemetry-instrumented application that you run through the Bash tool doesn't inherit Claude Code's exporter endpoint or headers, so set those variables directly in the command if that application needs to export its own telemetry.

70 70 

71### Managed endpoints govern signal-specific endpoints71### How managed settings lock the OTLP destination

72 72 

73A generic `OTEL_EXPORTER_OTLP_ENDPOINT` set in managed settings governs every signal's endpoint. If a lower-precedence source, such as user settings or a shell export, sets a signal-specific endpoint like `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`, Claude Code removes that variable at startup and logs a warning, visible with `claude --debug`. Users can't point one signal's OTLP traffic at a different endpoint, so you don't need to set the signal-specific endpoint variables in managed settings to prevent it.73When you set an `OTEL_EXPORTER_OTLP_*` variable in managed settings, Claude Code removes conflicting developer-set variables at startup and logs a warning you can see with `claude --debug`. What it removes depends on which variable you set:

74 74 

75This applies only on machines where an administrator deploys managed settings with telemetry configured, and it changes where telemetry is delivered, not what Claude Code collects.75* **Endpoints**: when you set `OTEL_EXPORTER_OTLP_ENDPOINT`, Claude Code removes every developer-set per-signal endpoint. Developers can't point one signal at a different collector, so you don't need to also set the per-signal endpoint variables in managed settings.

76* **Protocols**: when you set `OTEL_EXPORTER_OTLP_PROTOCOL`, Claude Code removes every developer-set per-signal protocol.

77* **Credentials**: when you set `OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_EXPORTER_OTLP_CLIENT_KEY`, or `OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE`, Claude Code removes the developer-set per-signal versions of that variable, plus every developer-set endpoint variable, generic or per-signal, since those credentials would otherwise reach a collector the managed settings didn't choose.

78* **Exporter selectors**: `OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER`, and the beta `OTEL_TRACES_EXPORTER` follow normal per-key precedence. A developer's setting can still disable a signal or switch it to the console exporter, so set the selectors in managed settings too if you need them locked.

76 79 

77A managed `OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_EXPORTER_OTLP_CLIENT_KEY`, or `OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE` variable also governs the endpoint variables, since those credentials would otherwise accompany telemetry to a collector the managed settings didn't choose.80Claude Code doesn't remove per-signal variables that you set in managed settings itself, so you can route one signal to a different collector by setting its variable there, as the [SIEM example](#send-events-to-a-siem) does. If you set a per-signal credential there, Claude Code removes the developer-set endpoint for that signal.

78 81 

79Two cases keep the normal per-key precedence:82This removal behavior changes where telemetry is delivered, not what Claude Code collects.

80 

81* Signal-specific variables set in the managed settings file itself still apply, so you can route one signal to a different collector by setting them there, as the [SIEM example](#send-events-to-a-siem) does.

82* The exporter selectors (`OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER`, and the beta `OTEL_TRACES_EXPORTER`) and the protocol variables follow per-key precedence, so a lower-precedence source can still change how a signal is exported. To make those authoritative too, set the signal-specific keys in managed settings directly.

83 83 

84{/* min-version: 2.1.217 */}Before v2.1.217, every variable followed per-key settings precedence independently, so a signal-specific endpoint set in user settings or the shell redirected that signal away from the managed collector.84{/* min-version: 2.1.217 */}Before v2.1.217, every variable followed per-key settings precedence independently, so a signal-specific endpoint set in user settings or the shell redirected that signal away from the managed collector.

85 85 


87 87 

88### Common configuration variables88### Common configuration variables

89 89 

90These variables configure exporters, endpoints, and export behavior for all deployments. A signal-specific variable overrides its generic counterpart, except that a generic endpoint or credential variable set in [managed settings](#administrator-configuration) governs all signals' endpoints and can't be overridden from lower-precedence sources.90These variables configure exporters, endpoints, and export behavior for all deployments. A per-signal variable overrides its generic counterpart. On machines with managed settings, see [How managed settings lock the OTLP destination](#how-managed-settings-lock-the-otlp-destination) for what Claude Code removes.

91 91 

92| Environment Variable | Description | Example Values |92| Environment Variable | Description | Example Values |

93| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |93| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |

94| `CLAUDE_CODE_ENABLE_TELEMETRY` | Enables telemetry collection (required) | `1` |94| `CLAUDE_CODE_ENABLE_TELEMETRY` | Enables telemetry collection (required) | `1` |

95| `OTEL_METRICS_EXPORTER` | Metrics exporter types, comma-separated. Use `none` to disable | `console`, `otlp`, `prometheus`, `none` |95| `OTEL_METRICS_EXPORTER` | Metrics exporter types, comma-separated. Use `none` to disable | `console`, `otlp`, `prometheus`, `none` |

96| `OTEL_LOGS_EXPORTER` | Logs/events exporter types, comma-separated. Use `none` to disable | `console`, `otlp`, `none` |96| `OTEL_LOGS_EXPORTER` | Logs/events exporter types, comma-separated. Use `none` to disable | `console`, `otlp`, `none` |

97| `OTEL_EXPORTER_OTLP_PROTOCOL` | Protocol for OTLP exporter, applies to all signals | `grpc`, `http/json`, `http/protobuf` |97| `OTEL_EXPORTER_OTLP_PROTOCOL` | Protocol for OTLP exporter, applies to all signals. Claude Code has no default protocol, so set this or the signal-specific protocol variable for each `otlp` exporter you enable | `grpc`, `http/json`, `http/protobuf` |

98| `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP collector endpoint for all signals | `http://localhost:4317` |98| `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP collector endpoint for all signals | `http://localhost:4317` |

99| `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL` | Protocol for metrics, overrides general setting | `grpc`, `http/json`, `http/protobuf` |99| `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL` | Protocol for metrics, overrides general setting | `grpc`, `http/json`, `http/protobuf` |

100| `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` | OTLP metrics endpoint, overrides general setting | `http://localhost:4318/v1/metrics` |100| `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` | OTLP metrics endpoint, overrides general setting | `http://localhost:4318/v1/metrics` |


123| `http/protobuf`, `http/json` | `CLAUDE_CODE_CLIENT_CERT`, `CLAUDE_CODE_CLIENT_KEY`, and optionally `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE`. See [Network configuration](/docs/en/network-config#mtls-authentication) | `NODE_EXTRA_CA_CERTS` |123| `http/protobuf`, `http/json` | `CLAUDE_CODE_CLIENT_CERT`, `CLAUDE_CODE_CLIENT_KEY`, and optionally `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE`. See [Network configuration](/docs/en/network-config#mtls-authentication) | `NODE_EXTRA_CA_CERTS` |

124| `grpc` | `OTEL_EXPORTER_OTLP_CLIENT_KEY` and `OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE`, or the per-signal variants such as `OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY` to use a different certificate per signal | `OTEL_EXPORTER_OTLP_CERTIFICATE` |124| `grpc` | `OTEL_EXPORTER_OTLP_CLIENT_KEY` and `OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE`, or the per-signal variants such as `OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY` to use a different certificate per signal | `OTEL_EXPORTER_OTLP_CERTIFICATE` |

125 125 

126For `grpc`, the OpenTelemetry SDK reads the standard OTLP variables directly, so existing configurations that set the per-signal metrics variables continue to work.126For `grpc`, the OpenTelemetry SDK reads the standard OTLP variables directly, so existing configurations that set the per-signal metrics variables continue to work. On machines with managed settings, Claude Code [may remove developer-set per-signal credentials and endpoints](#how-managed-settings-lock-the-otlp-destination) at startup.

127 127 

128### Metrics cardinality control128### Metrics cardinality control

129 129 


143 143 

144Distributed tracing exports spans that link each user prompt to the API requests and tool executions it triggers, so you can view a full request as a single trace in your tracing backend.144Distributed tracing exports spans that link each user prompt to the API requests and tool executions it triggers, so you can view a full request as a single trace in your tracing backend.

145 145 

146Tracing is off by default. To enable it, set both `CLAUDE_CODE_ENABLE_TELEMETRY=1` and `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1`, then set `OTEL_TRACES_EXPORTER` to choose where spans are sent. Traces reuse the [common OTLP configuration](#common-configuration-variables) for endpoint, protocol, headers, and [mTLS](#mtls-authentication). A generic endpoint or credential variable set in [managed settings](#managed-endpoints-govern-signal-specific-endpoints) governs the traces endpoint too, so the `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` override in the table below applies only when managed settings don't set one.146Tracing is off by default. To enable it, set both `CLAUDE_CODE_ENABLE_TELEMETRY=1` and `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1`, then set `OTEL_TRACES_EXPORTER` to choose where spans are sent. Traces reuse the [common OTLP configuration](#common-configuration-variables) for endpoint, protocol, headers, and [mTLS](#mtls-authentication). On machines with managed settings, Claude Code [may remove developer-set](#how-managed-settings-lock-the-otlp-destination) `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` and `OTEL_EXPORTER_OTLP_TRACES_PROTOCOL` variables at startup.

147 147 

148| Environment Variable | Description | Example Values |148| Environment Variable | Description | Example Values |

149| ------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------ |149| ------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------ |


371 371 

372### Example configurations372### Example configurations

373 373 

374Set these environment variables before running `claude`. Each scenario below shows a complete configuration, and each variable is described under [Common configuration variables](#common-configuration-variables).374Set these environment variables before running `claude`. Each scenario below shows a complete configuration, and each variable is described under [Common configuration variables](#common-configuration-variables). To confirm a configuration took effect, check your backend for the `claude_code.session.count` metric after starting a session; the [Quick start](#quick-start) covers logs-only verification and what to check when nothing arrives.

375 375 

376For console debugging with a 1-second export interval:376For console debugging with a 1-second export interval:

377 377 


1225}1225}

1226```1226```

1227 1227 

1228To confirm events arrive, submit a prompt in a session running under this configuration and check your SIEM for the `claude_code.user_prompt` event. If nothing arrives, run `claude --debug` and check the debug log for OTel export errors.

1229 

1228## Backend considerations1230## Backend considerations

1229 1231 

1230Your choice of metrics, logs, and traces backends determines the types of analyses you can perform:1232Your choice of metrics, logs, and traces backends determines the types of analyses you can perform:

Details

8 8 

9Claude Code supports various enterprise network and security configurations through environment variables. This includes routing traffic through corporate proxy servers, trusting custom Certificate Authorities (CA), and authenticating with mutual Transport Layer Security (mTLS) certificates for enhanced security.9Claude Code supports various enterprise network and security configurations through environment variables. This includes routing traffic through corporate proxy servers, trusting custom Certificate Authorities (CA), and authenticating with mutual Transport Layer Security (mTLS) certificates for enhanced security.

10 10 

11Set these environment variables before you launch Claude Code. Variables exported in your shell are read once at startup, so a running session doesn't pick up later changes to your shell environment.

12 

11<Note>13<Note>

12 All environment variables shown on this page can also be configured in [`settings.json`](/docs/en/settings).14 All environment variables shown on this page can also be configured in [`settings.json`](/docs/en/settings).

13</Note>15</Note>


33export NO_PROXY="*"35export NO_PROXY="*"

34```36```

35 37 

38Lowercase variants also work, and Claude Code uses the first one that's set in the order `https_proxy`, `HTTPS_PROXY`, `http_proxy`, `HTTP_PROXY`.

39 

36<Note>40<Note>

37 Claude Code does not support SOCKS proxies.41 Claude Code does not support SOCKS proxies.

38</Note>42</Note>


113 117 

114In [Claude Desktop](/docs/en/desktop) sessions where the app manages the provider connection, such as the Code tab on a [third-party provider](/docs/en/third-party-integrations) and Cowork sessions, Claude Code reads these variables and the proxy variables `HTTP_PROXY`, `HTTPS_PROXY`, and `NO_PROXY` only from [managed settings](/docs/en/settings#settings-files) and `~/.claude/settings.json`: it ignores them in a repository's own settings files, so a checked-out repository can't redirect the TLS or proxy path of a session whose credentials come from the app. In a local, SSH, or WSL Code tab session signed in through claude.ai, the app doesn't manage the connection, and Claude Code reads these variables from every settings scope, like any terminal session; [cloud sessions](/docs/en/claude-code-on-the-web) follow the cloud-session rules above wherever you start them. Before v2.1.217, Claude Code ignored these variables in every settings file when the app managed the connection.118In [Claude Desktop](/docs/en/desktop) sessions where the app manages the provider connection, such as the Code tab on a [third-party provider](/docs/en/third-party-integrations) and Cowork sessions, Claude Code reads these variables and the proxy variables `HTTP_PROXY`, `HTTPS_PROXY`, and `NO_PROXY` only from [managed settings](/docs/en/settings#settings-files) and `~/.claude/settings.json`: it ignores them in a repository's own settings files, so a checked-out repository can't redirect the TLS or proxy path of a session whose credentials come from the app. In a local, SSH, or WSL Code tab session signed in through claude.ai, the app doesn't manage the connection, and Claude Code reads these variables from every settings scope, like any terminal session; [cloud sessions](/docs/en/claude-code-on-the-web) follow the cloud-session rules above wherever you start them. Before v2.1.217, Claude Code ignored these variables in every settings file when the app managed the connection.

115 119 

120## Verify your configuration

121 

122You usually find out about a wrong proxy address or a bad certificate path from a [connection or certificate error](/docs/en/errors#network-and-connection-errors) on a later request, since Claude Code doesn't validate most of these settings when it reads them. The one setting it checks at startup is the proxy URL: when it can't parse the value, such as one missing the `http://` scheme, Claude Code stops launch with an error naming the variable to fix.

123 

124To confirm your configuration loaded before you send a request, start Claude Code with debug logging:

125 

126```bash theme={null}

127claude --debug

128```

129 

130Debug output goes to `~/.claude/debug/<session-id>.txt` rather than the terminal, or to a path you set with `--debug-file <path>`. In the log, look for the lines that confirm each file loaded:

131 

132```text theme={null}

133CA certs: Appended extra certificates from NODE_EXTRA_CA_CERTS (/etc/ssl/certs/corp-ca.pem)

134mTLS: Loaded client certificate from CLAUDE_CODE_CLIENT_CERT

135mTLS: Loaded client key from CLAUDE_CODE_CLIENT_KEY

136```

137 

138If Claude Code can't read one of these files, the log shows a `Failed to read` or `Failed to load` line with the reason instead.

139 

140You can also run `/status` in an interactive session and check these rows:

141 

142* **Proxy**: shows the active proxy URL, and marks a value it can't parse as invalid and ignored.

143* **mTLS client cert** and **mTLS client key**: appear only when the files loaded, so a missing row means the load failed and the debug log has the reason.

144* **Additional CA cert(s)**: shows the `NODE_EXTRA_CA_CERTS` path without checking that the file loaded, so confirm this one in the debug log.

145 

116## Apply network settings to background agents146## Apply network settings to background agents

117 147 

118[Background agents](/docs/en/agent-view) don't run inside the terminal that dispatched them. A per-user supervisor process starts on demand, outlives your shell, and hosts every `claude agents`, `--bg`, and `/background` session. See [How background sessions are hosted](/docs/en/agent-view#how-background-sessions-are-hosted). This changes how the configuration on this page reaches those sessions.148[Background agents](/docs/en/agent-view) don't run inside the terminal that dispatched them. A per-user supervisor process starts on demand, outlives your shell, and hosts every `claude agents`, `--bg`, and `/background` session. See [How background sessions are hosted](/docs/en/agent-view#how-background-sessions-are-hosted). This changes how the configuration on this page reaches those sessions.

overview.md +2 −2

Details

81 claude81 claude

82 ```82 ```

83 83 

84 You'll be prompted to log in on first use. That's it! [Continue with the Quickstart →](/docs/en/quickstart)84 You'll be prompted to log in on first use. If you've set the `ANTHROPIC_API_KEY` environment variable, Claude Code skips the login prompt and asks you to approve the key instead. That's it! [Continue with the Quickstart →](/docs/en/quickstart)

85 85 

86 <Tip>86 <Tip>

87 See [advanced setup](/docs/en/setup) for installation options, manual updates, or uninstallation instructions. Visit [installation troubleshooting](/docs/en/troubleshoot-install) if you hit issues.87 See [advanced setup](/docs/en/setup) for installation options, manual updates, or uninstallation instructions. Visit [installation troubleshooting](/docs/en/troubleshoot-install) if you hit issues.


208 * Step away from your desk and keep working from your phone or any browser with [Remote Control](/docs/en/remote-control)208 * Step away from your desk and keep working from your phone or any browser with [Remote Control](/docs/en/remote-control)

209 * Message [Dispatch](/docs/en/desktop#sessions-from-dispatch) a task from your phone and open the Desktop session it creates209 * Message [Dispatch](/docs/en/desktop#sessions-from-dispatch) a task from your phone and open the Desktop session it creates

210 * Kick off a long-running task on the [web](/docs/en/claude-code-on-the-web) or the [Claude mobile app](/docs/en/mobile), then pull it into your terminal with `claude --teleport`. Teleport requires a claude.ai subscription.210 * Kick off a long-running task on the [web](/docs/en/claude-code-on-the-web) or the [Claude mobile app](/docs/en/mobile), then pull it into your terminal with `claude --teleport`. Teleport requires a claude.ai subscription.

211 * Run `/desktop` to continue your current terminal session in the [Desktop app](/docs/en/desktop), where you can review diffs visually. Available on macOS and x64 Windows.211 * Run `/desktop` to continue your current terminal session in the [Desktop app](/docs/en/desktop), where you can review diffs visually. The `/desktop` handoff requires a claude.ai subscription. Available on macOS and x64 Windows.

212 * Route tasks from team chat: mention `@Claude` in [Slack](/docs/en/slack) with a bug report and get a pull request back212 * Route tasks from team chat: mention `@Claude` in [Slack](/docs/en/slack) with a bug report and get a pull request back

213 </Accordion>213 </Accordion>

214</AccordionGroup>214</AccordionGroup>

Details

122 <Tab title="Web and mobile">122 <Tab title="Web and mobile">

123 Use the mode dropdown next to the prompt box on [claude.ai/code](https://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:123 Use the mode dropdown next to the prompt box on [claude.ai/code](https://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:

124 124 

125 * **Cloud sessions** on [Claude Code on the web](/docs/en/claude-code-on-the-web): Accept edits, Plan, and Auto. Accept edits corresponds to `default` mode: the cloud environment pre-approves file edits regardless of mode, so the dropdown shows Accept edits instead of Manual. Cloud sessions still honor `defaultMode: "acceptEdits"` from settings. Auto mode appears only when your organization allows it and the selected model supports it. Bypass permissions isn't available.125 * **Cloud sessions** on [Claude Code on the web](/docs/en/claude-code-on-the-web): Accept edits, Plan, and Auto. Accept edits corresponds to `default` mode: cloud sessions pre-approve file edits regardless of mode, so the dropdown shows Accept edits instead of Manual. Cloud sessions still honor `defaultMode: "acceptEdits"` from settings. Auto mode appears only when your organization allows it and the selected model supports it. Bypass permissions isn't available.

126 * **[Remote Control](/docs/en/remote-control) sessions** on your local machine: Manual, Accept edits, and Plan. You can't select Auto or Bypass permissions from the app. {/* min-version: 2.1.202 */}The dropdown shows the mode the local session is in, including a mode set from the terminal, and updates when the mode changes in the app or in the terminal. The one exception is Bypass permissions: the session never reports that mode to claude.ai, so switching into it from the terminal doesn't change what the dropdown shows. Before v2.1.202, sessions connected with `/remote-control` or `claude --remote-control` didn't report their mode at all, so claude.ai and the mobile app could show a mode the session wasn't in. The mismatch affected only the label: Claude Code generated permission prompts from the session's actual mode, and they still appeared in the app for approval.126 * **[Remote Control](/docs/en/remote-control) sessions** on your local machine: Manual, Accept edits, and Plan. You can't select Auto or Bypass permissions from the app. {/* min-version: 2.1.202 */}The dropdown shows the mode the local session is in, including a mode set from the terminal, and updates when the mode changes in the app or in the terminal. The one exception is Bypass permissions: the session never reports that mode to claude.ai, so switching into it from the terminal doesn't change what the dropdown shows. Before v2.1.202, sessions connected with `/remote-control` or `claude --remote-control` didn't report their mode at all, so claude.ai and the mobile app could show a mode the session wasn't in. The mismatch affected only the label: Claude Code generated permission prompts from the session's actual mode, and they still appeared in the app for approval.

127 127 

128 For Remote Control, the host must be signed in with your claude.ai account; API keys are not supported. You can also set the starting mode when launching the host:128 For Remote Control, the host must be signed in with your claude.ai account; API keys are not supported. You can also set the starting mode when launching the host:

Details

1034 1034 

1035* Verify the marketplace URL is accessible1035* Verify the marketplace URL is accessible

1036* Check that `.claude-plugin/marketplace.json` exists at the specified path1036* Check that `.claude-plugin/marketplace.json` exists at the specified path

1037* Ensure JSON syntax is valid using `claude plugin validate` or `/plugin validate`. To check skill, agent, and command frontmatter, run the command against each plugin directory1037* Ensure JSON syntax is valid using `claude plugin validate .` or `/plugin validate .` from the marketplace directory. To check skill, agent, and command frontmatter, run the command against each plugin directory

1038* For private repositories, confirm you have access permissions1038* For private repositories, confirm you have access permissions

1039 1039 

1040### Marketplace validation errors1040### Marketplace validation errors

Details

8 8 

9If you operate a plugin marketplace for your organization, you can have Claude Code suggest specific plugins to users based on what they are working on. Add a `relevance` block to a plugin's entry in `marketplace.json`, then allowlist the marketplace in managed settings. When a user's session matches one of the declared signals, Claude Code surfaces an install suggestion for that plugin.9If you operate a plugin marketplace for your organization, you can have Claude Code suggest specific plugins to users based on what they are working on. Add a `relevance` block to a plugin's entry in `marketplace.json`, then allowlist the marketplace in managed settings. When a user's session matches one of the declared signals, Claude Code surfaces an install suggestion for that plugin.

10 10 

11Marketplace-declared suggestions are opt-in per marketplace through [managed settings](/en/settings#settings-files). No marketplace's `relevance` declarations produce suggestions until an administrator adds it to the allowlist, including the official Anthropic marketplace. Claude Code also includes one built-in suggestion that is independent of this allowlist; that tip and all marketplace-declared tips are disabled when [`spinnerTipsEnabled`](/en/settings#available-settings) is set to `false`.11Marketplace-declared suggestions are opt-in per marketplace through [managed settings](/docs/en/settings#settings-files). No marketplace's `relevance` declarations produce suggestions until an administrator adds it to the allowlist, including the official Anthropic marketplace. Claude Code also includes one built-in suggestion that is independent of this allowlist; that tip and all marketplace-declared tips are disabled when [`spinnerTipsEnabled`](/docs/en/settings#available-settings) is set to `false`.

12 12 

13{/* min-version: 2.1.152 */}This feature requires Claude Code v2.1.152 or later. Older clients ignore the `relevance` field.13{/* min-version: 2.1.152 */}This feature requires Claude Code v2.1.152 or later. Older clients ignore the `relevance` field.

14 14 

15This page is for marketplace operators and enterprise administrators. If you are looking to install plugins, see [Discover and install plugins](/en/discover-plugins).15This page is for marketplace operators and enterprise administrators. If you are looking to install plugins, see [Discover and install plugins](/docs/en/discover-plugins).

16 16 

17## How it works17## How it works

18 18 


99```99```

100 100 

101<Note>101<Note>

102 Unknown fields under `relevance` and `relevance.signals` are ignored at load time so older Claude Code clients continue to load your marketplace. Run `claude plugin validate` to surface them as warnings.102 Claude Code ignores unknown fields under `relevance` and `relevance.signals` at load time, so older clients continue to load your marketplace. Run `claude plugin validate` against your marketplace directory, for example `claude plugin validate ./my-marketplace`, to surface them as warnings.

103</Note>103</Note>

104 104 

105## Enable suggestions in managed settings105## Enable suggestions in managed settings

106 106 

107Declaring `relevance` in `marketplace.json` is not enough on its own. An administrator must allowlist the marketplace in [managed settings](/en/settings#settings-files) before its suggestions appear to users.107Declaring `relevance` in `marketplace.json` is not enough on its own. An administrator must allowlist the marketplace in [managed settings](/docs/en/settings#settings-files) before its suggestions appear to users.

108 108 

109Add the marketplace name to `pluginSuggestionMarketplaces`. For any marketplace other than the official Anthropic marketplace, also declare the marketplace source in the same managed settings, either as that name's entry in `extraKnownMarketplaces` or as an entry in `strictKnownMarketplaces`. The allowlisted name is ignored if the marketplace registered on the machine came from a different source. This prevents an unrelated source from registering under an allowlisted name to have its plugins suggested across your org.109Add the marketplace name to `pluginSuggestionMarketplaces`. For any marketplace other than the official Anthropic marketplace, also declare the marketplace source in the same managed settings, either as that name's entry in `extraKnownMarketplaces` or as an entry in `strictKnownMarketplaces`. The allowlisted name is ignored if the marketplace registered on the machine came from a different source. This prevents an unrelated source from registering under an allowlisted name to have its plugins suggested across your org.

110 110 


132}132}

133```133```

134 134 

135See the [settings reference](/en/settings) for `pluginSuggestionMarketplaces` and [`extraKnownMarketplaces`](/en/settings#extraknownmarketplaces) for full configuration details.135See the [settings reference](/docs/en/settings) for `pluginSuggestionMarketplaces` and [`extraKnownMarketplaces`](/docs/en/settings#extraknownmarketplaces) for full configuration details.

136 136 

137## What the user sees137## What the user sees

138 138 


165 165 

166## See also166## See also

167 167 

168* [Create and distribute a plugin marketplace](/en/plugin-marketplaces): build the marketplace that hosts your plugins168* [Create and distribute a plugin marketplace](/docs/en/plugin-marketplaces): build the marketplace that hosts your plugins

169* [Recommend your plugin from your CLI](/en/plugin-hints): prompt users from your own CLI instead of from Claude Code's session signals169* [Recommend your plugin from your CLI](/docs/en/plugin-hints): prompt users from your own CLI instead of from Claude Code's session signals

170* [Settings](/en/settings): full reference for `pluginSuggestionMarketplaces` and `extraKnownMarketplaces`170* [Settings](/docs/en/settings): full reference for `pluginSuggestionMarketplaces` and `extraKnownMarketplaces`

plugins.md +41 −40

Details

8 8 

9Plugins let you extend Claude Code with custom functionality that can be shared across projects and teams. This guide covers creating your own plugins with skills, agents, hooks, and MCP servers.9Plugins let you extend Claude Code with custom functionality that can be shared across projects and teams. This guide covers creating your own plugins with skills, agents, hooks, and MCP servers.

10 10 

11Looking to install existing plugins? See [Discover and install plugins](/en/discover-plugins). For complete technical specifications, see [Plugins reference](/en/plugins-reference).11Looking to install existing plugins? See [Discover and install plugins](/docs/en/discover-plugins). For complete technical specifications, see [Plugins reference](/docs/en/plugins-reference).

12 12 

13## When to use plugins vs standalone configuration13## When to use plugins vs standalone configuration

14 14 


44 44 

45### Prerequisites45### Prerequisites

46 46 

47* Claude Code [installed and authenticated](/en/quickstart#step-1-install-claude-code)47* Claude Code [installed and authenticated](/docs/en/quickstart#step-1-install-claude-code)

48 48 

49<Note>49<Note>

50 If you don't see the `/plugin` command, update Claude Code to the latest version. See [Troubleshooting](/en/troubleshooting) for upgrade instructions.50 If you don't see the `/plugin` command, update Claude Code to the latest version. See [Troubleshooting](/docs/en/troubleshooting) for upgrade instructions.

51</Note>51</Note>

52 52 

53### Create your first plugin53### Create your first plugin


89 | :------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |89 | :------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

90 | `name` | Unique identifier and skill namespace. Skills are prefixed with this (e.g., `/my-first-plugin:hello`). |90 | `name` | Unique identifier and skill namespace. Skills are prefixed with this (e.g., `/my-first-plugin:hello`). |

91 | `description` | Shown in the plugin manager when browsing or installing plugins. |91 | `description` | Shown in the plugin manager when browsing or installing plugins. |

92 | `version` | Optional. If set, users only receive updates when you bump this field. If omitted and your plugin is distributed via git, the commit SHA is used and every commit counts as a new version. See [version management](/en/plugins-reference#version-management). |92 | `version` | Optional. If set, users only receive updates when you bump this field. If omitted and your plugin is distributed via git, the commit SHA is used and every commit counts as a new version. See [version management](/docs/en/plugins-reference#version-management). |

93 | `author` | Optional. Helpful for attribution. |93 | `author` | Optional. Helpful for attribution. |

94 94 

95 For additional fields like `homepage`, `repository`, and `license`, see the [full manifest schema](/en/plugins-reference#plugin-manifest-schema).95 For additional fields like `homepage`, `repository`, and `license`, see the [full manifest schema](/docs/en/plugins-reference#plugin-manifest-schema).

96 </Step>96 </Step>

97 97 

98 <Step title="Add a skill">98 <Step title="Add a skill">


129 /my-first-plugin:hello129 /my-first-plugin:hello

130 ```130 ```

131 131 

132 You'll see Claude respond with a greeting. Run `/help` to see your skill listed under the plugin namespace.132 You'll see Claude respond with a greeting. Run `/help` and open the **Custom commands** tab to see your skill listed under the plugin namespace.

133 133 

134 <Note>134 <Note>

135 **Why namespacing?** Plugin skills are always namespaced (like `/my-first-plugin:hello`) to prevent conflicts when multiple plugins have skills with the same name.135 **Why namespacing?** Plugin skills are always namespaced (like `/my-first-plugin:hello`) to prevent conflicts when multiple plugins have skills with the same name.


153 Greet the user named "$ARGUMENTS" warmly and ask how you can help them today. Make the greeting personal and encouraging.153 Greet the user named "$ARGUMENTS" warmly and ask how you can help them today. Make the greeting personal and encouraging.

154 ```154 ```

155 155 

156 Run `/reload-plugins` to pick up the changes, then try the skill with your name:156 Run `/reload-plugins` to pick up the changes. The skills count in the summary covers only `commands/` directories, so it can report `0 skills` even though the skill you just edited reloaded. Then try the skill with your name:

157 157 

158 ```shell theme={null}158 ```shell theme={null}

159 /my-first-plugin:hello Alex159 /my-first-plugin:hello Alex

160 ```160 ```

161 161 

162 Claude will greet you by name. For more on passing arguments to skills, see [Skills](/en/skills#pass-arguments-to-skills).162 Claude will greet you by name. For more on passing arguments to skills, see [Skills](/docs/en/skills#pass-arguments-to-skills).

163 </Step>163 </Step>

164</Steps>164</Steps>

165 165 


170* **Skill arguments** (`$ARGUMENTS`): captures user input for dynamic behavior170* **Skill arguments** (`$ARGUMENTS`): captures user input for dynamic behavior

171 171 

172<Tip>172<Tip>

173 The `--plugin-dir` flag is useful for development and testing. When you're ready to share your plugin with others, see [Create and distribute a plugin marketplace](/en/plugin-marketplaces).173 The `--plugin-dir` flag is useful for development and testing. When you're ready to share your plugin with others, see [Create and distribute a plugin marketplace](/docs/en/plugin-marketplaces).

174</Tip>174</Tip>

175 175 

176## Develop a plugin in your skills directory176## Develop a plugin in your skills directory


183 183 

184This creates `~/.claude/skills/my-tool/` with a `.claude-plugin/plugin.json` manifest and a starter `SKILL.md`. On the next session it loads as `my-tool@skills-dir` with no marketplace or install step.184This creates `~/.claude/skills/my-tool/` with a `.claude-plugin/plugin.json` manifest and a starter `SKILL.md`. On the next session it loads as `my-tool@skills-dir` with no marketplace or install step.

185 185 

186For the auto-load rules, personal vs. project scope, the workspace-trust requirement, and how to update or remove one, see [Skills-directory plugins](/en/plugins-reference#skills-directory-plugins).186For the auto-load rules, personal vs. project scope, the workspace-trust requirement, and how to update or remove one, see [Skills-directory plugins](/docs/en/plugins-reference#skills-directory-plugins).

187 187 

188## Plugin structure overview188## Plugin structure overview

189 189 


206| `.lsp.json` | Plugin root | LSP server configurations for code intelligence |206| `.lsp.json` | Plugin root | LSP server configurations for code intelligence |

207| `monitors/` | Plugin root | Background monitor configurations in `monitors.json` |207| `monitors/` | Plugin root | Background monitor configurations in `monitors.json` |

208| `bin/` | Plugin root | Executables added to the Bash tool's `PATH` while the plugin is enabled |208| `bin/` | Plugin root | Executables added to the Bash tool's `PATH` while the plugin is enabled |

209| `settings.json` | Plugin root | Default [settings](/en/settings) applied when the plugin is enabled |209| `settings.json` | Plugin root | Default [settings](/docs/en/settings) applied when the plugin is enabled |

210 210 

211A plugin that ships exactly one skill can place `SKILL.md` directly at the plugin root instead of creating a `skills/` directory. Claude Code loads it as a single skill and uses the frontmatter `name` field for the invocation name. Use the `skills/` layout for plugins that may grow to more than one skill.211A plugin that ships exactly one skill can place `SKILL.md` directly at the plugin root instead of creating a `skills/` directory. Claude Code loads it as a single skill and uses the frontmatter `name` field for the invocation name. Use the `skills/` layout for plugins that may grow to more than one skill.

212 212 

213<Note>213<Note>

214 **Next steps**: Ready to add more features? Jump to [Develop more complex plugins](#develop-more-complex-plugins) to add agents, hooks, MCP servers, and LSP servers. For complete technical specifications of all plugin components, see [Plugins reference](/en/plugins-reference).214 **Next steps**: Ready to add more features? Jump to [Develop more complex plugins](#develop-more-complex-plugins) to add agents, hooks, MCP servers, and LSP servers. For complete technical specifications of all plugin components, see [Plugins reference](/docs/en/plugins-reference).

215</Note>215</Note>

216 216 

217## Develop more complex plugins217## Develop more complex plugins


220 220 

221### Add Skills to your plugin221### Add Skills to your plugin

222 222 

223Plugins can include [Agent Skills](/en/skills) to extend Claude's capabilities. Skills are model-invoked: Claude automatically uses them based on the task context.223Plugins can include [Agent Skills](/docs/en/skills) to extend Claude's capabilities. Skills are model-invoked: Claude automatically uses them based on the task context.

224 224 

225Add a `skills/` directory at your plugin root with Skill folders containing `SKILL.md` files:225Add a `skills/` directory at your plugin root with Skill folders containing `SKILL.md` files:

226 226 


2474. Test coverage2474. Test coverage

248```248```

249 249 

250After installing the plugin, run `/reload-plugins` to load the Skills. For complete Skill authoring guidance including progressive disclosure and tool restrictions, see [Agent Skills](/en/skills).250After installing the plugin, run `/reload-plugins` to load the Skills. For complete Skill authoring guidance including progressive disclosure and tool restrictions, see [Agent Skills](/docs/en/skills).

251 251 

252### Add LSP servers to your plugin252### Add LSP servers to your plugin

253 253 


271 271 

272Users installing your plugin must have the language server binary installed on their machine.272Users installing your plugin must have the language server binary installed on their machine.

273 273 

274For complete LSP configuration options, see [LSP servers](/en/plugins-reference#lsp-servers).274To confirm the server starts, launch Claude Code with the plugin enabled and check the `/plugin` Errors tab: a language server that fails to start appears there, for example with `Executable not found in $PATH` when the binary isn't installed. An entry with an invalid configuration is skipped instead; run `claude --debug` to see why.

275 

276For complete LSP configuration options, see [LSP servers](/docs/en/plugins-reference#lsp-servers).

275 277 

276### Add background monitors to your plugin278### Add background monitors to your plugin

277 279 


289]291]

290```292```

291 293 

292Each stdout line from `command` is delivered to Claude as a notification during the session. For the full schema, including the `when` trigger and variable substitution, see [Monitors](/en/plugins-reference#monitors).294Each stdout line from `command` is delivered to Claude as a notification during the session. For the full schema, including the `when` trigger and variable substitution, see [Monitors](/docs/en/plugins-reference#monitors).

293 295 

294### Ship default settings with your plugin296### Ship default settings with your plugin

295 297 

296Plugins can include a `settings.json` file at the plugin root to apply default configuration when the plugin is enabled. Currently, only the `agent` and `subagentStatusLine` keys are supported.298Plugins can include a `settings.json` file at the plugin root to apply default configuration when the plugin is enabled. Currently, only the `agent` and `subagentStatusLine` keys are supported.

297 299 

298Setting `agent` activates one of the plugin's [custom agents](/en/sub-agents) as the main thread, applying its system prompt, tool restrictions, and model. This lets a plugin change how Claude Code behaves by default when enabled.300Setting `agent` activates one of the plugin's [custom agents](/docs/en/sub-agents) as the main thread, applying its system prompt, tool restrictions, and model. This lets a plugin change how Claude Code behaves by default when enabled.

299 301 

300```json settings.json theme={null}302```json settings.json theme={null}

301{303{


307 309 

308### Organize complex plugins310### Organize complex plugins

309 311 

310For plugins with many components, organize your directory structure by functionality. For complete directory layouts and organization patterns, see [Plugin directory structure](/en/plugins-reference#plugin-directory-structure).312For plugins with many components, organize your directory structure by functionality. For complete directory layouts and organization patterns, see [Plugin directory structure](/docs/en/plugins-reference#plugin-directory-structure).

311 313 

312### Test your plugins locally314### Test your plugins locally

313 315 


329 331 

330* Try your skills with `/plugin-name:skill-name`332* Try your skills with `/plugin-name:skill-name`

331* Check that agents appear in `/context` under Custom Agents, or @-mention one by its scoped name333* Check that agents appear in `/context` under Custom Agents, or @-mention one by its scoped name

332* Verify hooks work as expected334* Trigger the event each hook matches, such as asking Claude to edit a file for a `PostToolUse` hook, and confirm its effect. Claude Code records which hooks matched, their exit codes, and their output in the [debug log](/docs/en/hooks#debug-hooks)

333 335 

334<Tip>336<Tip>

335 You can load multiple plugins at once by specifying the flag multiple times:337 You can load multiple plugins at once by specifying the flag multiple times:


339 ```341 ```

340</Tip>342</Tip>

341 343 

342To test a plugin that is already packaged as a `.zip` archive and hosted at a URL, such as a CI build artifact, use `--plugin-url` instead. Claude Code fetches the archive at startup and loads it for that session only. If the fetch fails or the archive is invalid, Claude Code reports a plugin load error and starts without it. The same [trust considerations](/en/discover-plugins#security) apply as for any plugin source: only point this flag at archives you control or trust.344To test a plugin that is already packaged as a `.zip` archive and hosted at a URL, such as a CI build artifact, use `--plugin-url` instead. Claude Code fetches the archive at startup and loads it for that session only. If Claude Code can't fetch the archive, or the archive is invalid, it starts without the plugin and records a plugin load error that you can review in the `/plugin` manager's **Errors** tab. The same [trust considerations](/docs/en/discover-plugins#security) apply as for any plugin source: only point this flag at archives you control or trust.

343 345 

344To load multiple plugins, repeat the flag for each URL:346To load multiple plugins, repeat the flag for each URL:

345 347 


359 361 

3601. **Check the structure**: Ensure your directories are at the plugin root, not inside `.claude-plugin/`3621. **Check the structure**: Ensure your directories are at the plugin root, not inside `.claude-plugin/`

3612. **Test components individually**: Check each skill, agent, and hook separately3632. **Test components individually**: Check each skill, agent, and hook separately

3623. **Use validation and debugging tools**: See [Debugging and development tools](/en/plugins-reference#debugging-and-development-tools) for CLI commands and troubleshooting techniques3643. **Use validation and debugging tools**: See [Debugging and development tools](/docs/en/plugins-reference#debugging-and-development-tools) for CLI commands and troubleshooting techniques

363 365 

364### Share your plugins366### Share your plugins

365 367 

366When your plugin is ready to share:368When your plugin is ready to share:

367 369 

3681. **Add documentation**: Include a `README.md` with installation and usage instructions3701. **Add documentation**: Include a `README.md` with installation and usage instructions

3692. **Choose a versioning strategy**: Decide whether to set an explicit `version` or rely on the git commit SHA. See [version management](/en/plugins-reference#version-management)3712. **Choose a versioning strategy**: Decide whether to set an explicit `version` or rely on the git commit SHA. See [version management](/docs/en/plugins-reference#version-management)

3703. **Create or use a marketplace**: Distribute through [plugin marketplaces](/en/plugin-marketplaces) for installation3723. **Create or use a marketplace**: Distribute through [plugin marketplaces](/docs/en/plugin-marketplaces) for installation

3714. **Test with others**: Have team members test the plugin before wider distribution3734. **Test with others**: Have team members test the plugin before wider distribution

372 374 

373Once your plugin is in a marketplace, others can install it using the instructions in [Discover and install plugins](/en/discover-plugins). To keep a plugin internal to your team, host the marketplace in a [private repository](/en/plugin-marketplaces#private-repositories).375Once your plugin is in a marketplace, others can install it using the instructions in [Discover and install plugins](/docs/en/discover-plugins). To keep a plugin internal to your team, host the marketplace in a [private repository](/docs/en/plugin-marketplaces#private-repositories).

374 376 

375### Submit your plugin to the community marketplace377### Submit your plugin to the community marketplace

376 378 


386 388 

387The claude.ai form requires a Team or Enterprise organization and directory management access; organization Owners have this access by default. Individual authors who aren't part of a Team or Enterprise organization can use the Console form instead.389The claude.ai form requires a Team or Enterprise organization and directory management access; organization Owners have this access by default. Individual authors who aren't part of a Team or Enterprise organization can use the Console form instead.

388 390 

389Run `claude plugin validate` locally before you submit. The review pipeline runs the same check on every submission, along with automated safety screening.391Run `claude plugin validate ./your-plugin` locally before you submit, replacing `./your-plugin` with the path to your plugin directory. The review pipeline runs the same check on every submission, along with automated safety screening. When validation passes, Claude Code prints `✔ Validation passed`, or `✔ Validation passed with warnings` if there are warnings. Warnings don't fail validation; add `--strict` to treat them as errors.

390 392 

391Approved plugins are pinned to a specific commit SHA in the [`anthropics/claude-plugins-community`](https://github.com/anthropics/claude-plugins-community) catalog, and CI bumps the pin automatically as you push new commits to your repository. The public catalog syncs nightly from the review pipeline, so there can be a delay between approval and your plugin appearing in `marketplace.json`. To check whether your plugin is installable yet, search for its name in the [community catalog](https://github.com/anthropics/claude-plugins-community/blob/main/.claude-plugin/marketplace.json).393Approved plugins are pinned to a specific commit SHA in the [`anthropics/claude-plugins-community`](https://github.com/anthropics/claude-plugins-community) catalog, and CI bumps the pin automatically as you push new commits to your repository. The public catalog syncs nightly from the review pipeline, so there can be a delay between approval and your plugin appearing in `marketplace.json`. To check whether your plugin is installable yet, search for its name in the [community catalog](https://github.com/anthropics/claude-plugins-community/blob/main/.claude-plugin/marketplace.json).

392 394 

393The official marketplace, `claude-plugins-official`, is curated separately. Anthropic decides which plugins to include at its discretion. There is no application process, and the submission form does not add plugins to the official marketplace.395The official marketplace, `claude-plugins-official`, is curated separately. Anthropic decides which plugins to include at its discretion. There is no application process, and the submission form does not add plugins to the official marketplace.

394 396 

395If Anthropic lists your plugin in the official marketplace, your CLI can prompt Claude Code users to install it. See [Recommend your plugin from your CLI](/en/plugin-hints).397If Anthropic lists your plugin in the official marketplace, your CLI can prompt Claude Code users to install it. See [Recommend your plugin from your CLI](/docs/en/plugin-hints).

396 398 

397<Note>399<Note>

398 For complete technical specifications, debugging techniques, and distribution strategies, see [Plugins reference](/en/plugins-reference).400 For complete technical specifications, debugging techniques, and distribution strategies, see [Plugins reference](/docs/en/plugins-reference).

399</Note>401</Note>

400 402 

401## Convert existing configurations to plugins403## Convert existing configurations to plugins


424 </Step>426 </Step>

425 427 

426 <Step title="Copy your existing files">428 <Step title="Copy your existing files">

427 Copy your existing configurations to the plugin directory:429 Copy each configuration directory you have to the plugin root. You might not have all three: if a directory doesn't exist, `cp` prints `No such file or directory` and copies nothing, so skip that command or ignore the error.

428 430 

429 ```bash theme={null}431 ```bash theme={null}

430 # Copy commands

431 cp -r .claude/commands my-plugin/432 cp -r .claude/commands my-plugin/

432 433 

433 # Copy agents (if any)

434 cp -r .claude/agents my-plugin/434 cp -r .claude/agents my-plugin/

435 435 

436 # Copy skills (if any)

437 cp -r .claude/skills my-plugin/436 cp -r .claude/skills my-plugin/

438 ```437 ```

438 

439 Your plugin now contains copies of the directories you had under `.claude/`. Run `ls my-plugin` to confirm: you should see each directory you copied.

439 </Step>440 </Step>

440 441 

441 <Step title="Migrate hooks">442 <Step title="Migrate hooks">


468 claude --plugin-dir ./my-plugin469 claude --plugin-dir ./my-plugin

469 ```470 ```

470 471 

471 Test each component: run your commands, check that agents appear in `/context`, and verify hooks trigger correctly.472 Test each component: run your commands, check that agents appear in `/context`, and trigger the event each hook matches to confirm its effect. Claude Code records which hooks matched and how they exited in the [debug log](/docs/en/hooks#debug-hooks).

472 </Step>473 </Step>

473</Steps>474</Steps>

474 475 


491 492 

492### For plugin users493### For plugin users

493 494 

494* [Discover and install plugins](/en/discover-plugins): browse marketplaces and install plugins495* [Discover and install plugins](/docs/en/discover-plugins): browse marketplaces and install plugins

495* [Configure team marketplaces](/en/discover-plugins#configure-team-marketplaces): set up repository-level plugins for your team496* [Configure team marketplaces](/docs/en/discover-plugins#configure-team-marketplaces): set up repository-level plugins for your team

496 497 

497### For plugin developers498### For plugin developers

498 499 

499* [Create and distribute a marketplace](/en/plugin-marketplaces): package and share your plugins500* [Create and distribute a marketplace](/docs/en/plugin-marketplaces): package and share your plugins

500* [Plugins reference](/en/plugins-reference): complete technical specifications501* [Plugins reference](/docs/en/plugins-reference): complete technical specifications

501* Dive deeper into specific plugin components:502* Dive deeper into specific plugin components:

502 * [Skills](/en/skills): skill development details503 * [Skills](/docs/en/skills): skill development details

503 * [Subagents](/en/sub-agents): agent configuration and capabilities504 * [Subagents](/docs/en/sub-agents): agent configuration and capabilities

504 * [Hooks](/en/hooks): event handling and automation505 * [Hooks](/docs/en/hooks): event handling and automation

505 * [MCP](/en/mcp): external tool integration506 * [MCP](/docs/en/mcp): external tool integration

Details

119| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |119| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |

120| `UserPromptExpansion` | When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion |120| `UserPromptExpansion` | When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion |

121| `PreToolUse` | Before a tool call executes. Can block it |121| `PreToolUse` | Before a tool call executes. Can block it |

122| `PermissionRequest` | When a permission dialog appears |122| `PermissionRequest` | When a tool call needs a permission decision |

123| `PermissionDenied` | When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call |123| `PermissionDenied` | When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call |

124| `PostToolUse` | After a tool call succeeds |124| `PostToolUse` | After a tool call succeeds |

125| `PostToolUseFailure` | After a tool call fails |125| `PostToolUseFailure` | After a tool call fails |


359When you install a plugin, you choose a **scope** that determines where the plugin is available and who else can use it:359When you install a plugin, you choose a **scope** that determines where the plugin is available and who else can use it:

360 360 

361| Scope | Settings file | Use case |361| Scope | Settings file | Use case |

362| :-------- | :---------------------------------------------- | :------------------------------------------------------- |362| :-------- | :---------------------------------------------- | :-------------------------------------------------------------------------- |

363| `user` | `~/.claude/settings.json` | Personal plugins available across all projects (default) |363| `user` | `~/.claude/settings.json` | Personal plugins available across all projects (default) |

364| `project` | `.claude/settings.json` | Team plugins shared via version control |364| `project` | `.claude/settings.json` | Team plugins shared via version control |

365| `local` | `.claude/settings.local.json` | Project-specific plugins, gitignored |365| `local` | `.claude/settings.local.json` | Project-specific plugins, gitignored when Claude Code saves a setting to it |

366| `managed` | [Managed settings](/docs/en/settings#settings-files) | Managed plugins (read-only, update only) |366| `managed` | [Managed settings](/docs/en/settings#settings-files) | Managed plugins (read-only, update only) |

367 367 

368Plugins use the same scope system as other Claude Code configurations. For installation instructions and scope flags, see [Install plugins](/docs/en/discover-plugins#install-plugins). For a complete explanation of scopes, see [Configuration scopes](/docs/en/settings#configuration-scopes).368Plugins use the same scope system as other Claude Code configurations. For installation instructions and scope flags, see [Install plugins](/docs/en/discover-plugins#install-plugins). For a complete explanation of scopes, see [Configuration scopes](/docs/en/settings#configuration-scopes).


397Personal-scope plugins have none of these restrictions.397Personal-scope plugins have none of these restrictions.

398 398 

399<Warning>399<Warning>

400 Project-scope `@skills-dir` plugins load only from the `.claude/skills/` of the directory where you start Claude Code. They do not [walk up to the repository root](/docs/en/skills#automatic-discovery-from-parent-and-nested-directories) the way plain skills and commands do, so launching from a subdirectory misses a plugin that lives at the repo root. Launch from the repository root, or run `/reload-plugins` after changing directories.400 Project-scope `@skills-dir` plugins load only from the `.claude/skills/` of the directory where you start Claude Code. They don't [walk up to the repository root](/docs/en/skills#discovery-from-parent-and-nested-directories) the way plain skills and commands do, so launching from a subdirectory misses a plugin that lives at the repo root. Launch from the repository root, or run `/reload-plugins` after changing directories.

401</Warning>401</Warning>

402 402 

403### Edit, reload, and disable a skills-directory plugin403### Edit, reload, and disable a skills-directory plugin


953# Install to project scope (shared with team)953# Install to project scope (shared with team)

954claude plugin install formatter@my-marketplace --scope project954claude plugin install formatter@my-marketplace --scope project

955 955 

956# Install to local scope (gitignored)956# Install to local scope (not shared with team)

957claude plugin install formatter@my-marketplace --scope local957claude plugin install formatter@my-marketplace --scope local

958```958```

959 959 


1187### Common issues1187### Common issues

1188 1188 

1189| Issue | Cause | Solution |1189| Issue | Cause | Solution |

1190| :---------------------------------- | :------------------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------- |1190| :---------------------------------- | :------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

1191| Plugin not loading | Invalid `plugin.json` | Run `claude plugin validate` or `/plugin validate` to check `plugin.json`, skill/agent/command frontmatter, and `hooks/hooks.json` for syntax and schema errors |1191| Plugin not loading | Invalid `plugin.json` | Run `claude plugin validate ./my-plugin` or `/plugin validate ./my-plugin`, where `./my-plugin` is your plugin directory, to check `plugin.json`, skill/agent/command frontmatter, and `hooks/hooks.json` for syntax and schema errors |

1192| Skills not appearing | Wrong directory structure | Ensure `skills/` or `commands/` is at the plugin root, not inside `.claude-plugin/` |1192| Skills not appearing | Wrong directory structure | Ensure `skills/` or `commands/` is at the plugin root, not inside `.claude-plugin/` |

1193| Hooks not firing | Script not executable | Run `chmod +x script.sh` |1193| Hooks not firing | Script not executable | Run `chmod +x script.sh` |

1194| MCP server fails | Missing `${CLAUDE_PLUGIN_ROOT}` | Use variable for all plugin paths |1194| MCP server fails | Missing `${CLAUDE_PLUGIN_ROOT}` | Use variable for all plugin paths |

Details

6 6 

7> Claude Code manages prompt caching automatically. See why a model switch triggers a slow uncached turn, what `/compact` costs, why CLAUDE.md edits don't apply mid-session, and how to check your cache hit rate.7> Claude Code manages prompt caching automatically. See why a model switch triggers a slow uncached turn, what `/compact` costs, why CLAUDE.md edits don't apply mid-session, and how to check your cache hit rate.

8 8 

9Prompt caching makes Claude Code faster and more cost-efficient. Without caching, the API would reprocess your full history on every turn. With caching, it reuses what it already processed and only does new work for what changed.9Prompt caching makes Claude Code faster and more cost-efficient. Without caching, the API would reprocess your full history on every turn. With caching, it reuses what it already processed, bills the re-read at the [cached token rate](https://platform.claude.com/docs/en/about-claude/pricing), and fully processes only what changed.

10 10 

11Claude Code handles prompt caching for you, unless you [disable it](#disable-prompt-caching). It is still useful to know how prompt caching works, because some actions invalidate the cache and make the next response slower and more expensive while it rebuilds. This page covers which actions those are, why some settings wait for a restart to apply, and how to check cache performance when usage looks high.11Claude Code handles prompt caching for you, unless you [disable it](#disable-prompt-caching). It is still useful to know how prompt caching works, because some actions invalidate the cache and make the next response slower and more expensive while it rebuilds. This page covers which actions those are, why some settings wait for a restart to apply, and how to check cache performance when usage looks high.

12 12 


92Tool definitions sit in the system prompt layer, so the cache invalidates when the set of tool definitions in the request changes between turns. Toggling the [advisor tool](/docs/en/advisor) is an exception: its definition sits after the cache breakpoint, so enabling or disabling `/advisor` keeps the cached prefix intact. Whether an [MCP server](/docs/en/mcp) change does this depends on whether its tools are deferred by [tool search](/docs/en/mcp#scale-with-mcp-tool-search) or loaded into the prefix:92Tool definitions sit in the system prompt layer, so the cache invalidates when the set of tool definitions in the request changes between turns. Toggling the [advisor tool](/docs/en/advisor) is an exception: its definition sits after the cache breakpoint, so enabling or disabling `/advisor` keeps the cached prefix intact. Whether an [MCP server](/docs/en/mcp) change does this depends on whether its tools are deferred by [tool search](/docs/en/mcp#scale-with-mcp-tool-search) or loaded into the prefix:

93 93 

94* **Deferred tools**, the default on supported models: a server connecting, disconnecting, or changing its tool list only appends new content and doesn't disturb anything already cached.94* **Deferred tools**, the default on supported models: a server connecting, disconnecting, or changing its tool list only appends new content and doesn't disturb anything already cached.

95* **Tools loaded into the prefix**: any change to them invalidates the cache. This happens when [tool search is unavailable or disabled](/docs/en/mcp#configure-tool-search), such as on Google Cloud's Agent Platform or with a custom `ANTHROPIC_BASE_URL` gateway. It also happens for a server or tool marked [`alwaysLoad`](/docs/en/mcp#exempt-a-server-from-deferral), and for definitions kept upfront by [threshold-based loading](/docs/en/mcp#configure-tool-search).95* **Tools loaded into the prefix**: any change to them invalidates the cache. This happens when [tool search is unavailable or disabled](/docs/en/mcp#configure-tool-search), such as on Google Cloud's Agent Platform, with a custom `ANTHROPIC_BASE_URL` gateway, or on a Microsoft Foundry [deployment hosted on Azure](https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry#hosting-options) once Claude Code detects that the deployment rejects tool search. It also happens for a server or tool marked [`alwaysLoad`](/docs/en/mcp#exempt-a-server-from-deferral), and for definitions kept upfront by [threshold-based loading](/docs/en/mcp#configure-tool-search).

96 96 

97When tools load into the prefix, the most common cause of an invalidation is a server connecting or disconnecting mid-session, which can happen without any action on your part: a stdio server's process exits, an HTTP session expires, or a server [reconnects automatically after a transient failure](/docs/en/mcp#automatic-reconnection). A connected server can also push a [dynamic tool update](/docs/en/mcp#dynamic-tool-updates) that changes its tool list.97When tools load into the prefix, the most common cause of an invalidation is a server connecting or disconnecting mid-session, which can happen without any action on your part: a stdio server's process exits, an HTTP session expires, or a server [reconnects automatically after a transient failure](/docs/en/mcp#automatic-reconnection). A connected server can also push a [dynamic tool update](/docs/en/mcp#dynamic-tool-updates) that changes its tool list.

98 98 


118 118 

119[Compaction](/docs/en/context-window#what-survives-compaction) replaces your message history with a summary. By design, this invalidates the conversation layer, since the next request has a new, shorter history that doesn't share a prefix with the old one. Claude Code reuses the system prompt layer and reloads project context from disk, which cache-hits only if CLAUDE.md and memory are unchanged since the session started.119[Compaction](/docs/en/context-window#what-survives-compaction) replaces your message history with a summary. By design, this invalidates the conversation layer, since the next request has a new, shorter history that doesn't share a prefix with the old one. Claude Code reuses the system prompt layer and reloads project context from disk, which cache-hits only if CLAUDE.md and memory are unchanged since the session started.

120 120 

121To produce the summary, Claude Code sends a one-off request with the same system prompt, tools, and history as your conversation, plus a summarization instruction appended as a final user message. Because it shares your prefix, that request reads the existing cache rather than reprocessing the full history. Most of compaction's time goes to generating the summary, not to a cache miss. The turn that follows rebuilds the conversation cache only for the much shorter summary, so the post-compaction turn is not the slow part.121To produce the summary, Claude Code sends a separate request with the same system prompt, tools, and history as your conversation, plus a summarization instruction appended as a final user message. While the cache is warm, that request reads your prefix from the cache, so a mid-session `/compact` costs a fraction of what the context size suggests and spends most of its time generating the summary.

122 

123After a break longer than the [cache lifetime](#cache-lifetime), there is no cache left to read, so the summarization request reprocesses the full history as uncached input. This is why `/compact` costs the most when you [resume an old session](/docs/en/sessions#resume-from-a-summary). In both the warm and cold cases, the turn after compaction rebuilds the conversation cache for only the much shorter summary, so that turn is not the slow part.

122 124 

123<Tip>125<Tip>

124 Compaction works in your favor when the context you discard is content you no longer need. To choose when its overhead happens, run `/compact` at a natural break in your work, such as between tasks, instead of waiting for auto-compaction to trigger mid-task. If you've gone down a path you want to abandon entirely, [`/rewind`](#rewinding-the-conversation) to an earlier turn instead. Rewinding truncates back to a prefix that is already cached, rather than building a new one as compaction does.126 Compaction works in your favor when the context you discard is content you no longer need. To choose when its overhead happens, run `/compact` at a natural break in your work, such as between tasks, instead of waiting for auto-compaction to trigger mid-task. If you've gone down a path you want to abandon entirely, [`/rewind`](#rewinding-the-conversation) to an earlier turn instead. Rewinding truncates back to a prefix that is already cached, rather than building a new one as compaction does.


181 183 

182Cached prefixes expire after a period of inactivity. Each request that hits the cache resets the timer, so the cache stays warm as long as you keep working. After a long enough gap, the next request recomputes the full input and re-establishes the cache, which is why the first turn back after stepping away can be noticeably slower.184Cached prefixes expire after a period of inactivity. Each request that hits the cache resets the timer, so the cache stays warm as long as you keep working. After a long enough gap, the next request recomputes the full input and re-establishes the cache, which is why the first turn back after stepping away can be noticeably slower.

183 185 

186On a Pro or Max plan, when you resume a large session after a long break, Claude Code [offers to resume from a summary](/docs/en/sessions#resume-from-a-summary) so later requests don't carry the full history.

187 

184The time to live (TTL) controls how long a gap the cache survives. The API offers two: a five-minute TTL, and a [one-hour TTL](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#1-hour-cache-duration) that keeps the cache warm through longer breaks but [bills cache writes at a higher rate](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pricing). Claude Code picks the TTL for you based on how you authenticate, and you can override it with environment variables.188The time to live (TTL) controls how long a gap the cache survives. The API offers two: a five-minute TTL, and a [one-hour TTL](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#1-hour-cache-duration) that keeps the cache warm through longer breaks but [bills cache writes at a higher rate](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pricing). Claude Code picks the TTL for you based on how you authenticate, and you can override it with environment variables.

185 189 

186### On a Claude subscription190### On a Claude subscription

187 191 

188On a Claude subscription, Claude Code requests the one-hour TTL automatically. Usage is included in your plan rather than billed per token, so the longer TTL costs you nothing extra and only affects how long your cache stays warm.192On a Claude subscription, Claude Code requests the one-hour TTL automatically, so the cache survives breaks of up to an hour.

189 193 

190If you've gone over your plan's usage limit and Claude Code is drawing on [usage credits](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans), you are billed for that usage, so Claude Code automatically drops the TTL to five minutes.194If you've gone over your plan's usage limit and Claude Code is drawing on [usage credits](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans), you are billed for that usage. Cache writes cost more at the one-hour TTL than at the five-minute TTL, so Claude Code automatically drops to the shorter one.

191 195 

192### On an API key or third-party provider196### On an API key or third-party provider

193 197 

quickstart.md +16 −16

Details

13Make sure you have:13Make sure you have:

14 14 

15* A terminal or command prompt open15* A terminal or command prompt open

16 * If you've never used the terminal before, check out the [terminal guide](/en/terminal-guide)16 * If you've never used the terminal before, check out the [terminal guide](/docs/en/terminal-guide)

17* A code project to work with17* A code project to work with

18* A [Claude subscription](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=quickstart_prereq) (Pro, Max, Team, or Enterprise), [Claude Console](https://console.anthropic.com/) account, or access through a [supported cloud provider](/en/third-party-integrations)18* A [Claude subscription](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=quickstart_prereq) (Pro, Max, Team, or Enterprise), [Claude Console](https://console.anthropic.com/) account, or access through a [supported cloud provider](/docs/en/third-party-integrations)

19 19 

20<Note>20<Note>

21 This guide covers the terminal CLI. Claude Code is also available on the [web](https://claude.ai/code), as a [desktop app](/en/desktop), in [VS Code](/en/vs-code) and [JetBrains IDEs](/en/jetbrains), in [Slack](/en/slack), and in CI/CD with [GitHub Actions](/en/github-actions) and [GitLab](/en/gitlab-ci-cd). See [all interfaces](/en/overview#use-claude-code-everywhere).21 This guide covers the terminal CLI. Claude Code is also available on the [web](https://claude.ai/code), as a [desktop app](/docs/en/desktop), in [VS Code](/docs/en/vs-code) and [JetBrains IDEs](/docs/en/jetbrains), in [Slack](/docs/en/slack), and in CI/CD with [GitHub Actions](/docs/en/github-actions) and [GitLab](/docs/en/gitlab-ci-cd). See [all interfaces](/docs/en/overview#use-claude-code-everywhere).

22</Note>22</Note>

23 23 

24## Step 1: Install Claude Code24## Step 1: Install Claude Code


47 47 

48 If you see `The token '&&' is not a valid statement separator`, you're in PowerShell, not CMD. If you see `'irm' is not recognized as an internal or external command`, you're in CMD, not PowerShell. Your prompt shows `PS C:\` when you're in PowerShell and `C:\` without the `PS` when you're in CMD.48 If you see `The token '&&' is not a valid statement separator`, you're in PowerShell, not CMD. If you see `'irm' is not recognized as an internal or external command`, you're in CMD, not PowerShell. Your prompt shows `PS C:\` when you're in PowerShell and `C:\` without the `PS` when you're in CMD.

49 49 

50 If the install command fails with `syntax error near unexpected token '<'`, a `403`, or another curl error, see [Troubleshoot installation](/en/troubleshoot-install#find-your-error) to match the error to a fix and for alternative install methods.50 If the install command fails with `syntax error near unexpected token '<'`, a `403`, or another curl error, see [Troubleshoot installation](/docs/en/troubleshoot-install#find-your-error) to match the error to a fix and for alternative install methods.

51 51 

52 [Git for Windows](https://git-scm.com/downloads/win) is recommended on native Windows so Claude Code can use the Bash tool. If Git for Windows is not installed, Claude Code uses PowerShell as the shell tool instead. WSL setups do not need Git for Windows.52 [Git for Windows](https://git-scm.com/downloads/win) is recommended on native Windows so Claude Code can use the Bash tool. If Git for Windows is not installed, Claude Code uses PowerShell as the shell tool instead. WSL setups do not need Git for Windows.

53 53 


79 </Tab>79 </Tab>

80</Tabs>80</Tabs>

81 81 

82You can also install with [apt, dnf, or apk](/en/setup#install-with-linux-package-managers) on Debian, Fedora, RHEL, and Alpine.82You can also install with [apt, dnf, or apk](/docs/en/setup#install-with-linux-package-managers) on Debian, Fedora, RHEL, and Alpine.

83 83 

84To confirm the installation worked, run:84To confirm the installation worked, run:

85 85 


97claude97claude

98```98```

99 99 

100For Claude subscription or Console accounts, follow the prompts to complete authentication in your browser. To switch accounts later or re-authenticate, type `/login` inside the running session:100For Claude subscription or Console accounts, follow the prompts to complete authentication in your browser. If you've set the `ANTHROPIC_API_KEY` environment variable, Claude Code skips the login prompt and asks you to approve the key instead. To switch accounts later or re-authenticate, type `/login` inside the running session:

101 101 

102```text theme={null}102```text theme={null}

103/login103/login


107 107 

108* [Claude Pro, Max, Team, or Enterprise](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=quickstart_login) (recommended)108* [Claude Pro, Max, Team, or Enterprise](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=quickstart_login) (recommended)

109* [Claude Console](https://console.anthropic.com/) (API access with pre-paid credits). On first login, a "Claude Code" workspace is automatically created in the Console for centralized cost tracking.109* [Claude Console](https://console.anthropic.com/) (API access with pre-paid credits). On first login, a "Claude Code" workspace is automatically created in the Console for centralized cost tracking.

110* [Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry](/en/third-party-integrations) (enterprise cloud providers)110* [Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry](/docs/en/third-party-integrations) (enterprise cloud providers)

111* A self-hosted [Claude apps gateway](/en/claude-apps-gateway), if your organization runs one: your admin pre-configures the gateway URL, and `/login` opens directly on the **Cloud gateway** screen for you to sign in with corporate SSO111* A self-hosted [Claude apps gateway](/docs/en/claude-apps-gateway), if your organization runs one: your admin pre-configures the gateway URL, and `/login` opens directly on the **Cloud gateway** screen for you to sign in with corporate SSO

112 112 

113Once logged in, your credentials are stored and you won't need to log in again.113Once logged in, your credentials are stored and you won't need to log in again.

114 114 


126You'll see the Claude Code prompt with the version, current model, and working directory shown above it. Type `/help` for available commands or `/resume` to continue a previous conversation.126You'll see the Claude Code prompt with the version, current model, and working directory shown above it. Type `/help` for available commands or `/resume` to continue a previous conversation.

127 127 

128<Tip>128<Tip>

129 After logging in (Step 2), your credentials are stored on your system. Learn more in [Credential Management](/en/authentication#credential-management).129 After logging in (Step 2), your credentials are stored on your system. Learn more in [Credential Management](/docs/en/authentication#credential-management).

130</Tip>130</Tip>

131 131 

132## Step 4: Ask your first question132## Step 4: Ask your first question


1854. Make the edit1854. Make the edit

186 186 

187<Note>187<Note>

188 Whether Claude Code asks before changing files depends on your [permission mode](/en/permission-modes). In default mode, Claude asks for approval before each change. Press `Shift+Tab` to cycle through modes: `acceptEdits` auto-approves file edits, and `plan` lets Claude propose changes without editing. Some accounts also have an `auto` mode that runs a background safety check and blocks risky actions, returning to prompts only after repeated blocks.188 Whether Claude Code asks before changing files depends on your [permission mode](/docs/en/permission-modes). In default mode, Claude asks for approval before each change. Press `Shift+Tab` to cycle through modes: `acceptEdits` auto-approves file edits, and `plan` lets Claude propose changes without editing. Some accounts also have an `auto` mode that runs a background safety check and blocks risky actions, returning to prompts only after repeated blocks.

189</Note>189</Note>

190 190 

191## Step 6: Use Git with Claude Code191## Step 6: Use Git with Claude Code


291| `/help` | Show available commands | `/help` |291| `/help` | Show available commands | `/help` |

292| `/exit` or Ctrl+D twice | Exit Claude Code | `/exit` |292| `/exit` or Ctrl+D twice | Exit Claude Code | `/exit` |

293 293 

294See the [CLI reference](/en/cli-reference) for the complete list of shell commands and the [commands reference](/en/commands) for the complete list of session commands.294See the [CLI reference](/docs/en/cli-reference) for the complete list of shell commands and the [commands reference](/docs/en/commands) for the complete list of session commands.

295 295 

296## Pro tips for beginners296## Pro tips for beginners

297 297 

298For more, see [best practices](/en/best-practices) and [common workflows](/en/common-workflows).298For more, see [best practices](/docs/en/best-practices) and [common workflows](/docs/en/common-workflows).

299 299 

300<AccordionGroup>300<AccordionGroup>

301 <Accordion title="Be specific with your requests">301 <Accordion title="Be specific with your requests">


339Now that you've learned the basics, explore more advanced features:339Now that you've learned the basics, explore more advanced features:

340 340 

341<CardGroup cols={2}>341<CardGroup cols={2}>

342 <Card title="How Claude Code works" icon="microchip" href="/en/how-claude-code-works">342 <Card title="How Claude Code works" icon="microchip" href="/docs/en/how-claude-code-works">

343 Understand the agentic loop, built-in tools, and how Claude Code interacts with your project343 Understand the agentic loop, built-in tools, and how Claude Code interacts with your project

344 </Card>344 </Card>

345 345 

346 <Card title="Best practices" icon="star" href="/en/best-practices">346 <Card title="Best practices" icon="star" href="/docs/en/best-practices">

347 Get better results with effective prompting and project setup347 Get better results with effective prompting and project setup

348 </Card>348 </Card>

349 349 

350 <Card title="Common workflows" icon="graduation-cap" href="/en/common-workflows">350 <Card title="Common workflows" icon="graduation-cap" href="/docs/en/common-workflows">

351 Step-by-step guides for common tasks351 Step-by-step guides for common tasks

352 </Card>352 </Card>

353 353 

354 <Card title="Extend Claude Code" icon="puzzle-piece" href="/en/features-overview">354 <Card title="Extend Claude Code" icon="puzzle-piece" href="/docs/en/features-overview">

355 Customize with CLAUDE.md, skills, hooks, MCP, and more355 Customize with CLAUDE.md, skills, hooks, MCP, and more

356 </Card>356 </Card>

357</CardGroup>357</CardGroup>

Details

30* **Subscription**: available on Pro, Max, Team, and Enterprise plans. API keys are not supported. On Team and Enterprise, an Owner must first enable the Remote Control toggle in [Claude Code admin settings](https://claude.ai/admin-settings/claude-code).30* **Subscription**: available on Pro, Max, Team, and Enterprise plans. API keys are not supported. On Team and Enterprise, an Owner must first enable the Remote Control toggle in [Claude Code admin settings](https://claude.ai/admin-settings/claude-code).

31* **Authentication**: run `claude` and use `/login` to sign in through claude.ai if you haven't already. Without an eligible login, `claude remote-control` exits with an error, while `claude --remote-control` still starts an interactive session and shows a Remote Control failure notification shortly after launch.31* **Authentication**: run `claude` and use `/login` to sign in through claude.ai if you haven't already. Without an eligible login, `claude remote-control` exits with an error, while `claude --remote-control` still starts an interactive session and shows a Remote Control failure notification shortly after launch.

32* **API endpoint**: not available on Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry. {/* min-version: 2.1.196 */}As of v2.1.196, Remote Control is also disabled when [`ANTHROPIC_BASE_URL`](/docs/en/env-vars) points at a host other than `api.anthropic.com`, such as an [LLM gateway](/docs/en/llm-gateway) or proxy. Unset the variable to use Remote Control.32* **API endpoint**: not available on Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry. {/* min-version: 2.1.196 */}As of v2.1.196, Remote Control is also disabled when [`ANTHROPIC_BASE_URL`](/docs/en/env-vars) points at a host other than `api.anthropic.com`, such as an [LLM gateway](/docs/en/llm-gateway) or proxy. Unset the variable to use Remote Control.

33* **Feature-flag evaluation**: [`DISABLE_TELEMETRY`, `DO_NOT_TRACK`, `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, and `DISABLE_GROWTHBOOK`](/docs/en/env-vars) each disable the feature-flag evaluation that Remote Control availability depends on. Unset the variable wherever it's set, in your shell environment or in the `env` block of a [`settings.json` file](/docs/en/settings#available-settings), to use Remote Control.

33* **Workspace trust**: run `claude` in your project directory at least once to accept the workspace trust dialog. The startup trust dialog never saves trust for your home directory, so start Remote Control from a project directory.34* **Workspace trust**: run `claude` in your project directory at least once to accept the workspace trust dialog. The startup trust dialog never saves trust for your home directory, so start Remote Control from a project directory.

34 35 

35## Start a Remote Control session36## Start a Remote Control session


59 | `--[no-]create-session-in-dir` | Pre-create one session in the current directory when the server starts, so you have somewhere to type immediately. In `worktree` mode this session stays in the current directory while on-demand sessions get isolated worktrees. On by default; pass `--no-create-session-in-dir` to start with none. |60 | `--[no-]create-session-in-dir` | Pre-create one session in the current directory when the server starts, so you have somewhere to type immediately. In `worktree` mode this session stays in the current directory while on-demand sessions get isolated worktrees. On by default; pass `--no-create-session-in-dir` to start with none. |

60 | `--verbose` | Show detailed connection and session logs. |61 | `--verbose` | Show detailed connection and session logs. |

61 | `--sandbox` / `--no-sandbox` | Enable or disable [sandboxing](/docs/en/sandboxing) for filesystem and network isolation. Off by default. |62 | `--sandbox` / `--no-sandbox` | Enable or disable [sandboxing](/docs/en/sandboxing) for filesystem and network isolation. Off by default. |

63 

64 Claude Code checks Remote Control eligibility before printing help, so `claude remote-control --help` returns an error instead of this flag list when you aren't signed in with an eligible account.

62 </Tab>65 </Tab>

63 66 

64 <Tab title="Interactive session">67 <Tab title="Interactive session">


150 153 

151### Enable Remote Control for all sessions154### Enable Remote Control for all sessions

152 155 

153Remote Control only activates when you explicitly run `claude remote-control`, `claude --remote-control`, or `/remote-control`, unless auto-connect is turned on. 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 to `false` to never auto-connect, or leave it unset to follow your organization's default. In the Desktop app, you can also toggle this from **Settings → Claude Code → Enable remote control by default**. {/* min-version: 2.1.203 */}In the [VS Code extension](/docs/en/vs-code#use-the-prompt-box), the same toggle appears as **Enable Remote Control for all sessions** in the command menu's Settings section; requires Claude Code v2.1.203 or later.156Remote Control only activates when you explicitly run `claude remote-control`, `claude --remote-control`, or `/remote-control`, unless auto-connect is turned on. 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 to `false` to never auto-connect, or to `default` to clear your choice. When the setting is cleared, Remote Control follows your organization's admin default if one is set, and otherwise Claude Code's current default. In the Desktop app, you can also toggle this from **Settings → Claude Code → Enable remote control by default**. {/* min-version: 2.1.203 */}In the [VS Code extension](/docs/en/vs-code#use-the-prompt-box), the same toggle appears as **Enable Remote Control for all sessions** in the command menu's Settings section; requires Claude Code v2.1.203 or later.

154 157 

155With 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](#start-a-remote-control-session) instead.158With this setting on, each interactive Claude Code process registers one remote session. If you run multiple instances, each one gets its own remote session. To run multiple concurrent sessions from a single process, use [server mode](#start-a-remote-control-session) instead.

156 159 

157## Connection and security160## Connection and security

158 161 


262## Limitations265## Limitations

263 266 

264* **One remote session per interactive process**: outside of server mode, each Claude Code instance supports one remote session at a time. Use [server mode](#start-a-remote-control-session) to run multiple concurrent sessions from a single process.267* **One remote session per interactive process**: outside of server mode, each Claude Code instance supports one remote session at a time. Use [server mode](#start-a-remote-control-session) to run multiple concurrent sessions from a single process.

265* **Local process must keep running**: Remote Control runs as a local process. If you close the terminal, quit VS Code, or otherwise stop the `claude` process, the session ends.268* **Local process must keep running**: Remote Control runs as a local process. If you close the terminal, quit VS Code, or otherwise stop the `claude` process, the session ends. To keep a session running on a remote machine after you disconnect from SSH, start it inside `tmux` or `screen`.

266* **Extended network outage**: if your machine is awake but unable to reach the network for more than roughly 10 minutes, the session times out and the process exits. Run `claude remote-control` again to start a new session.269* **Extended network outage**: if your machine is awake but unable to reach the network for more than roughly 10 minutes, the session times out and the process exits. Run `claude remote-control` again to start a new session.

267* **Ultraplan disconnects Remote Control**: starting an [ultraplan](/docs/en/ultraplan) session disconnects any active Remote Control session because both features occupy the claude.ai/code interface and only one can be connected at a time.270* **Ultraplan disconnects Remote Control**: starting an [ultraplan](/docs/en/ultraplan) session disconnects any active Remote Control session because both features occupy the claude.ai/code interface and only one can be connected at a time.

268* **Some commands are local-only**: commands that only run in the terminal interface, such as `/plugin` or `/resume`, work only from the local CLI, whether or not you pass an argument. The following work from mobile and web:271* **Some commands are local-only**: commands that only run in the terminal interface, such as `/plugin` or `/resume`, work only from the local CLI, whether or not you pass an argument. The following work from mobile and web:


290 293 

291### "Remote Control is not yet enabled for your account"294### "Remote Control is not yet enabled for your account"

292 295 

293The Remote Control rollout has not reached your account, or your cached entitlements are out of date. If you recently changed plans, run `claude auth logout` then `claude auth login` to refresh them. Run `claude doctor` to see which individual eligibility check failed. Environment-variable conflicts, unreachable checks, and organization policy each produce their own message, so this error means the rollout gate itself.296The Remote Control rollout has not reached your account, or your cached entitlements are out of date. If you recently changed plans, run `claude auth logout` then `claude auth login` to refresh them. Run `claude doctor` to see which individual eligibility check failed. Environment-variable conflicts, unreachable checks, and organization policy each produce their own message, so this error means the rollout gate itself. {/* min-version: 2.1.154 */}Before v2.1.154, a variable that disables feature-flag evaluation, such as `DISABLE_TELEMETRY` or `DO_NOT_TRACK`, also produced this message; the "Remote Control requires feature-flag evaluation" entry below covers that configuration.

294 297 

295### "Couldn't verify Remote Control eligibility"298### "Couldn't verify Remote Control eligibility"

296 299 

297Claude Code could not reach the feature-flag service to check whether Remote Control is enabled for your account, typically because you are offline or a proxy is blocking the request. Retry once you have network access, or run `claude doctor` for details. The related message "Couldn't verify your organization's Remote Control policy" has the same cause and the same fix. Both messages were added in v2.1.178.300Claude Code could not reach the feature-flag service to check whether Remote Control is enabled for your account, typically because you are offline or a proxy is blocking the request. Retry once you have network access, or run `claude doctor` for details. The related message "Couldn't verify your organization's Remote Control policy" has the same cause and the same fix. Both messages were added in v2.1.178.

298 301 

302### "Remote Control requires feature-flag evaluation"

303 

304One of these variables is set: [`DISABLE_TELEMETRY`, `DO_NOT_TRACK`, `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, or `DISABLE_GROWTHBOOK`](/docs/en/env-vars). Each of them disables the feature-flag evaluation that Remote Control availability depends on, and the full message names the variable Claude Code found. Unset that variable wherever it's set, in your shell environment or in the `env` block of a [`settings.json` file](/docs/en/settings#available-settings). On versions before 2.1.154, the same configuration produces "Remote Control is not yet enabled for your account" instead.

305 

299### "Remote Control is only available when using Claude via api.anthropic.com"306### "Remote Control is only available when using Claude via api.anthropic.com"

300 307 

301The session isn't talking to the Anthropic API directly, so there is no claude.ai backend to pair with. This happens on Amazon Bedrock, Google Cloud's Agent Platform, and Microsoft Foundry. {/* min-version: 2.1.196 */}It also happens when [`ANTHROPIC_BASE_URL`](/docs/en/env-vars) points at a host other than `api.anthropic.com`, such as an [LLM gateway](/docs/en/llm-gateway) or proxy, even if you sign in with claude.ai. Before v2.1.196, Claude Code didn't show this message for a custom `ANTHROPIC_BASE_URL`. See the [error reference](/docs/en/errors#remote-control-requires-the-anthropic-api) for the full cause list.308The session isn't talking to the Anthropic API directly, so there is no claude.ai backend to pair with. This happens on Amazon Bedrock, Google Cloud's Agent Platform, and Microsoft Foundry. {/* min-version: 2.1.196 */}It also happens when [`ANTHROPIC_BASE_URL`](/docs/en/env-vars) points at a host other than `api.anthropic.com`, such as an [LLM gateway](/docs/en/llm-gateway) or proxy, even if you sign in with claude.ai. Before v2.1.196, Claude Code didn't show this message for a custom `ANTHROPIC_BASE_URL`. See the [error reference](/docs/en/errors#remote-control-requires-the-anthropic-api) for the full cause list.


355 362 

356## Related resources363## Related resources

357 364 

358* [Claude Code on the web](/docs/en/claude-code-on-the-web): run sessions in Anthropic-managed cloud environments instead of on your machine365* [Claude Code on the web](/docs/en/claude-code-on-the-web): run sessions on Anthropic-managed infrastructure instead of your machine, configured through [cloud environments](/docs/en/cloud-environments)

359* [Ultraplan](/docs/en/ultraplan): launch a cloud planning session from your terminal and review the plan in your browser366* [Ultraplan](/docs/en/ultraplan): launch a cloud planning session from your terminal and review the plan in your browser

360* [Channels](/docs/en/channels): forward Telegram, Discord, or iMessage into a session so Claude reacts to messages while you're away367* [Channels](/docs/en/channels): forward Telegram, Discord, or iMessage into a session so Claude reacts to messages while you're away

361* [Dispatch](/docs/en/desktop#sessions-from-dispatch): message a task from your phone and it can spawn a Desktop session to handle it368* [Dispatch](/docs/en/desktop#sessions-from-dispatch): message a task from your phone and it can spawn a Desktop session to handle it

routines.md +10 −10

Details

50 50 

51The creation form sets up the routine's prompt, repositories, environment, connectors, and triggers.51The creation form sets up the routine's prompt, repositories, environment, connectors, and triggers.

52 52 

53Routines run autonomously as full Claude Code cloud sessions: there is no permission-mode picker and no approval prompts during a run. The session can run shell commands, use [skills](/docs/en/skills) committed to the cloned repository, and call any connectors you include. What a routine can reach is determined by the repositories you select and their branch-push setting, the [environment's](/docs/en/claude-code-on-the-web#the-cloud-environment) network access and variables, and the connectors you include. Scope each of those to what the routine actually needs.53Routines run autonomously as full Claude Code cloud sessions: there is no permission-mode picker and no approval prompts during a run. The session can run shell commands, use [skills](/docs/en/skills) committed to the cloned repository, and call any connectors you include. What a routine can reach is determined by the repositories you select and their branch-push setting, the [environment's](/docs/en/cloud-environments) network access and variables, and the connectors you include. Scope each of those to what the routine actually needs.

54 54 

55Routines belong to your individual claude.ai account. They are not shared with teammates, and they count against your account's daily run allowance. Anything a routine does through your connected GitHub identity or connectors appears as you: commits and pull requests carry your GitHub user, and Slack messages, Linear tickets, or other connector actions use your linked accounts for those services.55Routines belong to your individual claude.ai account. They are not shared with teammates, and they count against your account's daily run allowance. Anything a routine does through your connected GitHub identity or connectors appears as you: commits and pull requests carry your GitHub user, and Slack messages, Linear tickets, or other connector actions use your linked accounts for those services.

56 56 


74 </Step>74 </Step>

75 75 

76 <Step title="Select an environment">76 <Step title="Select an environment">

77 Pick a [cloud environment](/docs/en/claude-code-on-the-web#the-cloud-environment) for the routine. Environments control what the cloud session has access to:77 Pick a [cloud environment](/docs/en/cloud-environments) for the routine. Environments control what the cloud session has access to:

78 78 

79 * **Network access**: set the level of internet access available during each run79 * **Network access**: set the level of internet access available during each run

80 * **Environment variables**: provide API keys, tokens, or other secrets Claude can use80 * **Environment variables**: provide values Claude can use during each run. They're [visible to anyone who uses the environment](/docs/en/cloud-environments#what-carries-over-from-your-setup), so add credentials with that in mind

81 * **Setup script**: install dependencies and tools the routine needs. The result is [cached](/docs/en/claude-code-on-the-web#environment-caching), so the script doesn't re-run on every session81 * **Setup script**: install dependencies and tools the routine needs. The result is [cached](/docs/en/cloud-environments#environment-caching), so the script doesn't re-run on every session

82 82 

83 A **Default** environment is provided with **Trusted** network access, which allows the [default set](/docs/en/claude-code-on-the-web#default-allowed-domains) of package registries, cloud provider APIs, container registries, and common development domains, but blocks everything else. If your routine needs to reach your own services or a domain outside that list, edit the environment's [network access](/docs/en/claude-code-on-the-web#network-access) before running. To use a separate environment, [create one](/docs/en/claude-code-on-the-web#configure-your-environment) first.83 A **Default** environment is provided with **Trusted** network access, which allows only the [default allowlist](/docs/en/cloud-environments#default-allowed-domains) of package registries, cloud provider APIs, container registries, and common development domains through the session's network. Connectors you add to the routine reach their services through Anthropic's servers, so they don't need allowlist changes. If your routine needs to reach your own services directly, or a domain outside that list, edit the environment's [network access](/docs/en/cloud-environments#network-access) before running. To use a separate environment, [create one](/docs/en/cloud-environments#configure-your-environment) first.

84 </Step>84 </Step>

85 85 

86 <Step title="Select a trigger">86 <Step title="Select a trigger">


340 340 

341### Environments and network access341### Environments and network access

342 342 

343Each routine runs in a [cloud environment](/docs/en/claude-code-on-the-web#the-cloud-environment) that controls network access, environment variables, and setup scripts. The routine inherits the environment's network policy on every run.343Each routine uses a [cloud environment](/docs/en/cloud-environments) that controls network access, environment variables, and setup scripts. The routine inherits the environment's network policy on every run.

344 344 

345The **Default** environment uses **Trusted** network access: the [default allowlist](/docs/en/claude-code-on-the-web#default-allowed-domains) of package registries, cloud provider APIs, container registries, and common development domains is reachable, but arbitrary domains are not. Outbound requests to other hosts fail with `403` and `x-deny-reason: host_not_allowed`. MCP connector traffic is routed through Anthropic's servers, so the connectors you add to the routine work without adding their hosts to **Allowed domains**. Remove any connectors you don't need under [Connectors](#connectors).345The **Default** environment uses **Trusted** network access, which allows only the [default allowlist](/docs/en/cloud-environments#default-allowed-domains) through the session's network. Requests on that path to hosts outside the allowlist fail with `403` and `x-deny-reason: host_not_allowed`. MCP connector traffic is routed through Anthropic's servers rather than that path, so the connectors you add to the routine work without adding their hosts to **Allowed domains**. Remove any connectors you don't need under [Connectors](#connectors).

346 346 

347To allow additional domains:347To allow additional domains:

348 348 


360 </Step>360 </Step>

361 361 

362 <Step title="Change the network access level">362 <Step title="Change the network access level">

363 In the **Update cloud environment** dialog, change **Network access** to **Custom** and enter your domains in **Allowed domains**. Check **Also include default list of common package managers** to keep the [default allowlist](/docs/en/claude-code-on-the-web#default-allowed-domains) alongside your custom domains. Select **Full** instead for unrestricted access.363 In the **Update cloud environment** dialog, change **Network access** to **Custom** and enter your domains in **Allowed domains**. Check **Also include default list of common package managers** to keep the [default allowlist](/docs/en/cloud-environments#default-allowed-domains) alongside your custom domains. Select **Full** instead for unrestricted access.

364 </Step>364 </Step>

365 365 

366 <Step title="Save">366 <Step title="Save">


368 </Step>368 </Step>

369</Steps>369</Steps>

370 370 

371See [Network access](/docs/en/claude-code-on-the-web#network-access) for details on access levels and the default allowlist.371See [Network access](/docs/en/cloud-environments#network-access) for details on access levels and the default allowlist.

372 372 

373## Usage and limits373## Usage and limits

374 374 


402 402 

403* [`/loop` and in-session scheduling](/docs/en/scheduled-tasks): schedule local tasks within an open CLI session403* [`/loop` and in-session scheduling](/docs/en/scheduled-tasks): schedule local tasks within an open CLI session

404* [Desktop scheduled tasks](/docs/en/desktop-scheduled-tasks): local scheduled tasks that run on your machine with access to local files404* [Desktop scheduled tasks](/docs/en/desktop-scheduled-tasks): local scheduled tasks that run on your machine with access to local files

405* [Cloud environment](/docs/en/claude-code-on-the-web#the-cloud-environment): configure the runtime environment for cloud sessions405* [Cloud environments](/docs/en/cloud-environments): configure network access, environment variables, and setup scripts for cloud sessions

406* [MCP connectors](/docs/en/mcp): connect external services like Slack, Linear, and Google Drive406* [MCP connectors](/docs/en/mcp): connect external services like Slack, Linear, and Google Drive

407* [GitHub Actions](/docs/en/github-actions): run Claude in your CI pipeline on repository events407* [GitHub Actions](/docs/en/github-actions): run Claude in your CI pipeline on repository events

Details

11Claude Code can run in several kinds of isolated environments, ranging from a lightweight per-command sandbox to a fully separate virtual machine. This page compares them by what they isolate and what they require, helps you choose one for your threat model, and shows how to enforce that choice across an organization.11Claude Code can run in several kinds of isolated environments, ranging from a lightweight per-command sandbox to a fully separate virtual machine. This page compares them by what they isolate and what they require, helps you choose one for your threat model, and shows how to enforce that choice across an organization.

12 12 

13<Info>13<Info>

14 For the broader security model, see [Security](/en/security). For Agent SDK deployments, see [Secure deployment](/en/agent-sdk/secure-deployment).14 For the broader security model, see [Security](/docs/en/security). For Agent SDK deployments, see [Secure deployment](/docs/en/agent-sdk/secure-deployment).

15</Info>15</Info>

16 16 

17## Compare sandboxing approaches17## Compare sandboxing approaches


19The first two approaches in the table below run on the host operating system without containers. The rest place Claude Code inside a container or virtual machine.19The first two approaches in the table below run on the host operating system without containers. The rest place Claude Code inside a container or virtual machine.

20 20 

21| Approach | What is isolated | Requires Docker | Setup effort |21| Approach | What is isolated | Requires Docker | Setup effort |

22| :------------------------------------------------ | :-------------------------------------------------------------------------- | :-------------- | :---------------------------------------------- |22| :------------------------------------------------ | :-------------------------------------------------------------------------- | :-------------- | :-------------------------------------------------------------------------------------- |

23| [Sandboxed Bash tool](#sandboxed-bash-tool) | Bash commands and their child processes | No | Minimal on macOS; low on Linux and WSL2 |23| [Sandboxed Bash tool](#sandboxed-bash-tool) | Bash commands and their child processes | No | Minimal on macOS; low on Linux and WSL2 |

24| [Sandbox runtime](#sandbox-runtime) | The whole Claude Code process, including file tools, MCP servers, and hooks | No | Low |24| [Sandbox runtime](#sandbox-runtime) | The whole Claude Code process, including file tools, MCP servers, and hooks | No | Low |

25| [Dev container](#dev-containers) | Full development environment | Yes | Medium |25| [Dev container](#dev-containers) | Full development environment | Yes | Medium |

26| [Custom container](#custom-container) | Full development environment | Yes | Medium to high |26| [Custom container](#custom-container) | Full development environment | Yes | Medium to high |

27| [Virtual machine](#virtual-machine) | Full operating system | No | High |27| [Virtual machine](#virtual-machine) | Full operating system | No | High |

28| [Claude Code on the web](#claude-code-on-the-web) | Full operating system, hosted by Anthropic | No | None; requires a Claude subscription and GitHub |28| [Claude Code on the web](#claude-code-on-the-web) | Full operating system, hosted by Anthropic | No | None; requires a Claude subscription, and GitHub when you launch from the web interface |

29 29 

30The [sandboxed Bash tool](/en/sandboxing) is built into Claude Code and restricts only Bash commands. Built-in file tools, MCP servers, and hooks still run directly on your host. Every other approach in the table puts the whole Claude Code process inside the isolation boundary, so file tools, MCP servers, and hooks are restricted too.30The [sandboxed Bash tool](/docs/en/sandboxing) is built into Claude Code and restricts only Bash commands. Built-in file tools, MCP servers, and hooks still run directly on your host. Every other approach in the table puts the whole Claude Code process inside the isolation boundary, so file tools, MCP servers, and hooks are restricted too.

31 31 

32<Warning>32<Warning>

33 Sandbox isolation reduces the impact of a breach, but it does not eliminate risk. Any approach that allows network egress can still leak data the agent can read, and any approach that mounts your project directory writable can still modify that code. Review the [security limitations](/en/sandboxing#security-limitations) before relying on a sandbox as a hard control.33 Sandbox isolation reduces the impact of a breach, but it does not eliminate risk. Any approach that allows network egress can still leak data the agent can read, and any approach that mounts your project directory writable can still modify that code. Review the [security limitations](/docs/en/sandboxing#security-limitations) before relying on a sandbox as a hard control.

34 34 

35 Isolation also does not change what is sent to the model. Your prompts and the files Claude reads are transmitted to the Anthropic API or your configured provider with or without a sandbox. See [Data usage](/en/data-usage) for what Claude Code sends and how to reduce it.35 Isolation also does not change what is sent to the model. Your prompts and the files Claude reads are transmitted to the Anthropic API or your configured provider with or without a sandbox. See [Data usage](/docs/en/data-usage) for what Claude Code sends and how to reduce it.

36</Warning>36</Warning>

37 37 

38## Choose an approach38## Choose an approach


40Match your goal to a row below, then read the detail section that follows.40Match your goal to a row below, then read the detail section that follows.

41 41 

42| You want to | Start with |42| You want to | Start with |

43| :---------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------- |43| :---------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

44| Reduce permission prompts during everyday work on your own machine | The [sandboxed Bash tool](/en/sandboxing), enabled with `/sandbox` |44| Reduce permission prompts during everyday work on your own machine | The [sandboxed Bash tool](/docs/en/sandboxing), enabled with `/sandbox` |

45| Let Claude work unattended with `--dangerously-skip-permissions` or auto mode | The preconfigured [dev container](/en/devcontainer), any container or VM, or the [sandbox runtime](#sandbox-runtime) |45| Let Claude work unattended with `--dangerously-skip-permissions` or auto mode | The preconfigured [dev container](/docs/en/devcontainer), any container or VM, or the [sandbox runtime](#sandbox-runtime) |

46| Isolate MCP servers and hooks as well as Bash, without Docker | The sandbox runtime |46| Isolate MCP servers and hooks as well as Bash, without Docker | The sandbox runtime |

47| Work on an untrusted repository | A dedicated virtual machine, or [Claude Code on the web](/en/claude-code-on-the-web) if you have a Claude subscription and a connected GitHub account |47| Work on an untrusted repository | A dedicated virtual machine, or [Claude Code on the web](/docs/en/claude-code-on-the-web) if you have a Claude subscription; GitHub is only required when you launch from the web interface |

48| Standardize a sandboxed environment across a team | The preconfigured [dev container](/en/devcontainer), copied into your repository |48| Standardize a sandboxed environment across a team | The preconfigured [dev container](/docs/en/devcontainer), copied into your repository |

49| Use Claude Code from a device with no local setup | [Claude Code on the web](/en/claude-code-on-the-web), which requires a Claude subscription and a connected GitHub account |49| Use Claude Code from a device with no local setup | [Claude Code on the web](/docs/en/claude-code-on-the-web), which requires a Claude subscription and a connected GitHub account |

50| Require isolation for every developer in your organization | [Enforce isolation across an organization](#enforce-isolation-across-an-organization) |50| Require isolation for every developer in your organization | [Enforce isolation across an organization](#enforce-isolation-across-an-organization) |

51| Work on a native Windows host | A container or VM, or run the Bash sandbox inside WSL2 |51| Work on a native Windows host | A container or VM, or run the Bash sandbox inside WSL2 |

52 52 

53### How isolation relates to permission modes53### How isolation relates to permission modes

54 54 

55[Permission modes](/en/permission-modes) decide whether a tool call runs and whether you are prompted first. Isolation restricts what a command can access once it runs. The two work together: when a permission mode lets actions run without asking you, an isolation boundary limits what those actions can reach.55[Permission modes](/docs/en/permission-modes) decide whether a tool call runs and whether you are prompted first. Isolation restricts what a command can access once it runs. The two work together: when a permission mode lets actions run without asking you, an isolation boundary limits what those actions can reach.

56 56 

57When you pass `--dangerously-skip-permissions`, Claude acts without asking you first; you're only prompted for explicit [ask rules](/en/permissions#manage-permissions), connector tools [your organization set to `ask`](/en/mcp#organization-controls-on-connector-tools), MCP tools marked [`requiresUserInteraction`](/en/mcp#require-approval-for-a-specific-tool), and removals targeting `/` or your home directory. With no prompts to catch mistakes, the isolation boundary you choose is what protects your system. Always run `--dangerously-skip-permissions` sessions inside a container, a VM, or the [sandbox runtime](#sandbox-runtime), so that file tools, MCP servers, and hooks are also inside the boundary.57When you pass `--dangerously-skip-permissions`, Claude acts without asking you first; you're only prompted for explicit [ask rules](/docs/en/permissions#manage-permissions), connector tools [your organization set to `ask`](/docs/en/mcp#organization-controls-on-connector-tools), MCP tools marked [`requiresUserInteraction`](/docs/en/mcp#require-approval-for-a-specific-tool), and removals targeting `/` or your home directory. With no prompts to catch mistakes, the isolation boundary you choose is what protects your system. Always run `--dangerously-skip-permissions` sessions inside a container, a VM, or the [sandbox runtime](#sandbox-runtime), so that file tools, MCP servers, and hooks are also inside the boundary.

58 58 

59[Auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) replaces the prompt with a classifier that reviews actions and blocks ones that escalate beyond the request, target unrecognized infrastructure, or appear driven by hostile content Claude read. The classifier is a per-action control, not an isolation boundary, so an isolation boundary still adds defense in depth for unattended runs, and is not required the way it is for `--dangerously-skip-permissions`.59[Auto mode](/docs/en/permission-modes#eliminate-prompts-with-auto-mode) replaces the prompt with a classifier that reviews actions and blocks ones that escalate beyond the request, target unrecognized infrastructure, or appear driven by hostile content Claude read. The classifier is a per-action control, not an isolation boundary, so an isolation boundary still adds defense in depth for unattended runs, and is not required the way it is for `--dangerously-skip-permissions`.

60 60 

61The [sandboxed Bash tool](#sandboxed-bash-tool) on its own constrains only Bash, so it is not sufficient for fully unattended runs in either mode. You can layer approaches: running the sandboxed Bash tool inside a container or VM gives you OS-level command restrictions on top of the outer environment boundary. For how the Bash sandbox itself interacts with permission rules and modes, see [How sandboxing relates to permissions and permission modes](/en/sandboxing#how-sandboxing-relates-to-permissions-and-permission-modes).61The [sandboxed Bash tool](#sandboxed-bash-tool) on its own constrains only Bash, so it is not sufficient for fully unattended runs in either mode. You can layer approaches: running the sandboxed Bash tool inside a container or VM gives you OS-level command restrictions on top of the outer environment boundary. For how the Bash sandbox itself interacts with permission rules and modes, see [How sandboxing relates to permissions and permission modes](/docs/en/sandboxing#how-sandboxing-relates-to-permissions-and-permission-modes).

62 62 

63## Sandboxed Bash tool63## Sandboxed Bash tool

64 64 


68 68 

69The sandboxed Bash tool is built into Claude Code. It uses operating system primitives to restrict the filesystem and network access of every Bash command Claude runs: Seatbelt, the built-in macOS sandbox, and [bubblewrap](https://github.com/containers/bubblewrap) on Linux and WSL2. By default it allows writes to the working directory and prompts the first time a command needs a new network domain.69The sandboxed Bash tool is built into Claude Code. It uses operating system primitives to restrict the filesystem and network access of every Bash command Claude runs: Seatbelt, the built-in macOS sandbox, and [bubblewrap](https://github.com/containers/bubblewrap) on Linux and WSL2. By default it allows writes to the working directory and prompts the first time a command needs a new network domain.

70 70 

71Enable it with the `/sandbox` command. The [Sandboxing](/en/sandboxing) guide covers the approval modes, the default boundary, and how to widen or narrow it.71Enable it with the `/sandbox` command. The [Sandboxing](/docs/en/sandboxing) guide covers the approval modes, the default boundary, and how to widen or narrow it.

72 72 

73The per-command sandbox does not cover everything that runs in a session:73The per-command sandbox does not cover everything that runs in a session:

74 74 

75* Other [built-in tools](/en/tools-reference) such as Read, Edit, and WebFetch run inside the Claude Code process and do not spawn arbitrary code. [Permission rules](/en/permissions) for path or domain gate them instead.75* Other [built-in tools](/docs/en/tools-reference) such as Read, Edit, and WebFetch run inside the Claude Code process and do not spawn arbitrary code. [Permission rules](/docs/en/permissions) for path or domain gate them instead.

76* [MCP](/en/mcp) servers and hooks are separate processes that run unconstrained on the host.76* [MCP](/docs/en/mcp) servers and hooks are separate processes that run unconstrained on the host.

77 77 

78To put built-in tools, MCP servers, and hooks all behind one OS boundary, run the whole Claude Code process inside the [sandbox runtime](#sandbox-runtime), the [dev container](#dev-containers), or a [custom container](#custom-container).78To put built-in tools, MCP servers, and hooks all behind one OS boundary, run the whole Claude Code process inside the [sandbox runtime](#sandbox-runtime), the [dev container](#dev-containers), or a [custom container](#custom-container).

79 79 


95 95 

96A dev container runs Claude Code inside a Docker container that VS Code or a compatible editor manages, with your project mounted in. You can define your own with a `.devcontainer/` directory in your repository.96A dev container runs Claude Code inside a Docker container that VS Code or a compatible editor manages, with your project mounted in. You can define your own with a `.devcontainer/` directory in your repository.

97 97 

98The claude-code repository publishes an [example dev container](/en/devcontainer) with a default-deny iptables firewall as a starting point. Copy it into your repository and adjust the firewall allowlist, base image, and pinned Claude Code version to fit your environment. Because the firewall blocks unapproved egress, a configuration like this supports running Claude Code with `--dangerously-skip-permissions` for unattended work.98The claude-code repository publishes an [example dev container](/docs/en/devcontainer) with a default-deny iptables firewall as a starting point. Copy it into your repository and adjust the firewall allowlist, base image, and pinned Claude Code version to fit your environment. Because the firewall blocks unapproved egress, a configuration like this supports running Claude Code with `--dangerously-skip-permissions` for unattended work.

99 99 

100## Custom container100## Custom container

101 101 


103 103 

104Several managed sandbox and remote execution services can host the container for you. The same checklist applies as for any container you operate: review what is mounted writable, what credentials and tokens are reachable inside it, and what the network egress policy allows.104Several managed sandbox and remote execution services can host the container for you. The same checklist applies as for any container you operate: review what is mounted writable, what credentials and tokens are reachable inside it, and what the network egress policy allows.

105 105 

106You can layer the built-in Bash sandbox inside the container for per-command restrictions. Unprivileged containers need the nested-sandbox setting described in [Sandboxing troubleshooting](/en/sandboxing#troubleshooting).106You can layer the built-in Bash sandbox inside the container for per-command restrictions. Unprivileged containers need the nested-sandbox setting described in [Sandboxing troubleshooting](/docs/en/sandboxing#troubleshooting).

107 107 

108## Virtual machine108## Virtual machine

109 109 


113 113 

114## Claude Code on the web114## Claude Code on the web

115 115 

116[Claude Code on the web](/en/claude-code-on-the-web) runs each session in an isolated, Anthropic-managed virtual machine. A network proxy enforces a default allowlist, and a separate proxy holds your GitHub token outside the sandbox while issuing scoped credentials for repository access inside it.116[Claude Code on the web](/docs/en/claude-code-on-the-web) runs each session in an isolated, Anthropic-managed virtual machine. A network proxy enforces a default allowlist, and a separate proxy holds your GitHub token outside the sandbox while issuing scoped credentials for repository access inside it.

117 117 

118Use this approach when you want full VM isolation without provisioning infrastructure yourself, or when you are delegating tasks from a device that does not have a local development environment. It requires a Claude subscription and a connected GitHub account, and sessions clone your repository from GitHub. See [Claude Code on the web](/en/claude-code-on-the-web) for plan availability and GitHub authentication options.118Use this approach when you want full VM isolation without provisioning infrastructure yourself, or when you are delegating tasks from a device that does not have a local development environment. It requires a Claude subscription. When you launch a session from the web interface, you also need a connected GitHub account so the sandbox can clone your repository. When you launch from the CLI with `--cloud`, Claude Code can [bundle and upload your local repository](/docs/en/claude-code-on-the-web#send-local-repositories-without-github) instead if GitHub isn't connected. See [Claude Code on the web](/docs/en/claude-code-on-the-web) for plan availability and GitHub authentication options.

119 119 

120## Enforce isolation across an organization120## Enforce isolation across an organization

121 121 

122Individual developers can opt into any approach above. What an organization can enforce, and with which tools, depends on the approach:122Individual developers can opt into any approach above. What an organization can enforce, and with which tools, depends on the approach:

123 123 

124* **Built-in Bash sandbox**: the only approach Claude Code enforces itself. Deliver the `sandbox` settings keys through [managed settings](/en/settings#settings-files), either as a file managed by your MDM or through [server-managed settings](/en/server-managed-settings) on Claude.ai. See [Enforce sandboxing with managed settings](/en/sandboxing#enforce-sandboxing-with-managed-settings) for the keys to deploy and how to keep developers from widening the policy.124* **Built-in Bash sandbox**: the only approach Claude Code enforces itself. Deliver the `sandbox` settings keys through [managed settings](/docs/en/settings#settings-files), either as a file managed by your MDM or through [server-managed settings](/docs/en/server-managed-settings) on Claude.ai. See [Enforce sandboxing with managed settings](/docs/en/sandboxing#enforce-sandboxing-with-managed-settings) for the keys to deploy and how to keep developers from widening the policy.

125* **Dev containers**: commit the [example dev container](/en/devcontainer) to your repositories to standardize the environment across a team. This is a convention rather than an enforcement boundary, because Claude Code does not require a container. If developers should not be able to run Claude Code outside it, enforce that with your organization's device management or software allowlisting tools.125* **Dev containers**: commit the [example dev container](/docs/en/devcontainer) to your repositories to standardize the environment across a team. This is a convention rather than an enforcement boundary, because Claude Code does not require a container. If developers should not be able to run Claude Code outside it, enforce that with your organization's device management or software allowlisting tools.

126* **Custom containers and VMs**: distribute Claude Code through the approved image and use your organization's device management or software allowlisting tools to prevent installation outside it.126* **Custom containers and VMs**: distribute Claude Code through the approved image and use your organization's device management or software allowlisting tools to prevent installation outside it.

127 127 

128## See also128## See also

129 129 

130These pages cover configuration and policy details for the approaches above.130These pages cover configuration and policy details for the approaches above.

131 131 

132* [Sandboxing](/en/sandboxing): configure the built-in sandboxed Bash tool132* [Sandboxing](/docs/en/sandboxing): configure the built-in sandboxed Bash tool

133* [Dev container](/en/devcontainer): the preconfigured Docker development container133* [Dev container](/docs/en/devcontainer): the preconfigured Docker development container

134* [Security](/en/security): the full Claude Code security model134* [Security](/docs/en/security): the full Claude Code security model

135* [Secure deployment](/en/agent-sdk/secure-deployment): isolation guidance for Agent SDK applications135* [Secure deployment](/docs/en/agent-sdk/secure-deployment): isolation guidance for Agent SDK applications

136* [Settings](/en/settings#sandbox-settings): all sandbox configuration keys, including managed settings delivery136* [Settings](/docs/en/settings#sandbox-settings): all sandbox configuration keys, including managed settings delivery

sandboxing.md +1 −1

Details

46 </Step>46 </Step>

47</Steps>47</Steps>

48 48 

49Selecting a mode in the panel writes to your project's local settings at `.claude/settings.local.json`, which apply to the current project and are not checked into git. To enable the sandbox across all of your projects, set [`sandbox.enabled`](/docs/en/settings#sandbox-settings) to `true` in your user settings at `~/.claude/settings.json`. To enforce sandboxing for every developer in an organization, use [managed settings](#enforce-sandboxing-with-managed-settings).49Selecting a mode in the panel writes to your project's local settings at `.claude/settings.local.json`, which apply to the current project. Claude Code adds that file to your global gitignore when it saves a setting there. To enable the sandbox across all of your projects, set [`sandbox.enabled`](/docs/en/settings#sandbox-settings) to `true` in your user settings at `~/.claude/settings.json`. To enforce sandboxing for every developer in an organization, use [managed settings](#enforce-sandboxing-with-managed-settings).

50 50 

51<Warning>51<Warning>

52 By default, if the sandbox cannot start because dependencies are missing or the platform is unsupported, Claude Code shows a warning and runs commands without sandboxing. To make this a hard failure instead, set [`sandbox.failIfUnavailable`](/docs/en/settings#sandbox-settings) to `true`. This is intended for managed deployments that require sandboxing as a security gate.52 By default, if the sandbox cannot start because dependencies are missing or the platform is unsupported, Claude Code shows a warning and runs commands without sandboxing. To make this a hard failure instead, set [`sandbox.failIfUnavailable`](/docs/en/settings#sandbox-settings) to `true`. This is intended for managed deployments that require sandboxing as a security gate.

security.md +23 −22

Details

16 16 

17Claude Code uses strict read-only permissions by default. When additional actions are needed (editing files, running tests, executing commands), Claude Code requests explicit permission. Users control whether to approve actions once or allow them automatically.17Claude Code uses strict read-only permissions by default. When additional actions are needed (editing files, running tests, executing commands), Claude Code requests explicit permission. Users control whether to approve actions once or allow them automatically.

18 18 

19Claude Code requires approval before running Bash commands that can modify your system. A built-in set of [read-only commands](/en/permissions#read-only-commands) such as `ls`, `cat`, and `git status` runs without a prompt. This approach lets users and organizations configure permissions directly.19Claude Code requires approval before running Bash commands that can modify your system. A built-in set of [read-only commands](/docs/en/permissions#read-only-commands) such as `ls`, `cat`, and `git status` runs without a prompt. This approach lets users and organizations configure permissions directly.

20 20 

21For detailed permission configuration, see [Permissions](/en/permissions).21For detailed permission configuration, see [Permissions](/docs/en/permissions).

22 22 

23### Built-in protections23### Built-in protections

24 24 

25To mitigate risks in agentic systems:25To mitigate risks in agentic systems:

26 26 

27* **Sandboxed bash tool**: [Sandbox](/en/sandboxing) bash commands with filesystem and network isolation, reducing permission prompts while maintaining security. Enable with `/sandbox` to define boundaries where Claude Code can work autonomously27* **Sandboxed bash tool**: [Sandbox](/docs/en/sandboxing) bash commands with filesystem and network isolation, reducing permission prompts while maintaining security. Enable with `/sandbox` to define boundaries where Claude Code can work autonomously

28* **Working directory boundary**: Claude Code can only write to the folder where it was started and its subfolders, and cannot modify files in parent directories without explicit permission. Reading paths outside this boundary with the Read, Grep, and Glob tools is possible after an approval prompt. Extend the boundary with [additional directories](/en/permissions#working-directories) to skip the prompt, or restrict the broader read access available to read-only Bash commands with [sandbox `denyRead` rules](/en/sandboxing#filesystem-isolation), which apply only when sandboxing is enabled28* **Working directory boundary**: Claude Code can only write to the folder where it was started and its subfolders, and cannot modify files in parent directories without explicit permission. Reading paths outside this boundary with the Read, Grep, and Glob tools is possible after an approval prompt. Extend the boundary with [additional directories](/docs/en/permissions#working-directories) to skip the prompt, or restrict the broader read access available to read-only Bash commands with [sandbox `denyRead` rules](/docs/en/sandboxing#filesystem-isolation), which apply only when sandboxing is enabled

29* **Prompt fatigue mitigation**: Support for allowlisting frequently used safe commands per-user, per-codebase, or per-organization29* **Prompt fatigue mitigation**: Support for allowlisting frequently used safe commands per-user, per-codebase, or per-organization

30* **Accept Edits mode**: Auto-approves file edits and a fixed set of filesystem Bash commands like `mkdir`, `touch`, `rm`, `mv`, `cp`, and `sed` for paths in the working directory. Other Bash commands and out-of-scope paths still prompt30* **Accept Edits mode**: Auto-approves file edits and a fixed set of filesystem Bash commands like `mkdir`, `touch`, `rm`, `mv`, `cp`, and `sed` for paths in the working directory. Other Bash commands and out-of-scope paths still prompt

31 31 


42* **Permission system**: Sensitive operations require explicit approval42* **Permission system**: Sensitive operations require explicit approval

43* **Context-aware analysis**: Detects potentially harmful instructions by analyzing the full request43* **Context-aware analysis**: Detects potentially harmful instructions by analyzing the full request

44* **Input sanitization**: Prevents command injection by processing user inputs44* **Input sanitization**: Prevents command injection by processing user inputs

45* **Network command approval**: Commands that fetch content from the web such as `curl` and `wget` are not auto-approved by default. They prompt like any other non-read-only Bash command, so you can still approve once or add an explicit allow rule like `Bash(curl *)`. To block them entirely, add them to [`permissions.deny`](/en/permissions#tool-specific-permission-rules)45* **Network command approval**: Commands that fetch content from the web such as `curl` and `wget` are not auto-approved by default. They prompt like any other non-read-only Bash command, so you can still approve once or add an explicit allow rule like `Bash(curl *)`. To block them entirely, add them to [`permissions.deny`](/docs/en/permissions#tool-specific-permission-rules)

46 46 

47### Privacy safeguards47### Privacy safeguards

48 48 


64* **Command injection detection**: Suspicious bash commands require manual approval even if previously allowlisted64* **Command injection detection**: Suspicious bash commands require manual approval even if previously allowlisted

65* **Fail-closed matching**: Unmatched commands default to requiring manual approval65* **Fail-closed matching**: Unmatched commands default to requiring manual approval

66* **Natural language descriptions**: Complex bash commands include explanations for user understanding66* **Natural language descriptions**: Complex bash commands include explanations for user understanding

67* **Secure credential storage**: API keys and tokens are stored in the macOS Keychain when available, and protected by file permissions on Windows and Linux. See [Credential Management](/en/authentication#credential-management)67* **Secure credential storage**: API keys and tokens are stored in the macOS Keychain when available, and protected by file permissions on Windows and Linux. See [Credential Management](/docs/en/authentication#credential-management)

68 68 

69<Warning>69<Warning>

70 **Windows WebDAV security risk**: When running Claude Code on Windows, we recommend against enabling WebDAV or allowing Claude Code to access paths such as `\\*` that may contain WebDAV subdirectories. [WebDAV has been deprecated by Microsoft](https://learn.microsoft.com/en-us/windows/whats-new/deprecated-features#:~:text=The%20Webclient%20\(WebDAV\)%20service%20is%20deprecated) due to security risks. Enabling WebDAV may allow Claude Code to trigger network requests to remote hosts, bypassing the permission system.70 **Windows WebDAV security risk**: When running Claude Code on Windows, we recommend against enabling WebDAV or allowing Claude Code to access paths such as `\\*` that may contain WebDAV subdirectories. [WebDAV has been deprecated by Microsoft](https://learn.microsoft.com/en-us/windows/whats-new/deprecated-features#:~:text=The%20Webclient%20\(WebDAV\)%20service%20is%20deprecated) due to security risks. Enabling WebDAV may allow Claude Code to trigger network requests to remote hosts, bypassing the permission system.


92 92 

93## IDE security93## IDE security

94 94 

95See [VS Code security and privacy](/en/vs-code#security-and-privacy) for more information on running Claude Code in an IDE.95See [VS Code security and privacy](/docs/en/vs-code#security-and-privacy) for more information on running Claude Code in an IDE.

96 96 

97## Cloud execution security97## Cloud execution security

98 98 

99When using [Claude Code on the web](/en/claude-code-on-the-web), additional security controls are in place:99When using [Claude Code on the web](/docs/en/claude-code-on-the-web), additional security controls are in place:

100 100 

101* **Isolated virtual machines**: Each cloud session runs in an isolated, Anthropic-managed VM101* **Isolated virtual machines**: Each cloud session runs in an isolated, Anthropic-managed VM

102* **Network access controls**: Network access is limited by default and can be configured to be disabled or allow only specific domains102* **Network access controls**: Network access is limited by default and can be configured to be disabled or allow only specific domains

103* **Credential protection**: Authentication is handled through a secure proxy that uses a scoped credential inside the sandbox, which is then translated to your actual GitHub authentication token103* **Credential protection**: Authentication is handled through a secure proxy that uses a scoped credential inside the sandbox, which is then translated to your actual GitHub authentication token

104* **Branch restrictions**: Git push operations are restricted to the current working branch104* **Branch restrictions**: Git push operations are restricted to the current working branch

105* **Audit logging**: All operations in cloud environments are logged for compliance and audit purposes105* **Audit logging**: All operations in cloud sessions are logged for compliance and audit purposes

106* **Automatic cleanup**: Cloud environments are automatically terminated after session completion106* **Automatic cleanup**: Session VMs are reclaimed after a period of inactivity

107 107 

108For more details on cloud execution, see [Claude Code on the web](/en/claude-code-on-the-web).108For more details on cloud execution, see [Claude Code on the web](/docs/en/claude-code-on-the-web); to configure network access for cloud sessions, see [Configure cloud environments](/docs/en/cloud-environments#network-access).

109 109 

110[Remote Control](/en/remote-control) sessions work differently: the web interface connects to a Claude Code process running on your local machine. All code execution and file access stays local, and session traffic travels through the Anthropic API over TLS; while connected, the session transcript is stored on Anthropic servers to sync the conversation across devices, as described in [Connection and security](/en/remote-control#connection-and-security). No cloud VMs or sandboxing are involved. The connection uses multiple short-lived, narrowly scoped credentials, each limited to a specific purpose and expiring independently, to limit the blast radius of any single compromised credential.110[Remote Control](/docs/en/remote-control) sessions work differently: the web interface connects to a Claude Code process running on your local machine. All code execution and file access stays local, and session traffic travels through the Anthropic API over TLS; while connected, the session transcript is stored on Anthropic servers to sync the conversation across devices, as described in [Connection and security](/docs/en/remote-control#connection-and-security). No cloud VMs or sandboxing are involved. The connection uses multiple short-lived, narrowly scoped credentials, each limited to a specific purpose and expiring independently, to limit the blast radius of any single compromised credential.

111 111 

112## Security best practices112## Security best practices

113 113 


115 115 

116* Review all suggested changes before approval116* Review all suggested changes before approval

117* Use project-specific permission settings for sensitive repositories117* Use project-specific permission settings for sensitive repositories

118* Consider using [dev containers](/en/devcontainer) for additional isolation118* Consider using [dev containers](/docs/en/devcontainer) for additional isolation

119* Regularly audit your permission settings with `/permissions`119* Regularly audit your permission settings with `/permissions`

120 120 

121### Team security121### Team security

122 122 

123* Use [managed settings](/en/settings#settings-files) to enforce organizational standards123* Use [managed settings](/docs/en/settings#settings-files) to enforce organizational standards

124* Share approved permission configurations through version control124* Share approved permission configurations through version control

125* Train team members on security best practices125* Train team members on security best practices

126* Monitor Claude Code usage through [OpenTelemetry metrics](/en/monitoring-usage)126* Monitor Claude Code usage through [OpenTelemetry metrics](/docs/en/monitoring-usage)

127* Audit or block settings changes during sessions with [`ConfigChange` hooks](/en/hooks#configchange)127* Audit or block settings changes during sessions with [`ConfigChange` hooks](/docs/en/hooks#configchange)

128 128 

129### Reporting security issues129### Reporting security issues

130 130 


137 137 

138## Related resources138## Related resources

139 139 

140* [Security guidance plugin](/en/security-guidance): have Claude review and fix vulnerabilities in its own code changes during the session140* [Security guidance plugin](/docs/en/security-guidance): have Claude review and fix vulnerabilities in its own code changes during the session

141* [Sandbox environments](/en/sandbox-environments): compare isolation approaches and choose one for your threat model141* [`/security-review`](/docs/en/commands#all-commands): run an on-demand security pass over the changes on your current branch

142* [Sandboxing](/en/sandboxing): filesystem and network isolation for Bash commands142* [Sandbox environments](/docs/en/sandbox-environments): compare isolation approaches and choose one for your threat model

143* [Permissions](/en/permissions): configure permissions and access controls143* [Sandboxing](/docs/en/sandboxing): filesystem and network isolation for Bash commands

144* [Monitoring usage](/en/monitoring-usage): track and audit Claude Code activity144* [Permissions](/docs/en/permissions): configure permissions and access controls

145* [Development containers](/en/devcontainer): secure, isolated environments145* [Monitoring usage](/docs/en/monitoring-usage): track and audit Claude Code activity

146* [Development containers](/docs/en/devcontainer): secure, isolated environments

146* [Anthropic Trust Center](https://trust.anthropic.com): security certifications and compliance147* [Anthropic Trust Center](https://trust.anthropic.com): security certifications and compliance

Details

10 10 

11Once installed, the plugin runs automatically. There is nothing to invoke and no separate command to remember.11Once installed, the plugin runs automatically. There is nothing to invoke and no separate command to remember.

12 12 

13The plugin is the in-session companion to [Code Review](/docs/en/code-review), which runs on pull requests. This plugin reduces what reaches the PR. Code Review catches what does. For how the plugin layers with on-demand review and CI scanning, see [How this fits with other security tools](#how-this-fits-with-other-security-tools).13The plugin is the in-session companion to [Code Review](/docs/en/code-review), which runs on pull requests. This plugin reduces what reaches the PR. Code Review catches what does. For how the plugin layers with on-demand review and CI scanning, or to scan code you already have rather than changes Claude is writing, see [How this fits with other security tools](#how-this-fits-with-other-security-tools).

14 14 

15## Prerequisites15## Prerequisites

16 16 


157The plugin looks for `claude-security-guidance.md` and `security-patterns.yaml` in the same locations, independently of how the plugin was enabled:157The plugin looks for `claude-security-guidance.md` and `security-patterns.yaml` in the same locations, independently of how the plugin was enabled:

158 158 

159| Scope | Path | Notes |159| Scope | Path | Notes |

160| :------------ | :------------------------------------------ | :--------------------------------------- |160| :------------ | :------------------------------------------ | :-------------------------------------------------- |

161| User | `~/.claude/claude-security-guidance.md` | Applies to every project on your machine |161| User | `~/.claude/claude-security-guidance.md` | Applies to every project on your machine |

162| Project | `.claude/claude-security-guidance.md` | Checked in with the repository |162| Project | `.claude/claude-security-guidance.md` | Checked in with the repository |

163| Project local | `.claude/claude-security-guidance.local.md` | Gitignored, for personal overrides |163| Project local | `.claude/claude-security-guidance.local.md` | For personal overrides; add it to your `.gitignore` |

164 164 

165The plugin loads all locations that exist and concatenates them, with a combined cap of 8 KB for the guidance file. Administrators can distribute organization-wide rules by pushing the user-scope file to `~/.claude/` through device management. The same paths apply to `security-patterns.yaml`.165The plugin loads all locations that exist and concatenates them, with a combined cap of 8 KB for the guidance file. Administrators can distribute organization-wide rules by pushing the user-scope file to `~/.claude/` through device management. The same paths apply to `security-patterns.yaml`.

166 166 


226 226 

227Each later stage catches what earlier ones miss. The plugin's value is reducing the volume that reaches them, not eliminating the need for them.227Each later stage catches what earlier ones miss. The plugin's value is reducing the volume that reaches them, not eliminating the need for them.

228 228 

229To find security issues in code you already have, rather than in changes Claude is writing, ask Claude in a session to review a specific file or directory for vulnerabilities, or use the [Claude Security plugin](/docs/en/claude-security) for a deeper multi-agent scan of the whole repository; [`/security-review`](/docs/en/commands#all-commands) covers only the changes on your current branch. Either way, the review reads the source code in your checkout, not a running site or deployed service.

230 

229## Troubleshooting231## Troubleshooting

230 232 

231The plugin writes runtime diagnostics to `~/.claude/security/log.txt`. Check there first if reviews are not appearing.233The plugin writes runtime diagnostics to `~/.claude/security/log.txt`. Check there first if reviews are not appearing.

sessions.md +12 −0

Details

37 37 

38Not every configuration flag from the original launch is restored. If the session depended on `--mcp-config`, `--settings`, `--plugin-dir`, `--fallback-model`, or directories added with `--add-dir`, pass them again when you resume; directories added mid-session with `/add-dir` aren't restored either, though the session picker still uses them to locate the session. The standard settings files, such as `settings.json` and `settings.local.json`, are re-read at launch, so configuration that lives in them doesn't need to be passed again.38Not every configuration flag from the original launch is restored. If the session depended on `--mcp-config`, `--settings`, `--plugin-dir`, `--fallback-model`, or directories added with `--add-dir`, pass them again when you resume; directories added mid-session with `/add-dir` aren't restored either, though the session picker still uses them to locate the session. The standard settings files, such as `settings.json` and `settings.local.json`, are re-read at launch, so configuration that lives in them doesn't need to be passed again.

39 39 

40### Resume from a summary

41 

42On a Pro or Max plan, when you resume a session that has been inactive for more than about an hour and is over 100,000 tokens, Claude Code restores the conversation and then opens a dialog before you send your first message. The session's [prompt cache](/docs/en/prompt-caching#cache-lifetime) has expired by then, so the next request processes the full history once no matter which of the dialog's options you pick.

43 

44The dialog offers three ways to continue the session. They differ in how much of the conversation each one carries forward into later requests, which is a tradeoff between keeping every detail and sending fewer tokens per request:

45 

46* **Resume from summary**: runs [`/compact`](/docs/en/context-window#what-survives-compaction) immediately. Claude Code sends one summarization request over the full history, then replaces the history with the summary, your most recent exchanges, and up to five recently read files. Later requests carry the summary instead of the full history.

47* **Resume full session as-is**: loads the conversation unchanged. After you send your first message, Claude Code reprocesses and re-caches the full history, then re-reads it from the cache on later requests while the cache stays warm.

48* **Don't ask me again**: resumes the full session and stops showing the dialog on all future resumes.

49 

50Resuming as-is keeps every detail of the conversation available, at a per-request cost that scales with the conversation's size. Resuming from the summary costs less on each later request because it carries the summary instead of the full history, but whatever the summary leaves out is no longer in Claude's context. See [why usage climbs in a long session](/docs/en/costs#why-usage-climbs-in-a-long-session) for where that per-request cost comes from.

51 

40### Where the session picker looks52### Where the session picker looks

41 53 

42Claude Code stores sessions per project directory. By default the session picker shows:54Claude Code stores sessions per project directory. By default the session picker shows:

settings.md +10 −8

Details

15### Available scopes15### Available scopes

16 16 

17| Scope | Location | Who it affects | Shared with team? |17| Scope | Location | Who it affects | Shared with team? |

18| :---------- | :--------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------ |18| :---------- | :--------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------- |

19| **Managed** | Server-managed settings, plist / registry, or system-level `managed-settings.json` | All organization members for server-managed delivery; all users on the machine for plist, HKLM registry, and file delivery; the current user for HKCU registry delivery | Yes (deployed by IT) |19| **Managed** | Server-managed settings, plist / registry, or system-level `managed-settings.json` | All organization members for server-managed delivery; all users on the machine for plist, HKLM registry, and file delivery; the current user for HKCU registry delivery | Yes (deployed by IT) |

20| **User** | `~/.claude/` directory | You, across all projects | No |20| **User** | `~/.claude/` directory | You, across all projects | No |

21| **Project** | `.claude/` in repository | All collaborators on this repository | Yes (committed to git) |21| **Project** | `.claude/` in repository | All collaborators on this repository | Yes (committed to git) |

22| **Local** | `.claude/settings.local.json` at the repository root | You, in this repository only | No (gitignored when Claude Code creates it) |22| **Local** | `.claude/settings.local.json` at the repository root | You, in this repository only | No (gitignored when Claude Code saves a setting to it) |

23 23 

24### When to use each scope24### When to use each scope

25 25 


84 projects.84 projects.

85* **Project settings** are saved in your project directory:85* **Project settings** are saved in your project directory:

86 * `.claude/settings.json` for settings that are checked into source control and shared with your team86 * `.claude/settings.json` for settings that are checked into source control and shared with your team

87 * `.claude/settings.local.json` for settings that are not checked in, useful for personal preferences and experimentation. When Claude Code creates `.claude/settings.local.json`, it configures git to ignore the file. If you create the file yourself, add it to your gitignore manually.87 * `.claude/settings.local.json` for settings that are not checked in, useful for personal preferences and experimentation. When Claude Code saves a setting to this file in a repository that doesn't already ignore it, Claude Code adds `**/.claude/settings.local.json` to your global git excludes file. That excludes file is `core.excludesFile` from your global git config when it's set to an absolute or `~`-prefixed path, otherwise `$XDG_CONFIG_HOME/git/ignore`, or `~/.config/git/ignore`. If you create the file by hand or have Claude write it with the Write tool, add it to your gitignore yourself.

88 88 

89 Claude Code reads and writes this file at the root of the git repository, resolved through [worktrees](/docs/en/worktrees) to the main checkout, so one file covers sessions started in any subdirectory or worktree of the repository. The file stays in the directory you start Claude Code from in three cases: outside a git repository, when the repository root is your home directory, and in [Agent SDK](/docs/en/agent-sdk/claude-code-features#control-filesystem-settings-with-settingsources) sessions.89 Claude Code reads and writes this file at the root of the git repository, resolved through [worktrees](/docs/en/worktrees) to the main checkout, so one file covers sessions started in any subdirectory or worktree of the repository. The file stays in the directory you start Claude Code from in three cases: outside a git repository, when the repository root is your home directory, and in [Agent SDK](/docs/en/agent-sdk/claude-code-features#control-filesystem-settings-with-settingsources) sessions.

90 90 


153 },153 },

154 "env": {154 "env": {

155 "CLAUDE_CODE_ENABLE_TELEMETRY": "1",155 "CLAUDE_CODE_ENABLE_TELEMETRY": "1",

156 "OTEL_METRICS_EXPORTER": "otlp"156 "OTEL_METRICS_EXPORTER": "otlp",

157 "OTEL_EXPORTER_OTLP_PROTOCOL": "http/protobuf"

157 },158 },

158 "companyAnnouncements": [159 "companyAnnouncements": [

159 "Welcome to Acme Corp! Review our code guidelines at docs.acme.com",160 "Welcome to Acme Corp! Review our code guidelines at docs.acme.com",


305| `prefersReducedMotion` | Reduce or disable UI animations (spinners, shimmer, flash effects) for accessibility | `true` |306| `prefersReducedMotion` | Reduce or disable UI animations (spinners, shimmer, flash effects) for accessibility | `true` |

306| `processWrapper` | {/* min-version: 2.1.210 */}Corporate launcher command placed in front of the [background processes Claude Code starts](/docs/en/corporate-launcher#what-the-launcher-covers). Honored from managed settings, a `--settings` file, and user settings only; the [`CLAUDE_CODE_PROCESS_WRAPPER`](/docs/en/env-vars) environment variable takes precedence when both are set. See [Run Claude Code behind a corporate launcher](/docs/en/corporate-launcher) for the launcher contract. Requires Claude Code v2.1.210 or later | `"/opt/corp/launcher --profile claude"` |307| `processWrapper` | {/* min-version: 2.1.210 */}Corporate launcher command placed in front of the [background processes Claude Code starts](/docs/en/corporate-launcher#what-the-launcher-covers). Honored from managed settings, a `--settings` file, and user settings only; the [`CLAUDE_CODE_PROCESS_WRAPPER`](/docs/en/env-vars) environment variable takes precedence when both are set. See [Run Claude Code behind a corporate launcher](/docs/en/corporate-launcher) for the launcher contract. Requires Claude Code v2.1.210 or later | `"/opt/corp/launcher --profile claude"` |

307| `prUrlTemplate` | URL template for the PR badge shown in the footer and in tool-result summaries. Substitutes `{host}`, `{owner}`, `{repo}`, `{number}`, and `{url}` from the `gh`-reported PR URL. Use to point PR links at an internal code-review tool instead of `github.com`. Does not affect `#123` autolinks in Claude's prose | `"https://reviews.example.com/{owner}/{repo}/pull/{number}"` |308| `prUrlTemplate` | URL template for the PR badge shown in the footer and in tool-result summaries. Substitutes `{host}`, `{owner}`, `{repo}`, `{number}`, and `{url}` from the `gh`-reported PR URL. Use to point PR links at an internal code-review tool instead of `github.com`. Does not affect `#123` autolinks in Claude's prose | `"https://reviews.example.com/{owner}/{repo}/pull/{number}"` |

308| `remoteControlAtStartup` | {/* min-version: 2.1.119 */}Connect [Remote Control](/docs/en/remote-control) automatically when each interactive session starts, instead of waiting for `/remote-control`. Set to `true` to always auto-connect, `false` to never auto-connect, or leave unset to follow your organization's default. Appears in `/config` as **Enable Remote Control for all sessions**. See [Enable Remote Control for all sessions](/docs/en/remote-control#enable-remote-control-for-all-sessions) | `false` |309| `remote.defaultEnvironmentId` | Default [cloud environment](/docs/en/cloud-environments) for cloud sessions you create from the CLI, such as with `claude --cloud` or [ultraplan](/docs/en/ultraplan). Written to user settings when you pick an environment with [`/remote-env`](/docs/en/cloud-environments#select-an-environment-from-the-cli). Follows the standard settings precedence, so a value in a repo's project settings overrides the user-level pick | `"env_0123abcd"` |

310| `remoteControlAtStartup` | {/* min-version: 2.1.119 */}Connect [Remote Control](/docs/en/remote-control) automatically when each interactive session starts, instead of waiting for `/remote-control`. Set to `true` to always auto-connect, `false` to never auto-connect, or leave unset to follow your organization's admin default if one is set, and otherwise Claude Code's current default. Appears in `/config` as **Enable Remote Control for all sessions**. See [Enable Remote Control for all sessions](/docs/en/remote-control#enable-remote-control-for-all-sessions) | `false` |

309| `requiredMaximumVersion` | Managed settings only. Maximum Claude Code version allowed to start. If the running version is newer, Claude Code exits at startup and instructs the user to install an approved version through the organization's approved method; `claude install <version>` may also work. Background auto-updates and `claude update` skip versions above the ceiling, so an in-range installation stays in range. `claude update`, `claude install`, and `claude doctor` keep working above the ceiling so users can recover. Versions that predate this setting ignore it | `"2.1.150"` |311| `requiredMaximumVersion` | Managed settings only. Maximum Claude Code version allowed to start. If the running version is newer, Claude Code exits at startup and instructs the user to install an approved version through the organization's approved method; `claude install <version>` may also work. Background auto-updates and `claude update` skip versions above the ceiling, so an in-range installation stays in range. `claude update`, `claude install`, and `claude doctor` keep working above the ceiling so users can recover. Versions that predate this setting ignore it | `"2.1.150"` |

310| `requiredMinimumVersion` | Managed settings only. Minimum Claude Code version required to start. If the running version is older, Claude Code exits at startup and instructs the user to update through the organization's approved method. `claude update`, `claude install`, and `claude doctor` keep working below the floor so users can recover. Differs from `minimumVersion`, which prevents downgrades but never blocks startup. Versions that predate this setting ignore it | `"2.1.150"` |312| `requiredMinimumVersion` | Managed settings only. Minimum Claude Code version required to start. If the running version is older, Claude Code exits at startup and instructs the user to update through the organization's approved method. `claude update`, `claude install`, and `claude doctor` keep working below the floor so users can recover. Differs from `minimumVersion`, which prevents downgrades but never blocks startup. Versions that predate this setting ignore it | `"2.1.150"` |

311| `respectGitignore` | **Default**: `true`. Control whether the `@` file picker respects `.gitignore` patterns. When `true`, files matching `.gitignore` patterns are excluded from suggestions | `false` |313| `respectGitignore` | **Default**: `true`. Control whether the `@` file picker respects `.gitignore` patterns. When `true`, files matching `.gitignore` patterns are excluded from suggestions | `false` |


487* Pull request descriptions are plain text489* Pull request descriptions are plain text

488 490 

489| Keys | Description |491| Keys | Description |

490| :----------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |492| :----------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

491| `commit` | Attribution for git commits, including any trailers. Empty string hides commit attribution |493| `commit` | Attribution for git commits, including any trailers. Empty string hides commit attribution |

492| `pr` | Attribution for pull request descriptions. Empty string hides pull request attribution |494| `pr` | Attribution for pull request descriptions. Empty string hides pull request attribution |

493| `sessionUrl` | Whether to append the claude.ai session link as a `Claude-Session` trailer on commits and a link in pull request descriptions when running from a web or Remote Control session. Defaults to `true`. Set to `false` to omit the link |495| `sessionUrl` | Whether to append the claude.ai session link as a `Claude-Session` trailer on commits and a link in pull request descriptions when running from a cloud or Remote Control session. Defaults to `true`. Set to `false` to omit the link |

494 496 

495**Default commit attribution:**497**Default commit attribution:**

496 498 


786 788 

787* **User settings** (`~/.claude/settings.json`): Personal plugin preferences789* **User settings** (`~/.claude/settings.json`): Personal plugin preferences

788* **Project settings** (`.claude/settings.json`): Project-specific plugins shared with team790* **Project settings** (`.claude/settings.json`): Project-specific plugins shared with team

789* **Local settings** (`.claude/settings.local.json`): Per-machine overrides, gitignored when Claude Code creates it791* **Local settings** (`.claude/settings.local.json`): Per-machine overrides, gitignored when Claude Code saves a setting to it

790* **Managed settings** (`managed-settings.json`): Organization-wide policy overrides that block installation at all scopes and hide the plugin from the marketplace792* **Managed settings** (`managed-settings.json`): Organization-wide policy overrides that block installation at all scopes and hide the plugin from the marketplace

791 793 

792<Note>794<Note>

setup.md +50 −37

Details

6 6 

7> System requirements, platform-specific installation, version management, and uninstallation for Claude Code.7> System requirements, platform-specific installation, version management, and uninstallation for Claude Code.

8 8 

9This page covers system requirements, platform-specific installation details, updates, and uninstallation. For a guided walkthrough of your first session, see the [quickstart](/en/quickstart). If you've never used a terminal before, see the [terminal guide](/en/terminal-guide).9This page covers system requirements, platform-specific installation details, updates, and uninstallation. For a guided walkthrough of your first session, see the [quickstart](/docs/en/quickstart). If you've never used a terminal before, see the [terminal guide](/docs/en/terminal-guide).

10 10 

11## System requirements11## System requirements

12 12 


19 * Debian 10+19 * Debian 10+

20 * Alpine Linux 3.19+20 * Alpine Linux 3.19+

21* **Hardware**: 4 GB+ RAM, x64 or ARM64 processor21* **Hardware**: 4 GB+ RAM, x64 or ARM64 processor

22* **Network**: internet connection required. See [network configuration](/en/network-config#network-access-requirements).22* **Network**: internet connection required. See [network configuration](/docs/en/network-config#network-access-requirements).

23* **Shell**: Bash, Zsh, PowerShell, or CMD.23* **Shell**: Bash, Zsh, PowerShell, or CMD.

24* **Location**: [Anthropic supported countries](https://www.anthropic.com/supported-countries)24* **Location**: [Anthropic supported countries](https://www.anthropic.com/supported-countries)

25 25 

26### Additional dependencies26### Additional dependencies

27 27 

28* **ripgrep**: usually included with Claude Code. If search fails, see [search troubleshooting](/en/troubleshooting#search-and-discovery-issues).28* **ripgrep**: usually included with Claude Code. If search fails, see [search troubleshooting](/docs/en/troubleshooting#search-and-discovery-issues).

29 29 

30## Install Claude Code30## Install Claude Code

31 31 

32<Tip>32<Tip>

33 Prefer a graphical interface? The [Desktop app](/en/desktop-quickstart) lets you use Claude Code without the terminal. Download it for [macOS](https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code\&utm_medium=docs), [Windows](https://claude.com/download?utm_source=claude_code\&utm_medium=docs), or [Linux](/en/desktop-linux).33 Prefer a graphical interface? The [Desktop app](/docs/en/desktop-quickstart) lets you use Claude Code without the terminal. Download it for [macOS](https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code\&utm_medium=docs), [Windows](https://claude.com/download?utm_source=claude_code\&utm_medium=docs), or [Linux](/docs/en/desktop-linux).

34 34 

35 New to the terminal? See the [terminal guide](/en/terminal-guide) for step-by-step instructions.35 New to the terminal? See the [terminal guide](/docs/en/terminal-guide) for step-by-step instructions.

36</Tip>36</Tip>

37 37 

38To install Claude Code, use one of the following methods:38To install Claude Code, use one of the following methods:


59 59 

60 If you see `The token '&&' is not a valid statement separator`, you're in PowerShell, not CMD. If you see `'irm' is not recognized as an internal or external command`, you're in CMD, not PowerShell. Your prompt shows `PS C:\` when you're in PowerShell and `C:\` without the `PS` when you're in CMD.60 If you see `The token '&&' is not a valid statement separator`, you're in PowerShell, not CMD. If you see `'irm' is not recognized as an internal or external command`, you're in CMD, not PowerShell. Your prompt shows `PS C:\` when you're in PowerShell and `C:\` without the `PS` when you're in CMD.

61 61 

62 If the install command fails with `syntax error near unexpected token '<'`, a `403`, or another curl error, see [Troubleshoot installation](/en/troubleshoot-install#find-your-error) to match the error to a fix and for alternative install methods.62 If the install command fails with `syntax error near unexpected token '<'`, a `403`, or another curl error, see [Troubleshoot installation](/docs/en/troubleshoot-install#find-your-error) to match the error to a fix and for alternative install methods.

63 63 

64 [Git for Windows](https://git-scm.com/downloads/win) is recommended on native Windows so Claude Code can use the Bash tool. If Git for Windows is not installed, Claude Code uses PowerShell as the shell tool instead. WSL setups do not need Git for Windows.64 [Git for Windows](https://git-scm.com/downloads/win) is recommended on native Windows so Claude Code can use the Bash tool. If Git for Windows is not installed, Claude Code uses PowerShell as the shell tool instead. WSL setups do not need Git for Windows.

65 65 


91 </Tab>91 </Tab>

92</Tabs>92</Tabs>

93 93 

94You can also install with [apt, dnf, or apk](/en/setup#install-with-linux-package-managers) on Debian, Fedora, RHEL, and Alpine.94You can also install with [apt, dnf, or apk](/docs/en/setup#install-with-linux-package-managers) on Debian, Fedora, RHEL, and Alpine.

95 95 

96After installation completes, open a terminal in the project you want to work in and start Claude Code:96After installation completes, open a terminal in the project you want to work in and start Claude Code:

97 97 


101 101 

102Claude Code opens an interactive session in your terminal.102Claude Code opens an interactive session in your terminal.

103 103 

104If you encounter any issues during installation, see [Troubleshoot installation and login](/en/troubleshoot-install).104If you encounter any issues during installation, see [Troubleshoot installation and login](/docs/en/troubleshoot-install).

105 105 

106### Set up on Windows106### Set up on Windows

107 107 

108You can run Claude Code natively on Windows or inside WSL. Pick based on where your projects are located and which features you need:108You can run Claude Code natively on Windows or inside WSL. Pick based on where your projects are located and which features you need:

109 109 

110| Option | Requires | [Sandboxing](/en/sandboxing) | When to use |110| Option | Requires | [Sandboxing](/docs/en/sandboxing) | When to use |

111| -------------- | ---------------------------------------------------------------------- | ---------------------------- | ----------------------------------------------- |111| -------------- | ---------------------------------------------------------------------- | ---------------------------- | ----------------------------------------------- |

112| Native Windows | None; [Git for Windows](https://git-scm.com/downloads/win) is optional | Not supported | Windows-native projects and tools |112| Native Windows | None; [Git for Windows](https://git-scm.com/downloads/win) is optional | Not supported | Windows-native projects and tools |

113| WSL 2 | WSL 2 enabled | Supported | Linux toolchains or sandboxed command execution |113| WSL 2 | WSL 2 enabled | Supported | Linux toolchains or sandboxed command execution |


115 115 

116**Option 1: Native Windows**116**Option 1: Native Windows**

117 117 

118Run the install command from PowerShell or CMD. You do not need to run as Administrator. Installing [Git for Windows](https://git-scm.com/downloads/win) is optional. It enables the [Bash tool](/en/tools-reference#bash-tool-behavior) by providing Git Bash.118Run the install command from PowerShell or CMD. You do not need to run as Administrator. Installing [Git for Windows](https://git-scm.com/downloads/win) is optional. It enables the [Bash tool](/docs/en/tools-reference#bash-tool-behavior) by providing Git Bash.

119 119 

120Whether you install from PowerShell or CMD only affects which install command you run. Your prompt shows `PS C:\Users\YourName>` in PowerShell and `C:\Users\YourName>` without the `PS` in CMD. If you're new to the terminal, the [terminal guide](/en/terminal-guide#windows) walks through each step.120Whether you install from PowerShell or CMD only affects which install command you run. Your prompt shows `PS C:\Users\YourName>` in PowerShell and `C:\Users\YourName>` without the `PS` in CMD. If you're new to the terminal, the [terminal guide](/docs/en/terminal-guide#windows) walks through each step.

121 121 

122After installation, launch `claude` from any terminal.122After installation, launch `claude` from any terminal.

123 123 

124* **Without Git for Windows**, Claude Code runs shell commands via the [PowerShell tool](/en/tools-reference#powershell-tool).124* **Without Git for Windows**, Claude Code runs shell commands via the [PowerShell tool](/docs/en/tools-reference#powershell-tool).

125* **With Git for Windows**, Claude Code uses Git Bash for the [Bash tool](/en/tools-reference#bash-tool-behavior). If Claude Code can't find Git Bash, set the path in your [settings.json file](/en/settings):125* **With Git for Windows**, Claude Code uses Git Bash for the [Bash tool](/docs/en/tools-reference#bash-tool-behavior). If Claude Code can't find Git Bash, set the path in your [settings.json file](/docs/en/settings):

126 126 

127 ```json theme={null}127 ```json theme={null}

128 {128 {


132 }132 }

133 ```133 ```

134 134 

135When Git for Windows is installed, the PowerShell tool is rolling out progressively as an additional option alongside Bash. Set `CLAUDE_CODE_USE_POWERSHELL_TOOL=1` to opt in or `0` to opt out. See [PowerShell tool](/en/tools-reference#powershell-tool) for setup and limitations.135When Git for Windows is installed, the PowerShell tool is rolling out progressively as an additional option alongside Bash. Set `CLAUDE_CODE_USE_POWERSHELL_TOOL=1` to opt in or `0` to opt out. See [PowerShell tool](/docs/en/tools-reference#powershell-tool) for setup and limitations.

136 136 

137**Option 2: WSL**137**Option 2: WSL**

138 138 


156 156 

157Run `apk update` to refresh the package index, and retry the `apk add` command.157Run `apk update` to refresh the package index, and retry the `apk add` command.

158 158 

159Then set `USE_BUILTIN_RIPGREP` to `0` in your [`settings.json`](/en/settings#available-settings) file:159Then set `USE_BUILTIN_RIPGREP` to `0` in your [`settings.json`](/docs/en/settings#available-settings) file:

160 160 

161```json theme={null}161```json theme={null}

162{162{


176 176 

177A working installation prints a version number such as `2.1.211 (Claude Code)`.177A working installation prints a version number such as `2.1.211 (Claude Code)`.

178 178 

179If this fails with `command not found` or another error, see [Troubleshoot installation and login](/en/troubleshoot-install).179If this fails with `command not found` or another error, see [Troubleshoot installation and login](/docs/en/troubleshoot-install).

180 180 

181For a more detailed check of your installation and configuration, run [`claude doctor`](/en/troubleshooting#get-more-help):181For a more detailed check of your installation and configuration, run [`claude doctor`](/docs/en/troubleshooting#get-more-help):

182 182 

183```bash theme={null}183```bash theme={null}

184claude doctor184claude doctor


188 188 

189## Authenticate189## Authenticate

190 190 

191Claude Code requires a Pro, Max, Team, Enterprise, or Console account. The free Claude.ai plan does not include Claude Code access. You can also use Claude Code with a third-party API provider like [Amazon Bedrock](/en/amazon-bedrock), [Google Cloud's Agent Platform](/en/google-vertex-ai), or [Microsoft Foundry](/en/microsoft-foundry).191Claude Code requires a Pro, Max, Team, Enterprise, or Console account. The free Claude.ai plan does not include Claude Code access. You can also use Claude Code with a third-party API provider like [Amazon Bedrock](/docs/en/amazon-bedrock), [Google Cloud's Agent Platform](/docs/en/google-vertex-ai), or [Microsoft Foundry](/docs/en/microsoft-foundry).

192 192 

193After installing, log in by running `claude` and following the browser prompts. If the `ANTHROPIC_API_KEY` environment variable is set, Claude Code prompts you once to approve the key instead of opening a browser. See [Authentication](/en/authentication) for all account types and team setup options.193After installing, log in by running `claude` and following the browser prompts. If the `ANTHROPIC_API_KEY` environment variable is set, Claude Code prompts you once to approve the key instead of opening a browser. See [Authentication](/docs/en/authentication) for all account types and team setup options.

194 194 

195## Update Claude Code195## Update Claude Code

196 196 


208 208 

209To let Claude Code manage the launcher again, remove `~/.local/bin/claude` and run `claude update`.209To let Claude Code manage the launcher again, remove `~/.local/bin/claude` and run `claude update`.

210 210 

211If an npm global install can't auto-update because the npm global directory isn't writable, Claude Code shows a one-time notice at startup, and `claude doctor` lists the available fixes. See [permission errors during installation](/en/troubleshoot-install#permission-errors-during-installation) for details.211If an npm global install can't auto-update because the npm global directory isn't writable, Claude Code shows a one-time notice at startup, and `claude doctor` lists the available fixes. See [permission errors during installation](/docs/en/troubleshoot-install#permission-errors-during-installation) for details.

212 212 

213<Note>213<Note>

214 Homebrew, WinGet, apt, dnf, and apk installations do not auto-update by default; see below to opt in for Homebrew and WinGet. To upgrade Homebrew manually, run `brew upgrade claude-code` or `brew upgrade claude-code@latest`, depending on which cask you installed. For WinGet, run `winget upgrade Anthropic.ClaudeCode`. For Linux package managers, see the upgrade commands in [Install with Linux package managers](#install-with-linux-package-managers).214 Homebrew, WinGet, apt, dnf, and apk installations do not auto-update by default; see below to opt in for Homebrew and WinGet. To upgrade Homebrew manually, run `brew upgrade claude-code` or `brew upgrade claude-code@latest`, depending on which cask you installed. For WinGet, run `winget upgrade Anthropic.ClaudeCode`. For Linux package managers, see the upgrade commands in [Install with Linux package managers](#install-with-linux-package-managers).

215 215 

216 To have Claude Code run the upgrade command for you on Homebrew or WinGet, set [`CLAUDE_CODE_PACKAGE_MANAGER_AUTO_UPDATE`](/en/env-vars) to `1`. Claude Code then runs the upgrade in the background when a new version is available and shows a restart prompt on success. The upgrade targets only the Claude Code package and does not affect other software you have installed.216 To have Claude Code run the upgrade command for you on Homebrew or WinGet, set [`CLAUDE_CODE_PACKAGE_MANAGER_AUTO_UPDATE`](/docs/en/env-vars) to `1`. Claude Code then runs the upgrade in the background when a new version is available and shows a restart prompt on success. The upgrade targets only the Claude Code package and does not affect other software you have installed.

217 217 

218 On WinGet the upgrade may fail while Claude Code is running because Windows locks the executable. In that case Claude Code shows the manual command instead. apt, dnf, and apk continue to require a manual upgrade because those commands need elevated privileges.218 On WinGet the upgrade may fail while Claude Code is running because Windows locks the executable. In that case Claude Code shows the manual command instead. apt, dnf, and apk continue to require a manual upgrade because those commands need elevated privileges.

219 219 


229* `"latest"`, the default: receive new features as soon as they're released229* `"latest"`, the default: receive new features as soon as they're released

230* `"stable"`: use a version that is typically about one week old, skipping releases with major regressions230* `"stable"`: use a version that is typically about one week old, skipping releases with major regressions

231 231 

232Configure this via `/config` → **Auto-update channel**, or add it to your [settings.json file](/en/settings):232Configure this via `/config` → **Auto-update channel**, or add it to your [settings.json file](/docs/en/settings):

233 233 

234```json theme={null}234```json theme={null}

235{235{


237}237}

238```238```

239 239 

240For enterprise deployments, you can enforce a consistent release channel across your organization using [managed settings](/en/permissions#managed-settings).240For enterprise deployments, you can enforce a consistent release channel across your organization using [managed settings](/docs/en/permissions#managed-settings).

241 241 

242Homebrew installations choose a channel by cask name instead of this setting: `claude-code` tracks stable and `claude-code@latest` tracks latest.242Homebrew installations choose a channel by cask name instead of this setting: `claude-code` tracks stable and `claude-code@latest` tracks latest.

243 243 


247 247 

248Switching from `"latest"` to `"stable"` via `/config` prompts you to either stay on the current version or allow the downgrade. Choosing to stay sets `minimumVersion` to that version. Switching back to `"latest"` clears it.248Switching from `"latest"` to `"stable"` via `/config` prompts you to either stay on the current version or allow the downgrade. Choosing to stay sets `minimumVersion` to that version. Switching back to `"latest"` clears it.

249 249 

250Add it to your [settings.json file](/en/settings) to pin a floor explicitly:250Add it to your [settings.json file](/docs/en/settings) to pin a floor explicitly:

251 251 

252```json theme={null}252```json theme={null}

253{253{


256}256}

257```257```

258 258 

259In [managed settings](/en/permissions#managed-settings), this enforces an organization-wide minimum that user and project settings cannot override.259In [managed settings](/docs/en/permissions#managed-settings), this enforces an organization-wide minimum that user and project settings cannot override.

260 260 

261The `minimumVersion` pin only constrains updates. To make Claude Code refuse to start outside a version range, use the managed settings `requiredMinimumVersion` and `requiredMaximumVersion` instead. Updates also respect the `requiredMaximumVersion` ceiling. See [available settings](/en/settings#available-settings).261The `minimumVersion` pin only constrains updates. To make Claude Code refuse to start outside a version range, use the managed settings `requiredMinimumVersion` and `requiredMaximumVersion` instead. Updates also respect the `requiredMaximumVersion` ceiling. See [available settings](/docs/en/settings#available-settings).

262 262 

263### Disable auto-updates263### Disable auto-updates

264 264 

265Set `DISABLE_AUTOUPDATER` to `"1"` in the `env` key of your [`settings.json`](/en/settings#available-settings) file:265Set `DISABLE_AUTOUPDATER` to `"1"` in the `env` key of your [`settings.json`](/docs/en/settings#available-settings) file:

266 266 

267```json theme={null}267```json theme={null}

268{268{


272}272}

273```273```

274 274 

275`DISABLE_AUTOUPDATER` only stops the background check; `claude update` and `claude install` still work. To block all update paths, including manual updates, set [`DISABLE_UPDATES`](/en/env-vars) instead. Use this when you distribute Claude Code through your own channels and need users to stay on the version you provide.275`DISABLE_AUTOUPDATER` only stops the background check; `claude update` and `claude install` still work. To block all update paths, including manual updates, set [`DISABLE_UPDATES`](/docs/en/env-vars) instead. Use this when you distribute Claude Code through your own channels and need users to stay on the version you provide.

276 276 

277### Update manually277### Update manually

278 278 


358 </Tab>358 </Tab>

359</Tabs>359</Tabs>

360 360 

361To confirm which version installed, run `claude --version`: the command prints the exact version you passed, such as `2.1.89 (Claude Code)`.

362 

361### Install with Linux package managers363### Install with Linux package managers

362 364 

363Claude Code publishes signed apt, dnf, and apk repositories. Each repository offers two channels: `stable` serves a version that is typically about one week old, skipping releases with major regressions, and `latest` serves every release as soon as it ships. The commands below configure the `stable` channel, which fits most users; each tab also shows the `latest` repository URL. Package manager installations do not auto-update through Claude Code; updates arrive through your normal system upgrade workflow.365Claude Code publishes signed apt, dnf, and apk repositories. Each repository offers two channels: `stable` serves a version that is typically about one week old, skipping releases with major regressions, and `latest` serves every release as soon as it ships. The commands below configure the `stable` channel, which fits most users; each tab also shows the `latest` repository URL. Package manager installations do not auto-update through Claude Code; updates arrive through your normal system upgrade workflow.


366 368 

367<Tabs>369<Tabs>

368 <Tab title="apt">370 <Tab title="apt">

369 For Debian and Ubuntu. The install commands below download the signing key with `curl`, which fresh Debian and Ubuntu installations may not include. If the download fails with `sudo: curl: command not found`, install curl first:371 For Debian and Ubuntu. The install commands below download the signing key with `curl` and verify it with `gpg`, which fresh Debian and Ubuntu installations may not include. If either command reports `command not found`, install both first:

370 372 

371 ```bash theme={null}373 ```bash theme={null}

372 sudo apt install curl374 sudo apt install curl gnupg

373 ```375 ```

374 376 

375 The following commands configure the `stable` channel:377 Download the signing key:

376 378 

377 ```bash theme={null}379 ```bash theme={null}

378 sudo install -d -m 0755 /etc/apt/keyrings380 sudo install -d -m 0755 /etc/apt/keyrings

379 sudo curl -fsSL https://downloads.claude.ai/keys/claude-code.asc \381 sudo curl -fsSL https://downloads.claude.ai/keys/claude-code.asc \

380 -o /etc/apt/keyrings/claude-code.asc382 -o /etc/apt/keyrings/claude-code.asc

383 ```

384 

385 If this download fails, `apt update` later fails with `NO_PUBKEY BAA929FF1A7ECACE`. Confirm the key downloaded and belongs to Anthropic before continuing:

386 

387 ```bash theme={null}

388 gpg --show-keys /etc/apt/keyrings/claude-code.asc

389 ```

390 

391 The fingerprint gpg prints should be `31DDDE24DDFAB679F42D7BD2BAA929FF1A7ECACE`. If gpg reports that the file can't be opened or contains no valid OpenPGP data, the download failed or returned the wrong content: confirm your network can reach `downloads.claude.ai`, then rerun the download command.

392 

393 Register the repository on the `stable` channel and install:

394 

395 ```bash theme={null}

381 echo "deb [signed-by=/etc/apt/keyrings/claude-code.asc] https://downloads.claude.ai/claude-code/apt/stable stable main" \396 echo "deb [signed-by=/etc/apt/keyrings/claude-code.asc] https://downloads.claude.ai/claude-code/apt/stable stable main" \

382 | sudo tee /etc/apt/sources.list.d/claude-code.list397 | sudo tee /etc/apt/sources.list.d/claude-code.list

383 sudo apt update398 sudo apt update


391 | sudo tee /etc/apt/sources.list.d/claude-code.list406 | sudo tee /etc/apt/sources.list.d/claude-code.list

392 ```407 ```

393 408 

394 Verify the GPG key fingerprint before trusting it: `gpg --show-keys /etc/apt/keyrings/claude-code.asc` should report `31DD DE24 DDFA B679 F42D 7BD2 BAA9 29FF 1A7E CACE`.

395 

396 To upgrade later, run `sudo apt update && sudo apt upgrade claude-code`.409 To upgrade later, run `sudo apt update && sudo apt upgrade claude-code`.

397 </Tab>410 </Tab>

398 411 


455 468 

456The npm package installs the same native binary as the standalone installer. npm pulls the binary in through a per-platform optional dependency such as `@anthropic-ai/claude-code-darwin-arm64`, and a postinstall step links it into place. The installed `claude` binary does not itself invoke Node.469The npm package installs the same native binary as the standalone installer. npm pulls the binary in through a per-platform optional dependency such as `@anthropic-ai/claude-code-darwin-arm64`, and a postinstall step links it into place. The installed `claude` binary does not itself invoke Node.

457 470 

458Supported npm install platforms are `darwin-arm64`, `darwin-x64`, `linux-x64`, `linux-arm64`, `linux-x64-musl`, `linux-arm64-musl`, `win32-x64`, and `win32-arm64`. Your package manager must allow optional dependencies. See [troubleshooting](/en/troubleshoot-install#native-binary-not-found-after-npm-install) if the binary is missing after install.471Supported npm install platforms are `darwin-arm64`, `darwin-x64`, `linux-x64`, `linux-arm64`, `linux-x64-musl`, `linux-arm64-musl`, `win32-x64`, and `win32-arm64`. Your package manager must allow optional dependencies. See [troubleshooting](/docs/en/troubleshoot-install#native-binary-not-found-after-npm-install) if the binary is missing after install.

459 472 

460To upgrade an npm installation, run `npm install -g @anthropic-ai/claude-code@latest`. Avoid `npm update -g`, which respects the semver range from the original install and may not move you to the newest release.473To upgrade an npm installation, run `npm install -g @anthropic-ai/claude-code@latest`. Avoid `npm update -g`, which respects the semver range from the original install and may not move you to the newest release.

461 474 

462<Warning>475<Warning>

463 Do NOT use `sudo npm install -g` as this can lead to permission issues and security risks. If you encounter permission errors, see [troubleshooting permission errors](/en/troubleshoot-install#permission-errors-during-installation).476 Do NOT use `sudo npm install -g` as this can lead to permission issues and security risks. If you encounter permission errors, see [troubleshooting permission errors](/docs/en/troubleshoot-install#permission-errors-during-installation).

464</Warning>477</Warning>

465 478 

466### Binary integrity and code signing479### Binary integrity and code signing


554 567 

555## Uninstall Claude Code568## Uninstall Claude Code

556 569 

557To remove Claude Code, follow the instructions for your installation method. If `claude` still runs afterward, you likely have a second installation or a leftover shell alias from an older installer. See [Check for conflicting installations](/en/troubleshoot-install#check-for-conflicting-installations) to find and remove it.570To remove Claude Code, follow the instructions for your installation method. If `claude` still runs afterward, you likely have a second installation or a leftover shell alias from an older installer. See [Check for conflicting installations](/docs/en/troubleshoot-install#check-for-conflicting-installations) to find and remove it.

558 571 

559### Native installation572### Native installation

560 573 


640 Removing configuration files will delete all your settings, allowed tools, MCP server configurations, and session history.653 Removing configuration files will delete all your settings, allowed tools, MCP server configurations, and session history.

641</Warning>654</Warning>

642 655 

643The VS Code extension, the JetBrains plugin, and the Desktop app also write to `~/.claude/`. If any of them is still installed, the directory is recreated the next time it runs. To remove Claude Code completely, uninstall the [VS Code extension](/en/vs-code#uninstall-the-extension), the JetBrains plugin, and the Desktop app before deleting these files.656The VS Code extension, the JetBrains plugin, and the Desktop app also write to `~/.claude/`. If any of them is still installed, the directory is recreated the next time it runs. To remove Claude Code completely, uninstall the [VS Code extension](/docs/en/vs-code#uninstall-the-extension), the JetBrains plugin, and the Desktop app before deleting these files.

644 657 

645To remove Claude Code settings and cached data:658To remove Claude Code settings and cached data:

646 659 

skills.md +6 −4

Details

143 Live change detection covers `SKILL.md` text only. For a skill folder that is also a [plugin](/docs/en/plugins-reference#skills-directory-plugins), changes to `hooks/`, `.mcp.json`, `agents/`, and `output-styles/` need `/reload-plugins` to take effect.143 Live change detection covers `SKILL.md` text only. For a skill folder that is also a [plugin](/docs/en/plugins-reference#skills-directory-plugins), changes to `hooks/`, `.mcp.json`, `agents/`, and `output-styles/` need `/reload-plugins` to take effect.

144</Note>144</Note>

145 145 

146#### Automatic discovery from parent and nested directories146#### Discovery from parent and nested directories

147 147 

148Project skills load from `.claude/skills/` in your starting directory and in every parent directory up to the repository root, so starting Claude in a subdirectory still picks up skills defined at the root. When you work with files in subdirectories below your starting directory, Claude Code also discovers skills from nested `.claude/skills/` directories on demand. For example, if you're editing a file in `packages/frontend/`, Claude Code also looks for skills in `packages/frontend/.claude/skills/`. This supports monorepo setups where packages have their own skills.148Project skills load from `.claude/skills/` in the directory where you start Claude Code and in every parent directory up to the repository root. Starting Claude in a subdirectory still picks up skills defined at the root. To load skills from a directory outside that path at startup, pass it with [`--add-dir`](/docs/en/cli-reference). Claude Code reads `.claude/skills/` inside each added directory alongside the project skills.

149 

150Skills in nested `.claude/skills/` directories below your starting directory aren't loaded at startup. They load the first time Claude reads or edits a file inside that subdirectory, and stay available for the rest of the session. For example, after Claude edits a file under `packages/frontend/`, skills in `packages/frontend/.claude/skills/` become available. Until then, those skills don't appear in autocomplete and can't be invoked by name.

149 151 

150Each skill is a directory with `SKILL.md` as the entrypoint:152Each skill is a directory with `SKILL.md` as the entrypoint:

151 153 


177 179 

178#### Skills in Cowork and cloud sessions180#### Skills in Cowork and cloud sessions

179 181 

180[Cowork](https://claude.com/product/cowork) sessions and [cloud sessions](/docs/en/claude-code-on-the-web#the-cloud-environment), including [routines](/docs/en/routines), don't read `~/.claude/skills/` on your machine. Both interactive and scheduled Cowork sessions load the skills enabled for your claude.ai account, synced at session start; manage them from **Customize** in the Desktop app sidebar or from the skills settings on claude.ai. Cloud sessions additionally load project skills committed to the cloned repository's `.claude/skills/`.182[Cowork](https://claude.com/product/cowork) sessions and [cloud sessions](/docs/en/cloud-environments#what-carries-over-from-your-setup), including [routines](/docs/en/routines), don't read `~/.claude/skills/` on your machine. Both interactive and scheduled Cowork sessions load the skills enabled for your claude.ai account, synced at session start; manage them from **Customize** in the Desktop app sidebar or from the skills settings on claude.ai. Cloud sessions additionally load project skills committed to the cloned repository's `.claude/skills/`.

181 183 

182If a skill exists only in `~/.claude/skills/` on your machine, Claude Code reports that the skill was not found when a [routine](/docs/en/routines) invokes it, because each routine run starts as a fresh remote session. To make a personal skill available in these sessions:184If a skill exists only in `~/.claude/skills/` on your machine, Claude Code reports that the skill was not found when a [routine](/docs/en/routines) invokes it, because each routine run starts as a fresh remote session. To make a personal skill available in these sessions:

183 185 

184* For Cowork and cloud sessions, enable the skill for your claude.ai account.186* For Cowork and cloud sessions, enable the skill for your claude.ai account.

185* For cloud sessions, you can instead commit the skill to the repository's `.claude/skills/`, or ship it in a plugin declared in the repository's `.claude/settings.json`. Repo-declared plugins [install at session start](/docs/en/claude-code-on-the-web#what’s-available-in-cloud-sessions); plugins enabled only in your user settings don't transfer.187* For cloud sessions, you can instead commit the skill to the repository's `.claude/skills/`, or ship it in a plugin declared in the repository's `.claude/settings.json`. Repo-declared plugins [install at session start](/docs/en/cloud-environments#what-carries-over-from-your-setup); plugins enabled only in your user settings don't transfer.

186 188 

187[Desktop scheduled tasks](/docs/en/desktop-scheduled-tasks) are different: they run locally on your machine and load skills from the same locations as any other local session.189[Desktop scheduled tasks](/docs/en/desktop-scheduled-tasks) are different: they run locally on your machine and load skills from the same locations as any other local session.

188 190 

slack.md +21 −7

Details

4 4 

5# Claude Code in Slack5# Claude Code in Slack

6 6 

7> Delegate coding tasks directly from your Slack workspace7> Delegate coding tasks directly from your Slack workspace. Anthropic is retiring this earlier version for Team and Enterprise workspaces in favor of Claude Tag; it remains the setup path on Pro and Max plans.

8 8 

9<Note>9<Warning>

10 Claude Code in Slack is being replaced by [Claude Tag](https://claude.com/product/tag) for Team and Enterprise workspaces. Claude Tag runs @Claude as your organization's shared identity with admin-configured access, under the same Slack app, so there is nothing to reinstall and existing setups continue to work during the transition. To switch a workspace, see [Migrate from the earlier Claude in Slack](https://claude.com/docs/claude-tag/admins/migrate-from-earlier).10 This page documents the earlier Claude Code in Slack, which runs each session under an individual user's account.

11</Note>11 

12 * **Team and Enterprise plans:** Anthropic is retiring this version in favor of [Claude Tag](https://claude.com/docs/claude-tag/overview), which runs @Claude as your organization's shared identity with admin-configured access. Your existing Slack app and @Claude handle stay, and your Anthropic account team can tell you the cutover date. Set up Claude Tag for a new workspace; to move one that already uses this version, see [Migrate from the earlier Claude in Slack](https://claude.com/docs/claude-tag/admins/migrate-from-earlier).

13 * **Pro and Max plans:** Claude Tag isn't available on individual plans, so this page remains the setup path.

14</Warning>

12 15 

13Claude 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.16Claude 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.

14 17 


28| Requirement | Details |31| Requirement | Details |

29| :--------------------- | :------------------------------------------------------------------------------------------------ |32| :--------------------- | :------------------------------------------------------------------------------------------------ |

30| Claude Plan | Pro, Max, Team, or Enterprise with Claude Code access (premium seats or Chat + Claude Code seats) |33| Claude Plan | Pro, Max, Team, or Enterprise with Claude Code access (premium seats or Chat + Claude Code seats) |

31| Claude Code on the web | Access to [Claude Code on the web](/en/claude-code-on-the-web) must be enabled |34| Claude Code on the web | Access to [Claude Code on the web](/docs/en/claude-code-on-the-web) must be enabled |

32| GitHub Account | Connected to Claude Code on the web with at least one repository authenticated |35| GitHub Account | Connected to Claude Code on the web with at least one repository authenticated |

33| Slack Authentication | Your Slack account linked to your Claude account via the Claude app |36| Slack Authentication | Your Slack account linked to your Claude account via the Claude app |

34 37 


163**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.166**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.

164 167 

165For Enterprise and Team accounts, sessions created from Claude in Slack are168For Enterprise and Team accounts, sessions created from Claude in Slack are

166automatically visible to the organization. See [Claude Code on the Web sharing](/en/claude-code-on-the-web#share-sessions)169automatically visible to the organization. See [Claude Code on the Web sharing](/docs/en/claude-code-on-the-web#share-sessions)

167for more details.170for more details.

168 171 

169## Best practices172## Best practices


1932. Check that you have Claude Code on the web access enabled1962. Check that you have Claude Code on the web access enabled

1943. Ensure you have at least one GitHub repository connected to Claude Code1973. Ensure you have at least one GitHub repository connected to Claude Code

195 198 

199### Sessions from a Claude Tag channel fail to start

200 

201This entry applies to workspaces using [Claude Tag](https://claude.com/docs/claude-tag/overview), where Claude works in channels as your organization's shared identity, not as any member's account. If you created the channel's cloud environment at [claude.ai/code](https://claude.ai/code), it belongs to your personal account, and Claude can't start channel sessions in a personal environment. Claude Code fails the session immediately, and retrying doesn't help.

202 

203If you're an Owner or admin, recreate the environment as an [organization-shared environment](/docs/en/cloud-environments#organization-shared-environments) from the **Cloud environments** page in [admin settings](https://claude.ai/admin-settings). You can apply it in two ways:

204 

205* Set it as the organization default at [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code).

206* [Set it on the channel](https://claude.com/docs/claude-tag/admins/troubleshooting#channel-sessions-use-the-wrong-environment-or-can%E2%80%99t-find-one) in the Claude Tag admin settings.

207 

208If you're not an Owner or admin, send this entry to one.

209 

196### Repository not showing210### Repository not showing

197 211 

1981. Connect the repository in Claude Code on the web at [claude.ai/code](https://claude.ai/code)2121. Connect the repository in Claude Code on the web at [claude.ai/code](https://claude.ai/code)


225## Related resources239## Related resources

226 240 

227<CardGroup>241<CardGroup>

228 <Card title="Claude Code on the web" icon="globe" href="/en/claude-code-on-the-web">242 <Card title="Claude Code on the web" icon="globe" href="/docs/en/claude-code-on-the-web">

229 Learn more about Claude Code on the web243 Learn more about Claude Code on the web

230 </Card>244 </Card>

231 245 

sub-agents.md +10 −0

Details

573exit 0573exit 0

574```574```

575 575 

576On macOS and Linux, make the script executable, or the hook fails instead of blocking anything:

577 

578```bash theme={null}

579chmod +x ./scripts/validate-readonly-query.sh

580```

581 

582To test the rule, ask the subagent to run an `UPDATE` statement: the script exits with code 2, Claude Code blocks the command, and the subagent sees the `Blocked: Only SELECT queries are allowed` message.

583 

576See [Hook input](/docs/en/hooks#pretooluse-input) for the complete input schema and [exit codes](/docs/en/hooks#exit-code-output) for how exit codes affect behavior. On Windows, write hook scripts in PowerShell and add `shell: powershell` to the hook entry as shown in [running hooks in PowerShell](/docs/en/hooks#windows-powershell-tool).584See [Hook input](/docs/en/hooks#pretooluse-input) for the complete input schema and [exit codes](/docs/en/hooks#exit-code-output) for how exit codes affect behavior. On Windows, write hook scripts in PowerShell and add `shell: powershell` to the hook entry as shown in [running hooks in PowerShell](/docs/en/hooks#windows-powershell-tool).

577 585 

578#### Disable specific subagents586#### Disable specific subagents


1227 1235 

1228The hook receives JSON via stdin with the Bash command in `tool_input.command`. Exit code 2 blocks the operation and feeds the error message back to Claude. See [Hooks](/docs/en/hooks#exit-code-output) for details on exit codes and [Hook input](/docs/en/hooks#pretooluse-input) for the complete input schema.1236The hook receives JSON via stdin with the Bash command in `tool_input.command`. Exit code 2 blocks the operation and feeds the error message back to Claude. See [Hooks](/docs/en/hooks#exit-code-output) for details on exit codes and [Hook input](/docs/en/hooks#pretooluse-input) for the complete input schema.

1229 1237 

1238The system prompt tells the subagent to refuse write requests, so the hook is a backstop: if the subagent attempts a write anyway, Claude Code blocks the command and the subagent sees the `Blocked: Write operations not allowed. Use SELECT queries only.` message.

1239 

1230## Next steps1240## Next steps

1231 1241 

1232Now that you understand subagents, explore these related features:1242Now that you understand subagents, explore these related features:

Details

38| `Monitor` | Runs a command in the background and feeds each output line back to Claude, so it can react to log entries, file changes, or polled status mid-conversation. Can also open a WebSocket and treat each incoming message as an event. See [Monitor tool](#monitor-tool) | Yes |38| `Monitor` | Runs a command in the background and feeds each output line back to Claude, so it can react to log entries, file changes, or polled status mid-conversation. Can also open a WebSocket and treat each incoming message as an event. See [Monitor tool](#monitor-tool) | Yes |

39| `NotebookEdit` | Modifies Jupyter notebook cells. See [NotebookEdit tool behavior](#notebookedit-tool-behavior) | Yes |39| `NotebookEdit` | Modifies Jupyter notebook cells. See [NotebookEdit tool behavior](#notebookedit-tool-behavior) | Yes |

40| `PowerShell` | Executes PowerShell commands natively. See [PowerShell tool](#powershell-tool) for availability | Yes |40| `PowerShell` | Executes PowerShell commands natively. See [PowerShell tool](#powershell-tool) for availability | Yes |

41| `PushNotification` | Sends a desktop notification, and a phone push when [Remote Control](/docs/en/remote-control) is connected, so a long-running task or [scheduled task](/docs/en/scheduled-tasks) can reach you when you step away. {/* plan-availability: feature=push-notifications providers=anthropic */}Push delivery runs through Anthropic-hosted infrastructure, which is not accessible from Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry | No |41| `PushNotification` | Sends a desktop notification, and a phone push when [Remote Control](/docs/en/remote-control) is connected, so a long-running task or [scheduled task](/docs/en/scheduled-tasks) can reach you when you step away. {/* plan-availability: feature=push-notifications providers=anthropic */}Push delivery runs through Anthropic-hosted infrastructure, which is not accessible from Amazon Bedrock, Claude Platform on AWS, Google Cloud's Agent Platform, or Microsoft Foundry | No |

42| `Read` | Reads the contents of files. See [Read tool behavior](#read-tool-behavior) | No |42| `Read` | Reads the contents of files. See [Read tool behavior](#read-tool-behavior) | No |

43| `ReadMcpResourceTool` | Reads a specific MCP resource by URI | No |43| `ReadMcpResourceTool` | Reads a specific MCP resource by URI | No |

44| `RemoteTrigger` | Creates, updates, runs, and lists [Routines](/docs/en/routines) on claude.ai. Backs the `/schedule` command. {/* plan-availability: feature=routines plans=pro,max,team,enterprise providers=anthropic */}Routines live on claude.ai and require a Pro, Max, Team, or Enterprise plan, so this tool is not accessible from Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry | No |44| `RemoteTrigger` | Creates, updates, runs, and lists [Routines](/docs/en/routines) on claude.ai. Backs the `/schedule` command. {/* plan-availability: feature=routines plans=pro,max,team,enterprise providers=anthropic */}Routines live on claude.ai and require a Pro, Max, Team, or Enterprise plan, so this tool is not accessible from Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry | No |


424The search backend is not configurable. To search with a different provider, add an [MCP server](/docs/en/mcp) that exposes a search tool.424The search backend is not configurable. To search with a different provider, add an [MCP server](/docs/en/mcp) that exposes a search tool.

425 425 

426<Note>426<Note>

427 WebSearch is available on the Claude API, [Claude Platform on AWS](/docs/en/claude-platform-on-aws), and Microsoft Foundry. On Google Cloud's Agent Platform it works with Claude 4 and later models, including Opus, Sonnet, and Haiku. Amazon Bedrock doesn't expose the server-side web search tool.427 WebSearch is available on the Claude API and [Claude Platform on AWS](/docs/en/claude-platform-on-aws). On Microsoft Foundry it requires a [deployment hosted on Anthropic](https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry#hosting-options): deployments hosted on Azure don't support server-side tools, so the WebSearch call fails. On Google Cloud's Agent Platform it works with Claude 4 and later models, including Opus, Sonnet, and Haiku. Amazon Bedrock doesn't expose the server-side web search tool.

428</Note>428</Note>

429 429 

430### Session search limit430### Session search limit

Details

352 winget install Anthropic.ClaudeCode352 winget install Anthropic.ClaudeCode

353 ```353 ```

354 354 

355 Then run `claude --version` to confirm: the command prints a version number such as `2.1.211 (Claude Code)`. If the shell reports `claude` isn't found, open a new terminal window and retry: the session you installed from keeps its old `PATH`.

356 

3552. **Retry after a few minutes**: the issue is often temporary. Wait and try the original command again.3572. **Retry after a few minutes**: the issue is often temporary. Wait and try the original command again.

356 358 

357### `command not found: claude` after installation359### `command not found: claude` after installation


399 winget install Anthropic.ClaudeCode401 winget install Anthropic.ClaudeCode

400 ```402 ```

401 403 

404 Then run `claude --version` to confirm: the command prints a version number such as `2.1.211 (Claude Code)`. If the shell reports `claude` isn't found, open a new terminal window and retry: the session you installed from keeps its old `PATH`.

405 

402### Homebrew cask unavailable or outdated406### Homebrew cask unavailable or outdated

403 407 

404Homebrew reports `Error: Cask 'claude-code' is unavailable: No Cask with this name exists` when your local copy of the Homebrew cask index predates the cask's publication. Refresh the index and retry:408Homebrew reports `Error: Cask 'claude-code' is unavailable: No Cask with this name exists` when your local copy of the Homebrew cask index predates the cask's publication. Refresh the index and retry:


485 winget install Anthropic.ClaudeCode489 winget install Anthropic.ClaudeCode

486 ```490 ```

487 491 

492 Then run `claude --version` to confirm: the command prints a version number such as `2.1.211 (Claude Code)`. If the shell reports `claude` isn't found, open a new terminal window and retry: the session you installed from keeps its old `PATH`.

493 

488### Wrong install command on Windows494### Wrong install command on Windows

489 495 

490If you see `'irm' is not recognized`, `The token '&&' is not valid`, `A parameter cannot be found that matches parameter name 'fsSL'`, or `'bash' is not recognized as the name of a cmdlet`, you copied the install command for a different shell or operating system.496If you see `'irm' is not recognized`, `The token '&&' is not valid`, `A parameter cannot be found that matches parameter name 'fsSL'`, or `'bash' is not recognized as the name of a cmdlet`, you copied the install command for a different shell or operating system.


554 560 

555### Install killed on low-memory Linux servers561### Install killed on low-memory Linux servers

556 562 

557A `Killed` message during install usually means the Linux out-of-memory (OOM) killer terminated the `claude install` step because the system ran out of free memory. This is common on small VPS and cloud instances. The install script reports the cause and exits with code 137:563A `Killed` message during install usually means the Linux out-of-memory (OOM) killer terminated the `claude install` step because the system ran out of free memory. This is common on small VPS and cloud instances. The install script reports the cause and exits with code 137. In this example, the line number and process ID vary by release and run:

558 564 

559```text theme={null}565```text theme={null}

560Setting up Claude Code...566Setting up Claude Code...

561bash: line 142: 34803 Killed "$binary_path" install ${TARGET:+"$TARGET"}567bash: line 183: 34803 Killed "$binary_path" install ${TARGET:+"$TARGET"}

562Installation was killed before it could finish (exit code 137). This usually means the system ran out of memory.568Installation was killed before it could finish (exit code 137). This usually means the system ran out of memory.

563Claude Code needs roughly 512MB of free memory to install. Free up memory, then run this script again.569Claude Code needs roughly 512MB of free memory to install. Free up memory, then run this script again.

564```570```

ultraplan.md +8 −8

Details

10 Ultraplan is in research preview. Behavior and capabilities may change based on feedback.10 Ultraplan is in research preview. Behavior and capabilities may change based on feedback.

11</Note>11</Note>

12 12 

13Ultraplan hands a planning task from your local CLI to a [Claude Code on the web](/en/claude-code-on-the-web) session running in [plan mode](/en/permission-modes#analyze-before-you-edit-with-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.13Ultraplan hands a planning task from your local CLI to a [Claude Code on the web](/docs/en/claude-code-on-the-web) session running in [plan mode](/docs/en/permission-modes#analyze-before-you-edit-with-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.

14 14 

15This is useful when you want a richer review surface than the terminal offers:15This is useful when you want a richer review surface than the terminal offers:

16 16 


18* **Hands-off drafting**: the plan is generated remotely, so your terminal stays free for other work18* **Hands-off drafting**: the plan is generated remotely, so your terminal stays free for other work

19* **Flexible execution**: approve the plan to run on the web and open a pull request, or send it back to your terminal19* **Flexible execution**: approve the plan to run on the web and open a pull request, or send it back to your terminal

20 20 

21Ultraplan requires a [Claude Code on the web](/en/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's Agent Platform, or Microsoft Foundry. The cloud session runs in your account's default [cloud environment](/en/claude-code-on-the-web#the-cloud-environment). If you don't have a cloud environment yet, ultraplan creates one automatically when it first launches.21Ultraplan requires a [Claude Code on the web](/docs/en/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's Agent Platform, or Microsoft Foundry. The cloud session runs in your default [cloud environment](/docs/en/cloud-environments); use [`/remote-env`](/docs/en/cloud-environments#select-an-environment-from-the-cli) in your terminal to change which environment that is. If you don't have a cloud environment yet, ultraplan creates one automatically when it first launches.

22 22 

23## Launch ultraplan from the CLI23## Launch ultraplan from the CLI

24 24 


34/ultraplan migrate the auth service from sessions to JWTs34/ultraplan migrate the auth service from sessions to JWTs

35```35```

36 36 

37The 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](/en/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.37The 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](/docs/en/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.

38 38 

39After the cloud session launches, your CLI's prompt input shows a status indicator while the cloud session works:39After the cloud session launches, your CLI's prompt input shows a status indicator while the cloud session works:

40 40 


62 62 

63### Execute on the web63### Execute on the web

64 64 

65Select **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](/en/claude-code-on-the-web#review-changes) and create a pull request from the web interface.65Select **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](/docs/en/claude-code-on-the-web#review-changes) and create a pull request from the web interface.

66 66 

67### Send the plan back to your terminal67### Send the plan back to your terminal

68 68 


78 78 

79## Related resources79## Related resources

80 80 

81* [Claude Code on the web](/en/claude-code-on-the-web): the cloud infrastructure ultraplan runs on81* [Claude Code on the web](/docs/en/claude-code-on-the-web): the cloud infrastructure ultraplan runs on

82* [Plan mode](/en/permission-modes#analyze-before-you-edit-with-plan-mode): how planning works in a local session82* [Plan mode](/docs/en/permission-modes#analyze-before-you-edit-with-plan-mode): how planning works in a local session

83* [Find bugs with ultrareview](/en/ultrareview): the code review counterpart to ultraplan for catching issues before merge83* [Find bugs with ultrareview](/docs/en/ultrareview): the code review counterpart to ultraplan for catching issues before merge

84* [Remote Control](/en/remote-control): use the claude.ai/code interface with a session running on your own machine84* [Remote Control](/docs/en/remote-control): use the claude.ai/code interface with a session running on your own machine

web-quickstart.md +36 −38

Details

12 12 

13Claude Code on the web runs on Anthropic-managed cloud infrastructure instead of your machine. Submit tasks from [claude.ai/code](https://claude.ai/code) in your browser or the Claude mobile app.13Claude Code on the web runs on Anthropic-managed cloud infrastructure instead of your machine. Submit tasks from [claude.ai/code](https://claude.ai/code) in your browser or the Claude mobile app.

14 14 

15You'll need a GitHub repository to [get started](#connect-github-and-create-an-environment). 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.15You'll need a GitHub repository to [get started](#connect-github). 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.

16 16 

17Claude Code on the web works well for:17Claude Code on the web works well for:

18 18 


21* **Tasks that don't need frequent steering**: submit a well-defined task, do something else, and review the result when Claude is done21* **Tasks that don't need frequent steering**: submit a well-defined task, do something else, and review the result when Claude is done

22* **Code questions and exploration**: understand a codebase or trace how a feature is implemented without a local checkout22* **Code questions and exploration**: understand a codebase or trace how a feature is implemented without a local checkout

23 23 

24For work that needs your local config, tools, or environment, running Claude Code locally or using [Remote Control](/en/remote-control) is a better fit.24For work that needs your local config, tools, or environment, running Claude Code locally or using [Remote Control](/docs/en/remote-control) is a better fit.

25 25 

26## How sessions run26## How sessions run

27 27 

28When you submit a task:28When you submit a task:

29 29 

301. **Clone and prepare**: your repository is cloned to an Anthropic-managed VM, and your [setup script](/en/claude-code-on-the-web#setup-scripts) runs if configured.301. **Clone and prepare**: your repository is cloned to an Anthropic-managed VM, and your [setup script](/docs/en/cloud-environments#setup-scripts) runs if configured.

312. **Configure network**: internet access is set based on your environment's [access level](/en/claude-code-on-the-web#access-levels).312. **Configure network**: internet access is set based on your environment's [access level](/docs/en/cloud-environments#access-levels).

323. **Work**: Claude analyzes code, makes changes, runs tests, and checks its work. You can watch and steer throughout, or step away and come back when it's done.323. **Work**: Claude analyzes code, makes changes, runs tests, and checks its work. You can watch and steer throughout, or step away and come back when it's done.

334. **Push the branch**: when Claude reaches a stopping point, it pushes its branch to GitHub. You review the diff, leave inline comments, create a PR, or send another message to keep going.334. **Push the branch**: when Claude reaches a stopping point, it pushes its branch to GitHub. You review the diff, leave inline comments, create a PR, or send another message to keep going.

34 34 


43| **Code runs on** | Anthropic cloud VM | Your machine | Your machine | Your machine or cloud VM |43| **Code runs on** | Anthropic cloud VM | Your machine | Your machine | Your machine or cloud VM |

44| **You chat from** | claude.ai or mobile app | claude.ai or mobile app | Your terminal | The Desktop UI |44| **You chat from** | claude.ai or mobile app | claude.ai or mobile app | Your terminal | The Desktop UI |

45| **Uses your local config** | No, repo only | Yes | Yes | Yes for local, no for cloud |45| **Uses your local config** | No, repo only | Yes | Yes | Yes for local, no for cloud |

46| **Requires GitHub** | Yes, or [bundle a local repo](/en/claude-code-on-the-web#send-local-repositories-without-github) via `--cloud` | No | No | Only for cloud sessions |46| **Requires GitHub** | Yes, or [bundle a local repo](/docs/en/claude-code-on-the-web#send-local-repositories-without-github) via `--cloud` | No | No | Only for cloud sessions |

47| **Keeps running if you disconnect** | Yes | While terminal stays open | No | Depends on session type |47| **Keeps running if you disconnect** | Yes | While terminal stays open | No | Depends on session type |

48| **[Permission modes](/en/permission-modes)** | Accept edits, Plan, Auto | Manual, Accept edits, Plan | All modes | Depends on session type |48| **[Permission modes](/docs/en/permission-modes)** | Accept edits, Plan, Auto | Manual, Accept edits, Plan | All modes | Depends on session type |

49| **Network access** | Configurable per environment | Your machine's network | Your machine's network | Depends on session type |49| **Network access** | Configurable per environment | Your machine's network | Your machine's network | Depends on session type |

50 50 

51See the [terminal quickstart](/en/quickstart), [Desktop app](/en/desktop), or [Remote Control](/en/remote-control) docs to set those up.51See the [terminal quickstart](/docs/en/quickstart), [Desktop app](/docs/en/desktop), or [Remote Control](/docs/en/remote-control) docs to set those up.

52 52 

53## Connect GitHub and create an environment53## Connect GitHub

54 54 

55Setup is a one-time process. If you already use the GitHub CLI, you can [do this from your terminal](#connect-from-your-terminal) instead of the browser.55Setup is a one-time process. If you already use the GitHub CLI, you can [do this from your terminal](#connect-from-your-terminal) instead of the browser.

56 56 


63 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](https://github.com/new) first.63 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](https://github.com/new) first.

64 </Step>64 </Step>

65 65 

66 <Step title="Create your environment">66 <Step title="Confirm your Default environment">

67 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](/en/claude-code-on-the-web#installed-tools) for what's available without any configuration.67 When you finish connecting GitHub, onboarding creates a [cloud environment](/docs/en/cloud-environments) named **Default** for you; if onboarding shows an environment form instead, keep its defaults to create the same **Default** environment. The environment controls what network access Claude has during sessions and what runs when a new session is created. **Default** uses [`Trusted` network access](/docs/en/cloud-environments#access-levels): sessions reach [common package registries](/docs/en/cloud-environments#default-allowed-domains) and other allowlisted domains, and nothing else through the session's network. See [Installed tools](/docs/en/cloud-environments#installed-tools) for what's available without any configuration.

68 68 

69 The form has these fields:69 For a first project, the **Default** environment works as is. To change its network access, add environment variables, or run a [setup script](/docs/en/cloud-environments#setup-scripts) before sessions start, [edit it or create additional environments](/docs/en/cloud-environments#configure-your-environment).

70 

71 * **Name**: a display label. Useful when you have multiple environments for different projects or access levels.

72 * **Network access**: controls what the session can reach on the internet. The default, `Trusted`, allows connections to [common package registries](/en/claude-code-on-the-web#default-allowed-domains) like npm, PyPI, and RubyGems while blocking general internet access.

73 * **Environment variables**: optional variables available in every session, in `.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.

74 * **Setup script**: an optional Bash script that runs before Claude Code launches. Use it to install system tools the cloud VM doesn't include, like `apt install -y gh`. The result is [cached](/en/claude-code-on-the-web#environment-caching), so the script doesn't re-run on every session. See [Setup scripts](/en/claude-code-on-the-web#setup-scripts) for examples and debugging tips.

75 

76 For a first project, leave the defaults and click **Create environment**. You can [edit it later or create additional environments](/en/claude-code-on-the-web#configure-your-environment) for different projects.

77 </Step>70 </Step>

78</Steps>71</Steps>

79 72 

80### Connect from your terminal73### Connect from your terminal

81 74 

82If 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](/en/quickstart). `/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.75If 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](/docs/en/quickstart). `/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.

83 76 

84<Note>77<Note>

85 Organizations with [Zero Data Retention](/en/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.78 Organizations with [Zero Data Retention](/docs/en/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.

86</Note>79</Note>

87 80 

88<Steps>81<Steps>


95 </Step>88 </Step>

96 89 

97 <Step title="Sign in to Claude">90 <Step title="Sign in to Claude">

98 In the Claude Code CLI, run `/login` to sign in with your claude.ai account. Skip this step if you're already signed in.91 In the Claude Code CLI, run `/login` to sign in with your claude.ai account. Skip this step if you're already signed in with a claude.ai account. Authenticating with an API key doesn't count. To check, run `/status` and confirm the **Login method** row shows a claude.ai account.

99 </Step>92 </Step>

100 93 

101 <Step title="Run /web-setup">94 <Step title="Run /web-setup">


105 /web-setup98 /web-setup

106 ```99 ```

107 100 

108 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](/en/claude-code-on-the-web#configure-your-environment) afterward. Once `/web-setup` completes, you can start cloud sessions from your terminal with [`--cloud`](/en/claude-code-on-the-web#from-terminal-to-web) or set up recurring tasks with [`/schedule`](/en/routines).101 This syncs your `gh` token to your Claude account. On success, Claude Code prints `Connected as <your-github-username>` and opens [claude.ai/code](https://claude.ai/code) in your browser. 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](/docs/en/cloud-environments#configure-your-environment) afterward. Once `/web-setup` completes, you can start cloud sessions from your terminal with [`--cloud`](/docs/en/claude-code-on-the-web#from-terminal-to-web) or set up recurring tasks with [`/schedule`](/docs/en/routines).

109 </Step>102 </Step>

110</Steps>103</Steps>

111 104 


119 </Step>112 </Step>

120 113 

121 <Step title="Choose a permission mode">114 <Step title="Choose a permission mode">

122 The mode dropdown next to the input defaults to **Accept edits**, where Claude makes changes and pushes a branch without stopping for approval. Switch to **Plan** if you want Claude to propose an approach and wait for you to approve it before editing files. Cloud sessions don't offer Manual or Bypass permissions. See the [full list of permission modes](/en/permission-modes#available-modes) for what each one allows.115 The mode dropdown next to the input defaults to **Accept edits**, where Claude makes changes and pushes a branch without stopping for approval. Switch to **Plan** if you want Claude to propose an approach and wait for you to approve it before editing files. Cloud sessions don't offer Manual or Bypass permissions. See the [full list of permission modes](/docs/en/permission-modes#available-modes) for what each one allows.

123 </Step>116 </Step>

124 117 

125 <Step title="Describe the task and submit">118 <Step title="Describe the task and submit">


142| `prompt` | Prompt text to prefill in the input box. The alias `q` is also accepted. |135| `prompt` | Prompt text to prefill in the input box. The alias `q` is also accepted. |

143| `prompt_url` | URL to fetch the prompt text from, for prompts too long to embed in a query string. The URL must allow cross-origin requests. Ignored when `prompt` is also set. |136| `prompt_url` | URL to fetch the prompt text from, for prompts too long to embed in a query string. The URL must allow cross-origin requests. Ignored when `prompt` is also set. |

144| `repositories` | Comma-separated list of `owner/repo` slugs to preselect. The alias `repo` is also accepted. |137| `repositories` | Comma-separated list of `owner/repo` slugs to preselect. The alias `repo` is also accepted. |

145| `environment` | Name or ID of the [environment](#connect-github-and-create-an-environment) to preselect. |138| `environment` | Name or ID of the [environment](#connect-github) to preselect. |

146 139 

147URL-encode each value. The example below opens the form with a prompt and a repository already selected:140URL-encode each value. The example below opens the form with a prompt and a repository already selected:

148 141 


168 </Step>161 </Step>

169 162 

170 <Step title="Keep iterating after the PR">163 <Step title="Keep iterating after the PR">

171 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](/en/claude-code-on-the-web#auto-fix-pull-requests).164 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](/docs/en/claude-code-on-the-web#auto-fix-pull-requests).

172 </Step>165 </Step>

173</Steps>166</Steps>

174 167 


176 169 

177### No repositories appear after connecting GitHub170### No repositories appear after connecting GitHub

178 171 

179A cloud session can use any repository the connected GitHub account can see, regardless of which repositories the Claude GitHub App is installed on. If a repository is missing, verify the connected GitHub account has access to it on GitHub. If you also want [Auto-fix](/en/claude-code-on-the-web#auto-fix-pull-requests) for a repository, install the App on it: on github.com, open **Settings → Applications → Claude → Configure** and verify the repository is listed under **Repository access**. Private repositories need the same authorization as public ones.172A cloud session can use any repository the connected GitHub account can see, regardless of which repositories the Claude GitHub App is installed on. If a repository is missing, verify the connected GitHub account has access to it on GitHub. If you also want [Auto-fix](/docs/en/claude-code-on-the-web#auto-fix-pull-requests) for a repository, install the App on it: on github.com, open **Settings → Applications → Claude → Configure** and verify the repository is listed under **Repository access**. Private repositories need the same authorization as public ones.

180 173 

181### The page only shows a GitHub login button174### The page only shows a GitHub login button

182 175 

183Cloud 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](/en/remote-control) to run Claude Code on your own machine and monitor it from the web.176Cloud 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](/docs/en/remote-control) to run Claude Code on your own machine and monitor it from the web.

184 177 

185### "Not available for the selected organization"178### "Not available for the selected organization"

186 179 

187Enterprise organizations may need an Owner to enable Claude Code on the web. Contact your Anthropic account team.180Enterprise organizations may need an Owner to enable Claude Code on the web. Contact your Anthropic account team.

188 181 

182### `/web-setup` says "Not signed in to Claude"

183 

184If `/web-setup` responds with "Not signed in to Claude. Run /login first.", the CLI doesn't have a valid claude.ai sign-in. This can also happen when a previous sign-in has expired. Run `/login`, sign in with your claude.ai account, then run `/web-setup` again.

185 

189### `/web-setup` shows "No commands match" or "Unknown command"186### `/web-setup` shows "No commands match" or "Unknown command"

190 187 

191`/web-setup` runs inside the Claude Code CLI, not your shell. Launch `claude` first, then type `/web-setup` at the prompt.188`/web-setup` runs inside the Claude Code CLI, not your shell. Launch `claude` first, then type `/web-setup` at the prompt.

192 189 

193If you typed it inside Claude Code and the command menu shows `No commands match "/web-setup"`, or submitting it returns `Unknown command: /web-setup`, the command is hidden because a requirement isn't met. The cause is usually that you're authenticated with an API key or third-party provider instead of a claude.ai subscription. Run `/login` to sign in with your claude.ai account.190If you typed it inside Claude Code and the command menu shows `No commands match "/web-setup"`, or submitting it returns `Unknown command: /web-setup`, the command is hidden because a requirement isn't met. The cause is usually that you're authenticated with an API key or third-party provider instead of a claude.ai subscription. Run `/login` to sign in with your claude.ai account. Team and Enterprise Owners can also [disable `/web-setup`](/docs/en/claude-code-on-the-web#github-authentication-options) for their organization, which hides the command. In that case, use the browser flow above instead.

194 191 

195On Team and Enterprise plans, the command is also hidden when any of the following apply:192On Team and Enterprise plans, the command is also hidden when any of the following apply:

196 193 

197* an administrator has disabled Claude Code on the web for your organization194* an administrator has disabled Claude Code on the web for your organization

198* an administrator has disabled the [Quick web setup toggle](/en/claude-code-on-the-web#github-authentication-options)195* an administrator has disabled the [Quick web setup toggle](/docs/en/claude-code-on-the-web#github-authentication-options)

199* your Enterprise organization has [Zero Data Retention](/en/zero-data-retention) enabled, which makes Claude Code on the web unavailable196* your Enterprise organization has [Zero Data Retention](/docs/en/zero-data-retention) enabled, which makes Claude Code on the web unavailable

200 197 

201### "Could not create a cloud environment" or "No cloud environment available" when using `--cloud` or ultraplan198### "Could not create a cloud environment" or "No cloud environment available" when using `--cloud` or ultraplan

202 199 

203Remote-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](https://claude.ai/code) and follow the **Create your environment** step above.200Remote-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, or add an environment from the [environment selector](/docs/en/cloud-environments#configure-your-environment) at [claude.ai/code](https://claude.ai/code).

204 201 

205### Setup script failed202### Setup script failed

206 203 

207The setup script exited with a non-zero status, which blocks the session from starting. Common causes:204The setup script exited with a non-zero status, which blocks the session from starting. Common causes:

208 205 

209* A package install failed because the registry isn't in your [network access level](/en/claude-code-on-the-web#access-levels). `Trusted` covers most package managers; `None` blocks them all.206* A package install failed because the registry isn't in your [network access level](/docs/en/cloud-environments#access-levels). `Trusted` covers most package managers; `None` blocks them all.

210* The script references a file or path that doesn't exist in a fresh clone.207* The script references a file or path that doesn't exist in a fresh clone.

211* A command that works locally needs a different invocation on Ubuntu.208* A command that works locally needs a different invocation on Ubuntu.

212 209 


214 211 

215### New sessions hang or time out during setup212### New sessions hang or time out during setup

216 213 

217If new sessions stall on the setup script step or fail with a generic container error before the script finishes, the script is likely exceeding the roughly five-minute time budget for building the [environment cache](/en/claude-code-on-the-web#environment-caching). Heavy steps such as pulling large Docker images, syncing full dependency trees, or downloading model weights often push the total over the limit, especially when they run one after another.214If new sessions stall on the setup script step or fail with a generic container error before the script finishes, the script is likely exceeding the roughly five-minute time budget for building the [environment cache](/docs/en/cloud-environments#environment-caching). Heavy steps such as pulling large Docker images, syncing full dependency trees, or downloading model weights often push the total over the limit, especially when they run one after another.

218 215 

219To fix this, trim the script so it reliably finishes in under five minutes:216To fix this, trim the script so it reliably finishes in under five minutes:

220 217 

221* Run independent installs in parallel with `&` and a final `wait` instead of running them serially.218* Run independent installs in parallel with `&` and a final `wait` instead of running them serially.

222* Move the largest downloads out of the setup script and into a [SessionStart hook](/en/claude-code-on-the-web#setup-scripts-vs-sessionstart-hooks) that launches them in the background, so the session becomes usable while they finish.219* Move the largest downloads out of the setup script and into a [SessionStart hook](/docs/en/cloud-environments#setup-scripts-vs-sessionstart-hooks) that launches them in the background, so the session becomes usable while they finish.

223* Remove long retry sleeps from the setup script, since a stalled retry loop counts against the budget.220* Remove long retry sleeps from the setup script, since a stalled retry loop counts against the budget.

224 221 

225### Session keeps running after closing the tab222### Session keeps running after closing the tab

226 223 

227This 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](/en/claude-code-on-the-web#archive-sessions) to hide it from your list, or [delete it](/en/claude-code-on-the-web#delete-sessions) to remove it permanently.224This 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](/docs/en/claude-code-on-the-web#archive-sessions) to hide it from your list, or [delete it](/docs/en/claude-code-on-the-web#delete-sessions) to remove it permanently.

228 225 

229## Next steps226## Next steps

230 227 

231Now 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.228Now 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.

232 229 

233* [Use Claude Code on the web](/en/claude-code-on-the-web): the full reference, including teleporting sessions to your terminal, setup scripts, environment variables, and network config230* [Use Claude Code on the web](/docs/en/claude-code-on-the-web): the full reference, including teleporting sessions to your terminal, session sharing, and auto-fixing pull requests

234* [Routines](/en/routines): automate work on a schedule, via API call, or in response to GitHub events231* [Configure cloud environments](/docs/en/cloud-environments): network access levels, environment variables, and setup scripts for cloud sessions

235* [CLAUDE.md](/en/memory): give Claude persistent instructions and context that load at the start of every session232* [Routines](/docs/en/routines): automate work on a schedule, via API call, or in response to GitHub events

233* [CLAUDE.md](/docs/en/memory): give Claude persistent instructions and context that load at the start of every session

236* Install the Claude mobile app for [iOS](https://apps.apple.com/us/app/claude-by-anthropic/id6473753684) or [Android](https://play.google.com/store/apps/details?id=com.anthropic.claude) to monitor sessions from your phone. From the Claude Code CLI, `/mobile` shows a QR code.234* Install the Claude mobile app for [iOS](https://apps.apple.com/us/app/claude-by-anthropic/id6473753684) or [Android](https://play.google.com/store/apps/details?id=com.anthropic.claude) to monitor sessions from your phone. From the Claude Code CLI, `/mobile` shows a QR code.

worktrees.md +27 −27

Details

9A [git worktree](https://git-scm.com/docs/git-worktree) is a separate working directory with its own files and branch, sharing the same repository history and remote as your main checkout. Running each Claude Code session in its own worktree means edits in one session never touch files in another, so one session can build a feature while a second fixes a bug.9A [git worktree](https://git-scm.com/docs/git-worktree) is a separate working directory with its own files and branch, sharing the same repository history and remote as your main checkout. Running each Claude Code session in its own worktree means edits in one session never touch files in another, so one session can build a feature while a second fixes a bug.

10 10 

11<Note>11<Note>

12 Worktrees require a git repository; for other version control systems, [configure hooks to replace the git logic](#non-git-version-control). In the [desktop app](/en/desktop#work-in-parallel-with-sessions), every new session gets its own worktree automatically.12 Worktrees require a git repository; for other version control systems, [configure hooks to replace the git logic](#non-git-version-control). In the [desktop app](/docs/en/desktop#work-in-parallel-with-sessions), every new session gets its own worktree automatically.

13</Note>13</Note>

14 14 

15Worktrees are one of several ways to run Claude in parallel. They isolate file edits, while [subagents](/en/sub-agents) and [agent teams](/en/agent-teams) coordinate the work itself. See [Run agents in parallel](/en/agents) to compare the approaches, or skip ahead to [Isolate subagents with worktrees](#isolate-subagents-with-worktrees) to use worktrees and subagents together.15Worktrees are one of several ways to run Claude in parallel. They isolate file edits, while [subagents](/docs/en/sub-agents) and [agent teams](/docs/en/agent-teams) coordinate the work itself. See [Run agents in parallel](/docs/en/agents) to compare the approaches, or skip ahead to [Isolate subagents with worktrees](#isolate-subagents-with-worktrees) to use worktrees and subagents together.

16 16 

17Most sessions need only the first two sections: [start Claude in a worktree](#start-claude-in-a-worktree), then [clean up when you exit](#clean-up-worktrees). Return to the rest of the page when you need to [resume a session](#resume-a-worktree-session), [change how worktrees are created](#customize-worktree-creation), or [debug a failure](#troubleshooting).17Most sessions need only the first two sections: [start Claude in a worktree](#start-claude-in-a-worktree), then [clean up when you exit](#clean-up-worktrees). Return to the rest of the page when you need to [resume a session](#resume-a-worktree-session), [change how worktrees are created](#customize-worktree-creation), or [debug a failure](#troubleshooting).

18 18 


26 26 

27Run the command again with a different name in another terminal to start a second isolated session. If you omit the name, Claude generates one such as `bright-running-fox`.27Run the command again with a different name in another terminal to start a second isolated session. If you omit the name, Claude generates one such as `bright-running-fox`.

28 28 

29Interactive runs require [workspace trust](/en/security): if you haven't run Claude in the directory before, run `claude` once there to accept the trust dialog, or `--worktree` exits with an error prompting you to. Non-interactive runs with `-p` skip the trust check, so `claude -p --worktree` proceeds without it.29Interactive runs require [workspace trust](/docs/en/security): if you haven't run Claude in the directory before, run `claude` once there to accept the trust dialog, or `--worktree` exits with an error prompting you to. Non-interactive runs with `-p` skip the trust check, so `claude -p --worktree` proceeds without it.

30 30 

31<Tip>31<Tip>

32 Add `.claude/worktrees/` to your `.gitignore` so worktree contents don't appear as untracked files in your main checkout.32 Add `.claude/worktrees/` to your `.gitignore` so worktree contents don't appear as untracked files in your main checkout.


38 38 

39### Ask Claude to create a worktree39### Ask Claude to create a worktree

40 40 

41You can also ask Claude to "work in a worktree" during a session, and it creates one with the [`EnterWorktree`](/en/tools-reference) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path; the previous worktree stays on disk untouched.41You can also ask Claude to "work in a worktree" during a session, and it creates one with the [`EnterWorktree`](/docs/en/tools-reference) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path; the previous worktree stays on disk untouched.

42 42 

43When Claude enters a path outside the repository's `.claude/worktrees/` directory, Claude Code asks for your approval first, because the move takes the session's working directory, write access, and project configuration such as `CLAUDE.md` and settings to that location. An `EnterWorktree` [permission rule](/en/permissions) or choosing "don't ask again" doesn't suppress this prompt; only `bypassPermissions` mode skips it. Before v2.1.206, Claude could enter any existing worktree path without asking.43When Claude enters a path outside the repository's `.claude/worktrees/` directory, Claude Code asks for your approval first, because the move takes the session's working directory, write access, and project configuration such as `CLAUDE.md` and settings to that location. An `EnterWorktree` [permission rule](/docs/en/permissions) or choosing "don't ask again" doesn't suppress this prompt; only `bypassPermissions` mode skips it. Before v2.1.206, Claude could enter any existing worktree path without asking.

44 44 

45## Clean up worktrees45## Clean up worktrees

46 46 

47When you exit an interactive worktree session, Claude checks the worktree for work that removal would delete: changed or untracked files, and new commits.47When you exit an interactive worktree session, Claude checks the worktree for work that removal would delete: changed or untracked files, and new commits.

48 48 

49* **The worktree is clean**: for an unnamed session, Claude removes the worktree and its branch automatically. A [named](/en/sessions#name-your-sessions) session prompts you first so you can keep the worktree for later49* **The worktree is clean**: for an unnamed session, Claude removes the worktree and its branch automatically. A [named](/docs/en/sessions#name-your-sessions) session prompts you first so you can keep the worktree for later

50* **The worktree has work in it**: Claude prompts you to keep or remove the worktree. Keeping preserves the directory and branch so you can return later. Removing deletes the worktree directory and its branch, along with all the work in them50* **The worktree has work in it**: Claude prompts you to keep or remove the worktree. Keeping preserves the directory and branch so you can return later. Removing deletes the worktree directory and its branch, along with all the work in them

51 51 

52Non-interactive runs with `-p` have no exit prompt, so Claude doesn't clean up their worktrees. Remove them with `git worktree remove`.52Non-interactive runs with `-p` have no exit prompt, so Claude doesn't clean up their worktrees. Remove them with `git worktree remove`.


55 55 

56## Resume a worktree session56## Resume a worktree session

57 57 

58When you resume a session that was inside a worktree, Claude Code returns the session to that worktree. This holds for interactive resumes, for `--continue` and `--resume` in [non-interactive mode](/en/headless) with `-p`, and for the Agent SDK. Back inside the worktree, Claude can still exit it with the [`ExitWorktree`](/en/tools-reference) tool.58When you resume a session that was inside a worktree, Claude Code returns the session to that worktree. This holds for interactive resumes, for `--continue` and `--resume` in [non-interactive mode](/docs/en/headless) with `-p`, and for the Agent SDK. Back inside the worktree, Claude can still exit it with the [`ExitWorktree`](/docs/en/tools-reference) tool.

59 59 

60A resume that forks the session with `--fork-session` starts in the directory you launched Claude from and leaves the original session's worktree untouched. If the worktree directory no longer exists, the session resumes in the directory you launched Claude from.60A resume that forks the session with `--fork-session` starts in the directory you launched Claude from and leaves the original session's worktree untouched. If the worktree directory no longer exists, the session resumes in the directory you launched Claude from.

61 61 


63 Before v2.1.212, a non-interactive resume stayed in the starting directory and `ExitWorktree` reported that there was no active worktree session to exit.63 Before v2.1.212, a non-interactive resume stayed in the starting directory and `ExitWorktree` reported that there was no active worktree session to exit.

64</Note>64</Note>

65 65 

66{/* min-version: 2.1.198 */}When Claude enters or exits a worktree that Claude Code created with git, the transcript follows: Claude Code records the session under the session's new working directory, the same way [`/cd`](/en/commands) does, so `/desktop` and `--resume` find it there. Exiting moves it back the same way. A worktree created by a [`WorktreeCreate` hook](#non-git-version-control) keeps its transcript at the launch directory. Requires Claude Code v2.1.198 or later.66{/* min-version: 2.1.198 */}When Claude enters or exits a worktree that Claude Code created with git, the transcript follows: Claude Code records the session under the session's new working directory, the same way [`/cd`](/docs/en/commands) does, so `/desktop` and `--resume` find it there. Exiting moves it back the same way. A worktree created by a [`WorktreeCreate` hook](#non-git-version-control) keeps its transcript at the launch directory. Requires Claude Code v2.1.198 or later.

67 67 

68## Isolate subagents with worktrees68## Isolate subagents with worktrees

69 69 

70Subagents can run in their own worktrees so parallel edits don't conflict. Ask Claude to "use worktrees for your agents", or make the isolation permanent for a [custom subagent](/en/sub-agents#supported-frontmatter-fields) by adding `isolation: worktree` to its frontmatter.70Subagents can run in their own worktrees so parallel edits don't conflict. Ask Claude to "use worktrees for your agents", or make the isolation permanent for a [custom subagent](/docs/en/sub-agents#supported-frontmatter-fields) by adding `isolation: worktree` to its frontmatter.

71 71 

72This subagent in `.claude/agents/` always runs in its own worktree:72This subagent in `.claude/agents/` always runs in its own worktree:

73 73 


88 88 

89### Clean up subagent and background-session worktrees89### Clean up subagent and background-session worktrees

90 90 

91A periodic sweep removes worktrees that Claude created for subagents and [background sessions](/en/agent-view#how-file-edits-are-isolated) once they are older than your [`cleanupPeriodDays`](/en/settings#available-settings) setting. The sweep skips a worktree that still holds work: changed or untracked files, or unpushed commits. It never removes worktrees you create with `--worktree`.91A periodic sweep removes worktrees that Claude created for subagents and [background sessions](/docs/en/agent-view#how-file-edits-are-isolated) once they are older than your [`cleanupPeriodDays`](/docs/en/settings#available-settings) setting. The sweep skips a worktree that still holds work: changed or untracked files, or unpushed commits. It never removes worktrees you create with `--worktree`.

92 92 

93While an agent is running, Claude runs `git worktree lock` on its worktree so that concurrent cleanup cannot remove it. The lock is released when the agent finishes.93While an agent is running, Claude runs `git worktree lock` on its worktree so that concurrent cleanup cannot remove it. The lock is released when the agent finishes.

94 94 


102 102 

103### Choose the base branch103### Choose the base branch

104 104 

105New worktrees branch from the repository's default branch, so most sessions don't need this setting. Set `worktree.baseRef` in [settings](/en/settings#worktree-settings) to branch from your current work instead. The setting accepts two values:105New worktrees branch from the repository's default branch, so most sessions don't need this setting. Set `worktree.baseRef` in [settings](/docs/en/settings#worktree-settings) to branch from your current work instead. The setting accepts two values:

106 106 

107* `"fresh"` (default): branch from the repository's default branch on the remote, usually `main`, so the worktree starts from a clean tree matching the remote.107* `"fresh"` (default): branch from the repository's default branch on the remote, usually `main`, so the worktree starts from a clean tree matching the remote.

108* `"head"`: branch from your current local `HEAD`, so the worktree carries your unpushed commits and feature-branch state. Use this when isolating subagents that need to operate on in-progress work. Inside a worktree, `"head"` resolves to that worktree's `HEAD`, not the main checkout's.108* `"head"`: branch from your current local `HEAD`, so the worktree carries your unpushed commits and feature-branch state. Use this when isolating subagents that need to operate on in-progress work. Inside a worktree, `"head"` resolves to that worktree's `HEAD`, not the main checkout's.


143config/secrets.json143config/secrets.json

144```144```

145 145 

146This applies to every worktree Claude Code creates with git: `--worktree` worktrees, [subagent worktrees](#isolate-subagents-with-worktrees), and parallel sessions in the [desktop app](/en/desktop#work-in-parallel-with-sessions). With a [`WorktreeCreate` hook](#non-git-version-control), copy the files inside the hook script.146This applies to every worktree Claude Code creates with git: `--worktree` worktrees, [subagent worktrees](#isolate-subagents-with-worktrees), and parallel sessions in the [desktop app](/docs/en/desktop#work-in-parallel-with-sessions). With a [`WorktreeCreate` hook](#non-git-version-control), copy the files inside the hook script.

147 147 

148### Reuse a worktree name148### Reuse a worktree name

149 149 


161 161 

162### Replace worktree creation with a hook162### Replace worktree creation with a hook

163 163 

164Configure a [`WorktreeCreate` hook](/en/hooks#worktreecreate) to replace the default `git worktree` logic entirely, including placing worktrees somewhere other than `.claude/worktrees/`. For a complete example, see [Non-git version control](#non-git-version-control).164Configure a [`WorktreeCreate` hook](/docs/en/hooks#worktreecreate) to replace the default `git worktree` logic entirely, including placing worktrees somewhere other than `.claude/worktrees/`. For a complete example, see [Non-git version control](#non-git-version-control).

165 165 

166## What worktrees share with the main checkout166## What worktrees share with the main checkout

167 167 

168A worktree gets its own files and branch, but it shares the repository's `.git` directory, project-scope plugins, and saved permission approvals with the main checkout:168A worktree gets its own files and branch, but it shares the repository's `.git` directory, project-scope plugins, and saved permission approvals with the main checkout:

169 169 

170* **The repository's `.git` directory**: git commands in a worktree write to the main repository's shared `.git` directory, and [sandboxing](/en/sandboxing#filesystem-isolation) allows those writes, so commands such as `git commit` work from inside a worktree with the sandbox enabled.170* **The repository's `.git` directory**: git commands in a worktree write to the main repository's shared `.git` directory, and [sandboxing](/docs/en/sandboxing#filesystem-isolation) allows those writes, so commands such as `git commit` work from inside a worktree with the sandbox enabled.

171* {/* min-version: 2.1.200 */}**Plugins**: plugins installed at [project scope](/en/plugins-reference#plugin-installation-scopes) from the main checkout also load in worktrees of the same repository, so you don't need to reinstall them per worktree. Requires Claude Code v2.1.200 or later.171* {/* min-version: 2.1.200 */}**Plugins**: plugins installed at [project scope](/docs/en/plugins-reference#plugin-installation-scopes) from the main checkout also load in worktrees of the same repository, so you don't need to reinstall them per worktree. Requires Claude Code v2.1.200 or later.

172* {/* min-version: 2.1.211 */}**Permission approvals**: choosing "Yes, don't ask again" for a Bash command in a worktree session saves the rule to the main checkout's `.claude/settings.local.json`, so it applies in the main checkout and in every other worktree of the repository, and it survives the worktree's removal. Before v2.1.211, an approval granted in a worktree was saved inside that worktree, didn't apply elsewhere, and was lost when the worktree was removed. See [where approvals are saved](/en/permissions#permission-system).172* {/* min-version: 2.1.211 */}**Permission approvals**: choosing "Yes, don't ask again" for a Bash command in a worktree session saves the rule to the main checkout's `.claude/settings.local.json`, so it applies in the main checkout and in every other worktree of the repository, and it survives the worktree's removal. Before v2.1.211, an approval granted in a worktree was saved inside that worktree, didn't apply elsewhere, and was lost when the worktree was removed. See [where approvals are saved](/docs/en/permissions#permission-system).

173 173 

174All three apply whether you create the worktree with `--worktree`, with `git worktree add`, or through the [desktop app](/en/desktop#work-in-parallel-with-sessions).174All three apply whether you create the worktree with `--worktree`, with `git worktree add`, or through the [desktop app](/docs/en/desktop#work-in-parallel-with-sessions).

175 175 

176## Manage worktrees manually176## Manage worktrees manually

177 177 


183git worktree add ../project-feature-a -b feature-a183git worktree add ../project-feature-a -b feature-a

184```184```

185 185 

186Create a worktree from an existing branch:186Create a worktree from an existing branch, replacing `fix-issue-456` with a branch that already exists in your repository:

187 187 

188```bash theme={null}188```bash theme={null}

189git worktree add ../project-bugfix bugfix-123189git worktree add ../project-bugfix fix-issue-456

190```190```

191 191 

192Start Claude in the worktree:192Start Claude in the worktree:


212 212 

213## Non-git version control213## Non-git version control

214 214 

215Worktree isolation uses git by default. For SVN, Perforce, Mercurial, or other systems, configure [`WorktreeCreate` and `WorktreeRemove` hooks](/en/hooks#worktreecreate) to provide custom creation and cleanup logic. Because the hook replaces the default git behavior, [`.worktreeinclude`](#copy-gitignored-files-into-worktrees) is not processed when you use `--worktree`. Copy any local configuration files inside your hook script instead.215Worktree isolation uses git by default. For SVN, Perforce, Mercurial, or other systems, configure [`WorktreeCreate` and `WorktreeRemove` hooks](/docs/en/hooks#worktreecreate) to provide custom creation and cleanup logic. Because the hook replaces the default git behavior, [`.worktreeinclude`](#copy-gitignored-files-into-worktrees) is not processed when you use `--worktree`. Copy any local configuration files inside your hook script instead.

216 216 

217This `WorktreeCreate` hook reads the worktree name from the JSON on stdin with `jq`, checks out a fresh SVN working copy, and prints the directory path so Claude Code can use it as the session's working directory. Add the configuration to your [`settings.json`](/en/settings#settings-files):217This `WorktreeCreate` hook reads the worktree name from the JSON on stdin with `jq`, checks out a fresh SVN working copy, and prints the directory path so Claude Code can use it as the session's working directory. Add the configuration to your [`settings.json`](/docs/en/settings#settings-files):

218 218 

219```json theme={null}219```json theme={null}

220{220{


233}233}

234```234```

235 235 

236Pair it with a `WorktreeRemove` hook to clean up when the session ends. See the [hooks reference](/en/hooks#worktreecreate) for the input schema and a removal example.236Pair it with a `WorktreeRemove` hook to clean up when the session ends. See the [hooks reference](/docs/en/hooks#worktreecreate) for the input schema and a removal example.

237 237 

238## Troubleshooting238## Troubleshooting

239 239 


241 241 

242### Claude Code can't enter the worktree at startup242### Claude Code can't enter the worktree at startup

243 243 

244When Claude Code can't enter the worktree directory at startup, it prints an error naming the path and exits with code 1. This can happen when a [`WorktreeCreate` hook](/en/hooks#worktreecreate) prints something other than the directory it created, or when the directory was deleted after it was set up. Before v2.1.205, this crashed the session, and with `-p` it stalled for about 30 seconds before exiting with code 0.244When Claude Code can't enter the worktree directory at startup, it prints an error naming the path and exits with code 1. This can happen when a [`WorktreeCreate` hook](/docs/en/hooks#worktreecreate) prints something other than the directory it created, or when the directory was deleted after it was set up. Before v2.1.205, this crashed the session, and with `-p` it stalled for about 30 seconds before exiting with code 0.

245 245 

246### Worktree creation fails on a symlinked path246### Worktree creation fails on a symlinked path

247 247 


251 251 

252Worktrees handle file isolation. The related pages below cover delegating work into those isolated checkouts and switching between the sessions you create:252Worktrees handle file isolation. The related pages below cover delegating work into those isolated checkouts and switching between the sessions you create:

253 253 

254* [Subagents](/en/sub-agents): delegate work to isolated agents within a session254* [Subagents](/docs/en/sub-agents): delegate work to isolated agents within a session

255* [Agent teams](/en/agent-teams): coordinate multiple Claude sessions automatically255* [Agent teams](/docs/en/agent-teams): coordinate multiple Claude sessions automatically

256* [Manage sessions](/en/sessions): name, resume, and switch between conversations256* [Manage sessions](/docs/en/sessions): name, resume, and switch between conversations

257* [Desktop parallel sessions](/en/desktop#work-in-parallel-with-sessions): worktree-backed sessions in the desktop app257* [Desktop parallel sessions](/docs/en/desktop#work-in-parallel-with-sessions): worktree-backed sessions in the desktop app