SpyBara
Go Premium

Documentation 2026-07-16 22:59 UTC to 2026-07-17 22:57 UTC

62 files changed +863 −205. View all changes and history on the product overview
2026
Sat 18 16:02 Fri 17 22:57 Thu 16 22:59 Wed 15 22:00 Tue 14 23:01 Mon 13 23:57 Sat 11 19:03 Fri 10 17:00 Thu 9 23:58 Wed 8 16:02 Tue 7 16:02 Mon 6 23:57 Sat 4 03:01 Fri 3 23:00 Thu 2 23:59 Wed 1 21:01
Details

94| Managed policy settings | Endpoint-managed policy, such as an MDM plist, registry policy, or managed settings file, loads from the host. [Server-managed settings](/en/server-managed-settings) are fetched on an [eligible configuration](/en/server-managed-settings#platform-availability) when the session authenticates with an organization OAuth login or a directly configured API key | Endpoint policy: remove the managed settings file, plist, or registry policy from the host. Server-managed settings: controlled by your org admin; cannot be disabled from the SDK |94| Managed policy settings | Endpoint-managed policy, such as an MDM plist, registry policy, or managed settings file, loads from the host. [Server-managed settings](/en/server-managed-settings) are fetched on an [eligible configuration](/en/server-managed-settings#platform-availability) when the session authenticates with an organization OAuth login or a directly configured API key | Endpoint policy: remove the managed settings file, plist, or registry policy from the host. Server-managed settings: controlled by your org admin; cannot be disabled from the SDK |

95| `~/.claude.json` global config | Always read | Relocate with `CLAUDE_CONFIG_DIR` in `env` |95| `~/.claude.json` global config | Always read | Relocate with `CLAUDE_CONFIG_DIR` in `env` |

96| Auto memory at `~/.claude/projects/<project>/memory/` | Loaded into the system prompt at session start. The agent writes new memories there with the standard `Write` and `Edit` tools rather than a dedicated memory tool, so those tools must be enabled for the agent to save memories | Set `autoMemoryEnabled: false` in settings, or `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` in `env` |96| Auto memory at `~/.claude/projects/<project>/memory/` | Loaded into the system prompt at session start. The agent writes new memories there with the standard `Write` and `Edit` tools rather than a dedicated memory tool, so those tools must be enabled for the agent to save memories | Set `autoMemoryEnabled: false` in settings, or `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` in `env` |

97| [claude.ai MCP connectors](/en/mcp#use-mcp-servers-from-claude-ai) | Loaded when the active authentication method is a claude.ai subscription. Passing `mcpServers: {}` does not suppress them | Set `strictMcpConfig: true`, [`disableClaudeAiConnectors: true`](/en/mcp#disable-claude-ai-connectors) in settings, or `ENABLE_CLAUDEAI_MCP_SERVERS=false` in `env` |97| [claude.ai MCP connectors](/en/mcp#use-mcp-servers-from-claude-ai) | Loaded when the session authenticates with your claude.ai login. Not loaded when `CLAUDE_CODE_OAUTH_TOKEN` holds a token from [`claude setup-token`](/en/authentication#generate-a-long-lived-token), which can only make model requests. Passing `mcpServers: {}` does not suppress the connectors | Set `strictMcpConfig: true`, [`disableClaudeAiConnectors: true`](/en/mcp#disable-claude-ai-connectors) in settings, or `ENABLE_CLAUDEAI_MCP_SERVERS=false` in `env` |

98 98 

99<Warning>99<Warning>

100 Do not rely on default `query()` options for multi-tenant isolation. Because the inputs above are read regardless of `settingSources`, an SDK process can pick up host-level configuration and per-directory memory. For multi-tenant deployments, run each tenant in its own filesystem and set `settingSources: []` plus `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` in `env`. [Server-managed settings](/en/server-managed-settings) are fetched when the process authenticates with an organization credential; filesystem isolation does not remove them. See [Secure deployment](/en/agent-sdk/secure-deployment).100 Do not rely on default `query()` options for multi-tenant isolation. Because the inputs above are read regardless of `settingSources`, an SDK process can pick up host-level configuration and per-directory memory. For multi-tenant deployments, run each tenant in its own filesystem and set `settingSources: []` plus `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` in `env`. [Server-managed settings](/en/server-managed-settings) are fetched when the process authenticates with an organization credential; filesystem isolation does not remove them. See [Secure deployment](/en/agent-sdk/secure-deployment).

Details

298 ```298 ```

299 299 

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

301 import { tool } from "@anthropic-ai/claude-agent-sdk";

302 import { z } from "zod";

303 

301 tool(304 tool(

302 "get_temperature",305 "get_temperature",

303 "Get the current temperature at a location",306 "Get the current temperature at a location",


353 import httpx356 import httpx

354 from typing import Any357 from typing import Any

355 358 

359 from claude_agent_sdk import tool

360 

356 361 

357 @tool(362 @tool(

358 "fetch_data",363 "fetch_data",


388 ```393 ```

389 394 

390 ```typescript TypeScript theme={null}395 ```typescript TypeScript theme={null}

396 import { tool } from "@anthropic-ai/claude-agent-sdk";

397 import { z } from "zod";

398 

391 tool(399 tool(

392 "fetch_data",400 "fetch_data",

393 "Fetch data from an API",401 "Fetch data from an API",


458 import base64466 import base64

459 import httpx467 import httpx

460 468 

469 from claude_agent_sdk import tool

470 

461 471 

462 # Define a tool that fetches an image from a URL and returns it to Claude472 # Define a tool that fetches an image from a URL and returns it to Claude

463 @tool("fetch_image", "Fetch an image from a URL and return it to Claude", {"url": str})473 @tool("fetch_image", "Fetch an image from a URL and return it to Claude", {"url": str})


481 ```491 ```

482 492 

483 ```typescript TypeScript theme={null}493 ```typescript TypeScript theme={null}

494 import { tool } from "@anthropic-ai/claude-agent-sdk";

495 import { z } from "zod";

496 

484 tool(497 tool(

485 "fetch_image",498 "fetch_image",

486 "Fetch an image from a URL and return it to Claude",499 "Fetch an image from a URL and return it to Claude",


774 ]787 ]

775 788 

776 for prompt in prompts:789 for prompt in prompts:

790 try:

777 async for message in query(prompt=prompt, options=options):791 async for message in query(prompt=prompt, options=options):

778 if isinstance(message, AssistantMessage):792 if isinstance(message, AssistantMessage):

779 for block in message.content:793 for block in message.content:


781 print(f"[tool call] {block.name}({block.input})")795 print(f"[tool call] {block.name}({block.input})")

782 elif isinstance(message, ResultMessage) and message.subtype == "success":796 elif isinstance(message, ResultMessage) and message.subtype == "success":

783 print(f"Q: {prompt}\nA: {message.result}\n")797 print(f"Q: {prompt}\nA: {message.result}\n")

798 except Exception as error:

799 # A single-shot query() raises after yielding an error result. Only success

800 # results are printed above, so handle the failure here and continue with

801 # the next prompt.

802 print(f"Call failed: {error}")

784 803 

785 804 

786 asyncio.run(main())805 asyncio.run(main())


796 ];815 ];

797 816 

798 for (const prompt of prompts) {817 for (const prompt of prompts) {

818 try {

799 for await (const message of query({819 for await (const message of query({

800 prompt,820 prompt,

801 options: {821 options: {


813 console.log(`Q: ${prompt}\nA: ${message.result}\n`);833 console.log(`Q: ${prompt}\nA: ${message.result}\n`);

814 }834 }

815 }835 }

836 } catch (error) {

837 // A single-shot query() throws after yielding an error result. Only success

838 // results are logged above, so handle the failure here and continue with

839 // the next prompt.

840 console.error(`Call failed: ${error}`);

841 }

816 }842 }

817 ```843 ```

818</CodeGroup>844</CodeGroup>

Details

118 let sessionId: string | undefined;118 let sessionId: string | undefined;

119 119 

120 // Step 2: Capture checkpoint UUID from the first user message120 // Step 2: Capture checkpoint UUID from the first user message

121 try {

121 for await (const message of response) {122 for await (const message of response) {

122 if (message.type === "user" && message.uuid && !checkpointId) {123 if (message.type === "user" && message.uuid && !checkpointId) {

123 checkpointId = message.uuid;124 checkpointId = message.uuid;


126 sessionId = message.session_id;127 sessionId = message.session_id;

127 }128 }

128 }129 }

130 } catch (error) {

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

132 // failure was an error result, sessionId and checkpointId were already

133 // captured by the loop above; connection or process failures yield no

134 // result message.

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

136 }

129 137 

130 // Step 3: Later, rewind by resuming the session with an empty prompt138 // Step 3: Later, rewind by resuming the session with an empty prompt

131 if (checkpointId && sessionId) {139 if (checkpointId && sessionId) {


229 ) as client:237 ) as client:

230 await client.query("") # Empty prompt to open the connection238 await client.query("") # Empty prompt to open the connection

231 async for message in client.receive_response():239 async for message in client.receive_response():

240 if checkpoint_id:

232 await client.rewind_files(checkpoint_id)241 await client.rewind_files(checkpoint_id)

233 break242 break

234 ```243 ```


240 });249 });

241 250 

242 for await (const msg of rewindQuery) {251 for await (const msg of rewindQuery) {

252 if (checkpointId) {

243 await rewindQuery.rewindFiles(checkpointId);253 await rewindQuery.rewindFiles(checkpointId);

254 }

244 break;255 break;

245 }256 }

246 ```257 ```


430 const checkpoints: Checkpoint[] = [];441 const checkpoints: Checkpoint[] = [];

431 let sessionId: string | undefined;442 let sessionId: string | undefined;

432 443 

444 try {

433 for await (const message of response) {445 for await (const message of response) {

434 if (message.type === "user" && message.uuid) {446 if (message.type === "user" && message.uuid) {

435 checkpoints.push({447 checkpoints.push({


442 sessionId = message.session_id;454 sessionId = message.session_id;

443 }455 }

444 }456 }

457 } catch (error) {

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

459 // failure was an error result, sessionId and the checkpoints array were

460 // already populated by the loop above; connection or process failures

461 // yield no result message.

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

463 }

445 464 

446 // Later: rewind to any checkpoint by resuming the session465 // Later: rewind to any checkpoint by resuming the session

447 if (checkpoints.length > 0 && sessionId) {466 if (checkpoints.length > 0 && sessionId) {


612 options: opts631 options: opts

613 });632 });

614 633 

634 try {

615 for await (const message of response) {635 for await (const message of response) {

616 // Capture the first user message UUID - this is our restore point636 // Capture the first user message UUID - this is our restore point

617 if (message.type === "user" && message.uuid && !checkpointId) {637 if (message.type === "user" && message.uuid && !checkpointId) {


622 sessionId = message.session_id;642 sessionId = message.session_id;

623 }643 }

624 }644 }

645 } catch (error) {

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

647 // failure was an error result, checkpointId and sessionId were already

648 // captured by the loop above; connection or process failures yield no

649 // result message.

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

651 }

625 652 

626 console.log("Done! Open utils.ts to see the added doc comments.\n");653 console.log("Done! Open utils.ts to see the added doc comments.\n");

627 654 


760 ) as client:787 ) as client:

761 await client.query("")788 await client.query("")

762 async for message in client.receive_response():789 async for message in client.receive_response():

790 if checkpoint_id:

763 await client.rewind_files(checkpoint_id)791 await client.rewind_files(checkpoint_id)

764 break792 break

765 ```793 ```


771 options: { ...opts, resume: sessionId }799 options: { ...opts, resume: sessionId }

772 });800 });

773 801 

802 try {

774 for await (const msg of rewindQuery) {803 for await (const msg of rewindQuery) {

804 if (checkpointId) {

775 await rewindQuery.rewindFiles(checkpointId);805 await rewindQuery.rewindFiles(checkpointId);

806 }

776 break;807 break;

777 }808 }

809 } catch (error) {

810 // An error here means the rewind didn't complete, for example the checkpoint

811 // wasn't found or the session couldn't be resumed.

812 console.error(`Rewind session ended with an error: ${error}`);

813 }

778 ```814 ```

779</CodeGroup>815</CodeGroup>

780 816 

agent-sdk/hooks.md +26 −11

Details

84 )84 )

85 85 

86 async with ClaudeSDKClient(options=options) as client:86 async with ClaudeSDKClient(options=options) as client:

87 await client.query("Update the database configuration")87 await client.query("Create a .env file with the standard local development database configuration")

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

89 # Filter for assistant and result messages89 # Filter for assistant and result messages

90 if isinstance(message, (AssistantMessage, ResultMessage)):90 if isinstance(message, (AssistantMessage, ResultMessage)):


123 };123 };

124 124 

125 for await (const message of query({125 for await (const message of query({

126 prompt: "Update the database configuration",126 prompt: "Create a .env file with the standard local development database configuration",

127 options: {127 options: {

128 hooks: {128 hooks: {

129 // Register the hook for PreToolUse events129 // Register the hook for PreToolUse events


140 ```140 ```

141</CodeGroup>141</CodeGroup>

142 142 

143When you run either script, Claude attempts to create the `.env` file, the hook denies the tool call, and Claude's final response explains that it can't create `.env` files.

144 

143## Available hooks145## Available hooks

144 146 

145The SDK provides hooks for different stages of agent execution. Some hooks are available in both SDKs, while others are TypeScript-only.147The SDK provides hooks for different stages of agent execution. Some hooks are available in both SDKs, while others are TypeScript-only.

146 148 

147| Hook Event | Python SDK | TypeScript SDK | What triggers it | Example use case |149| Hook Event | Python SDK | TypeScript SDK | What triggers it | Example use case |

148| ------------------------------------------------------ | ---------- | -------------- | ------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |150| ------------------------------------------------------ | ---------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |

149| `PreToolUse` | Yes | Yes | Tool call request (can block or modify) | Block dangerous shell commands |151| `PreToolUse` | Yes | Yes | Tool call request (can block or modify) | Block dangerous shell commands |

150| `PostToolUse` | Yes | Yes | Tool execution result | Log all file changes to audit trail |152| `PostToolUse` | Yes | Yes | Tool execution result | Log all file changes to audit trail |

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

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

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

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

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

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

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

157| `SubagentStart` | Yes | Yes | Subagent initialization | Track parallel task spawning |160| `SubagentStart` | Yes | Yes | Subagent initialization | Track parallel task spawning |

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

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

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

160| `PermissionRequest` | Yes | Yes | Permission dialog would be displayed | Custom permission handling |164| `PermissionRequest` | Yes | Yes | Permission dialog would be displayed | Custom permission handling |

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

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

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

163| `Notification` | Yes | Yes | Agent status messages | Send agent status updates to Slack or PagerDuty |168| `Notification` | Yes | Yes | Agent status messages | Send agent status updates to Slack or PagerDuty |

164| `Setup` | No | Yes | Session setup/maintenance | Run initialization tasks |169| `Setup` | No | Yes | Session setup/maintenance | Run initialization tasks |

165| `TeammateIdle` | No | Yes | Teammate becomes idle | Reassign work or notify |170| `TeammateIdle` | No | Yes | Teammate becomes idle | Reassign work or notify |

171| `TaskCreated` | No | Yes | A task is created via the `TaskCreate` tool | Enforce task naming conventions |

166| `TaskCompleted` | No | Yes | Background task completes | Aggregate results from parallel tasks |172| `TaskCompleted` | No | Yes | Background task completes | Aggregate results from parallel tasks |

173| `Elicitation` | No | Yes | An MCP server requests user input mid-task | Respond to MCP input requests programmatically |

174| `ElicitationResult` | No | Yes | A user responds to an MCP elicitation | Modify or block the response before it returns to the server |

167| `ConfigChange` | No | Yes | Configuration file changes | Reload settings dynamically |175| `ConfigChange` | No | Yes | Configuration file changes | Reload settings dynamically |

176| `InstructionsLoaded` | No | Yes | A `CLAUDE.md` or rules file is loaded into context | Audit which instruction files load |

168| `WorktreeCreate` | No | Yes | Git worktree created | Track isolated workspaces |177| `WorktreeCreate` | No | Yes | Git worktree created | Track isolated workspaces |

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

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

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

170 181 

171## Configure hooks182## Configure hooks

172 183 

173To configure a hook, pass it in the `hooks` field of your agent options (`ClaudeAgentOptions` in Python, the `options` object in TypeScript):184To configure a hook, pass it in the `hooks` field of your agent options (`ClaudeAgentOptions` in Python, the `options` object in TypeScript). This snippet assumes you have already defined a hook callback, like `protect_env_files` in Python or `protectEnvFiles` in TypeScript from the example above:

174 185 

175<CodeGroup>186<CodeGroup>

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


215 226 

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

217 228 

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

230 

218| Option | Type | Default | Description |231| Option | Type | Default | Description |

219| --------- | ---------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |232| --------- | ---------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

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

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

222| `timeout` | `number` | `60` | Timeout in seconds |235| `timeout` | `number` | `undefined` | Timeout in seconds. When omitted, the per-event default applies: 10 minutes for most events, 30 seconds for `UserPromptSubmit`. A few events run with shorter limits, such as 10 seconds for `MessageDisplay` |

223 236 

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

225 238 


258 271 

259#### Asynchronous output272#### Asynchronous output

260 273 

261By default, the agent waits for your hook to return before proceeding. If your hook performs a side effect, such as logging or sending a webhook, and doesn't need to influence the agent's behavior, you can return an async output instead. This tells the agent to continue immediately without waiting for the hook to finish:274By default, the agent waits for your hook to return before proceeding. If your hook performs a side effect, such as logging or sending a webhook, and doesn't need to influence the agent's behavior, you can return an async output instead. This tells the agent to continue immediately without waiting for the hook to finish. In this snippet, `send_to_logging_service` in Python and `sendToLoggingService` in TypeScript stand in for any logging function you define:

262 275 

263<CodeGroup>276<CodeGroup>

264 ```python Python theme={null}277 ```python Python theme={null}


288 301 

289## Examples302## Examples

290 303 

304Several examples in this section show only the callback function. To run one, register the callback under the matching event in the `hooks` field of your options, as shown in [Configure hooks](#configure-hooks).

305 

291### Modify tool input306### Modify tool input

292 307 

293This example intercepts Write tool calls and rewrites the `file_path` argument to prepend `/sandbox`, redirecting all file writes to a sandboxed directory. The callback returns `updatedInput` with the modified path and `permissionDecision: 'allow'` to auto-approve the rewritten operation:308This example intercepts Write tool calls and rewrites the `file_path` argument to prepend `/sandbox`, redirecting all file writes to a sandboxed directory. The callback returns `updatedInput` with the modified path and `permissionDecision: 'allow'` to auto-approve the rewritten operation:


469 484 

470Use multi-tool matchers to share one callback across related tools. This example registers three matchers with different scopes:485Use multi-tool matchers to share one callback across related tools. This example registers three matchers with different scopes:

471 486 

472* A pipe-separated exact list (`Write|Edit|Delete`) triggers `file_security_hook` only for file modification tools.487* A pipe-separated exact list (`Write|Edit|NotebookEdit`) triggers `file_security_hook` only for file modification tools.

473* A regex (`^mcp__`) triggers `mcp_audit_hook` for any MCP tool whose name starts with `mcp__`.488* A regex (`^mcp__`) triggers `mcp_audit_hook` for any MCP tool whose name starts with `mcp__`.

474* An omitted matcher triggers `global_logger` for every tool call regardless of name.489* An omitted matcher triggers `global_logger` for every tool call regardless of name.

475 490 


479 hooks={494 hooks={

480 "PreToolUse": [495 "PreToolUse": [

481 # Match file modification tools496 # Match file modification tools

482 HookMatcher(matcher="Write|Edit|Delete", hooks=[file_security_hook]),497 HookMatcher(matcher="Write|Edit|NotebookEdit", hooks=[file_security_hook]),

483 # Match all MCP tools498 # Match all MCP tools

484 HookMatcher(matcher="^mcp__", hooks=[mcp_audit_hook]),499 HookMatcher(matcher="^mcp__", hooks=[mcp_audit_hook]),

485 # Match everything (no matcher)500 # Match everything (no matcher)


494 hooks: {509 hooks: {

495 PreToolUse: [510 PreToolUse: [

496 // Match file modification tools511 // Match file modification tools

497 { matcher: "Write|Edit|Delete", hooks: [fileSecurityHook] },512 { matcher: "Write|Edit|NotebookEdit", hooks: [fileSecurityHook] },

498 513 

499 // Match all MCP tools514 // Match all MCP tools

500 { matcher: "^mcp__", hooks: [mcpAuditHook] },515 { matcher: "^mcp__", hooks: [mcpAuditHook] },


650 665 

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

652 667 

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

654 669 

655<CodeGroup>670<CodeGroup>

656 ```python Python theme={null}671 ```python Python theme={null}

agent-sdk/mcp.md +23 −18

Details

643 643 

644### Query a database644### Query a database

645 645 

646This example uses the [Postgres MCP server](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/postgres) to query a database. The reference server is archived but still runs with `npx`. The connection string is passed as an argument to the server. The agent automatically discovers the database schema, writes the SQL query, and returns the results.646This example uses [DBHub](https://github.com/bytebase/dbhub) to query a Postgres database. The agent automatically discovers the database schema, writes the SQL query, and returns the results.

647 647 

648Before running, set the `DATABASE_URL` environment variable to your connection string. Replace the placeholder values with your own database details:648DBHub's `execute_sql` tool runs whatever SQL the agent emits, including writes, unless you restrict it. Setting `readonly = true` in the [DBHub configuration file](https://dbhub.ai/config/toml) makes DBHub reject `INSERT`, `UPDATE`, `DELETE`, and DDL statements, so the example cannot modify your data even if the agent emits a write. DBHub resolves `${DATABASE_URL}` from the process environment when it loads the config, so the connection string stays out of the file. Create this `dbhub.toml` next to your script:

649 

650```toml dbhub.toml theme={null}

651[[sources]]

652id = "production"

653dsn = "${DATABASE_URL}"

654 

655[[tools]]

656name = "execute_sql"

657source = "production"

658readonly = true

659```

660 

661The script then points DBHub at the config file instead of passing a connection string directly. Before running, set the `DATABASE_URL` environment variable to your connection string. Replace the placeholder values with your own database details:

649 662 

650```bash theme={null}663```bash theme={null}

651export DATABASE_URL=postgresql://user:password@localhost:5432/mydb664export DATABASE_URL=postgresql://user:password@localhost:5432/mydb


655 ```typescript TypeScript theme={null}668 ```typescript TypeScript theme={null}

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

657 670 

658 // Connection string from environment variable

659 const connectionString = process.env.DATABASE_URL;

660 

661 for await (const message of query({671 for await (const message of query({

662 // Natural language query - Claude writes the SQL672 // Natural language query - Claude writes the SQL

663 prompt: "How many users signed up last week? Break it down by day.",673 prompt: "How many users signed up last week? Break it down by day.",


665 mcpServers: {675 mcpServers: {

666 postgres: {676 postgres: {

667 command: "npx",677 command: "npx",

668 // Pass connection string as argument to the server678 // dbhub.toml sets readonly = true, so execute_sql rejects writes

669 args: ["-y", "@modelcontextprotocol/server-postgres", connectionString]679 args: ["-y", "@bytebase/dbhub", "--config", "dbhub.toml"]

670 }680 }

671 },681 },

672 // Allow only read queries, not writes682 allowedTools: ["mcp__postgres__execute_sql"]

673 allowedTools: ["mcp__postgres__query"]

674 }683 }

675 })) {684 })) {

676 if (message.type === "result" && message.subtype === "success") {685 if (message.type === "result" && message.subtype === "success") {


681 690 

682 ```python Python theme={null}691 ```python Python theme={null}

683 import asyncio692 import asyncio

684 import os

685 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage693 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

686 694 

687 695 

688 async def main():696 async def main():

689 # Connection string from environment variable

690 connection_string = os.environ["DATABASE_URL"]

691 

692 options = ClaudeAgentOptions(697 options = ClaudeAgentOptions(

693 mcp_servers={698 mcp_servers={

694 "postgres": {699 "postgres": {

695 "command": "npx",700 "command": "npx",

696 # Pass connection string as argument to the server701 # dbhub.toml sets readonly = true, so execute_sql rejects writes

697 "args": [702 "args": [

698 "-y",703 "-y",

699 "@modelcontextprotocol/server-postgres",704 "@bytebase/dbhub",

700 connection_string,705 "--config",

706 "dbhub.toml",

701 ],707 ],

702 }708 }

703 },709 },

704 # Allow only read queries, not writes710 allowed_tools=["mcp__postgres__execute_sql"],

705 allowed_tools=["mcp__postgres__query"],

706 )711 )

707 712 

708 # Natural language query - Claude writes the SQL713 # Natural language query - Claude writes the SQL

Details

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

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

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

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

123 123 

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

125 125 


455 session_id = None455 session_id = None

456 456 

457 # First query: capture the session ID457 # First query: capture the session ID

458 try:

458 async for message in query(459 async for message in query(

459 prompt="Read the authentication module",460 prompt="Read the authentication module",

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

461 ):462 ):

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

463 session_id = message.data["session_id"]464 session_id = message.data["session_id"]

465 except Exception as error:

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

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

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

469 # result message.

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

464 471 

465 # Resume with full context from the first query472 # Resume with full context from the first query

466 async for message in query(473 async for message in query(


480 let sessionId: string | undefined;487 let sessionId: string | undefined;

481 488 

482 // First query: capture the session ID489 // First query: capture the session ID

490 try {

483 for await (const message of query({491 for await (const message of query({

484 prompt: "Read the authentication module",492 prompt: "Read the authentication module",

485 options: { allowedTools: ["Read", "Glob"] }493 options: { allowedTools: ["Read", "Glob"] }


488 sessionId = message.session_id;496 sessionId = message.session_id;

489 }497 }

490 }498 }

499 } catch (error) {

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

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

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

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

504 }

491 505 

492 // Resume with full context from the first query506 // Resume with full context from the first query

493 for await (const message of query({507 for await (const message of query({

agent-sdk/python.md +233 −46

Details

57 57 

58## Functions58## Functions

59 59 

60<Note>Signature blocks and bare `async for` / `async with` fragments on this page are illustrative. To run them, wrap the body in `async def main(): ...` and call `asyncio.run(main())`.</Note>

61 

60### `query()`62### `query()`

61 63 

62Creates a new session for each interaction with Claude Code by default. Returns an async iterator that yields messages as they arrive. Each call to `query()` starts fresh with no memory of previous interactions unless you pass `continue_conversation=True` or `resume` in [`ClaudeAgentOptions`](#claudeagentoptions). See [Sessions](/en/agent-sdk/sessions).64Creates a new session for each interaction with Claude Code by default. Returns an async iterator that yields messages as they arrive. Each call to `query()` starts fresh with no memory of previous interactions unless you pass `continue_conversation=True` or `resume` in [`ClaudeAgentOptions`](#claudeagentoptions). See [Sessions](/en/agent-sdk/sessions).


93 options = ClaudeAgentOptions(95 options = ClaudeAgentOptions(

94 system_prompt="You are an expert Python developer",96 system_prompt="You are an expert Python developer",

95 permission_mode="acceptEdits",97 permission_mode="acceptEdits",

96 cwd="/home/user/project",

97 )98 )

98 99 

99 async for message in query(prompt="Create a Python web server", options=options):100 async for message in query(prompt="Create a Python web server", options=options):


215#### Example216#### Example

216 217 

217```python theme={null}218```python theme={null}

218from claude_agent_sdk import tool, create_sdk_mcp_server219from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeAgentOptions

219 220 

220 221 

221@tool("add", "Add two numbers", {"a": float, "b": float})222@tool("add", "Add two numbers", {"a": float, "b": float})


428```python theme={null}429```python theme={null}

429from claude_agent_sdk import list_sessions, tag_session430from claude_agent_sdk import list_sessions, tag_session

430 431 

431# Tag a session432# Tag the most recent session

432tag_session("550e8400-e29b-41d4-a716-446655440000", "needs-review")433sessions = list_sessions(directory="/path/to/project", limit=1)

434if sessions:

435 tag_session(sessions[0].session_id, "needs-review")

433 436 

434# Later: find all sessions with that tag437# Later: find all sessions with that tag

435for session in list_sessions(directory="/path/to/project"):438for session in list_sessions(directory="/path/to/project"):


496The client can be used as an async context manager for automatic connection management:499The client can be used as an async context manager for automatic connection management:

497 500 

498```python theme={null}501```python theme={null}

499async with ClaudeSDKClient() as client:502import asyncio

503from claude_agent_sdk import ClaudeSDKClient

504 

505 

506async def main():

507 async with ClaudeSDKClient() as client:

500 await client.query("Hello Claude")508 await client.query("Hello Claude")

501 async for message in client.receive_response():509 async for message in client.receive_response():

502 print(message)510 print(message)

511 

512 

513asyncio.run(main())

503```514```

504 515 

505> **Important:** When iterating over messages, avoid using `break` to exit early as this can cause asyncio cleanup issues. Instead, let the iteration complete naturally or use flags to track when you've found what you need.516> **Important:** When iterating over messages, avoid using `break` to exit early as this can cause asyncio cleanup issues. Instead, let the iteration complete naturally or use flags to track when you've found what you need.


635#### Example - Advanced permission control646#### Example - Advanced permission control

636 647 

637```python theme={null}648```python theme={null}

649import asyncio

638from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions650from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions

639from claude_agent_sdk.types import (651from claude_agent_sdk.types import (

640 PermissionResultAllow,652 PermissionResultAllow,


768 permission_mode: PermissionMode | None = None780 permission_mode: PermissionMode | None = None

769 continue_conversation: bool = False781 continue_conversation: bool = False

770 resume: str | None = None782 resume: str | None = None

783 session_id: str | None = None

771 max_turns: int | None = None784 max_turns: int | None = None

772 max_budget_usd: float | None = None785 max_budget_usd: float | None = None

773 disallowed_tools: list[str] = field(default_factory=list)786 disallowed_tools: list[str] = field(default_factory=list)


802 enable_file_checkpointing: bool = False815 enable_file_checkpointing: bool = False

803 session_store: SessionStore | None = None816 session_store: SessionStore | None = None

804 session_store_flush: SessionStoreFlushMode = "batched"817 session_store_flush: SessionStoreFlushMode = "batched"

818 load_timeout_ms: int = 60_000

819 task_budget: TaskBudget | None = None

805```820```

806 821 

807| Property | Type | Default | Description |822| Property | Type | Default | Description |


814| `permission_mode` | `PermissionMode \| None` | `None` | Permission mode for tool usage |829| `permission_mode` | `PermissionMode \| None` | `None` | Permission mode for tool usage |

815| `continue_conversation` | `bool` | `False` | Continue the most recent conversation |830| `continue_conversation` | `bool` | `False` | Continue the most recent conversation |

816| `resume` | `str \| None` | `None` | Session ID to resume |831| `resume` | `str \| None` | `None` | Session ID to resume |

832| `session_id` | `str \| None` | `None` | Use a specific session ID instead of an auto-generated one. Must be a valid UUID. Can't be combined with `continue_conversation` or `resume` unless `fork_session` is also set |

817| `max_turns` | `int \| None` | `None` | Maximum agentic turns (tool-use round trips) |833| `max_turns` | `int \| None` | `None` | Maximum agentic turns (tool-use round trips) |

818| `max_budget_usd` | `float \| None` | `None` | 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 |834| `max_budget_usd` | `float \| None` | `None` | 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 |

819| `disallowed_tools` | `list[str]` | `[]` | Tools to deny. A bare name such as `"Bash"` removes the tool from Claude's context. A scoped rule such as `"Bash(rm *)"` leaves the tool available and denies matching calls in every permission mode, including `bypassPermissions`. See [Permissions](/en/agent-sdk/permissions#allow-and-deny-rules) |835| `disallowed_tools` | `list[str]` | `[]` | Tools to deny. A bare name such as `"Bash"` removes the tool from Claude's context. A scoped rule such as `"Bash(rm *)"` leaves the tool available and denies matching calls in every permission mode, including `bypassPermissions`. See [Permissions](/en/agent-sdk/permissions#allow-and-deny-rules) |


848| `effort` | [`EffortLevel`](#effortlevel) ` \| None` | `None` | Effort level for thinking depth. See [adjust the effort level](/en/model-config#adjust-effort-level) |864| `effort` | [`EffortLevel`](#effortlevel) ` \| None` | `None` | Effort level for thinking depth. See [adjust the effort level](/en/model-config#adjust-effort-level) |

849| `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) |865| `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) |

850| `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` |866| `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` |

867| `load_timeout_ms` | `int` | `60000` | Per-call timeout for `session_store.load()` and `list_subkeys()` during resume materialization, in milliseconds |

868| `task_budget` | `TaskBudget \| None` | `None` | API-side token budget. Sent as `output_config.task_budget` with the `task-budgets-2026-03-13` beta header. Pass `{"total": <int>}`. |

851 869 

852#### Handle slow or stalled API responses870#### Handle slow or stalled API responses

853 871 

854The CLI subprocess reads several environment variables that control API timeouts and stall detection. Pass them through `ClaudeAgentOptions.env`:872The CLI subprocess reads several environment variables that control API timeouts and stall detection. Pass them through `ClaudeAgentOptions.env`:

855 873 

856```python theme={null}874```python theme={null}

875from claude_agent_sdk import ClaudeAgentOptions

876 

857options = ClaudeAgentOptions(877options = ClaudeAgentOptions(

858 env={878 env={

859 "API_TIMEOUT_MS": "120000",879 "API_TIMEOUT_MS": "120000",


943 963 

944```python theme={null}964```python theme={null}

945# Do not load user, project, or local settings from disk965# Do not load user, project, or local settings from disk

966import asyncio

946from claude_agent_sdk import query, ClaudeAgentOptions967from claude_agent_sdk import query, ClaudeAgentOptions

947 968 

948async for message in query(969 

970async def main():

971 async for message in query(

949 prompt="Analyze this code",972 prompt="Analyze this code",

950 options=ClaudeAgentOptions(973 options=ClaudeAgentOptions(

951 setting_sources=[]974 setting_sources=[]

952 ),975 ),

953):976 ):

954 print(message)977 print(message)

978 

979 

980asyncio.run(main())

955```981```

956 982 

957<Note>983<Note>


961**Load all filesystem settings explicitly:**987**Load all filesystem settings explicitly:**

962 988 

963```python theme={null}989```python theme={null}

990import asyncio

964from claude_agent_sdk import query, ClaudeAgentOptions991from claude_agent_sdk import query, ClaudeAgentOptions

965 992 

966async for message in query(993 

994async def main():

995 async for message in query(

967 prompt="Analyze this code",996 prompt="Analyze this code",

968 options=ClaudeAgentOptions(997 options=ClaudeAgentOptions(

969 setting_sources=["user", "project", "local"]998 setting_sources=["user", "project", "local"]

970 ),999 ),

971):1000 ):

972 print(message)1001 print(message)

1002 

1003 

1004asyncio.run(main())

973```1005```

974 1006 

975**Load only specific setting sources:**1007**Load only specific setting sources:**

976 1008 

977```python theme={null}1009```python theme={null}

978# Load only project settings, ignore user and local1010# Load only project settings, ignore user and local

979async for message in query(1011import asyncio

1012from claude_agent_sdk import query, ClaudeAgentOptions

1013 

1014 

1015async def main():

1016 async for message in query(

980 prompt="Run CI checks",1017 prompt="Run CI checks",

981 options=ClaudeAgentOptions(1018 options=ClaudeAgentOptions(

982 setting_sources=["project"] # Only .claude/settings.json1019 setting_sources=["project"] # Only .claude/settings.json

983 ),1020 ),

984):1021 ):

985 print(message)1022 print(message)

1023 

1024 

1025asyncio.run(main())

986```1026```

987 1027 

988**Testing and CI environments:**1028**Testing and CI environments:**

989 1029 

990```python theme={null}1030```python theme={null}

991# Ensure consistent behavior in CI by excluding local settings1031# Ensure consistent behavior in CI by excluding local settings

992async for message in query(1032import asyncio

1033from claude_agent_sdk import query, ClaudeAgentOptions

1034 

1035 

1036async def main():

1037 async for message in query(

993 prompt="Run tests",1038 prompt="Run tests",

994 options=ClaudeAgentOptions(1039 options=ClaudeAgentOptions(

995 setting_sources=["project"], # Only team-shared settings1040 setting_sources=["project"], # Only team-shared settings

996 permission_mode="bypassPermissions",1041 permission_mode="bypassPermissions",

997 ),1042 ),

998):1043 ):

999 print(message)1044 print(message)

1045 

1046 

1047asyncio.run(main())

1000```1048```

1001 1049 

1002**SDK-only applications:**1050**SDK-only applications:**


1004```python theme={null}1052```python theme={null}

1005# Define everything programmatically.1053# Define everything programmatically.

1006# Pass [] to opt out of filesystem setting sources.1054# Pass [] to opt out of filesystem setting sources.

1007async for message in query(1055import asyncio

1056from claude_agent_sdk import AgentDefinition, ClaudeAgentOptions, query

1057 

1058 

1059async def main():

1060 async for message in query(

1008 prompt="Review this PR",1061 prompt="Review this PR",

1009 options=ClaudeAgentOptions(1062 options=ClaudeAgentOptions(

1010 setting_sources=[],1063 setting_sources=[],

1011 agents={...},1064 agents={

1012 mcp_servers={...},1065 "code-reviewer": AgentDefinition(

1066 description="Reviews code changes",

1067 prompt="You are a code reviewer. Report issues in the diff.",

1068 ),

1069 },

1013 allowed_tools=["Read", "Grep", "Glob"],1070 allowed_tools=["Read", "Grep", "Glob"],

1014 ),1071 ),

1015):1072 ):

1016 print(message)1073 print(message)

1074 

1075 

1076asyncio.run(main())

1017```1077```

1018 1078 

1019**Loading CLAUDE.md project instructions:**1079**Loading CLAUDE.md project instructions:**

1020 1080 

1021```python theme={null}1081```python theme={null}

1022# Load project settings to include CLAUDE.md files1082# Load project settings to include CLAUDE.md files

1023async for message in query(1083import asyncio

1084from claude_agent_sdk import query, ClaudeAgentOptions

1085 

1086 

1087async def main():

1088 async for message in query(

1024 prompt="Add a new feature following project conventions",1089 prompt="Add a new feature following project conventions",

1025 options=ClaudeAgentOptions(1090 options=ClaudeAgentOptions(

1026 system_prompt={1091 system_prompt={


1030 setting_sources=["project"], # Loads CLAUDE.md from project1095 setting_sources=["project"], # Loads CLAUDE.md from project

1031 allowed_tools=["Read", "Write", "Edit"],1096 allowed_tools=["Read", "Write", "Edit"],

1032 ),1097 ),

1033):1098 ):

1034 print(message)1099 print(message)

1100 

1101 

1102asyncio.run(main())

1035```1103```

1036 1104 

1037#### Settings precedence1105#### Settings precedence


1097 "plan", # Planning mode - explore without editing1165 "plan", # Planning mode - explore without editing

1098 "dontAsk", # Deny anything not pre-approved instead of prompting1166 "dontAsk", # Deny anything not pre-approved instead of prompting

1099 "bypassPermissions", # Bypass permission checks; explicit ask rules still prompt (use with caution)1167 "bypassPermissions", # Bypass permission checks; explicit ask rules still prompt (use with caution)

1100 "auto", # A model classifier approves or denies each tool call1168 "auto", # Model classifier approves or denies permission prompts

1101]1169]

1102```1170```

1103 1171 


1146class ToolPermissionContext:1214class ToolPermissionContext:

1147 signal: Any | None = None # Future: abort signal support1215 signal: Any | None = None # Future: abort signal support

1148 suggestions: list[PermissionUpdate] = field(default_factory=list)1216 suggestions: list[PermissionUpdate] = field(default_factory=list)

1217 tool_use_id: str | None = None

1218 agent_id: str | None = None

1149 blocked_path: str | None = None1219 blocked_path: str | None = None

1150 decision_reason: str | None = None1220 decision_reason: str | None = None

1151 title: str | None = None1221 title: str | None = None


1157| :---------------- | :----------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |1227| :---------------- | :----------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

1158| `signal` | `Any \| None` | Reserved for future abort signal support |1228| `signal` | `Any \| None` | Reserved for future abort signal support |

1159| `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. |1229| `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. |

1230| `tool_use_id` | `str \| None` | Identifier of the specific tool call this prompt is for. Always populated when delivered to `can_use_tool` |

1231| `agent_id` | `str \| None` | Sub-agent ID when the call originates from a subagent; `None` for the main agent |

1160| `blocked_path` | `str \| None` | File path that triggered the permission request, when applicable. For example, when a Bash command tries to access a path outside allowed directories |1232| `blocked_path` | `str \| None` | File path that triggered the permission request, when applicable. For example, when a Bash command tries to access a path outside allowed directories |

1161| `decision_reason` | `str \| None` | Reason this permission request was triggered. Forwarded from a PreToolUse hook's `permissionDecisionReason` when the hook returned `"ask"` |1233| `decision_reason` | `str \| None` | Reason this permission request was triggered. Forwarded from a PreToolUse hook's `permissionDecisionReason` when the hook returned `"ask"` |

1162| `title` | `str \| None` | Full permission prompt sentence, such as `Claude wants to read foo.txt`. Use as the primary prompt text when present |1234| `title` | `str \| None` | Full permission prompt sentence, such as `Claude wants to read foo.txt`. Use as the primary prompt text when present |


1309# config.budget_tokens would raise AttributeError1381# config.budget_tokens would raise AttributeError

1310```1382```

1311 1383 

1384### `TaskBudget`

1385 

1386API-side task budget in tokens, used with the `task_budget` field in `ClaudeAgentOptions`.

1387 

1388```python theme={null}

1389class TaskBudget(TypedDict):

1390 total: int

1391```

1392 

1393| Field | Type | Description |

1394| :------ | :---- | :------------------------------ |

1395| `total` | `int` | Total token budget for the task |

1396 

1397Because this is a `TypedDict`, pass it as a plain dict, such as `ClaudeAgentOptions(task_budget={"total": 50000})`.

1398 

1312### `SdkBeta`1399### `SdkBeta`

1313 1400 

1314Literal type for SDK beta features.1401Literal type for SDK beta features.


1498 error: AssistantMessageError | None = None1585 error: AssistantMessageError | None = None

1499 usage: dict[str, Any] | None = None1586 usage: dict[str, Any] | None = None

1500 message_id: str | None = None1587 message_id: str | None = None

1588 stop_reason: str | None = None

1589 session_id: str | None = None

1590 uuid: str | None = None

1501```1591```

1502 1592 

1503| Field | Type | Description |1593| Field | Type | Description |


1508| `error` | [`AssistantMessageError`](#assistantmessageerror) ` \| None` | Error type if the response encountered an error |1598| `error` | [`AssistantMessageError`](#assistantmessageerror) ` \| None` | Error type if the response encountered an error |

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

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

1601| `stop_reason` | `str \| None` | Stop reason from the API (e.g. `end_turn`, `tool_use`) |

1602| `session_id` | `str \| None` | ID of the session this message belongs to |

1603| `uuid` | `str \| None` | Unique message identifier within the session transcript |

1511 1604 

1512### `AssistantMessageError`1605### `AssistantMessageError`

1513 1606 


1898```1991```

1899 1992 

1900<Note>1993<Note>

1901 The TypeScript SDK supports additional hook events not yet available in Python: `SessionStart`, `SessionEnd`, `Setup`, `TeammateIdle`, `TaskCompleted`, `ConfigChange`, `WorktreeCreate`, `WorktreeRemove`, `PostToolBatch`, and `MessageDisplay`.1994 The TypeScript SDK supports additional hook events not yet available in Python. See the [hook availability table](/en/agent-sdk/hooks#available-hooks) for per-SDK support.

1902</Note>1995</Note>

1903 1996 

1904### `HookCallback`1997### `HookCallback`


1944 default_factory=list2037 default_factory=list

1945 ) # List of callbacks to execute2038 ) # List of callbacks to execute

1946 timeout: float | None = (2039 timeout: float | None = (

1947 None # Timeout in seconds for all hooks in this matcher (default: 60)2040 None # Timeout in seconds. When omitted, the per-event default applies

1948 )2041 )

1949```2042```

1950 2043 


2297This example registers two hooks: one that blocks dangerous bash commands like `rm -rf /`, and another that logs all tool usage for auditing. The security hook only runs on Bash commands (via the `matcher`), while the logging hook runs on all tools.2390This example registers two hooks: one that blocks dangerous bash commands like `rm -rf /`, and another that logs all tool usage for auditing. The security hook only runs on Bash commands (via the `matcher`), while the logging hook runs on all tools.

2298 2391 

2299```python theme={null}2392```python theme={null}

2393import asyncio

2300from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher, HookContext2394from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher, HookContext

2301from typing import Any2395from typing import Any

2302 2396 


2334 ), # 2 min for validation2428 ), # 2 min for validation

2335 HookMatcher(2429 HookMatcher(

2336 hooks=[log_tool_use]2430 hooks=[log_tool_use]

2337 ), # Applies to all tools (default 60s timeout)2431 ), # Applies to all tools (per-event default timeout)

2338 ],2432 ],

2339 "PostToolUse": [HookMatcher(hooks=[log_tool_use])],2433 "PostToolUse": [HookMatcher(hooks=[log_tool_use])],

2340 }2434 }

2341)2435)

2342 2436 

2343async for message in query(prompt="Analyze this codebase", options=options):2437async def main():

2438 async for message in query(prompt="Analyze this codebase", options=options):

2344 print(message)2439 print(message)

2440 

2441 

2442asyncio.run(main())

2345```2443```

2346 2444 

2347## Tool Input/Output Types2445## Tool Input/Output Types


2350 2448 

2351### Agent2449### Agent

2352 2450 

2353**Tool name:** `Agent` (previously `Task`, which is still accepted as an alias)2451**Tool name:** `Agent`. The previous name `Task` is still accepted as an alias, and the `tools` list in the init [`SystemMessage`](#systemmessage) reports this tool as `Task` for backward compatibility.

2354 2452 

2355**Input:**2453**Input:**

2356 2454 


2358{2456{

2359 "description": str, # A short (3-5 word) description of the task2457 "description": str, # A short (3-5 word) description of the task

2360 "prompt": str, # The task for the agent to perform2458 "prompt": str, # The task for the agent to perform

2361 "subagent_type": str, # The type of specialized agent to use2459 "subagent_type": str | None, # The type of specialized agent to use

2460 "model": "sonnet" | "opus" | "haiku" | "fable" | None, # Model override for this agent

2461 "run_in_background": bool | None, # Launch the agent in the background

2462 "name": str | None, # Name for the spawned agent

2463 "mode": "acceptEdits" | "auto" | "bypassPermissions" | "default" | "dontAsk" | "plan" | None, # Permission mode for the agent

2464 "isolation": "worktree" | "remote" | None, # Isolation mode for the agent's changes

2362}2465}

2363```2466```

2364 2467 

2365**Output:**2468Launches a new agent to handle complex, multi-step tasks autonomously.

2469 

2470**Output (status: `"completed"`):**

2366 2471 

2367```python theme={null}2472```python theme={null}

2368{2473{

2369 "result": str, # Final result from the subagent2474 "status": "completed",

2370 "usage": dict | None, # Token usage statistics2475 "agentId": str, # ID of the agent that ran

2371 "total_cost_usd": float | None, # Estimated total cost in USD2476 "agentType": str | None, # The subagent type that handled the task

2372 "duration_ms": int | None, # Execution duration in milliseconds2477 "content": [ # Result content blocks

2478 {

2479 "type": "text",

2480 "text": str,

2481 "citations": list | None,

2482 }

2483 ],

2484 "resolvedModel": str | None, # Model the subagent actually ran on

2485 "totalToolUseCount": int, # Number of tool calls the agent made

2486 "totalDurationMs": int, # Execution duration in milliseconds

2487 "totalTokens": int, # Total tokens used

2488 "usage": { # Token usage statistics

2489 "input_tokens": int,

2490 "output_tokens": int,

2491 "cache_creation_input_tokens": int | None,

2492 "cache_read_input_tokens": int | None,

2493 "server_tool_use": {"web_search_requests": int, "web_fetch_requests": int} | None,

2494 "service_tier": str | None,

2495 "cache_creation": {"ephemeral_1h_input_tokens": int, "ephemeral_5m_input_tokens": int} | None,

2496 "inference_geo": str | None,

2497 "speed": str | None,

2498 "iterations": Any | None,

2499 },

2500 "toolStats": { # Aggregate tool activity for the run

2501 "readCount": int,

2502 "searchCount": int,

2503 "bashCount": int,

2504 "editFileCount": int,

2505 "linesAdded": int,

2506 "linesRemoved": int,

2507 "otherToolCount": int,

2508 "frameCount": int | None,

2509 } | None,

2510 "prompt": str, # The prompt the agent ran

2511 "worktreePath": str | None, # Present for worktree-isolated runs

2512 "worktreeBranch": str | None, # Present for worktree-isolated runs

2373}2513}

2374```2514```

2375 2515 

2516**Output (status: `"async_launched"`):**

2517 

2518```python theme={null}

2519{

2520 "status": "async_launched",

2521 "isAsync": bool | None, # True on background launches

2522 "agentId": str, # ID of the launched agent

2523 "description": str, # The task description

2524 "resolvedModel": str | None, # Model the subagent runs on

2525 "prompt": str, # The prompt the agent runs

2526 "outputFile": str, # File path where the agent's output is written

2527 "canReadOutputFile": bool | None, # Whether the output file can be read directly

2528}

2529```

2530 

2531**Output (status: `"remote_launched"`):**

2532 

2533```python theme={null}

2534{

2535 "status": "remote_launched",

2536 "taskId": str, # ID of the remote task

2537 "sessionUrl": str, # Link to the remote cloud session

2538 "description": str, # The task description

2539 "prompt": str, # The prompt the agent runs

2540 "outputFile": str, # File path where the agent's output is written

2541}

2542```

2543 

2544Returns the result from the subagent. The output is discriminated on the `status` field: `"completed"` for finished tasks, `"async_launched"` for background tasks, and `"remote_launched"` for tasks Claude Code dispatched to a remote cloud session, where `sessionUrl` links to that session and `taskId` identifies it. Worktree-isolated runs include `worktreePath` and `worktreeBranch` on the `completed` variant.

2545 

2546The `resolvedModel` field on the `completed` and `async_launched` variants names the model the subagent actually ran on, which can differ from the requested `model` input when [`availableModels`](/en/model-config#restrict-model-selection) or another override applies. {/* min-version: 2.1.174 */}This field requires Claude Code v2.1.174 or later.

2547 

2376### AskUserQuestion2548### AskUserQuestion

2377 2549 

2378**Tool name:** `AskUserQuestion`2550**Tool name:** `AskUserQuestion`


2396 "multiSelect": bool, # Set to true to allow multiple selections2568 "multiSelect": bool, # Set to true to allow multiple selections

2397 }2569 }

2398 ],2570 ],

2399 "answers": dict[str, str | list[str]] | None,2571 "answers": dict[str, str] | None,

2400 # User answers populated by the permission system. Multi-select2572 # User answers populated by the permission system. Multi-select

2401 # answers may be a list of labels or a comma-joined string2573 # answers are a comma-joined string of the selected labels; a

2574 # list of labels is accepted on input and coerced to that form

2402}2575}

2403```2576```

2404 2577 


2845}3018}

2846```3019```

2847 3020 

2848### BashOutput3021### TaskOutput

3022 

3023**Tool name:** `TaskOutput`. The previous name `BashOutput` is still accepted as an alias.

2849 3024 

2850**Tool name:** `BashOutput`3025<Note>`TaskOutput` is deprecated; prefer `Read` on the task's output file path. {/* min-version: 2.1.83 */}Deprecated since Claude Code v2.1.83. The schemas below remain valid for hooks and permission handlers that encounter the tool.</Note>

2851 3026 

2852**Input:**3027**Input:**

2853 3028 

2854```python theme={null}3029```python theme={null}

2855{3030{

2856 "bash_id": str, # The ID of the background shell3031 "task_id": str, # The task ID to get output from

2857 "filter": str | None, # Optional regex to filter output lines3032 "block": bool, # Whether to wait for completion (default True)

3033 "timeout": int, # Max wait time in ms (default 30000)

2858}3034}

2859```3035```

2860 3036 


2862 3038 

2863```python theme={null}3039```python theme={null}

2864{3040{

2865 "output": str, # New output since last check3041 "retrieval_status": "success" | "timeout" | "not_ready", # Whether the output was retrieved

2866 "status": "running" | "completed" | "failed", # Current shell status3042 "task": dict | None, # Task details: task_id, task_type, status, description, output, plus type-specific fields such as exitCode

2867 "exitCode": int | None, # Exit code when completed

2868}3043}

2869```3044```

2870 3045 

2871### KillBash3046### TaskStop

2872 3047 

2873**Tool name:** `KillBash`3048**Tool name:** `TaskStop`. The previous names `KillShell` and `KillBash` are still accepted as aliases.

2874 3049 

2875**Input:**3050**Input:**

2876 3051 

2877```python theme={null}3052```python theme={null}

2878{3053{

2879 "shell_id": str # The ID of the background shell to kill3054 "task_id": str | None, # The ID of the background task to stop

3055 "shell_id": str | None, # Deprecated: use task_id instead

2880}3056}

2881```3057```

2882 3058 


2884 3060 

2885```python theme={null}3061```python theme={null}

2886{3062{

2887 "message": str, # Success message3063 "message": str, # Status message about the operation

2888 "shell_id": str, # ID of the killed shell3064 "task_id": str, # The ID of the task that was stopped

3065 "task_type": str, # The type of the task that was stopped

3066 "command": str | None, # The command or description of the stopped task

2889}3067}

2890```3068```

2891 3069 


3182 options = ClaudeAgentOptions(3360 options = ClaudeAgentOptions(

3183 allowed_tools=["Read", "Write", "Bash"],3361 allowed_tools=["Read", "Write", "Bash"],

3184 permission_mode="acceptEdits",3362 permission_mode="acceptEdits",

3185 cwd="/home/user/project",

3186 )3363 )

3187 3364 

3188 async for message in query(3365 async for message in query(


3448</Note>3625</Note>

3449 3626 

3450```python theme={null}3627```python theme={null}

3628import asyncio

3451from claude_agent_sdk import (3629from claude_agent_sdk import (

3452 query,3630 query,

3453 ClaudeAgentOptions,3631 ClaudeAgentOptions,


3458)3636)

3459 3637 

3460 3638 

3639def is_command_authorized(command: str | None) -> bool:

3640 # Replace with your own authorization logic

3641 return False

3642 

3643 

3644 

3461async def can_use_tool(3645async def can_use_tool(

3462 tool: str, input: dict, context: ToolPermissionContext3646 tool: str, input: dict, context: ToolPermissionContext

3463) -> PermissionResultAllow | PermissionResultDeny:3647) -> PermissionResultAllow | PermissionResultDeny:


3500 ),3684 ),

3501 ):3685 ):

3502 print(message)3686 print(message)

3687 

3688 

3689asyncio.run(main())

3503```3690```

3504 3691 

3505This pattern enables you to:3692This pattern enables you to:

Details

45 npm install --save-dev tsx45 npm install --save-dev tsx

46 ```46 ```

47 47 

48 Setting `"type": "module"` in `package.json` lets your agent script use top-level `await`, and [tsx](https://tsx.is) runs TypeScript files directly.48 Setting `"type": "module"` in `package.json` lets your agent script use top-level `await`, and [tsx](https://tsx.is) runs TypeScript files directly. npm prints `added N packages` when the install succeeds.

49 </Tab>49 </Tab>

50 50 

51 <Tab title="TypeScript (existing project)">51 <Tab title="TypeScript (existing project)">


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

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

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

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

122 122 

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

124 124 


352**Permission modes** control how much human oversight you want:352**Permission modes** control how much human oversight you want:

353 353 

354| Mode | Behavior | Use case |354| Mode | Behavior | Use case |

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

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

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

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

359| `auto` | A model classifier approves or denies each tool call | Autonomous agents with safety guardrails |359| `auto` | A model classifier approves or denies each tool call | Autonomous agents with safety guardrails |

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

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

362 362 

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

Details

112 const store = new InMemorySessionStore();112 const store = new InMemorySessionStore();

113 113 

114 let sessionId: string | undefined;114 let sessionId: string | undefined;

115 try {

115 for await (const message of query({116 for await (const message of query({

116 prompt: "List the TypeScript files under src/",117 prompt: "List the TypeScript files under src/",

117 options: { sessionStore: store },118 options: { sessionStore: store },


120 sessionId = message.session_id;121 sessionId = message.session_id;

121 }122 }

122 }123 }

124 } catch (error) {

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

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

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

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

129 }

123 130 

124 // Resume from the store. The agent has full context from the first call.131 // Resume from the store. The agent has full context from the first call.

125 for await (const message of query({132 for await (const message of query({


146 153 

147 async def main():154 async def main():

148 session_id = None155 session_id = None

156 try:

149 async for message in query(157 async for message in query(

150 prompt="List the Python files under src/",158 prompt="List the Python files under src/",

151 options=ClaudeAgentOptions(session_store=store),159 options=ClaudeAgentOptions(session_store=store),

152 ):160 ):

153 if isinstance(message, ResultMessage):161 if isinstance(message, ResultMessage):

154 session_id = message.session_id162 session_id = message.session_id

163 except Exception as error:

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

165 # failure was an error result, session_id was already captured by the

166 # loop above; connection or process failures yield no result message.

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

155 168 

156 # Resume from the store. The agent has full context from the first call.169 # Resume from the store. The agent has full context from the first call.

157 async for message in query(170 async for message in query(


228 241 

229@pytest.mark.asyncio242@pytest.mark.asyncio

230async def test_my_store_conformance():243async def test_my_store_conformance():

231 await run_session_store_conformance(MyRedisStore)244 await run_session_store_conformance(MyRedisStore) # Your adapter class

232```245```

233 246 

234## Behavior notes247## Behavior notes

Details

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

111 111 

112// First query: creates a new session112// First query: creates a new session

113for await (const message of query({113try {

114 for await (const message of query({

114 prompt: "Analyze the auth module",115 prompt: "Analyze the auth module",

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

116})) {117 })) {

117 if (message.type === "result" && message.subtype === "success") {118 if (message.type === "result" && message.subtype === "success") {

118 console.log(message.result);119 console.log(message.result);

119 }120 }

121 }

122} catch (error) {

123 // A single-shot query() throws after yielding an error result,

124 // so the follow-up query below still runs.

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

120}126}

121 127 

122// Second query: continue: true resumes the most recent session128// Second query: continue: true resumes the most recent session


213Pass a session ID to `resume` to return to that specific session. The agent picks up with full context from wherever the session left off. Common reasons to resume:219Pass a session ID to `resume` to return to that specific session. The agent picks up with full context from wherever the session left off. Common reasons to resume:

214 220 

215* **Follow up on a completed task.** The agent already analyzed something; now you want it to act on that analysis without re-reading files.221* **Follow up on a completed task.** The agent already analyzed something; now you want it to act on that analysis without re-reading files.

216* **Recover from a limit.** The first run ended with `error_max_turns` or `error_max_budget_usd` (see [Handle the result](/en/agent-sdk/agent-loop#handle-the-result)); resume with a higher limit.222* **Recover from a limit.** The first run ended with `error_max_turns` or `error_max_budget_usd` (see [Handle the result](/en/agent-sdk/agent-loop#handle-the-result)); resume with a higher limit. In a single-shot `query()` call the SDK raises after yielding that error result, so catch the error before resuming.

217* **Restart your process.** You captured the ID before shutdown and want to restore the conversation.223* **Restart your process.** You captured the ID before shutdown and want to restore the conversation.

218 224 

219This example resumes the session from [Capture the session ID](#capture-the-session-id) with a follow-up prompt. Because you're resuming, the agent already has the prior analysis in context:225This example resumes the session from [Capture the session ID](#capture-the-session-id) with a follow-up prompt. Because you're resuming, the agent already has the prior analysis in context:


291 async def main():297 async def main():

292 # Fork: branch from session_id into a new session298 # Fork: branch from session_id into a new session

293 forked_id = None299 forked_id = None

300 try:

294 async for message in query(301 async for message in query(

295 prompt="Instead of JWT, outline how OAuth2 would work for the auth module",302 prompt="Instead of JWT, outline how OAuth2 would work for the auth module",

296 options=ClaudeAgentOptions(303 options=ClaudeAgentOptions(


303 forked_id = message.session_id # The fork's ID, distinct from session_id310 forked_id = message.session_id # The fork's ID, distinct from session_id

304 if message.subtype == "success":311 if message.subtype == "success":

305 print(message.result)312 print(message.result)

313 except Exception as error:

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

315 # failure was an error result, forked_id was already captured by the

316 # loop above; connection or process failures yield no result message.

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

306 318 

307 print(f"Forked session: {forked_id}")319 print(f"Forked session: {forked_id}")

308 320 

309 # Original session is untouched; resuming it continues the JWT thread321 # Original session is untouched; resuming it continues the JWT thread

322 try:

310 async for message in query(323 async for message in query(

311 prompt="Continue with the JWT approach",324 prompt="Continue with the JWT approach",

312 options=ClaudeAgentOptions(resume=session_id),325 options=ClaudeAgentOptions(resume=session_id),

313 ):326 ):

314 if isinstance(message, ResultMessage) and message.subtype == "success":327 if isinstance(message, ResultMessage) and message.subtype == "success":

315 print(message.result)328 print(message.result)

329 except Exception as error:

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

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

316 332 

317 333 

318 asyncio.run(main())334 asyncio.run(main())


326 // Fork: branch from sessionId into a new session342 // Fork: branch from sessionId into a new session

327 let forkedId: string | undefined;343 let forkedId: string | undefined;

328 344 

345 try {

329 for await (const message of query({346 for await (const message of query({

330 prompt: "Instead of JWT, outline how OAuth2 would work for the auth module",347 prompt: "Instead of JWT, outline how OAuth2 would work for the auth module",

331 options: {348 options: {


341 console.log(message.result);358 console.log(message.result);

342 }359 }

343 }360 }

361 } catch (error) {

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

363 // failure was an error result, forkedId was already captured by the loop

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

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

366 }

344 367 

345 console.log(`Forked session: ${forkedId}`);368 console.log(`Forked session: ${forkedId}`);

346 369 

347 // Original session is untouched; resuming it continues the JWT thread370 // Original session is untouched; resuming it continues the JWT thread

371 try {

348 for await (const message of query({372 for await (const message of query({

349 prompt: "Continue with the JWT approach",373 prompt: "Continue with the JWT approach",

350 options: { resume: sessionId }374 options: { resume: sessionId }


353 console.log(message.result);377 console.log(message.result);

354 }378 }

355 }379 }

380 } catch (error) {

381 // A single-shot query() throws after yielding an error result.

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

383 }

356 ```384 ```

357</CodeGroup>385</CodeGroup>

358 386 

Details

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

364 364 

365 // Pass arguments to custom command365 // Pass arguments to custom command

366 try {

366 for await (const message of query({367 for await (const message of query({

367 prompt: "/fix-issue 123 high",368 prompt: "/fix-issue 123 high",

368 options: { maxTurns: 5 }369 options: { maxTurns: 5 }


372 console.log("Issue fixed:", message.result);373 console.log("Issue fixed:", message.result);

373 }374 }

374 }375 }

376 } catch (err) {

377 // The run ends with an error when it reaches the maxTurns limit

378 console.error("Session ended with an error:", err);

379 }

375 ```380 ```

376 381 

377 ```python Python theme={null}382 ```python Python theme={null}


381 386 

382 async def main():387 async def main():

383 # Pass arguments to custom command388 # Pass arguments to custom command

389 try:

384 async for message in query(prompt="/fix-issue 123 high", options=ClaudeAgentOptions(max_turns=5)):390 async for message in query(prompt="/fix-issue 123 high", options=ClaudeAgentOptions(max_turns=5)):

385 # Command will process with $0="123" and $1="high"391 # Command will process with $0="123" and $1="high"

386 if isinstance(message, ResultMessage):392 if isinstance(message, ResultMessage):

387 print("Issue fixed:", message.result)393 print("Issue fixed:", message.result)

394 except Exception as error:

395 # The run ends with an error when it reaches the max_turns limit

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

388 397 

389 398 

390 asyncio.run(main())399 asyncio.run(main())

Details

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

251 251 

252 // Simple one-shot query252 // Simple one-shot query

253 // query() throws after an error result, such as error_max_turns

254 try {

253 for await (const message of query({255 for await (const message of query({

254 prompt: "Explain the authentication flow",256 prompt: "Explain the authentication flow",

255 options: {257 options: {


261 console.log(message.result);263 console.log(message.result);

262 }264 }

263 }265 }

266 } catch (error) {

267 console.error(`Query failed: ${error}`);

268 }

264 269 

265 // Continue conversation with session management270 // Continue conversation with session management

271 try {

266 for await (const message of query({272 for await (const message of query({

267 prompt: "Now explain the authorization process",273 prompt: "Now explain the authorization process",

268 options: {274 options: {


274 console.log(message.result);280 console.log(message.result);

275 }281 }

276 }282 }

283 } catch (error) {

284 console.error(`Query failed: ${error}`);

285 }

277 ```286 ```

278 287 

279 ```python Python theme={null}288 ```python Python theme={null}


283 292 

284 async def single_message_example():293 async def single_message_example():

285 # Simple one-shot query using query() function294 # Simple one-shot query using query() function

295 # query() raises after an error result, such as error_max_turns

296 try:

286 async for message in query(297 async for message in query(

287 prompt="Explain the authentication flow",298 prompt="Explain the authentication flow",

288 options=ClaudeAgentOptions(max_turns=5, allowed_tools=["Read", "Grep"]),299 options=ClaudeAgentOptions(max_turns=5, allowed_tools=["Read", "Grep"]),

289 ):300 ):

290 if isinstance(message, ResultMessage):301 if isinstance(message, ResultMessage) and message.subtype == "success":

291 print(message.result)302 print(message.result)

303 # The SDK raises a plain Exception for error results, so match Exception here

304 except Exception as e:

305 print(f"Query failed: {e}")

292 306 

293 # Continue conversation with session management307 # Continue conversation with session management

308 try:

294 async for message in query(309 async for message in query(

295 prompt="Now explain the authorization process",310 prompt="Now explain the authorization process",

296 options=ClaudeAgentOptions(continue_conversation=True, max_turns=5),311 options=ClaudeAgentOptions(continue_conversation=True, max_turns=5),

297 ):312 ):

298 if isinstance(message, ResultMessage):313 if isinstance(message, ResultMessage) and message.subtype == "success":

299 print(message.result)314 print(message.result)

315 except Exception as e:

316 print(f"Query failed: {e}")

300 317 

301 318 

302 asyncio.run(single_message_example())319 asyncio.run(single_message_example())

Details

73 required: ["company_name"]73 required: ["company_name"]

74 };74 };

75 75 

76 try {

76 for await (const message of query({77 for await (const message of query({

77 prompt: "Research Anthropic and provide key company information",78 prompt: "Research Anthropic and provide key company information",

78 options: {79 options: {


88 // { company_name: "Anthropic", founded_year: 2021, headquarters: "San Francisco, CA" }89 // { company_name: "Anthropic", founded_year: 2021, headquarters: "San Francisco, CA" }

89 }90 }

90 }91 }

92 } catch (error) {

93 // A single-shot query() throws after yielding an error result, such as

94 // error_max_structured_output_retries; see the Error handling section.

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

96 }

91 ```97 ```

92 98 

93 ```python Python theme={null}99 ```python Python theme={null}


107 113 

108 114 

109 async def main():115 async def main():

116 try:

110 async for message in query(117 async for message in query(

111 prompt="Research Anthropic and provide key company information",118 prompt="Research Anthropic and provide key company information",

112 options=ClaudeAgentOptions(119 options=ClaudeAgentOptions(


117 if isinstance(message, ResultMessage) and message.structured_output:124 if isinstance(message, ResultMessage) and message.structured_output:

118 print(message.structured_output)125 print(message.structured_output)

119 # {'company_name': 'Anthropic', 'founded_year': 2021, 'headquarters': 'San Francisco, CA'}126 # {'company_name': 'Anthropic', 'founded_year': 2021, 'headquarters': 'San Francisco, CA'}

127 except Exception as error:

128 # A single-shot query() raises after yielding an error result, such as

129 # error_max_structured_output_retries; see the Error handling section.

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

120 131 

121 132 

122 asyncio.run(main())133 asyncio.run(main())


129 140 

130The example below defines a schema for a feature implementation plan with a summary, list of steps (each with complexity level), and potential risks. The agent plans the feature and returns a typed `FeaturePlan` object. You can then access properties like `plan.summary` and iterate over `plan.steps` with full type safety.141The example below defines a schema for a feature implementation plan with a summary, list of steps (each with complexity level), and potential risks. The agent plans the feature and returns a typed `FeaturePlan` object. You can then access properties like `plan.summary` and iterate over `plan.steps` with full type safety.

131 142 

143The SDK validates schemas with JSON Schema draft-07, so schemas that declare a newer version are rejected. Zod targets draft 2020-12 by default, so pass `target: "draft-7"` when converting your schema.

144 

132<CodeGroup>145<CodeGroup>

133 ```typescript TypeScript theme={null}146 ```typescript TypeScript theme={null}

134 import { z } from "zod";147 import { z } from "zod";


150 163 

151 type FeaturePlan = z.infer<typeof FeaturePlan>;164 type FeaturePlan = z.infer<typeof FeaturePlan>;

152 165 

153 // Convert to JSON Schema166 // Convert to JSON Schema using the draft-07 target the SDK expects

154 const schema = z.toJSONSchema(FeaturePlan);167 const schema = z.toJSONSchema(FeaturePlan, { target: "draft-7" });

155 168 

156 // Use in query169 // Use in query

170 try {

157 for await (const message of query({171 for await (const message of query({

158 prompt:172 prompt:

159 "Plan how to add dark mode support to a React app. Break it into implementation steps.",173 "Plan how to add dark mode support to a React app. Break it into implementation steps.",


177 }191 }

178 }192 }

179 }193 }

194 } catch (error) {

195 // A single-shot query() throws after yielding an error result, such as

196 // error_max_structured_output_retries; see the Error handling section.

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

198 }

180 ```199 ```

181 200 

182 ```python Python theme={null}201 ```python Python theme={null}


199 218 

200 219 

201 async def main():220 async def main():

221 try:

202 async for message in query(222 async for message in query(

203 prompt="Plan how to add dark mode support to a React app. Break it into implementation steps.",223 prompt="Plan how to add dark mode support to a React app. Break it into implementation steps.",

204 options=ClaudeAgentOptions(224 options=ClaudeAgentOptions(


217 print(237 print(

218 f"{step.step_number}. [{step.estimated_complexity}] {step.description}"238 f"{step.step_number}. [{step.estimated_complexity}] {step.description}"

219 )239 )

240 except Exception as error:

241 # A single-shot query() raises after yielding an error result, such as

242 # error_max_structured_output_retries; see the Error handling section.

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

220 244 

221 245 

222 asyncio.run(main())246 asyncio.run(main())


235The `outputFormat` (TypeScript) or `output_format` (Python) option accepts an object with:259The `outputFormat` (TypeScript) or `output_format` (Python) option accepts an object with:

236 260 

237* `type`: Set to `"json_schema"` for structured outputs261* `type`: Set to `"json_schema"` for structured outputs

238* `schema`: A [JSON Schema](https://json-schema.org/understanding-json-schema/about) object defining your output structure. You can generate this from a Zod schema with `z.toJSONSchema()` or a Pydantic model with `.model_json_schema()`262* `schema`: A [JSON Schema](https://json-schema.org/understanding-json-schema/about) object defining your output structure. You can generate this from a Zod schema with `z.toJSONSchema(schema, { target: "draft-7" })` or a Pydantic model with `.model_json_schema()`

239 263 

240The SDK supports standard JSON Schema features including all basic types (object, array, string, number, boolean, null), `enum`, `const`, `required`, nested objects, and `$ref` definitions. For the full list of supported features and limitations, see [JSON Schema limitations](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#json-schema-limitations).264The SDK supports standard JSON Schema features including all basic types (object, array, string, number, boolean, null), `enum`, `const`, `required`, nested objects, and `$ref` definitions. For the full list of supported features and limitations, see [JSON Schema limitations](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#json-schema-limitations).

241 265 


277 };301 };

278 302 

279 // Agent uses Grep to find TODOs, Bash to get git blame info303 // Agent uses Grep to find TODOs, Bash to get git blame info

304 try {

280 for await (const message of query({305 for await (const message of query({

281 prompt: "Find all TODO comments in this codebase and identify who added them",306 prompt: "Find all TODO comments in this codebase and identify who added them",

282 options: {307 options: {


297 });322 });

298 }323 }

299 }324 }

325 } catch (error) {

326 // A single-shot query() throws after yielding an error result, such as

327 // error_max_structured_output_retries; see the Error handling section.

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

329 }

300 ```330 ```

301 331 

302 ```python Python theme={null}332 ```python Python theme={null}


329 359 

330 async def main():360 async def main():

331 # Agent uses Grep to find TODOs, Bash to get git blame info361 # Agent uses Grep to find TODOs, Bash to get git blame info

362 try:

332 async for message in query(363 async for message in query(

333 prompt="Find all TODO comments in this codebase and identify who added them",364 prompt="Find all TODO comments in this codebase and identify who added them",

334 options=ClaudeAgentOptions(365 options=ClaudeAgentOptions(


342 print(f"{todo['file']}:{todo['line']} - {todo['text']}")373 print(f"{todo['file']}:{todo['line']} - {todo['text']}")

343 if "author" in todo:374 if "author" in todo:

344 print(f" Added by {todo['author']} on {todo['date']}")375 print(f" Added by {todo['author']} on {todo['date']}")

376 except Exception as error:

377 # A single-shot query() raises after yielding an error result, such as

378 # error_max_structured_output_retries; see the Error handling section.

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

345 380 

346 381 

347 asyncio.run(main())382 asyncio.run(main())


350 385 

351## Error handling386## Error handling

352 387 

353Structured output generation can fail when the agent cannot produce valid JSON matching your schema. This typically happens when the schema is too complex for the task, the task itself is ambiguous, or the agent hits its retry limit trying to fix validation errors. It can also happen without any validation failure: a [model fallback](/en/model-config#automatic-model-fallback) can retract an already-completed output mid-stream, and if no retry replaces it the run ends with the same error. Check the `errors` field on the result message to tell the two causes apart before debugging your schema.388Structured output generation can fail when the agent cannot produce valid JSON matching your schema. This typically happens when the schema is too complex for the task, the task itself is ambiguous, or the agent hits its retry limit trying to fix validation errors. It can also happen without any validation failure: a [model fallback](/en/model-config#automatic-model-fallback) can retract an already-completed output mid-stream, and if no retry replaces it the run ends with the same error. Check the `errors` list on the result message to tell the two causes apart before debugging your schema.

354 389 

355When an error occurs, the result message has a `subtype` indicating what went wrong:390When an error occurs, the result message has a `subtype` indicating what went wrong:

356 391 


359| `success` | Output was generated and validated successfully |394| `success` | Output was generated and validated successfully |

360| `error_max_structured_output_retries` | No valid output remained after multiple attempts (validation failures, or a model-fallback retraction with no successful retry) |395| `error_max_structured_output_retries` | No valid output remained after multiple attempts (validation failures, or a model-fallback retraction with no successful retry) |

361 396 

362The example below checks the `subtype` field to determine whether the output was generated successfully or if you need to handle a failure:397A result can also end with subtype `success` but no `structured_output` value, for example when the run completes without the agent producing a structured output. Treat that case as a failure as well. The example below treats a result as successful only when the `subtype` is `success` and `structured_output` is present, and handles every other result as a failure:

363 398 

364<CodeGroup>399<CodeGroup>

365 ```typescript TypeScript theme={null}400 ```typescript TypeScript theme={null}


390 console.log(msg.structured_output);425 console.log(msg.structured_output);

391 } else if (msg.subtype === "error_max_structured_output_retries") {426 } else if (msg.subtype === "error_max_structured_output_retries") {

392 console.error("Could not produce valid output");427 console.error("Could not produce valid output");

428 } else {

429 console.error("Run ended without a structured output");

393 }430 }

394 }431 }

395 }432 }


431 print(message.structured_output)468 print(message.structured_output)

432 elif message.subtype == "error_max_structured_output_retries":469 elif message.subtype == "error_max_structured_output_retries":

433 print("Could not produce valid output")470 print("Could not produce valid output")

471 else:

472 print("Run ended without a structured output")

434 except Exception as error:473 except Exception as error:

435 # A single-shot query() raises after yielding an error result.474 # A single-shot query() raises after yielding an error result.

436 # If the failure was an error result, the subtype branches above475 # If the failure was an error result, the subtype branches above

Details

804 | "bypassPermissions" // Bypass permission checks; explicit ask rules still prompt804 | "bypassPermissions" // Bypass permission checks; explicit ask rules still prompt

805 | "plan" // Planning mode - explore without editing805 | "plan" // Planning mode - explore without editing

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

807 | "auto"; // Use a model classifier to approve or deny each tool call807 | "auto"; // Model classifier approves or denies permission prompts

808```808```

809 809 

810### `CanUseTool`810### `CanUseTool`


1838 run_in_background?: boolean;1838 run_in_background?: boolean;

1839 name?: string;1839 name?: string;

1840 mode?: "acceptEdits" | "auto" | "bypassPermissions" | "default" | "dontAsk" | "plan";1840 mode?: "acceptEdits" | "auto" | "bypassPermissions" | "default" | "dontAsk" | "plan";

1841 isolation?: "worktree";1841 isolation?: "worktree" | "remote";

1842};1842};

1843```1843```

1844 1844 

agent-view.md +2 −1

Details

389claude --agent code-reviewer --bg "address review comments on PR 1234"389claude --agent code-reviewer --bg "address review comments on PR 1234"

390```390```

391 391 

392If the name doesn't match any of your subagents, Claude Code prints a stderr warning, `warning: no agent named '<name>' spawning with default template`, and runs the session with the default agent.392If the name doesn't match any of your subagents, the launch fails: Claude Code prints a `no agent named` warning and still reports the session as backgrounded, but the session exits immediately with an `--agent '<name>' not found` error. {/* min-version: 2.1.212 */}Before v2.1.212, Claude Code ran the session with the default agent instead.

393 393 

394Pass `--name` to set the session's display name in agent view instead of the auto-generated one:394Pass `--name` to set the session's display name in agent view instead of the auto-generated one:

395 395 


770 770 

771| Version | Change |771| Version | Change |

772| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |772| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

773| v2.1.212 | {/* min-version: 2.1.212 */}`claude --bg` with an `--agent` name that doesn't match any of your subagents fails the launch: the session exits immediately with an `--agent '<name>' not found` error instead of running with the default agent. |

773| v2.1.211 | {/* min-version: 2.1.211 */}Waking a stopped session by attaching, peeking, or replying from the directory it runs in forwards your shell's gateway `ANTHROPIC_BASE_URL` again, under the same conditions as a fresh dispatch, so a session authenticated through a gateway `ANTHROPIC_AUTH_TOKEN` resumes on the gateway instead of reporting `Not logged in`. Opening a stopped session that was backgrounded from another conversation before its first response finished is refused with `This session has no saved transcript` instead of silently starting a blank conversation under the same session id. Ending the process of a `←` or `/background` session from outside Claude Code marks it stopped instead of the supervisor restarting it, a stop already recorded on disk is honored unless a reply you sent is still waiting to be delivered, a session restarted after a crash is told it was restarted, and a restarted `←` or `/background` session doesn't resume an interrupted response older than about an hour. A session-naming reply that answers or refuses the prompt instead of labeling it, such as for a prompt that's mostly a link, is discarded and the row keeps a name taken from the prompt text. Deleting a session whose worktree git no longer recognizes succeeds, leaving the worktree directory on disk and naming its path, instead of every attempt being refused. A refused delete shows the reason on the session's row, including the underlying git error when the worktree couldn't be removed, instead of the row silently reappearing. |774| v2.1.211 | {/* min-version: 2.1.211 */}Waking a stopped session by attaching, peeking, or replying from the directory it runs in forwards your shell's gateway `ANTHROPIC_BASE_URL` again, under the same conditions as a fresh dispatch, so a session authenticated through a gateway `ANTHROPIC_AUTH_TOKEN` resumes on the gateway instead of reporting `Not logged in`. Opening a stopped session that was backgrounded from another conversation before its first response finished is refused with `This session has no saved transcript` instead of silently starting a blank conversation under the same session id. Ending the process of a `←` or `/background` session from outside Claude Code marks it stopped instead of the supervisor restarting it, a stop already recorded on disk is honored unless a reply you sent is still waiting to be delivered, a session restarted after a crash is told it was restarted, and a restarted `←` or `/background` session doesn't resume an interrupted response older than about an hour. A session-naming reply that answers or refuses the prompt instead of labeling it, such as for a prompt that's mostly a link, is discarded and the row keeps a name taken from the prompt text. Deleting a session whose worktree git no longer recognizes succeeds, leaving the worktree directory on disk and naming its path, instead of every attempt being refused. A refused delete shows the reason on the session's row, including the underlying git error when the worktree couldn't be removed, instead of the row silently reappearing. |

774| v2.1.210 | {/* min-version: 2.1.210 */}`claude attach` waits while the background service is starting or reconnecting instead of failing with a `job not found` or `still starting` error, reports a session that finished during the attach as exited, and applies a terminal resize made during a slow attach when the attach completes. The prompt footer's `←` needs-input count appears on every provider, including third-party providers that previously showed the plain `← for agents` form. Backgrounding a session with `←` carries Claude's task list to the background session instead of dropping it. The row you pressed `←` from keeps a bold, undimmed name after the selection moves. `claude agents --effort` accepts `ultracode` instead of silently dropping it. |775| v2.1.210 | {/* min-version: 2.1.210 */}`claude attach` waits while the background service is starting or reconnecting instead of failing with a `job not found` or `still starting` error, reports a session that finished during the attach as exited, and applies a terminal resize made during a slow attach when the attach completes. The prompt footer's `←` needs-input count appears on every provider, including third-party providers that previously showed the plain `← for agents` form. Backgrounding a session with `←` carries Claude's task list to the background session instead of dropping it. The row you pressed `←` from keeps a bold, undimmed name after the selection moves. `claude agents --effort` accepts `ultracode` instead of silently dropping it. |

775| v2.1.208 | {/* min-version: 2.1.208 */}Attaching to a session whose process has stopped shows the last screenful of its transcript while the process starts, instead of only a `Session is starting` note. A reply that can't be delivered because the background service is unreachable or the send fails is saved and sent as the session's next prompt when its process starts again; before this release, a reply lost while the background service was unreachable was discarded. A process whose own binary was replaced by an update can still start the supervisor, from the installed `claude` launcher or the newest version on disk, instead of failing until Claude Code was restarted. A supervisor running an older version never restarts an idle session started by a newer version onto its own older binary. Deleting a session removes its worktree even after the session moved the worktree onto a different branch, and keeps the worktree together with the session row when the worktree has commits that aren't pushed anywhere or another session claims it, instead of destroying the commits or orphaning the worktree. `/install-github-app` and the `/mcp` settings list and its authentication actions are refused in a background session with a message naming the alternative; in v2.1.208 only, the `/model` picker was refused the same way and a typed `/model <name>` switched that session only instead of also saving your default model. |776| v2.1.208 | {/* min-version: 2.1.208 */}Attaching to a session whose process has stopped shows the last screenful of its transcript while the process starts, instead of only a `Session is starting` note. A reply that can't be delivered because the background service is unreachable or the send fails is saved and sent as the session's next prompt when its process starts again; before this release, a reply lost while the background service was unreachable was discarded. A process whose own binary was replaced by an update can still start the supervisor, from the installed `claude` launcher or the newest version on disk, instead of failing until Claude Code was restarted. A supervisor running an older version never restarts an idle session started by a newer version onto its own older binary. Deleting a session removes its worktree even after the session moved the worktree onto a different branch, and keeps the worktree together with the session row when the worktree has commits that aren't pushed anywhere or another session claims it, instead of destroying the commits or orphaning the worktree. `/install-github-app` and the `/mcp` settings list and its authentication actions are refused in a background session with a message naming the alternative; in v2.1.208 only, the `/model` picker was refused the same way and a typed `/model <name>` switched that session only instead of also saving your default model. |

Details

547* [Amazon Bedrock pricing](https://aws.amazon.com/bedrock/pricing/)547* [Amazon Bedrock pricing](https://aws.amazon.com/bedrock/pricing/)

548* [Amazon Bedrock inference profiles](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html)548* [Amazon Bedrock inference profiles](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html)

549* [Amazon Bedrock token burndown and quotas](https://docs.aws.amazon.com/bedrock/latest/userguide/quotas-token-burndown.html)549* [Amazon Bedrock token burndown and quotas](https://docs.aws.amazon.com/bedrock/latest/userguide/quotas-token-burndown.html)

550* [Claude Code on Amazon Bedrock: Quick Setup Guide](https://community.aws/content/2tXkZKrZzlrlu0KfH8gST5Dkppq/claude-code-on-amazon-bedrock-quick-setup-guide)550* [Claude Code on Amazon Bedrock: Quick Setup Guide](https://builder.aws.com/content/2tXkZKrZzlrlu0KfH8gST5Dkppq/claude-code-on-amazon-bedrock-quick-setup-guide)

551* [Claude Code Monitoring Implementation (Amazon Bedrock)](https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md)551* [Claude Code Monitoring Implementation (Amazon Bedrock)](https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md)

Details

180claude setup-token180claude setup-token

181```181```

182 182 

183The command walks you through OAuth authorization and prints a token to the terminal. It does not save the token anywhere; copy it and set it as the `CLAUDE_CODE_OAUTH_TOKEN` environment variable wherever you want to authenticate:183The command opens the same browser authorization flow as `/login`, and the token prints to the terminal after you approve access in the browser. It does not save the token anywhere; copy it and set it as the `CLAUDE_CODE_OAUTH_TOKEN` environment variable wherever you want to authenticate:

184 184 

185```bash theme={null}185```bash theme={null}

186export CLAUDE_CODE_OAUTH_TOKEN=your-token186export CLAUDE_CODE_OAUTH_TOKEN=your-token

187```187```

188 188 

189This token authenticates with your Claude subscription and requires a Pro, Max, Team, or Enterprise plan. It is scoped to inference only and cannot establish [Remote Control](/en/remote-control) sessions.189This token authenticates with your Claude subscription and requires a Pro, Max, Team, or Enterprise plan. It can only make model requests, so it can't establish [Remote Control](/en/remote-control) sessions or fetch [claude.ai connectors](/en/mcp#use-mcp-servers-from-claude-ai). MCP servers you configure locally still work.

190 190 

191[Bare mode](/en/headless#start-faster-with-bare-mode) does not read `CLAUDE_CODE_OAUTH_TOKEN`. If your script passes `--bare`, authenticate with `ANTHROPIC_API_KEY` or an `apiKeyHelper` instead.191[Bare mode](/en/headless#start-faster-with-bare-mode) does not read `CLAUDE_CODE_OAUTH_TOKEN`. If your script passes `--bare`, authenticate with `ANTHROPIC_API_KEY` or an `apiKeyHelper` instead.

Details

9[Auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) lets Claude Code run without routine permission prompts by routing tool calls through a classifier that blocks anything irreversible, destructive, or aimed outside your environment. Deny and explicit ask rules are evaluated before the classifier and still block or prompt. Use the `autoMode` settings block to tell that classifier which repos, buckets, and domains your organization trusts, so it stops blocking routine internal operations.9[Auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) lets Claude Code run without routine permission prompts by routing tool calls through a classifier that blocks anything irreversible, destructive, or aimed outside your environment. Deny and explicit ask rules are evaluated before the classifier and still block or prompt. Use the `autoMode` settings block to tell that classifier which repos, buckets, and domains your organization trusts, so it stops blocking routine internal operations.

10 10 

11<Note>11<Note>

12 Auto mode is available to all users on every provider, including the Anthropic API, Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, and signed-in [Claude apps gateway](/en/claude-apps-gateway) sessions. If Claude Code reports auto mode as unavailable for your account, check the [full requirements](/en/permission-modes#eliminate-prompts-with-auto-mode), which also cover the supported models and Owner enablement on Team and Enterprise plans. {/* min-version: 2.1.207 */}In v2.1.158 through v2.1.206, auto mode on Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, and Claude apps gateway sessions required setting `CLAUDE_CODE_ENABLE_AUTO_MODE=1`; v2.1.207 removed the requirement.12 Auto mode is available to all users on every provider, including the Anthropic API, [Claude Platform on AWS](/en/claude-platform-on-aws), Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, and signed-in [Claude apps gateway](/en/claude-apps-gateway) sessions. If Claude Code reports auto mode as unavailable for your account, check the [full requirements](/en/permission-modes#eliminate-prompts-with-auto-mode), which also cover the supported models and Owner enablement on Team and Enterprise plans. {/* min-version: 2.1.207 */}In v2.1.158 through v2.1.206, auto mode on Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, and Claude apps gateway sessions required setting `CLAUDE_CODE_ENABLE_AUTO_MODE=1`; v2.1.207 removed the requirement.

13</Note>13</Note>

14 14 

15By default, the classifier trusts only the working directory and the current repo's configured remotes. Actions like pushing to your company's source-control org or writing to a team cloud bucket are blocked until you add them to `autoMode.environment`.15By default, the classifier trusts only the working directory and the current repo's configured remotes. Actions like pushing to your company's source-control org or writing to a team cloud bucket are blocked until you add them to `autoMode.environment`.

Details

171- Prefer running single tests, and not the whole test suite, for performance171- Prefer running single tests, and not the whole test suite, for performance

172```172```

173 173 

174CLAUDE.md is loaded every session, so only include things that apply broadly. For domain knowledge or workflows that are only relevant sometimes, use [skills](/en/skills) instead. Claude loads them on demand without bloating every conversation.174Run `/context` to confirm Claude loaded the file. CLAUDE.md is loaded every session, so only include things that apply broadly. For domain knowledge or workflows that are only relevant sometimes, use [skills](/en/skills) instead. Claude loads them on demand without bloating every conversation.

175 175 

176Keep it concise. For each line, ask: *"Would removing this cause Claude to make mistakes?"* If not, cut it. Bloated CLAUDE.md files cause Claude to ignore your actual instructions!176Keep it concise. For each line, ask: *"Would removing this cause Claude to make mistakes?"* If not, cut it. Bloated CLAUDE.md files cause Claude to ignore your actual instructions!

177 177 


357 For larger features, have Claude interview you first. Start with a minimal prompt and ask Claude to interview you using the `AskUserQuestion` tool.357 For larger features, have Claude interview you first. Start with a minimal prompt and ask Claude to interview you using the `AskUserQuestion` tool.

358</Tip>358</Tip>

359 359 

360Claude asks about things you might not have considered yet, including technical implementation, UI/UX, edge cases, and tradeoffs.360Claude asks about things you might not have considered yet, including technical implementation, UI/UX, edge cases, and tradeoffs. Replace `[brief description]` with your feature before sending the prompt.

361 361 

362```text theme={null}362```text theme={null}

363I want to build [brief description]. Interview me in detail using the AskUserQuestion tool.363I want to build [brief description]. Interview me in detail using the AskUserQuestion tool.


479claude -p "Analyze this log file" --output-format stream-json --verbose479claude -p "Analyze this log file" --output-format stream-json --verbose

480```480```

481 481 

482The first command prints plain text. The `json` format returns a single JSON object with a `result` field. The `stream-json` format prints one JSON object per line, starting with an init event.

483 

482### Run multiple Claude sessions484### Run multiple Claude sessions

483 485 

484<Tip>486<Tip>

Details

189 189 

190## Server options190## Server options

191 191 

192A channel sets these options in the [`Server`](https://modelcontextprotocol.io/docs/concepts/servers) constructor. The `instructions` and `capabilities.tools` fields are [standard MCP](https://modelcontextprotocol.io/docs/concepts/servers); `capabilities.experimental['claude/channel']` and `capabilities.experimental['claude/channel/permission']` are the channel-specific additions:192A channel sets these options in the [`Server`](https://modelcontextprotocol.io/docs/learn/server-concepts) constructor. The `instructions` and `capabilities.tools` fields are [standard MCP](https://modelcontextprotocol.io/docs/learn/server-concepts); `capabilities.experimental['claude/channel']` and `capabilities.experimental['claude/channel/permission']` are the channel-specific additions:

193 193 

194| Field | Type | Description |194| Field | Type | Description |

195| :------------------------------------------------------- | :------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |195| :------------------------------------------------------- | :------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

Details

19* Every user prompt creates a new checkpoint19* Every user prompt creates a new checkpoint

20* Claude Code keeps file snapshots for the 100 most recent checkpoints in a session. Discarding an older checkpoint deletes the snapshot files that no remaining checkpoint references, except each file's first snapshot, which the VS Code extension uses as the baseline for its session diffs. {/* min-version: 2.1.208 */}Before v2.1.208, those superseded snapshot files stayed on disk until the session was cleaned up.20* Claude Code keeps file snapshots for the 100 most recent checkpoints in a session. Discarding an older checkpoint deletes the snapshot files that no remaining checkpoint references, except each file's first snapshot, which the VS Code extension uses as the baseline for its session diffs. {/* min-version: 2.1.208 */}Before v2.1.208, those superseded snapshot files stayed on disk until the session was cleaned up.

21* Checkpoints are saved with the conversation, so a resumed session can still `/rewind` to them21* Checkpoints are saved with the conversation, so a resumed session can still `/rewind` to them

22* Automatically cleaned up along with sessions after 30 days (configurable)22* Automatically cleaned up along with sessions after 30 days, configurable via [`cleanupPeriodDays`](/en/settings#available-settings)

23 23 

24### Rewind and summarize24### Rewind and summarize

25 25 


38* **Summarize up to here**: compress the conversation before this point into a summary, keeping later messages intact38* **Summarize up to here**: compress the conversation before this point into a summary, keeping later messages intact

39* **Never mind**: return to the message list without making changes39* **Never mind**: return to the message list without making changes

40 40 

41The two code restore options appear only when the selected checkpoint has tracked file changes to revert. If no file edits were captured after that point, the menu offers only **Restore conversation**, the summarize options, and **Never mind**.

42 

41After restoring the conversation or choosing Summarize from here, the original prompt from the selected message is restored into the input field so you can re-send or edit it.43After restoring the conversation or choosing Summarize from here, the original prompt from the selected message is restored into the input field so you can re-send or edit it.

42 44 

43Choosing Summarize up to here leaves you at the end of the conversation with the input empty.45Choosing Summarize up to here leaves you at the end of the conversation with the input empty. With either summarize option, a **Summarized conversation** marker appears in the conversation where the compressed messages were.

44 46 

45#### Rewind past a cleared conversation47#### Rewind past a cleared conversation

46 48 


53* **Summarize from here**: messages before the selected message stay intact. The selected message and everything after it are replaced with a summary. Use this to discard a side discussion while keeping early context in full detail.55* **Summarize from here**: messages before the selected message stay intact. The selected message and everything after it are replaced with a summary. Use this to discard a side discussion while keeping early context in full detail.

54* **Summarize up to here**: messages before the selected message are replaced with a summary. The selected message and everything after it stay intact, and you remain at the end of the conversation. Use this to compress early setup discussion while keeping recent work in full detail.56* **Summarize up to here**: messages before the selected message are replaced with a summary. The selected message and everything after it stay intact, and you remain at the end of the conversation. Use this to compress early setup discussion while keeping recent work in full detail.

55 57 

56In both cases the original messages are preserved in the session transcript, so Claude can reference the details if needed. You can type optional instructions to guide what the summary focuses on. This is similar to `/compact`, but targeted: instead of summarizing the entire conversation, you choose which side of the selected message to compress.58In both cases the original messages are preserved in the session transcript, so Claude can reference the details if needed. To guide what the summary focuses on, highlight a **Summarize** option with the arrow keys and type instructions inline where the row reads **add context (optional)**, then press `Enter` to summarize; selecting the option by its number key summarizes immediately without instructions. This is similar to `/compact`, but targeted: instead of summarizing the entire conversation, you choose which side of the selected message to compress.

57 59 

58<Note>60<Note>

59 Summarize keeps you in the same session and compresses context. If you want to branch off and try a different approach while preserving the original session intact, use [fork](/en/sessions#branch-a-session) instead (`claude --continue --fork-session`).61 Summarize keeps you in the same session and compresses context. If you want to branch off and try a different approach while preserving the original session intact, use [fork](/en/sessions#branch-a-session) instead (`claude --continue --fork-session`).

Details

62 oneLiner: 'Project-scoped MCP servers, shared with your team',62 oneLiner: 'Project-scoped MCP servers, shared with your team',

63 when: <>Servers connect when the session begins. Tool schemas are deferred by default and load on demand via <A href="/en/mcp#scale-with-mcp-tool-search">tool search</A></>,63 when: <>Servers connect when the session begins. Tool schemas are deferred by default and load on demand via <A href="/en/mcp#scale-with-mcp-tool-search">tool search</A></>,

64 description: <>Configures Model Context Protocol (MCP) servers that give Claude access to external tools: databases, APIs, browsers, and more. This file holds the project-scoped servers your whole team uses. Personal servers you want to keep to yourself go in <C>~/.claude.json</C> instead.</>,64 description: <>Configures Model Context Protocol (MCP) servers that give Claude access to external tools: databases, APIs, browsers, and more. This file holds the project-scoped servers your whole team uses. Personal servers you want to keep to yourself go in <C>~/.claude.json</C> instead.</>,

65 tips: [<>Use environment variable references for secrets: <C>{'${GITHUB_TOKEN}'}</C></>, <>Lives at the project root, not inside <C>.claude/</C></>, <>For servers only you need, run <C>claude mcp add --scope user</C>. This writes to <C>~/.claude.json</C> instead of <C>.mcp.json</C></>],65 tips: [<>Use environment variable references for secrets: <C>{'${NOTION_TOKEN}'}</C></>, <>Lives at the project root, not inside <C>.claude/</C></>, <>For servers only you need, run <C>claude mcp add --scope user</C>. This writes to <C>~/.claude.json</C> instead of <C>.mcp.json</C></>],

66 exampleIntro: <>This example configures the GitHub MCP server so Claude can read issues and open pull requests. The <C>{'${GITHUB_TOKEN}'}</C> reference is read from your shell environment when Claude Code starts the server, so the token never lands in the file.</>,66 exampleIntro: <>This example configures the Notion MCP server so Claude can read and update pages in your workspace. The <C>{'${NOTION_TOKEN}'}</C> reference is read from your shell environment when Claude Code starts the server, so the token never lands in the file.</>,

67 example: `{67 example: `{

68 "mcpServers": {68 "mcpServers": {

69 "github": {69 "notion": {

70 "command": "npx",70 "command": "npx",

71 "args": ["-y", "@modelcontextprotocol/server-github"],71 "args": ["-y", "@notionhq/notion-mcp-server"],

72 "env": {72 "env": {

73 "GITHUB_TOKEN": "\${GITHUB_TOKEN}"73 "NOTION_TOKEN": "\${NOTION_TOKEN}"

74 }74 }

75 }75 }

76 }76 }

Details

232}232}

233```233```

234 234 

235Claude Code also runs this command at startup when it can't validate your existing AWS credentials, and shows the command's output in a Cloud authentication panel until the login completes.235Claude Code also runs this command at startup when it can't validate your existing AWS credentials, and shows the command's output in an Authentication panel until the login completes. {/* min-version: 2.1.212 */}Before v2.1.212, the panel was titled Cloud authentication.

236 236 

237With `awsAuthRefresh` configured, `/login` shows a **Claude Platform on AWS · refresh credentials** option under **Using 3rd-party platforms**. Selecting it runs the configured command and re-reads your AWS credentials without restarting Claude Code.237With `awsAuthRefresh` configured, `/login` shows a **Claude Platform on AWS · refresh credentials** option under **Using 3rd-party platforms**. Selecting it runs the configured command and re-reads your AWS credentials without restarting Claude Code.

238 238 

code-review.md +18 −13

Details

20 20 

21* [How reviews work](#how-reviews-work)21* [How reviews work](#how-reviews-work)

22* [Setup](#set-up-code-review)22* [Setup](#set-up-code-review)

23* [Triggering reviews manually](#manually-trigger-reviews) with `@claude review` and `@claude review once`23* [Triggering reviews manually](#manually-trigger-reviews) with `@claude review` and `@claude review always`

24* [Customizing reviews](#customize-reviews) with `CLAUDE.md` and `REVIEW.md`24* [Customizing reviews](#customize-reviews) with `CLAUDE.md` and `REVIEW.md`

25* [Pricing](#pricing)25* [Pricing](#pricing)

26* [Troubleshooting](#troubleshooting) failed runs and missing comments26* [Troubleshooting](#troubleshooting) failed runs and missing comments


32 32 

33## How reviews work33## How reviews work

34 34 

35Once an Owner [enables Code Review](#set-up-code-review) for your organization, reviews trigger when a PR opens, on every push, or when manually requested, depending on the repository's configured behavior. Commenting `@claude review` [starts reviews on a PR](#manually-trigger-reviews) in any mode.35Once an Owner [enables Code Review](#set-up-code-review) for your organization, reviews trigger when a PR opens, on every push, or when manually requested, depending on the repository's configured behavior. Commenting `@claude review` [starts a review on a PR](#manually-trigger-reviews) in any mode.

36 36 

37When a review runs, multiple agents analyze the diff and surrounding code in parallel on Anthropic infrastructure. Each agent looks for a different class of issue, then a verification step checks candidates against actual code behavior to filter out false positives. The results are deduplicated, ranked by severity, and posted as inline comments on the specific lines where issues were found, with a summary in the review body. If no issues are found, Code Review updates the GitHub check run to show that no issues were detected. Claude may also post a short confirmation comment on the PR.37When a review runs, multiple agents analyze the diff and surrounding code in parallel on Anthropic infrastructure. Each agent looks for a different class of issue, then a verification step checks candidates against actual code behavior to filter out false positives. The results are deduplicated, ranked by severity, and posted as inline comments on the specific lines where issues were found, with a summary in the review body. If no issues are found, Code Review updates the GitHub check run to show that no issues were detected. Claude may also post a short confirmation comment on the PR.

38 38 


54 54 

55Each review comment from Claude arrives with 👍 and 👎 already attached so both buttons appear in the GitHub UI for one-click rating. Click 👍 if the finding was useful or 👎 if it was wrong or noisy. Anthropic collects reaction counts after the PR merges and uses them to tune the reviewer. Reactions do not trigger a re-review or change anything on the PR.55Each review comment from Claude arrives with 👍 and 👎 already attached so both buttons appear in the GitHub UI for one-click rating. Click 👍 if the finding was useful or 👎 if it was wrong or noisy. Anthropic collects reaction counts after the PR merges and uses them to tune the reviewer. Reactions do not trigger a re-review or change anything on the PR.

56 56 

57Replying to an inline comment does not prompt Claude to respond or update the PR. To act on a finding, fix the code and push. If the PR is subscribed to push-triggered reviews, the next run resolves the thread when the issue is fixed. To request a fresh review without pushing, comment `@claude review once` as a [top-level PR comment](#manually-trigger-reviews).57Replying to an inline comment does not prompt Claude to respond or update the PR. To act on a finding, fix the code and push. If the PR is subscribed to push-triggered reviews, the next run resolves the thread when the issue is fixed. To request a fresh review without pushing, comment `@claude review` as a [top-level PR comment](#manually-trigger-reviews).

58 58 

59### Check run output59### Check run output

60 60 


112 112 

113 * **Once after PR creation**: review runs once when a PR is opened or marked ready for review113 * **Once after PR creation**: review runs once when a PR is opened or marked ready for review

114 * **After every push**: review runs on every push to the PR branch, catching new issues as the PR evolves and auto-resolving threads when you fix flagged issues114 * **After every push**: review runs on every push to the PR branch, catching new issues as the PR evolves and auto-resolving threads when you fix flagged issues

115 * **Manual**: reviews start only when someone [comments `@claude review` or `@claude review once` on a PR](#manually-trigger-reviews); `@claude review` also subscribes the PR to reviews on subsequent pushes115 * **Manual**: reviews start only when someone [comments `@claude review` on a PR](#manually-trigger-reviews); `@claude review always` starts a review and subscribes the PR to reviews on subsequent pushes

116 116 

117 Reviewing on every push runs the most reviews and costs the most. Manual mode is useful for high-traffic repos where you want to opt specific PRs into review, or to only start reviewing your PRs once they're ready.117 Reviewing on every push runs the most reviews and costs the most. Manual mode is useful for high-traffic repos where you want to opt specific PRs into review, or to only start reviewing your PRs once they're ready.

118 </Step>118 </Step>


124 124 

125## Manually trigger reviews125## Manually trigger reviews

126 126 

127Two comment commands start a review on demand. Both work regardless of the repository's configured trigger, so you can use them to opt specific PRs into review in Manual mode or to get an immediate re-review in other modes.127Comment commands start a review on demand. They work regardless of the repository's configured trigger, so you can use them to opt specific PRs into review in Manual mode or to get an immediate re-review in other modes.

128 128 

129| Command | What it does |129| Command | What it does |

130| :-------------------- | :---------------------------------------------------------------------------- |130| :---------------------- | :---------------------------------------------------------------------------- |

131| `@claude review` | Starts a review and subscribes the PR to push-triggered reviews going forward |131| `@claude review` | Starts a single review without subscribing the PR to future pushes |

132| `@claude review once` | Starts a single review without subscribing the PR to future pushes |132| `@claude review always` | Starts a review and subscribes the PR to push-triggered reviews going forward |

133| `@claude review once` | Same as `@claude review`: starts a single review without subscribing |

133 134 

134Use `@claude review once` when you want feedback on the current state of a PR but don't want every subsequent push to incur a review. This is useful for long-running PRs with frequent pushes, or when you want a one-off second opinion without changing the PR's review behavior.135Use `@claude review always` when you want every subsequent push to the PR to start a fresh review, such as on a high-priority PR in a repository set to Manual mode. Because the bare command doesn't subscribe the PR, you can request a one-off second opinion without changing whether later pushes trigger reviews.

135 136 

136For either command to trigger a review:137<Note>

138 Before a July 2026 update, `@claude review` subscribed the PR to push-triggered reviews. If you relied on that behavior, comment `@claude review always` instead. `@claude review once` still works and behaves the same as the bare command.

139</Note>

140 

141For any of these commands to trigger a review:

137 142 

138* Post it as a top-level PR comment, not an inline comment on a diff line143* Post it as a top-level PR comment, not an inline comment on a diff line

139* Put the command at the start of the comment, with `once` on the same line if you're using the one-shot form144* Put the command at the start of the comment, with `once` or `always` on the same line as the rest of the command

140* You must have owner, member, or collaborator access to the repository145* You must have owner, member, or collaborator access to the repository

141* The PR must be open146* The PR must be open

142 147 


245* **After every push**: runs on each push, multiplying cost by the number of pushes250* **After every push**: runs on each push, multiplying cost by the number of pushes

246* **Manual**: no reviews until someone comments `@claude review` on a PR251* **Manual**: no reviews until someone comments `@claude review` on a PR

247 252 

248In any mode, commenting `@claude review` [opts the PR into push-triggered reviews](#manually-trigger-reviews), so additional cost accrues per push after that comment. To run a single review without subscribing to future pushes, comment `@claude review once` instead.253In Once after PR creation or Manual mode, commenting `@claude review always` [opts the PR into push-triggered reviews](#manually-trigger-reviews), so additional cost accrues per push after that comment. In After every push mode, pushes already trigger reviews, so the subscription doesn't change per-push cost. Commenting `@claude review` runs a single review without subscribing to future pushes.

249 254 

250Costs appear on your Anthropic bill regardless of whether your organization uses Amazon Bedrock or Google Cloud's Agent Platform for other Claude Code features. To set a monthly spend cap for Code Review, go to [claude.ai/admin-settings/usage](https://claude.ai/admin-settings/usage) and configure the limit for the Claude Code Review service.255Costs appear on your Anthropic bill regardless of whether your organization uses Amazon Bedrock or Google Cloud's Agent Platform for other Claude Code features. To set a monthly spend cap for Code Review, go to [claude.ai/admin-settings/usage](https://claude.ai/admin-settings/usage) and configure the limit for the Claude Code Review service.

251 256 


259 264 

260When the review infrastructure hits an internal error or exceeds its time limit, the check run completes with a title of **Code review encountered an error** or **Code review timed out**. The conclusion is still neutral, so nothing blocks your merge, but no findings are posted.265When the review infrastructure hits an internal error or exceeds its time limit, the check run completes with a title of **Code review encountered an error** or **Code review timed out**. The conclusion is still neutral, so nothing blocks your merge, but no findings are posted.

261 266 

262To run the review again, comment `@claude review once` on the PR. This starts a fresh review without subscribing the PR to future pushes. If the PR is already subscribed to push-triggered reviews, pushing a new commit also starts a new review.267To run the review again, comment `@claude review` on the PR. This starts a fresh review without subscribing the PR to future pushes. If the PR is already subscribed to push-triggered reviews, pushing a new commit also starts a new review.

263 268 

264The **Re-run** button in GitHub's Checks tab does not retrigger Code Review. Use the comment command or a new push instead.269The **Re-run** button in GitHub's Checks tab does not retrigger Code Review. Use the comment command or a new push instead.

265 270 

data-usage.md +1 −1

Details

114 114 

115## Default behaviors by API provider115## Default behaviors by API provider

116 116 

117By default, error reporting, telemetry, and bug reporting are disabled when using Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, or Claude Platform on AWS. Session quality surveys and the WebFetch domain safety check are exceptions and run regardless of provider. On a signed-in [Claude apps gateway](/en/claude-apps-gateway) session, usage analytics, error reporting, and survey ratings to Anthropic are disabled by the gateway credential itself, with no setting to re-enable them. You can opt out of all non-essential traffic, including surveys, at once by setting `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`. This variable does not affect the WebFetch check, which has its own opt-out. Here are the full default behaviors:117By default, error reporting, telemetry, and bug reporting are disabled when using Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, or Claude Platform on AWS. Session quality surveys and the WebFetch domain safety check are exceptions and run regardless of provider. On a signed-in [Claude apps gateway](/en/claude-apps-gateway) session, usage analytics, error reporting, and survey ratings to Anthropic are disabled by the gateway credential itself, with no setting to re-enable them. You can opt out of all non-essential traffic, including surveys, at once by setting `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`. This variable doesn't affect the WebFetch check or official plugin marketplace auto-install; each has its own opt-out: `skipWebFetchPreflight` in [settings](/en/settings) for WebFetch, and `CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL` for the marketplace. Here are the full default behaviors:

118 118 

119| Service | Claude API | Google Cloud's Agent Platform API | Amazon Bedrock API | Microsoft Foundry API | Claude Platform on AWS |119| Service | Claude API | Google Cloud's Agent Platform API | Amazon Bedrock API | Microsoft Foundry API | Claude Platform on AWS |

120| ------------------------------------ | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |120| ------------------------------------ | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |

desktop.md +5 −3

Details

347 347 

348### Run long-running tasks remotely348### Run long-running tasks remotely

349 349 

350For large refactors, test suites, migrations, or other long-running tasks, select **Remote** instead of **Local** when starting a session. Cloud sessions run on Anthropic's cloud infrastructure and continue even if you close the app or shut down your computer. Check back anytime to see progress or steer Claude in a different direction. You can also monitor cloud sessions from [claude.ai/code](https://claude.ai/code) or the Claude iOS app.350For large refactors, test suites, migrations, or other long-running tasks, select **Remote** instead of **Local** when starting a session. Cloud sessions run on Anthropic's cloud infrastructure and continue even if you close the app or shut down your computer. Check back anytime to see progress or steer Claude in a different direction. You can also monitor cloud sessions from [claude.ai/code](https://claude.ai/code) or the [Claude mobile app](/en/mobile).

351 351 

352Cloud sessions also support multiple repositories. After selecting a cloud environment, click the **+** button next to the repo pill to add additional repositories to the session. Each repo gets its own branch selector. This is useful for tasks that span multiple codebases, such as updating a shared library and its consumers.352Cloud sessions also support multiple repositories. After selecting a cloud environment, click the **+** button next to the repo pill to add additional repositories to the session. Each repo gets its own branch selector. This is useful for tasks that span multiple codebases, such as updating a shared library and its consumers.

353 353 


376 376 

377## Extend Claude Code377## Extend Claude Code

378 378 

379Connect external services, add reusable workflows, customize Claude's behavior, and configure preview servers. To manage connectors, skills, and plugins in one place, click **Customize** in the sidebar.379Connect external services, add reusable workflows, customize Claude's behavior, and configure preview servers. To manage connectors, skills, and plugins in one place, click **Customize** in the sidebar. The [Cowork](https://claude.com/product/cowork) tab in the Desktop app sources its skills, plugins, and connectors from this Customize configuration, which syncs through your claude.ai account, not from the CLI's `~/.claude` directory.

380 380 

381### Connect external tools381### Connect external tools

382 382 


394 394 

395You can send a command while Claude is working, the same as any other message, and the session returns to idle once the turn finishes. Before v2.1.206, a command sent mid-turn could leave the session showing as running and messages you sent afterward weren't delivered.395You can send a command while Claude is working, the same as any other message, and the session returns to idle once the turn finishes. Before v2.1.206, a command sent mid-turn could leave the session showing as running and messages you sent afterward weren't delivered.

396 396 

397Personal skills in `~/.claude/skills/` apply to local sessions; an [SSH](#ssh-sessions) session reads `~/.claude/skills/` from the remote host's home directory, not from your machine. Cloud sessions load the skills enabled for your claude.ai account instead. See [Skills in Cowork and cloud sessions](/en/skills#skills-in-cowork-and-cloud-sessions).

398 

397### Install plugins399### Install plugins

398 400 

399[Plugins](/en/plugins) are reusable packages that add skills, agents, hooks, MCP servers, and LSP configurations to Claude Code. You can install plugins from the desktop app without using the terminal.401[Plugins](/en/plugins) are reusable packages that add skills, agents, hooks, MCP servers, and LSP configurations to Claude Code. You can install plugins from the desktop app without using the terminal.

400 402 

401For local and [SSH](#ssh-sessions) sessions, click the **+** button next to the prompt box and select **Plugins** to see your installed plugins and their skills. To add a plugin, select **Add plugin** from the submenu to open the plugin browser, which shows available plugins from your configured [marketplaces](/en/plugin-marketplaces) including the official Anthropic marketplace. Select **Manage plugins** to enable, disable, or uninstall plugins.403For local and [SSH](#ssh-sessions) sessions, click the **+** button next to the prompt box and select **Plugins** to see your installed plugins and their skills. To add a plugin, select **Add plugin** from the submenu to open the plugin browser, which shows available plugins from your configured [marketplaces](/en/plugin-marketplaces) including the official Anthropic marketplace. Select **Manage plugins** to enable, disable, or uninstall plugins.

402 404 

403Plugins can be scoped to your user account, a specific project, or local-only. If your organization manages plugins centrally, those plugins are available in desktop sessions the same way they are in the CLI. The plugin browser is not available in cloud sessions, but plugins declared in the repository's `.claude/settings.json` under [`enabledPlugins`](/en/settings#enabledplugins) still load. Plugins aren't available in WSL sessions. For the full plugin reference including creating your own plugins, see [plugins](/en/plugins).405Plugins can be scoped to your user account, a specific project, or local-only. If your organization manages plugins centrally, those plugins are available in desktop sessions the same way they are in the CLI. The plugin browser is not available in cloud sessions, and plugins you install from the desktop app aren't available for cloud sessions; to use a plugin in a cloud session, declare it in the repository's `.claude/settings.json` under [`enabledPlugins`](/en/settings#enabledplugins) so it [installs at session start](/en/claude-code-on-the-web#what’s-available-in-cloud-sessions). Plugins aren't available in WSL sessions. For the full plugin reference including creating your own plugins, see [plugins](/en/plugins).

404 406 

405### Configure preview servers407### Configure preview servers

406 408 

env-vars.md +5 −2

Details

217| `CLAUDE_CODE_DISABLE_LEGACY_MODEL_REMAP` | Set to `1` to prevent automatic remapping of Opus 4.0 and 4.1 to the current Opus version on the Anthropic API. Use when you intentionally want to pin an older model. The remap does not run on Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry |217| `CLAUDE_CODE_DISABLE_LEGACY_MODEL_REMAP` | Set to `1` to prevent automatic remapping of Opus 4.0 and 4.1 to the current Opus version on the Anthropic API. Use when you intentionally want to pin an older model. The remap does not run on Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry |

218| `CLAUDE_CODE_DISABLE_MOUSE` | Set to `1` to disable mouse tracking in [fullscreen rendering](/en/fullscreen). Keyboard scrolling with `PgUp` and `PgDn` still works. Use this to keep your terminal's native copy-on-select behavior |218| `CLAUDE_CODE_DISABLE_MOUSE` | Set to `1` to disable mouse tracking in [fullscreen rendering](/en/fullscreen). Keyboard scrolling with `PgUp` and `PgDn` still works. Use this to keep your terminal's native copy-on-select behavior |

219| `CLAUDE_CODE_DISABLE_MOUSE_CLICKS` | {/* min-version: 2.1.195 */}Set to `1` to disable click, drag, and hover handling in [fullscreen rendering](/en/fullscreen) while keeping mouse-wheel scrolling. Use this when you want wheel scroll to work inside Claude Code but don't want clicks to position the cursor, expand tool output, or open links. `CLAUDE_CODE_DISABLE_MOUSE` takes precedence when both are set. Requires Claude Code v2.1.195 or later |219| `CLAUDE_CODE_DISABLE_MOUSE_CLICKS` | {/* min-version: 2.1.195 */}Set to `1` to disable click, drag, and hover handling in [fullscreen rendering](/en/fullscreen) while keeping mouse-wheel scrolling. Use this when you want wheel scroll to work inside Claude Code but don't want clicks to position the cursor, expand tool output, or open links. `CLAUDE_CODE_DISABLE_MOUSE` takes precedence when both are set. Requires Claude Code v2.1.195 or later |

220| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | Equivalent of setting `DISABLE_AUTOUPDATER`, `DISABLE_FEEDBACK_COMMAND`, `DISABLE_ERROR_REPORTING`, and `DISABLE_TELEMETRY` |220| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | Set to any non-empty value to disable nonessential network traffic: auto-updates, telemetry, error reporting, the `/feedback` command, release notes, [gateway model discovery](/en/llm-gateway-connect#add-gateway-models-to-the-model-picker) refreshes, and availability checks such as the [fast mode](/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways) check. Official plugin marketplace auto-install isn't covered; disable it with `CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL` |

221| `CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK` | Set to `1` to disable the non-streaming fallback when a streaming request fails mid-stream. Streaming errors propagate to the retry layer instead. Useful when a proxy or gateway causes the fallback to produce duplicate tool execution |221| `CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK` | Set to `1` to disable the non-streaming fallback when a streaming request fails mid-stream. Streaming errors propagate to the retry layer instead. Useful when a proxy or gateway causes the fallback to produce duplicate tool execution |

222| `CLAUDE_CODE_DISABLE_NOTIFICATION_PRESENCE_CHECK` | {/* min-version: 2.1.193 */}Set to `1` to send the `PushNotification` tool's desktop notification even while you are typing in or focused on the terminal. By default the tool skips both the desktop notification and the [mobile push](/en/remote-control#mobile-push-notifications) when it detects recent keyboard activity or terminal focus. This variable disables only that local check, so the server can still suppress the mobile push when it detects that you are active. Requires Claude Code v2.1.193 or later |222| `CLAUDE_CODE_DISABLE_NOTIFICATION_PRESENCE_CHECK` | {/* min-version: 2.1.193 */}Set to `1` to send the `PushNotification` tool's desktop notification even while you are typing in or focused on the terminal. By default the tool skips both the desktop notification and the [mobile push](/en/remote-control#mobile-push-notifications) when it detects recent keyboard activity or terminal focus. This variable disables only that local check, so the server can still suppress the mobile push when it detects that you are active. Requires Claude Code v2.1.193 or later |

223| `CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL` | Set to `1` to skip automatic addition of the official plugin marketplace on first run |223| `CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL` | Set to `1` to skip automatic addition of the official plugin marketplace on first run |


258| `CLAUDE_CODE_MAX_CONTEXT_TOKENS` | Override the context window size Claude Code assumes for the active model. {/* min-version: 2.1.193 */}As of v2.1.193, applied directly for model names Claude Code does not recognize as a Claude model; for recognized Claude models it only takes effect when `DISABLE_COMPACT` is also set. Use this when routing to a model through `ANTHROPIC_BASE_URL` whose context window does not match the built-in size for its name |258| `CLAUDE_CODE_MAX_CONTEXT_TOKENS` | Override the context window size Claude Code assumes for the active model. {/* min-version: 2.1.193 */}As of v2.1.193, applied directly for model names Claude Code does not recognize as a Claude model; for recognized Claude models it only takes effect when `DISABLE_COMPACT` is also set. Use this when routing to a model through `ANTHROPIC_BASE_URL` whose context window does not match the built-in size for its name |

259| `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | Set the maximum number of output tokens for most requests. Defaults and caps vary by model; see [max output tokens](https://platform.claude.com/docs/en/about-claude/models/overview#latest-models-comparison). Increasing this value reduces the effective context window available before [auto-compaction](/en/costs#reduce-token-usage) triggers |259| `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | Set the maximum number of output tokens for most requests. Defaults and caps vary by model; see [max output tokens](https://platform.claude.com/docs/en/about-claude/models/overview#latest-models-comparison). Increasing this value reduces the effective context window available before [auto-compaction](/en/costs#reduce-token-usage) triggers |

260| `CLAUDE_CODE_MAX_RETRIES` | Override the number of times to retry failed API requests (default: 10). {/* min-version: 2.1.186 */}Capped at 15 as of v2.1.186; {/* min-version: 2.1.199 */}as of v2.1.199, `CLAUDE_CODE_RETRY_WATCHDOG` raises the default and removes the cap. For unattended sessions that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG` instead |260| `CLAUDE_CODE_MAX_RETRIES` | Override the number of times to retry failed API requests (default: 10). {/* min-version: 2.1.186 */}Capped at 15 as of v2.1.186; {/* min-version: 2.1.199 */}as of v2.1.199, `CLAUDE_CODE_RETRY_WATCHDOG` raises the default and removes the cap. For unattended sessions that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG` instead |

261| `CLAUDE_CODE_MAX_SUBAGENTS_PER_SESSION` | {/* min-version: 2.1.212 */}Cap on the total number of [subagents](/en/sub-agents#session-subagent-limit) one session can spawn (default: 200). When Claude reaches the cap, spawning another subagent fails with an error telling it to finish the remaining work directly. Accepts a positive whole number with no upper bound. Anything else is ignored and the default applies, so the cap can be raised but not turned off. Requires Claude Code v2.1.212 or later |

261| `CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY` | Maximum number of read-only tools and subagents that can execute in parallel (default: 10). Higher values increase parallelism but consume more resources |262| `CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY` | Maximum number of read-only tools and subagents that can execute in parallel (default: 10). Higher values increase parallelism but consume more resources |

262| `CLAUDE_CODE_MAX_TURNS` | Cap the number of agentic turns when no explicit limit is passed. Equivalent to passing [`--max-turns`](/en/cli-reference#cli-flags), which takes precedence when both are set. A value that is not a positive integer is rejected at startup with an error rather than treated as no cap |263| `CLAUDE_CODE_MAX_TURNS` | Cap the number of agentic turns when no explicit limit is passed. Equivalent to passing [`--max-turns`](/en/cli-reference#cli-flags), which takes precedence when both are set. A value that is not a positive integer is rejected at startup with an error rather than treated as no cap |

263| `CLAUDE_CODE_MCP_ALLOWLIST_ENV` | Set to `1` to spawn stdio MCP servers with only a safe baseline environment plus the server's configured `env`, instead of inheriting your shell environment |264| `CLAUDE_CODE_MCP_ALLOWLIST_ENV` | Set to `1` to spawn stdio MCP servers with only a safe baseline environment plus the server's configured `env`, instead of inheriting your shell environment |


294| `CLAUDE_CODE_RETRY_WATCHDOG` | {/* min-version: 2.1.186 */}Set to `1` for unattended sessions such as eval harnesses, CI jobs, or remote workers. Retries `429` and `529` capacity errors indefinitely instead of failing after `CLAUDE_CODE_MAX_RETRIES` attempts. The watchdog backs off up to 5 minutes between attempts, or until the limit resets when the response carries a rate-limit reset time, so a session that hits a usage limit waits out the remaining window. {/* min-version: 2.1.199 */}As of v2.1.199 it also raises the default retry count for other transient errors, such as server errors, timeouts, and dropped connections, to 300, roughly three hours of backoff, and removes the cap of 15 on `CLAUDE_CODE_MAX_RETRIES` if you set that variable explicitly. Requires Claude Code v2.1.186 or later |295| `CLAUDE_CODE_RETRY_WATCHDOG` | {/* min-version: 2.1.186 */}Set to `1` for unattended sessions such as eval harnesses, CI jobs, or remote workers. Retries `429` and `529` capacity errors indefinitely instead of failing after `CLAUDE_CODE_MAX_RETRIES` attempts. The watchdog backs off up to 5 minutes between attempts, or until the limit resets when the response carries a rate-limit reset time, so a session that hits a usage limit waits out the remaining window. {/* min-version: 2.1.199 */}As of v2.1.199 it also raises the default retry count for other transient errors, such as server errors, timeouts, and dropped connections, to 300, roughly three hours of backoff, and removes the cap of 15 on `CLAUDE_CODE_MAX_RETRIES` if you set that variable explicitly. Requires Claude Code v2.1.186 or later |

295| `CLAUDE_CODE_SAFE_MODE` | Set to `1` to start in safe mode: CLAUDE.md, skills, plugins, hooks, MCP servers, custom commands and agents, output styles, workflows, custom themes, custom keybindings, status line and file-suggestion commands, LSP servers, and auto-memory do not load, for troubleshooting a broken configuration. Managed settings policy still applies, including policy-configured hooks, status line, and file-suggestion commands; managed plugins, managed skills, managed CLAUDE.md, and policy-configured MCP servers do not. Equivalent to passing [`--safe-mode`](/en/cli-reference#cli-flags). Directly spawned child processes inherit the variable |296| `CLAUDE_CODE_SAFE_MODE` | Set to `1` to start in safe mode: CLAUDE.md, skills, plugins, hooks, MCP servers, custom commands and agents, output styles, workflows, custom themes, custom keybindings, status line and file-suggestion commands, LSP servers, and auto-memory do not load, for troubleshooting a broken configuration. Managed settings policy still applies, including policy-configured hooks, status line, and file-suggestion commands; managed plugins, managed skills, managed CLAUDE.md, and policy-configured MCP servers do not. Equivalent to passing [`--safe-mode`](/en/cli-reference#cli-flags). Directly spawned child processes inherit the variable |

296| `CLAUDE_CODE_SCRIPT_CAPS` | JSON object limiting how many times specific scripts may be invoked per session when `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` is set. Keys are substrings matched against the command text; values are integer call limits. For example, `{"deploy.sh": 2}` allows `deploy.sh` to be called at most twice. Matching is substring-based so shell-expansion tricks like `./scripts/deploy.sh $(evil)` still count against the cap. Runtime fan-out via `xargs` or `find -exec` is not detected; this is a defense-in-depth control |297| `CLAUDE_CODE_SCRIPT_CAPS` | JSON object limiting how many times specific scripts may be invoked per session when `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` is set. Keys are substrings matched against the command text; values are integer call limits. For example, `{"deploy.sh": 2}` allows `deploy.sh` to be called at most twice. Matching is substring-based so shell-expansion tricks like `./scripts/deploy.sh $(evil)` still count against the cap. Runtime fan-out via `xargs` or `find -exec` is not detected; this is a defense-in-depth control |

297| `CLAUDE_CODE_SCROLL_SPEED` | Set the mouse wheel scroll multiplier in [fullscreen rendering](/en/fullscreen#mouse-wheel-scrolling). Accepts values from 1 to 20, and fractional values below 1 such as `0.5` to slow accelerated trackpad and wheel scrolling in terminals that already amplify wheel events. Set to `3` to match `vim` if your terminal sends one wheel event per notch without amplification. Ignored in the JetBrains IDE terminal, where Claude Code uses its own scroll handling |298| `CLAUDE_CODE_SCROLL_SPEED` | Set the mouse wheel scroll multiplier in [fullscreen rendering](/en/fullscreen#mouse-wheel-scrolling). Accepts any positive value up to 20, including fractional values below 1 such as `0.5` to slow accelerated trackpad and wheel scrolling in terminals that already amplify wheel events. Set to `3` to match `vim` if your terminal sends one wheel event per notch without amplification. Ignored in the JetBrains IDE terminal, where Claude Code uses its own scroll handling |

298| `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` | Override the time budget in milliseconds for [SessionEnd](/en/hooks#sessionend) hooks. Applies to session exit, `/clear`, and switching sessions via interactive `/resume`. By default the budget is 1.5 seconds, automatically raised to the highest per-hook `timeout` configured in settings files, up to 60 seconds. Timeouts on plugin-provided hooks do not raise the budget |299| `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` | Override the time budget in milliseconds for [SessionEnd](/en/hooks#sessionend) hooks. Applies to session exit, `/clear`, and switching sessions via interactive `/resume`. By default the budget is 1.5 seconds, automatically raised to the highest per-hook `timeout` configured in settings files, up to 60 seconds. Timeouts on plugin-provided hooks do not raise the budget |

299| `CLAUDE_CODE_SESSION_ID` | Set automatically to the current session ID in Bash and PowerShell tool subprocesses, [hook command](/en/hooks) subprocesses, and stdio [MCP server](/en/mcp) subprocesses. For Bash, PowerShell, and hooks this matches the `session_id` field in the hook JSON input and is updated on `/clear`. An MCP server subprocess retains the ID it was spawned with. On `--resume <session-id>` it receives the resumed ID, matching hooks and Bash. On `--continue` or `--resume` without an explicit ID it may receive the initial startup ID instead. Use to correlate scripts and external tools with the Claude Code session that launched them |300| `CLAUDE_CODE_SESSION_ID` | Set automatically to the current session ID in Bash and PowerShell tool subprocesses, [hook command](/en/hooks) subprocesses, and stdio [MCP server](/en/mcp) subprocesses. For Bash, PowerShell, and hooks this matches the `session_id` field in the hook JSON input and is updated on `/clear`. An MCP server subprocess retains the ID it was spawned with. On `--resume <session-id>` it receives the resumed ID, matching hooks and Bash. On `--continue` or `--resume` without an explicit ID it may receive the initial startup ID instead. Use to correlate scripts and external tools with the Claude Code session that launched them |

300| `CLAUDE_CODE_SHELL` | Set the shell Claude Code uses to run Bash tool commands. Accepts a path to a `bash` or `zsh` binary, for example `/opt/homebrew/bin/bash`. Other shells such as `fish` are not supported. If the value is not a working `bash` or `zsh` path, Claude Code ignores it and falls back to auto-detection. Auto-detection uses your `$SHELL` when it points to `bash` or `zsh`, otherwise it picks the first working `zsh` then `bash` found on your `PATH` and standard install locations |301| `CLAUDE_CODE_SHELL` | Set the shell Claude Code uses to run Bash tool commands. Accepts a path to a `bash` or `zsh` binary, for example `/opt/homebrew/bin/bash`. Other shells such as `fish` are not supported. If the value is not a working `bash` or `zsh` path, Claude Code ignores it and falls back to auto-detection. Auto-detection uses your `$SHELL` when it points to `bash` or `zsh`, otherwise it picks the first working `zsh` then `bash` found on your `PATH` and standard install locations |


304| `CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH` | Skip client-side authentication for [Claude Platform on AWS](/en/claude-platform-on-aws), for gateways that sign requests themselves |305| `CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH` | Skip client-side authentication for [Claude Platform on AWS](/en/claude-platform-on-aws), for gateways that sign requests themselves |

305| `CLAUDE_CODE_SKIP_AWS_CRED_CACHE` | {/* min-version: 2.1.207 */}Set to `1` to turn off the in-process cache of credentials resolved from the AWS default credential provider chain, so Claude Code resolves the chain on every API request. With the cache off, an SSO-backed profile requests credentials from IAM Identity Center on every request. See [credential caching and resolution timeout](/en/amazon-bedrock#credential-caching-and-resolution-timeout). Requires Claude Code v2.1.207 or later |306| `CLAUDE_CODE_SKIP_AWS_CRED_CACHE` | {/* min-version: 2.1.207 */}Set to `1` to turn off the in-process cache of credentials resolved from the AWS default credential provider chain, so Claude Code resolves the chain on every API request. With the cache off, an SSO-backed profile requests credentials from IAM Identity Center on every request. See [credential caching and resolution timeout](/en/amazon-bedrock#credential-caching-and-resolution-timeout). Requires Claude Code v2.1.207 or later |

306| `CLAUDE_CODE_SKIP_BEDROCK_AUTH` | Skip AWS authentication for Amazon Bedrock (for example, when using an LLM gateway) |307| `CLAUDE_CODE_SKIP_BEDROCK_AUTH` | Skip AWS authentication for Amazon Bedrock (for example, when using an LLM gateway) |

308| `CLAUDE_CODE_SKIP_FAST_MODE_NETWORK_ERRORS` | Set to `1` to treat a failed [fast mode](/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways) availability check as available, for networks that block the check's direct request to `api.anthropic.com`. Claude Code still honors a "disabled by your organization" response |

309| `CLAUDE_CODE_SKIP_FAST_MODE_ORG_CHECK` | Set to `1` to skip the client-side [fast mode](/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways) availability check, for proxies that intercept the check's request rather than refuse it. The API still rejects fast mode requests when your organization has fast mode disabled |

307| `CLAUDE_CODE_SKIP_FOUNDRY_AUTH` | Skip Azure authentication for Microsoft Foundry, for a proxy or gateway that injects its own `Authorization` header. Claude Code sends requests without an Azure credential and preserves the `Authorization` header you supply, for example through `ANTHROPIC_CUSTOM_HEADERS`. Ignored when `ANTHROPIC_FOUNDRY_API_KEY` or `ANTHROPIC_FOUNDRY_AUTH_TOKEN` is set. {/* min-version: 2.1.203 */}Before v2.1.203, this variable left the Microsoft Foundry client unable to send requests unless an API key was also set |310| `CLAUDE_CODE_SKIP_FOUNDRY_AUTH` | Skip Azure authentication for Microsoft Foundry, for a proxy or gateway that injects its own `Authorization` header. Claude Code sends requests without an Azure credential and preserves the `Authorization` header you supply, for example through `ANTHROPIC_CUSTOM_HEADERS`. Ignored when `ANTHROPIC_FOUNDRY_API_KEY` or `ANTHROPIC_FOUNDRY_AUTH_TOKEN` is set. {/* min-version: 2.1.203 */}Before v2.1.203, this variable left the Microsoft Foundry client unable to send requests unless an API key was also set |

308| `CLAUDE_CODE_SKIP_MANTLE_AUTH` | Skip AWS authentication for Amazon Bedrock Mantle (for example, when using an LLM gateway) |311| `CLAUDE_CODE_SKIP_MANTLE_AUTH` | Skip AWS authentication for Amazon Bedrock Mantle (for example, when using an LLM gateway) |

309| `CLAUDE_CODE_SKIP_PROMPT_HISTORY` | Set to `1` to skip writing prompt history and session transcripts to disk. Sessions started with this variable set do not appear in `--resume`, `--continue`, or up-arrow history. Useful for ephemeral scripted sessions |312| `CLAUDE_CODE_SKIP_PROMPT_HISTORY` | Set to `1` to skip writing prompt history and session transcripts to disk. Sessions started with this variable set do not appear in `--resume`, `--continue`, or up-arrow history. Useful for ephemeral scripted sessions |

errors.md +1 −1

Details

429* Run the command configured in `apiKeyHelper` directly in your shell to reproduce the failure429* Run the command configured in `apiKeyHelper` directly in your shell to reproduce the failure

430* If the command reports an expired session, re-authenticate with your credential provider, for example by signing in to your SSO or secrets vault again430* If the command reports an expired session, re-authenticate with your credential provider, for example by signing in to your SSO or secrets vault again

431* Fix the command so it prints the key to stdout and exits with code 0. See [rotate credentials with apiKeyHelper](/en/llm-gateway-connect#rotate-credentials-with-apikeyhelper) for a working setup.431* Fix the command so it prints the key to stdout and exits with code 0. See [rotate credentials with apiKeyHelper](/en/llm-gateway-connect#rotate-credentials-with-apikeyhelper) for a working setup.

432* Run `/status` to confirm `apiKeyHelper` is the active credential source. Each time the command fails, its exit code and error output appear in a `Cloud authentication` panel in the terminal.432* Run `/status` to confirm `apiKeyHelper` is the active credential source. Each time the command fails, its exit code and error output appear in an `Authentication` panel in the terminal. {/* min-version: 2.1.212 */}Before v2.1.212, the panel was titled Cloud authentication.

433 433 

434### This organization has been disabled434### This organization has been disabled

435 435 

fast-mode.md +24 −0

Details

113 113 

114Another option to disable fast mode entirely is to set `CLAUDE_CODE_DISABLE_FAST_MODE=1`. See [Environment variables](/en/env-vars).114Another option to disable fast mode entirely is to set `CLAUDE_CODE_DISABLE_FAST_MODE=1`. See [Environment variables](/en/env-vars).

115 115 

116### Use fast mode behind proxies and LLM gateways

117 

118Before offering fast mode, Claude Code checks your organization's fast mode availability with a request directly to `api.anthropic.com`. The check doesn't follow [`ANTHROPIC_BASE_URL`](/en/llm-gateway-connect#set-the-base-url-and-credential), so on a network that routes Claude traffic through an [LLM gateway](/en/llm-gateway) and blocks direct egress to `api.anthropic.com`, the check fails even though inference requests work. The check does use a configured [HTTP proxy](/en/network-config#proxy-configuration), so a network block fails the check only where `api.anthropic.com` is unreachable even through the proxy.

119 

120When the check fails, `/fast` reports "Fast mode unavailable due to network connectivity issues", and requests run at standard speed, even when your organization has fast mode enabled. A check that succeeded in the past keeps working from its cached result, so a blocked check mostly affects new installations.

121 

122The same connectivity message appears on an open network when the check reaches `api.anthropic.com` but presents a credential Anthropic rejects. A session whose resolved key is a gateway-issued credential, held in [`ANTHROPIC_API_KEY`](/en/llm-gateway-connect#set-the-base-url-and-credential) or produced by an [`apiKeyHelper`](/en/settings#available-settings), sends the check with that key, and the rejected request is reported as a connectivity failure.

123 

124To restore fast mode, allowlist direct egress to `api.anthropic.com` where a network block is the cause, or set whichever variable matches how the check fails:

125 

126* `CLAUDE_CODE_SKIP_FAST_MODE_NETWORK_ERRORS=1` treats a failed check as available and still honors a "disabled by your organization" response. Use it when your network refuses the connection, or when Anthropic rejects a gateway credential; allowlisting doesn't help the credential case, since nothing is blocked.

127* `CLAUDE_CODE_SKIP_FAST_MODE_ORG_CHECK=1` skips the check entirely. Use it when your network intercepts the request rather than refusing it.

128 

129Two gateway configurations report "Fast mode has been disabled by your organization" rather than the connectivity message, even when your organization has fast mode enabled:

130 

131* A session that authenticates with [`ANTHROPIC_AUTH_TOKEN`](/en/llm-gateway-connect#set-the-base-url-and-credential) alone skips the check: without a claude.ai login or an Anthropic API key, and without a cached successful check, Claude Code treats fast mode as disabled by your organization without sending the request.

132* A proxy that intercepts the check and answers with its own page, for example a TLS-inspecting proxy returning an HTTP 200 block page, is read as a response saying your organization has fast mode disabled.

133 

134In both cases, set `CLAUDE_CODE_SKIP_FAST_MODE_ORG_CHECK=1` to restore fast mode. `CLAUDE_CODE_SKIP_FAST_MODE_NETWORK_ERRORS` doesn't apply to either case, since it only bypasses failed checks and both of these produce a disabled response instead. Allowlisting direct egress doesn't help the bearer-token case, which never sends the request.

135 

136The variables affect only the client-side check. When your organization has fast mode disabled, the API rejects fast mode requests whether or not they're set.

137 

138Setting `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` also suppresses the availability check. Without a previously cached successful check, `/fast` reports "Fast mode is currently unavailable"; both skip variables restore fast mode in that configuration too.

139 

116### Require per-session opt-in140### Require per-session opt-in

117 141 

118By default, fast mode a user turns on in an interactive session persists across sessions: it stays on in future sessions. To change this, set `fastModePerSessionOptIn` to `true` in any [settings file](/en/settings#settings-files), which causes each session to start with fast mode off and requires users to explicitly enable it with `/fast`. Owners on [Team](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=fast_mode_teams#team-&-enterprise) or [Enterprise](https://anthropic.com/contact-sales?utm_source=claude_code\&utm_medium=docs\&utm_content=fast_mode_enterprise) plans can deploy it organization-wide through [server-managed settings](/en/server-managed-settings).142By default, fast mode a user turns on in an interactive session persists across sessions: it stays on in future sessions. To change this, set `fastModePerSessionOptIn` to `true` in any [settings file](/en/settings#settings-files), which causes each session to start with fast mode off and requires users to explicitly enable it with `/fast`. Owners on [Team](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=fast_mode_teams#team-&-enterprise) or [Enterprise](https://anthropic.com/contact-sales?utm_source=claude_code\&utm_medium=docs\&utm_content=fast_mode_enterprise) plans can deploy it organization-wide through [server-managed settings](/en/server-managed-settings).

fullscreen.md +5 −4

Details

108export CLAUDE_CODE_SCROLL_SPEED=3108export CLAUDE_CODE_SCROLL_SPEED=3

109```109```

110 110 

111A value of `3` matches the default in `vim` and similar applications. The setting accepts values from 1 to 20, and fractional values below 1 such as `0.5` to slow accelerated trackpad and wheel scrolling in terminals that already amplify wheel events.111A value of `3` matches the default in `vim` and similar applications. The setting accepts any positive value up to 20, including fractional values below 1 such as `0.25` to slow accelerated trackpad and wheel scrolling in terminals that already amplify wheel events.

112 112 

113To adjust scroll speed interactively, run `/scroll-speed`. The dialog shows a ruler you can scroll while it is open so you can feel the change immediately. Press `←` and `→` to adjust, `r` to reset to the auto-detected default, and `Enter` to save.113To adjust scroll speed interactively, run `/scroll-speed`. The dialog shows a ruler you can scroll while it is open so you can feel the change immediately. Press `←` and `→` to adjust the speed, `r` to reset to the auto-detected default, and `Enter` to save. The dialog steps in whole numbers up to 10, and on terminals that support finer control it also offers quarter steps down to 0.25. {/* min-version: 2.1.172 */}Quarter steps require Claude Code v2.1.172 or later.

114 114 

115The command writes the same value the `CLAUDE_CODE_SCROLL_SPEED` environment variable sets, persisted to `~/.claude/settings.json`. The command isn't available in the JetBrains IDE terminal.115The command writes the same value the `CLAUDE_CODE_SCROLL_SPEED` environment variable sets, persisted to `~/.claude/settings.json`. The dialog's maximum is 10: if you set a higher value through the environment variable, the dialog shows 10, and saving from the dialog persists 10. The command isn't available in the JetBrains IDE terminal.

116 116 

117Separately from the base speed, Claude Code accelerates the scroll rate when you spin the wheel quickly, so a fast spin covers more distance than the same number of slow notches. {/* min-version: 2.1.174 */}To turn acceleration off and keep a constant rate per notch, set `wheelScrollAccelerationEnabled` to `false` in [`settings.json`](/en/settings#available-settings). This setting requires Claude Code v2.1.174 or later.117Separately from the base speed, Claude Code accelerates the scroll rate when you spin the wheel quickly, so a fast spin covers more distance than the same number of slow notches. {/* min-version: 2.1.174 */}To turn acceleration off and keep a constant rate per notch, set `wheelScrollAccelerationEnabled` to `false` in [`settings.json`](/en/settings#available-settings). This setting requires Claude Code v2.1.174 or later.

118 118 


136| `n` / `N` | Jump to next or previous match. Works after you've closed the search bar |136| `n` / `N` | Jump to next or previous match. Works after you've closed the search bar |

137| `j` / `k` or `↑` / `↓` | Scroll one line |137| `j` / `k` or `↑` / `↓` | Scroll one line |

138| `g` / `G` or `Home` / `End` | Jump to top or bottom |138| `g` / `G` or `Home` / `End` | Jump to top or bottom |

139| `{` / `}` | Jump to the previous or next prompt |

139| `Ctrl+u` / `Ctrl+d` | Scroll half a page |140| `Ctrl+u` / `Ctrl+d` | Scroll half a page |

140| `Ctrl+b` / `Ctrl+f` or `Space` / `b` | Scroll a full page |141| `Ctrl+b` / `Ctrl+f` or `Space` / `b` | Scroll a full page |

141| `Ctrl+o`, `Esc`, or `q` | Exit transcript mode and return to the prompt |142| `Ctrl+o`, `Esc`, or `q` | Exit transcript mode and return to the prompt |


235 236 

236If you encounter a problem, run `/feedback` inside Claude Code to report it, or open an issue on the [claude-code GitHub repo](https://github.com/anthropics/claude-code/issues). Include your terminal emulator name and version.237If you encounter a problem, run `/feedback` inside Claude Code to report it, or open an issue on the [claude-code GitHub repo](https://github.com/anthropics/claude-code/issues). Include your terminal emulator name and version.

237 238 

238To turn fullscreen rendering off, run `/tui default`, or unset `CLAUDE_CODE_NO_FLICKER` if you enabled it that way. To force the classic renderer regardless of the saved `tui` setting, set `CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN=1`. The classic renderer keeps the conversation in your terminal's native scrollback so `Cmd+f` and tmux copy mode work as usual.239To turn fullscreen rendering off, run `/tui default`, or unset `CLAUDE_CODE_NO_FLICKER` if you enabled it that way. When you switch back with `/tui default`, Claude Code may first show an optional feedback prompt asking what made you switch. Type a reason and press `Enter` to send it, or press `Esc` to skip. The CLI relaunches into the classic renderer either way. To force the classic renderer regardless of the saved `tui` setting, set `CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN=1`. The classic renderer keeps the conversation in your terminal's native scrollback so `Cmd+f` and tmux copy mode work as usual.

239 240 

240Background sessions opened from [agent view](/en/agent-view) or `claude attach` always use fullscreen rendering. The attaching terminal enters the alternate screen buffer to show the session, and the classic renderer has no scrollback or mouse handling there, so the `tui` setting and `CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN` don't apply to them.241Background sessions opened from [agent view](/en/agent-view) or `claude attach` always use fullscreen rendering. The attaching terminal enters the alternate screen buffer to show the session, and the classic renderer has no scrollback or mouse handling there, so the `tui` setting and `CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN` don't apply to them.

glossary.md +1 −1

Details

276 276 

277### Surface277### Surface

278 278 

279Any place you access Claude Code: the CLI, VS Code, JetBrains, Desktop, or claude.ai. All surfaces share the same engine, so your CLAUDE.md, settings, and skills work the same way across them. Slack and the Chrome extension are integrations that connect to a surface rather than surfaces themselves.279Any place you access Claude Code: the CLI, VS Code, JetBrains, Desktop, or claude.ai. All surfaces share the same engine. Sessions on your machine read your local CLAUDE.md, settings, and skills; [cloud sessions](/en/claude-code-on-the-web#what’s-available-in-cloud-sessions) start from a fresh clone of your repository and don't read `~/.claude/` on your machine. Slack and the Chrome extension are integrations that connect to a surface rather than surfaces themselves.

280 280 

281Learn more: [Platforms and integrations](/en/platforms)281Learn more: [Platforms and integrations](/en/platforms)

282 282 

headless.md +2 −2

Details

127If the value isn't a valid JSON Schema, `claude` exits with `Error: --json-schema is not a valid JSON Schema` followed by the validator's diagnostic. Claude Code accepts schemas that use the `format` keyword, such as `"format": "email"`, but treats `format` as an annotation and doesn't enforce it. Before v2.1.205, Claude Code silently ignored an invalid schema and returned unstructured text, and treated any schema containing `format` as invalid.127If the value isn't a valid JSON Schema, `claude` exits with `Error: --json-schema is not a valid JSON Schema` followed by the validator's diagnostic. Claude Code accepts schemas that use the `format` keyword, such as `"format": "email"`, but treats `format` as an annotation and doesn't enforce it. Before v2.1.205, Claude Code silently ignored an invalid schema and returned unstructured text, and treated any schema containing `format` as invalid.

128 128 

129<Tip>129<Tip>

130 Use a tool like [jq](https://jqlang.github.io/jq/) to parse the response and extract specific fields:130 Use a tool like [jq](https://jqlang.org/) to parse the response and extract specific fields:

131 131 

132 ```bash theme={null}132 ```bash theme={null}

133 # Extract the text result133 # Extract the text result


155 155 

156By default, Claude Code emits only subagent `tool_use` and `tool_result` blocks. {/* min-version: 2.1.211 */}Pass [`--forward-subagent-text`](/en/cli-reference#cli-flags) or set [`CLAUDE_CODE_FORWARD_SUBAGENT_TEXT`](/en/env-vars) to also emit subagent text and thinking blocks, so you can reconstruct each subagent's transcript. This requires Claude Code v2.1.211 or later.156By default, Claude Code emits only subagent `tool_use` and `tool_result` blocks. {/* min-version: 2.1.211 */}Pass [`--forward-subagent-text`](/en/cli-reference#cli-flags) or set [`CLAUDE_CODE_FORWARD_SUBAGENT_TEXT`](/en/env-vars) to also emit subagent text and thinking blocks, so you can reconstruct each subagent's transcript. This requires Claude Code v2.1.211 or later.

157 157 

158The following example uses [jq](https://jqlang.github.io/jq/) to filter for text deltas and display just the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously:158The following example uses [jq](https://jqlang.org/) to filter for text deltas and display just the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously:

159 159 

160```bash theme={null}160```bash theme={null}

161claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \161claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \

hooks.md +1 −1

Details

1579If the deferred tool is no longer available when you resume, the process exits with `stop_reason: "tool_deferred_unavailable"` and `is_error: true` before the hook fires. This happens when an MCP server that provided the tool is not connected for the resumed session. The `deferred_tool_use` payload is still included so you can identify which tool went missing.1579If the deferred tool is no longer available when you resume, the process exits with `stop_reason: "tool_deferred_unavailable"` and `is_error: true` before the hook fires. This happens when an MCP server that provided the tool is not connected for the resumed session. The `deferred_tool_use` payload is still included so you can identify which tool went missing.

1580 1580 

1581<Note>1581<Note>

1582 `--resume` restores the permission mode that was active when the tool was deferred, so you don't need to pass `--permission-mode` again. The exceptions are `plan` and `bypassPermissions`, which are never carried over. Passing `--permission-mode` explicitly on resume overrides the restored value.1582 `--resume` restores the permission mode that was active when the tool was deferred, so you don't need to pass `--permission-mode` again. The exceptions are `plan` and `bypassPermissions`, which are never carried over, and `auto`, which is restored only when your account still meets the [auto mode requirements](/en/permission-modes#eliminate-prompts-with-auto-mode). Passing `--permission-mode` explicitly on resume overrides the restored value.

1583</Note>1583</Note>

1584 1584 

1585### PermissionRequest1585### PermissionRequest

hooks-guide.md +5 −5

Details

22 22 

23<Steps>23<Steps>

24 <Step title="Add the hook to your settings">24 <Step title="Add the hook to your settings">

25 Open `~/.claude/settings.json` and add a `Notification` hook. The example below uses `osascript` for macOS; see [Get notified when Claude needs input](#get-notified-when-claude-needs-input) for Linux and Windows commands.25 Open `~/.claude/settings.json` and add a `Notification` hook. If the file doesn't exist, create it. The example below uses `osascript` for macOS; see [Get notified when Claude needs input](#get-notified-when-claude-needs-input) for Linux and Windows commands.

26 26 

27 ```json theme={null}27 ```json theme={null}

28 {28 {


186 186 

187Automatically run [Prettier](https://prettier.io/) on every file Claude edits, so formatting stays consistent without manual intervention.187Automatically run [Prettier](https://prettier.io/) on every file Claude edits, so formatting stays consistent without manual intervention.

188 188 

189This hook uses the `PostToolUse` event with an `Edit|Write` matcher, so it runs only after file-editing tools. The command extracts the edited file path with [`jq`](https://jqlang.github.io/jq/) and passes it to Prettier. Add this to `.claude/settings.json` in your project root:189This hook uses the `PostToolUse` event with an `Edit|Write` matcher, so it runs only after file-editing tools. The command extracts the edited file path with [`jq`](https://jqlang.org/) and passes it to Prettier. Add this to `.claude/settings.json` in your project root:

190 190 

191```json theme={null}191```json theme={null}

192{192{


209On Claude Code v2.1.191 or later you can also write the matcher as `Edit,Write`, since `|` and `,` are interchangeable list separators for tool-name matchers on those versions.209On Claude Code v2.1.191 or later you can also write the matcher as `Edit,Write`, since `|` and `,` are interchangeable list separators for tool-name matchers on those versions.

210 210 

211<Note>211<Note>

212 The Bash examples on this page use `jq` for JSON parsing. Install it with `brew install jq` on macOS, `apt-get install jq` on Debian and Ubuntu, or see [`jq` downloads](https://jqlang.github.io/jq/download/).212 The Bash examples on this page use `jq` for JSON parsing. Install it with `brew install jq` on macOS, `apt-get install jq` on Debian and Ubuntu, or see [`jq` downloads](https://jqlang.org/download/).

213</Note>213</Note>

214 214 

215### Block edits to protected files215### Block edits to protected files


823 823 

824When verification requires inspecting files or running commands, use `type: "agent"` hooks. Unlike prompt hooks, which make a single LLM call, agent hooks spawn a subagent that can read files, search code, and use other tools to verify conditions before returning a decision.824When verification requires inspecting files or running commands, use `type: "agent"` hooks. Unlike prompt hooks, which make a single LLM call, agent hooks spawn a subagent that can read files, search code, and use other tools to verify conditions before returning a decision.

825 825 

826Agent hooks use the same `"ok"` / `"reason"` response format as prompt hooks, but with a longer default timeout of 60 seconds and up to 50 tool-use turns.826Agent hooks use the same `"ok"` / `"reason"` response format as prompt hooks, but with a longer default timeout of 60 seconds and up to 50 tool-use turns. The `$ARGUMENTS` placeholder in the prompt is replaced with the hook's JSON input. See [prompt and agent hook fields](/en/hooks#prompt-and-agent-hook-fields).

827 827 

828This example verifies that tests pass before allowing Claude to stop:828This example verifies that tests pass before allowing Claude to stop:

829 829 


902 902 

903### Hooks and permission modes903### Hooks and permission modes

904 904 

905`PreToolUse` hooks fire before any permission-mode check. A hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. This lets you enforce policy that users can't bypass by changing their permission mode.905`PreToolUse` hooks fire before any permission-mode check, in every [permission mode](/en/permission-modes), including `dontAsk`. A hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. This lets you enforce policy that users can't bypass by changing their permission mode.

906 906 

907The reverse is not true: a hook returning `"allow"` doesn't bypass deny rules from settings, and it can't suppress the prompt for connector tools [your organization set to `ask`](/en/mcp#organization-controls-on-connector-tools) or MCP tools marked [`requiresUserInteraction`](/en/mcp#require-approval-for-a-specific-tool). Hooks can tighten restrictions but not loosen them past what permission rules allow.907The reverse is not true: a hook returning `"allow"` doesn't bypass deny rules from settings, and it can't suppress the prompt for connector tools [your organization set to `ask`](/en/mcp#organization-controls-on-connector-tools) or MCP tools marked [`requiresUserInteraction`](/en/mcp#require-approval-for-a-specific-tool). Hooks can tighten restrictions but not loosen them past what permission rules allow.

908 908 

Details

11<Note>11<Note>

12 Keyboard shortcuts may vary by platform and terminal. In [fullscreen rendering](/en/fullscreen), press `?` in the transcript viewer to see available shortcuts there.12 Keyboard shortcuts may vary by platform and terminal. In [fullscreen rendering](/en/fullscreen), press `?` in the transcript viewer to see available shortcuts there.

13 13 

14 **macOS users**: Option/Alt key shortcuts (`Alt+B`, `Alt+F`, `Alt+Y`, `Alt+M`, `Alt+P`) require configuring Option as Meta in your terminal:14 **macOS users**: Option/Alt key shortcuts (`Alt+B`, `Alt+F`, `Alt+Y`, `Alt+P`) require configuring Option as Meta in your terminal:

15 15 

16 * **iTerm2**: Settings → Profiles → Keys → General → set Left/Right Option key to "Esc+"16 * **iTerm2**: Settings → Profiles → Keys → General → set Left/Right Option key to "Esc+"

17 * **Apple Terminal**: Settings → Profiles → Keyboard → check "Use Option as Meta Key"17 * **Apple Terminal**: Settings → Profiles → Keyboard → check "Use Option as Meta Key"


23### General controls23### General controls

24 24 

25| Shortcut | Description | Context |25| Shortcut | Description | Context |

26| :-------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |26| :------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

27| `Ctrl+C` | Interrupt, or clear input | Interrupts a running operation. If nothing is running, the first press clears the prompt input and a second press exits Claude Code |27| `Ctrl+C` | Interrupt, or clear input | Interrupts a running operation. If nothing is running, the first press clears the prompt input and a second press exits Claude Code |

28| `Ctrl+X Ctrl+K` | Stop all running [background subagents](/en/sub-agents#run-subagents-in-foreground-or-background) in this session. Press twice within 3 seconds to confirm | Subagent control |28| `Ctrl+X Ctrl+K` | Stop all running [background subagents](/en/sub-agents#run-subagents-in-foreground-or-background) in this session. Press twice within 3 seconds to confirm | Subagent control |

29| `Ctrl+D` | Exit Claude Code session | The first press shows a confirmation hint and a second press within 800ms exits. When the prompt has text, `Ctrl+D` deletes the character after the cursor instead |29| `Ctrl+D` | Exit Claude Code session | The first press shows a confirmation hint and a second press within 800ms exits. When the prompt has text, `Ctrl+D` deletes the character after the cursor instead |


34| `Ctrl+V` or `Cmd+V` (iTerm2) or `Alt+V` (Windows and WSL) | Paste image from clipboard | Inserts an `[Image #N]` chip at the cursor so you can reference it positionally in your prompt. On WSL, both `Ctrl+V` and `Alt+V` are bound; use `Alt+V` if your terminal intercepts `Ctrl+V` |34| `Ctrl+V` or `Cmd+V` (iTerm2) or `Alt+V` (Windows and WSL) | Paste image from clipboard | Inserts an `[Image #N]` chip at the cursor so you can reference it positionally in your prompt. On WSL, both `Ctrl+V` and `Alt+V` are bound; use `Alt+V` if your terminal intercepts `Ctrl+V` |

35| `Ctrl+B` | Background running tasks | Backgrounds Bash commands and agents. Tmux users press twice |35| `Ctrl+B` | Background running tasks | Backgrounds Bash commands and agents. Tmux users press twice |

36| `Ctrl+T` | Toggle Claude's task checklist | Show or hide [Claude's to-do checklist](#task-list) in the status area. This is not the background-task view; use [`/tasks`](/en/commands) to see running shells and subagents |36| `Ctrl+T` | Toggle Claude's task checklist | Show or hide [Claude's to-do checklist](#task-list) in the status area. This is not the background-task view; use [`/tasks`](/en/commands) to see running shells and subagents |

37| `Ctrl+S` | Stash or restore prompt | With text in the input, stashes it and clears the prompt. Pressed again on an empty prompt, restores the stashed text, cursor position, and pasted content |

38| `Ctrl+Z` | Suspend Claude Code | Unix only. Suspends the process to your shell; run `fg` to resume |

37| `Left/Right arrows` | Cycle through dialog tabs | Navigate between tabs in permission dialogs and menus |39| `Left/Right arrows` | Cycle through dialog tabs | Navigate between tabs in permission dialogs and menus |

38| `Up/Down arrows` or `Ctrl+P`/`Ctrl+N` | Move cursor or navigate command history | When the input spans more than one visual row, whether wrapped or multiline, first moves the cursor within the prompt. Once the cursor is on the first or last visual row, pressing again navigates command history. {/* min-version: 2.1.169 */}As of v2.1.169, wrapped single-line input behaves the same as multiline |40| `Up/Down arrows` or `Ctrl+P`/`Ctrl+N` | Move cursor or navigate command history | When the input spans more than one visual row, whether wrapped or multiline, first moves the cursor within the prompt. Once the cursor is on the first or last visual row, pressing again navigates command history. {/* min-version: 2.1.169 */}As of v2.1.169, wrapped single-line input behaves the same as multiline |

39| `Esc` | Interrupt Claude, or close a dialog | Stop the current response or tool call mid-turn so you can redirect. Claude keeps the work done so far. When a dialog such as a permission prompt is open, `Esc` closes the dialog rather than interrupting Claude. {/* min-version: 2.1.202 */}Before v2.1.202, `Esc` on some dialogs interrupted Claude and left the dialog open |41| `Esc` | Interrupt Claude, or close a dialog | Stop the current response or tool call mid-turn so you can redirect. Claude keeps the work done so far. When a dialog such as a permission prompt is open, `Esc` closes the dialog rather than interrupting Claude. {/* min-version: 2.1.202 */}Before v2.1.202, `Esc` on some dialogs interrupted Claude and left the dialog open |

40| `Esc` + `Esc` | Clear input draft, or rewind | When the prompt input contains text, double `Esc` clears it and saves the draft to history so `Up` recalls it. When the input is empty, double `Esc` opens the [rewind menu](/en/checkpointing) to restore or summarize code and conversation from a previous point |42| `Esc` + `Esc` | Clear input draft, or rewind | When the prompt input contains text, double `Esc` clears it and saves the draft to history so `Up` recalls it. When the input is empty, double `Esc` opens the [rewind menu](/en/checkpointing) to restore or summarize code and conversation from a previous point |

41| `Shift+Tab` or `Alt+M` (some configurations) | Cycle permission modes | Cycle through `default` (labeled Manual in the mode indicator), `acceptEdits`, `plan`, and any modes you have enabled, such as `auto` or `bypassPermissions`. See [permission modes](/en/permission-modes). |43| `Shift+Tab`, or `Alt+M` on Windows when the Node or Bun runtime doesn't enable VT input mode | Cycle permission modes | Cycle through `default` (labeled Manual in the mode indicator), `acceptEdits`, `plan`, and any modes you have enabled, such as `auto` or `bypassPermissions`. See [permission modes](/en/permission-modes). |

42| `Option+P` (macOS) or `Alt+P` (Windows/Linux) | Switch model | Switch models without clearing your prompt |44| `Option+P` (macOS) or `Alt+P` (Windows/Linux) | Switch model | Switch models without clearing your prompt |

43| `Option+T` (macOS) or `Alt+T` (Windows/Linux) | Toggle extended thinking | Enable or disable extended thinking mode. Has no effect on Fable 5, which always uses extended thinking. {/* min-version: 2.1.132 */}As of v2.1.132 this shortcut works on macOS without configuring Option as Meta |45| `Option+T` (macOS) or `Alt+T` (Windows/Linux) | Toggle extended thinking | Enable or disable extended thinking mode. Has no effect on Fable 5, which always uses extended thinking. {/* min-version: 2.1.132 */}As of v2.1.132 this shortcut works on macOS without configuring Option as Meta |

44| `Option+O` (macOS) or `Alt+O` (Windows/Linux) | Toggle fast mode | Enable or disable [fast mode](/en/fast-mode) |46| `Option+O` (macOS) or `Alt+O` (Windows/Linux) | Toggle fast mode | Enable or disable [fast mode](/en/fast-mode) |


46### Text editing48### Text editing

47 49 

48| Shortcut | Description | Context |50| Shortcut | Description | Context |

49| :----------------------- | :----------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |51| :------------------------- | :----------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

50| `Ctrl+A` | Move cursor to start of current line | In multiline input, moves to the start of the current logical line |52| `Ctrl+A` | Move cursor to start of current line | In multiline input, moves to the start of the current logical line |

51| `Ctrl+E` | Move cursor to end of current line | In multiline input, moves to the end of the current logical line |53| `Ctrl+E` | Move cursor to end of current line | In multiline input, moves to the end of the current logical line |

52| `Ctrl+K` | Delete to end of line | Stores deleted text for pasting |54| `Ctrl+K` | Delete to end of line | Stores deleted text for pasting |


56| `Alt+Y` (after `Ctrl+Y`) | Cycle paste history | After pasting, cycle through previously deleted text. Requires [Option as Meta](#keyboard-shortcuts) on macOS |58| `Alt+Y` (after `Ctrl+Y`) | Cycle paste history | After pasting, cycle through previously deleted text. Requires [Option as Meta](#keyboard-shortcuts) on macOS |

57| `Alt+B` | Move cursor back one word | Word navigation. Requires [Option as Meta](#keyboard-shortcuts) on macOS |59| `Alt+B` | Move cursor back one word | Word navigation. Requires [Option as Meta](#keyboard-shortcuts) on macOS |

58| `Alt+F` | Move cursor forward one word | Word navigation. Requires [Option as Meta](#keyboard-shortcuts) on macOS |60| `Alt+F` | Move cursor forward one word | Word navigation. Requires [Option as Meta](#keyboard-shortcuts) on macOS |

61| `Ctrl+_` or `Ctrl+Shift+-` | Undo last input edit | Restores the previous input text and cursor position |

59 62 

60### Theme and display63### Theme and display

61 64 


88 91 

89### Transcript viewer92### Transcript viewer

90 93 

91When the transcript viewer is open (toggled with `Ctrl+O`), these shortcuts are available. In [fullscreen rendering](/en/fullscreen), press `?` to show the full shortcut reference panel inside the viewer. `Ctrl+E` can be rebound via [`transcript:toggleShowAll`](/en/keybindings).94When the transcript viewer is open (toggled with `Ctrl+O`), these shortcuts are available. Run `/tui` with no argument to check which renderer is active. In [fullscreen rendering](/en/fullscreen), press `?` to show the full shortcut reference panel inside the viewer. `Ctrl+E` can be rebound via [`transcript:toggleShowAll`](/en/keybindings).

92 95 

93| Shortcut | Description |96| Shortcut | Description |

94| :------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |97| :------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

95| `?` | Toggle the keyboard shortcut help panel. Requires [fullscreen rendering](/en/fullscreen) |98| `?` | Toggle the keyboard shortcut help panel. Requires [fullscreen rendering](/en/fullscreen) |

96| `{` / `}` | Jump to the previous or next user prompt, like vim paragraph motion. Requires [fullscreen rendering](/en/fullscreen) |99| `{` / `}` | Jump to the previous or next user prompt, like vim paragraph motion. Requires [fullscreen rendering](/en/fullscreen) |

97| `Ctrl+E` | Toggle show all content |100| `Ctrl+E` | Toggle show all content. Available in the default renderer only, not in [fullscreen rendering](/en/fullscreen) |

98| `[` | Write the full conversation to your terminal's native scrollback so `Cmd+F`, tmux copy mode, and other native tools can search it. Requires [fullscreen rendering](/en/fullscreen#search-and-review-the-conversation) |101| `[` | Write the full conversation to your terminal's native scrollback so `Cmd+F`, tmux copy mode, and other native tools can search it. Requires [fullscreen rendering](/en/fullscreen#search-and-review-the-conversation) |

99| `v` | Write the conversation to a temporary file and open it in `$VISUAL` or `$EDITOR`. Requires [fullscreen rendering](/en/fullscreen) |102| `v` | Write the conversation to a temporary file and open it in `$VISUAL` or `$EDITOR`. Requires [fullscreen rendering](/en/fullscreen) |

100| `q`, `Ctrl+C`, `Esc` | Exit transcript view. All three can be rebound via [`transcript:exit`](/en/keybindings) |103| `q`, `Ctrl+C`, `Esc` | Exit transcript view. All three can be rebound via [`transcript:exit`](/en/keybindings) |


245 248 

246### Reverse search with Ctrl+R249### Reverse search with Ctrl+R

247 250 

248Press `Ctrl+R` to interactively search through your command history:251Press `Ctrl+R` to interactively search through your command history. In [fullscreen rendering](/en/fullscreen), `Ctrl+R` opens a search dialog instead: type to filter, press `Up` and `Down` to move through matches, and press `Ctrl+S` to cycle the scope through this session, this project, and all projects. Press `Enter` or `Tab` to place a match in the prompt input, or `Esc` to cancel. The steps below describe the default inline search:

249 252 

2501. **Start search**: press `Ctrl+R` to activate reverse history search2531. **Start search**: press `Ctrl+R` to activate reverse history search

2512. **Type query**: enter text to search for in previous commands. The search term is highlighted in matching results2542. **Type query**: enter text to search for in previous commands. The search term is highlighted in matching results

2523. **Navigate matches**: press `Ctrl+R` again to cycle through older matches2553. **Navigate matches**: press `Ctrl+R` again to cycle through older matches

2534. **Change scope**: search defaults to prompts from all projects. Press `Ctrl+S` to cycle the scope through this session, this project, and all projects2564. **Search scope**: the inline search always searches prompts from all projects

2545. **Accept match**:2575. **Accept match**:

255 * Press `Tab` or `Esc` to accept the current match and continue editing258 * Press `Tab` or `Esc` to accept the current match and continue editing

256 * Press `Enter` to accept and execute the command immediately259 * Press `Enter` to accept and execute the command immediately


258 * Press `Ctrl+C` to cancel and restore your original input261 * Press `Ctrl+C` to cancel and restore your original input

259 * Press `Backspace` on empty search to cancel262 * Press `Backspace` on empty search to cancel

260 263 

261The search loads the 100 most recent unique prompts in the selected scope, with duplicates collapsed to the newest occurrence. Matching prompts display with the search term highlighted, so you can find and reuse previous inputs.264The inline search scans your full prompt history, newest first, with duplicates collapsed to the newest occurrence. The fullscreen dialog lists the 100 most recent unique prompts in the selected scope. Matching prompts display with the search term highlighted, so you can find and reuse previous inputs.

262 265 

263Accepting a match or canceling the search takes effect immediately, even while Claude Code is still loading the history. Before v2.1.202, accepting or canceling during that load could report an internal error.266Accepting a match or canceling the search takes effect immediately, even while Claude Code is still loading the history. Before v2.1.202, accepting or canceling during that load could report an internal error.

264 267 


331 334 

332Suggestions are automatically skipped after the first turn of a conversation and in plan mode.335Suggestions are automatically skipped after the first turn of a conversation and in plan mode.

333 336 

334In print mode they are off by default. Pass [`--prompt-suggestions`](/en/cli-reference#cli-flags) with `--output-format stream-json --verbose` to emit a `prompt_suggestion` message after each turn instead.337In print mode they are off by default. Pass [`--prompt-suggestions`](/en/cli-reference#cli-flags) with `-p "<prompt>" --output-format stream-json --verbose` to emit a `prompt_suggestion` message after each turn instead.

335 338 

336To disable prompt suggestions entirely, set the environment variable or toggle the setting in `/config`:339To disable prompt suggestions entirely, set the environment variable or toggle the setting in `/config`:

337 340 

jetbrains.md +3 −1

Details

77 77 

781. Run `claude`781. Run `claude`

792. Enter the `/config` command792. Enter the `/config` command

803. Set the diff tool to `auto` to show diffs in the IDE, or `terminal` to keep them in the terminal803. Set **Diff tool** to `auto` to show diffs in the IDE, or `terminal` to keep them in the terminal

81 

82The **Diff tool** entry appears in `/config` only when Claude Code is connected to the IDE, so run `claude` from the JetBrains terminal or run [`/ide`](/en/commands) first from an external terminal. See [`diffTool`](/en/settings#global-config-settings) for the underlying setting.

81 83 

82### Plugin settings84### Plugin settings

83 85 

keybindings.md +4 −0

Details

159| `transcript:toggleShowAll` | Ctrl+E | Toggle show all content |159| `transcript:toggleShowAll` | Ctrl+E | Toggle show all content |

160| `transcript:exit` | q, Ctrl+C, Escape | Exit transcript view |160| `transcript:exit` | q, Ctrl+C, Escape | Exit transcript view |

161 161 

162`transcript:toggleShowAll` applies in the default renderer only; in [fullscreen rendering](/en/fullscreen), the transcript viewer doesn't offer a show-all toggle.

163 

162### History search actions164### History search actions

163 165 

164Actions available in the `HistorySearch` context:166Actions available in the `HistorySearch` context:


171| `historySearch:execute` | Enter | Execute selected command |173| `historySearch:execute` | Enter | Execute selected command |

172| `historySearch:cycleScope` | Ctrl+S | Cycle scope: session, project, everywhere |174| `historySearch:cycleScope` | Ctrl+S | Cycle scope: session, project, everywhere |

173 175 

176The `historySearch:next`, `historySearch:accept`, `historySearch:cancel`, and `historySearch:execute` defaults apply to the inline history search in the default renderer, which always searches prompts from all projects. `historySearch:cycleScope` takes effect only in [fullscreen rendering](/en/fullscreen), where `Ctrl+R` opens a search dialog instead and `Ctrl+S` cycles its scope. The dialog's other keys are fixed and can't be rebound: `Enter` or `Tab` places the highlighted match in the prompt input and `Esc` cancels.

177 

174### Task actions178### Task actions

175 179 

176Actions available in the `Task` context:180Actions available in the `Task` context:

Details

489These are the most common errors when running Claude Code through a gateway, with the gateway-side cause and the fix:489These are the most common errors when running Claude Code through a gateway, with the gateway-side cause and the fix:

490 490 

491| Error | Cause | Fix |491| Error | Cause | Fix |

492| :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |492| :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

493| A startup warning naming two credential sources and ending in `auth may not work as expected`. Older versions show `Auth conflict: Both a token (SOURCE) and an API key (SOURCE) are set` instead. | A gateway credential and a saved login are both active; the variable is used for requests, but the stale login can cause unexpected auth behavior | Unset the variable to use the saved login, or run `/logout` to use the gateway credential |493| A startup warning naming two credential sources and ending in `auth may not work as expected`. Older versions show `Auth conflict: Both a token (SOURCE) and an API key (SOURCE) are set` instead. | A gateway credential and a saved login are both active; the variable is used for requests, but the stale login can cause unexpected auth behavior | Unset the variable to use the saved login, or run `/logout` to use the gateway credential |

494| `401` errors naming an invalid or unrecognized token | The credential isn't one the gateway issued, or it's in a header the gateway doesn't read | Confirm the variable matches your credential kind in the [credential table](#set-the-credential-variable), and regenerate the key at the gateway if it was revoked |494| `401` errors naming an invalid or unrecognized token | The credential isn't one the gateway issued, or it's in a header the gateway doesn't read | Confirm the variable matches your credential kind in the [credential table](#set-the-credential-variable), and regenerate the key at the gateway if it was revoked |

495| `Your apiKeyHelper script is failing` | The command in the [`apiKeyHelper`](/en/settings#available-settings) setting exited with an error, timed out, or printed nothing, so requests carry a placeholder key | Run the command directly to see why it fails, and re-authenticate with your credential provider if it reports an expired session; see [the error reference](/en/errors#your-apikeyhelper-script-is-failing) |495| `Your apiKeyHelper script is failing` | The command in the [`apiKeyHelper`](/en/settings#available-settings) setting exited with an error, timed out, or printed nothing, so requests carry a placeholder key | Run the command directly to see why it fails, and re-authenticate with your credential provider if it reports an expired session; see [the error reference](/en/errors#your-apikeyhelper-script-is-failing) |


499| `400` errors naming `thinking` or `adaptive`, such as `Input tag 'adaptive' found` | The upstream model build doesn't accept adaptive reasoning, which Claude Code requests for Claude 4.6 and later models | Upgrade the gateway's upstream. On Opus 4.6 and Sonnet 4.6, `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1` works instead. The [model configuration](/en/model-config) capability variables apply only to the provider configurations, such as `CLAUDE_CODE_USE_BEDROCK` and `CLAUDE_CODE_USE_VERTEX`, not behind an `ANTHROPIC_BASE_URL` gateway |499| `400` errors naming `thinking` or `adaptive`, such as `Input tag 'adaptive' found` | The upstream model build doesn't accept adaptive reasoning, which Claude Code requests for Claude 4.6 and later models | Upgrade the gateway's upstream. On Opus 4.6 and Sonnet 4.6, `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1` works instead. The [model configuration](/en/model-config) capability variables apply only to the provider configurations, such as `CLAUDE_CODE_USE_BEDROCK` and `CLAUDE_CODE_USE_VERTEX`, not behind an `ANTHROPIC_BASE_URL` gateway |

500| `400` errors stating a context or token limit in the gateway's own words, such as `ContextWindowExceededError` or `prompt token count of N exceeds the limit of M` | The gateway enforces a smaller context than the model's native window and rewrites the upstream error, so the automatic compact-and-retry, which matches Anthropic's `prompt is too long` wording, doesn't fire | Run `/compact` to recover the session. To prevent it, set `CLAUDE_CODE_AUTO_COMPACT_WINDOW` to the gateway's limit; the value is clamped to at least 100,000 tokens and at most the model's context window, so a gateway limit below 100,000 can't be matched and `/compact` remains the recovery there. Also set `CLAUDE_CODE_MAX_OUTPUT_TOKENS` below the gateway model's output limit |500| `400` errors stating a context or token limit in the gateway's own words, such as `ContextWindowExceededError` or `prompt token count of N exceeds the limit of M` | The gateway enforces a smaller context than the model's native window and rewrites the upstream error, so the automatic compact-and-retry, which matches Anthropic's `prompt is too long` wording, doesn't fire | Run `/compact` to recover the session. To prevent it, set `CLAUDE_CODE_AUTO_COMPACT_WINDOW` to the gateway's limit; the value is clamped to at least 100,000 tokens and at most the model's context window, so a gateway limit below 100,000 can't be matched and `/compact` remains the recovery there. Also set `CLAUDE_CODE_MAX_OUTPUT_TOKENS` below the gateway model's output limit |

501| Models missing from the `/model` picker | Gateway model names aren't in Claude Code's built-in list | Enable [gateway model discovery](#add-gateway-models-to-the-model-picker) or add names with the [model configuration](/en/model-config) variables |501| Models missing from the `/model` picker | Gateway model names aren't in Claude Code's built-in list | Enable [gateway model discovery](#add-gateway-models-to-the-model-picker) or add names with the [model configuration](/en/model-config) variables |

502| `/fast` reports `Fast mode unavailable due to network connectivity issues` while inference requests work | The [fast mode](/en/fast-mode) availability check goes directly to `api.anthropic.com` and doesn't follow `ANTHROPIC_BASE_URL`, so blocked direct egress fails the check. The same message appears on an open network when the check presents a gateway-issued key from `ANTHROPIC_API_KEY` or an `apiKeyHelper` and Anthropic rejects it | Allowlist `api.anthropic.com` if egress is blocked, or set a skip variable; for a rejected gateway key only the skip variables help. See [use fast mode behind proxies and LLM gateways](/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways) |

503| `/fast` reports `Fast mode has been disabled by your organization` in a session authenticated with `ANTHROPIC_AUTH_TOKEN`, even though the organization has fast mode enabled | The availability check requires a claude.ai login or an Anthropic API key; with only a bearer token, Claude Code treats fast mode as disabled without sending the check | Set `CLAUDE_CODE_SKIP_FAST_MODE_ORG_CHECK=1`; see [use fast mode behind proxies and LLM gateways](/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways) |

502| Claude Code asks you to log in even though the [curl test](#verify-the-connection) succeeds | The CLI has no credential of its own: a reachable base URL isn't one, and an `env` block in a project's `.claude/settings.json` or `.claude/settings.local.json` applies only after the first-run wizard and trust prompt | Set `ANTHROPIC_AUTH_TOKEN` somewhere Claude Code reads before first-run setup: a shell export, the `env` block in `~/.claude/settings.json`, or managed settings |504| Claude Code asks you to log in even though the [curl test](#verify-the-connection) succeeds | The CLI has no credential of its own: a reachable base URL isn't one, and an `env` block in a project's `.claude/settings.json` or `.claude/settings.local.json` applies only after the first-run wizard and trust prompt | Set `ANTHROPIC_AUTH_TOKEN` somewhere Claude Code reads before first-run setup: a shell export, the `env` block in `~/.claude/settings.json`, or managed settings |

503| `ANTHROPIC_API_KEY` is set but ignored, with no prompt | The key needs a one-time approval in interactive sessions, and a previously declined key is ignored without asking again | Enable it under `/config` with the `Use custom API key` option |505| `ANTHROPIC_API_KEY` is set but ignored, with no prompt | The key needs a one-time approval in interactive sessions, and a previously declined key is ignored without asking again | Enable it under `/config` with the `Use custom API key` option |

504| `This machine's managed settings require a first-party login` | Managed settings include `forceLoginMethod` or `forceLoginOrgUUID`, which on Claude Code v2.1.146 and later cannot coexist with `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or `apiKeyHelper` | Your administrator must remove `forceLoginMethod` and `forceLoginOrgUUID` from managed settings to use gateway credentials, or remove the gateway credential to use first-party login. The two cannot be combined |506| `This machine's managed settings require a first-party login` | Managed settings include `forceLoginMethod` or `forceLoginOrgUUID`, which on Claude Code v2.1.146 and later cannot coexist with `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or `apiKeyHelper` | Your administrator must remove `forceLoginMethod` and `forceLoginOrgUUID` from managed settings to use gateway credentials, or remove the gateway credential to use first-party login. The two cannot be combined |

Details

50 50 

51A gateway also sees best-effort startup traffic it can reject without breaking anything: a `HEAD /` connectivity probe, and on Amazon Bedrock-format gateways a `GET /inference-profiles?type=SYSTEM_DEFINED` request.51A gateway also sees best-effort startup traffic it can reject without breaking anything: a `HEAD /` connectivity probe, and on Amazon Bedrock-format gateways a `GET /inference-profiles?type=SYSTEM_DEFINED` request.

52 52 

53The [fast mode](/en/fast-mode) availability check never appears in gateway logs: it calls `api.anthropic.com` directly rather than following `ANTHROPIC_BASE_URL`, so on a network that blocks direct egress to `api.anthropic.com`, fast mode can report a connectivity error while inference through the gateway keeps working. The [WebFetch domain safety check](/en/data-usage#webfetch-domain-safety-check) also calls `api.anthropic.com` directly. [Use fast mode behind proxies and LLM gateways](/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways) covers the variables that restore it.

54 

53### Streaming55### Streaming

54 56 

55Inference responses must stream. Claude Code consumes server-sent events as they arrive, so a gateway that buffers complete responses before relaying them stalls the client.57Inference responses must stream. Claude Code consumes server-sent events as they arrive, so a gateway that buffers complete responses before relaying them stalls the client.

Details

164The same set of variables applies whichever path you choose. Most rollouts only need `ANTHROPIC_BASE_URL` and a credential; include the conditional rows when your gateway setup calls for them.164The same set of variables applies whichever path you choose. Most rollouts only need `ANTHROPIC_BASE_URL` and a credential; include the conditional rows when your gateway setup calls for them.

165 165 

166| Variable or setting | What it does | Include when |166| Variable or setting | What it does | Include when |

167| :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |167| :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

168| `ANTHROPIC_BASE_URL` | Sends Claude Code's API requests to the gateway instead of `api.anthropic.com` | Always |168| `ANTHROPIC_BASE_URL` | Sends Claude Code's API requests to the gateway instead of `api.anthropic.com` | Always |

169| `apiKeyHelper`, or a credential in `ANTHROPIC_AUTH_TOKEN` or `ANTHROPIC_API_KEY` | Authenticates each request to the gateway. The helper runs a command to fetch the key; the variables hold a static key, sent as `Authorization: Bearer` and `x-api-key` respectively | Always; one of the three |169| `apiKeyHelper`, or a credential in `ANTHROPIC_AUTH_TOKEN` or `ANTHROPIC_API_KEY` | Authenticates each request to the gateway. The helper runs a command to fetch the key; the variables hold a static key, sent as `Authorization: Bearer` and `x-api-key` respectively | Always; one of the three |

170| `ANTHROPIC_CUSTOM_HEADERS` | Adds extra HTTP headers to every API request | Your gateway requires a tenant or routing header on every request |170| `ANTHROPIC_CUSTOM_HEADERS` | Adds extra HTTP headers to every API request | Your gateway requires a tenant or routing header on every request |

171| `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY` | Queries the gateway's `/v1/models` at startup and adds the returned names to the `/model` picker | Your gateway serves `/v1/models` and you want developers' pickers populated from it |171| `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY` | Queries the gateway's `/v1/models` at startup and adds the returned names to the `/model` picker | Your gateway serves `/v1/models` and you want developers' pickers populated from it |

172| `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` | Stops Claude Code sending pre-release capability headers and body fields | Your gateway forwards to an Amazon Bedrock or Google Cloud's Agent Platform upstream that rejects beta fields; see [Gateway requirements](#gateway-requirements) |172| `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` | Stops Claude Code sending pre-release capability headers and body fields | Your gateway forwards to an Amazon Bedrock or Google Cloud's Agent Platform upstream that rejects beta fields; see [Gateway requirements](#gateway-requirements) |

173| `CLAUDE_CODE_SKIP_FAST_MODE_NETWORK_ERRORS` or `CLAUDE_CODE_SKIP_FAST_MODE_ORG_CHECK` | Restores [fast mode](/en/fast-mode) when its availability check, which calls `api.anthropic.com` directly rather than following `ANTHROPIC_BASE_URL`, fails, is intercepted, or is skipped for lack of an Anthropic credential | Your organization uses fast mode, and developers authenticate with `ANTHROPIC_AUTH_TOKEN` alone, with a gateway-issued key in `ANTHROPIC_API_KEY` or from an `apiKeyHelper`, or your network blocks or intercepts direct requests to `api.anthropic.com`; [use fast mode behind proxies and LLM gateways](/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways) covers which of the two variables matches your configuration |

173| `ANTHROPIC_MODEL` or [`ANTHROPIC_DEFAULT_HAIKU_MODEL`](/en/model-config) | Set which model name Claude Code requests for the main session and for background traffic | Your gateway routes model names that don't match Claude Code's defaults, or you route [background functionality](/en/costs#background-token-usage) to a different model. Route both the override names and the built-in model IDs Claude Code requests when no override is set, since some background sub-calls request a built-in ID regardless of the override; [model configuration](/en/model-config) covers which model each part of a session uses |174| `ANTHROPIC_MODEL` or [`ANTHROPIC_DEFAULT_HAIKU_MODEL`](/en/model-config) | Set which model name Claude Code requests for the main session and for background traffic | Your gateway routes model names that don't match Claude Code's defaults, or you route [background functionality](/en/costs#background-token-usage) to a different model. Route both the override names and the built-in model IDs Claude Code requests when no override is set, since some background sub-calls request a built-in ID regardless of the override; [model configuration](/en/model-config) covers which model each part of a session uses |

174| `ANTHROPIC_BEDROCK_BASE_URL`, `ANTHROPIC_VERTEX_BASE_URL`, `ANTHROPIC_FOUNDRY_BASE_URL`, or `ANTHROPIC_AWS_BASE_URL` with the [variables for that provider](/en/llm-gateway-connect#route-to-a-cloud-provider-through-a-gateway) | Point Claude Code at the gateway through a provider-specific base URL. Amazon Bedrock and Google Cloud's Agent Platform also switch to those providers' native request format | Your gateway fronts Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, or the Claude Platform on AWS; see [API formats](/en/llm-gateway-protocol#api-formats) |175| `ANTHROPIC_BEDROCK_BASE_URL`, `ANTHROPIC_VERTEX_BASE_URL`, `ANTHROPIC_FOUNDRY_BASE_URL`, or `ANTHROPIC_AWS_BASE_URL` with the [variables for that provider](/en/llm-gateway-connect#route-to-a-cloud-provider-through-a-gateway) | Point Claude Code at the gateway through a provider-specific base URL. Amazon Bedrock and Google Cloud's Agent Platform also switch to those providers' native request format | Your gateway fronts Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, or the Claude Platform on AWS; see [API formats](/en/llm-gateway-protocol#api-formats) |

175 176 


248* `Failed to authenticate` errors mean the gateway is rejecting requests; its log says which credential failed. A rejection the gateway logs itself names the developer key, while a `401` from `api.anthropic.com` or your provider's endpoint means the provider credential the gateway holds was rejected249* `Failed to authenticate` errors mean the gateway is rejecting requests; its log says which credential failed. A rejection the gateway logs itself names the developer key, while a `401` from `api.anthropic.com` or your provider's endpoint means the provider credential the gateway holds was rejected

249* A one-time approval prompt for the key is expected on first use when the gateway expects keys in the `x-api-key` header, set as `ANTHROPIC_API_KEY`. With `ANTHROPIC_AUTH_TOKEN`, no prompt appears and the variable takes over silently; a previously saved claude.ai login is inactive for that session250* A one-time approval prompt for the key is expected on first use when the gateway expects keys in the `x-api-key` header, set as `ANTHROPIC_API_KEY`. With `ANTHROPIC_AUTH_TOKEN`, no prompt appears and the variable takes over silently; a previously saved claude.ai login is inactive for that session

250 251 

252If your organization uses [fast mode](/en/fast-mode), run `/fast` here too: the availability check calls `api.anthropic.com` directly rather than following the gateway base URL, so a gateway-routed session can report fast mode as unavailable or disabled even though inference works. [Use fast mode behind proxies and LLM gateways](/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways) maps each message to the variable that restores it, distributed with [the rest of the configuration](#distribute-the-configuration).

253 

251Finally, check the gateway's logs for the message you sent: the credential identifies the developer, and the [`x-claude-code-session-id` header](/en/llm-gateway-protocol#request-headers) groups requests by session. If features fail with the [troubleshooting symptoms](/en/llm-gateway-connect#troubleshoot-gateway-errors), the gateway is stripping headers or rewriting errors; see the [gateway requirements](#gateway-requirements) above.254Finally, check the gateway's logs for the message you sent: the credential identifies the developer, and the [`x-claude-code-session-id` header](/en/llm-gateway-protocol#request-headers) groups requests by session. If features fail with the [troubleshooting symptoms](/en/llm-gateway-connect#troubleshoot-gateway-errors), the gateway is stripping headers or rewriting errors; see the [gateway requirements](#gateway-requirements) above.

252 255 

253## Maintain the gateway256## Maintain the gateway

mcp.md +1 −1

Details

859 859 

860From v2.1.161, connectors you have never signed in to are collapsed behind a `Show unused connectors` row at the end of the claude.ai section, so an organization-provisioned list doesn't fill the panel. Select the row to expand them. A connector you signed in to before stays visible even when it currently needs re-authentication.860From v2.1.161, connectors you have never signed in to are collapsed behind a `Show unused connectors` row at the end of the claude.ai section, so an organization-provisioned list doesn't fill the panel. Select the row to expand them. A connector you signed in to before stays visible even when it currently needs re-authentication.

861 861 

862Connectors from claude.ai are fetched only when your active [authentication method](/en/authentication#authentication-precedence) is your claude.ai subscription. They aren't loaded when `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, `apiKeyHelper`, or a third-party provider such as Amazon Bedrock or Google Cloud's Agent Platform is active, even if you previously ran `/login`.862Connectors from claude.ai are fetched only when your active [authentication method](/en/authentication#authentication-precedence) is a claude.ai subscription login. They aren't loaded when `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, `apiKeyHelper`, or a third-party provider such as Amazon Bedrock or Google Cloud's Agent Platform is active, even if you previously ran `/login`. They also aren't loaded when `CLAUDE_CODE_OAUTH_TOKEN` holds a token from [`claude setup-token`](/en/authentication#generate-a-long-lived-token), which can only make model requests.

863 863 

864If `/mcp` doesn't list a connector you added, run `/status` to confirm which authentication method is active, unset that environment variable or remove the `apiKeyHelper` setting, then run `/login` to select your claude.ai account.864If `/mcp` doesn't list a connector you added, run `/status` to confirm which authentication method is active, unset that environment variable or remove the `apiKeyHelper` setting, then run `/login` to select your claude.ai account.

865 865 

memory.md +2 −0

Details

383 383 

384Topic files like `debugging.md` or `patterns.md` are not loaded at startup. Claude reads them on demand using its standard file tools when it needs the information.384Topic files like `debugging.md` or `patterns.md` are not loaded at startup. Claude reads them on demand using its standard file tools when it needs the information.

385 385 

386The main conversation's auto memory isn't loaded into [subagents](/en/sub-agents#what-loads-at-startup); the exception is a [fork](/en/sub-agents#fork-the-current-conversation), which inherits the parent conversation and system prompt. A subagent's own auto memory, enabled with the subagent `memory` field, is a separate directory.

387 

386Claude reads and writes memory files during your session. When you see "Writing memory" or "Recalled memory" in the Claude Code interface, Claude is actively updating or reading from `~/.claude/projects/<project>/memory/`.388Claude reads and writes memory files during your session. When you see "Writing memory" or "Recalled memory" in the Claude Code interface, Claude is actively updating or reading from `~/.claude/projects/<project>/memory/`.

387 389 

388### Audit and edit your memory390### Audit and edit your memory

mobile.md +84 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Claude Code on mobile

6 

7> Start, monitor, and steer Claude Code tasks from your phone with the Claude app for iOS and Android.

8 

9The Claude app for [iOS](https://apps.apple.com/us/app/claude-by-anthropic/id6473753684) and [Android](https://play.google.com/store/apps/details?id=com.anthropic.claude) is a client for Claude Code sessions rather than a place where code runs. From your phone you reach [cloud sessions](#start-and-monitor-cloud-sessions) on Anthropic-managed infrastructure, a session running on your own machine through [Remote Control](#continue-a-local-session-with-remote-control), or the Desktop app through [Dispatch](/en/desktop#sessions-from-dispatch).

10 

11<Note>

12 Claude Code doesn't have a separate mobile app: cloud sessions and Remote Control both live in the **Code** tab in the Claude app, and Dispatch is a task you message in the app.

13</Note>

14 

15## Get the app

16 

17<Steps>

18 <Step title="Download the Claude app">

19 Install the Claude app for [iOS](https://apps.apple.com/us/app/claude-by-anthropic/id6473753684) or [Android](https://play.google.com/store/apps/details?id=com.anthropic.claude). On an iPad, install the same iOS app.

20 

21 <Tip>

22 Run `/mobile` in a Claude Code session to display a download QR code you can scan. `/ios` and `/android` do the same thing.

23 </Tip>

24 </Step>

25 

26 <Step title="Sign in">

27 Sign in with the same claude.ai account and organization you use for Claude Code. Cloud sessions and Remote Control require a claude.ai account, so they aren't reachable with an Anthropic Console API key or from a third-party provider such as Amazon Bedrock.

28 </Step>

29 

30 <Step title="Open the Code tab">

31 Tap **Code** in the app's navigation to reach your sessions, or open [claude.ai/code/new](https://claude.ai/code/new) on your phone to start a new Code session in the app. If you don't see the Code tab, your plan or organization may not include these features; see [availability by subscription plan](/en/feature-availability#availability-by-subscription-plan).

32 </Step>

33</Steps>

34 

35## Work from your phone

36 

37From the app you can start cloud sessions, drive a Claude Code session running on your computer, or message Dispatch a task. The app is the same for all three; they differ in where the work happens.

38 

39| Feature | What you connect to | When to use |

40| :--------------------------------------------------- | :-------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------- |

41| [Claude Code on the web](/en/claude-code-on-the-web) | A cloud session on Anthropic-managed infrastructure | Your repository is on GitHub and the task should keep running after you put your phone away. See the [web quickstart](/en/web-quickstart) to set up. |

42| [Remote Control](/en/remote-control) | A Claude Code session running on your computer | The work needs your local filesystem, tools, or MCP servers. |

43| [Dispatch](/en/desktop#sessions-from-dispatch) | The Desktop app on your computer | You want to message a task and let Dispatch decide how to run it. Requires a Pro or Max plan. |

44 

45If your computer will be off, use cloud sessions: they run on Anthropic's infrastructure and continue with your laptop closed. Remote Control and Dispatch drive your own machine, so it needs to stay on with Claude Code or the Desktop app running. If your machine sleeps during a Remote Control session, the session reconnects when it comes back online.

46 

47For a fuller comparison that also covers Channels, Slack, and scheduled tasks, see [work when you are away from your terminal](/en/platforms#work-when-you-are-away-from-your-terminal).

48 

49Cloud sessions and Remote Control run from the **Code** tab and are covered below. For Dispatch, which you message as a task in the app, see [sessions from Dispatch](/en/desktop#sessions-from-dispatch).

50 

51### Start and monitor cloud sessions

52 

53Claude Code on the web runs tasks on Anthropic-managed cloud infrastructure, so a session continues after you put your phone away. From the Code tab, select a repository and branch, describe the task, and submit it. Sessions persist across devices: a task you start on your laptop is ready to review from your phone, and one you start from your phone is waiting when you're back at your desk.

54 

55Open a session in the app to check progress, answer Claude's questions, or steer it in a new direction. You can also tell Claude to [watch a pull request](/en/claude-code-on-the-web#auto-fix-pull-requests) and fix CI failures or review comments as they arrive. To connect GitHub and create your first environment, follow the [web quickstart](/en/web-quickstart), and see [Claude Code on the web](/en/claude-code-on-the-web) for everything cloud sessions can do.

56 

57### Continue a local session with Remote Control

58 

59Remote Control connects the Claude app to a Claude Code session running on your machine, so code execution and filesystem access stay local while you drive the session from your phone. Start the session on your computer with `claude remote-control`, or run `/remote-control` in a session that's already open. Then scan the session QR code the terminal can display, or open the Claude app, tap **Code**, and pick the session from the list. See [connect from another device](/en/remote-control#connect-from-another-device) for each option.

60 

61Attachments you add in the Claude app reach the local session too: Claude Code downloads the image or file to your machine and passes it to Claude as an `@` file reference. For requirements, invocation modes, and troubleshooting, see the [Remote Control overview](/en/remote-control).

62 

63### Get push notifications

64 

65When Remote Control is active, Claude can send push notifications to your phone, typically when a long-running task finishes or when it needs a decision from you. You can also ask for one in your prompt, such as `notify me when the tests finish`. See [mobile push notifications](/en/remote-control#mobile-push-notifications) for the two `/config` toggles and delivery troubleshooting.

66 

67Dispatch sends its own notification when a Code session it spawned finishes or needs your approval, described in [sessions from Dispatch](/en/desktop#sessions-from-dispatch).

68 

69## Limitations

70 

71The mobile client covers most of what a session needs, with a few limitations:

72 

73* **Local-only commands**: commands that only run in the terminal interface, such as `/plugin` and `/resume`, don't work from the app. The [Remote Control limitations](/en/remote-control#limitations) list the commands that do work from mobile and how their behavior differs.

74* **Permission modes**: cloud sessions offer Accept edits, Plan, and Auto in the mode dropdown, and Remote Control sessions offer Manual, Accept edits, and Plan. You can't select Bypass permissions from the app in either case, and you can't select Auto for a Remote Control session. See [switch permission modes](/en/permission-modes#switch-permission-modes).

75* **Dispatch plans**: Dispatch requires a Pro or Max plan and isn't available on Team or Enterprise.

76 

77## Related resources

78 

79* [Platforms and integrations](/en/platforms): compare every surface Claude Code runs on

80* [Claude Code on the web](/en/claude-code-on-the-web): how cloud sessions run, network access, and moving work to and from your terminal

81* [Remote Control](/en/remote-control): continue a local session from any device

82* [Sessions from Dispatch](/en/desktop#sessions-from-dispatch): how Dispatch tasks become Code sessions in the Desktop app

83* [Channels](/en/channels): ask Claude something from your phone via Telegram, Discord, or iMessage while the work runs on your machine

84* [Claude Code in Slack](/en/slack): delegate coding tasks from your Slack workspace by mentioning `@Claude`

model-config.md +3 −3

Details

100 100 

101Prices in the `/model` picker appear when Claude Code talks to the Anthropic API, directly or through an [LLM gateway](/en/llm-gateway) that proxies it, and the price on a row is the price of the model that row selects. On [third-party providers](/en/third-party-integrations) such as Amazon Bedrock and on the [Claude apps gateway](/en/claude-apps-gateway), your provider or gateway determines what you pay, so picker rows show no price. The price is a display label only; it doesn't affect which model a row selects or what your provider bills. Before v2.1.206, [Claude Platform on AWS](/en/claude-platform-on-aws) and gateway sessions showed Anthropic list prices, and a row could show the price of a different model than the one it selected.101Prices in the `/model` picker appear when Claude Code talks to the Anthropic API, directly or through an [LLM gateway](/en/llm-gateway) that proxies it, and the price on a row is the price of the model that row selects. On [third-party providers](/en/third-party-integrations) such as Amazon Bedrock and on the [Claude apps gateway](/en/claude-apps-gateway), your provider or gateway determines what you pay, so picker rows show no price. The price is a display label only; it doesn't affect which model a row selects or what your provider bills. Before v2.1.206, [Claude Platform on AWS](/en/claude-platform-on-aws) and gateway sessions showed Anthropic list prices, and a row could show the price of a different model than the one it selected.

102 102 

103Resumed sessions started with `claude --resume`, `--continue`, or the `/resume` picker keep the model they were using when the transcript was saved, regardless of the current `model` setting. If the restored model has been retired or is excluded by [`availableModels`](#restrict-model-selection), the session falls through to the normal precedence order. This prevents another session's `/model` choice from changing the model on resume.103Resumed sessions started with `claude --resume`, `--continue`, or the `/resume` picker keep the model they were using when the transcript was saved, regardless of the current `model` setting. If the restored model has been retired or is excluded by [`availableModels`](#restrict-model-selection), the session falls through to the normal precedence order. This prevents another session's `/model` choice from changing the model on resume. On providers that use provider-specific deployment IDs rather than Anthropic model IDs, such as Amazon Bedrock, Google Cloud's Agent Platform, and Microsoft Foundry, the transcript model isn't restored at all and the session resolves its model through the normal precedence order.

104 104 

105A model you pick for the new launch with `--model` or `ANTHROPIC_MODEL` still takes precedence over the restored model. {/* min-version: 2.1.195 */}As of v2.1.195, so does an [`ANTHROPIC_DEFAULT_OPUS_MODEL`](#environment-variables) family variable.105A model you pick for the new launch with `--model` or `ANTHROPIC_MODEL` still takes precedence over the restored model. {/* min-version: 2.1.195 */}As of v2.1.195, so does an [`ANTHROPIC_DEFAULT_OPUS_MODEL`](#environment-variables) family variable.

106 106 


497 497 

498The `effortLevel` key in [managed settings](/en/settings#settings-precedence) is a starting default, not enforcement: users can change it for a session with `/effort` or `--effort`, and the managed value re-asserts as the default in new sessions.498The `effortLevel` key in [managed settings](/en/settings#settings-precedence) is a starting default, not enforcement: users can change it for a session with `/effort` or `--effort`, and the managed value re-asserts as the default in new sessions.

499 499 

500The effort slider appears in `/model` when a supported model is selected. The current effort level is also displayed next to the logo and spinner, for example "with low effort", so you can confirm which setting is active without opening `/model`.500The effort slider appears in `/model` when a supported model is selected. The current effort level is also shown in the session header next to the model name, for example "with low effort", so you can confirm which setting is active without opening `/model`. The footer also briefly shows the effort level at startup and when it changes.

501 501 

502#### Adaptive reasoning and fixed thinking budgets502#### Adaptive reasoning and fixed thinking budgets

503 503 


541 541 

542You can also use the `[1m]` suffix with model aliases or full model names:542You can also use the `[1m]` suffix with model aliases or full model names:

543 543 

544```bash theme={null}544```text theme={null}

545# Use the opus[1m] or sonnet[1m] alias545# Use the opus[1m] or sonnet[1m] alias

546/model opus[1m]546/model opus[1m]

547/model sonnet[1m]547/model sonnet[1m]

Details

143 143 

144When using [Amazon Bedrock](/en/amazon-bedrock), [Google Cloud's Agent Platform](/en/google-vertex-ai), [Microsoft Foundry](/en/microsoft-foundry), or a signed-in [Claude apps gateway](/en/claude-apps-gateway) session, model traffic and authentication go to your provider or gateway instead of `api.anthropic.com`, `claude.ai`, or `platform.claude.com`. The WebFetch tool still calls `api.anthropic.com` for its [domain safety check](/en/data-usage#webfetch-domain-safety-check) unless you set `skipWebFetchPreflight: true` in [settings](/en/settings).144When using [Amazon Bedrock](/en/amazon-bedrock), [Google Cloud's Agent Platform](/en/google-vertex-ai), [Microsoft Foundry](/en/microsoft-foundry), or a signed-in [Claude apps gateway](/en/claude-apps-gateway) session, model traffic and authentication go to your provider or gateway instead of `api.anthropic.com`, `claude.ai`, or `platform.claude.com`. The WebFetch tool still calls `api.anthropic.com` for its [domain safety check](/en/data-usage#webfetch-domain-safety-check) unless you set `skipWebFetchPreflight: true` in [settings](/en/settings).

145 145 

146When routing through an [LLM gateway](/en/llm-gateway) with [`ANTHROPIC_BASE_URL`](/en/llm-gateway-connect#set-the-base-url-and-credential), the [fast mode](/en/fast-mode) availability check still calls `api.anthropic.com` rather than the gateway base URL. The check does honor a configured HTTP proxy, so where a network block is the cause, an allowlist entry for `api.anthropic.com` in the proxy is the fix. A network block fails the check only where the host is unreachable even through the proxy, and fast mode then reports a connectivity error. The same connectivity error appears when the check presents a gateway-issued credential that Anthropic rejects; allowlisting doesn't help there, since nothing is blocked. See [use fast mode behind proxies and LLM gateways](/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways) for the variables that restore it.

147 

146[Claude Code on the web](/en/claude-code-on-the-web) and [Code Review](/en/code-review) connect to your repositories from Anthropic-managed infrastructure. If your GitHub Enterprise Cloud organization restricts access by IP address, enable [IP allow list inheritance for installed GitHub Apps](https://docs.github.com/en/enterprise-cloud@latest/organizations/keeping-your-organization-secure/managing-security-settings-for-your-organization/managing-allowed-ip-addresses-for-your-organization#allowing-access-by-github-apps). The Claude GitHub App registers its IP ranges, so enabling this setting allows access without manual configuration. To [add the ranges to your allow list manually](https://docs.github.com/en/enterprise-cloud@latest/organizations/keeping-your-organization-secure/managing-security-settings-for-your-organization/managing-allowed-ip-addresses-for-your-organization#adding-an-allowed-ip-address) instead, or to configure other firewalls, see the [Anthropic API IP addresses](https://platform.claude.com/docs/en/api/ip-addresses).148[Claude Code on the web](/en/claude-code-on-the-web) and [Code Review](/en/code-review) connect to your repositories from Anthropic-managed infrastructure. If your GitHub Enterprise Cloud organization restricts access by IP address, enable [IP allow list inheritance for installed GitHub Apps](https://docs.github.com/en/enterprise-cloud@latest/organizations/keeping-your-organization-secure/managing-security-settings-for-your-organization/managing-allowed-ip-addresses-for-your-organization#allowing-access-by-github-apps). The Claude GitHub App registers its IP ranges, so enabling this setting allows access without manual configuration. To [add the ranges to your allow list manually](https://docs.github.com/en/enterprise-cloud@latest/organizations/keeping-your-organization-secure/managing-security-settings-for-your-organization/managing-allowed-ip-addresses-for-your-organization#adding-an-allowed-ip-address) instead, or to configure other firewalls, see the [Anthropic API IP addresses](https://platform.claude.com/docs/en/api/ip-addresses).

147 149 

148For self-hosted [GitHub Enterprise Server](/en/github-enterprise-server) instances behind a firewall, allowlist the same [Anthropic API IP addresses](https://platform.claude.com/docs/en/api/ip-addresses) so Anthropic infrastructure can reach your GHES host to clone repositories and post review comments.150For self-hosted [GitHub Enterprise Server](/en/github-enterprise-server) instances behind a firewall, allowlist the same [Anthropic API IP addresses](https://platform.claude.com/docs/en/api/ip-addresses) so Anthropic infrastructure can reach your GHES host to clone repositories and post review comments.

Details

101* All output styles trigger reminders for Claude to adhere to the output style instructions during the conversation.101* All output styles trigger reminders for Claude to adhere to the output style instructions during the conversation.

102* Custom output styles leave out Claude Code's built-in software engineering instructions, such as how to scope changes, write comments, and verify work, unless `keep-coding-instructions` is set to `true`.102* Custom output styles leave out Claude Code's built-in software engineering instructions, such as how to scope changes, write comments, and verify work, unless `keep-coding-instructions` is set to `true`.

103 103 

104Output styles apply to the main conversation only: a [subagent runs its own system prompt](/en/sub-agents#what-loads-at-startup), so styles don't change how subagents respond. A [fork](/en/sub-agents#fork-the-current-conversation) is the exception, because it inherits the parent's full system prompt.

105 

104Token usage depends on the style. Adding instructions to the system prompt increases input tokens, though prompt caching reduces this cost after the first request in a session. The built-in Explanatory and Learning styles produce longer responses than Default by design, which increases output tokens. For custom styles, output token usage depends on what your instructions tell Claude to produce.106Token usage depends on the style. Adding instructions to the system prompt increases input tokens, though prompt caching reduces this cost after the first request in a session. The built-in Explanatory and Learning styles produce longer responses than Default by design, which increases output tokens. For custom styles, output token usage depends on what your instructions tell Claude to produce.

105 107 

106## Comparisons to related features108## Comparisons to related features

overview.md +4 −4

Details

114 </Tab>114 </Tab>

115 115 

116 <Tab title="Web">116 <Tab title="Web">

117 Run Claude Code in your browser with no local setup. Kick off long-running tasks and check back when they're done, work on repos you don't have locally, or run multiple tasks in parallel. Available on desktop browsers and the Claude iOS app.117 Run Claude Code in your browser with no local setup. Kick off long-running tasks and check back when they're done, work on repos you don't have locally, or run multiple tasks in parallel. Available on desktop browsers and [the Claude app for iOS and Android](/en/mobile).

118 118 

119 Start coding at [claude.ai/code](https://claude.ai/code).119 Start coding at [claude.ai/code](https://claude.ai/code).

120 120 


207 207 

208 * Step away from your desk and keep working from your phone or any browser with [Remote Control](/en/remote-control)208 * Step away from your desk and keep working from your phone or any browser with [Remote Control](/en/remote-control)

209 * Message [Dispatch](/en/desktop#sessions-from-dispatch) a task from your phone and open the Desktop session it creates209 * Message [Dispatch](/en/desktop#sessions-from-dispatch) a task from your phone and open the Desktop session it creates

210 * Kick off a long-running task on the [web](/en/claude-code-on-the-web) or [iOS app](https://apps.apple.com/app/claude-by-anthropic/id6473753684), then pull it into your terminal with `claude --teleport`. Teleport requires a claude.ai subscription.210 * Kick off a long-running task on the [web](/en/claude-code-on-the-web) or the [Claude mobile app](/en/mobile), then pull it into your terminal with `claude --teleport`. Teleport requires a claude.ai subscription.

211 * Hand off a terminal session to the [Desktop app](/en/desktop) with `/desktop` for visual diff review211 * Hand off a terminal session to the [Desktop app](/en/desktop) with `/desktop` for visual diff review

212 * Route tasks from team chat: mention `@Claude` in [Slack](/en/slack) with a bug report and get a pull request back212 * Route tasks from team chat: mention `@Claude` in [Slack](/en/slack) with a bug report and get a pull request back

213 </Accordion>213 </Accordion>


220Beyond the [Terminal](/en/quickstart), [VS Code](/en/vs-code), [JetBrains](/en/jetbrains), [Desktop](/en/desktop), and [Web](/en/claude-code-on-the-web) surfaces above, Claude Code integrates with CI/CD, chat, and browser workflows:220Beyond the [Terminal](/en/quickstart), [VS Code](/en/vs-code), [JetBrains](/en/jetbrains), [Desktop](/en/desktop), and [Web](/en/claude-code-on-the-web) surfaces above, Claude Code integrates with CI/CD, chat, and browser workflows:

221 221 

222| I want to... | Best option |222| I want to... | Best option |

223| ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |223| ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |

224| Continue a local session from my phone or another device | [Remote Control](/en/remote-control) |224| Continue a local session from my phone or another device | [Remote Control](/en/remote-control) |

225| Push events from Telegram, Discord, iMessage, or my own webhooks into a session | [Channels](/en/channels) |225| Push events from Telegram, Discord, iMessage, or my own webhooks into a session | [Channels](/en/channels) |

226| Start a task locally, continue on mobile | [Web](/en/claude-code-on-the-web) or [Claude iOS app](https://apps.apple.com/app/claude-by-anthropic/id6473753684) |226| Start a task locally, continue on mobile | [`claude --cloud`](/en/claude-code-on-the-web#from-terminal-to-web), then the [Claude mobile app](/en/mobile) |

227| Run Claude on a recurring schedule | [Routines](/en/routines) or [Desktop scheduled tasks](/en/desktop-scheduled-tasks) |227| Run Claude on a recurring schedule | [Routines](/en/routines) or [Desktop scheduled tasks](/en/desktop-scheduled-tasks) |

228| Automate PR reviews and issue triage | [GitHub Actions](/en/github-actions) or [GitLab CI/CD](/en/gitlab-ci-cd) |228| Automate PR reviews and issue triage | [GitHub Actions](/en/github-actions) or [GitLab CI/CD](/en/gitlab-ci-cd) |

229| Get automatic code review on every PR | [GitHub Code Review](/en/code-review) |229| Get automatic code review on every PR | [GitHub Code Review](/en/code-review) |

Details

33 33 

34<Tabs>34<Tabs>

35 <Tab title="CLI">35 <Tab title="CLI">

36 **During a session**: press `Shift+Tab` to cycle `default` → `acceptEdits` → `plan`. The current mode appears in the status bar. {/* min-version: 2.1.203 */}Manual mode, `default` in that cycle, shows a gray `⏸ manual mode on` badge. Before v2.1.203, the status bar showed no badge in Manual mode.36 **During a session**: press `Shift+Tab` to cycle `default` → `acceptEdits` → `plan`. The status bar shows the active mode as `⏸ plan mode on`, `⏵⏵ accept edits on`, `⏵⏵ auto mode on`, `⏵⏵ don't ask on`, or `⏵⏵ bypass permissions on`. {/* min-version: 2.1.203 */}Manual mode, `default` in that cycle, shows a gray `⏸ manual mode on` badge. Before v2.1.203, the status bar showed no badge in Manual mode.

37 37 

38 Not every mode is in the default cycle:38 Not every mode is in the default cycle:

39 39 

40 * `auto`: appears when your account meets the [auto mode requirements](#eliminate-prompts-with-auto-mode); cycling to it switches modes without a confirmation prompt40 * `auto`: appears when your account meets the [auto mode requirements](#eliminate-prompts-with-auto-mode); cycling to it switches modes without a confirmation prompt

41 * `bypassPermissions`: appears after you start with `--permission-mode bypassPermissions`, `--dangerously-skip-permissions`, or `--allow-dangerously-skip-permissions`; the `--allow-` variant adds the mode to the cycle without activating it41 * `bypassPermissions`: appears after you start with `--permission-mode bypassPermissions`, `--dangerously-skip-permissions`, `--allow-dangerously-skip-permissions`, or `permissions.defaultMode: "bypassPermissions"` in [settings](/en/settings#permission-settings); the `--allow-` variant adds the mode to the cycle without activating it

42 * `dontAsk`: never appears in the cycle; set it with `--permission-mode dontAsk`42 * `dontAsk`: never appears in the cycle; set it with `--permission-mode dontAsk`

43 43 

44 Enabled optional modes slot in after `plan`, with `bypassPermissions` first and `auto` last. If you have both enabled, you will cycle through `bypassPermissions` on the way to `auto`.44 Enabled optional modes slot in after `plan`, with `bypassPermissions` first and `auto` last. If you have both enabled, you will cycle through `bypassPermissions` on the way to `auto`.


49 claude --permission-mode plan49 claude --permission-mode plan

50 ```50 ```

51 51 

52 **As a default**: set `defaultMode` in [settings](/en/settings#settings-files).52 **As a default**: set `defaultMode` in a [settings file](/en/settings#settings-files) such as `~/.claude/settings.json`:

53 53 

54 ```json theme={null}54 ```json theme={null}

55 {55 {


119 * **Cloud sessions** on [Claude Code on the web](/en/claude-code-on-the-web): Accept edits, Plan, and Auto. Accept edits corresponds to `default` mode: the cloud environment pre-approves file edits regardless of mode, so the dropdown shows Accept edits instead of Manual. Cloud sessions still honor `defaultMode: "acceptEdits"` from settings. Auto mode appears only when your organization allows it and the selected model supports it. Bypass permissions isn't available.119 * **Cloud sessions** on [Claude Code on the web](/en/claude-code-on-the-web): Accept edits, Plan, and Auto. Accept edits corresponds to `default` mode: the cloud environment pre-approves file edits regardless of mode, so the dropdown shows Accept edits instead of Manual. Cloud sessions still honor `defaultMode: "acceptEdits"` from settings. Auto mode appears only when your organization allows it and the selected model supports it. Bypass permissions isn't available.

120 * **[Remote Control](/en/remote-control) sessions** on your local machine: Manual, Accept edits, and Plan. You can't select Auto or Bypass permissions from the app. {/* min-version: 2.1.202 */}The dropdown shows the mode the local session is in, including a mode set from the terminal, and updates when the mode changes in the app or in the terminal. The one exception is Bypass permissions: the session never reports that mode to claude.ai, so switching into it from the terminal doesn't change what the dropdown shows. Before v2.1.202, sessions connected with `/remote-control` or `claude --remote-control` didn't report their mode at all, so claude.ai and the mobile app could show a mode the session wasn't in. The mismatch affected only the label: Claude Code generated permission prompts from the session's actual mode, and they still appeared in the app for approval.120 * **[Remote Control](/en/remote-control) sessions** on your local machine: Manual, Accept edits, and Plan. You can't select Auto or Bypass permissions from the app. {/* min-version: 2.1.202 */}The dropdown shows the mode the local session is in, including a mode set from the terminal, and updates when the mode changes in the app or in the terminal. The one exception is Bypass permissions: the session never reports that mode to claude.ai, so switching into it from the terminal doesn't change what the dropdown shows. Before v2.1.202, sessions connected with `/remote-control` or `claude --remote-control` didn't report their mode at all, so claude.ai and the mobile app could show a mode the session wasn't in. The mismatch affected only the label: Claude Code generated permission prompts from the session's actual mode, and they still appeared in the app for approval.

121 121 

122 For Remote Control, you can also set the starting mode when launching the host:122 For Remote Control, the host must be signed in with your claude.ai account; API keys are not supported. You can also set the starting mode when launching the host:

123 123 

124 ```bash theme={null}124 ```bash theme={null}

125 claude remote-control --permission-mode acceptEdits125 claude remote-control --permission-mode acceptEdits


157 157 

158### Review and approve a plan158### Review and approve a plan

159 159 

160When the plan is ready, Claude presents it and asks how to proceed. From that prompt you can:160When the plan is ready, Claude presents it and asks how to proceed. From that prompt you can choose:

161 161 

162* Approve and start in auto mode162* **Yes, and use auto mode**: approve and start in [auto mode](#eliminate-prompts-with-auto-mode). When auto mode is unavailable, this option reads **Yes, auto-accept edits**. Sessions started with bypass permissions enabled show **Yes, and bypass permissions** instead.

163* Approve and accept edits163* **Yes, manually approve edits**: approve and review each edit individually.

164* Approve and review each edit manually164* **No, refine with Ultraplan on Claude Code on the web**: send the plan to [Ultraplan](/en/ultraplan) for browser-based review.

165* Keep planning with feedback165* **No, keep planning**: stay in plan mode and tell Claude what to change.

166* Refine with [Ultraplan](/en/ultraplan) for browser-based review

167 166 

168Approving a plan exits plan mode and switches the session to the permission mode each approve option describes, so Claude starts editing. To plan again, cycle back to plan mode with `Shift+Tab`, or prefix your next prompt with `/plan`.167Approving a plan exits plan mode and switches the session to the permission mode each approve option describes, so Claude starts editing. To plan again, cycle back to plan mode with `Shift+Tab`, or prefix your next prompt with `/plan`.

169 168 

170Press `Ctrl+G` to open the proposed plan in your default text editor and edit it directly before Claude proceeds. When [`showClearContextOnPlanAccept`](/en/settings#available-settings) is enabled, each approve option also offers to clear the planning context first.169Press `Ctrl+G` to open the proposed plan in your default text editor and edit it directly before Claude proceeds. When [`showClearContextOnPlanAccept`](/en/settings#available-settings) is enabled, the list gains a first option that approves the plan and clears the planning context.

171 170 

172Accepting a plan also names the session from the plan content automatically, unless you've already set a name with `--name` or `/rename`.171Accepting a plan also names the session from the plan content automatically, unless you've already set a name with `--name` or `/rename`.

173 172 


201 200 

202* **Plan**: All plans.201* **Plan**: All plans.

203* **Owner**: on Team and Enterprise, an Owner must enable it in [Claude Code admin settings](https://claude.ai/admin-settings/claude-code) before users can turn it on. Administrators can also turn auto mode off by setting `permissions.disableAutoMode` to `"disable"` in [managed settings](/en/permissions#managed-settings). For the desktop app's Code tab, `disableAutoMode` is the organization-level control, and the admin settings toggle doesn't apply.202* **Owner**: on Team and Enterprise, an Owner must enable it in [Claude Code admin settings](https://claude.ai/admin-settings/claude-code) before users can turn it on. Administrators can also turn auto mode off by setting `permissions.disableAutoMode` to `"disable"` in [managed settings](/en/permissions#managed-settings). For the desktop app's Code tab, `disableAutoMode` is the organization-level control, and the admin settings toggle doesn't apply.

204* **Model**: on the Anthropic API, Claude Opus 4.6 or later, Sonnet 4.6 or later, or [Fable 5](/en/model-config#work-with-fable-5). On Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, and signed-in [Claude apps gateway](/en/claude-apps-gateway) sessions, only Claude Sonnet 5, Opus 4.7, Opus 4.8, and Fable 5. Older models, including Sonnet 4.5, Opus 4.5, Haiku, and claude-3 models, are not supported on any provider.203* **Model**: on the Anthropic API and [Claude Platform on AWS](/en/claude-platform-on-aws), Claude Opus 4.6 or later, Sonnet 4.6 or later, or [Fable 5](/en/model-config#work-with-fable-5). On Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, and signed-in [Claude apps gateway](/en/claude-apps-gateway) sessions, only Claude Sonnet 5, Opus 4.7, Opus 4.8, and Fable 5. Older models, including Sonnet 4.5, Opus 4.5, Haiku, and claude-3 models, are not supported on any provider.

205* **Provider**: available by default on the Anthropic API, Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, and signed-in Claude apps gateway sessions. {/* min-version: 2.1.207 */}In v2.1.158 through v2.1.206, auto mode was off on all of these providers except the Anthropic API until you set `CLAUDE_CODE_ENABLE_AUTO_MODE=1`; v2.1.207 removed the requirement.204* **Provider**: available by default on the Anthropic API, Claude Platform on AWS, Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, and signed-in Claude apps gateway sessions. {/* min-version: 2.1.207 */}In v2.1.158 through v2.1.206, auto mode was off on all of these providers except the Anthropic API and Claude Platform on AWS until you set `CLAUDE_CODE_ENABLE_AUTO_MODE=1`; v2.1.207 removed the requirement.

206 205 

207If Claude Code reports auto mode as unavailable, one of these requirements is unmet; this is not a transient outage. A separate message that names a model and says auto mode "cannot determine the safety" of an action is a transient classifier outage; see the [error reference](/en/errors#auto-mode-cannot-determine-the-safety-of-an-action).206If Claude Code reports auto mode as unavailable, one of these requirements is unmet; this is not a transient outage. A separate message that names a model and says auto mode "cannot determine the safety" of an action is a transient classifier outage; see the [error reference](/en/errors#auto-mode-cannot-determine-the-safety-of-an-action).

208 207 


307* In [non-interactive mode](/en/headless) and Agent SDK sessions there is no turn boundary, so a deny is reused for the rest of the run306* In [non-interactive mode](/en/headless) and Agent SDK sessions there is no turn boundary, so a deny is reused for the rest of the run

308* Changing your permission mode or rules drops all cached verdicts307* Changing your permission mode or rules drops all cached verdicts

309 308 

310Run `claude auto-mode defaults` to see the full rule lists. If routine actions get blocked, an administrator can add trusted repos, buckets, and services via the `autoMode.environment` setting: see [Configure auto mode](/en/auto-mode-config).309Run `claude auto-mode defaults` to print the full rule lists as JSON. If routine actions get blocked, an administrator can add trusted repos, buckets, and services via the `autoMode.environment` setting: see [Configure auto mode](/en/auto-mode-config).

311 310 

312{/* min-version: 2.1.211 */}Pushing to any branch of the repository you're working in and creating a pull request that matches your request run without a prompt, with the two exceptions the lists above cover: the classifier judges a push to a deploy-named branch such as `production` or `gh-pages` on its own terms, and still blocks a push whose content carries risk. To require a human checkpoint before these actions while staying in auto mode, add `permissions.ask` rules: see [Common boundaries](/en/auto-mode-config#common-boundaries).311{/* min-version: 2.1.211 */}Pushing to any branch of the repository you're working in and creating a pull request that matches your request run without a prompt, with the two exceptions the lists above cover: the classifier judges a push to a deploy-named branch such as `production` or `gh-pages` on its own terms, and still blocks a push whose content carries risk. To require a human checkpoint before these actions while staying in auto mode, add `permissions.ask` rules: see [Common boundaries](/en/auto-mode-config#common-boundaries).

313 312 


395 Only use this mode in isolated environments like containers, VMs, or dev containers without internet access, where Claude Code cannot damage your host system.394 Only use this mode in isolated environments like containers, VMs, or dev containers without internet access, where Claude Code cannot damage your host system.

396</Warning>395</Warning>

397 396 

398You cannot enter `bypassPermissions` from a session that was started without one of the enabling flags; restart with one to enable it:397You can't enter `bypassPermissions` from a session that was started without it enabled. Enable it at launch with `permissions.defaultMode: "bypassPermissions"` in [settings](/en/settings#permission-settings) or with an enabling flag:

399 398 

400```bash theme={null}399```bash theme={null}

401claude --permission-mode bypassPermissions400claude --permission-mode bypassPermissions


403 402 

404The `--dangerously-skip-permissions` flag is equivalent.403The `--dangerously-skip-permissions` flag is equivalent.

405 404 

405The first time you start an interactive session with this mode enabled, Claude Code shows a warning dialog asking you to accept responsibility for actions taken without permission checks. Claude Code saves your acceptance to user settings, so the dialog appears only once. If you decline, Claude Code exits. In [non-interactive mode](/en/headless) no dialog is shown, and a [background session](/en/agent-view) started with `--bg` is refused until you've accepted the dialog in an interactive session.

406 

406On Linux and macOS, Claude Code refuses to start in this mode when running as root or under `sudo`:407On Linux and macOS, Claude Code refuses to start in this mode when running as root or under `sudo`:

407 408 

408```text theme={null}409```text theme={null}

permissions.md +1 −1

Details

206 206 

207 * Options before URL: `curl -X GET http://github.com/...`207 * Options before URL: `curl -X GET http://github.com/...`

208 * Different protocol: `curl https://github.com/...`208 * Different protocol: `curl https://github.com/...`

209 * Redirects: `curl -L http://bit.ly/xyz`, which redirects to GitHub209 * Redirects: `curl -L http://short.example.com/xyz`, which redirects to GitHub

210 * Variables: `URL=http://github.com && curl $URL`210 * Variables: `URL=http://github.com && curl $URL`

211 * Extra spaces: `curl http://github.com`211 * Extra spaces: `curl http://github.com`

212 212 

platforms.md +2 −2

Details

19| [VS Code](/en/vs-code) | Working inside VS Code without switching to a terminal | Inline diffs, integrated terminal, file context |19| [VS Code](/en/vs-code) | Working inside VS Code without switching to a terminal | Inline diffs, integrated terminal, file context |

20| [JetBrains](/en/jetbrains) | Working inside IntelliJ, PyCharm, WebStorm, or other JetBrains IDEs | Diff viewer, selection sharing, terminal session |20| [JetBrains](/en/jetbrains) | Working inside IntelliJ, PyCharm, WebStorm, or other JetBrains IDEs | Diff viewer, selection sharing, terminal session |

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](/en/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 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 Google Cloud's Agent Platform, and Desktop supports [gateway providers](/en/llm-gateway-connect#desktop-app); for Amazon Bedrock or Microsoft Foundry, use the CLI or VS Code, or [Claude Desktop on 3P](https://claude.com/docs/third-party/claude-desktop/overview), which runs the Code tab on those providers. 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 Google Cloud's Agent Platform, and Desktop supports [gateway providers](/en/llm-gateway-connect#desktop-app); for Amazon Bedrock or Microsoft Foundry, use the CLI or VS Code, or [Claude Desktop on 3P](https://claude.com/docs/third-party/claude-desktop/overview), which runs the Code tab on those providers. 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 


62* [VS Code](/en/vs-code): the Claude Code extension inside your editor62* [VS Code](/en/vs-code): the Claude Code extension inside your editor

63* [JetBrains](/en/jetbrains): the extension for IntelliJ, PyCharm, and other JetBrains IDEs63* [JetBrains](/en/jetbrains): the extension for IntelliJ, PyCharm, and other JetBrains IDEs

64* [Claude Code on the web](/en/claude-code-on-the-web): cloud sessions that keep running when you disconnect64* [Claude Code on the web](/en/claude-code-on-the-web): cloud sessions that keep running when you disconnect

65* Mobile: the Claude app for [iOS](https://apps.apple.com/us/app/claude-by-anthropic/id6473753684) and [Android](https://play.google.com/store/apps/details?id=com.anthropic.claude) for starting and monitoring tasks while away from your computer65* [Mobile](/en/mobile): the Claude app for [iOS](https://apps.apple.com/us/app/claude-by-anthropic/id6473753684) and [Android](https://play.google.com/store/apps/details?id=com.anthropic.claude) for starting and monitoring tasks while away from your computer

66 66 

67### Integrations67### Integrations

68 68 

quickstart.md +5 −5

Details

29 <Tab title="Native Install (Recommended)">29 <Tab title="Native Install (Recommended)">

30 **macOS, Linux, WSL:**30 **macOS, Linux, WSL:**

31 31 

32 ```bash theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null}32 ```bash theme={null}

33 curl -fsSL https://claude.ai/install.sh | bash33 curl -fsSL https://claude.ai/install.sh | bash

34 ```34 ```

35 35 

36 **Windows PowerShell:**36 **Windows PowerShell:**

37 37 

38 ```powershell theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null}38 ```powershell theme={null}

39 irm https://claude.ai/install.ps1 | iex39 irm https://claude.ai/install.ps1 | iex

40 ```40 ```

41 41 

42 **Windows CMD:**42 **Windows CMD:**

43 43 

44 ```batch theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null}44 ```batch theme={null}

45 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd45 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

46 ```46 ```

47 47 


57 </Tab>57 </Tab>

58 58 

59 <Tab title="Homebrew">59 <Tab title="Homebrew">

60 ```bash theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null}60 ```bash theme={null}

61 brew install --cask claude-code61 brew install --cask claude-code

62 ```62 ```

63 63 


69 </Tab>69 </Tab>

70 70 

71 <Tab title="WinGet">71 <Tab title="WinGet">

72 ```powershell theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null}72 ```powershell theme={null}

73 winget install Anthropic.ClaudeCode73 winget install Anthropic.ClaudeCode

74 ```74 ```

75 75 

Details

273 273 

274### "Remote Control requires a full-scope login token"274### "Remote Control requires a full-scope login token"

275 275 

276You're authenticated with a long-lived token from `claude setup-token` or the `CLAUDE_CODE_OAUTH_TOKEN` environment variable. These tokens are limited to inference-only and cannot establish Remote Control sessions. Run `claude auth login` to authenticate with a full-scope session token instead.276You're authenticated with a long-lived token from `claude setup-token` or the `CLAUDE_CODE_OAUTH_TOKEN` environment variable. These tokens can only make model requests, so they can't establish Remote Control sessions. Run `claude auth login` to authenticate with a full-scope session token instead.

277 277 

278### "Unable to determine your organization for Remote Control eligibility"278### "Unable to determine your organization for Remote Control eligibility"

279 279 

routines.md +1 −1

Details

116 116 

117### Create from the CLI117### Create from the CLI

118 118 

119Run `/schedule` in any session to create a scheduled routine conversationally. You can also pass a description directly, for a recurring routine like `/schedule daily PR review at 9am` or a one-off like `/schedule clean up feature flag in one week`. Claude walks through the same information the web form collects, then saves the routine to your account.119Run `/schedule` in any session to create a scheduled routine conversationally. You can also pass a description directly, for a recurring routine like `/schedule daily PR review at 9am` or a one-off like `/schedule clean up feature flag in one week`. Claude walks through the same information the web form collects, then saves the routine to your account. The command is also available under the alias `/routines`.

120 120 

121A successful start looks like a conversation: Claude asks follow-up questions about the schedule, repositories, and prompt before saving. If Claude instead replies that you need to authenticate or that it can't connect to your remote claude.ai account, no routine was created; see [Troubleshooting](#troubleshooting).121A successful start looks like a conversation: Claude asks follow-up questions about the schedule, repositories, and prompt before saving. If Claude instead replies that you need to authenticate or that it can't connect to your remote claude.ai account, no routine was created; see [Troubleshooting](#troubleshooting).

122 122 

sessions.md +12 −0

Details

24 24 

25Sessions created with [`claude -p`](/en/headless) or the [Agent SDK](/en/agent-sdk/overview) do not appear in the session picker, but you can still resume one by passing its session ID to `claude --resume <session-id>`. Run this from the directory the session was started in: session ID lookup is scoped to the current project directory and its git worktrees, so a session created elsewhere reports `No conversation found with session ID: <session-id>`.25Sessions created with [`claude -p`](/en/headless) or the [Agent SDK](/en/agent-sdk/overview) do not appear in the session picker, but you can still resume one by passing its session ID to `claude --resume <session-id>`. Run this from the directory the session was started in: session ID lookup is scoped to the current project directory and its git worktrees, so a session created elsewhere reports `No conversation found with session ID: <session-id>`.

26 26 

27### What a resumed session restores

28 

29A resumed session restores the conversation along with the state saved in it:

30 

31* Conversation history: the full history, including tool calls and results.

32* Model: the session continues on the model it was using. The model isn't restored when it has been retired or isn't allowed by `availableModels`, when a `--model` flag or `ANTHROPIC_MODEL`-family environment variable picks one at launch, or on providers that use provider-specific deployment IDs, such as [Amazon Bedrock, Google Cloud's Agent Platform, and Microsoft Foundry](/en/third-party-integrations); see [model configuration](/en/model-config#setting-your-model) for the resolution order.

33* Permission mode: the mode the session was in. `plan` and `bypassPermissions` are never restored; [bypassing permissions](/en/permission-modes#skip-all-checks-with-bypasspermissions-mode) must be enabled again at launch, with one of its launch flags or `permissions.defaultMode: "bypassPermissions"` in [settings](/en/settings#permission-settings). `auto` is restored only when your account still meets the [auto mode requirements](/en/permission-modes#eliminate-prompts-with-auto-mode). Pass `--permission-mode` to override the restored mode.

34* Active goal: a [goal](/en/goal#resume-with-an-active-goal) that was still active when the session ended carries over; its turn count, timer, and token-spend baseline reset.

35* Scheduled tasks: [tasks that haven't expired](/en/scheduled-tasks#limitations) are restored. Background Bash and monitor tasks aren't.

36 

37Not every configuration flag from the original launch is restored. If the session depended on `--mcp-config`, `--settings`, `--plugin-dir`, `--fallback-model`, or directories added with `--add-dir`, pass them again when you resume; directories added mid-session with `/add-dir` aren't restored either, though the session picker still uses them to locate the session. The standard settings files, such as `settings.json` and `settings.local.json`, are re-read at launch, so configuration that lives in them doesn't need to be passed again.

38 

27### Where the session picker looks39### Where the session picker looks

28 40 

29Sessions are stored per project directory. By default the session picker shows interactive sessions from the current worktree, plus sessions started elsewhere that added the current directory with `/add-dir`. Use `Ctrl+W` to widen to all worktrees of the repository or `Ctrl+A` to widen to every project on this machine.41Sessions are stored per project directory. By default the session picker shows interactive sessions from the current worktree, plus sessions started elsewhere that added the current directory with `/add-dir`. Use `Ctrl+W` to widen to all worktrees of the repository or `Ctrl+A` to widen to every project on this machine.

settings.md +2 −1

Details

347</Note>347</Note>

348 348 

349| Key | Description | Example |349| Key | Description | Example |

350| :--------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------- |350| :--------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------- |

351| `autoConnectIde` | **Default**: `false`. Automatically connect to a running IDE when Claude Code starts from an external terminal. Appears in `/config` as **Auto-connect to IDE (external terminal)** when running outside a VS Code or JetBrains terminal. The [`CLAUDE_CODE_AUTO_CONNECT_IDE`](/en/env-vars) environment variable overrides this when set | `true` |351| `autoConnectIde` | **Default**: `false`. Automatically connect to a running IDE when Claude Code starts from an external terminal. Appears in `/config` as **Auto-connect to IDE (external terminal)** when running outside a VS Code or JetBrains terminal. The [`CLAUDE_CODE_AUTO_CONNECT_IDE`](/en/env-vars) environment variable overrides this when set | `true` |

352| `autoInstallIdeExtension` | **Default**: `true`. Automatically install the Claude Code IDE extension when running from a VS Code terminal. Appears in `/config` as **Auto-install IDE extension** when running inside a VS Code or JetBrains terminal. You can also set the [`CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL`](/en/env-vars) environment variable to `1` | `false` |352| `autoInstallIdeExtension` | **Default**: `true`. Automatically install the Claude Code IDE extension when running from a VS Code terminal. Appears in `/config` as **Auto-install IDE extension** when running inside a VS Code or JetBrains terminal. You can also set the [`CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL`](/en/env-vars) environment variable to `1` | `false` |

353| `diffTool` | **Default**: `auto`. Where to display file diffs when an IDE is connected: `auto` opens diffs in the IDE's diff viewer, `terminal` keeps them in the terminal. Appears in `/config` as **Diff tool** only when Claude Code is connected to a VS Code or JetBrains IDE | `"terminal"` |

353| `externalEditorContext` | **Default**: `false`. Prepend Claude's previous response as `#`-commented context when you open the external editor with `Ctrl+G`. Appears in `/config` as **Show last response in external editor** | `true` |354| `externalEditorContext` | **Default**: `false`. Prepend Claude's previous response as `#`-commented context when you open the external editor with `Ctrl+G`. Appears in `/config` as **Show last response in external editor** | `true` |

354| `permissionExplainerEnabled` | **Default**: `true`. Show a model-generated [explanation of the command](/en/permissions#permission-system) when you press `Ctrl+E` on a Bash or PowerShell permission prompt. Set to `false` to turn the shortcut off | `false` |355| `permissionExplainerEnabled` | **Default**: `true`. Show a model-generated [explanation of the command](/en/permissions#permission-system) when you press `Ctrl+E` on a Bash or PowerShell permission prompt. Set to `false` to turn the shortcut off | `false` |

355| `teammateDefaultModel` | Default model for [agent team](/en/agent-teams) teammates when the spawn prompt doesn't specify one. Set to a model alias such as `"sonnet"`, or `null` to inherit the lead's current `/model` selection. Appears in `/config` as **Default teammate model** | `"sonnet"` |356| `teammateDefaultModel` | Default model for [agent team](/en/agent-teams) teammates when the spawn prompt doesn't specify one. Set to a model alias such as `"sonnet"`, or `null` to inherit the lead's current `/model` selection. Appears in `/config` as **Default teammate model** | `"sonnet"` |

setup.md +5 −5

Details

41 <Tab title="Native Install (Recommended)">41 <Tab title="Native Install (Recommended)">

42 **macOS, Linux, WSL:**42 **macOS, Linux, WSL:**

43 43 

44 ```bash theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null}44 ```bash theme={null}

45 curl -fsSL https://claude.ai/install.sh | bash45 curl -fsSL https://claude.ai/install.sh | bash

46 ```46 ```

47 47 

48 **Windows PowerShell:**48 **Windows PowerShell:**

49 49 

50 ```powershell theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null}50 ```powershell theme={null}

51 irm https://claude.ai/install.ps1 | iex51 irm https://claude.ai/install.ps1 | iex

52 ```52 ```

53 53 

54 **Windows CMD:**54 **Windows CMD:**

55 55 

56 ```batch theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null}56 ```batch theme={null}

57 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd57 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

58 ```58 ```

59 59 


69 </Tab>69 </Tab>

70 70 

71 <Tab title="Homebrew">71 <Tab title="Homebrew">

72 ```bash theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null}72 ```bash theme={null}

73 brew install --cask claude-code73 brew install --cask claude-code

74 ```74 ```

75 75 


81 </Tab>81 </Tab>

82 82 

83 <Tab title="WinGet">83 <Tab title="WinGet">

84 ```powershell theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null}84 ```powershell theme={null}

85 winget install Anthropic.ClaudeCode85 winget install Anthropic.ClaudeCode

86 ```86 ```

87 87 

skills.md +12 −1

Details

169 CLAUDE.md files from `--add-dir` directories are not loaded by default. To load them, set `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1`. See [Load from additional directories](/en/memory#load-from-additional-directories).169 CLAUDE.md files from `--add-dir` directories are not loaded by default. To load them, set `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1`. See [Load from additional directories](/en/memory#load-from-additional-directories).

170</Note>170</Note>

171 171 

172#### Skills in Cowork and cloud sessions

173 

174[Cowork](https://claude.com/product/cowork) sessions and [cloud sessions](/en/claude-code-on-the-web#the-cloud-environment), including [routines](/en/routines), don't read `~/.claude/skills/` on your machine. Both interactive and scheduled Cowork sessions load the skills enabled for your claude.ai account, synced at session start; manage them from **Customize** in the Desktop app sidebar or from the skills settings on claude.ai. Cloud sessions additionally load project skills committed to the cloned repository's `.claude/skills/`.

175 

176If a skill exists only in `~/.claude/skills/` on your machine, Claude Code reports that the skill was not found when a [routine](/en/routines) invokes it, because each routine run starts as a fresh remote session. To make a personal skill available in these sessions:

177 

178* For Cowork and cloud sessions, enable the skill for your claude.ai account.

179* For cloud sessions, you can instead commit the skill to the repository's `.claude/skills/`, or ship it in a plugin declared in the repository's `.claude/settings.json`. Repo-declared plugins [install at session start](/en/claude-code-on-the-web#what’s-available-in-cloud-sessions); plugins enabled only in your user settings don't transfer.

180 

181[Desktop scheduled tasks](/en/desktop-scheduled-tasks) are different: they run locally on your machine and load skills from the same locations as any other local session.

182 

172## Configure skills183## Configure skills

173 184 

174Skills are configured through YAML frontmatter at the top of `SKILL.md` and the markdown content that follows.185Skills are configured through YAML frontmatter at the top of `SKILL.md` and the markdown content that follows.


828 webbrowser.open(f'file://{out.absolute()}')839 webbrowser.open(f'file://{out.absolute()}')

829```840```

830 841 

831To test, open Claude Code in any project and ask "Visualize this codebase." Claude runs the script, which prints the generated file's path, such as `Generated /path/to/codebase-map.html`, and opens it in your browser.842To test, open Claude Code in any project and ask "Visualize this codebase." Claude runs the script, which prints the generated file's path, such as `Generated /path/to/codebase-map.html`, and opens it in your browser. If you work in a headless environment where no browser opens, the printed path confirms the script succeeded.

832 843 

833This pattern works for any visual output: dependency graphs, test coverage reports, API documentation, or database schema visualizations. The bundled script does the work while Claude handles orchestration.844This pattern works for any visual output: dependency graphs, test coverage reports, API documentation, or database schema visualizations. The bundled script does the work while Claude handles orchestration.

834 845 

statusline.md +2 −2

Details

86 86 

87<Steps>87<Steps>

88 <Step title="Create a script that reads JSON and prints output">88 <Step title="Create a script that reads JSON and prints output">

89 Claude Code sends JSON data to your script via stdin. This script uses [`jq`](https://jqlang.github.io/jq/), a command-line JSON parser you may need to install, to extract the model name, directory, and context percentage, then prints a formatted line.89 Claude Code sends JSON data to your script via stdin. This script uses [`jq`](https://jqlang.org/), a command-line JSON parser you may need to install, to extract the model name, directory, and context percentage, then prints a formatted line.

90 90 

91 Save this to `~/.claude/statusline.sh` (where `~` is your home directory, such as `/Users/username` on macOS or `/home/username` on Linux):91 Save this to `~/.claude/statusline.sh` (where `~` is your home directory, such as `/Users/username` on macOS or `/home/username` on Linux):

92 92 


3322. Make it executable: `chmod +x ~/.claude/statusline.sh`3322. Make it executable: `chmod +x ~/.claude/statusline.sh`

3333. Add the path to your [settings](#manually-configure-a-status-line)3333. Add the path to your [settings](#manually-configure-a-status-line)

334 334 

335The Bash examples use [`jq`](https://jqlang.github.io/jq/) to parse JSON. Python and Node.js have built-in JSON parsing.335The Bash examples use [`jq`](https://jqlang.org/) to parse JSON. Python and Node.js have built-in JSON parsing.

336 336 

337### Context window usage337### Context window usage

338 338 

sub-agents.md +25 −5

Details

223 223 

224**Managed subagents** are deployed by organization administrators. Place markdown files in `.claude/agents/` inside the [managed settings directory](/en/settings#settings-files), using the same frontmatter format as project and user subagents. Managed definitions take precedence over project and user subagents with the same name.224**Managed subagents** are deployed by organization administrators. Place markdown files in `.claude/agents/` inside the [managed settings directory](/en/settings#settings-files), using the same frontmatter format as project and user subagents. Managed definitions take precedence over project and user subagents with the same name.

225 225 

226**Plugin subagents** come from [plugins](/en/plugins) you've installed. They load alongside your custom subagents and appear in the @-mention typeahead under their scoped name. See the [plugin components reference](/en/plugins-reference#agents) for details on creating plugin subagents.226**Plugin subagents** come from [plugins](/en/plugins) you've installed. They load automatically alongside your custom subagents and appear in the @-mention typeahead under their scoped name. See the [plugin components reference](/en/plugins-reference#agents) for details on creating plugin subagents.

227 227 

228<Note>228<Note>

229 For security reasons, plugin subagents don't support the `hooks`, `mcpServers`, or `permissionMode` frontmatter fields. These fields are ignored when loading agents from a plugin. If you need them, copy the agent file into `.claude/agents/` or `~/.claude/agents/`. You can also add rules to [`permissions.allow`](/en/settings#permission-settings) in `settings.json` or `settings.local.json`, but these rules apply to the entire session, not only the plugin subagent.229 For security reasons, plugin subagents don't support the `hooks`, `mcpServers`, or `permissionMode` frontmatter fields. These fields are ignored when loading agents from a plugin. If you need them, copy the agent file into `.claude/agents/` or `~/.claude/agents/`. You can also add rules to [`permissions.allow`](/en/settings#permission-settings) in `settings.json` or `settings.local.json`, but these rules apply to the entire session, not only the plugin subagent.


327* `ScheduleWakeup`327* `ScheduleWakeup`

328* `WaitForMcpServers`328* `WaitForMcpServers`

329 329 

330The `Agent` tool itself is inherited, so a subagent can [spawn nested subagents](#spawn-nested-subagents).

331 

330To restrict tools, use the `tools` field as an allowlist or the `disallowedTools` field as a denylist. This example uses `tools` to allow only Read, Grep, Glob, and Bash. The subagent can't edit files, write files, or use any MCP tools:332To restrict tools, use the `tools` field as an allowlist or the `disallowedTools` field as a denylist. This example uses `tools` to allow only Read, Grep, Glob, and Bash. The subagent can't edit files, write files, or use any MCP tools:

331 333 

332```yaml theme={null}334```yaml theme={null}


696 698 

697Subagents provided by an enabled [plugin](/en/plugins) appear in the typeahead under their scoped name, such as `my-plugin:code-reviewer` or `my-plugin:review:security` when the plugin [organizes agents into subfolders](#choose-the-subagent-scope). Named background subagents currently running in the session also appear in the typeahead, showing their status next to the name.699Subagents provided by an enabled [plugin](/en/plugins) appear in the typeahead under their scoped name, such as `my-plugin:code-reviewer` or `my-plugin:review:security` when the plugin [organizes agents into subfolders](#choose-the-subagent-scope). Named background subagents currently running in the session also appear in the typeahead, showing their status next to the name.

698 700 

699You can also type the mention manually without using the picker: `@agent-<name>` for local subagents, or `@agent-` followed by the scoped name for plugin subagents, for example `@agent-my-plugin:code-reviewer`.701You can also type the mention manually without using the picker: `@agent-<name>` for local subagents, or `@agent-` followed by the scoped name for plugin subagents, for example `@agent-my-plugin:code-reviewer`. While you type this form the typeahead shows file matches rather than agents. The agent mention still resolves when you submit.

700 702 

701**Run the whole session as a subagent.** Pass [`--agent <name>`](/en/cli-reference) to start a session where the main thread itself takes on that subagent's system prompt, tool restrictions, and model:703**Run the whole session as a subagent.** Pass [`--agent <name>`](/en/cli-reference) to start a session where the main thread itself takes on that subagent's system prompt, tool restrictions, and model:

702 704 


752 754 

753To disable all background task functionality, set the `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` environment variable to `1`. See [Environment variables](/en/env-vars).755To disable all background task functionality, set the `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` environment variable to `1`. See [Environment variables](/en/env-vars).

754 756 

755When [`CLAUDE_CODE_FORK_SUBAGENT`](#fork-the-current-conversation) is set to `1`, every subagent spawn runs in the background and the frontmatter `background` field has no effect, because fork mode removes the `run_in_background` parameter from the `Agent` tool. `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` takes precedence over fork mode and keeps subagent spawns in the foreground.757When [`CLAUDE_CODE_FORK_SUBAGENT`](#fork-the-current-conversation) is set to `1`, every subagent runs in the background and the frontmatter `background` field has no effect, because fork mode removes the `run_in_background` parameter from the `Agent` tool. `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` takes precedence over fork mode and keeps subagents in the foreground.

756 758 

757### API errors in subagents759### API errors in subagents

758 760 


845 847 

846A [fork](#fork-the-current-conversation) still can't spawn another fork. It can spawn other subagent types, and those count toward the depth limit.848A [fork](#fork-the-current-conversation) still can't spawn another fork. It can spawn other subagent types, and those count toward the depth limit.

847 849 

850### Session subagent limit

851 

852By default, Claude can spawn at most 200 subagents per session. To raise the limit, set [`CLAUDE_CODE_MAX_SUBAGENTS_PER_SESSION`](/en/env-vars) to any positive whole number; there is no upper bound, but the limit can't be turned off. Requires Claude Code v2.1.212 or later.

853 

854Every subagent Claude spawns with the Agent tool counts toward the limit: nested subagents, [forks](#fork-the-current-conversation), and background subagents, including subagents that a [workflow](/en/workflows)'s agents spawn with the Agent tool. Agents a workflow script spawns with `agent()` don't count; workflows have their own per-run limit. A finished subagent still counts.

855 

856When Claude reaches the limit, the Agent tool fails with `Subagent spawn limit reached`, and the error tells Claude to complete the remaining work directly with its own tools.

857 

858Run [`/clear`](/en/commands#all-commands) to reset the count and start a new conversation with the full budget. If work that can still spawn subagents survives the clear, such as a running workflow, the count carries over instead.

859 

860This limit is separate from the [depth limit](#spawn-nested-subagents), which caps how deeply subagents nest.

861 

848### Manage subagent context862### Manage subagent context

849 863 

850#### What loads at startup864#### What loads at startup


855 869 

856* **System prompt**: the agent's own prompt plus environment details that Claude Code appends, not the full Claude Code system prompt. Custom subagents define theirs in the [markdown body](#write-subagent-files) or `prompt` field. Built-in agents have predefined prompts.870* **System prompt**: the agent's own prompt plus environment details that Claude Code appends, not the full Claude Code system prompt. Custom subagents define theirs in the [markdown body](#write-subagent-files) or `prompt` field. Built-in agents have predefined prompts.

857* **Task message**: the delegation prompt Claude writes when it hands off the work.871* **Task message**: the delegation prompt Claude writes when it hands off the work.

858* **CLAUDE.md and memory**: every level of the [memory hierarchy](/en/memory#how-claude-md-files-load) the main conversation loads, including `~/.claude/CLAUDE.md`, project rules, `CLAUDE.local.md`, and managed policy files. The built-in Explore and Plan agents skip this.872* **CLAUDE.md files**: every level of the [CLAUDE.md hierarchy](/en/memory#how-claude-md-files-load) the main conversation loads, including `~/.claude/CLAUDE.md`, project rules, `CLAUDE.local.md`, and managed policy files. The built-in Explore and Plan agents skip this.

859* **Git status**: a snapshot taken at the start of the parent session. Absent when the working directory isn't a Git repository or when [`includeGitInstructions`](/en/settings#available-settings) is `false`. Explore and Plan skip it regardless.873* **Git status**: a snapshot taken at the start of the parent session. Absent when the working directory isn't a Git repository or when [`includeGitInstructions`](/en/settings#available-settings) is `false`. Explore and Plan skip it regardless.

860* **Preloaded skills**: full content of any skill named in the agent's [`skills` field](#preload-skills-into-subagents). Built-in agents don't preload skills.874* **Preloaded skills**: full content of any skill named in the agent's [`skills` field](#preload-skills-into-subagents). Built-in agents don't preload skills.

861* **Sibling roster**: a system reminder listing `main` and every other named agent in the session, each a valid `to` value for [`SendMessage`](#resume-subagents). {/* min-version: 2.1.206 */}Requires Claude Code v2.1.206 or later. The roster appears only when the subagent's tools include `SendMessage` and at least one other agent has a name, whether Claude named it when spawning it or it runs as an [agent team](/en/agent-teams) teammate. It is a snapshot taken when the subagent starts, so agents named later don't appear.875* **Sibling roster**: a system reminder listing `main` and every other named agent in the session, each a valid `to` value for [`SendMessage`](#resume-subagents). {/* min-version: 2.1.206 */}Requires Claude Code v2.1.206 or later. The roster appears only when the subagent's tools include `SendMessage` and at least one other agent has a name, whether Claude named it when spawning it or it runs as an [agent team](/en/agent-teams) teammate. It is a snapshot taken when the subagent starts, so agents named later don't appear.


864 878 

865The main conversation reads Explore and Plan results with full CLAUDE.md context, so most rules don't need to reach the subagent itself. If a rule must, such as "ignore the `vendor/` directory," restate it in the prompt you give Claude when delegating.879The main conversation reads Explore and Plan results with full CLAUDE.md context, so most rules don't need to reach the subagent itself. If a rule must, such as "ignore the `vendor/` directory," restate it in the prompt you give Claude when delegating.

866 880 

881Some main-conversation state never reaches a non-fork subagent:

882 

883* **Output style**: a subagent runs its own system prompt, so your [output style](/en/output-styles) doesn't shape its responses, except in a [fork](#fork-the-current-conversation).

884* **Auto memory**: the main conversation's [auto memory](/en/memory#auto-memory) isn't loaded. To give a subagent persistent memory of its own, use the [`memory` field](#enable-persistent-memory).

885* **Context window size**: a subagent's context window is sized by its own model, not the parent's. Delegating to a model with a smaller window gives that subagent the smaller window.

886 

867#### Resume subagents887#### Resume subagents

868 888 

869Each subagent invocation creates a new instance with fresh context. To continue an existing subagent's work instead of starting over, ask Claude to resume it.889Each subagent invocation creates a new instance with fresh context. To continue an existing subagent's work instead of starting over, ask Claude to resume it.


890 910 

891Resuming starts a new run of the agent under the same ID, so a subagent that had already failed or completed shows as running again in the task list and in the Agent SDK's task events. Before v2.1.205, it kept showing its earlier failed or completed status while the resumed run was working.911Resuming starts a new run of the agent under the same ID, so a subagent that had already failed or completed shows as running again in the task list and in the Agent SDK's task events. Before v2.1.205, it kept showing its earlier failed or completed status while the resumed run was working.

892 912 

893{/* min-version: 2.1.199 */}As of v2.1.199, `SendMessage` checks that a name still refers to the same agent it reached earlier in the conversation. If a newer agent has taken the name, such as a re-spawned background agent that reused it, Claude Code refuses the send rather than delivering it to the wrong agent, and the error reports which agent the name now reaches so Claude can retarget. To reach the earlier agent while it's still running, Claude addresses it by the agent ID from its spawn result. The check is scoped to the current conversation and resets on `/clear`.913{/* min-version: 2.1.199 */}As of v2.1.199, `SendMessage` checks that a name still refers to the same agent it reached earlier in the conversation. If a newer agent has taken the name, such as a re-spawned background agent that reused it, Claude Code refuses the send rather than delivering it to the wrong agent, and the error reports which agent the name now reaches so Claude can retarget. To reach the earlier agent while it's still running, Claude addresses it by the agent ID it received when it spawned that agent. The check is scoped to the current conversation and resets on `/clear`.

894 914 

895{/* min-version: 2.1.198 */}As of v2.1.198, a subagent treats messages from the agent that launched it as normal task direction, including mid-task course corrections, and acts on them within its own permission settings. Two limits still hold regardless of who sent the message: no message from any agent counts as your approval for a pending permission prompt, and no agent message can change a subagent's permission settings, `CLAUDE.md`, or configuration. Only the permission system or your own messages can grant approval.915{/* min-version: 2.1.198 */}As of v2.1.198, a subagent treats messages from the agent that launched it as normal task direction, including mid-task course corrections, and acts on them within its own permission settings. Two limits still hold regardless of who sent the message: no message from any agent counts as your approval for a pending permission prompt, and no agent message can change a subagent's permission settings, `CLAUDE.md`, or configuration. Only the permission system or your own messages can grant approval.

896 916 

Details

105 </Tab>105 </Tab>

106</Tabs>106</Tabs>

107 107 

108Then set `USE_BUILTIN_RIPGREP=0` in your [environment](/en/env-vars).108Then set `USE_BUILTIN_RIPGREP=0` in your [environment](/en/env-vars). To confirm the switch took effect, run `claude doctor` in your terminal and check that the Search line shows the path of your system ripgrep instead of `OK (bundled)`.

109 109 

110### Slow or incomplete search results on WSL110### Slow or incomplete search results on WSL

111 111 

whats-new.md +8 −0

Details

8 8 

9The weekly dev digest highlights the features most likely to change how you work. Each entry includes runnable code, a short demo, and a link to the full docs. For every bug fix and minor improvement, see the [changelog](/en/changelog).9The weekly dev digest highlights the features most likely to change how you work. Each entry includes runnable code, a short demo, and a link to the full docs. For every bug fix and minor improvement, see the [changelog](/en/changelog).

10 10 

11<Update label="Week 29" description="July 13–17, 2026" tags={["v2.1.207–v2.1.212"]}>

12 **Artifacts call your MCP connectors**: a published artifact can pull live data and take actions through each viewer's own MCP connectors when they open the page, and this week also adds public sharing links, editor roles on Team and Enterprise, and artifacts created from Claude Tag sessions.

13 

14 Also this week: **screen reader mode** replaces the visual terminal interface with plain, linear text for screen readers such as VoiceOver and NVDA; **`/fork`** copies your conversation into a new background session while you keep working; and **auto mode** no longer needs an opt-in variable on Amazon Bedrock, Google Cloud's Agent Platform, and Microsoft Foundry.

15 

16 [Read the Week 29 digest →](/en/whats-new/2026-w29)

17</Update>

18 

11<Update label="Week 28" description="July 6–10, 2026" tags={["v2.1.202–v2.1.206"]}>19<Update label="Week 28" description="July 6–10, 2026" tags={["v2.1.202–v2.1.206"]}>

12 **In-app browser on Desktop**: Claude Code on desktop gets a built-in browser, so Claude can pull up docs, designs, or any other site and interact with pages the same way it does with your local dev server previews.20 **In-app browser on Desktop**: Claude Code on desktop gets a built-in browser, so Claude can pull up docs, designs, or any other site and interact with pages the same way it does with your local dev server previews.

13 21 

whats-new/2026-w29.md +70 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Week 29 · July 13–17, 2026

6 

7> Pull live data into published artifacts through MCP connectors, and use Claude Code with a screen reader in the new screen reader mode.

8 

9<div className="digest-meta">

10 <span>Releases <a href="/docs/en/changelog#2-1-207">v2.1.207 → v2.1.212</a></span>

11 <span>2 features · July 13–17</span>

12</div>

13 

14<div className="digest-feature">

15 <div className="digest-feature-header">

16 <span className="digest-feature-title">Artifacts call your MCP connectors</span>

17 <span className="digest-feature-pill">web</span>

18 </div>

19 

20 <p className="digest-feature-lede">A published artifact can now call MCP connectors each time someone views it, so a dashboard shows live data and can take actions on demand rather than a snapshot from the session that built it. Each call runs through the viewing account's own connections, and viewers approve access before the page's first connector call. This week also adds public sharing links, editor roles for shared editing on Team and Enterprise plans, and artifacts created from Claude Tag sessions.</p>

21 

22 <Frame>

23 <video autoPlay muted loop playsInline className="w-full" src="https://mintcdn.com/claude-code/ItzF3QVI6L0QypjJ/images/whats-new/artifacts-mcp.mp4?fit=max&auto=format&n=ItzF3QVI6L0QypjJ&q=85&s=ff8b81ed52b26c773899dc28cec959e6" data-path="images/whats-new/artifacts-mcp.mp4" />

24 </Frame>

25 

26 <p className="digest-feature-try">Name the connector and the data you want in your prompt:</p>

27 

28 ```text Claude Code theme={null}

29 > Build a dashboard artifact of open pull requests that pulls the live list through my GitHub connector when the page loads.

30 ```

31 

32 <a className="digest-feature-link" href="/docs/en/artifacts#pull-live-data-with-mcp-connectors">Pull live data with MCP connectors</a>

33</div>

34 

35<div className="digest-feature">

36 <div className="digest-feature-header">

37 <span className="digest-feature-title">Screen reader mode</span>

38 <span className="digest-feature-pill">CLI</span>

39 </div>

40 

41 <p className="digest-feature-lede">Screen reader mode replaces the visual terminal interface with plain, linear text: instead of boxes, spinners, and in-place redraws, Claude Code prints labeled lines that a screen reader such as VoiceOver or NVDA reads in order, so you can approve permissions and review output end to end. Turn it on per session with a flag, per shell with the <code>CLAUDE\_AX\_SCREEN\_READER</code> environment variable, or everywhere with the <code>axScreenReader</code> setting.</p>

42 

43 <p className="digest-feature-try">Start a session in screen reader mode:</p>

44 

45 ```bash terminal theme={null}

46 claude --ax-screen-reader

47 ```

48 

49 <a className="digest-feature-link" href="/docs/en/accessibility#turn-on-screen-reader-mode">Turn on screen reader mode</a>

50</div>

51 

52<div className="digest-wins">

53 <p className="digest-wins-title">Other wins</p>

54 

55 <div className="digest-wins-grid">

56 <div><code>/fork</code> now copies your conversation into a new background session with its own row in <code>claude agents</code> while you keep working; the in-session forked subagent it used to launch is now <code>/subtask</code></div>

57 <div><a href="/docs/en/permission-modes#enable-auto-mode-on-bedrock-agent-platform-or-foundry">Auto mode</a> no longer needs the <code>CLAUDE\_CODE\_ENABLE\_AUTO\_MODE</code> opt-in on Amazon Bedrock, Google Cloud's Agent Platform, and Microsoft Foundry; administrators can turn it off with <code>disableAutoMode</code></div>

58 <div>MCP tool calls that run longer than two minutes now move to the background automatically so the session stays usable; tune or disable the threshold with <code>CLAUDE\_CODE\_MCP\_AUTO\_BACKGROUND\_MS</code></div>

59 <div>New <code>claude auto-mode reset</code> restores the default auto-mode configuration, and `--yes` skips the confirmation prompt</div>

60 <div>New <a href="/docs/en/corporate-launcher">corporate launcher</a> support: <code>CLAUDE\_CODE\_PROCESS\_WRAPPER</code> or the <code>processWrapper</code> setting runs the processes Claude Code starts from its own binary, such as the background service and agent view sessions, through a required wrapper executable</div>

61 <div><code>vimInsertModeRemaps</code> setting maps two-key insert-mode sequences such as <code>jj</code> to Escape in vim mode</div>

62 <div>`--forward-subagent-text` and <code>CLAUDE\_CODE\_FORWARD\_SUBAGENT\_TEXT</code> include subagent text and thinking blocks in <a href="/docs/en/headless">stream-json output</a></div>

63 <div>Session-wide caps stop runaway loops: WebSearch calls and subagent spawns each default to 200, tunable with <code>CLAUDE\_CODE\_MAX\_WEB\_SEARCHES\_PER\_SESSION</code> and <code>CLAUDE\_CODE\_MAX\_SUBAGENTS\_PER\_SESSION</code></div>

64 <div>"Always allow" permission rules save at the repository root, so approvals granted in a git worktree persist across sessions and worktrees</div>

65 <div>Amazon Bedrock, Google Cloud's Agent Platform, and Claude Platform on AWS now default to Claude Opus 4.8</div>

66 <div>The collapsed tool summary line shows a live elapsed-time counter, so long-running tool calls visibly tick instead of looking stuck</div>

67 </div>

68</div>

69 

70[Full changelog for v2.1.207–v2.1.212 →](/en/changelog#2-1-207)