SpyBara
Go Premium

Documentation 2026-05-04 22:58 UTC to 2026-05-05 23:00 UTC

51 files changed +431 −249. View all changes and history on the product overview
2026
Sun 31 06:39 Sat 30 06:23 Fri 29 06:38 Thu 28 06:37 Wed 27 06:42 Tue 26 06:33 Sun 24 06:25 Sat 23 06:18 Fri 22 06:33 Thu 21 06:36 Wed 20 06:35 Tue 19 06:34 Mon 18 23:59 Sun 17 01:01 Fri 15 22:58 Thu 14 17:02 Wed 13 23:01 Tue 12 22:57 Mon 11 23:00 Sun 10 23:03 Sat 9 04:57 Fri 8 22:00 Thu 7 22:59 Tue 5 23:00 Mon 4 22:58 Sat 2 18:14 Fri 1 18:19
Details

47 47 

48As the loop runs, the SDK yields a stream of messages. Each message carries a type that tells you what stage of the loop it came from. The five core types are:48As the loop runs, the SDK yields a stream of messages. Each message carries a type that tells you what stage of the loop it came from. The five core types are:

49 49 

50* **`SystemMessage`:** session lifecycle events. The `subtype` field distinguishes them: `"init"` is the first message (session metadata), and `"compact_boundary"` fires after [compaction](#automatic-compaction). In TypeScript, the compact boundary is its own [`SDKCompactBoundaryMessage`](/en/agent-sdk/typescript#sdk-compact-boundary-message) type rather than a subtype of `SDKSystemMessage`.50* **`SystemMessage`:** session lifecycle events. The `subtype` field distinguishes them: `"init"` is the first message (session metadata), and `"compact_boundary"` fires after [compaction](#automatic-compaction). In TypeScript, the compact boundary is its own [`SDKCompactBoundaryMessage`](/en/agent-sdk/typescript#sdkcompactboundarymessage) type rather than a subtype of `SDKSystemMessage`.

51* **`AssistantMessage`:** emitted after each Claude response, including the final text-only one. Contains text content blocks and tool call blocks from that turn.51* **`AssistantMessage`:** emitted after each Claude response, including the final text-only one. Contains text content blocks and tool call blocks from that turn.

52* **`UserMessage`:** emitted after each tool execution with the tool result content sent back to Claude. Also emitted for any user inputs you stream mid-loop.52* **`UserMessage`:** emitted after each tool execution with the tool result content sent back to Claude. Also emitted for any user inputs you stream mid-loop.

53* **`StreamEvent`:** only emitted when partial messages are enabled. Contains raw API streaming events (text deltas, tool input chunks). See [Stream responses](/en/agent-sdk/streaming-output).53* **`StreamEvent`:** only emitted when partial messages are enabled. Contains raw API streaming events (text deltas, tool input chunks). See [Stream responses](/en/agent-sdk/streaming-output).


141 141 

142When Claude requests multiple tool calls in a single turn, both SDKs can run them concurrently or sequentially depending on the tool. Read-only tools (like `Read`, `Glob`, `Grep`, and MCP tools marked as read-only) can run concurrently. Tools that modify state (like `Edit`, `Write`, and `Bash`) run sequentially to avoid conflicts.142When Claude requests multiple tool calls in a single turn, both SDKs can run them concurrently or sequentially depending on the tool. Read-only tools (like `Read`, `Glob`, `Grep`, and MCP tools marked as read-only) can run concurrently. Tools that modify state (like `Edit`, `Write`, and `Bash`) run sequentially to avoid conflicts.

143 143 

144Custom tools default to sequential execution. To enable parallel execution for a custom tool, mark it as read-only in its annotations: `readOnly` in [TypeScript](/en/agent-sdk/typescript#tool) or `readOnlyHint` in [Python](/en/agent-sdk/python#tool).144Custom tools default to sequential execution. To enable parallel execution for a custom tool, set `readOnlyHint` in its annotations. Both the [TypeScript](/en/agent-sdk/typescript#tool) and [Python](/en/agent-sdk/python#tool) SDKs use this field name from the MCP SDK.

145 145 

146## Control how the loop runs146## Control how the loop runs

147 147 

148You can limit how many turns the loop takes, how much it costs, how deeply Claude reasons, and whether tools require approval before running. All of these are fields on [`ClaudeAgentOptions`](/en/agent-sdk/python#claude-agent-options) (Python) / [`Options`](/en/agent-sdk/typescript#options) (TypeScript).148You can limit how many turns the loop takes, how much it costs, how deeply Claude reasons, and whether tools require approval before running. All of these are fields on [`ClaudeAgentOptions`](/en/agent-sdk/python#claudeagentoptions) (Python) / [`Options`](/en/agent-sdk/typescript#options) (TypeScript).

149 149 

150### Turns and budget150### Turns and budget

151 151 


154| Max turns (`max_turns` / `maxTurns`) | Maximum tool-use round trips | No limit |154| Max turns (`max_turns` / `maxTurns`) | Maximum tool-use round trips | No limit |

155| Max budget (`max_budget_usd` / `maxBudgetUsd`) | Maximum cost before stopping | No limit |155| Max budget (`max_budget_usd` / `maxBudgetUsd`) | Maximum cost before stopping | No limit |

156 156 

157When either limit is hit, the SDK returns a `ResultMessage` with a corresponding error subtype (`error_max_turns` or `error_max_budget_usd`). See [Handle the result](#handle-the-result) for how to check these subtypes and [`ClaudeAgentOptions`](/en/agent-sdk/python#claude-agent-options) / [`Options`](/en/agent-sdk/typescript#options) for syntax.157When either limit is hit, the SDK returns a `ResultMessage` with a corresponding error subtype (`error_max_turns` or `error_max_budget_usd`). See [Handle the result](#handle-the-result) for how to check these subtypes and [`ClaudeAgentOptions`](/en/agent-sdk/python#claudeagentoptions) / [`Options`](/en/agent-sdk/typescript#options) for syntax.

158 158 

159### Effort level159### Effort level

160 160 


174 `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.174 `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.

175</Note>175</Note>

176 176 

177Use lower effort for agents doing simple, well-scoped tasks (like listing files or running a single grep) to reduce cost and latency. `effort` is set at the top-level `query()` options, not per-subagent.177Use 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`](/en/agent-sdk/subagents#agentdefinition-configuration) to override the session level.

178 178 

179### Permission mode179### Permission mode

180 180 


184| :------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |184| :------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

185| `"default"` | Tools not covered by allow rules trigger your approval callback; no callback means deny |185| `"default"` | Tools not covered by allow rules trigger your approval callback; no callback means deny |

186| `"acceptEdits"` | Auto-approves file edits and common filesystem commands (`mkdir`, `touch`, `mv`, `cp`, etc.); other Bash commands follow default rules |186| `"acceptEdits"` | Auto-approves file edits and common filesystem commands (`mkdir`, `touch`, `mv`, `cp`, etc.); other Bash commands follow default rules |

187| `"plan"` | No tool execution; Claude produces a plan for review |187| `"plan"` | Read-only tools run; Claude explores and produces a plan without editing your source files |

188| `"dontAsk"` | Never prompts. Tools pre-approved by [permission rules](/en/settings#permission-settings) run, everything else is denied |188| `"dontAsk"` | Never prompts. Tools pre-approved by [permission rules](/en/settings#permission-settings) run, everything else is denied |

189| `"auto"` (TypeScript only) | Uses a model classifier to approve or deny each tool call. See [Auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) for availability and behavior |189| `"auto"` (TypeScript only) | Uses a model classifier to approve or deny each tool call. See [Auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) for availability and behavior |

190| `"bypassPermissions"` | Runs all allowed tools without asking. Cannot be used when running as root on Unix. Use only in isolated environments where the agent's actions cannot affect systems you care about |190| `"bypassPermissions"` | Runs all allowed tools without asking. Cannot be used when running as root on Unix. Use only in isolated environments where the agent's actions cannot affect systems you care about |


244A few strategies for long-running agents:244A few strategies for long-running agents:

245 245 

246* **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](/en/agent-sdk/subagents#what-subagents-inherit) for details.246* **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](/en/agent-sdk/subagents#what-subagents-inherit) for details.

247* **Be selective with tools.** Every tool definition takes context space. Use the `tools` field on [`AgentDefinition`](/en/agent-sdk/subagents#agent-definition-configuration) to scope subagents to the minimum set they need, and use [MCP tool search](/en/agent-sdk/mcp#mcp-tool-search) to load tools on demand instead of preloading all of them.247* **Be selective with tools.** Every tool definition takes context space. Use the `tools` field on [`AgentDefinition`](/en/agent-sdk/subagents#agentdefinition-configuration) to scope subagents to the minimum set they need, and use [MCP tool search](/en/agent-sdk/mcp#mcp-tool-search) to load tools on demand instead of preloading all of them.

248* **Watch MCP server costs.** Each MCP server adds all its tool schemas to every request. A few servers with many tools can consume significant context before the agent does any work. The `ToolSearch` tool can help by loading tools on-demand instead of preloading all of them. See [MCP tool search](/en/agent-sdk/mcp#mcp-tool-search) for configuration.248* **Watch MCP server costs.** Each MCP server adds all its tool schemas to every request. A few servers with many tools can consume significant context before the agent does any work. The `ToolSearch` tool can help by loading tools on-demand instead of preloading all of them. See [MCP tool search](/en/agent-sdk/mcp#mcp-tool-search) for configuration.

249* **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.249* **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.

250 250 


259See [Session management](/en/agent-sdk/sessions) for the full guide on resume, continue, and fork patterns.259See [Session management](/en/agent-sdk/sessions) for the full guide on resume, continue, and fork patterns.

260 260 

261<Note>261<Note>

262 In Python, `ClaudeSDKClient` handles session IDs automatically across multiple calls. See the [Python SDK reference](/en/agent-sdk/python#choosing-between-query-and-claude-sdk-client) for details.262 In Python, `ClaudeSDKClient` handles session IDs automatically across multiple calls. See the [Python SDK reference](/en/agent-sdk/python#choosing-between-query-and-claudesdkclient) for details.

263</Note>263</Note>

264 264 

265## Handle the result265## Handle the result


276 276 

277The `result` field (the final text output) is only present on the `success` variant, so always check the subtype before reading it. All result subtypes carry `total_cost_usd`, `usage`, `num_turns`, and `session_id` so you can track cost and resume even after errors. In Python, `total_cost_usd` and `usage` are typed as optional and may be `None` on some error paths, so guard before formatting them. See [Tracking costs and usage](/en/agent-sdk/cost-tracking) for details on interpreting the `usage` fields.277The `result` field (the final text output) is only present on the `success` variant, so always check the subtype before reading it. All result subtypes carry `total_cost_usd`, `usage`, `num_turns`, and `session_id` so you can track cost and resume even after errors. In Python, `total_cost_usd` and `usage` are typed as optional and may be `None` on some error paths, so guard before formatting them. See [Tracking costs and usage](/en/agent-sdk/cost-tracking) for details on interpreting the `usage` fields.

278 278 

279The result also includes a `stop_reason` field (`string | null` in TypeScript, `str | None` in Python) indicating why the model stopped generating on its final turn. Common values are `end_turn` (model finished normally), `max_tokens` (hit the output token limit), and `refusal` (the model declined the request). On error result subtypes, `stop_reason` carries the value from the last assistant response before the loop ended. To detect refusals, check `stop_reason === "refusal"` (TypeScript) or `stop_reason == "refusal"` (Python). See [`SDKResultMessage`](/en/agent-sdk/typescript#sdk-result-message) (TypeScript) or [`ResultMessage`](/en/agent-sdk/python#result-message) (Python) for the full type.279The result also includes a `stop_reason` field (`string | null` in TypeScript, `str | None` in Python) indicating why the model stopped generating on its final turn. Common values are `end_turn` (model finished normally), `max_tokens` (hit the output token limit), and `refusal` (the model declined the request). On error result subtypes, `stop_reason` carries the value from the last assistant response before the loop ended. To detect refusals, check `stop_reason === "refusal"` (TypeScript) or `stop_reason == "refusal"` (Python). See [`SDKResultMessage`](/en/agent-sdk/typescript#sdkresultmessage) (TypeScript) or [`ResultMessage`](/en/agent-sdk/python#resultmessage) (Python) for the full type.

280 280 

281## Hooks281## Hooks

282 282 

Details

14 14 

15## Control filesystem settings with settingSources15## Control filesystem settings with settingSources

16 16 

17The setting sources option ([`setting_sources`](/en/agent-sdk/python#claude-agent-options) in Python, [`settingSources`](/en/agent-sdk/typescript#setting-source) in TypeScript) controls which filesystem-based settings the SDK loads. Pass an explicit list to opt in to specific sources, or pass an empty array to disable user, project, and local settings.17The setting sources option ([`setting_sources`](/en/agent-sdk/python#claudeagentoptions) in Python, [`settingSources`](/en/agent-sdk/typescript#settingsource) in TypeScript) controls which filesystem-based settings the SDK loads. Pass an explicit list to opt in to specific sources, or pass an empty array to disable user, project, and local settings.

18 18 

19This example loads both user-level and project-level settings by setting `settingSources` to `["user", "project"]`:19This example loads both user-level and project-level settings by setting `settingSources` to `["user", "project"]`:

20 20 


65 ```65 ```

66</CodeGroup>66</CodeGroup>

67 67 

68Each source loads settings from a specific location, where `<cwd>` is the working directory you pass via the `cwd` option (or the process's current directory if unset). For the full type definition, see [`SettingSource`](/en/agent-sdk/typescript#setting-source) (TypeScript) or [`SettingSource`](/en/agent-sdk/python#setting-source) (Python).68Each source loads settings from a specific location, where `<cwd>` is the working directory you pass via the `cwd` option, or the process's current directory if unset. For the full type definition, see [`SettingSource`](/en/agent-sdk/typescript#settingsource) (TypeScript) or [`SettingSource`](/en/agent-sdk/python#settingsource) (Python).

69 69 

70| Source | What it loads | Location |70| Source | What it loads | Location |

71| :---------- | :---------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------- |71| :---------- | :---------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------- |

Details

31 31 

32Cost tracking depends on understanding how the SDK scopes usage data:32Cost tracking depends on understanding how the SDK scopes usage data:

33 33 

34* **`query()` call:** one invocation of the SDK's `query()` function. A single call can involve multiple steps (Claude responds, uses tools, gets results, responds again). Each call produces one [`result`](/en/agent-sdk/typescript#sdk-result-message) message at the end.34* **`query()` call:** one invocation of the SDK's `query()` function. A single call can involve multiple steps (Claude responds, uses tools, gets results, responds again). Each call produces one [`result`](/en/agent-sdk/typescript#sdkresultmessage) message at the end.

35* **Step:** a single request/response cycle within a `query()` call. Each step produces assistant messages with token usage.35* **Step:** a single request/response cycle within a `query()` call. Each step produces assistant messages with token usage.

36* **Session:** a series of `query()` calls linked by a session ID (using the `resume` option). Each `query()` call within a session reports its own cost independently.36* **Session:** a series of `query()` calls linked by a session ID (using the `resume` option). Each `query()` call within a session reports its own cost independently.

37 37 


45 </Step>45 </Step>

46 46 

47 <Step title="The result message provides the cumulative estimate">47 <Step title="The result message provides the cumulative estimate">

48 When the `query()` call completes, the SDK emits a result message with `total_cost_usd` and cumulative `usage`. This is available in both TypeScript ([`SDKResultMessage`](/en/agent-sdk/typescript#sdk-result-message)) and Python ([`ResultMessage`](/en/agent-sdk/python#result-message)). If you make multiple `query()` calls (for example, in a multi-turn session), each result only reflects the cost of that individual call. If you only need the estimated total, you can ignore the per-step usage and read this single value.48 When the `query()` call completes, the SDK emits a result message with `total_cost_usd` and cumulative `usage`. This is available in both TypeScript ([`SDKResultMessage`](/en/agent-sdk/typescript#sdkresultmessage)) and Python ([`ResultMessage`](/en/agent-sdk/python#resultmessage)). If you make multiple `query()` calls (for example, in a multi-turn session), each result only reflects the cost of that individual call. If you only need the estimated total, you can ignore the per-step usage and read this single value.

49 </Step>49 </Step>

50</Steps>50</Steps>

51 51 

52## Get the total cost of a query52## Get the total cost of a query

53 53 

54The result message ([TypeScript](/en/agent-sdk/typescript#sdk-result-message), [Python](/en/agent-sdk/python#result-message)) marks the end of the agent loop for a `query()` call. It includes `total_cost_usd`, the cumulative estimated cost across all steps in that call. This works for both success and error results. If you use sessions to make multiple `query()` calls, each result only reflects the cost of that individual call.54The result message ([TypeScript](/en/agent-sdk/typescript#sdkresultmessage), [Python](/en/agent-sdk/python#resultmessage)) marks the end of the agent loop for a `query()` call. It includes `total_cost_usd`, the cumulative estimated cost across all steps in that call. This works for both success and error results. If you use sessions to make multiple `query()` calls, each result only reflects the cost of that individual call.

55 55 

56The following examples iterate over the message stream from a `query()` call and print the total cost when the `result` message arrives:56The following examples iterate over the message stream from a `query()` call and print the total cost when the `result` message arrives:

57 57 


83 83 

84## Track per-step and per-model usage84## Track per-step and per-model usage

85 85 

86The examples in this section use TypeScript field names. In Python, the equivalent fields are [`AssistantMessage.usage`](/en/agent-sdk/python#assistant-message) and `AssistantMessage.message_id` for per-step usage, and [`ResultMessage.model_usage`](/en/agent-sdk/python#result-message) for per-model breakdowns.86The examples in this section use TypeScript field names. In Python, the equivalent fields are [`AssistantMessage.usage`](/en/agent-sdk/python#assistantmessage) and `AssistantMessage.message_id` for per-step usage, and [`ResultMessage.model_usage`](/en/agent-sdk/python#resultmessage) for per-model breakdowns.

87 87 

88### Track per-step usage88### Track per-step usage

89 89 


122 122 

123### Break down usage per model123### Break down usage per model

124 124 

125The result message includes [`modelUsage`](/en/agent-sdk/typescript#model-usage), a map of model name to per-model token counts and cost. This is useful when you run multiple models (for example, Haiku for subagents and Opus for the main agent) and want to see where tokens are going.125The result message includes [`modelUsage`](/en/agent-sdk/typescript#modelusage), a map of model name to per-model token counts and cost. This is useful when you run multiple models (for example, Haiku for subagents and Opus for the main agent) and want to see where tokens are going.

126 126 

127The following example runs a query and prints the cost and token breakdown for each model used:127The following example runs a query and prints the cost and token breakdown for each model used:

128 128 


223* `cache_creation_input_tokens`: tokens used to create new cache entries (charged at a higher rate than standard input tokens).223* `cache_creation_input_tokens`: tokens used to create new cache entries (charged at a higher rate than standard input tokens).

224* `cache_read_input_tokens`: tokens read from existing cache entries (charged at a reduced rate).224* `cache_read_input_tokens`: tokens read from existing cache entries (charged at a reduced rate).

225 225 

226Track these separately from `input_tokens` to understand caching savings. In TypeScript, these fields are typed on the [`Usage`](/en/agent-sdk/typescript#usage) object. In Python, they appear as keys in the [`ResultMessage.usage`](/en/agent-sdk/python#result-message) dict (for example, `message.usage.get("cache_read_input_tokens", 0)`).226Track these separately from `input_tokens` to understand caching savings. In TypeScript, these fields are typed on the [`Usage`](/en/agent-sdk/typescript#usage) object. In Python, they appear as keys in the [`ResultMessage.usage`](/en/agent-sdk/python#resultmessage) dict (for example, `message.usage.get("cache_read_input_tokens", 0)`).

227 227 

228### Extend the prompt cache TTL to one hour228### Extend the prompt cache TTL to one hour

229 229 

Details

34 * `content` (required): an array of result blocks, each with a `type` of `"text"`, `"image"`, or `"resource"`. See [Return images and resources](#return-images-and-resources) for non-text blocks.34 * `content` (required): an array of result blocks, each with a `type` of `"text"`, `"image"`, or `"resource"`. See [Return images and resources](#return-images-and-resources) for non-text blocks.

35 * `isError` (optional): set to `true` to signal a tool failure so Claude can react to it. See [Handle errors](#handle-errors).35 * `isError` (optional): set to `true` to signal a tool failure so Claude can react to it. See [Handle errors](#handle-errors).

36 36 

37After defining a tool, wrap it in a server with [`createSdkMcpServer`](/en/agent-sdk/typescript#create-sdk-mcp-server) (TypeScript) or [`create_sdk_mcp_server`](/en/agent-sdk/python#create-sdk-mcp-server) (Python). The server runs in-process inside your application, not as a separate process.37After defining a tool, wrap it in a server with [`createSdkMcpServer`](/en/agent-sdk/typescript#createsdkmcpserver) (TypeScript) or [`create_sdk_mcp_server`](/en/agent-sdk/python#create_sdk_mcp_server) (Python). The server runs in-process inside your application, not as a separate process.

38 38 

39### Weather tool example39### Weather tool example

40 40 


306 ```306 ```

307</CodeGroup>307</CodeGroup>

308 308 

309See `ToolAnnotations` in the [TypeScript](/en/agent-sdk/typescript#tool-annotations) or [Python](/en/agent-sdk/python#tool-annotations) reference.309See `ToolAnnotations` in the [TypeScript](/en/agent-sdk/typescript#toolannotations) or [Python](/en/agent-sdk/python#toolannotations) reference.

310 310 

311## Control tool access311## Control tool access

312 312 

agent-sdk/hooks.md +16 −16

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#setting-source) or [`setting_sources`](/en/agent-sdk/python#setting-source) 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`](/en/agent-sdk/typescript#settingsource) or [`setting_sources`](/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">


225 225 

226Every hook callback receives three arguments:226Every hook callback receives three arguments:

227 227 

228* **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#hook-input) and [Python](/en/agent-sdk/python#hook-input) SDK references.228* **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.

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

230 * `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 on `PreToolUse`, `PostToolUse`, and `PostToolUseFailure` only.230 * `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 on `PreToolUse`, `PostToolUse`, and `PostToolUseFailure` only.

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


238* **Top-level fields** control the conversation: `systemMessage` injects a message into the conversation visible to the model, and `continue` (`continue_` in Python) determines whether the agent keeps running after this hook.238* **Top-level fields** control the conversation: `systemMessage` injects a message into the conversation visible to the model, and `continue` (`continue_` in Python) determines whether the agent keeps running after this hook.

239* **`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"`, or `"ask"`), `permissionDecisionReason`, and `updatedInput`. In the TypeScript SDK, `permissionDecision` also accepts `"defer"` to end the query and [resume later](/en/hooks#defer-a-tool-call-for-later); this value is not available in the Python SDK. For `PostToolUse` hooks, you can set `additionalContext` to append information to the tool result, or `updatedToolOutput` to replace the tool's output entirely before Claude sees it.239* **`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"`, or `"ask"`), `permissionDecisionReason`, and `updatedInput`. In the TypeScript SDK, `permissionDecision` also accepts `"defer"` to end the query and [resume later](/en/hooks#defer-a-tool-call-for-later); this value is not available in the Python SDK. For `PostToolUse` hooks, you can set `additionalContext` to append information to the tool result, or `updatedToolOutput` to replace the tool's output entirely before Claude sees it.

240 240 

241Return `{}` 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#sync-hook-json-output) and [Python](/en/agent-sdk/python#sync-hook-json-output) SDK references.241Return `{}` 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.

242 242 

243<Note>243<Note>

244 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.244 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.


417 ```417 ```

418</CodeGroup>418</CodeGroup>

419 419 

420### Chain multiple hooks420### Register multiple hooks

421 421 

422Hooks execute in the order they appear in the array. Keep each hook focused on a single responsibility and chain multiple hooks for complex logic:422When an event fires, all matching hooks run in parallel. For permission decisions, the most restrictive result wins: a single `deny` blocks the tool call regardless of what the other hooks return. Because completion order is non-deterministic, write each hook to act independently rather than relying on another hook having run first.

423 

424The example below registers three independent checks for every tool call:

423 425 

424<CodeGroup>426<CodeGroup>

425 ```python Python theme={null}427 ```python Python theme={null}

426 options = ClaudeAgentOptions(428 options = ClaudeAgentOptions(

427 hooks={429 hooks={

428 "PreToolUse": [430 "PreToolUse": [

429 HookMatcher(hooks=[rate_limiter]), # First: check rate limits431 HookMatcher(hooks=[authorization_check]),

430 HookMatcher(hooks=[authorization_check]), # Second: verify permissions432 HookMatcher(hooks=[input_validator]),

431 HookMatcher(hooks=[input_sanitizer]), # Third: sanitize inputs433 HookMatcher(hooks=[audit_logger]),

432 HookMatcher(hooks=[audit_logger]), # Last: log the action

433 ]434 ]

434 }435 }

435 )436 )


439 const options = {440 const options = {

440 hooks: {441 hooks: {

441 PreToolUse: [442 PreToolUse: [

442 { hooks: [rateLimiter] }, // First: check rate limits443 { hooks: [authorizationCheck] },

443 { hooks: [authorizationCheck] }, // Second: verify permissions444 { hooks: [inputValidator] },

444 { hooks: [inputSanitizer] }, // Third: sanitize inputs445 { hooks: [auditLogger] }

445 { hooks: [auditLogger] } // Last: log the action

446 ]446 ]

447 }447 }

448 };448 };


489 489 

490### Track subagent activity490### Track subagent activity

491 491 

492Use `SubagentStop` hooks to monitor when subagents finish their work. See the full input type in the [TypeScript](/en/agent-sdk/typescript#hook-input) and [Python](/en/agent-sdk/python#hook-input) SDK references. This example logs a summary each time a subagent completes:492Use `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:

493 493 

494<CodeGroup>494<CodeGroup>

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


727* Check that your matcher pattern matches the tool name exactly727* Check that your matcher pattern matches the tool name exactly

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

729* For non-tool hooks like `Stop` and `SubagentStop`, matchers match against different fields (see [matcher patterns](/en/hooks#matcher-patterns))729* For non-tool hooks like `Stop` and `SubagentStop`, matchers match against different fields (see [matcher patterns](/en/hooks#matcher-patterns))

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

731 731 

732### Matcher not filtering as expected732### Matcher not filtering as expected

733 733 


775 775 

776### Session hooks not available in Python776### Session hooks not available in Python

777 777 

778`SessionStart` and `SessionEnd` can be registered as SDK callback hooks in TypeScript, but are not available in the Python SDK (`HookEvent` omits them). In Python, they are only available as [shell command hooks](/en/hooks#hook-events) defined in settings files (for example, `.claude/settings.json`). To load shell command hooks from your SDK application, include the appropriate setting source with [`setting_sources`](/en/agent-sdk/python#setting-source) or [`settingSources`](/en/agent-sdk/typescript#setting-source):778`SessionStart` and `SessionEnd` can be registered as SDK callback hooks in TypeScript, but are not available in the Python SDK (`HookEvent` omits them). In Python, they are only available as [shell command hooks](/en/hooks#hook-events) defined in settings files (for example, `.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):

779 779 

780<CodeGroup>780<CodeGroup>

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

Details

18 18 

19For security and isolation, the SDK should run inside a sandboxed container environment. This provides process isolation, resource limits, network control, and ephemeral filesystems.19For security and isolation, the SDK should run inside a sandboxed container environment. This provides process isolation, resource limits, network control, and ephemeral filesystems.

20 20 

21The SDK also supports [programmatic sandbox configuration](/en/agent-sdk/typescript#sandbox-settings) for command execution.21The SDK also supports [programmatic sandbox configuration](/en/agent-sdk/typescript#sandboxsettings) for command execution.

22 22 

23### System Requirements23### System Requirements

24 24 


135## Next Steps135## Next Steps

136 136 

137* [Secure Deployment](/en/agent-sdk/secure-deployment) - Network controls, credential management, and isolation hardening137* [Secure Deployment](/en/agent-sdk/secure-deployment) - Network controls, credential management, and isolation hardening

138* [TypeScript SDK - Sandbox Settings](/en/agent-sdk/typescript#sandbox-settings) - Configure sandbox programmatically138* [TypeScript SDK - Sandbox Settings](/en/agent-sdk/typescript#sandboxsettings) - Configure sandbox programmatically

139* [Sessions Guide](/en/agent-sdk/sessions) - Learn about session management139* [Sessions Guide](/en/agent-sdk/sessions) - Learn about session management

140* [Permissions](/en/agent-sdk/permissions) - Configure tool permissions140* [Permissions](/en/agent-sdk/permissions) - Configure tool permissions

141* [Cost Tracking](/en/agent-sdk/cost-tracking) - Monitor API usage141* [Cost Tracking](/en/agent-sdk/cost-tracking) - Monitor API usage

Details

205 205 

206**Why this changed:** Provides better control and isolation for SDK applications. You can now build agents with custom behavior without inheriting Claude Code's CLI-focused instructions.206**Why this changed:** Provides better control and isolation for SDK applications. You can now build agents with custom behavior without inheriting Claude Code's CLI-focused instructions.

207 207 

208### Settings Sources No Longer Loaded by Default208### Settings sources default

209 209 

210**What changed:** The SDK no longer reads from filesystem settings (CLAUDE.md, settings.json, slash commands, etc.) by default.210This default was briefly changed in v0.1.0 and then reverted, so no migration action is needed.

211 211 

212**Migration:**212**Current behavior:** Omitting `settingSources` on `query()` loads user, project, and local filesystem settings, matching the CLI. This includes `~/.claude/settings.json`, `.claude/settings.json`, `.claude/settings.local.json`, CLAUDE.md files, and custom commands.

213 

214To run isolated from filesystem settings, pass an empty array:

213 215 

214<CodeGroup>216<CodeGroup>

215 ```typescript TypeScript theme={null}217 ```typescript TypeScript theme={null}

216 // BEFORE (v0.0.x) - Loaded all settings automatically

217 const result = query({ prompt: "Hello" });

218 // Would read from:

219 // - ~/.claude/settings.json (user)

220 // - .claude/settings.json (project)

221 // - .claude/settings.local.json (local)

222 // - CLAUDE.md files

223 // - Custom slash commands

224 

225 // AFTER (v0.1.0) - No settings loaded by default

226 // To get the old behavior:

227 const result = query({218 const result = query({

228 prompt: "Hello",219 prompt: "Hello",

229 options: {220 options: {

230 settingSources: ["user", "project", "local"]221 settingSources: [] // No filesystem settings loaded

231 }222 }

232 });223 });

233 224 


241 ```232 ```

242 233 

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

244 # BEFORE (v0.0.x) - Loaded all settings automatically

245 async for message in query(prompt="Hello"):

246 print(message)

247 # Would read from:

248 # - ~/.claude/settings.json (user)

249 # - .claude/settings.json (project)

250 # - .claude/settings.local.json (local)

251 # - CLAUDE.md files

252 # - Custom slash commands

253 

254 # AFTER (v0.1.0) - No settings loaded by default

255 # To get the old behavior:

256 from claude_agent_sdk import query, ClaudeAgentOptions235 from claude_agent_sdk import query, ClaudeAgentOptions

257 236 

258 async for message in query(237 async for message in query(

259 prompt="Hello",238 prompt="Hello",

260 options=ClaudeAgentOptions(setting_sources=["user", "project", "local"]),239 options=ClaudeAgentOptions(setting_sources=[]), # No filesystem settings loaded

261 ):240 ):

262 print(message)241 print(message)

263 242 


272 ```251 ```

273</CodeGroup>252</CodeGroup>

274 253 

275**Why this changed:** Ensures SDK applications have predictable behavior independent of local filesystem configurations. This is especially important for:254Isolation is especially important for CI/CD pipelines, deployed applications, test environments, and multi-tenant systems where local customizations should not leak in.

276 255 

277* **CI/CD environments** - Consistent behavior without local customizations256<Note>

278* **Deployed applications** - No dependency on filesystem settings257 SDK v0.1.0 briefly defaulted to no settings loaded; this was reverted in subsequent releases. Python SDK 0.1.59 and earlier treated an empty list the same as omitting the option, so upgrade before relying on `setting_sources=[]`. See [What settingSources does not control](/en/agent-sdk/claude-code-features#what-settingsources-does-not-control) for inputs that are read even when `settingSources` is `[]`.

279* **Testing** - Isolated test environments258</Note>

280* **Multi-tenant systems** - Prevent settings leakage between users

281 

282<Warning>

283 Current SDK releases have reverted this default for `query()`: omitting the option once again loads user, project, and local settings, matching the CLI. Pass `settingSources: []` in TypeScript or `setting_sources=[]` in Python if your application depends on the isolated behavior described above. Python SDK 0.1.59 and earlier treated an empty list the same as omitting the option, so upgrade before relying on `setting_sources=[]`. See [What settingSources does not control](/en/agent-sdk/claude-code-features#what-settingsources-does-not-control) for inputs that are read even when `settingSources` is `[]`.

284</Warning>

285 259 

286## Why the Rename?260## Why the Rename?

287 261 

Details

194 ```194 ```

195</CodeGroup>195</CodeGroup>

196 196 

197## Attribute actions to your end users

198 

199The CLI attaches [identity attributes](/en/monitoring-usage#standard-attributes) to every event based on the credential it uses to call Anthropic. When you build an application that serves many end users from one deployment, these attributes identify your service's credential, not the end user on whose behalf the agent acted.

200 

201To make tool calls and MCP activity attributable to your application's end users, inject end-user identity as resource attributes on each `query()` call. Percent-encode values before interpolating them, since `OTEL_RESOURCE_ATTRIBUTES` [reserves commas, spaces, and equals signs](/en/monitoring-usage#multi-team-organization-support). The following example attaches the requesting user and tenant to every span and event from one request:

202 

203<CodeGroup>

204 ```python Python theme={null}

205 from urllib.parse import quote

206 

207 options = ClaudeAgentOptions(

208 env={

209 # ... exporter configuration ...

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

211 },

212 )

213 ```

214 

215 ```typescript TypeScript theme={null}

216 const options = {

217 env: {

218 ...process.env,

219 // ... exporter configuration ...

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

221 },

222 };

223 ```

224</CodeGroup>

225 

226With end-user identity attached, the `tool_decision`, `tool_result`, `mcp_server_connection`, and `permission_mode_changed` events become a per-user audit trail you can forward to a Security Information and Event Management (SIEM) platform. See [Audit security events](/en/monitoring-usage#audit-security-events) in the Monitoring reference for the full list of security-relevant events and the attributes each one carries.

227 

197## Control sensitive data in exports228## Control sensitive data in exports

198 229 

199Telemetry is structural by default. Durations, model names, and tool names are recorded on every span; token counts are recorded when the underlying API request returns usage data, so spans for failed or aborted requests may omit them. The content your agent reads and writes is not recorded by default. These opt-in variables add content to the exported data:230Telemetry is structural by default. Durations, model names, and tool names are recorded on every span; token counts are recorded when the underlying API request returns usage data, so spans for failed or aborted requests may omit them. The content your agent reads and writes is not recorded by default. These opt-in variables add content to the exported data:

Details

18 18 

19<Steps>19<Steps>

20 <Step title="Hooks">20 <Step title="Hooks">

21 Run [hooks](/en/agent-sdk/hooks) first, which can allow, deny, or continue to the next step21 Run [hooks](/en/agent-sdk/hooks) first. A hook can deny the call outright or pass it on. A hook that returns `allow` does not skip the deny and ask rules below; those are evaluated regardless of the hook result.

22 </Step>22 </Step>

23 23 

24 <Step title="Deny rules">24 <Step title="Deny rules">


38 </Step>38 </Step>

39</Steps>39</Steps>

40 40 

41<img src="https://mintcdn.com/claude-code/gvy2DIUELtNA8qD3/images/agent-sdk/permissions-flow.svg?fit=max&auto=format&n=gvy2DIUELtNA8qD3&q=85&s=0ccd63043a9ffc2a34d863602e043f72" alt="Permission evaluation flow diagram" width="920" height="260" data-path="images/agent-sdk/permissions-flow.svg" />41<img src="https://mintcdn.com/claude-code/FEspvVUyRuaWjm0s/images/agent-sdk/permissions-flow.svg?fit=max&auto=format&n=FEspvVUyRuaWjm0s&q=85&s=a1759b0cf4541281a9fdd8f5348228e8" alt="Permission evaluation flow diagram" width="920" height="260" data-path="images/agent-sdk/permissions-flow.svg" />

42 42 

43This page focuses on **allow and deny rules** and **permission modes**. For the other steps:43This page focuses on **allow and deny rules** and **permission modes**. For the other steps:

44 44 


83| `dontAsk` | Deny instead of prompting | Anything not pre-approved by `allowed_tools` or rules is denied; `canUseTool` is never called |83| `dontAsk` | Deny instead of prompting | Anything not pre-approved by `allowed_tools` or rules is denied; `canUseTool` is never called |

84| `acceptEdits` | Auto-accept file edits | File edits and [filesystem operations](#accept-edits-mode-acceptedits) (`mkdir`, `rm`, `mv`, etc.) are automatically approved |84| `acceptEdits` | Auto-accept file edits | File edits and [filesystem operations](#accept-edits-mode-acceptedits) (`mkdir`, `rm`, `mv`, etc.) are automatically approved |

85| `bypassPermissions` | Bypass all permission checks | All tools run without permission prompts (use with caution) |85| `bypassPermissions` | Bypass all permission checks | All tools run without permission prompts (use with caution) |

86| `plan` | Planning mode | No tool execution; Claude plans without making changes |86| `plan` | Planning mode | Read-only tools run; Claude analyzes and plans without editing your source files |

87| `auto` (TypeScript only) | Model-classified approvals | A model classifier approves or denies each tool call. See [Auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) for availability |87| `auto` (TypeScript only) | Model-classified approvals | A model classifier approves or denies each tool call. See [Auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) for availability |

88 88 

89<Warning>89<Warning>


145 <CodeGroup>145 <CodeGroup>

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

147 import asyncio147 import asyncio

148 from claude_agent_sdk import query, ClaudeAgentOptions148 from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions

149 149 

150 150 

151 async def main():151 async def main():

152 q = query(152 async with ClaudeSDKClient(

153 prompt="Help me refactor this code",

154 options=ClaudeAgentOptions(153 options=ClaudeAgentOptions(

155 permission_mode="default", # Start in default mode154 permission_mode="default", # Start in default mode

156 ),

157 )155 )

156 ) as client:

157 await client.query("Help me refactor this code")

158 158 

159 # Change mode dynamically mid-session159 # Change mode dynamically mid-session

160 await q.set_permission_mode("acceptEdits")160 await client.set_permission_mode("acceptEdits")

161 161 

162 # Process messages with the new permission mode162 # Process messages with the new permission mode

163 async for message in q:163 async for message in client.receive_response():

164 if hasattr(message, "result"):164 if hasattr(message, "result"):

165 print(message.result)165 print(message.result)

166 166 


229 229 

230#### Plan mode (`plan`)230#### Plan mode (`plan`)

231 231 

232Prevents tool execution entirely. Claude can analyze code and create plans but cannot make changes. Claude may use `AskUserQuestion` to clarify requirements before finalizing the plan. See [Handle approvals and user input](/en/agent-sdk/user-input#handle-clarifying-questions) for handling these prompts.232Restricts Claude to read-only tools. Claude can read files and run read-only shell commands to explore the codebase but does not edit your source files. Claude may use `AskUserQuestion` to clarify requirements before finalizing the plan. See [Handle approvals and user input](/en/agent-sdk/user-input#handle-clarifying-questions) for handling these prompts.

233 233 

234**Use when:** you want Claude to propose changes without executing them, such as during code review or when you need to approve changes before they're made.234**Use when:** you want Claude to propose changes without executing them, such as during code review or when you need to approve changes before they're made.

235 235 

Details

113#### Parameters113#### Parameters

114 114 

115| Parameter | Type | Description |115| Parameter | Type | Description |

116| :------------- | :----------------------------------------------- | :------------------------------------------------------------------ |116| :------------- | :---------------------------------------------- | :------------------------------------------------------------------ |

117| `name` | `str` | Unique identifier for the tool |117| `name` | `str` | Unique identifier for the tool |

118| `description` | `str` | Human-readable description of what the tool does |118| `description` | `str` | Human-readable description of what the tool does |

119| `input_schema` | `type \| dict[str, Any]` | Schema defining the tool's input parameters (see below) |119| `input_schema` | `type \| dict[str, Any]` | Schema defining the tool's input parameters (see below) |

120| `annotations` | [`ToolAnnotations`](#tool-annotations)` \| None` | Optional MCP tool annotations providing behavioral hints to clients |120| `annotations` | [`ToolAnnotations`](#toolannotations)` \| None` | Optional MCP tool annotations providing behavioral hints to clients |

121 121 

122#### Input schema options122#### Input schema options

123 123 


267| `first_prompt` | `str \| None` | First meaningful user prompt in the session |267| `first_prompt` | `str \| None` | First meaningful user prompt in the session |

268| `git_branch` | `str \| None` | Git branch at the end of the session |268| `git_branch` | `str \| None` | Git branch at the end of the session |

269| `cwd` | `str \| None` | Working directory for the session |269| `cwd` | `str \| None` | Working directory for the session |

270| `tag` | `str \| None` | User-set session tag (see [`tag_session()`](#tag-session)) |270| `tag` | `str \| None` | User-set session tag (see [`tag_session()`](#tag_session)) |

271| `created_at` | `int \| None` | Session creation time in milliseconds since epoch |271| `created_at` | `int \| None` | Session creation time in milliseconds since epoch |

272 272 

273#### Example273#### Example


343| `session_id` | `str` | required | UUID of the session to look up |343| `session_id` | `str` | required | UUID of the session to look up |

344| `directory` | `str \| None` | `None` | Project directory path. When omitted, searches all project directories |344| `directory` | `str \| None` | `None` | Project directory path. When omitted, searches all project directories |

345 345 

346Returns [`SDKSessionInfo`](#return-type-sdk-session-info), or `None` if the session is not found.346Returns [`SDKSessionInfo`](#return-type-sdksessioninfo), or `None` if the session is not found.

347 347 

348#### Example348#### Example

349 349 


381 381 

382#### Example382#### Example

383 383 

384Rename the most recent session so it's easier to find later. The new title appears in [`SDKSessionInfo.custom_title`](#return-type-sdk-session-info) on subsequent reads.384Rename the most recent session so it's easier to find later. The new title appears in [`SDKSessionInfo.custom_title`](#return-type-sdksessioninfo) on subsequent reads.

385 385 

386```python theme={null}386```python theme={null}

387from claude_agent_sdk import list_sessions, rename_session387from claude_agent_sdk import list_sessions, rename_session


476| `set_permission_mode(mode)` | Change the permission mode for the current session |476| `set_permission_mode(mode)` | Change the permission mode for the current session |

477| `set_model(model)` | Change the model for the current session. Pass `None` to reset to default |477| `set_model(model)` | Change the model for the current session. Pass `None` to reset to default |

478| `rewind_files(user_message_id)` | Restore files to their state at the specified user message. Requires `enable_file_checkpointing=True`. See [File checkpointing](/en/agent-sdk/file-checkpointing) |478| `rewind_files(user_message_id)` | Restore files to their state at the specified user message. Requires `enable_file_checkpointing=True`. See [File checkpointing](/en/agent-sdk/file-checkpointing) |

479| `get_mcp_status()` | Get the status of all configured MCP servers. Returns [`McpStatusResponse`](#mcp-status-response) |479| `get_mcp_status()` | Get the status of all configured MCP servers. Returns [`McpStatusResponse`](#mcpstatusresponse) |

480| `reconnect_mcp_server(server_name)` | Retry connecting to an MCP server that failed or was disconnected |480| `reconnect_mcp_server(server_name)` | Retry connecting to an MCP server that failed or was disconnected |

481| `toggle_mcp_server(server_name, enabled)` | Enable or disable an MCP server mid-session. Disabling removes its tools |481| `toggle_mcp_server(server_name, enabled)` | Enable or disable an MCP server mid-session. Disabling removes its tools |

482| `stop_task(task_id)` | Stop a running background task. A [`TaskNotificationMessage`](#task-notification-message) with status `"stopped"` follows in the message stream |482| `stop_task(task_id)` | Stop a running background task. A [`TaskNotificationMessage`](#tasknotificationmessage) with status `"stopped"` follows in the message stream |

483| `get_server_info()` | Get server information including session ID and capabilities |483| `get_server_info()` | Get server information including session ID and capabilities |

484| `disconnect()` | Disconnect from Claude |484| `disconnect()` | Disconnect from Claude |

485 485 


791 effort: Literal["low", "medium", "high", "max"] | None = None791 effort: Literal["low", "medium", "high", "max"] | None = None

792 enable_file_checkpointing: bool = False792 enable_file_checkpointing: bool = False

793 session_store: SessionStore | None = None793 session_store: SessionStore | None = None

794 session_store_flush: SessionStoreFlushMode = "batched"

794```795```

795 796 

796| Property | Type | Default | Description |797| Property | Type | Default | Description |

797| :---------------------------- | :------------------------------------------------------------------------------------- | :--------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |798| :---------------------------- | :------------------------------------------------------------------------------------ | :--------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

798| `tools` | `list[str] \| ToolsPreset \| None` | `None` | Tools configuration. Use `{"type": "preset", "preset": "claude_code"}` for Claude Code's default tools |799| `tools` | `list[str] \| ToolsPreset \| None` | `None` | Tools configuration. Use `{"type": "preset", "preset": "claude_code"}` for Claude Code's default tools |

799| `allowed_tools` | `list[str]` | `[]` | Tools to auto-approve without prompting. This does not restrict Claude to only these tools; unlisted tools fall through to `permission_mode` and `can_use_tool`. Use `disallowed_tools` to block tools. See [Permissions](/en/agent-sdk/permissions#allow-and-deny-rules) |800| `allowed_tools` | `list[str]` | `[]` | Tools to auto-approve without prompting. This does not restrict Claude to only these tools; unlisted tools fall through to `permission_mode` and `can_use_tool`. Use `disallowed_tools` to block tools. See [Permissions](/en/agent-sdk/permissions#allow-and-deny-rules) |

800| `system_prompt` | `str \| SystemPromptPreset \| None` | `None` | System prompt configuration. Pass a string for custom prompt, or use `{"type": "preset", "preset": "claude_code"}` for Claude Code's system prompt. Add `"append"` to extend the preset |801| `system_prompt` | `str \| SystemPromptPreset \| None` | `None` | System prompt configuration. Pass a string for custom prompt, or use `{"type": "preset", "preset": "claude_code"}` for Claude Code's system prompt. Add `"append"` to extend the preset |


808| `enable_file_checkpointing` | `bool` | `False` | Enable file change tracking for rewinding. See [File checkpointing](/en/agent-sdk/file-checkpointing) |809| `enable_file_checkpointing` | `bool` | `False` | Enable file change tracking for rewinding. See [File checkpointing](/en/agent-sdk/file-checkpointing) |

809| `model` | `str \| None` | `None` | Claude model to use |810| `model` | `str \| None` | `None` | Claude model to use |

810| `fallback_model` | `str \| None` | `None` | Fallback model to use if the primary model fails |811| `fallback_model` | `str \| None` | `None` | Fallback model to use if the primary model fails |

811| `betas` | `list[SdkBeta]` | `[]` | Beta features to enable. See [`SdkBeta`](#sdk-beta) for available options |812| `betas` | `list[SdkBeta]` | `[]` | Beta features to enable. See [`SdkBeta`](#sdkbeta) for available options |

812| `output_format` | `dict[str, Any] \| None` | `None` | Output format for structured responses (e.g., `{"type": "json_schema", "schema": {...}}`). See [Structured outputs](/en/agent-sdk/structured-outputs) for details |813| `output_format` | `dict[str, Any] \| None` | `None` | Output format for structured responses (e.g., `{"type": "json_schema", "schema": {...}}`). See [Structured outputs](/en/agent-sdk/structured-outputs) for details |

813| `permission_prompt_tool_name` | `str \| None` | `None` | MCP tool name for permission prompts |814| `permission_prompt_tool_name` | `str \| None` | `None` | MCP tool name for permission prompts |

814| `cwd` | `str \| Path \| None` | `None` | Current working directory |815| `cwd` | `str \| Path \| None` | `None` | Current working directory |


820| `max_buffer_size` | `int \| None` | `None` | Maximum bytes when buffering CLI stdout |821| `max_buffer_size` | `int \| None` | `None` | Maximum bytes when buffering CLI stdout |

821| `debug_stderr` | `Any` | `sys.stderr` | *Deprecated* - File-like object for debug output. Use `stderr` callback instead |822| `debug_stderr` | `Any` | `sys.stderr` | *Deprecated* - File-like object for debug output. Use `stderr` callback instead |

822| `stderr` | `Callable[[str], None] \| None` | `None` | Callback function for stderr output from CLI |823| `stderr` | `Callable[[str], None] \| None` | `None` | Callback function for stderr output from CLI |

823| `can_use_tool` | [`CanUseTool`](#can-use-tool) ` \| None` | `None` | Tool permission callback function. See [Permission types](#can-use-tool) for details |824| `can_use_tool` | [`CanUseTool`](#canusetool) ` \| None` | `None` | Tool permission callback function. See [Permission types](#canusetool) for details |

824| `hooks` | `dict[HookEvent, list[HookMatcher]] \| None` | `None` | Hook configurations for intercepting events |825| `hooks` | `dict[HookEvent, list[HookMatcher]] \| None` | `None` | Hook configurations for intercepting events |

825| `user` | `str \| None` | `None` | User identifier |826| `user` | `str \| None` | `None` | User identifier |

826| `include_partial_messages` | `bool` | `False` | Include partial message streaming events. When enabled, [`StreamEvent`](#stream-event) messages are yielded |827| `include_partial_messages` | `bool` | `False` | Include partial message streaming events. When enabled, [`StreamEvent`](#streamevent) messages are yielded |

827| `fork_session` | `bool` | `False` | When resuming with `resume`, fork to a new session ID instead of continuing the original session |828| `fork_session` | `bool` | `False` | When resuming with `resume`, fork to a new session ID instead of continuing the original session |

828| `agents` | `dict[str, AgentDefinition] \| None` | `None` | Programmatically defined subagents |829| `agents` | `dict[str, AgentDefinition] \| None` | `None` | Programmatically defined subagents |

829| `plugins` | `list[SdkPluginConfig]` | `[]` | Load custom plugins from local paths. See [Plugins](/en/agent-sdk/plugins) for details |830| `plugins` | `list[SdkPluginConfig]` | `[]` | Load custom plugins from local paths. See [Plugins](/en/agent-sdk/plugins) for details |

830| `sandbox` | [`SandboxSettings`](#sandbox-settings) ` \| None` | `None` | Configure sandbox behavior programmatically. See [Sandbox settings](#sandbox-settings) for details |831| `sandbox` | [`SandboxSettings`](#sandboxsettings) ` \| None` | `None` | Configure sandbox behavior programmatically. See [Sandbox settings](#sandboxsettings) for details |

831| `setting_sources` | `list[SettingSource] \| None` | `None` (CLI defaults: all sources) | Control which filesystem settings to load. Pass `[]` to disable user, project, and local settings. Managed policy settings load regardless. See [Use Claude Code features](/en/agent-sdk/claude-code-features#what-settingsources-does-not-control) |832| `setting_sources` | `list[SettingSource] \| None` | `None` (CLI defaults: all sources) | Control which filesystem settings to load. Pass `[]` to disable user, project, and local settings. Managed policy settings load regardless. See [Use Claude Code features](/en/agent-sdk/claude-code-features#what-settingsources-does-not-control) |

832| `max_thinking_tokens` | `int \| None` | `None` | *Deprecated* - Maximum tokens for thinking blocks. Use `thinking` instead |833| `max_thinking_tokens` | `int \| None` | `None` | *Deprecated* - Maximum tokens for thinking blocks. Use `thinking` instead |

833| `thinking` | [`ThinkingConfig`](#thinking-config) ` \| None` | `None` | Controls extended thinking behavior. Takes precedence over `max_thinking_tokens` |834| `thinking` | [`ThinkingConfig`](#thinkingconfig) ` \| None` | `None` | Controls extended thinking behavior. Takes precedence over `max_thinking_tokens` |

834| `effort` | `Literal["low", "medium", "high", "max"] \| None` | `None` | Effort level for thinking depth |835| `effort` | `Literal["low", "medium", "high", "max"] \| None` | `None` | Effort level for thinking depth |

835| `session_store` | [`SessionStore`](/en/agent-sdk/session-storage#the-session-store-interface) ` \| None` | `None` | Mirror session transcripts to an external backend so any host can resume them. See [Persist sessions to external storage](/en/agent-sdk/session-storage) |836| `session_store` | [`SessionStore`](/en/agent-sdk/session-storage#the-sessionstore-interface) ` \| None` | `None` | Mirror session transcripts to an external backend so any host can resume them. See [Persist sessions to external storage](/en/agent-sdk/session-storage) |

837| `session_store_flush` | `Literal["batched", "eager"]` | `"batched"` | When to flush mirrored transcript entries to `session_store`. `"batched"` flushes once per turn or when the buffer fills; `"eager"` triggers a background flush after every frame. Ignored when `session_store` is `None` |

836 838 

837### `OutputFormat`839### `OutputFormat`

838 840 


1031| `maxTurns` | No | Maximum number of agentic turns before the agent stops |1033| `maxTurns` | No | Maximum number of agentic turns before the agent stops |

1032| `background` | No | Run this agent as a non-blocking background task when invoked |1034| `background` | No | Run this agent as a non-blocking background task when invoked |

1033| `effort` | No | Reasoning effort level for this agent. Accepts a named level or an integer |1035| `effort` | No | Reasoning effort level for this agent. Accepts a named level or an integer |

1034| `permissionMode` | No | Permission mode for tool execution within this agent. See [`PermissionMode`](#permission-mode) |1036| `permissionMode` | No | Permission mode for tool execution within this agent. See [`PermissionMode`](#permissionmode) |

1035 1037 

1036<Note>1038<Note>

1037 `AgentDefinition` field names use camelCase, such as `disallowedTools`, `permissionMode`, and `maxTurns`. These names map directly to the wire format shared with the TypeScript SDK. This differs from `ClaudeAgentOptions`, which uses Python snake\_case for the equivalent top-level fields such as `disallowed_tools` and `permission_mode`. Because `AgentDefinition` is a dataclass, passing a snake\_case keyword raises a `TypeError` at construction time.1039 `AgentDefinition` field names use camelCase, such as `disallowedTools`, `permissionMode`, and `maxTurns`. These names map directly to the wire format shared with the TypeScript SDK. This differs from `ClaudeAgentOptions`, which uses Python snake\_case for the equivalent top-level fields such as `disallowed_tools` and `permission_mode`. Because `AgentDefinition` is a dataclass, passing a snake\_case keyword raises a `TypeError` at construction time.


1045PermissionMode = Literal[1047PermissionMode = Literal[

1046 "default", # Standard permission behavior1048 "default", # Standard permission behavior

1047 "acceptEdits", # Auto-accept file edits1049 "acceptEdits", # Auto-accept file edits

1048 "plan", # Planning mode - no execution1050 "plan", # Planning mode - read-only tools only

1049 "dontAsk", # Deny anything not pre-approved instead of prompting1051 "dontAsk", # Deny anything not pre-approved instead of prompting

1050 "bypassPermissions", # Bypass all permission checks (use with caution)1052 "bypassPermissions", # Bypass all permission checks (use with caution)

1051]1053]


1081```1083```

1082 1084 

1083| Field | Type | Description |1085| Field | Type | Description |

1084| :------------ | :----------------------- | :----------------------------------------- |1086| :------------ | :----------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

1085| `signal` | `Any \| None` | Reserved for future abort signal support |1087| `signal` | `Any \| None` | Reserved for future abort signal support |

1086| `suggestions` | `list[PermissionUpdate]` | Permission update suggestions from the CLI |1088| `suggestions` | `list[PermissionUpdate]` | Permission update suggestions from the CLI. Bash prompts include a suggestion with the `localSettings` destination, so returning it in `updated_permissions` writes the rule to `.claude/settings.local.json` and persists across sessions. |

1087 1089 

1088### `PermissionResult`1090### `PermissionResult`

1089 1091 


1289 1291 

1290### `McpServerStatusConfig`1292### `McpServerStatusConfig`

1291 1293 

1292The configuration of an MCP server as reported by [`get_mcp_status()`](#methods). This is the union of all [`McpServerConfig`](#mcp-server-config) transport variants plus an output-only `claudeai-proxy` variant for servers proxied through claude.ai.1294The configuration of an MCP server as reported by [`get_mcp_status()`](#methods). This is the union of all [`McpServerConfig`](#mcpserverconfig) transport variants plus an output-only `claudeai-proxy` variant for servers proxied through claude.ai.

1293 1295 

1294```python theme={null}1296```python theme={null}

1295McpServerStatusConfig = (1297McpServerStatusConfig = (


1301)1303)

1302```1304```

1303 1305 

1304`McpSdkServerConfigStatus` is the serializable form of [`McpSdkServerConfig`](#mcp-sdk-server-config) with only `type` (`"sdk"`) and `name` (`str`) fields; the in-process `instance` is omitted. `McpClaudeAIProxyServerConfig` has `type` (`"claudeai-proxy"`), `url` (`str`), and `id` (`str`) fields.1306`McpSdkServerConfigStatus` is the serializable form of [`McpSdkServerConfig`](#mcpsdkserverconfig) with only `type` (`"sdk"`) and `name` (`str`) fields; the in-process `instance` is omitted. `McpClaudeAIProxyServerConfig` has `type` (`"claudeai-proxy"`), `url` (`str`), and `id` (`str`) fields.

1305 1307 

1306### `McpStatusResponse`1308### `McpStatusResponse`

1307 1309 


1314 1316 

1315### `McpServerStatus`1317### `McpServerStatus`

1316 1318 

1317Status of a connected MCP server, contained in [`McpStatusResponse`](#mcp-status-response).1319Status of a connected MCP server, contained in [`McpStatusResponse`](#mcpstatusresponse).

1318 1320 

1319```python theme={null}1321```python theme={null}

1320class McpServerStatus(TypedDict):1322class McpServerStatus(TypedDict):


1328```1330```

1329 1331 

1330| Field | Type | Description |1332| Field | Type | Description |

1331| :----------- | :-------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |1333| :----------- | :----------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

1332| `name` | `str` | Server name |1334| `name` | `str` | Server name |

1333| `status` | `str` | One of `"connected"`, `"failed"`, `"needs-auth"`, `"pending"`, or `"disabled"` |1335| `status` | `str` | One of `"connected"`, `"failed"`, `"needs-auth"`, `"pending"`, or `"disabled"` |

1334| `serverInfo` | `dict` (optional) | Server name and version (`{"name": str, "version": str}`) |1336| `serverInfo` | `dict` (optional) | Server name and version (`{"name": str, "version": str}`) |

1335| `error` | `str` (optional) | Error message if the server failed to connect |1337| `error` | `str` (optional) | Error message if the server failed to connect |

1336| `config` | [`McpServerStatusConfig`](#mcp-server-status-config) (optional) | Server configuration. Same shape as [`McpServerConfig`](#mcp-server-config) (stdio, SSE, HTTP, or SDK), plus a `claudeai-proxy` variant for servers connected through claude.ai |1338| `config` | [`McpServerStatusConfig`](#mcpserverstatusconfig) (optional) | Server configuration. Same shape as [`McpServerConfig`](#mcpserverconfig) (stdio, SSE, HTTP, or SDK), plus a `claudeai-proxy` variant for servers connected through claude.ai |

1337| `scope` | `str` (optional) | Configuration scope |1339| `scope` | `str` (optional) | Configuration scope |

1338| `tools` | `list` (optional) | Tools provided by this server, each with `name`, `description`, and `annotations` fields |1340| `tools` | `list` (optional) | Tools provided by this server, each with `name`, `description`, and `annotations` fields |

1339 1341 


1416```1418```

1417 1419 

1418| Field | Type | Description |1420| Field | Type | Description |

1419| :------------------- | :------------------------------------------------------------- | :------------------------------------------------------------------------------ |1421| :------------------- | :----------------------------------------------------------- | :----------------------------------------------------------------------------- |

1420| `content` | `list[ContentBlock]` | List of content blocks in the response |1422| `content` | `list[ContentBlock]` | List of content blocks in the response |

1421| `model` | `str` | Model that generated the response |1423| `model` | `str` | Model that generated the response |

1422| `parent_tool_use_id` | `str \| None` | Tool use ID if this is a nested response |1424| `parent_tool_use_id` | `str \| None` | Tool use ID if this is a nested response |

1423| `error` | [`AssistantMessageError`](#assistant-message-error) ` \| None` | Error type if the response encountered an error |1425| `error` | [`AssistantMessageError`](#assistantmessageerror) ` \| None` | Error type if the response encountered an error |

1424| `usage` | `dict[str, Any] \| None` | Per-message token usage (same keys as [`ResultMessage.usage`](#result-message)) |1426| `usage` | `dict[str, Any] \| None` | Per-message token usage (same keys as [`ResultMessage.usage`](#resultmessage)) |

1425| `message_id` | `str \| None` | API message ID. Multiple messages from one turn share the same ID |1427| `message_id` | `str \| None` | API message ID. Multiple messages from one turn share the same ID |

1426 1428 

1427### `AssistantMessageError`1429### `AssistantMessageError`


1481| `cache_creation_input_tokens` | `int` | Tokens used to create new cache entries. |1483| `cache_creation_input_tokens` | `int` | Tokens used to create new cache entries. |

1482| `cache_read_input_tokens` | `int` | Tokens read from existing cache entries. |1484| `cache_read_input_tokens` | `int` | Tokens read from existing cache entries. |

1483 1485 

1484The `model_usage` dict maps model names to per-model usage. The inner dict keys use camelCase because the value is passed through unmodified from the underlying CLI process, matching the TypeScript [`ModelUsage`](/en/agent-sdk/typescript#model-usage) type:1486The `model_usage` dict maps model names to per-model usage. The inner dict keys use camelCase because the value is passed through unmodified from the underlying CLI process, matching the TypeScript [`ModelUsage`](/en/agent-sdk/typescript#modelusage) type:

1485 1487 

1486| Key | Type | Description |1488| Key | Type | Description |

1487| -------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------- |1489| -------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------- |


1527```1529```

1528 1530 

1529| Field | Type | Description |1531| Field | Type | Description |

1530| :---------------- | :---------------------------------- | :----------------------- |1532| :---------------- | :-------------------------------- | :----------------------- |

1531| `rate_limit_info` | [`RateLimitInfo`](#rate-limit-info) | Current rate limit state |1533| `rate_limit_info` | [`RateLimitInfo`](#ratelimitinfo) | Current rate limit state |

1532| `uuid` | `str` | Unique event identifier |1534| `uuid` | `str` | Unique event identifier |

1533| `session_id` | `str` | Session identifier |1535| `session_id` | `str` | Session identifier |

1534 1536 

1535### `RateLimitInfo`1537### `RateLimitInfo`

1536 1538 

1537Rate limit state carried by [`RateLimitEvent`](#rate-limit-event).1539Rate limit state carried by [`RateLimitEvent`](#ratelimitevent).

1538 1540 

1539```python theme={null}1541```python theme={null}

1540RateLimitStatus = Literal["allowed", "allowed_warning", "rejected"]1542RateLimitStatus = Literal["allowed", "allowed_warning", "rejected"]


1812 1814 

1813Parameters:1815Parameters:

1814 1816 

1815* `input`: Strongly-typed hook input with discriminated unions based on `hook_event_name` (see [`HookInput`](#hook-input))1817* `input`: Strongly-typed hook input with discriminated unions based on `hook_event_name` (see [`HookInput`](#hookinput))

1816* `tool_use_id`: Optional tool use identifier (for tool-related hooks)1818* `tool_use_id`: Optional tool use identifier (for tool-related hooks)

1817* `context`: Hook context with additional information1819* `context`: Hook context with additional information

1818 1820 

1819Returns a [`HookJSONOutput`](#hook-json-output) that may contain:1821Returns a [`HookJSONOutput`](#hookjsonoutput) that may contain:

1820 1822 

1821* `decision`: `"block"` to block the action1823* `decision`: `"block"` to block the action

1822* `systemMessage`: System message to add to the transcript1824* `systemMessage`: System message to add to the transcript


3109```3111```

3110 3112 

3111| Property | Type | Default | Description |3113| Property | Type | Default | Description |

3112| :-------------------------- | :------------------------------------------------------ | :------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |3114| :-------------------------- | :---------------------------------------------------- | :------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

3113| `enabled` | `bool` | `False` | Enable sandbox mode for command execution |3115| `enabled` | `bool` | `False` | Enable sandbox mode for command execution |

3114| `autoAllowBashIfSandboxed` | `bool` | `True` | Auto-approve bash commands when sandbox is enabled |3116| `autoAllowBashIfSandboxed` | `bool` | `True` | Auto-approve bash commands when sandbox is enabled |

3115| `excludedCommands` | `list[str]` | `[]` | Commands that always bypass sandbox restrictions (e.g., `["docker"]`). These run unsandboxed automatically without model involvement |3117| `excludedCommands` | `list[str]` | `[]` | Commands that always bypass sandbox restrictions (e.g., `["docker"]`). These run unsandboxed automatically without model involvement |

3116| `allowUnsandboxedCommands` | `bool` | `True` | Allow the model to request running commands outside the sandbox. When `True`, the model can set `dangerouslyDisableSandbox` in tool input, which falls back to the [permissions system](#permissions-fallback-for-unsandboxed-commands) |3118| `allowUnsandboxedCommands` | `bool` | `True` | Allow the model to request running commands outside the sandbox. When `True`, the model can set `dangerouslyDisableSandbox` in tool input, which falls back to the [permissions system](#permissions-fallback-for-unsandboxed-commands) |

3117| `network` | [`SandboxNetworkConfig`](#sandbox-network-config) | `None` | Network-specific sandbox configuration |3119| `network` | [`SandboxNetworkConfig`](#sandboxnetworkconfig) | `None` | Network-specific sandbox configuration |

3118| `ignoreViolations` | [`SandboxIgnoreViolations`](#sandbox-ignore-violations) | `None` | Configure which sandbox violations to ignore |3120| `ignoreViolations` | [`SandboxIgnoreViolations`](#sandboxignoreviolations) | `None` | Configure which sandbox violations to ignore |

3119| `enableWeakerNestedSandbox` | `bool` | `False` | Enable a weaker nested sandbox for compatibility |3121| `enableWeakerNestedSandbox` | `bool` | `False` | Enable a weaker nested sandbox for compatibility |

3120 3122 

3121#### Example usage3123#### Example usage

Details

173 173 

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

175 175 

1763. **`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#claude-agent-options) or [TypeScript](/en/agent-sdk/typescript#options).1763. **`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).

177 177 

178The `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.178The `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.

179 179 

Details

31 31 

32### Continue, resume, and fork32### Continue, resume, and fork

33 33 

34Continue, resume, and fork are option fields you set on `query()` ([`ClaudeAgentOptions`](/en/agent-sdk/python#claude-agent-options) in Python, [`Options`](/en/agent-sdk/typescript#options) in TypeScript).34Continue, resume, and fork are option fields you set on `query()` ([`ClaudeAgentOptions`](/en/agent-sdk/python#claudeagentoptions) in Python, [`Options`](/en/agent-sdk/typescript#options) in TypeScript).

35 35 

36**Continue** and **resume** both pick up an existing session and add to it. The difference is how they find that session:36**Continue** and **resume** both pick up an existing session and add to it. The difference is how they find that session:

37 37 


46 46 

47### Python: `ClaudeSDKClient`47### Python: `ClaudeSDKClient`

48 48 

49[`ClaudeSDKClient`](/en/agent-sdk/python#claude-sdk-client) handles session IDs internally. Each call to `client.query()` automatically continues the same session. Call [`client.receive_response()`](/en/agent-sdk/python#claude-sdk-client) to iterate over the messages for the current query. The client must be used as an async context manager.49[`ClaudeSDKClient`](/en/agent-sdk/python#claudesdkclient) handles session IDs internally. Each call to `client.query()` automatically continues the same session. Call [`client.receive_response()`](/en/agent-sdk/python#claudesdkclient) to iterate over the messages for the current query. The client must be used as an async context manager.

50 50 

51This example runs two queries against the same `client`. The first asks the agent to analyze a module; the second asks it to refactor that module. Because both calls go through the same client instance, the second query has full context from the first without any explicit `resume` or session ID:51This example runs two queries against the same `client`. The first asks the agent to analyze a module; the second asks it to refactor that module. Because both calls go through the same client instance, the second query has full context from the first without any explicit `resume` or session ID:

52 52 


96asyncio.run(main())96asyncio.run(main())

97```97```

98 98 

99See the [Python SDK reference](/en/agent-sdk/python#choosing-between-query-and-claude-sdk-client) for details on when to use `ClaudeSDKClient` vs the standalone `query()` function.99See the [Python SDK reference](/en/agent-sdk/python#choosing-between-query-and-claudesdkclient) for details on when to use `ClaudeSDKClient` vs the standalone `query()` function.

100 100 

101### TypeScript: `continue: true`101### TypeScript: `continue: true`

102 102 


139 139 

140### Capture the session ID140### Capture the session ID

141 141 

142Resume and fork require a session ID. Read it from the `session_id` field on the result message ([`ResultMessage`](/en/agent-sdk/python#result-message) in Python, [`SDKResultMessage`](/en/agent-sdk/typescript#sdk-result-message) in TypeScript), which is present on every result regardless of success or error. In TypeScript the ID is also available earlier as a direct field on the init `SystemMessage`; in Python it's nested inside `SystemMessage.data`.142Resume and fork require a session ID. Read it from the `session_id` field on the result message ([`ResultMessage`](/en/agent-sdk/python#resultmessage) in Python, [`SDKResultMessage`](/en/agent-sdk/typescript#sdkresultmessage) in TypeScript), which is present on every result regardless of success or error. In TypeScript the ID is also available earlier as a direct field on the init `SystemMessage`; in Python it's nested inside `SystemMessage.data`.

143 143 

144<CodeGroup>144<CodeGroup>

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


312* **Move the session file.** Persist `~/.claude/projects/<encoded-cwd>/<session-id>.jsonl` from the first run and restore it to the same path on the new host before calling `resume`. The `cwd` must match.312* **Move the session file.** Persist `~/.claude/projects/<encoded-cwd>/<session-id>.jsonl` from the first run and restore it to the same path on the new host before calling `resume`. The `cwd` must match.

313* **Don't rely on session resume.** Capture the results you need (analysis output, decisions, file diffs) as application state and pass them into a fresh session's prompt. This is often more robust than shipping transcript files around.313* **Don't rely on session resume.** Capture the results you need (analysis output, decisions, file diffs) as application state and pass them into a fresh session's prompt. This is often more robust than shipping transcript files around.

314 314 

315Both SDKs expose functions for enumerating sessions on disk and reading their messages: [`listSessions()`](/en/agent-sdk/typescript#list-sessions) and [`getSessionMessages()`](/en/agent-sdk/typescript#get-session-messages) in TypeScript, [`list_sessions()`](/en/agent-sdk/python#list-sessions) and [`get_session_messages()`](/en/agent-sdk/python#get-session-messages) in Python. Use them to build custom session pickers, cleanup logic, or transcript viewers.315Both SDKs expose functions for enumerating sessions on disk and reading their messages: [`listSessions()`](/en/agent-sdk/typescript#listsessions) and [`getSessionMessages()`](/en/agent-sdk/typescript#getsessionmessages) in TypeScript, [`list_sessions()`](/en/agent-sdk/python#list_sessions) and [`get_session_messages()`](/en/agent-sdk/python#get_session_messages) in Python. Use them to build custom session pickers, cleanup logic, or transcript viewers.

316 316 

317Both SDKs also expose functions for looking up and mutating individual sessions: [`get_session_info()`](/en/agent-sdk/python#get-session-info), [`rename_session()`](/en/agent-sdk/python#rename-session), and [`tag_session()`](/en/agent-sdk/python#tag-session) in Python, and [`getSessionInfo()`](/en/agent-sdk/typescript#get-session-info), [`renameSession()`](/en/agent-sdk/typescript#rename-session), and [`tagSession()`](/en/agent-sdk/typescript#tag-session) in TypeScript. Use them to organize sessions by tag or give them human-readable titles.317Both SDKs also expose functions for looking up and mutating individual sessions: [`get_session_info()`](/en/agent-sdk/python#get_session_info), [`rename_session()`](/en/agent-sdk/python#rename_session), and [`tag_session()`](/en/agent-sdk/python#tag_session) in Python, and [`getSessionInfo()`](/en/agent-sdk/typescript#getsessioninfo), [`renameSession()`](/en/agent-sdk/typescript#renamesession), and [`tagSession()`](/en/agent-sdk/typescript#tagsession) in TypeScript. Use them to organize sessions by tag or give them human-readable titles.

318 318 

319## Related resources319## Related resources

320 320 

321* [How the agent loop works](/en/agent-sdk/agent-loop): Understand turns, messages, and context accumulation within a session321* [How the agent loop works](/en/agent-sdk/agent-loop): Understand turns, messages, and context accumulation within a session

322* [File checkpointing](/en/agent-sdk/file-checkpointing): Track and revert file changes across sessions322* [File checkpointing](/en/agent-sdk/file-checkpointing): Track and revert file changes across sessions

323* [Python `ClaudeAgentOptions`](/en/agent-sdk/python#claude-agent-options): Full session option reference for Python323* [Python `ClaudeAgentOptions`](/en/agent-sdk/python#claudeagentoptions): Full session option reference for Python

324* [TypeScript `Options`](/en/agent-sdk/typescript#options): Full session option reference for TypeScript324* [TypeScript `Options`](/en/agent-sdk/typescript#options): Full session option reference for TypeScript

Details

233 ```233 ```

234</CodeGroup>234</CodeGroup>

235 235 

236For more details on `settingSources`/`setting_sources`, see the [TypeScript SDK reference](/en/agent-sdk/typescript#setting-source) or [Python SDK reference](/en/agent-sdk/python#setting-source).236For 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).

237 237 

238**Check working directory**: The SDK loads Skills relative to the `cwd` option. Ensure it points to a directory containing `.claude/skills/`:238**Check working directory**: The SDK loads Skills relative to the `cwd` option. Ensure it points to a directory containing `.claude/skills/`:

239 239 

Details

93 ```typescript TypeScript theme={null}93 ```typescript TypeScript theme={null}

94 type SDKPartialAssistantMessage = {94 type SDKPartialAssistantMessage = {

95 type: "stream_event";95 type: "stream_event";

96 event: RawMessageStreamEvent; // From Anthropic SDK96 event: BetaRawMessageStreamEvent; // From Anthropic SDK

97 parent_tool_use_id: string | null;97 parent_tool_use_id: string | null;

98 uuid: UUID;98 uuid: UUID;

99 session_id: string;99 session_id: string;

Details

15 15 

16You can create subagents in three ways:16You can create subagents in three ways:

17 17 

18* **Programmatically**: use the `agents` parameter in your `query()` options ([TypeScript](/en/agent-sdk/typescript#agent-definition), [Python](/en/agent-sdk/python#agent-definition))18* **Programmatically**: use the `agents` parameter in your `query()` options ([TypeScript](/en/agent-sdk/typescript#agentdefinition), [Python](/en/agent-sdk/python#agentdefinition))

19* **Filesystem-based**: define agents as markdown files in `.claude/agents/` directories (see [defining subagents as files](/en/sub-agents))19* **Filesystem-based**: define agents as markdown files in `.claude/agents/` directories (see [defining subagents as files](/en/sub-agents))

20* **Built-in general-purpose**: Claude can invoke the built-in `general-purpose` subagent at any time via the Agent tool without you defining anything20* **Built-in general-purpose**: Claude can invoke the built-in `general-purpose` subagent at any time via the Agent tool without you defining anything

21 21 


174| `effort` | `'low' \| 'medium' \| 'high' \| 'xhigh' \| 'max' \| number` | No | Reasoning effort level for this agent |174| `effort` | `'low' \| 'medium' \| 'high' \| 'xhigh' \| 'max' \| number` | No | Reasoning effort level for this agent |

175| `permissionMode` | `PermissionMode` | No | Permission mode for tool execution within this agent |175| `permissionMode` | `PermissionMode` | No | Permission mode for tool execution within this agent |

176 176 

177In the Python SDK, these field names use camelCase to match the wire format. See the [`AgentDefinition` reference](/en/agent-sdk/python#agent-definition) for details.177In the Python SDK, these field names use camelCase to match the wire format. See the [`AgentDefinition` reference](/en/agent-sdk/python#agentdefinition) for details.

178 178 

179<Note>179<Note>

180 Subagents cannot spawn their own subagents. Don't include `Agent` in a subagent's `tools` array.180 Subagents cannot spawn their own subagents. Don't include `Agent` in a subagent's `tools` array.

Details

57 ```57 ```

58 58 

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

60 from claude_agent_sdk import query, AssistantMessage, ToolUseBlock60 from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ToolUseBlock

61 61 

62 async for message in query(62 async for message in query(

63 prompt="Optimize my React app performance and track progress with todos",63 prompt="Optimize my React app performance and track progress with todos",

64 options={"max_turns": 15},64 options=ClaudeAgentOptions(max_turns=15),

65 ):65 ):

66 # Todo updates are reflected in the message stream66 # Todo updates are reflected in the message stream

67 if isinstance(message, AssistantMessage):67 if isinstance(message, AssistantMessage):


132 ```132 ```

133 133 

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

135 from claude_agent_sdk import query, AssistantMessage, ToolUseBlock135 from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ToolUseBlock

136 from typing import List, Dict136 from typing import List, Dict

137 137 

138 138 


167 print(f"{i + 1}. {icon} {text}")167 print(f"{i + 1}. {icon} {text}")

168 168 

169 async def track_query(self, prompt: str):169 async def track_query(self, prompt: str):

170 async for message in query(prompt=prompt, options={"max_turns": 20}):170 async for message in query(prompt=prompt, options=ClaudeAgentOptions(max_turns=20)):

171 if isinstance(message, AssistantMessage):171 if isinstance(message, AssistantMessage):

172 for block in message.content:172 for block in message.content:

173 if isinstance(block, ToolUseBlock) and block.name == "TodoWrite":173 if isinstance(block, ToolUseBlock) and block.name == "TodoWrite":

Details

41#### Parameters41#### Parameters

42 42 

43| Parameter | Type | Description |43| Parameter | Type | Description |

44| :-------- | :---------------------------------------------------------------- | :---------------------------------------------------------------- |44| :-------- | :--------------------------------------------------------------- | :---------------------------------------------------------------- |

45| `prompt` | `string \| AsyncIterable<`[`SDKUserMessage`](#sdkuser-message)`>` | The input prompt as a string or async iterable for streaming mode |45| `prompt` | `string \| AsyncIterable<`[`SDKUserMessage`](#sdkusermessage)`>` | The input prompt as a string or async iterable for streaming mode |

46| `options` | [`Options`](#options) | Optional configuration object (see Options type below) |46| `options` | [`Options`](#options) | Optional configuration object (see Options type below) |

47 47 

48#### Returns48#### Returns

49 49 

50Returns a [`Query`](#query-object) object that extends `AsyncGenerator<`[`SDKMessage`](#sdk-message)`, void>` with additional methods.50Returns a [`Query`](#query-object) object that extends `AsyncGenerator<`[`SDKMessage`](#sdkmessage)`, void>` with additional methods.

51 51 

52### `startup()`52### `startup()`

53 53 

54Pre-warms the CLI subprocess by spawning it and completing the initialize handshake before a prompt is available. The returned [`WarmQuery`](#warm-query) handle accepts a prompt later and writes it to an already-ready process, so the first `query()` call resolves without paying subprocess spawn and initialization cost inline.54Pre-warms the CLI subprocess by spawning it and completing the initialize handshake before a prompt is available. The returned [`WarmQuery`](#warmquery) handle accepts a prompt later and writes it to an already-ready process, so the first `query()` call resolves without paying subprocess spawn and initialization cost inline.

55 55 

56```typescript theme={null}56```typescript theme={null}

57function startup(params?: {57function startup(params?: {


69 69 

70#### Returns70#### Returns

71 71 

72Returns a `Promise<`[`WarmQuery`](#warm-query)`>` that resolves once the subprocess has spawned and completed its initialize handshake.72Returns a `Promise<`[`WarmQuery`](#warmquery)`>` that resolves once the subprocess has spawned and completed its initialize handshake.

73 73 

74#### Example74#### Example

75 75 


104#### Parameters104#### Parameters

105 105 

106| Parameter | Type | Description |106| Parameter | Type | Description |

107| :------------ | :------------------------------------------------------------------ | :------------------------------------------------------------------------------ |107| :------------ | :---------------------------------------------------------------- | :------------------------------------------------------------------------------ |

108| `name` | `string` | The name of the tool |108| `name` | `string` | The name of the tool |

109| `description` | `string` | A description of what the tool does |109| `description` | `string` | A description of what the tool does |

110| `inputSchema` | `Schema extends AnyZodRawShape` | Zod schema defining the tool's input parameters (supports both Zod 3 and Zod 4) |110| `inputSchema` | `Schema extends AnyZodRawShape` | Zod schema defining the tool's input parameters (supports both Zod 3 and Zod 4) |

111| `handler` | `(args, extra) => Promise<`[`CallToolResult`](#call-tool-result)`>` | Async function that executes the tool logic |111| `handler` | `(args, extra) => Promise<`[`CallToolResult`](#calltoolresult)`>` | Async function that executes the tool logic |

112| `extras` | `{ annotations?: `[`ToolAnnotations`](#tool-annotations)` }` | Optional MCP tool annotations providing behavioral hints to clients |112| `extras` | `{ annotations?: `[`ToolAnnotations`](#toolannotations)` }` | Optional MCP tool annotations providing behavioral hints to clients |

113 113 

114#### `ToolAnnotations`114#### `ToolAnnotations`

115 115 


186| `firstPrompt` | `string \| undefined` | First meaningful user prompt in the session |186| `firstPrompt` | `string \| undefined` | First meaningful user prompt in the session |

187| `gitBranch` | `string \| undefined` | Git branch at the end of the session |187| `gitBranch` | `string \| undefined` | Git branch at the end of the session |

188| `cwd` | `string \| undefined` | Working directory for the session |188| `cwd` | `string \| undefined` | Working directory for the session |

189| `tag` | `string \| undefined` | User-set session tag (see [`tagSession()`](#tag-session)) |189| `tag` | `string \| undefined` | User-set session tag (see [`tagSession()`](#tagsession)) |

190| `createdAt` | `number \| undefined` | Creation time in milliseconds since epoch, from the first entry's timestamp |190| `createdAt` | `number \| undefined` | Creation time in milliseconds since epoch, from the first entry's timestamp |

191 191 

192#### Example192#### Example


270| `sessionId` | `string` | required | UUID of the session to look up |270| `sessionId` | `string` | required | UUID of the session to look up |

271| `options.dir` | `string` | `undefined` | Project directory path. When omitted, searches all project directories |271| `options.dir` | `string` | `undefined` | Project directory path. When omitted, searches all project directories |

272 272 

273Returns [`SDKSessionInfo`](#return-type-sdk-session-info), or `undefined` if the session is not found.273Returns [`SDKSessionInfo`](#return-type-sdksessioninfo), or `undefined` if the session is not found.

274 274 

275### `renameSession()`275### `renameSession()`

276 276 


323| `abortController` | `AbortController` | `new AbortController()` | Controller for cancelling operations |323| `abortController` | `AbortController` | `new AbortController()` | Controller for cancelling operations |

324| `additionalDirectories` | `string[]` | `[]` | Additional directories Claude can access |324| `additionalDirectories` | `string[]` | `[]` | Additional directories Claude can access |

325| `agent` | `string` | `undefined` | Agent name for the main thread. The agent must be defined in the `agents` option or in settings |325| `agent` | `string` | `undefined` | Agent name for the main thread. The agent must be defined in the `agents` option or in settings |

326| `agents` | `Record<string, [`AgentDefinition`](#agent-definition)>` | `undefined` | Programmatically define subagents |326| `agents` | `Record<string, [`AgentDefinition`](#agentdefinition)>` | `undefined` | Programmatically define subagents |

327| `allowDangerouslySkipPermissions` | `boolean` | `false` | Enable bypassing permissions. Required when using `permissionMode: 'bypassPermissions'` |327| `allowDangerouslySkipPermissions` | `boolean` | `false` | Enable bypassing permissions. Required when using `permissionMode: 'bypassPermissions'` |

328| `allowedTools` | `string[]` | `[]` | Tools to auto-approve without prompting. This does not restrict Claude to only these tools; unlisted tools fall through to `permissionMode` and `canUseTool`. Use `disallowedTools` to block tools. See [Permissions](/en/agent-sdk/permissions#allow-and-deny-rules) |328| `allowedTools` | `string[]` | `[]` | Tools to auto-approve without prompting. This does not restrict Claude to only these tools; unlisted tools fall through to `permissionMode` and `canUseTool`. Use `disallowedTools` to block tools. See [Permissions](/en/agent-sdk/permissions#allow-and-deny-rules) |

329| `betas` | [`SdkBeta`](#sdk-beta)`[]` | `[]` | Enable beta features |329| `betas` | [`SdkBeta`](#sdkbeta)`[]` | `[]` | Enable beta features |

330| `canUseTool` | [`CanUseTool`](#can-use-tool) | `undefined` | Custom permission function for tool usage |330| `canUseTool` | [`CanUseTool`](#canusetool) | `undefined` | Custom permission function for tool usage |

331| `continue` | `boolean` | `false` | Continue the most recent conversation |331| `continue` | `boolean` | `false` | Continue the most recent conversation |

332| `cwd` | `string` | `process.cwd()` | Current working directory |332| `cwd` | `string` | `process.cwd()` | Current working directory |

333| `debug` | `boolean` | `false` | Enable debug mode for the Claude Code process |333| `debug` | `boolean` | `false` | Enable debug mode for the Claude Code process |


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

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

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

344| `hooks` | `Partial<Record<`[`HookEvent`](#hook-event)`, `[`HookCallbackMatcher`](#hook-callback-matcher)`[]>>` | `{}` | Hook callbacks for events |344| `hooks` | `Partial<Record<`[`HookEvent`](#hookevent)`, `[`HookCallbackMatcher`](#hookcallbackmatcher)`[]>>` | `{}` | Hook callbacks for events |

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

346| `maxBudgetUsd` | `number` | `undefined` | Stop the query when the client-side cost estimate reaches this USD value. Compared against the same estimate as `total_cost_usd`; see [Track cost and usage](/en/agent-sdk/cost-tracking) for accuracy caveats |346| `maxBudgetUsd` | `number` | `undefined` | Stop the query when the client-side cost estimate reaches this USD value. Compared against the same estimate as `total_cost_usd`; see [Track cost and usage](/en/agent-sdk/cost-tracking) for accuracy caveats |

347| `maxThinkingTokens` | `number` | `undefined` | *Deprecated:* Use `thinking` instead. Maximum tokens for thinking process |347| `maxThinkingTokens` | `number` | `undefined` | *Deprecated:* Use `thinking` instead. Maximum tokens for thinking process |

348| `maxTurns` | `number` | `undefined` | Maximum agentic turns (tool-use round trips) |348| `maxTurns` | `number` | `undefined` | Maximum agentic turns (tool-use round trips) |

349| `mcpServers` | `Record<string, [`McpServerConfig`](#mcp-server-config)>` | `{}` | MCP server configurations |349| `mcpServers` | `Record<string, [`McpServerConfig`](#mcpserverconfig)>` | `{}` | MCP server configurations |

350| `model` | `string` | Default from CLI | Claude model to use |350| `model` | `string` | Default from CLI | Claude model to use |

351| `outputFormat` | `{ type: 'json_schema', schema: JSONSchema }` | `undefined` | Define output format for agent results. See [Structured outputs](/en/agent-sdk/structured-outputs) for details |351| `outputFormat` | `{ type: 'json_schema', schema: JSONSchema }` | `undefined` | Define output format for agent results. See [Structured outputs](/en/agent-sdk/structured-outputs) for details |

352| `pathToClaudeCodeExecutable` | `string` | Auto-resolved from bundled native binary | Path to Claude Code executable. Only needed if optional dependencies were skipped during install or your platform isn't in the supported set |352| `pathToClaudeCodeExecutable` | `string` | Auto-resolved from bundled native binary | Path to Claude Code executable. Only needed if optional dependencies were skipped during install or your platform isn't in the supported set |

353| `permissionMode` | [`PermissionMode`](#permission-mode) | `'default'` | Permission mode for the session |353| `permissionMode` | [`PermissionMode`](#permissionmode) | `'default'` | Permission mode for the session |

354| `permissionPromptToolName` | `string` | `undefined` | MCP tool name for permission prompts |354| `permissionPromptToolName` | `string` | `undefined` | MCP tool name for permission prompts |

355| `persistSession` | `boolean` | `true` | When `false`, disables session persistence to disk. Sessions cannot be resumed later |355| `persistSession` | `boolean` | `true` | When `false`, disables session persistence to disk. Sessions cannot be resumed later |

356| `plugins` | [`SdkPluginConfig`](#sdk-plugin-config)`[]` | `[]` | Load custom plugins from local paths. See [Plugins](/en/agent-sdk/plugins) for details |356| `plugins` | [`SdkPluginConfig`](#sdkpluginconfig)`[]` | `[]` | Load custom plugins from local paths. See [Plugins](/en/agent-sdk/plugins) for details |

357| `promptSuggestions` | `boolean` | `false` | Enable prompt suggestions. Emits a `prompt_suggestion` message after each turn with a predicted next user prompt |357| `promptSuggestions` | `boolean` | `false` | Enable prompt suggestions. Emits a `prompt_suggestion` message after each turn with a predicted next user prompt |

358| `resume` | `string` | `undefined` | Session ID to resume |358| `resume` | `string` | `undefined` | Session ID to resume |

359| `resumeSessionAt` | `string` | `undefined` | Resume session at a specific message UUID |359| `resumeSessionAt` | `string` | `undefined` | Resume session at a specific message UUID |

360| `sandbox` | [`SandboxSettings`](#sandbox-settings) | `undefined` | Configure sandbox behavior programmatically. See [Sandbox settings](#sandbox-settings) for details |360| `sandbox` | [`SandboxSettings`](#sandboxsettings) | `undefined` | Configure sandbox behavior programmatically. See [Sandbox settings](#sandboxsettings) for details |

361| `sessionId` | `string` | Auto-generated | Use a specific UUID for the session instead of auto-generating one |361| `sessionId` | `string` | Auto-generated | Use a specific UUID for the session instead of auto-generating one |

362| `sessionStore` | [`SessionStore`](/en/agent-sdk/session-storage#the-session-store-interface) | `undefined` | Mirror session transcripts to an external backend so any host can resume them. See [Persist sessions to external storage](/en/agent-sdk/session-storage) |362| `sessionStore` | [`SessionStore`](/en/agent-sdk/session-storage#the-sessionstore-interface) | `undefined` | Mirror session transcripts to an external backend so any host can resume them. See [Persist sessions to external storage](/en/agent-sdk/session-storage) |

363| `settingSources` | [`SettingSource`](#setting-source)`[]` | CLI defaults (all sources) | Control which filesystem settings to load. Pass `[]` to disable user, project, and local settings. Managed policy settings load regardless. See [Use Claude Code features](/en/agent-sdk/claude-code-features#what-settingsources-does-not-control) |363| `settingSources` | [`SettingSource`](#settingsource)`[]` | CLI defaults (all sources) | Control which filesystem settings to load. Pass `[]` to disable user, project, and local settings. Managed policy settings load regardless. See [Use Claude Code features](/en/agent-sdk/claude-code-features#what-settingsources-does-not-control) |

364| `spawnClaudeCodeProcess` | `(options: SpawnOptions) => SpawnedProcess` | `undefined` | Custom function to spawn the Claude Code process. Use to run Claude Code in VMs, containers, or remote environments |364| `spawnClaudeCodeProcess` | `(options: SpawnOptions) => SpawnedProcess` | `undefined` | Custom function to spawn the Claude Code process. Use to run Claude Code in VMs, containers, or remote environments |

365| `stderr` | `(data: string) => void` | `undefined` | Callback for stderr output |365| `stderr` | `(data: string) => void` | `undefined` | Callback for stderr output |

366| `strictMcpConfig` | `boolean` | `false` | Enforce strict MCP validation |366| `strictMcpConfig` | `boolean` | `false` | Enforce strict MCP validation |

367| `systemPrompt` | `string \| { type: 'preset'; preset: 'claude_code'; append?: string; excludeDynamicSections?: boolean }` | `undefined` (minimal prompt) | System prompt configuration. Pass a string for custom prompt, or `{ type: 'preset', preset: 'claude_code' }` to use Claude Code's system prompt. When using the preset object form, add `append` to extend it with additional instructions, and set `excludeDynamicSections: true` to move per-session context into the first user message for [better prompt-cache reuse across machines](/en/agent-sdk/modifying-system-prompts#improve-prompt-caching-across-users-and-machines) |367| `systemPrompt` | `string \| { type: 'preset'; preset: 'claude_code'; append?: string; excludeDynamicSections?: boolean }` | `undefined` (minimal prompt) | System prompt configuration. Pass a string for custom prompt, or `{ type: 'preset', preset: 'claude_code' }` to use Claude Code's system prompt. When using the preset object form, add `append` to extend it with additional instructions, and set `excludeDynamicSections: true` to move per-session context into the first user message for [better prompt-cache reuse across machines](/en/agent-sdk/modifying-system-prompts#improve-prompt-caching-across-users-and-machines) |

368| `thinking` | [`ThinkingConfig`](#thinking-config) | `{ type: 'adaptive' }` for supported models | Controls Claude's thinking/reasoning behavior. See [`ThinkingConfig`](#thinking-config) for options |368| `thinking` | [`ThinkingConfig`](#thinkingconfig) | `{ type: 'adaptive' }` for supported models | Controls Claude's thinking/reasoning behavior. See [`ThinkingConfig`](#thinkingconfig) for options |

369| `toolConfig` | [`ToolConfig`](#tool-config) | `undefined` | Configuration for built-in tool behavior. See [`ToolConfig`](#tool-config) for details |369| `toolConfig` | [`ToolConfig`](#toolconfig) | `undefined` | Configuration for built-in tool behavior. See [`ToolConfig`](#toolconfig) for details |

370| `tools` | `string[] \| { type: 'preset'; preset: 'claude_code' }` | `undefined` | Tool configuration. Pass an array of tool names or use the preset to get Claude Code's default tools |370| `tools` | `string[] \| { type: 'preset'; preset: 'claude_code' }` | `undefined` | Tool configuration. Pass an array of tool names or use the preset to get Claude Code's default tools |

371 371 

372### `Query` object372### `Query` object


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

411| `supportedCommands()` | Returns available slash commands |411| `supportedCommands()` | Returns available slash commands |

412| `supportedModels()` | Returns available models with display info |412| `supportedModels()` | Returns available models with display info |

413| `supportedAgents()` | Returns available subagents as [`AgentInfo`](#agent-info)`[]` |413| `supportedAgents()` | Returns available subagents as [`AgentInfo`](#agentinfo)`[]` |

414| `mcpServerStatus()` | Returns status of connected MCP servers |414| `mcpServerStatus()` | Returns status of connected MCP servers |

415| `accountInfo()` | Returns account information |415| `accountInfo()` | Returns account information |

416| `reconnectMcpServer(serverName)` | Reconnect an MCP server by name |416| `reconnectMcpServer(serverName)` | Reconnect an MCP server by name |


493| `background` | No | Run this agent as a non-blocking background task when invoked |493| `background` | No | Run this agent as a non-blocking background task when invoked |

494| `memory` | No | Memory source for this agent: `'user'`, `'project'`, or `'local'` |494| `memory` | No | Memory source for this agent: `'user'`, `'project'`, or `'local'` |

495| `effort` | No | Reasoning effort level for this agent. Accepts a named level or an integer |495| `effort` | No | Reasoning effort level for this agent. Accepts a named level or an integer |

496| `permissionMode` | No | Permission mode for tool execution within this agent. See [`PermissionMode`](#permission-mode) |496| `permissionMode` | No | Permission mode for tool execution within this agent. See [`PermissionMode`](#permissionmode) |

497| `criticalSystemReminder_EXPERIMENTAL` | No | Experimental: Critical reminder added to the system prompt |497| `criticalSystemReminder_EXPERIMENTAL` | No | Experimental: Critical reminder added to the system prompt |

498 498 

499### `AgentMcpServerSpec`499### `AgentMcpServerSpec`


626 | "default" // Standard permission behavior626 | "default" // Standard permission behavior

627 | "acceptEdits" // Auto-accept file edits627 | "acceptEdits" // Auto-accept file edits

628 | "bypassPermissions" // Bypass all permission checks628 | "bypassPermissions" // Bypass all permission checks

629 | "plan" // Planning mode - no execution629 | "plan" // Planning mode - read-only tools only

630 | "dontAsk" // Don't prompt for permissions, deny if not pre-approved630 | "dontAsk" // Don't prompt for permissions, deny if not pre-approved

631 | "auto"; // Use a model classifier to approve or deny each tool call631 | "auto"; // Use a model classifier to approve or deny each tool call

632```632```


651```651```

652 652 

653| Option | Type | Description |653| Option | Type | Description |

654| :--------------- | :------------------------------------------- | :--------------------------------------------------------------------------- |654| :--------------- | :------------------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

655| `signal` | `AbortSignal` | Signaled if the operation should be aborted |655| `signal` | `AbortSignal` | Signaled if the operation should be aborted |

656| `suggestions` | [`PermissionUpdate`](#permission-update)`[]` | Suggested permission updates so the user is not prompted again for this tool |656| `suggestions` | [`PermissionUpdate`](#permissionupdate)`[]` | Suggested permission updates so the user is not prompted again for this tool. Bash prompts include a suggestion with the `localSettings` [destination](#permissionupdatedestination), so returning it in `updatedPermissions` writes the rule to `.claude/settings.local.json` and persists across sessions. |

657| `blockedPath` | `string` | The file path that triggered the permission request, if applicable |657| `blockedPath` | `string` | The file path that triggered the permission request, if applicable |

658| `decisionReason` | `string` | Explains why this permission request was triggered |658| `decisionReason` | `string` | Explains why this permission request was triggered |

659| `toolUseID` | `string` | Unique identifier for this specific tool call within the assistant message |659| `toolUseID` | `string` | Unique identifier for this specific tool call within the assistant message |


2379 | McpClaudeAIProxyServerConfig;2379 | McpClaudeAIProxyServerConfig;

2380```2380```

2381 2381 

2382See [`McpServerConfig`](#mcp-server-config) for details on each transport type.2382See [`McpServerConfig`](#mcpserverconfig) for details on each transport type.

2383 2383 

2384### `AccountInfo`2384### `AccountInfo`

2385 2385 


2825```2825```

2826 2826 

2827| Property | Type | Default | Description |2827| Property | Type | Default | Description |

2828| :-------------------------- | :------------------------------------------------------ | :---------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |2828| :-------------------------- | :---------------------------------------------------- | :---------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

2829| `enabled` | `boolean` | `false` | Enable sandbox mode for command execution |2829| `enabled` | `boolean` | `false` | Enable sandbox mode for command execution |

2830| `autoAllowBashIfSandboxed` | `boolean` | `true` | Auto-approve bash commands when sandbox is enabled |2830| `autoAllowBashIfSandboxed` | `boolean` | `true` | Auto-approve bash commands when sandbox is enabled |

2831| `excludedCommands` | `string[]` | `[]` | Commands that always bypass sandbox restrictions (e.g., `['docker']`). These run unsandboxed automatically without model involvement |2831| `excludedCommands` | `string[]` | `[]` | Commands that always bypass sandbox restrictions (e.g., `['docker']`). These run unsandboxed automatically without model involvement |

2832| `allowUnsandboxedCommands` | `boolean` | `true` | Allow the model to request running commands outside the sandbox. When `true`, the model can set `dangerouslyDisableSandbox` in tool input, which falls back to the [permissions system](#permissions-fallback-for-unsandboxed-commands) |2832| `allowUnsandboxedCommands` | `boolean` | `true` | Allow the model to request running commands outside the sandbox. When `true`, the model can set `dangerouslyDisableSandbox` in tool input, which falls back to the [permissions system](#permissions-fallback-for-unsandboxed-commands) |

2833| `network` | [`SandboxNetworkConfig`](#sandbox-network-config) | `undefined` | Network-specific sandbox configuration |2833| `network` | [`SandboxNetworkConfig`](#sandboxnetworkconfig) | `undefined` | Network-specific sandbox configuration |

2834| `filesystem` | [`SandboxFilesystemConfig`](#sandbox-filesystem-config) | `undefined` | Filesystem-specific sandbox configuration for read/write restrictions |2834| `filesystem` | [`SandboxFilesystemConfig`](#sandboxfilesystemconfig) | `undefined` | Filesystem-specific sandbox configuration for read/write restrictions |

2835| `ignoreViolations` | `Record<string, string[]>` | `undefined` | Map of violation categories to patterns to ignore (e.g., `{ file: ['/tmp/*'], network: ['localhost'] }`) |2835| `ignoreViolations` | `Record<string, string[]>` | `undefined` | Map of violation categories to patterns to ignore (e.g., `{ file: ['/tmp/*'], network: ['localhost'] }`) |

2836| `enableWeakerNestedSandbox` | `boolean` | `false` | Enable a weaker nested sandbox for compatibility |2836| `enableWeakerNestedSandbox` | `boolean` | `false` | Enable a weaker nested sandbox for compatibility |

2837| `ripgrep` | `{ command: string; args?: string[] }` | `undefined` | Custom ripgrep binary configuration for sandbox environments |2837| `ripgrep` | `{ command: string; args?: string[] }` | `undefined` | Custom ripgrep binary configuration for sandbox environments |

Details

54Once you've passed a `canUseTool` callback in your query options, it fires when Claude wants to use a tool that isn't auto-approved. Your callback receives three arguments:54Once you've passed a `canUseTool` callback in your query options, it fires when Claude wants to use a tool that isn't auto-approved. Your callback receives three arguments:

55 55 

56| Argument | Description |56| Argument | Description |

57| ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |57| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

58| `toolName` | The name of the tool Claude wants to use (e.g., `"Bash"`, `"Write"`, `"Edit"`) |58| `toolName` | The name of the tool Claude wants to use (e.g., `"Bash"`, `"Write"`, `"Edit"`) |

59| `input` | The parameters Claude is passing to the tool. Contents vary by tool. |59| `input` | The parameters Claude is passing to the tool. Contents vary by tool. |

60| `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#tool-permission-context) for Python. |60| `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. |

61 61 

62The `input` object contains tool-specific parameters. Common examples:62The `input` object contains tool-specific parameters. Common examples:

63 63 


68| `Edit` | `file_path`, `old_string`, `new_string` |68| `Edit` | `file_path`, `old_string`, `new_string` |

69| `Read` | `file_path`, `offset`, `limit` |69| `Read` | `file_path`, `offset`, `limit` |

70 70 

71See the SDK reference for complete input schemas: [Python](/en/agent-sdk/python#tool-input-output-types) | [TypeScript](/en/agent-sdk/typescript#tool-input-types).71See the SDK reference for complete input schemas: [Python](/en/agent-sdk/python#tool-input%2Foutput-types) | [TypeScript](/en/agent-sdk/typescript#tool-input-types).

72 72 

73You can display this information to the user so they can decide whether to allow or reject the action, then return the appropriate response.73You can display this information to the user so they can decide whether to allow or reject the action, then return the appropriate response.

74 74 


807 807 

808* [Configure permissions](/en/agent-sdk/permissions): set up permission modes and rules808* [Configure permissions](/en/agent-sdk/permissions): set up permission modes and rules

809* [Control execution with hooks](/en/agent-sdk/hooks): run custom code at key points in the agent lifecycle809* [Control execution with hooks](/en/agent-sdk/hooks): run custom code at key points in the agent lifecycle

810* [TypeScript SDK reference](/en/agent-sdk/typescript#can-use-tool): full canUseTool API documentation810* [TypeScript SDK reference](/en/agent-sdk/typescript#canusetool): full canUseTool API documentation

Details

113 113 

114Claude Code securely manages your authentication credentials:114Claude Code securely manages your authentication credentials:

115 115 

116* **Storage location**: on macOS, credentials are stored in the encrypted macOS Keychain. On Linux and Windows, credentials are stored in `~/.claude/.credentials.json`, or under `$CLAUDE_CONFIG_DIR` if that variable is set. On Linux, the file is written with mode `0600`; on Windows, it inherits the access controls of your user profile directory.116* **Storage location**:

117 * On macOS, credentials are stored in the encrypted macOS Keychain.

118 * On Linux, credentials are stored in `~/.claude/.credentials.json` with file mode `0600`.

119 * On Windows, credentials are stored in `%USERPROFILE%\.claude\.credentials.json` and inherit the access controls of your user profile directory, which restricts the file to your user account by default.

120 * If you've set the `CLAUDE_CONFIG_DIR` environment variable on Linux or Windows, the `.credentials.json` file lives under that directory instead.

117* **Supported authentication types**: Claude.ai credentials, Claude API credentials, Azure Auth, Bedrock Auth, and Vertex Auth.121* **Supported authentication types**: Claude.ai credentials, Claude API credentials, Azure Auth, Bedrock Auth, and Vertex Auth.

118* **Custom credential scripts**: the [`apiKeyHelper`](/en/settings#available-settings) setting can be configured to run a shell script that returns an API key.122* **Custom credential scripts**: the [`apiKeyHelper`](/en/settings#available-settings) setting can be configured to run a shell script that returns an API key.

119* **Refresh intervals**: by default, `apiKeyHelper` is called after 5 minutes or on HTTP 401 response. Set `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` environment variable for custom refresh intervals.123* **Refresh intervals**: by default, `apiKeyHelper` is called after 5 minutes or on HTTP 401 response. Set `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` environment variable for custom refresh intervals.

channels.md +13 −8

Details

7> Use channels to push messages, alerts, and webhooks into your Claude Code session from an MCP server. Forward CI results, chat messages, and monitoring events so Claude can react while you're away.7> Use channels to push messages, alerts, and webhooks into your Claude Code session from an MCP server. Forward CI results, chat messages, and monitoring events so Claude can react while you're away.

8 8 

9<Note>9<Note>

10 Channels are in [research preview](#research-preview) and require Claude Code v2.1.80 or later. They require claude.ai login. Console and API key authentication is not supported. Team and Enterprise organizations must [explicitly enable them](#enterprise-controls).10 Channels are in [research preview](#research-preview) and require Claude Code v2.1.80 or later. They require Anthropic authentication through claude.ai or a Console API key, and are not available on Amazon Bedrock, Google Vertex AI, or Microsoft Foundry. Team and Enterprise organizations must [explicitly enable them](#enterprise-controls).

11</Note>11</Note>

12 12 

13A channel is an MCP server that pushes events into your running Claude Code session, so Claude can react to things that happen while you're not at the terminal. Channels can be two-way: Claude reads the event and replies back through the same channel, like a chat bridge. Events only arrive while the session is open, so for an always-on setup you run Claude in a background process or persistent terminal.13A channel is an MCP server that pushes events into your running Claude Code session, so Claude can react to things that happen while you're not at the terminal. Channels can be two-way: Claude reads the event and replies back through the same channel, like a chat bridge. Events only arrive while the session is open, so for an always-on setup you run Claude in a background process or persistent terminal.


23* [Supported channels](#supported-channels): Telegram, Discord, and iMessage setup23* [Supported channels](#supported-channels): Telegram, Discord, and iMessage setup

24* [Install and run a channel](#quickstart) with fakechat, a localhost demo24* [Install and run a channel](#quickstart) with fakechat, a localhost demo

25* [Who can push messages](#security): sender allowlists and how you pair25* [Who can push messages](#security): sender allowlists and how you pair

26* [Enable channels for your organization](#enterprise-controls) on Team and Enterprise26* [Enable channels for your organization](#enterprise-controls) if you manage a Team, Enterprise, or Console org

27* [How channels compare](#how-channels-compare) to web sessions, Slack, MCP, and Remote Control27* [How channels compare](#how-channels-compare) to web sessions, Slack, MCP, and Remote Control

28 28 

29To build your own channel, see the [Channels reference](/en/channels-reference).29To build your own channel, see the [Channels reference](/en/channels-reference).


225 225 

226To try the fakechat demo, you'll need:226To try the fakechat demo, you'll need:

227 227 

228* Claude Code [installed and authenticated](/en/quickstart#step-1-install-claude-code) with a claude.ai account228* Claude Code [installed and authenticated](/en/quickstart#step-1-install-claude-code) with a claude.ai account or a Claude Console API key

229* [Bun](https://bun.sh) installed. The pre-built channel plugins are Bun scripts. Check with `bun --version`; if that fails, [install Bun](https://bun.sh/docs/installation).229* [Bun](https://bun.sh) installed. The pre-built channel plugins are Bun scripts. Check with `bun --version`; if that fails, [install Bun](https://bun.sh/docs/installation).

230* **Team/Enterprise users**: your organization admin must [enable channels](#enterprise-controls) in managed settings230* **Team, Enterprise, or managed Console org**: your admin must [enable channels](#enterprise-controls) in managed settings

231 231 

232<Steps>232<Steps>

233 <Step title="Install the fakechat channel plugin">233 <Step title="Install the fakechat channel plugin">


280 280 

281iMessage works differently: texting yourself bypasses the gate automatically, and you add other contacts by handle with `/imessage:access allow`.281iMessage works differently: texting yourself bypasses the gate automatically, and you add other contacts by handle with `/imessage:access allow`.

282 282 

283On top of that, you control which servers are enabled each session with `--channels`, and on Team and Enterprise plans your organization controls availability with [`channelsEnabled`](#enterprise-controls).283On top of that, you control which servers are enabled each session with `--channels`, and your organization controls availability with [`channelsEnabled`](#enterprise-controls) on claude.ai Team and Enterprise plans and on Console organizations that deploy managed settings.

284 284 

285Being in `.mcp.json` isn't enough to push messages: a server also has to be named in `--channels`.285Being in `.mcp.json` isn't enough to push messages: a server also has to be named in `--channels`.

286 286 


288 288 

289## Enterprise controls289## Enterprise controls

290 290 

291On Team and Enterprise plans, channels are off by default. Admins control availability through two [managed settings](/en/settings) that users cannot override:291Admins control availability through two [managed settings](/en/settings) that users cannot override. The default depends on how you authenticate:

292 

293* **claude.ai Team and Enterprise**: channels are blocked until an admin enables them.

294* **Anthropic Console with API key authentication**: channels are permitted by default. You only need this setting if your organization deploys managed settings.

295 

296In all cases, no channel runs until a user opts it in for the session with `--channels`.

292 297 

293| Setting | Purpose | When not configured |298| Setting | Purpose | When not configured |

294| :---------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------- |299| :---------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

295| `channelsEnabled` | Master switch. Must be `true` for any channel to deliver messages. Set via the [claude.ai Admin console](https://claude.ai/admin-settings/claude-code) toggle or directly in managed settings. Blocks all channels including the development flag when off. | Channels blocked |300| `channelsEnabled` | Master switch. Must be `true` for any channel to deliver messages. Set via the [claude.ai Admin console](https://claude.ai/admin-settings/claude-code) toggle or directly in managed settings. Blocks all channels including the development flag when off. | claude.ai Team and Enterprise: channels blocked. Console: channels allowed unless your organization deploys managed settings, in which case channels are blocked until this key is set |

296| `allowedChannelPlugins` | Which plugins can register once channels are enabled. Replaces the Anthropic-maintained list when set. Only applies when `channelsEnabled` is `true`. | Anthropic default list applies |301| `allowedChannelPlugins` | Which plugins can register once channels are enabled. Replaces the Anthropic-maintained list when set. Only applies when `channelsEnabled` is `true`. | Anthropic default list applies |

297 302 

298Pro and Max users without an organization skip these checks entirely: channels are available and users opt in per session with `--channels`.303Pro and Max users without an organization skip these checks entirely: channels are available and users opt in per session with `--channels`.

Details

7> Build an MCP server that pushes webhooks, alerts, and chat messages into a Claude Code session. Reference for the channel contract: capability declaration, notification events, reply tools, sender gating, and permission relay.7> Build an MCP server that pushes webhooks, alerts, and chat messages into a Claude Code session. Reference for the channel contract: capability declaration, notification events, reply tools, sender gating, and permission relay.

8 8 

9<Note>9<Note>

10 Channels are in [research preview](/en/channels#research-preview) and require Claude Code v2.1.80 or later. They require claude.ai login. Console and API key authentication is not supported. Team and Enterprise organizations must [explicitly enable them](/en/channels#enterprise-controls).10 Channels are in [research preview](/en/channels#research-preview) and require Claude Code v2.1.80 or later. Team and Enterprise organizations must [explicitly enable them](/en/channels#enterprise-controls).

11</Note>11</Note>

12 12 

13A channel is an MCP server that pushes events into a Claude Code session so Claude can react to things happening outside the terminal.13A channel is an MCP server that pushes events into a Claude Code session so Claude can react to things happening outside the terminal.


138 138 

139 When Claude Code starts, it reads your MCP config, spawns your `webhook.ts` as a subprocess, and the HTTP listener starts automatically on the port you configured (8788 in this example). You don't need to run the server yourself.139 When Claude Code starts, it reads your MCP config, spawns your `webhook.ts` as a subprocess, and the HTTP listener starts automatically on the port you configured (8788 in this example). You don't need to run the server yourself.

140 140 

141 If you see "blocked by org policy," your Team or Enterprise admin needs to [enable channels](/en/channels#enterprise-controls) first.141 If you see "blocked by org policy," your organization admin needs to [enable channels](/en/channels#enterprise-controls) first.

142 142 

143 In a separate terminal, simulate a webhook by sending an HTTP POST with a message to your server. This example sends a CI failure alert to port 8788 (or whichever port you configured):143 In a separate terminal, simulate a webhook by sending an HTTP POST with a message to your server. This example sends a CI failure alert to port 8788 (or whichever port you configured):

144 144 

Details

185 185 

186If 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.186If 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.

187 187 

188Keep 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.

189 

188<Note>190<Note>

189 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 will fail to install packages if your environment uses **None** network access.191 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 will fail to install packages if your environment uses **None** network access.

190</Note>192</Note>

Details

83| `--output-format` | Specify output format for print mode (options: `text`, `json`, `stream-json`) | `claude -p "query" --output-format json` |83| `--output-format` | Specify output format for print mode (options: `text`, `json`, `stream-json`) | `claude -p "query" --output-format json` |

84| `--permission-mode` | Begin in a specified [permission mode](/en/permission-modes). Accepts `default`, `acceptEdits`, `plan`, `auto`, `dontAsk`, or `bypassPermissions`. Overrides `defaultMode` from settings files | `claude --permission-mode plan` |84| `--permission-mode` | Begin in a specified [permission mode](/en/permission-modes). Accepts `default`, `acceptEdits`, `plan`, `auto`, `dontAsk`, or `bypassPermissions`. Overrides `defaultMode` from settings files | `claude --permission-mode plan` |

85| `--permission-prompt-tool` | Specify an MCP tool to handle permission prompts in non-interactive mode | `claude -p --permission-prompt-tool mcp_auth_tool "query"` |85| `--permission-prompt-tool` | Specify an MCP tool to handle permission prompts in non-interactive mode | `claude -p --permission-prompt-tool mcp_auth_tool "query"` |

86| `--plugin-dir` | Load plugins from a directory for this session only. Each flag takes one path. Repeat the flag for multiple directories: `--plugin-dir A --plugin-dir B` | `claude --plugin-dir ./my-plugins` |86| `--plugin-dir` | Load a plugin from a directory or `.zip` archive for this session only. Each flag takes one path. Repeat the flag for multiple plugins: `--plugin-dir A --plugin-dir B.zip` | `claude --plugin-dir ./my-plugin` |

87| `--print`, `-p` | Print response without interactive mode (see [Agent SDK documentation](/en/agent-sdk/overview) for programmatic usage details) | `claude -p "query"` |87| `--print`, `-p` | Print response without interactive mode (see [Agent SDK documentation](/en/agent-sdk/overview) for programmatic usage details) | `claude -p "query"` |

88| `--remote` | Create a new [web session](/en/claude-code-on-the-web) on claude.ai with the provided task description | `claude --remote "Fix the login bug"` |88| `--remote` | Create a new [web session](/en/claude-code-on-the-web) on claude.ai with the provided task description | `claude --remote "Fix the login bug"` |

89| `--remote-control`, `--rc` | Start an interactive session with [Remote Control](/en/remote-control#start-a-remote-control-session) enabled so you can also control it from claude.ai or the Claude app. Optionally pass a name for the session | `claude --remote-control "My Project"` |89| `--remote-control`, `--rc` | Start an interactive session with [Remote Control](/en/remote-control#start-a-remote-control-session) enabled so you can also control it from claude.ai or the Claude app. Optionally pass a name for the session | `claude --remote-control "My Project"` |

commands.md +3 −3

Details

29| `/chrome` | Configure [Claude in Chrome](/en/chrome) settings |29| `/chrome` | Configure [Claude in Chrome](/en/chrome) settings |

30| `/claude-api [migrate\|managed-agents-onboard]` | **[Skill](/en/skills#bundled-skills).** Load Claude API reference material for your project's language (Python, TypeScript, Java, Go, Ruby, C#, PHP, or cURL) and Managed Agents reference. Covers tool use, streaming, batches, structured outputs, and common pitfalls. Also activates automatically when your code imports `anthropic` or `@anthropic-ai/sdk`. Run `/claude-api migrate` to upgrade existing Claude API code to a newer model: Claude asks which files to scan and which model to target, then updates model IDs, thinking configuration, and other parameters that changed between versions. Run `/claude-api managed-agents-onboard` for an interactive walkthrough that creates a new Managed Agent from scratch |30| `/claude-api [migrate\|managed-agents-onboard]` | **[Skill](/en/skills#bundled-skills).** Load Claude API reference material for your project's language (Python, TypeScript, Java, Go, Ruby, C#, PHP, or cURL) and Managed Agents reference. Covers tool use, streaming, batches, structured outputs, and common pitfalls. Also activates automatically when your code imports `anthropic` or `@anthropic-ai/sdk`. Run `/claude-api migrate` to upgrade existing Claude API code to a newer model: Claude asks which files to scan and which model to target, then updates model IDs, thinking configuration, and other parameters that changed between versions. Run `/claude-api managed-agents-onboard` for an interactive walkthrough that creates a new Managed Agent from scratch |

31| `/clear` | Start a new conversation with empty context. The previous conversation stays available in `/resume`. To free up context while continuing the same conversation, use `/compact` instead. Aliases: `/reset`, `/new` |31| `/clear` | Start a new conversation with empty context. The previous conversation stays available in `/resume`. To free up context while continuing the same conversation, use `/compact` instead. Aliases: `/reset`, `/new` |

32| `/color [color\|default]` | Set the prompt bar color for the current session. Available colors: `red`, `blue`, `green`, `yellow`, `purple`, `orange`, `pink`, `cyan`. Use `default` to reset. When [Remote Control](/en/remote-control) is connected, the color syncs to claude.ai/code |32| `/color [color\|default]` | Set the prompt bar color for the current session. Available colors: `red`, `blue`, `green`, `yellow`, `purple`, `orange`, `pink`, `cyan`. Use `default` to reset, or run with no argument to pick a random color. When [Remote Control](/en/remote-control) is connected, the color syncs to claude.ai/code |

33| `/compact [instructions]` | Free up context by summarizing the conversation so far. Optionally pass focus instructions for the summary. See [how compaction handles rules, skills, and memory files](/en/context-window#what-survives-compaction) |33| `/compact [instructions]` | Free up context by summarizing the conversation so far. Optionally pass focus instructions for the summary. See [how compaction handles rules, skills, and memory files](/en/context-window#what-survives-compaction) |

34| `/config` | Open the [Settings](/en/settings) interface to adjust theme, model, [output style](/en/output-styles), and other preferences. Alias: `/settings` |34| `/config` | Open the [Settings](/en/settings) interface to adjust theme, model, [output style](/en/output-styles), and other preferences. Alias: `/settings` |

35| `/context` | Visualize current context usage as a colored grid. Shows optimization suggestions for context-heavy tools, memory bloat, and capacity warnings |35| `/context` | Visualize current context usage as a colored grid. Shows optimization suggestions for context-heavy tools, memory bloat, and capacity warnings |


46| `/fast [on\|off]` | Toggle [fast mode](/en/fast-mode) on or off |46| `/fast [on\|off]` | Toggle [fast mode](/en/fast-mode) on or off |

47| `/feedback [report]` | Submit feedback about Claude Code. Alias: `/bug` |47| `/feedback [report]` | Submit feedback about Claude Code. Alias: `/bug` |

48| `/fewer-permission-prompts` | **[Skill](/en/skills#bundled-skills).** Scan your transcripts for common read-only Bash and MCP tool calls, then add a prioritized allowlist to project `.claude/settings.json` to reduce permission prompts |48| `/fewer-permission-prompts` | **[Skill](/en/skills#bundled-skills).** Scan your transcripts for common read-only Bash and MCP tool calls, then add a prioritized allowlist to project `.claude/settings.json` to reduce permission prompts |

49| `/focus` | Toggle the focus view, which shows only your last prompt, a one-line tool-call summary with edit diffstats, and the final response. The selection persists across sessions. Only available in [fullscreen rendering](/en/fullscreen) |49| `/focus` | Toggle the focus view, which shows only your last prompt, a one-line tool-call summary with edit diffstats, and the final response. The selection persists across sessions; set [`viewMode`](/en/settings#available-settings) in settings to override it. Only available in [fullscreen rendering](/en/fullscreen) |

50| `/heapdump` | Write a JavaScript heap snapshot and a memory breakdown to `~/Desktop`, or your home directory on Linux without a Desktop folder, for diagnosing high memory usage. See [troubleshooting](/en/troubleshooting#high-cpu-or-memory-usage) |50| `/heapdump` | Write a JavaScript heap snapshot and a memory breakdown to `~/Desktop`, or your home directory on Linux without a Desktop folder, for diagnosing high memory usage. See [troubleshooting](/en/troubleshooting#high-cpu-or-memory-usage) |

51| `/help` | Show help and available commands |51| `/help` | Show help and available commands |

52| `/hooks` | View [hook](/en/hooks) configurations for tool events |52| `/hooks` | View [hook](/en/hooks) configurations for tool events |


91| `/statusline` | Configure Claude Code's [status line](/en/statusline). Describe what you want, or run without arguments to auto-configure from your shell prompt |91| `/statusline` | Configure Claude Code's [status line](/en/statusline). Describe what you want, or run without arguments to auto-configure from your shell prompt |

92| `/stickers` | Order Claude Code stickers |92| `/stickers` | Order Claude Code stickers |

93| `/tasks` | List and manage background tasks. Also available as `/bashes` |93| `/tasks` | List and manage background tasks. Also available as `/bashes` |

94| `/team-onboarding` | Generate a team onboarding guide from your Claude Code usage history. Claude analyzes your sessions, commands, and MCP server usage from the past 30 days and produces a markdown guide a teammate can paste as a first message to get set up quickly |94| `/team-onboarding` | Generate a team onboarding guide from your Claude Code usage history. Claude analyzes your sessions, commands, and MCP server usage from the past 30 days and produces a markdown guide a teammate can paste as a first message to get set up quickly. For claude.ai subscribers on Pro, Max, Team, and Enterprise plans, also returns a share link teammates can open directly in Claude Code |

95| `/teleport` | Pull a [Claude Code on the web](/en/claude-code-on-the-web#from-web-to-terminal) session into this terminal: opens a picker, then fetches the branch and conversation. Also available as `/tp`. Requires a claude.ai subscription |95| `/teleport` | Pull a [Claude Code on the web](/en/claude-code-on-the-web#from-web-to-terminal) session into this terminal: opens a picker, then fetches the branch and conversation. Also available as `/tp`. Requires a claude.ai subscription |

96| `/terminal-setup` | Configure terminal keybindings for Shift+Enter and other shortcuts. Only visible in terminals that need it, like VS Code, Cursor, Windsurf, Alacritty, or Zed |96| `/terminal-setup` | Configure terminal keybindings for Shift+Enter and other shortcuts. Only visible in terminals that need it, like VS Code, Cursor, Windsurf, Alacritty, or Zed |

97| `/theme` | Change the color theme. Includes an `auto` option that matches your terminal's light or dark background, light and dark variants, colorblind-accessible (daltonized) themes, ANSI themes that use your terminal's color palette, and any [custom themes](/en/terminal-config#create-a-custom-theme) from `~/.claude/themes/` or plugins. Select **New custom theme…** to create one |97| `/theme` | Change the color theme. Includes an `auto` option that matches your terminal's light or dark background, light and dark variants, colorblind-accessible (daltonized) themes, ANSI themes that use your terminal's color palette, and any [custom themes](/en/terminal-config#create-a-custom-theme) from `~/.claude/themes/` or plugins. Select **New custom theme…** to create one |

data-usage.md +4 −4

Details

67 67 

68The diagram below shows how Claude Code connects to external services during installation and normal operation. Solid lines indicate required connections, while dashed lines represent optional or user-initiated data flows.68The diagram below shows how Claude Code connects to external services during installation and normal operation. Solid lines indicate required connections, while dashed lines represent optional or user-initiated data flows.

69 69 

70<img src="https://mintcdn.com/claude-code/YcBW2H7CArGcduPb/images/claude-code-data-flow.svg?fit=max&auto=format&n=YcBW2H7CArGcduPb&q=85&s=b600a89f84fc86f9ff7be00a466c0635" alt="Diagram showing Claude Code's external connections: install/update connects to the distribution server, and user requests connect to Anthropic services including Console auth, public-api, and optionally Statsig, Sentry, and bug reporting" width="720" height="520" data-path="images/claude-code-data-flow.svg" />70<img src="https://mintcdn.com/claude-code/RcOyXc06Ja8cuvMZ/images/claude-code-data-flow.svg?fit=max&auto=format&n=RcOyXc06Ja8cuvMZ&q=85&s=b5be40abf333defe984993af89546c19" alt="Diagram showing Claude Code's external connections: install/update connects to the distribution server, and user requests connect to Anthropic services including Console auth, public-api, and optionally metrics, Sentry, and bug reporting" width="720" height="520" data-path="images/claude-code-data-flow.svg" />

71 71 

72Claude Code runs locally. To interact with the LLM, Claude Code sends data over the network. This data includes all user prompts and model outputs, encrypted in transit via TLS 1.2+. Claude Code is compatible with most popular VPNs and LLM proxies.72Claude Code runs locally. To interact with the LLM, Claude Code sends data over the network. This data includes all user prompts and model outputs, encrypted in transit via TLS 1.2+. Claude Code is compatible with most popular VPNs and LLM proxies.

73 73 


95 95 

96## Telemetry services96## Telemetry services

97 97 

98Claude Code connects from users' machines to the Statsig service to log operational metrics such as latency, reliability, and usage patterns. This logging does not include any code or file paths. Data is encrypted in transit using TLS and at rest using 256-bit AES encryption. Read more in the [Statsig security documentation](https://www.statsig.com/trust/security). To opt out of Statsig telemetry, set the `DISABLE_TELEMETRY` environment variable.98Claude Code connects from users' machines to Anthropic to log operational metrics such as latency, reliability, and usage patterns. This logging does not include any code or file paths. Data is encrypted in transit and at rest. To opt out of telemetry, set the `DISABLE_TELEMETRY` environment variable.

99 99 

100Claude Code connects from users' machines to Sentry for operational error logging. The data is encrypted in transit using TLS and at rest using 256-bit AES encryption. Read more in the [Sentry security documentation](https://sentry.io/security/). To opt out of error logging, set the `DISABLE_ERROR_REPORTING` environment variable.100Claude Code connects from users' machines to Sentry for operational error logging. The data is encrypted in transit using TLS and at rest using 256-bit AES encryption. Read more in the [Sentry security documentation](https://sentry.io/security/). To opt out of error logging, set the `DISABLE_ERROR_REPORTING` environment variable.

101 101 


107 107 

108| Service | Claude API | Vertex API | Bedrock API | Foundry API |108| Service | Claude API | Vertex API | Bedrock API | Foundry API |

109| ------------------------------------ | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |109| ------------------------------------ | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |

110| **Statsig (Metrics)** | Default on.<br />`DISABLE_TELEMETRY=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. |110| **Anthropic (Metrics)** | Default on.<br />`DISABLE_TELEMETRY=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. |

111| **Sentry (Errors)** | Default on.<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. |111| **Sentry (Errors)** | Default on.<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. |

112| **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. |112| **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. |

113| **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. |113| **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. |


115 115 

116All environment variables can be checked into `settings.json` (see [settings reference](/en/settings)).116All environment variables can be checked into `settings.json` (see [settings reference](/en/settings)).

117 117 

118As of v2.1.126, when a host platform sets `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST`, Statsig metrics default to on for Vertex, Bedrock, and Foundry, and follow the standard `DISABLE_TELEMETRY` opt-out. Sentry error reporting and `/feedback` reports remain off by default on those providers.118As of v2.1.126, when a host platform sets `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST`, metrics default to on for Vertex, Bedrock, and Foundry, and follow the standard `DISABLE_TELEMETRY` opt-out. Sentry error reporting and `/feedback` reports remain off by default on those providers.

119 119 

120### WebFetch domain safety check120### WebFetch domain safety check

121 121 

desktop.md +2 −0

Details

284 284 

285Click **+ New session** in the sidebar, or press **Cmd+N** on macOS or **Ctrl+N** on Windows, to work on multiple tasks in parallel. Press **Ctrl+Tab** and **Ctrl+Shift+Tab** to cycle through sessions in the sidebar. For Git repositories, each session gets its own isolated copy of your project using [Git worktrees](/en/worktrees), so changes in one session don't affect other sessions until you commit them.285Click **+ New session** in the sidebar, or press **Cmd+N** on macOS or **Ctrl+N** on Windows, to work on multiple tasks in parallel. Press **Ctrl+Tab** and **Ctrl+Shift+Tab** to cycle through sessions in the sidebar. For Git repositories, each session gets its own isolated copy of your project using [Git worktrees](/en/worktrees), so changes in one session don't affect other sessions until you commit them.

286 286 

287To view two sessions at once, hold **Cmd** on macOS or **Ctrl** on Windows and click a session in the sidebar. The session opens in a second pane alongside the one you already have open. While the split is active, clicking another sidebar session replaces whichever pane has focus. Press **Cmd+\\** on macOS or **Ctrl+\\** on Windows to close the focused pane and return to a single session.

288 

287Worktrees are stored in `<project-root>/.claude/worktrees/` by default. You can change this to a custom directory in Settings → Claude Code under "Worktree location". You can also set a branch prefix that gets prepended to every worktree branch name, which is useful for keeping Claude-created branches organized. To remove a worktree when you're done, hover over the session in the sidebar and click the archive icon. To have sessions archive themselves when their pull request merges or closes, turn on **Auto-archive after PR merge or close** in Settings → Claude Code. Auto-archive only applies to local sessions that have finished running.289Worktrees are stored in `<project-root>/.claude/worktrees/` by default. You can change this to a custom directory in Settings → Claude Code under "Worktree location". You can also set a branch prefix that gets prepended to every worktree branch name, which is useful for keeping Claude-created branches organized. To remove a worktree when you're done, hover over the session in the sidebar and click the archive icon. To have sessions archive themselves when their pull request merges or closes, turn on **Auto-archive after PR merge or close** in Settings → Claude Code. Auto-archive only applies to local sessions that have finished running.

288 290 

289To include gitignored files like `.env` in new worktrees, create a [`.worktreeinclude` file](/en/worktrees#copy-gitignored-files-into-worktrees) in your project root.291To include gitignored files like `.env` in new worktrees, create a [`.worktreeinclude` file](/en/worktrees#copy-gitignored-files-into-worktrees) in your project root.

env-vars.md +3 −3

Details

60| `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](/en/llm-gateway). Anthropic API caching is unaffected |60| `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](/en/llm-gateway). Anthropic API caching is unaffected |

61| `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](/en/model-config#extended-context) models. 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 |61| `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](/en/model-config#extended-context) models. 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 |

62| `CLAUDE_CODE_AUTO_CONNECT_IDE` | Override automatic [IDE connection](/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 |62| `CLAUDE_CODE_AUTO_CONNECT_IDE` | Override automatic [IDE connection](/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 |

63| `CLAUDE_CODE_CERT_STORE` | Comma-separated list of CA certificate sources for TLS connections. `bundled` is the Mozilla CA set shipped with Claude Code. `system` is the operating system trust store. Default is `bundled,system`. The native binary distribution is required for system store integration. On the Node.js runtime, only the bundled set is used regardless of this value |63| `CLAUDE_CODE_CERT_STORE` | Comma-separated list of CA certificate sources for TLS connections. `bundled` is the Mozilla CA set shipped with Claude Code. `system` is the operating system trust store. Default is `bundled,system` |

64| `CLAUDE_CODE_CLIENT_CERT` | Path to client certificate file for mTLS authentication |64| `CLAUDE_CODE_CLIENT_CERT` | Path to client certificate file for mTLS authentication |

65| `CLAUDE_CODE_CLIENT_KEY` | Path to client private key file for mTLS authentication |65| `CLAUDE_CODE_CLIENT_KEY` | Path to client private key file for mTLS authentication |

66| `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE` | Passphrase for encrypted CLAUDE\_CODE\_CLIENT\_KEY (optional) |66| `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE` | Passphrase for encrypted CLAUDE\_CODE\_CLIENT\_KEY (optional) |


181| `DISABLE_PROMPT_CACHING_HAIKU` | Set to `1` to disable prompt caching for Haiku models |181| `DISABLE_PROMPT_CACHING_HAIKU` | Set to `1` to disable prompt caching for Haiku models |

182| `DISABLE_PROMPT_CACHING_OPUS` | Set to `1` to disable prompt caching for Opus models |182| `DISABLE_PROMPT_CACHING_OPUS` | Set to `1` to disable prompt caching for Opus models |

183| `DISABLE_PROMPT_CACHING_SONNET` | Set to `1` to disable prompt caching for Sonnet models |183| `DISABLE_PROMPT_CACHING_SONNET` | Set to `1` to disable prompt caching for Sonnet models |

184| `DISABLE_TELEMETRY` | Set to `1` to opt out of Statsig telemetry (note that Statsig events do not include user data like code, file paths, or bash commands) |184| `DISABLE_TELEMETRY` | Set to `1` to opt out of telemetry. Telemetry events do not include user data like code, file paths, or bash commands |

185| `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 |185| `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 |

186| `DISABLE_UPGRADE_COMMAND` | Set to `1` to hide the `/upgrade` command |186| `DISABLE_UPGRADE_COMMAND` | Set to `1` to hide the `/upgrade` command |

187| `ENABLE_CLAUDEAI_MCP_SERVERS` | Set to `false` to disable [claude.ai MCP servers](/en/mcp#use-mcp-servers-from-claude-ai) in Claude Code. Enabled by default for logged-in users |187| `ENABLE_CLAUDEAI_MCP_SERVERS` | Set to `false` to disable [claude.ai MCP servers](/en/mcp#use-mcp-servers-from-claude-ai) in Claude Code. Enabled by default for logged-in users |


198| `MAX_STRUCTURED_OUTPUT_RETRIES` | Number of times to retry when the model's response fails validation against the [`--json-schema`](/en/cli-reference#cli-flags) in non-interactive mode (the `-p` flag). Defaults to 5 |198| `MAX_STRUCTURED_OUTPUT_RETRIES` | Number of times to retry when the model's response fails validation against the [`--json-schema`](/en/cli-reference#cli-flags) in non-interactive mode (the `-p` flag). Defaults to 5 |

199| `MAX_THINKING_TOKENS` | Override the [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) token budget. The ceiling is the model's [max output tokens](https://platform.claude.com/docs/en/about-claude/models/overview#latest-models-comparison) minus one. Set to `0` to disable thinking entirely. On models with [adaptive reasoning](/en/model-config#adjust-effort-level), the budget is ignored unless adaptive reasoning is disabled via `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` |199| `MAX_THINKING_TOKENS` | Override the [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) token budget. The ceiling is the model's [max output tokens](https://platform.claude.com/docs/en/about-claude/models/overview#latest-models-comparison) minus one. Set to `0` to disable thinking entirely. On models with [adaptive reasoning](/en/model-config#adjust-effort-level), the budget is ignored unless adaptive reasoning is disabled via `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` |

200| `MCP_CLIENT_SECRET` | OAuth client secret for MCP servers that require [pre-configured credentials](/en/mcp#use-pre-configured-oauth-credentials). Avoids the interactive prompt when adding a server with `--client-secret` |200| `MCP_CLIENT_SECRET` | OAuth client secret for MCP servers that require [pre-configured credentials](/en/mcp#use-pre-configured-oauth-credentials). Avoids the interactive prompt when adding a server with `--client-secret` |

201| `MCP_CONNECTION_NONBLOCKING` | Set to `true` in non-interactive mode (`-p`) to skip the MCP connection wait entirely. Useful for scripted pipelines where MCP tools are not needed. Without this variable, the first query waits up to 5 seconds for `--mcp-config` server connections |201| `MCP_CONNECTION_NONBLOCKING` | Set to `true` in non-interactive mode (`-p`) to skip the MCP connection wait entirely. Useful for scripted pipelines where MCP tools are not needed. Without this variable, the first query waits up to 5 seconds for `--mcp-config` server connections. Servers configured with [`alwaysLoad: true`](/en/mcp#exempt-a-server-from-deferral) always block startup regardless of this variable, since their tools must be present when the first prompt is built |

202| `MCP_OAUTH_CALLBACK_PORT` | Fixed port for the OAuth redirect callback, as an alternative to `--callback-port` when adding an MCP server with [pre-configured credentials](/en/mcp#use-pre-configured-oauth-credentials) |202| `MCP_OAUTH_CALLBACK_PORT` | Fixed port for the OAuth redirect callback, as an alternative to `--callback-port` when adding an MCP server with [pre-configured credentials](/en/mcp#use-pre-configured-oauth-credentials) |

203| `MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE` | Maximum number of remote MCP servers (HTTP/SSE) to connect in parallel during startup (default: 20) |203| `MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE` | Maximum number of remote MCP servers (HTTP/SSE) to connect in parallel during startup (default: 20) |

204| `MCP_SERVER_CONNECTION_BATCH_SIZE` | Maximum number of local MCP servers (stdio) to connect in parallel during startup (default: 3) |204| `MCP_SERVER_CONNECTION_BATCH_SIZE` | Maximum number of local MCP servers (stdio) to connect in parallel during startup (default: 3) |

errors.md +3 −3

Details

307* Ensure your firewall allows the hosts listed in [Network access requirements](/en/network-config#network-access-requirements)307* Ensure your firewall allows the hosts listed in [Network access requirements](/en/network-config#network-access-requirements)

308* Intermittent failures are [retried automatically](#automatic-retries); persistent failures point to a local network issue308* Intermittent failures are [retried automatically](#automatic-retries); persistent failures point to a local network issue

309 309 

310If `curl` succeeds but Claude Code still fails, the cause is usually something between Node.js and the network rather than the network itself:310If `curl` succeeds but Claude Code still fails, the cause is usually something between the runtime and the network rather than the network itself:

311 311 

312* On Linux and WSL, check `/etc/resolv.conf` for an unreachable nameserver. WSL in particular can inherit a broken resolver from the host.312* On Linux and WSL, check `/etc/resolv.conf` for an unreachable nameserver. WSL in particular can inherit a broken resolver from the host.

313* On macOS, a VPN client that was disconnected or uninstalled can leave a tunnel interface or routing rule behind. Check `ifconfig` for stale `utun` interfaces and remove the VPN's network extension in System Settings.313* On macOS, a VPN client that was disconnected or uninstalled can leave a tunnel interface or routing rule behind. Check `ifconfig` for stale `utun` interfaces and remove the VPN's network extension in System Settings.


315 315 

316### SSL certificate errors316### SSL certificate errors

317 317 

318A proxy or security appliance on your network is intercepting TLS traffic with its own certificate, and Node.js does not trust it.318A proxy or security appliance on your network is intercepting TLS traffic with its own certificate, and Claude Code does not trust it.

319 319 

320```text theme={null}320```text theme={null}

321Unable to connect to API: SSL certificate verification failed. Check your proxy or corporate SSL certificates321Unable to connect to API: SSL certificate verification failed. Check your proxy or corporate SSL certificates


324 324 

325**What to do:**325**What to do:**

326 326 

327* Export your organization's CA bundle and point Node at it with `NODE_EXTRA_CA_CERTS=/path/to/ca-bundle.pem`327* Export your organization's CA bundle and point Claude Code at it with `NODE_EXTRA_CA_CERTS=/path/to/ca-bundle.pem`

328* See [Network configuration](/en/network-config#custom-ca-certificates) for full setup instructions328* See [Network configuration](/en/network-config#custom-ca-certificates) for full setup instructions

329* Do not set `NODE_TLS_REJECT_UNAUTHORIZED=0`, which disables certificate validation entirely329* Do not set `NODE_TLS_REJECT_UNAUTHORIZED=0`, which disables certificate validation entirely

330 330 

Details

71 * **Subagents** are isolated workers that run separately from your main conversation71 * **Subagents** are isolated workers that run separately from your main conversation

72 72 

73 | Aspect | Skill | Subagent |73 | Aspect | Skill | Subagent |

74 | --------------- | ---------------------------------------------- | ---------------------------------------------------------------- |74 | ----------------------------------------------- | ---------------------------------------------- | ---------------------------------------------------------------- |

75 | **What it is** | Reusable instructions, knowledge, or workflows | Isolated worker with its own context |75 | **What it is** | Reusable instructions, knowledge, or workflows | Isolated worker with its own context |

76 | **Key benefit** | Share content across contexts | Context isolation. Work happens separately, only summary returns |76 | **Key benefit** | Share content across contexts | Context isolation. Work happens separately, only summary returns |

77 | **[Context window](/en/context-window) impact** | Adds to your main window | Uses a separate window with its own input and output tokens |

77 | **Best for** | Reference material, invocable workflows | Tasks that read many files, parallel work, specialized workers |78 | **Best for** | Reference material, invocable workflows | Tasks that read many files, parallel work, specialized workers |

78 79 

79 **Skills can be reference or action.** Reference skills provide knowledge Claude uses throughout your session (like your API style guide). Action skills tell Claude to do something specific (like `/deploy` that runs your deployment workflow).80 **Skills can be reference or action.** Reference skills provide knowledge Claude uses throughout your session (like your API style guide). Action skills tell Claude to do something specific (like `/deploy` that runs your deployment workflow).

fullscreen.md +3 −1

Details

122 122 

123## Use with tmux123## Use with tmux

124 124 

125Fullscreen rendering works inside tmux, with two caveats.125Fullscreen rendering works inside tmux, with three caveats.

126 126 

127Mouse wheel scrolling requires tmux's mouse mode. If your `~/.tmux.conf` does not already enable it, add this line and reload your config:127Mouse wheel scrolling requires tmux's mouse mode. If your `~/.tmux.conf` does not already enable it, add this line and reload your config:

128 128 


134 134 

135Fullscreen rendering is incompatible with iTerm2's tmux integration mode, which is the mode you enter with `tmux -CC`. In integration mode, iTerm2 renders each tmux pane as a native split rather than letting tmux draw to the terminal. The alternate screen buffer and mouse tracking do not work correctly there: the mouse wheel does nothing, and double-click can corrupt the terminal state. Don't enable fullscreen rendering in `tmux -CC` sessions. Regular tmux inside iTerm2, without `-CC`, works fine.135Fullscreen rendering is incompatible with iTerm2's tmux integration mode, which is the mode you enter with `tmux -CC`. In integration mode, iTerm2 renders each tmux pane as a native split rather than letting tmux draw to the terminal. The alternate screen buffer and mouse tracking do not work correctly there: the mouse wheel does nothing, and double-click can corrupt the terminal state. Don't enable fullscreen rendering in `tmux -CC` sessions. Regular tmux inside iTerm2, without `-CC`, works fine.

136 136 

137tmux does not support synchronized output, so you may see more flicker during redraws than when running Claude Code directly in your terminal. If the flicker is noticeable, especially over SSH, run Claude Code in its own terminal tab outside tmux.

138 

137## Keep native text selection139## Keep native text selection

138 140 

139Mouse capture is the most common friction point, especially over SSH or inside tmux. When Claude Code captures mouse events, your terminal's native copy-on-select stops working. The selection you make with click-and-drag exists inside Claude Code, not in your terminal's selection buffer, so tmux copy mode, Kitty hints, and similar tools don't see it.141Mouse capture is the most common friction point, especially over SSH or inside tmux. When Claude Code captures mouse events, your terminal's native copy-on-select stops working. The selection you make with click-and-drag exists inside Claude Code, not in your terminal's selection buffer, so tmux copy mode, Kitty hints, and similar tools don't see it.

headless.md +6 −2

Details

78 78 

79With `--output-format json`, the response payload includes `total_cost_usd` and a per-model cost breakdown, so scripted callers can track spend per invocation without consulting the [usage dashboard](/en/costs).79With `--output-format json`, the response payload includes `total_cost_usd` and a per-model cost breakdown, so scripted callers can track spend per invocation without consulting the [usage dashboard](/en/costs).

80 80 

81<Note>

82 As of Claude Code v2.1.128, piped stdin is capped at 10MB. If you exceed the cap, Claude Code exits with a clear error and a non-zero status. To work with larger inputs, write the content to a file and reference the file path in your prompt instead of piping it.

83</Note>

84 

81### Add Claude to a build script85### Add Claude to a build script

82 86 

83You can wrap a non-interactive call in a script to use Claude as a project-specific linter or reviewer.87You can wrap a non-interactive call in a script to use Claude as a project-specific linter or reviewer.


163The `system/init` event reports session metadata including the model, tools, MCP servers, and loaded plugins. It is the first event in the stream unless [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](/en/env-vars) is set, in which case `plugin_install` events precede it. Use the plugin fields to fail CI when a plugin did not load:167The `system/init` event reports session metadata including the model, tools, MCP servers, and loaded plugins. It is the first event in the stream unless [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](/en/env-vars) is set, in which case `plugin_install` events precede it. Use the plugin fields to fail CI when a plugin did not load:

164 168 

165| Field | Type | Description |169| Field | Type | Description |

166| --------------- | ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |170| --------------- | ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

167| `plugins` | array | plugins that loaded successfully, each with `name` and `path` |171| `plugins` | array | plugins that loaded successfully, each with `name` and `path` |

168| `plugin_errors` | array | plugin load-time errors such as an unsatisfied dependency version, each with `plugin`, `type`, and `message`. Affected plugins are demoted and absent from `plugins`. The key is omitted when there are no errors |172| `plugin_errors` | array | plugin load-time errors, each with `plugin`, `type`, and `message`. Includes unsatisfied dependency versions and `--plugin-dir` load failures such as a missing path or invalid archive. Affected plugins are demoted and absent from `plugins`. The key is omitted when there are no errors |

169 173 

170When [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](/en/env-vars) is set, Claude Code emits `system/plugin_install` events while marketplace plugins install before the first turn. Use these to surface install progress in your own UI.174When [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](/en/env-vars) is set, Claude Code emits `system/plugin_install` events while marketplace plugins install before the first turn. Use these to surface install progress in your own UI.

171 175 

hooks.md +6 −6

Details

976| `decision` | `"block"` prevents the prompt from being processed and erases it from context. Omit to allow the prompt to proceed |976| `decision` | `"block"` prevents the prompt from being processed and erases it from context. Omit to allow the prompt to proceed |

977| `reason` | Shown to the user when `decision` is `"block"`. Not added to context |977| `reason` | Shown to the user when `decision` is `"block"`. Not added to context |

978| `additionalContext` | String added to Claude's context alongside the submitted prompt. See [Add context for Claude](#add-context-for-claude) |978| `additionalContext` | String added to Claude's context alongside the submitted prompt. See [Add context for Claude](#add-context-for-claude) |

979| `sessionTitle` | Sets the session title, same effect as `/rename`. Use to name sessions automatically based on the prompt content |979| `sessionTitle` | Sets the session title. Use to name sessions automatically based on the prompt content |

980 980 

981```json theme={null}981```json theme={null}

982{982{


1360`PostToolUse` hooks can provide feedback to Claude after tool execution. In addition to the [JSON output fields](#json-output) available to all hooks, your hook script can return these event-specific fields:1360`PostToolUse` hooks can provide feedback to Claude after tool execution. In addition to the [JSON output fields](#json-output) available to all hooks, your hook script can return these event-specific fields:

1361 1361 

1362| Field | Description |1362| Field | Description |

1363| :--------------------- | :--------------------------------------------------------------------------------------------------------------------------- |1363| :--------------------- | :--------------------------------------------------------------------------------------------------------------------------------- |

1364| `decision` | `"block"` prompts Claude with the `reason`. Omit to allow the action to proceed |1364| `decision` | `"block"` adds the `reason` next to the tool result. Claude still sees the original output; to replace it, use `updatedToolOutput` |

1365| `reason` | Explanation shown to Claude when `decision` is `"block"` |1365| `reason` | Explanation shown to Claude when `decision` is `"block"` |

1366| `additionalContext` | String added to Claude's context alongside the tool result. See [Add context for Claude](#add-context-for-claude) |1366| `additionalContext` | String added to Claude's context alongside the tool result. See [Add context for Claude](#add-context-for-claude) |

1367| `updatedToolOutput` | Replaces the tool's output with the provided value before it is sent to Claude. The value must match the tool's output shape |1367| `updatedToolOutput` | Replaces the tool's output with the provided value before it is sent to Claude. The value must match the tool's output shape |


2413```2413```

2414 2414 

2415| Field | Description |2415| Field | Description |

2416| :------- | :------------------------------------------------------- |2416| :------- | :------------------------------------------------------------------ |

2417| `ok` | `true` allows the action, `false` blocks it |2417| `ok` | `true` to allow, `false` to block. See the per-event behavior below |

2418| `reason` | Required when `ok` is `false`. Explanation for the block |2418| `reason` | Required when `ok` is `false`. Explanation for the decision |

2419 2419 

2420What happens on `ok: false` depends on the event:2420What happens on `ok: false` depends on the event:

2421 2421 

Details

130| Command | Action |130| Command | Action |

131| :-------------- | :-------------------------------------------------- |131| :-------------- | :-------------------------------------------------- |

132| `h`/`j`/`k`/`l` | Move left/down/up/right |132| `h`/`j`/`k`/`l` | Move left/down/up/right |

133| `Space` | Move right |

133| `w` | Next word |134| `w` | Next word |

134| `e` | End of word |135| `e` | End of word |

135| `b` | Previous word |136| `b` | Previous word |

mcp.md +6 −0

Details

327/mcp327/mcp

328```328```

329 329 

330The `/mcp` panel shows the tool count next to each connected server and flags servers that advertise the tools capability but expose no tools.

331 

332The server name `workspace` is reserved for internal use. If your configuration defines a server with that name, Claude Code skips it at load time and shows a warning asking you to rename it.

333 

330### Dynamic tool updates334### Dynamic tool updates

331 335 

332Claude Code supports MCP `list_changed` notifications, allowing MCP servers to dynamically update their available tools, prompts, and resources without requiring you to disconnect and reconnect. When an MCP server sends a `list_changed` notification, Claude Code automatically refreshes the available capabilities from that server.336Claude Code supports MCP `list_changed` notifications, allowing MCP servers to dynamically update their available tools, prompts, and resources without requiring you to disconnect and reconnect. When an MCP server sends a `list_changed` notification, Claude Code automatically refreshes the available capabilities from that server.


1185 1189 

1186The `alwaysLoad` field is available on all server types and requires Claude Code v2.1.121 or later. An MCP server can also mark individual tools as always-loaded by including `"anthropic/alwaysLoad": true` in the tool's `_meta` object, which has the same effect for that tool only.1190The `alwaysLoad` field is available on all server types and requires Claude Code v2.1.121 or later. An MCP server can also mark individual tools as always-loaded by including `"anthropic/alwaysLoad": true` in the tool's `_meta` object, which has the same effect for that tool only.

1187 1191 

1192Setting `alwaysLoad: true` also blocks startup until the server connects, capped at the standard 5-second connect timeout. This applies even when [`MCP_CONNECTION_NONBLOCKING=1`](/en/env-vars) is set, since the tools must be present when the first prompt is built. Other servers still connect in the background when nonblocking is enabled.

1193 

1188## Use MCP prompts as commands1194## Use MCP prompts as commands

1189 1195 

1190MCP servers can expose prompts that become available as commands in Claude Code.1196MCP servers can expose prompts that become available as commands in Claude Code.

Details

64 Managed settings can be distributed via MDM (Mobile Device Management) or other device management solutions. Environment variables defined in the managed settings file have high precedence and cannot be overridden by users.64 Managed settings can be distributed via MDM (Mobile Device Management) or other device management solutions. Environment variables defined in the managed settings file have high precedence and cannot be overridden by users.

65</Note>65</Note>

66 66 

67Claude Code does not 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 does not 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.

68 

67## Configuration details69## Configuration details

68 70 

69### Common configuration variables71### Common configuration variables


80| `OTEL_EXPORTER_OTLP_LOGS_PROTOCOL` | Protocol for logs, overrides general setting | `grpc`, `http/json`, `http/protobuf` |82| `OTEL_EXPORTER_OTLP_LOGS_PROTOCOL` | Protocol for logs, overrides general setting | `grpc`, `http/json`, `http/protobuf` |

81| `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` | OTLP logs endpoint, overrides general setting | `http://localhost:4318/v1/logs` |83| `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` | OTLP logs endpoint, overrides general setting | `http://localhost:4318/v1/logs` |

82| `OTEL_EXPORTER_OTLP_HEADERS` | Authentication headers for OTLP | `Authorization=Bearer token` |84| `OTEL_EXPORTER_OTLP_HEADERS` | Authentication headers for OTLP | `Authorization=Bearer token` |

83| `OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY` | Client key for mTLS authentication | Path to client key file |

84| `OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE` | Client certificate for mTLS authentication | Path to client cert file |

85| `OTEL_METRIC_EXPORT_INTERVAL` | Export interval in milliseconds (default: 60000) | `5000`, `60000` |85| `OTEL_METRIC_EXPORT_INTERVAL` | Export interval in milliseconds (default: 60000) | `5000`, `60000` |

86| `OTEL_LOGS_EXPORT_INTERVAL` | Logs export interval in milliseconds (default: 5000) | `1000`, `10000` |86| `OTEL_LOGS_EXPORT_INTERVAL` | Logs export interval in milliseconds (default: 5000) | `1000`, `10000` |

87| `OTEL_LOG_USER_PROMPTS` | Enable logging of user prompt content (default: disabled) | `1` to enable |87| `OTEL_LOG_USER_PROMPTS` | Enable logging of user prompt content (default: disabled) | `1` to enable |


91| `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE` | Metrics temporality preference (default: `delta`). Set to `cumulative` if your backend expects cumulative temporality | `delta`, `cumulative` |91| `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE` | Metrics temporality preference (default: `delta`). Set to `cumulative` if your backend expects cumulative temporality | `delta`, `cumulative` |

92| `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` | Interval for refreshing dynamic headers (default: 1740000ms / 29 minutes) | `900000` |92| `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` | Interval for refreshing dynamic headers (default: 1740000ms / 29 minutes) | `900000` |

93 93 

94### mTLS authentication

95 

96How you configure client certificates for the OTLP exporter depends on the OTLP protocol in use for that signal, set via `OTEL_EXPORTER_OTLP_PROTOCOL` or the per-signal override. The same configuration applies to metrics, logs, and traces.

97 

98| Protocol | Client certificate variables | Trust the collector's CA with |

99| :--------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------- |

100| `http/protobuf`, `http/json` | `CLAUDE_CODE_CLIENT_CERT`, `CLAUDE_CODE_CLIENT_KEY`, and optionally `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE`. See [Network configuration](/en/network-config#mtls-authentication) | `NODE_EXTRA_CA_CERTS` |

101| `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` |

102 

103For `grpc`, the OpenTelemetry SDK reads the standard OTLP variables directly, so existing configurations that set the per-signal metrics variables continue to work.

104 

94### Metrics cardinality control105### Metrics cardinality control

95 106 

96The following environment variables control which attributes are included in metrics to manage cardinality:107The following environment variables control which attributes are included in metrics to manage cardinality:


107 118 

108Distributed 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.119Distributed 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.

109 120 

110Tracing 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, and headers.121Tracing 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).

111 122 

112| Environment Variable | Description | Example Values |123| Environment Variable | Description | Example Values |

113| ------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------ |124| ------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------ |


233 244 

234### Dynamic headers245### Dynamic headers

235 246 

236For enterprise environments that require dynamic authentication, you can configure a script to generate headers dynamically:247For enterprise environments that require dynamic authentication, you can configure a script to generate headers dynamically. Dynamic headers apply only to the `http/protobuf` and `http/json` protocols. The `grpc` exporter uses only the static `OTEL_EXPORTER_OTLP_HEADERS` value.

237 248 

238#### Settings configuration249#### Settings configuration

239 250 


899 910 

900**Performance Monitoring**: track API request durations and tool execution times to identify performance bottlenecks.911**Performance Monitoring**: track API request durations and tool execution times to identify performance bottlenecks.

901 912 

913## Audit security events

914 

915OpenTelemetry events are the audit data source for Claude Code activity. Every event carries identity attributes that tie tool calls, MCP activity, and permission decisions back to the user who triggered them, and the OTLP logs exporter can deliver these events to any Security Information and Event Management (SIEM) platform with an OTLP receiver or to an OpenTelemetry Collector that forwards to your SIEM.

916 

917### Attribute actions to users

918 

919The [standard attributes](#standard-attributes) on each event include the authenticated user's identity: `user.email`, `user.account_uuid`, `user.account_id`, and `organization.id` when signed in with a Claude account, plus the installation-scoped `user.id` and the per-session `session.id`.

920 

921MCP tool calls, Bash commands, and file edits are therefore attributed to the developer who started the session. Claude Code does not act under a separate service account; the identity recorded on each event is the developer's own Claude account.

922 

923When Claude Code authenticates with a direct API key, or against Bedrock, Vertex AI, or Microsoft Foundry, there is no Claude account in the session and only `user.id` and `session.id` are populated. In these deployments, attach user identity yourself with `OTEL_RESOURCE_ATTRIBUTES`, set per user through the [managed settings](#administrator-configuration) file or a launch wrapper:

924 

925```bash theme={null}

926export OTEL_RESOURCE_ATTRIBUTES="enduser.id=jdoe@example.com,enduser.directory_id=S-1-5-21-..."

927```

928 

929### Audit MCP activity

930 

931To capture MCP server activity with full call detail, enable the logs exporter and set `OTEL_LOG_TOOL_DETAILS=1`. Each MCP operation then produces structured events that carry the server name, tool name, and call arguments alongside the standard identity attributes:

932 

933| Event | What it records for MCP |

934| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

935| `mcp_server_connection` | Server connect, disconnect, and connection failure with `server_name`, `transport_type`, `server_scope`, and error detail |

936| `tool_result` | Each MCP tool call with `tool_name` and `mcp_server_scope`, a `tool_parameters` payload containing `mcp_server_name` and `mcp_tool_name`, and a `tool_input` payload containing the call arguments |

937| `tool_decision` | Whether the call was allowed or denied, and whether the decision came from config, a hook, or the user |

938 

939Without `OTEL_LOG_TOOL_DETAILS`, `tool_result` events still carry `tool_name` and `mcp_server_scope` but omit the `mcp_server_name`/`mcp_tool_name` breakdown and the arguments, and `mcp_server_connection` events omit `server_name` and the error message.

940 

941### Map security questions to events

942 

943When building detection rules, look up the signal you want to monitor and query your backend for the corresponding event and attributes:

944 

945| Signal | Event | Key attributes |

946| ----------------------------------------- | -------------------------------------------- | ------------------------------------------------------------ |

947| Tool call allowed or denied, and by what | `tool_decision` | `decision`, `source`, `tool_name` |

948| Permission mode escalation | `permission_mode_changed` | `from_mode`, `to_mode`, `trigger` |

949| Policy hook blocked an action | `hook_execution_complete` | `hook_event`, `num_blocking` |

950| Login, logout, and authentication failure | `auth` | `action`, `success`, `error_category` |

951| MCP server connect or failure | `mcp_server_connection` | `status`, `server_name`, `error_code` |

952| Plugin installed and its source | `plugin_installed` | `plugin.name`, `marketplace.name`, `marketplace.is_official` |

953| Commands run and files touched | `tool_result` with `OTEL_LOG_TOOL_DETAILS=1` | `tool_parameters`, `tool_input` |

954 

955Claude Code emits the raw event stream only. Anomaly detection, baselining, correlation across sessions, and alerting are the responsibility of your SIEM or observability backend.

956 

957### Send events to a SIEM

958 

959Point `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` at your SIEM's OTLP receiver, or at an OpenTelemetry Collector that forwards to your SIEM's native ingest API. The following managed-settings example exports events only, with full tool detail enabled for MCP and Bash auditing:

960 

961```json theme={null}

962{

963 "env": {

964 "CLAUDE_CODE_ENABLE_TELEMETRY": "1",

965 "OTEL_LOGS_EXPORTER": "otlp",

966 "OTEL_LOG_TOOL_DETAILS": "1",

967 "OTEL_EXPORTER_OTLP_LOGS_PROTOCOL": "http/protobuf",

968 "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT": "https://siem.example.com:4318/v1/logs",

969 "OTEL_EXPORTER_OTLP_HEADERS": "Authorization=Bearer your-siem-token"

970 }

971}

972```

973 

902## Backend considerations974## Backend considerations

903 975 

904Your choice of metrics, logs, and traces backends determines the types of analyses you can perform:976Your choice of metrics, logs, and traces backends determines the types of analyses you can perform:

Details

57 57 

58By default, Claude Code trusts both its bundled Mozilla CA certificates and your operating system's certificate store. Enterprise TLS-inspection proxies such as CrowdStrike Falcon and Zscaler work without additional configuration when their root certificate is installed in the OS trust store.58By default, Claude Code trusts both its bundled Mozilla CA certificates and your operating system's certificate store. Enterprise TLS-inspection proxies such as CrowdStrike Falcon and Zscaler work without additional configuration when their root certificate is installed in the OS trust store.

59 59 

60<Note>

61 System CA store integration requires the native Claude Code binary distribution. When running on the Node.js runtime, the system CA store is not merged automatically. In that case, set `NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem` to trust an enterprise root CA.

62</Note>

63 

64`CLAUDE_CODE_CERT_STORE` accepts a comma-separated list of sources. Recognized values are `bundled` for the Mozilla CA set shipped with Claude Code and `system` for the operating system trust store. The default is `bundled,system`.60`CLAUDE_CODE_CERT_STORE` accepts a comma-separated list of sources. Recognized values are `bundled` for the Mozilla CA set shipped with Claude Code and `system` for the operating system trust store. The default is `bundled,system`.

65 61 

66To trust only the bundled Mozilla CA set:62To trust only the bundled Mozilla CA set:


107Claude Code requires access to the following URLs. Allowlist these in your proxy configuration and firewall rules, especially in containerized or restricted network environments.103Claude Code requires access to the following URLs. Allowlist these in your proxy configuration and firewall rules, especially in containerized or restricted network environments.

108 104 

109| URL | Required for |105| URL | Required for |

110| ------------------------------ | ------------------------------------------------------------------------------------------------- |106| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- |

111| `api.anthropic.com` | Claude API requests |107| `api.anthropic.com` | Claude API requests |

112| `claude.ai` | claude.ai account authentication |108| `claude.ai` | claude.ai account authentication |

113| `platform.claude.com` | Anthropic Console account authentication |109| `platform.claude.com` | Anthropic Console account authentication |

114| `downloads.claude.ai` | Plugin executable downloads; native installer and native auto-updater |110| `downloads.claude.ai` | Plugin executable downloads; native installer and native auto-updater |

115| `storage.googleapis.com` | {/* max-version: 2.1.115 */}Native installer and native auto-updater on versions prior to 2.1.116 |111| `storage.googleapis.com` | {/* max-version: 2.1.115 */}Native installer and native auto-updater on versions prior to 2.1.116 |

116| `bridge.claudeusercontent.com` | [Claude in Chrome](/en/chrome) extension WebSocket bridge |112| `bridge.claudeusercontent.com` | [Claude in Chrome](/en/chrome) extension WebSocket bridge |

113| `raw.githubusercontent.com` | Changelog feed for [`/release-notes`](/en/commands) and the release notes shown after updating; plugin marketplace install counts |

117 114 

118If you install Claude Code through npm or manage your own binary distribution, end users may not need access to `downloads.claude.ai` or `storage.googleapis.com`.115If you install Claude Code through npm or manage your own binary distribution, end users may not need access to `downloads.claude.ai` or `storage.googleapis.com`.

119 116 

permissions.md +4 −4

Details

36| :------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------- |36| :------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------- |

37| `default` | Standard behavior: prompts for permission on first use of each tool |37| `default` | Standard behavior: prompts for permission on first use of each tool |

38| `acceptEdits` | Automatically accepts file edits and common filesystem commands (`mkdir`, `touch`, `mv`, `cp`, etc.) for paths in the working directory or `additionalDirectories` |38| `acceptEdits` | Automatically accepts file edits and common filesystem commands (`mkdir`, `touch`, `mv`, `cp`, etc.) for paths in the working directory or `additionalDirectories` |

39| `plan` | Plan Mode: Claude can analyze but not modify files or execute commands |39| `plan` | Plan Mode: Claude reads files and runs read-only shell commands to explore but does not edit your source files |

40| `auto` | Auto-approves tool calls with background safety checks that verify actions align with your request. Currently a research preview |40| `auto` | Auto-approves tool calls with background safety checks that verify actions align with your request. Currently a research preview |

41| `dontAsk` | Auto-denies tools unless pre-approved via `/permissions` or `permissions.allow` rules |41| `dontAsk` | Auto-denies tools unless pre-approved via `/permissions` or `permissions.allow` rules |

42| `bypassPermissions` | Skips all permission prompts. Root and home directory removals such as `rm -rf /` still prompt as a circuit breaker |42| `bypassPermissions` | Skips all permission prompts. Root and home directory removals such as `rm -rf /` still prompt as a circuit breaker |


296 296 

297* Permission deny rules block Claude from even attempting to access restricted resources297* Permission deny rules block Claude from even attempting to access restricted resources

298* Sandbox restrictions prevent Bash commands from reaching resources outside defined boundaries, even if a prompt injection bypasses Claude's decision-making298* Sandbox restrictions prevent Bash commands from reaching resources outside defined boundaries, even if a prompt injection bypasses Claude's decision-making

299* Filesystem restrictions in the sandbox use Read and Edit deny rules, not separate sandbox configuration299* Filesystem restrictions in the sandbox combine the [`sandbox.filesystem`](/en/sandboxing) settings with Read and Edit deny rules; both are merged into the final sandbox boundary

300* Network restrictions combine WebFetch permission rules with the sandbox's `allowedDomains` and `deniedDomains` lists300* Network restrictions combine WebFetch permission rules with the sandbox's `allowedDomains` and `deniedDomains` lists

301 301 

302When sandboxing is enabled with `autoAllowBashIfSandboxed: true`, which is the default, sandboxed Bash commands run without prompting even if your permissions include `ask: Bash(*)`. The sandbox boundary substitutes for the per-command prompt. Explicit deny rules still apply, and `rm` or `rmdir` commands that target `/`, your home directory, or other critical system paths still trigger a prompt. See [sandbox modes](/en/sandboxing#sandbox-modes) to change this behavior.302When sandboxing is enabled with `autoAllowBashIfSandboxed: true`, which is the default, sandboxed Bash commands run without prompting even if your permissions include `ask: Bash(*)`. The sandbox boundary substitutes for the per-command prompt. Explicit deny rules still apply, and `rm` or `rmdir` commands that target `/`, your home directory, or other critical system paths still trigger a prompt. See [sandbox modes](/en/sandboxing#sandbox-modes) to change this behavior.


316| `allowManagedMcpServersOnly` | When `true`, only `allowedMcpServers` from managed settings are respected. `deniedMcpServers` still merges from all sources. See [Managed MCP configuration](/en/mcp#managed-mcp-configuration) |316| `allowManagedMcpServersOnly` | When `true`, only `allowedMcpServers` from managed settings are respected. `deniedMcpServers` still merges from all sources. See [Managed MCP configuration](/en/mcp#managed-mcp-configuration) |

317| `allowManagedPermissionRulesOnly` | When `true`, prevents user and project settings from defining `allow`, `ask`, or `deny` permission rules. Only rules in managed settings apply |317| `allowManagedPermissionRulesOnly` | When `true`, prevents user and project settings from defining `allow`, `ask`, or `deny` permission rules. Only rules in managed settings apply |

318| `blockedMarketplaces` | Blocklist of marketplace sources. Blocked sources are checked before downloading, so they never touch the filesystem. See [managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) |318| `blockedMarketplaces` | Blocklist of marketplace sources. Blocked sources are checked before downloading, so they never touch the filesystem. See [managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) |

319| `channelsEnabled` | Allow [channels](/en/channels) for Team and Enterprise users. Unset or `false` blocks channel message delivery regardless of what users pass to `--channels` |319| `channelsEnabled` | Allow [channels](/en/channels) for the organization. See [enterprise controls](/en/channels#enterprise-controls) for the default on each plan |

320| `forceRemoteSettingsRefresh` | When `true`, blocks CLI startup until remote managed settings are freshly fetched and exits if the fetch fails. See [fail-closed enforcement](/en/server-managed-settings#enforce-fail-closed-startup) |320| `forceRemoteSettingsRefresh` | When `true`, blocks CLI startup until remote managed settings are freshly fetched and exits if the fetch fails. See [fail-closed enforcement](/en/server-managed-settings#enforce-fail-closed-startup) |

321| `pluginTrustMessage` | Custom message appended to the plugin trust warning shown before installation |321| `pluginTrustMessage` | Custom message appended to the plugin trust warning shown before installation |

322| `sandbox.filesystem.allowManagedReadPathsOnly` | When `true`, only `filesystem.allowRead` paths from managed settings are respected. `denyRead` still merges from all sources |322| `sandbox.filesystem.allowManagedReadPathsOnly` | When `true`, only `filesystem.allowRead` paths from managed settings are respected. `denyRead` still merges from all sources |


327`disableBypassPermissionsMode` is typically placed in managed settings to enforce organizational policy, but it works from any scope. A user can set it in their own settings to lock themselves out of bypass mode.327`disableBypassPermissionsMode` is typically placed in managed settings to enforce organizational policy, but it works from any scope. A user can set it in their own settings to lock themselves out of bypass mode.

328 328 

329<Note>329<Note>

330 Access to [Remote Control](/en/remote-control) and [web sessions](/en/claude-code-on-the-web) is not controlled by a managed settings key. On Team and Enterprise plans, an admin enables or disables these features in [Claude Code admin settings](https://claude.ai/admin-settings/claude-code).330 On Team and Enterprise plans, an admin enables or disables [Remote Control](/en/remote-control) and [web sessions](/en/claude-code-on-the-web) organization-wide in [Claude Code admin settings](https://claude.ai/admin-settings/claude-code). Remote Control can additionally be disabled per device with the [`disableRemoteControl`](/en/settings#available-settings) managed setting. Web sessions have no per-device managed settings key.

331</Note>331</Note>

332 332 

333## Settings precedence333## Settings precedence

platforms.md +1 −1

Details

21| [Web](/en/claude-code-on-the-web) | Long-running tasks that don't need much steering, or work that should continue when you're offline | Anthropic-managed cloud, continues after you disconnect |21| [Web](/en/claude-code-on-the-web) | Long-running tasks that don't need much steering, or work that should continue when you're offline | Anthropic-managed cloud, continues after you disconnect |

22| Mobile | Starting and monitoring tasks while away from your computer | Cloud sessions from the Claude app for iOS and Android, [Remote Control](/en/remote-control) for local sessions, [Dispatch](/en/desktop#sessions-from-dispatch) to Desktop on Pro and Max |22| Mobile | Starting and monitoring tasks while away from your computer | Cloud sessions from the Claude app for iOS and Android, [Remote Control](/en/remote-control) for local sessions, [Dispatch](/en/desktop#sessions-from-dispatch) to Desktop on Pro and Max |

23 23 

24The CLI is the most complete surface for terminal-native work: scripting, third-party providers, and the Agent SDK are CLI-only. Desktop and the IDE extensions trade some CLI-only features for visual review and tighter editor integration. The web runs in Anthropic's cloud, so tasks keep going after you disconnect. Mobile is a thin client into those same cloud sessions or into a local session via Remote Control, and can send tasks to Desktop with Dispatch.24The CLI is the most complete surface for terminal-native work: scripting and the Agent SDK are CLI-only. Third-party providers also work in [VS Code](/en/vs-code#use-third-party-providers). Enterprise [Desktop](/en/desktop) deployments support Vertex AI and gateway providers; for Bedrock or Foundry, use the CLI or VS Code instead of Desktop. Desktop and the IDE extensions trade some CLI-only features for visual review and tighter editor integration. The web runs in Anthropic's cloud, so tasks keep going after you disconnect. Mobile is a thin client into those same cloud sessions or into a local session via Remote Control, and can send tasks to Desktop with Dispatch.

25 25 

26You can mix surfaces on the same project. Configuration, project memory, and MCP servers are shared across the local surfaces.26You can mix surfaces on the same project. Configuration, project memory, and MCP servers are shared across the local surfaces.

27 27 

Details

23 23 

24## Walkthrough: create a local marketplace24## Walkthrough: create a local marketplace

25 25 

26This example creates a marketplace with one plugin: a `/quality-review` skill for code reviews. You'll create the directory structure, add a skill, create the plugin manifest and marketplace catalog, then install and test it.26This example creates a marketplace with one plugin: a `quality-review` skill for code reviews. You'll create the directory structure, add a skill, create the plugin manifest and marketplace catalog, then install and test it.

27 27 

28<Steps>28<Steps>

29 <Step title="Create the directory structure">29 <Step title="Create the directory structure">


35 </Step>35 </Step>

36 36 

37 <Step title="Create the skill">37 <Step title="Create the skill">

38 Create a `SKILL.md` file that defines what the `/quality-review` skill does.38 Create a `SKILL.md` file that defines what the `quality-review` skill does.

39 39 

40 ```markdown my-marketplace/plugins/quality-review-plugin/skills/quality-review/SKILL.md theme={null}40 ```markdown my-marketplace/plugins/quality-review-plugin/skills/quality-review/SKILL.md theme={null}

41 ---41 ---


59 ```json my-marketplace/plugins/quality-review-plugin/.claude-plugin/plugin.json theme={null}59 ```json my-marketplace/plugins/quality-review-plugin/.claude-plugin/plugin.json theme={null}

60 {60 {

61 "name": "quality-review-plugin",61 "name": "quality-review-plugin",

62 "description": "Adds a /quality-review skill for quick code reviews",62 "description": "Adds a quality-review skill for quick code reviews",

63 "version": "1.0.0"63 "version": "1.0.0"

64 }64 }

65 ```65 ```


82 {82 {

83 "name": "quality-review-plugin",83 "name": "quality-review-plugin",

84 "source": "./plugins/quality-review-plugin",84 "source": "./plugins/quality-review-plugin",

85 "description": "Adds a /quality-review skill for quick code reviews"85 "description": "Adds a quality-review skill for quick code reviews"

86 }86 }

87 ]87 ]

88 }88 }


99 </Step>99 </Step>

100 100 

101 <Step title="Try it out">101 <Step title="Try it out">

102 Select some code in your editor and run your new skill.102 Select some code in your editor and run your new skill. Plugin skills are namespaced with the plugin name.

103 103 

104 ```shell theme={null}104 ```shell theme={null}

105 /quality-review105 /quality-review-plugin:quality-review

106 ```106 ```

107 </Step>107 </Step>

108</Steps>108</Steps>


693* For `hostPattern` sources: the marketplace host is matched against the regex pattern693* For `hostPattern` sources: the marketplace host is matched against the regex pattern

694* For `pathPattern` sources: the marketplace's filesystem path is matched against the regex pattern694* For `pathPattern` sources: the marketplace's filesystem path is matched against the regex pattern

695 695 

696Exact matching does not normalize URLs: a trailing slash, `.git` suffix, or `ssh://` versus `https://` form are treated as different values. If your organization's marketplace can be cloned by more than one URL form, prefer a `hostPattern` entry over a literal URL so all forms match.

697 

696Because `strictKnownMarketplaces` is set in [managed settings](/en/settings#settings-files), individual users and project configurations cannot override these restrictions.698Because `strictKnownMarketplaces` is set in [managed settings](/en/settings#settings-files), individual users and project configurations cannot override these restrictions.

697 699 

698For complete configuration details including all supported source types and comparison with `extraKnownMarketplaces`, see the [strictKnownMarketplaces reference](/en/settings#strictknownmarketplaces).700For complete configuration details including all supported source types and comparison with `extraKnownMarketplaces`, see the [strictKnownMarketplaces reference](/en/settings#strictknownmarketplaces).

Details

262**Available LSP plugins:**262**Available LSP plugins:**

263 263 

264| Plugin | Language server | Install command |264| Plugin | Language server | Install command |

265| :--------------- | :------------------------- | :----------------------------------------------------------------------------------------- |265| :------------------ | :------------------------- | :----------------------------------------------------------------------------------------- |

266| `pyright-lsp` | Pyright (Python) | `pip install pyright` or `npm install -g pyright` |266| `pyright-lsp` | Pyright (Python) | `pip install pyright` or `npm install -g pyright` |

267| `typescript-lsp` | TypeScript Language Server | `npm install -g typescript-language-server typescript` |267| `typescript-lsp` | TypeScript Language Server | `npm install -g typescript-language-server typescript` |

268| `rust-lsp` | rust-analyzer | [See rust-analyzer installation](https://rust-analyzer.github.io/manual.html#installation) |268| `rust-analyzer-lsp` | rust-analyzer | [See rust-analyzer installation](https://rust-analyzer.github.io/manual.html#installation) |

269 269 

270Install the language server first, then install the plugin from the marketplace.270Install the language server first, then install the plugin from the marketplace.

271 271 


533 533 

534Claude Code provides two variables for referencing plugin paths. Both are substituted inline anywhere they appear in skill content, agent content, hook commands, monitor commands, and MCP or LSP server configs. Both are also exported as environment variables to hook processes and MCP or LSP server subprocesses.534Claude Code provides two variables for referencing plugin paths. Both are substituted inline anywhere they appear in skill content, agent content, hook commands, monitor commands, and MCP or LSP server configs. Both are also exported as environment variables to hook processes and MCP or LSP server subprocesses.

535 535 

536**`${CLAUDE_PLUGIN_ROOT}`**: the absolute path to your plugin's installation directory. Use this to reference scripts, binaries, and config files bundled with the plugin. This path changes when the plugin updates, so files you write here do not survive an update.536**`${CLAUDE_PLUGIN_ROOT}`**: the absolute path to your plugin's installation directory. Use this to reference scripts, binaries, and config files bundled with the plugin. This path changes when the plugin updates. The previous version's directory remains on disk for about seven days after an update before cleanup, but treat it as ephemeral and do not write state here.

537 

538When a plugin updates mid-session, hook commands, monitors, MCP servers, and LSP servers keep using the previous version's path. Run `/reload-plugins` to switch hooks, MCP servers, and LSP servers to the new path; monitors require a session restart.

537 539 

538**`${CLAUDE_PLUGIN_DATA}`**: a persistent directory for plugin state that survives updates. Use this for installed dependencies such as `node_modules` or Python virtual environments, generated code, caches, and any other files that should persist across plugin versions. The directory is created automatically the first time this variable is referenced.540**`${CLAUDE_PLUGIN_DATA}`**: a persistent directory for plugin state that survives updates. Use this for installed dependencies such as `node_modules` or Python virtual environments, generated code, caches, and any other files that should persist across plugin versions. The directory is created automatically the first time this variable is referenced.

539 541 


679 The `.claude-plugin/` directory contains the `plugin.json` file. All other directories (commands/, agents/, skills/, output-styles/, themes/, monitors/, hooks/) must be at the plugin root, not inside `.claude-plugin/`.681 The `.claude-plugin/` directory contains the `plugin.json` file. All other directories (commands/, agents/, skills/, output-styles/, themes/, monitors/, hooks/) must be at the plugin root, not inside `.claude-plugin/`.

680</Warning>682</Warning>

681 683 

684A `CLAUDE.md` file at the plugin root is not loaded as project context. Plugins contribute context through skills, agents, and hooks rather than CLAUDE.md. To ship instructions that load into Claude's context, put them in a [skill](#skills).

685 

682### File locations reference686### File locations reference

683 687 

684| Component | Default Location | Purpose |688| Component | Default Location | Purpose |

Details

113 113 

114* **Open the session URL** in any browser to go directly to the session on [claude.ai/code](https://claude.ai/code).114* **Open the session URL** in any browser to go directly to the session on [claude.ai/code](https://claude.ai/code).

115* **Scan the QR code** shown alongside the session URL to open it directly in the Claude app. With `claude remote-control`, press spacebar to toggle the QR code display.115* **Scan the QR code** shown alongside the session URL to open it directly in the Claude app. With `claude remote-control`, press spacebar to toggle the QR code display.

116* **Open [claude.ai/code](https://claude.ai/code) or the Claude app** and find the session by name in the session list. Remote Control sessions show a computer icon with a green status dot when online.116* **Open [claude.ai/code](https://claude.ai/code) or the Claude app** and find the session by name in the session list. In the Claude mobile app, tap **Code** in the navigation to reach the session list. Remote Control sessions show a computer icon with a green status dot when online.

117 117 

118The remote session title is chosen in this order:118The remote session title is chosen in this order:

119 119 


215 215 

216### "Remote Control is disabled by your organization's policy"216### "Remote Control is disabled by your organization's policy"

217 217 

218This error has three distinct causes. Run `/status` first to see which login method and subscription you're using.218This error has four distinct causes. Run `/status` first to see which login method and subscription you're using.

219 219 

220* **You're authenticated with an API key or Console account**: Remote Control requires claude.ai OAuth. Run `/login` and choose the claude.ai option. If `ANTHROPIC_API_KEY` is set in your environment, unset it.220* **You're authenticated with an API key or Console account**: Remote Control requires claude.ai OAuth. Run `/login` and choose the claude.ai option. If `ANTHROPIC_API_KEY` is set in your environment, unset it.

221* **Your Team or Enterprise admin hasn't enabled it**: Remote Control is off by default on these plans. An admin can enable it at [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code) by turning on the **Remote Control** toggle. This is a server-side organization setting, not a [managed settings](/en/permissions#managed-only-settings) key.221* **Your Team or Enterprise admin hasn't enabled it**: Remote Control is off by default on these plans. An admin can enable it at [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code) by turning on the **Remote Control** toggle. This toggle is a server-side organization setting.

222* **The admin toggle is grayed out**: your organization has a data retention or compliance configuration that is incompatible with Remote Control. This cannot be changed from the admin panel. Contact Anthropic support to discuss options.222* **The admin toggle is grayed out**: your organization has a data retention or compliance configuration that is incompatible with Remote Control. This cannot be changed from the admin panel. Contact Anthropic support to discuss options.

223* **The error mentions `disableRemoteControl`**: your IT administrator has disabled Remote Control on this device through [managed settings](/en/settings#settings-files), independent of the organization-wide toggle.

223 224 

224### "Remote credentials fetch failed"225### "Remote credentials fetch failed"

225 226 

Details

166 166 

167### Jitter167### Jitter

168 168 

169To avoid every session hitting the API at the same wall-clock moment, the scheduler adds a small deterministic offset to fire times:169To avoid every session hitting the API at the same wall-clock moment, the scheduler adds a deterministic offset to fire times:

170 170 

171* Recurring tasks fire up to 10% of their period late, capped at 15 minutes. An hourly job might fire anywhere from `:00` to `:06`.171* Recurring tasks fire up to 30 minutes after the scheduled time (or up to half the interval, for tasks that run more often than hourly). An hourly job scheduled for `:00` may fire anywhere up to `:30`.

172* One-shot tasks scheduled for the top or bottom of the hour fire up to 90 seconds early.172* One-shot tasks scheduled for the top or bottom of the hour fire up to 90 seconds early.

173 173 

174The offset is derived from the task ID, so the same task always gets the same offset. If exact timing matters, pick a minute that is not `:00` or `:30`, for example `3 9 * * *` instead of `0 9 * * *`, and the one-shot jitter will not apply.174The offset is derived from the task ID, so the same task always gets the same offset. If exact timing matters, pick a minute that is not `:00` or `:30`, for example `3 9 * * *` instead of `0 9 * * *`, and the one-shot jitter will not apply.

security.md +1 −1

Details

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](/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* **Write access restriction**: Claude Code can only write to the folder where it was started and its subfolders—it cannot modify files in parent directories without explicit permission. While Claude Code can read files outside the working directory (useful for accessing system libraries and dependencies), write operations are strictly confined to the project scope, creating a clear security boundary28* **Write access restriction**: Claude Code can only write to the folder where it was started and its subfolders—it cannot modify files in parent directories without explicit permission. While Claude Code can read files outside the working directory (useful for accessing system libraries and dependencies), write operations are strictly confined to the project scope, creating a clear security boundary

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**: Batch accept multiple edits while maintaining permission prompts for commands with side effects30* **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 

32### User responsibility32### User responsibility

33 33 

settings.md +26 −3

Details

71| **Plugins** | `~/.claude/settings.json` | `.claude/settings.json` | `.claude/settings.local.json` |71| **Plugins** | `~/.claude/settings.json` | `.claude/settings.json` | `.claude/settings.local.json` |

72| **CLAUDE.md** | `~/.claude/CLAUDE.md` | `CLAUDE.md` or `.claude/CLAUDE.md` | `CLAUDE.local.md` |72| **CLAUDE.md** | `~/.claude/CLAUDE.md` | `CLAUDE.md` or `.claude/CLAUDE.md` | `CLAUDE.local.md` |

73 73 

74On Windows, paths shown as `~/.claude` resolve to `%USERPROFILE%\.claude`.

75 

74***76***

75 77 

76## Settings files78## Settings files


169| `apiKeyHelper` | Custom script, to be executed in `/bin/sh`, to generate an auth value. This value will be sent as `X-Api-Key` and `Authorization: Bearer` headers for model requests | `/bin/generate_temp_api_key.sh` |171| `apiKeyHelper` | Custom script, to be executed in `/bin/sh`, to generate an auth value. This value will be sent as `X-Api-Key` and `Authorization: Bearer` headers for model requests | `/bin/generate_temp_api_key.sh` |

170| `attribution` | Customize attribution for git commits and pull requests. See [Attribution settings](#attribution-settings) | `{"commit": "🤖 Generated with Claude Code", "pr": ""}` |172| `attribution` | Customize attribution for git commits and pull requests. See [Attribution settings](#attribution-settings) | `{"commit": "🤖 Generated with Claude Code", "pr": ""}` |

171| `autoMemoryDirectory` | Custom directory for [auto memory](/en/memory#storage-location) storage. Accepts an absolute path or a `~/`-prefixed path. Accepted from policy and user settings, and from the `--settings` flag. Not accepted from project or local settings, since a cloned repository could supply either file to redirect memory writes to sensitive locations | `"~/my-memory-dir"` |173| `autoMemoryDirectory` | Custom directory for [auto memory](/en/memory#storage-location) storage. Accepts an absolute path or a `~/`-prefixed path. Accepted from policy and user settings, and from the `--settings` flag. Not accepted from project or local settings, since a cloned repository could supply either file to redirect memory writes to sensitive locations | `"~/my-memory-dir"` |

174| `autoMemoryEnabled` | Enable [auto memory](/en/memory#enable-or-disable-auto-memory). When `false`, Claude does not read from or write to the auto memory directory. Default: `true`. You can also toggle this with `/memory` during a session | `false` |

172| `autoMode` | Customize what the [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) classifier blocks and allows. Contains `environment`, `allow`, and `soft_deny` arrays of prose rules. Include the literal string `"$defaults"` in an array to inherit the built-in rules at that position. See [Configure auto mode](/en/auto-mode-config). Not read from shared project settings | `{"soft_deny": ["$defaults", "Never run terraform apply"]}` |175| `autoMode` | Customize what the [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) classifier blocks and allows. Contains `environment`, `allow`, and `soft_deny` arrays of prose rules. Include the literal string `"$defaults"` in an array to inherit the built-in rules at that position. See [Configure auto mode](/en/auto-mode-config). Not read from shared project settings | `{"soft_deny": ["$defaults", "Never run terraform apply"]}` |

173| `autoScrollEnabled` | In [fullscreen rendering](/en/fullscreen), follow new output to the bottom of the conversation. Default: `true`. Appears in `/config` as **Auto-scroll**. Permission prompts still scroll into view when this is off | `false` |176| `autoScrollEnabled` | In [fullscreen rendering](/en/fullscreen), follow new output to the bottom of the conversation. Default: `true`. Appears in `/config` as **Auto-scroll**. Permission prompts still scroll into view when this is off | `false` |

174| `autoUpdatesChannel` | Release channel to follow for updates. Use `"stable"` for a version that is typically about one week old and skips versions with major regressions, or `"latest"` (default) for the most recent release | `"stable"` |177| `autoUpdatesChannel` | Release channel to follow for updates. Use `"stable"` for a version that is typically about one week old and skips versions with major regressions, or `"latest"` (default) for the most recent release | `"stable"` |


177| `awsAuthRefresh` | Custom script that modifies the `.aws` directory (see [advanced credential configuration](/en/amazon-bedrock#advanced-credential-configuration)) | `aws sso login --profile myprofile` |180| `awsAuthRefresh` | Custom script that modifies the `.aws` directory (see [advanced credential configuration](/en/amazon-bedrock#advanced-credential-configuration)) | `aws sso login --profile myprofile` |

178| `awsCredentialExport` | Custom script that outputs JSON with AWS credentials (see [advanced credential configuration](/en/amazon-bedrock#advanced-credential-configuration)) | `/bin/generate_aws_grant.sh` |181| `awsCredentialExport` | Custom script that outputs JSON with AWS credentials (see [advanced credential configuration](/en/amazon-bedrock#advanced-credential-configuration)) | `/bin/generate_aws_grant.sh` |

179| `blockedMarketplaces` | (Managed settings only) Blocklist of marketplace sources. Enforced on marketplace add and on plugin install, update, refresh, and auto-update, so a marketplace added before the policy was set cannot be used to fetch plugins. Blocked sources are checked before downloading, so they never touch the filesystem. See [Managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) | `[{ "source": "github", "repo": "untrusted/plugins" }]` |182| `blockedMarketplaces` | (Managed settings only) Blocklist of marketplace sources. Enforced on marketplace add and on plugin install, update, refresh, and auto-update, so a marketplace added before the policy was set cannot be used to fetch plugins. Blocked sources are checked before downloading, so they never touch the filesystem. See [Managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) | `[{ "source": "github", "repo": "untrusted/plugins" }]` |

180| `channelsEnabled` | (Managed settings only) Allow [channels](/en/channels) for Team and Enterprise users. Unset or `false` blocks channel message delivery regardless of what users pass to `--channels` | `true` |183| `channelsEnabled` | (Managed settings only) Allow [channels](/en/channels) for the organization. On claude.ai Team and Enterprise plans, channels are blocked when this is unset or `false`. For [Anthropic Console](/en/authentication#claude-console-authentication) accounts using API key authentication, channels are allowed by default unless your organization deploys managed settings, in which case this key must be set to `true` | `true` |

181| `cleanupPeriodDays` | Session files older than this period are deleted at startup (default: 30 days, minimum 1). Setting to `0` is rejected with a validation error. Also controls the age cutoff for automatic removal of [orphaned subagent worktrees](/en/worktrees#clean-up-worktrees) at startup. To disable transcript writes entirely, set the [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](/en/env-vars) environment variable, or in non-interactive mode (`-p`) use the `--no-session-persistence` flag or the `persistSession: false` SDK option. | `20` |184| `cleanupPeriodDays` | Session files older than this period are deleted at startup (default: 30 days, minimum 1). Setting to `0` is rejected with a validation error. Also controls the age cutoff for automatic removal of [orphaned subagent worktrees](/en/worktrees#clean-up-worktrees) at startup. To disable transcript writes entirely, set the [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](/en/env-vars) environment variable, or in non-interactive mode (`-p`) use the `--no-session-persistence` flag or the `persistSession: false` SDK option. | `20` |

182| `companyAnnouncements` | Announcement to display to users at startup. If multiple announcements are provided, they will be cycled through at random. | `["Welcome to Acme Corp! Review our code guidelines at docs.acme.com"]` |185| `companyAnnouncements` | Announcement to display to users at startup. If multiple announcements are provided, they will be cycled through at random. | `["Welcome to Acme Corp! Review our code guidelines at docs.acme.com"]` |

183| `defaultShell` | Default shell for input-box `!` commands. Accepts `"bash"` (default) or `"powershell"`. Setting `"powershell"` routes interactive `!` commands through PowerShell on Windows. Requires `CLAUDE_CODE_USE_POWERSHELL_TOOL=1`. See [PowerShell tool](/en/tools-reference#powershell-tool) | `"powershell"` |186| `defaultShell` | Default shell for input-box `!` commands. Accepts `"bash"` (default) or `"powershell"`. Setting `"powershell"` routes interactive `!` commands through PowerShell on Windows. Requires `CLAUDE_CODE_USE_POWERSHELL_TOOL=1`. See [PowerShell tool](/en/tools-reference#powershell-tool) | `"powershell"` |


186| `disableAutoMode` | Set to `"disable"` to prevent [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) from being activated. Removes `auto` from the `Shift+Tab` cycle and rejects `--permission-mode auto` at startup. Most useful in [managed settings](/en/permissions#managed-settings) where users cannot override it | `"disable"` |189| `disableAutoMode` | Set to `"disable"` to prevent [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) from being activated. Removes `auto` from the `Shift+Tab` cycle and rejects `--permission-mode auto` at startup. Most useful in [managed settings](/en/permissions#managed-settings) where users cannot override it | `"disable"` |

187| `disableDeepLinkRegistration` | Set to `"disable"` to prevent Claude Code from registering the `claude-cli://` protocol handler with the operating system on startup. [Deep links](/en/deep-links) let external tools open a Claude Code session with a pre-filled prompt. Useful in environments where protocol handler registration is restricted or managed separately | `"disable"` |190| `disableDeepLinkRegistration` | Set to `"disable"` to prevent Claude Code from registering the `claude-cli://` protocol handler with the operating system on startup. [Deep links](/en/deep-links) let external tools open a Claude Code session with a pre-filled prompt. Useful in environments where protocol handler registration is restricted or managed separately | `"disable"` |

188| `disabledMcpjsonServers` | List of specific MCP servers from `.mcp.json` files to reject | `["filesystem"]` |191| `disabledMcpjsonServers` | List of specific MCP servers from `.mcp.json` files to reject | `["filesystem"]` |

192| `disableRemoteControl` | {/* min-version: 2.1.128 */}Disable [Remote Control](/en/remote-control): blocks `claude remote-control`, the `--remote-control` flag, auto-start, and the in-session toggle. Typically placed in [managed settings](/en/permissions#managed-settings) for per-device MDM enforcement, but works from any scope. Requires Claude Code v2.1.128 or later | `true` |

189| `disableSkillShellExecution` | Disable inline shell execution for `` !`...` `` and ` ```! ` blocks in [skills](/en/skills) and custom commands from user, project, plugin, or additional-directory sources. Commands are replaced with `[shell command execution disabled by policy]` instead of being run. Bundled and managed skills are not affected. Most useful in [managed settings](/en/permissions#managed-settings) where users cannot override it | `true` |193| `disableSkillShellExecution` | Disable inline shell execution for `` !`...` `` and ` ```! ` blocks in [skills](/en/skills) and custom commands from user, project, plugin, or additional-directory sources. Commands are replaced with `[shell command execution disabled by policy]` instead of being run. Bundled and managed skills are not affected. Most useful in [managed settings](/en/permissions#managed-settings) where users cannot override it | `true` |

190| `editorMode` | Key binding mode for the input prompt: `"normal"` or `"vim"`. Default: `"normal"`. Appears in `/config` as **Editor mode** | `"vim"` |194| `editorMode` | Key binding mode for the input prompt: `"normal"` or `"vim"`. Default: `"normal"`. Appears in `/config` as **Editor mode** | `"vim"` |

191| `effortLevel` | Persist the [effort level](/en/model-config#adjust-effort-level) across sessions. Accepts `"low"`, `"medium"`, `"high"`, or `"xhigh"`. Written automatically when you run `/effort` with one of those values. See [Adjust effort level](/en/model-config#adjust-effort-level) for supported models | `"xhigh"` |195| `effortLevel` | Persist the [effort level](/en/model-config#adjust-effort-level) across sessions. Accepts `"low"`, `"medium"`, `"high"`, or `"xhigh"`. Written automatically when you run `/effort` with one of those values. See [Adjust effort level](/en/model-config#adjust-effort-level) for supported models | `"xhigh"` |


553 },557 },

554 "extraKnownMarketplaces": {558 "extraKnownMarketplaces": {

555 "acme-tools": {559 "acme-tools": {

560 "source": {

556 "source": "github",561 "source": "github",

557 "repo": "acme-corp/claude-plugins"562 "repo": "acme-corp/claude-plugins"

558 }563 }

559 }564 }

565 }

560}566}

561```567```

562 568 


571* **Local settings** (`.claude/settings.local.json`): Per-machine overrides (not committed)577* **Local settings** (`.claude/settings.local.json`): Per-machine overrides (not committed)

572* **Managed settings** (`managed-settings.json`): Organization-wide policy overrides that block installation at all scopes and hide the plugin from the marketplace578* **Managed settings** (`managed-settings.json`): Organization-wide policy overrides that block installation at all scopes and hide the plugin from the marketplace

573 579 

580<Note>

581 Project settings take precedence over user settings, so setting a plugin to `false` in `~/.claude/settings.json` does not disable a plugin that the project's `.claude/settings.json` enables. To opt out of a project-enabled plugin on your machine, set it to `false` in `.claude/settings.local.json` instead.

582 

583 Plugins force-enabled by managed settings cannot be disabled this way, since managed settings override local settings.

584</Note>

585 

574**Example**:586**Example**:

575 587 

576```json theme={null}588```json theme={null}


662* Only available in managed settings (`managed-settings.json`)674* Only available in managed settings (`managed-settings.json`)

663* Cannot be overridden by user or project settings (highest precedence)675* Cannot be overridden by user or project settings (highest precedence)

664* Enforced BEFORE network/filesystem operations (blocked sources never execute)676* Enforced BEFORE network/filesystem operations (blocked sources never execute)

665* Uses exact matching for source specifications (including `ref`, `path` for git sources), except `hostPattern`, which uses regex matching677* Uses exact matching for source specifications (including `ref`, `path` for git sources), except `hostPattern` and `pathPattern`, which use regex matching

666 678 

667**Allowlist behavior**:679**Allowlist behavior**:

668 680 


672 684 

673**All supported source types**:685**All supported source types**:

674 686 

675The allowlist supports multiple marketplace source types. Most sources use exact matching, while `hostPattern` uses regex matching against the marketplace host.687The allowlist supports multiple marketplace source types. Most sources use exact matching, while `hostPattern` and `pathPattern` use regex matching against the marketplace host and filesystem path respectively.

676 688 

6771. **GitHub repositories**:6891. **GitHub repositories**:

678 690 


752* `url`: extracts hostname from the URL764* `url`: extracts hostname from the URL

753* `npm`, `file`, `directory`: not supported for host pattern matching765* `npm`, `file`, `directory`: not supported for host pattern matching

754 766 

7678. **Path pattern matching**:

768 

769```json theme={null}

770{ "source": "pathPattern", "pathPattern": "^/opt/approved/" }

771{ "source": "pathPattern", "pathPattern": ".*" }

772```

773 

774Fields: `pathPattern` (required: regex pattern matched against the `path` field of `file` and `directory` sources)

775 

776Use path pattern matching to allow filesystem-based marketplaces alongside `hostPattern` restrictions for network sources. Set `".*"` to allow all local paths, or a narrower pattern to restrict to specific directories.

777 

755**Configuration examples**:778**Configuration examples**:

756 779 

757Example: allow specific marketplaces only:780Example: allow specific marketplaces only:

skills.md +2 −0

Details

169 169 

170Your `SKILL.md` can contain anything, but thinking through how you want the skill invoked (by you, by Claude, or both) and where you want it to run (inline or in a subagent) helps guide what to include. For complex skills, you can also [add supporting files](#add-supporting-files) to keep the main skill focused.170Your `SKILL.md` can contain anything, but thinking through how you want the skill invoked (by you, by Claude, or both) and where you want it to run (inline or in a subagent) helps guide what to include. For complex skills, you can also [add supporting files](#add-supporting-files) to keep the main skill focused.

171 171 

172Keep the body itself concise. Once a skill loads, its content [stays in context across turns](#skill-content-lifecycle), so every line is a recurring token cost. State what to do rather than narrating how or why, and apply the same conciseness test you would for [CLAUDE.md content](/en/best-practices#write-an-effective-claude-md).

173 

172### Frontmatter reference174### Frontmatter reference

173 175 

174Beyond the markdown content, you can configure skill behavior using YAML frontmatter fields between `---` markers at the top of your `SKILL.md` file:176Beyond the markdown content, you can configure skill behavior using YAML frontmatter fields between `---` markers at the top of your `SKILL.md` file:

statusline.md +3 −3

Details

134 134 

135**When it updates**135**When it updates**

136 136 

137Your script runs after each new assistant message, when the permission mode changes, or when vim mode toggles. Updates are debounced at 300ms, meaning rapid changes batch together and your script runs once things settle. If a new update triggers while your script is still running, the in-flight execution is cancelled. If you edit your script, the changes won't appear until your next interaction with Claude Code triggers an update.137Your script runs after each new assistant message, after `/compact` finishes, when the permission mode changes, or when vim mode toggles. Updates are debounced at 300ms, meaning rapid changes batch together and your script runs once things settle. If a new update triggers while your script is still running, the in-flight execution is cancelled. If you edit your script, the changes won't appear until your next interaction with Claude Code triggers an update.

138 138 

139These triggers can go quiet when the main session is idle, for example while a coordinator waits on background subagents. To keep time-based or externally-sourced segments current during idle periods, set [`refreshInterval`](#manually-configure-a-status-line) to also re-run the command on a fixed timer.139These triggers can go quiet when the main session is idle, for example while a coordinator waits on background subagents. To keep time-based or externally-sourced segments current during idle periods, set [`refreshInterval`](#manually-configure-a-status-line) to also re-run the command on a fixed timer.

140 140 


272 272 

273 **Fields that may be `null`**:273 **Fields that may be `null`**:

274 274 

275 * `context_window.current_usage`: `null` before the first API call in a session275 * `context_window.current_usage`: `null` before the first API call in a session, and again after `/compact` until the next API call repopulates it

276 * `context_window.used_percentage`, `context_window.remaining_percentage`: may be `null` early in the session276 * `context_window.used_percentage`, `context_window.remaining_percentage`: may be `null` early in the session

277 277 

278 Handle missing fields with conditional access and null values with fallback defaults in your scripts.278 Handle missing fields with conditional access and null values with fallback defaults in your scripts.


296 296 

297If you calculate context percentage manually from `current_usage`, use the same input-only formula to match `used_percentage`.297If you calculate context percentage manually from `current_usage`, use the same input-only formula to match `used_percentage`.

298 298 

299The `current_usage` object is `null` before the first API call in a session.299The `current_usage` object is `null` before the first API call in a session, and again immediately after `/compact` until the next API call repopulates it.

300 300 

301## Examples301## Examples

302 302 

sub-agents.md +33 −8

Details

76 | Agent | Model | When Claude uses it |76 | Agent | Model | When Claude uses it |

77 | :---------------- | :----- | :------------------------------------------------------- |77 | :---------------- | :----- | :------------------------------------------------------- |

78 | statusline-setup | Sonnet | When you run `/statusline` to configure your status line |78 | statusline-setup | Sonnet | When you run `/statusline` to configure your status line |

79 | Claude Code Guide | Haiku | When you ask questions about Claude Code features |79 | claude-code-guide | Haiku | When you ask questions about Claude Code features |

80 </Tab>80 </Tab>

81</Tabs>81</Tabs>

82 82 


180 180 

181**CLI-defined subagents** are passed as JSON when launching Claude Code. They exist only for that session and aren't saved to disk, making them useful for quick testing or automation scripts. You can define multiple subagents in a single `--agents` call:181**CLI-defined subagents** are passed as JSON when launching Claude Code. They exist only for that session and aren't saved to disk, making them useful for quick testing or automation scripts. You can define multiple subagents in a single `--agents` call:

182 182 

183```bash theme={null}183<Tabs>

184claude --agents '{184 <Tab title="macOS, Linux, WSL">

185 ```bash theme={null}

186 claude --agents '{

185 "code-reviewer": {187 "code-reviewer": {

186 "description": "Expert code reviewer. Use proactively after code changes.",188 "description": "Expert code reviewer. Use proactively after code changes.",

187 "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",189 "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",


192 "description": "Debugging specialist for errors and test failures.",194 "description": "Debugging specialist for errors and test failures.",

193 "prompt": "You are an expert debugger. Analyze errors, identify root causes, and provide fixes."195 "prompt": "You are an expert debugger. Analyze errors, identify root causes, and provide fixes."

194 }196 }

195}'197 }'

196```198 ```

199 </Tab>

200 

201 <Tab title="Windows PowerShell">

202 ```powershell theme={null}

203 claude --agents @'

204 {

205 "code-reviewer": {

206 "description": "Expert code reviewer. Use proactively after code changes.",

207 "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",

208 "tools": ["Read", "Grep", "Glob", "Bash"],

209 "model": "sonnet"

210 },

211 "debugger": {

212 "description": "Debugging specialist for errors and test failures.",

213 "prompt": "You are an expert debugger. Analyze errors, identify root causes, and provide fixes."

214 }

215 }

216 '@

217 ```

218 </Tab>

219</Tabs>

197 220 

198The `--agents` flag accepts JSON with the same [frontmatter](#supported-frontmatter-fields) fields as file-based subagents: `description`, `prompt`, `tools`, `disallowedTools`, `model`, `permissionMode`, `mcpServers`, `hooks`, `maxTurns`, `skills`, `initialPrompt`, `memory`, `effort`, `background`, `isolation`, and `color`. Use `prompt` for the system prompt, equivalent to the markdown body in file-based subagents.221The `--agents` flag accepts JSON with the same [frontmatter](#supported-frontmatter-fields) fields as file-based subagents: `description`, `prompt`, `tools`, `disallowedTools`, `model`, `permissionMode`, `mcpServers`, `hooks`, `maxTurns`, `skills`, `initialPrompt`, `memory`, `effort`, `background`, `isolation`, and `color`. Use `prompt` for the system prompt, equivalent to the markdown body in file-based subagents.

199 222 


212Subagent files use YAML frontmatter for configuration, followed by the system prompt in Markdown:235Subagent files use YAML frontmatter for configuration, followed by the system prompt in Markdown:

213 236 

214<Note>237<Note>

215 Subagents are loaded at session start. If you create a subagent by manually adding a file, restart your session or use `/agents` to load it immediately.238 Subagents are loaded at session start. If you add or edit a subagent file directly on disk, restart your session to load it. Subagents created through the `/agents` interface take effect immediately without a restart.

216</Note>239</Note>

217 240 

218```markdown theme={null}241```markdown theme={null}


484exit 0507exit 0

485```508```

486 509 

487See [Hook input](/en/hooks#pretooluse-input) for the complete input schema and [exit codes](/en/hooks#exit-code-output) for how exit codes affect behavior.510See [Hook input](/en/hooks#pretooluse-input) for the complete input schema and [exit codes](/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](/en/hooks#windows-powershell-tool).

488 511 

489#### Disable specific subagents512#### Disable specific subagents

490 513 


994exit 01017exit 0

995```1018```

996 1019 

997Make the script executable:1020On macOS and Linux, make the script executable:

998 1021 

999```bash theme={null}1022```bash theme={null}

1000chmod +x ./scripts/validate-readonly-query.sh1023chmod +x ./scripts/validate-readonly-query.sh

1001```1024```

1002 1025 

1026On Windows, write the validation script in PowerShell and add `shell: powershell` to the hook entry. See [running hooks in PowerShell](/en/hooks#windows-powershell-tool).

1027 

1003The 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](/en/hooks#exit-code-output) for details on exit codes and [Hook input](/en/hooks#pretooluse-input) for the complete input schema.1028The 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](/en/hooks#exit-code-output) for details on exit codes and [Hook input](/en/hooks#pretooluse-input) for the complete input schema.

1004 1029 

1005## Next steps1030## Next steps

Details

11To add custom tools, connect an [MCP server](/en/mcp). To extend Claude with reusable prompt-based workflows, write a [skill](/en/skills), which runs through the existing `Skill` tool rather than adding a new tool entry.11To add custom tools, connect an [MCP server](/en/mcp). To extend Claude with reusable prompt-based workflows, write a [skill](/en/skills), which runs through the existing `Skill` tool rather than adding a new tool entry.

12 12 

13| Tool | Description | Permission Required |13| Tool | Description | Permission Required |

14| :--------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------ |14| :--------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------ |

15| `Agent` | Spawns a [subagent](/en/sub-agents) with its own context window to handle a task | No |15| `Agent` | Spawns a [subagent](/en/sub-agents) with its own context window to handle a task | No |

16| `AskUserQuestion` | Asks multiple-choice questions to gather requirements or clarify ambiguity | No |16| `AskUserQuestion` | Asks multiple-choice questions to gather requirements or clarify ambiguity | No |

17| `Bash` | Executes shell commands in your environment. See [Bash tool behavior](#bash-tool-behavior) | Yes |17| `Bash` | Executes shell commands in your environment. See [Bash tool behavior](#bash-tool-behavior) | Yes |


33| `Read` | Reads the contents of files | No |33| `Read` | Reads the contents of files | No |

34| `ReadMcpResourceTool` | Reads a specific MCP resource by URI | No |34| `ReadMcpResourceTool` | Reads a specific MCP resource by URI | No |

35| `SendMessage` | Sends a message to an [agent team](/en/agent-teams) teammate, or [resumes a subagent](/en/sub-agents#resume-subagents) by its agent ID. Stopped subagents auto-resume in the background. Only available when `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` is set | No |35| `SendMessage` | Sends a message to an [agent team](/en/agent-teams) teammate, or [resumes a subagent](/en/sub-agents#resume-subagents) by its agent ID. Stopped subagents auto-resume in the background. Only available when `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` is set | No |

36| `ShareOnboardingGuide` | {/* plan-availability: feature=onboarding-guide-share plans=pro,max,team,enterprise providers=anthropic */}Uploads `ONBOARDING.md` and returns a share link teammates can open in Claude Code. Called from `/team-onboarding` after the guide is written. Available to claude.ai subscribers on Pro, Max, Team, and Enterprise plans | Yes |

36| `Skill` | Executes a [skill](/en/skills#control-who-invokes-a-skill) within the main conversation | Yes |37| `Skill` | Executes a [skill](/en/skills#control-who-invokes-a-skill) within the main conversation | Yes |

37| `TaskCreate` | Creates a new task in the task list | No |38| `TaskCreate` | Creates a new task in the task list | No |

38| `TaskGet` | Retrieves full details for a specific task | No |39| `TaskGet` | Retrieves full details for a specific task | No |

Details

155* **`Voice mode requires a Claude.ai account`**: you are authenticated with an API key or a third-party provider. Run `/login` to sign in with a Claude.ai account.155* **`Voice mode requires a Claude.ai account`**: you are authenticated with an API key or a third-party provider. Run `/login` to sign in with a Claude.ai account.

156* **`Microphone access is denied`**: grant microphone permission to your terminal in system settings. On macOS, go to System Settings → Privacy & Security → Microphone and enable your terminal app, then run `/voice` again. On Windows, go to Settings → Privacy & security → Microphone and turn on microphone access for desktop apps, then run `/voice` again. If your terminal isn't listed in the macOS settings, see [Terminal not listed in macOS Microphone settings](#terminal-not-listed-in-macos-microphone-settings).156* **`Microphone access is denied`**: grant microphone permission to your terminal in system settings. On macOS, go to System Settings → Privacy & Security → Microphone and enable your terminal app, then run `/voice` again. On Windows, go to Settings → Privacy & security → Microphone and turn on microphone access for desktop apps, then run `/voice` again. If your terminal isn't listed in the macOS settings, see [Terminal not listed in macOS Microphone settings](#terminal-not-listed-in-macos-microphone-settings).

157* **`No audio recording tool found` on Linux**: the native audio module could not load and no fallback is installed. Install SoX with the command shown in the error message, for example `sudo apt-get install sox`.157* **`No audio recording tool found` on Linux**: the native audio module could not load and no fallback is installed. Install SoX with the command shown in the error message, for example `sudo apt-get install sox`.

158* **`Voice input is failing repeatedly and has been paused`**: voice dictation hit several start-up failures in a row and stopped attempting new sessions until one succeeds. This usually means the microphone or audio stack on this host can't capture audio, for example a headless server, a remote shell with no audio passthrough, or a denied microphone permission. Confirm a working input device, fix the underlying cause from the entries above, then trigger voice again.

158* **Nothing happens when holding `Space` in hold mode**: watch the prompt input while you hold. If spaces keep accumulating, voice dictation is likely off; run `/voice hold` to enable it. If only one or two spaces appear and then nothing, voice dictation is on but hold detection is not triggering. Hold detection requires your terminal to send key-repeat events, so it cannot detect a held key if key-repeat is disabled at the OS level. Switch to tap mode with `/voice tap` to avoid the key-repeat requirement.159* **Nothing happens when holding `Space` in hold mode**: watch the prompt input while you hold. If spaces keep accumulating, voice dictation is likely off; run `/voice hold` to enable it. If only one or two spaces appear and then nothing, voice dictation is on but hold detection is not triggering. Hold detection requires your terminal to send key-repeat events, so it cannot detect a held key if key-repeat is disabled at the OS level. Switch to tap mode with `/voice tap` to avoid the key-repeat requirement.

159* **Tapping `Space` types a space instead of recording in tap mode**: the first tap only starts recording when the prompt input is empty. Clear the input first, or check that you are in tap mode by running `/voice tap`.160* **Tapping `Space` types a space instead of recording in tap mode**: the first tap only starts recording when the prompt input is empty. Clear the input first, or check that you are in tap mode by running `/voice tap`.

160* **`No audio detected from microphone`**: recording started but captured silence. Confirm the correct input device is set as the system default and that its input level is not muted or near zero. On Windows, open Settings → System → Sound → Input and select your microphone. On macOS, open System Settings → Sound → Input.161* **`No audio detected from microphone`**: recording started but captured silence. Confirm the correct input device is set as the system default and that its input level is not muted or near zero. On Windows, open Settings → System → Sound → Input and select your microphone. On macOS, open System Settings → Sound → Input.

vs-code.md +10 −0

Details

476 476 

477Alternatively, click "✱ Claude Code" in the **Status Bar** (bottom-right corner). This works even without a file open. You can also use the **Command Palette** (`Cmd+Shift+P` / `Ctrl+Shift+P`) and type "Claude Code".477Alternatively, click "✱ Claude Code" in the **Status Bar** (bottom-right corner). This works even without a file open. You can also use the **Command Palette** (`Cmd+Shift+P` / `Ctrl+Shift+P`) and type "Claude Code".

478 478 

479### Cmd+Esc does nothing on macOS

480 

481On macOS Tahoe and later, the system Game Overlay shortcut is bound to `Cmd+Esc` by default and intercepts the keypress before it reaches VS Code. To free the shortcut:

482 

4831. Open System Settings

4842. Go to Keyboard, then Keyboard Shortcuts, then Game Controllers

4853. Clear the Game Overlay checkbox

486 

487Alternatively, rebind the extension to a different key: open the VS Code [Keyboard Shortcuts editor](https://code.visualstudio.com/docs/configure/keybindings) (`Cmd+K Cmd+S`), search for `Claude Code: Focus input`, and assign a new binding.

488 

479### Claude Code never responds489### Claude Code never responds

480 490 

481If Claude Code isn't responding to your prompts:491If Claude Code isn't responding to your prompts:

Details

206 206 

207To debug, add `set -x` at the top of the script to see which command failed. For non-critical commands, append `|| true` so they don't block session start.207To debug, add `set -x` at the top of the script to see which command failed. For non-critical commands, append `|| true` so they don't block session start.

208 208 

209### New sessions hang or time out during setup

210 

211If 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.

212 

213To fix this, trim the script so it reliably finishes in under five minutes:

214 

215* Run independent installs in parallel with `&` and a final `wait` instead of running them serially.

216* 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.

217* Remove long retry sleeps from the setup script, since a stalled retry loop counts against the budget.

218 

209### Session keeps running after closing the tab219### Session keeps running after closing the tab

210 220 

211This 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.221This 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.