modified Week 23 · June 1–5, 2026 View current →
--- a/2026-w23.md +++ b/2026-w23.md @@ -44,7 +44,9 @@ managed-settings.json - "requiredMinimumVersion": "2.1.163" + { + "requiredMinimumVersion": "2.1.163" + } [Decide what to enforce](</docs/en/admin-setup#decide-what-to-enforce>)
modified Set up Claude Code for your organization View current →
--- a/admin-setup.md +++ b/admin-setup.md @@ -34,11 +34,11 @@ Decide how settings reach devices -Managed settings define policy that takes precedence over local developer configuration. Claude Code checks the four sources below in priority order and applies the first one that returns a non-empty configuration. +Managed settings define policy that takes precedence over local developer configuration. Claude Code checks the four sources below in priority order and applies the first one that returns a non-empty configuration, with one exception: a small set of [cross-source lock keys](</docs/en/settings#settings-precedence>), such as the sandbox allowlist locks, is honored when any admin-controlled source sets them. Mechanism| Delivery| Priority| Platforms ---|---|---|--- -Server-managed| claude.ai admin console| Highest| All +Server-managed| claude.ai admin console, or a self-hosted [Claude apps gateway](</docs/en/claude-apps-gateway>) for gateway sign-ins| Highest| All plist / registry policy| macOS: `com.anthropic.claudecode` plist Windows: `HKLM\SOFTWARE\Policies\ClaudeCode`| High| macOS, Windows File-based managed| macOS: `/Library/Application Support/ClaudeCode/managed-settings.json` @@ -46,7 +46,7 @@ Windows: `C:\Program Files\ClaudeCode\managed-settings.json`| Medium| All Windows user registry| `HKCU\SOFTWARE\Policies\ClaudeCode`| Lowest| Windows only -Server-managed settings reach devices at authentication time and refresh hourly during active sessions, with no endpoint infrastructure. They require a Claude for Teams or Enterprise plan, so deployments on other providers need one of the file-based or OS-level mechanisms instead. If your organization mixes providers, configure [server-managed settings](</docs/en/server-managed-settings>) for claude.ai users plus a [file-based or plist/registry fallback](</docs/en/settings#settings-files>) so other users still receive managed policy. The plist and HKLM registry locations work with any provider and resist tampering because they require admin privileges to write. The Windows user registry at HKCU is writable without elevation, so treat it as a convenience default rather than an enforcement channel. By default, WSL reads only the Linux file path at `/etc/claude-code`. To extend your Windows registry and `C:\Program Files\ClaudeCode` policy to WSL on the same machine, set [`wslInheritsWindowsSettings: true`](</docs/en/settings#available-settings>) in either of those admin-only Windows sources. Whichever mechanism you choose, managed values take precedence over user and project settings. Array settings such as `permissions.allow` and `permissions.deny` merge entries from all sources, so developers can extend managed lists but not remove from them. For [two exceptions](</docs/en/settings#settings-precedence>), `fallbackModel` and `availableModels`, the managed value replaces lower layers rather than merging. See [Server-managed settings](</docs/en/server-managed-settings>) and [Settings files and precedence](</docs/en/settings#settings-files>). +A configured [`policyHelper`](</docs/en/settings#compute-managed-settings-with-a-policy-helper>) preempts all four sources: its output becomes the only managed configuration for the run. See [Settings precedence](</docs/en/settings#settings-precedence>). Server-managed settings reach devices at authentication time and refresh hourly during active sessions, with no endpoint infrastructure. Delivery through the claude.ai admin console requires a Claude for Teams or Enterprise plan. Deployments on Bedrock, Vertex AI, or Foundry can get the same remote delivery by running a [Claude apps gateway](</docs/en/claude-apps-gateway>), or use one of the file-based or OS-level mechanisms instead. If your organization mixes providers, configure [server-managed settings](</docs/en/server-managed-settings>) for claude.ai users plus a [file-based or plist/registry fallback](</docs/en/settings#settings-files>) so other users still receive managed policy. The plist and HKLM registry locations work with any provider and resist tampering because they require admin privileges to write. The Windows user registry at HKCU is writable without elevation, so treat it as a convenience default rather than an enforcement channel. By default, WSL reads only the Linux file path at `/etc/claude-code`. To extend your Windows registry and `C:\Program Files\ClaudeCode` policy to WSL on the same machine, set [`wslInheritsWindowsSettings: true`](</docs/en/settings#available-settings>) in either of those admin-only Windows sources. Whichever mechanism you choose, managed values take precedence over user and project settings. Array settings such as `permissions.allow` and `permissions.deny` merge entries from all sources, so developers can extend managed lists but not remove from them. For [two exceptions](</docs/en/settings#settings-precedence>), `fallbackModel` and `availableModels`, the managed value replaces lower layers rather than merging. See [Server-managed settings](</docs/en/server-managed-settings>) and [Settings files and precedence](</docs/en/settings#settings-files>). ## @@ -63,7 +63,7 @@ [Sandboxing](</docs/en/sandboxing>)| OS-level filesystem and network isolation with domain allowlists| `sandbox.enabled`, `sandbox.network.allowedDomains` [Managed policy CLAUDE.md](</docs/en/memory#deploy-organization-wide-claude-md>)| Org-wide instructions loaded in every session, can’t be excluded| File at the managed policy path [MCP server control](</docs/en/managed-mcp>)| Restrict which MCP servers users can add or connect to, or deploy a fixed set| `allowedMcpServers`, `deniedMcpServers`, `allowManagedMcpServersOnly`, or a deployed `managed-mcp.json` file -[Plugin marketplace control](</docs/en/plugin-marketplaces#managed-marketplace-restrictions>)| Restrict which marketplace sources users can add and install from| `strictKnownMarketplaces`, `blockedMarketplaces` +[Plugin marketplace control](</docs/en/plugin-marketplaces#managed-marketplace-restrictions>)| Restrict which marketplace sources users can add and install from, and reject the CLI flags that sideload plugins, agents, and MCP servers for a single run| `strictKnownMarketplaces`, `blockedMarketplaces`, `disableSideloadFlags` [Customization lockdown](</docs/en/settings#strictpluginonlycustomization>)| Block skills, agents, hooks, and MCP servers from user and project sources, so they can only come from plugins or managed settings| `strictPluginOnlyCustomization` [Hook restrictions](</docs/en/settings#hook-configuration>)| Only managed hooks load; restrict HTTP hook URLs| `allowManagedHooksOnly`, `allowedHttpHookUrls` [Disable agent view](</docs/en/agent-view#how-background-sessions-are-hosted>)| Turn off `claude agents`, `--bg`, `/background`, and the on-demand supervisor| `disableAgentView` @@ -85,7 +85,7 @@ ---|---|---|--- Usage monitoring| OpenTelemetry export of sessions, tools, and tokens| All providers| [Monitoring usage](</docs/en/monitoring-usage>) Analytics dashboard| Per-user metrics, contribution tracking, leaderboard| Anthropic only| [Analytics](</docs/en/analytics>) -Cost tracking| Spend limits, rate limits, and usage attribution| Anthropic only| [Costs](</docs/en/costs>) +Cost tracking| Spend limits, rate limits, and usage attribution| Anthropic; on third-party clouds, a [Claude apps gateway](</docs/en/claude-apps-gateway>) provides per-user attribution and [spend limits](</docs/en/claude-apps-gateway-spend-limits>)| [Costs](</docs/en/costs>) Cloud providers expose spend through AWS Cost Explorer, GCP Billing, or Azure Cost Management. Claude for Teams and Enterprise plans include a usage dashboard at [claude.ai/analytics/claude-code](<https://claude.ai/analytics/claude-code>). @@ -103,7 +103,7 @@ Zero Data Retention (ZDR)| Nothing stored after the request completes. Available to qualified accounts on Claude for Enterprise| [Zero data retention](</docs/en/zero-data-retention>) Security architecture| Network model, encryption, authentication, audit trail| [Security](</docs/en/security>) -If you need request-level audit logging or to route traffic by data sensitivity, place an [LLM gateway](</docs/en/llm-gateway>) between developers and your provider. For regulatory requirements and certifications, see [Legal and compliance](</docs/en/legal-and-compliance>). +If you need request-level audit logging or to route traffic by data sensitivity, place a gateway between developers and your provider: a self-hosted [Claude apps gateway](</docs/en/claude-apps-gateway>) records a per-request audit log with IdP identity, or use another [LLM gateway](</docs/en/llm-gateway>). For regulatory requirements and certifications, see [Legal and compliance](</docs/en/legal-and-compliance>). ##
modified Orchestrate teams of Claude Code sessions View current →
--- a/agent-teams.md +++ b/agent-teams.md @@ -94,7 +94,7 @@ `tmux` has known limitations on certain operating systems and traditionally works best on macOS. Using `tmux -CC` in iTerm2 is the suggested entrypoint into `tmux`. -The default is `"in-process"`. Before v2.1.179 the default was `"auto"`, so upgraded sessions that previously opened split panes now stay in one terminal unless you set the mode explicitly. Set `"auto"` to enable split panes when you’re already running inside a tmux session or your terminal is iTerm2, falling back to in-process otherwise. The `"tmux"` setting enables split-pane mode and auto-detects whether to use tmux or iTerm2 based on your terminal. As of v2.1.186, set `"iterm2"` to use iTerm2 native split panes explicitly. This mode requires the [`it2` CLI](<https://github.com/mkusaka/it2>) and shows an error with the install command if `it2` is missing. The setup prompt that offers to install `it2` or switch to tmux appears under `"auto"` or `"tmux"` when your terminal is iTerm2 and tmux is available as a fallback. To override the default, set [`teammateMode`](</docs/en/settings#available-settings>) in `~/.claude/settings.json`: +The default is `"in-process"`. Before v2.1.179 the default was `"auto"`, so upgraded sessions that previously opened split panes now stay in one terminal unless you set the mode explicitly. Set `"auto"` to enable split panes when you’re already running inside a tmux session, or when your terminal is iTerm2 with the `it2` CLI installed, falling back to in-process otherwise. The `"tmux"` setting enables split-pane mode and auto-detects whether to use tmux or iTerm2 based on your terminal. As of v2.1.186, set `"iterm2"` to use iTerm2 native split panes explicitly. This mode requires the [`it2` CLI](<https://github.com/mkusaka/it2>) and shows an error with the install command if `it2` is missing. The setup prompt that offers to install `it2` or switch to tmux appears under `"auto"` or `"tmux"` when your terminal is iTerm2 and tmux is available as a fallback. To override the default, set [`teammateMode`](</docs/en/settings#available-settings>) in `~/.claude/settings.json`: { "teammateMode": "auto"
modified Manage multiple agents with agent view View current →
Show diff (207 lines)
--- a/agent-view.md +++ b/agent-view.md @@ -60,7 +60,7 @@ Monitor sessions with agent view -Run `claude agents` to open agent view. It takes over the full terminal and lists every session grouped by state, with pinned sessions and the ones that need you at the top. Each row shows the session’s name, current activity, and how long ago it last changed. By default the list shows every background session you’ve started, across all your projects. A session working in one repository and another in a different worktree both appear here, regardless of which directory you opened agent view from. To narrow the list to one project, pass `--cwd`, which requires Claude Code v2.1.141 or later: +Run `claude agents` to open agent view. It takes over the full terminal and lists every session grouped by state, with pinned sessions and the ones that need you at the top. Each row shows the session’s name, current activity, and how long ago it last changed. By default the list shows every background session you’ve started, across all your projects. A session working in one repository and another in a different worktree both appear here, regardless of which directory you opened agent view from. To narrow the list to one project, pass `--cwd`: claude agents --cwd ~/projects/my-app @@ -117,7 +117,7 @@ Row summaries -The one-line summary in each row is generated by a [Haiku-class model](</docs/en/model-config>) so the row can tell you what the session is doing, what it needs, or what it produced without opening the transcript. While a session is actively working, the summary refreshes at most once every 15 seconds, plus once when each turn ends. From v2.1.161, when the session is running two or more parallel work items, such as subagents, background shell commands, or monitors, a `done/total` count such as `2/5` appears before the summary text. Each refresh is one short Haiku-class request through your normal provider, billed and handled under the same [data usage terms](</docs/en/data-usage>) as the session itself. On third-party providers such as Bedrock, Vertex AI, Microsoft Foundry, and custom gateways, the request falls back to the session’s main model when no Haiku model is configured. Set [`ANTHROPIC_DEFAULT_HAIKU_MODEL`](</docs/en/model-config#environment-variables>) to choose the model for these summaries on those providers. +The one-line summary in each row is generated by a [Haiku-class model](</docs/en/model-config>) so the row can tell you what the session is doing, what it needs, or what it produced without opening the transcript. While a session is actively working, the summary refreshes at most once every 15 seconds, plus once when each turn ends. When the session is running two or more parallel work items, such as subagents, background shell commands, or monitors, a `done/total` count such as `2/5` appears before the summary text. Each refresh is one short Haiku-class request through your normal provider, billed and handled under the same [data usage terms](</docs/en/data-usage>) as the session itself. On third-party providers such as Bedrock, Vertex AI, Microsoft Foundry, and custom gateways, the request falls back to the session’s main model when no Haiku model is configured. Set [`ANTHROPIC_DEFAULT_HAIKU_MODEL`](</docs/en/model-config#environment-variables>) to choose the model for these summaries on those providers. ### @@ -142,7 +142,7 @@ Peek and reply -Press `Space` on a selected row to open the peek panel. It shows what the session needs from you, its most recent output, and any pull requests it opened. Most of the time this is enough, and you never need to open the full transcript. From v2.1.161, when the session is running parallel work items, the panel also names the longest-running one and how long it has been going, so you can see what the session is waiting on without attaching. Type a reply in the peek panel and press `Enter` to send it to that session. When the session is asking a multiple-choice question, the peek panel shows the options and you can press a number key to pick one. For other blocked sessions, press `Tab` to fill the input with a suggested reply you can edit before sending. Prefix a reply with `!` to send a Bash command instead. From v2.1.145, with [voice dictation](</docs/en/voice-dictation>) enabled, hold or tap your push-to-talk key while the reply input is focused to dictate a reply instead of typing it. The same works in the dispatch input at the bottom of agent view. Use `↑` and `↓` to peek at adjacent sessions without closing the panel, or `→` to attach. +Press `Space` on a selected row to open the peek panel. It shows what the session needs from you, its most recent output, and any pull requests it opened. Most of the time this is enough, and you never need to open the full transcript. When the session is running parallel work items, the panel also names the longest-running one and how long it has been going, so you can see what the session is waiting on without attaching. Type a reply in the peek panel and press `Enter` to send it to that session. When the session is asking a multiple-choice question, the peek panel shows the options and you can press a number key to pick one. For other blocked sessions, press `Tab` to fill the input with a suggested reply you can edit before sending. Prefix a reply with `!` to send a Bash command instead. With [voice dictation](</docs/en/voice-dictation>) enabled, hold or tap your push-to-talk key while the reply input is focused to dictate a reply instead of typing it. The same works in the dispatch input at the bottom of agent view. Use `↑` and `↓` to peek at adjacent sessions without closing the panel, or `→` to attach. ### @@ -150,7 +150,7 @@ Attach to a session -Press `Enter` or `→` on a selected row to attach. Agent view is replaced by the full interactive session. When you attach, Claude posts a short recap of what happened while you were away. While attached, the session behaves like any other Claude Code session: every [command](</docs/en/commands>), keyboard shortcut, and feature works. Attached sessions always render in [fullscreen mode](</docs/en/fullscreen>), regardless of your `tui` setting, because a background session has no terminal scrollback to append to. Scroll with `PgUp`, `PgDn`, or the mouse wheel, and press `Ctrl+O` for transcript mode. Your terminal’s native scroll and tmux copy mode show only the current viewport, the same as when you run any fullscreen application. Press `←` on an empty prompt to detach and return to agent view. If a dialog has focus and isn’t responding to `←`, press `Ctrl+Z` to detach immediately. `Ctrl+C` keeps its standard interrupt behavior while attached: it cancels a running response or `!` shell command rather than detaching. Pressing `Ctrl+C` twice on an empty prompt detaches, the same as in any session. Detaching never stops a background session: `←`, `Ctrl+Z`, `/exit`, and double `Ctrl+C` or double `Ctrl+D` all leave it running. To end a session from inside it, run `/stop`. Pressing `←` on an empty prompt works from any Claude Code session, not only ones you attached to from agent view. It backgrounds the current session and opens agent view with that row selected, so you can switch sessions without leaving the terminal. The row is created even from a fresh session with no conversation history, so `→` returns to it. When that row is the only one, agent view shows an onboarding hint below it. You can turn this shortcut off in `/config` (the `leftArrowOpensAgents` setting). +Press `Enter` or `→` on a selected row to attach. Agent view is replaced by the full interactive session. When you attach, Claude posts a short recap of what happened while you were away. While attached, the session behaves like any other Claude Code session: every [command](</docs/en/commands>), keyboard shortcut, and feature works. Attached sessions always render in [fullscreen mode](</docs/en/fullscreen>), regardless of your `tui` setting, because a background session has no terminal scrollback to append to. Scroll with `PgUp`, `PgDn`, or the mouse wheel, and press `Ctrl+O` for transcript mode. Your terminal’s native scroll and tmux copy mode show only the current viewport, the same as when you run any fullscreen application. Press `←` on an empty prompt to detach and return to agent view. If a dialog has focus and isn’t responding to `←`, press `Ctrl+Z` to detach immediately. `Ctrl+C` keeps its standard interrupt behavior while attached: it cancels a running response or `!` shell command rather than detaching. Pressing `Ctrl+C` twice on an empty prompt detaches, the same as in any session. Detaching never stops a background session: `←`, `Ctrl+Z`, `/exit`, and double `Ctrl+C` or double `Ctrl+D` all leave it running. To end a session from inside it, run `/stop`. In a session running in the foreground, one you started in the terminal rather than attached to from agent view, pressing `←` on an empty prompt backgrounds it and opens agent view with that row selected, so you can switch sessions without leaving the terminal. The same single press detaches an attached session. If a tool is running when you press `←`, Claude Code waits up to about ten seconds for it to finish before backgrounding, and the response continues in the background session. Press `←` again to background immediately instead of waiting. When in-flight work can’t carry over to the background session, the `Background this session?` dialog appears first, the same as with `/background`. The row is created even from a fresh session with no conversation history, so `→` returns to it. When that row is the only one, agent view shows an onboarding hint below it. You can turn this shortcut off with the `leftArrowOpensAgents` setting in `/config`. ### @@ -165,7 +165,7 @@ * Press `Ctrl+R` to rename a session * Press `Enter` on a group header to collapse it -To remove a session from the list, press `Ctrl+X` to stop it and `Ctrl+X` again within two seconds to delete it. Pressing `Ctrl+X` on a group header deletes every session in that group after confirmation. Deleting removes the session from agent view. If Claude created a worktree for the session, deleting removes that worktree too, including any uncommitted changes in it, so push or commit work you want to keep first. A worktree you created yourself and started the session inside is left in place. The conversation transcript stays on your local machine and remains available through `claude --resume`. Older completed sessions fold into a `… N more` row to keep the list short. Failures and sessions with an open pull request always stay visible. +To remove a session from the list, press `Ctrl+X` to stop it and `Ctrl+X` again within two seconds to delete it. Pressing `Ctrl+X` on a group header deletes every session in that group after confirmation. Deleting removes the session from agent view. If Claude created a worktree for the session, deleting removes that worktree too, including any uncommitted changes in it, so push or commit work you want to keep first. A worktree you created yourself and started the session inside is left in place. The conversation transcript stays on your local machine and remains available through `claude --resume`. Completed sessions that don’t fit on screen fold into a `… N more` row. Failures and sessions with an open pull request always stay visible. The `Completed` group fills the vertical space left after the live groups, and on a short terminal the header compacts to a single summary line so sessions that are working or need input stay visible. ### @@ -257,7 +257,7 @@ From inside a session -Run `/background` or its alias `/bg` to move the current conversation into a background session. Pass a prompt such as `/bg run the test suite and fix any failures` to give one more instruction first. If Claude is responding when you run `/bg`, the response continues in the background session. Backgrounding from an interactive session starts a fresh process that resumes from the saved conversation, so running subagents, [monitors](</docs/en/tools-reference#monitor-tool>), and background commands do not transfer to it. Claude asks you to confirm before backgrounding when any are running. Once in the background, the session can start new subagents, monitors, and background commands, and those keep running across later detach and reattach. Configuration flags from the original launch carry through to the backgrounded session, so its MCP servers, settings, and fallback model remain in effect: +Run `/background` or its alias `/bg` to move the current conversation into a background session. Pass a prompt such as `/bg run the test suite and fix any failures` to give one more instruction first. If Claude is responding when you run `/bg`, the response continues in the background session. Backgrounding from an interactive session starts a fresh process that resumes from the saved conversation, and in-flight work moves to it: running background shell commands, backgrounded subagents, dynamic workflows, and scheduled tasks you created with [`/loop`](</docs/en/scheduled-tasks>) carry over to the background session and keep running there. A subagent moves together with everything it started, so it carries over only when all of that work can move too, including on Windows. To stop in-flight work instead of carrying it over, set the [`CLAUDE_DISABLE_ADOPT=1`](</docs/en/env-vars#variables>) environment variable; Claude Code then asks you to confirm before backgrounding. Work that can’t carry over, such as a running [monitor](</docs/en/tools-reference#monitor-tool>), is stopped. A backgrounded subagent that owns a monitor is stopped along with it. When any such work is running, Claude Code shows a `Background this session?` dialog so you can confirm before it’s stopped. Once in the background, the session can start new subagents, monitors, and background commands, and those keep running across later detach and reattach. Configuration flags from the original launch carry through to the backgrounded session, so its MCP servers, settings, and fallback model remain in effect: * `--mcp-config` and `--strict-mcp-config` * `--settings` @@ -330,8 +330,6 @@ } } -The `worktree.bgIsolation` setting requires Claude Code v2.1.143 or later. - Outside a git repository, sessions write to the working directory directly and aren’t isolated from each other, so avoid dispatching parallel sessions that edit the same files. If you use a different version control system, configure a [`WorktreeCreate` hook](</docs/en/worktrees#non-git-version-control>) and Claude isolates edits the same way it does for git. Deleting a session in agent view with `Ctrl+X` twice removes a worktree Claude created for it, including any uncommitted changes, so merge or push the changes you want to keep first. Deleting from the shell with `claude rm` keeps a worktree that has uncommitted changes and prints its path so you can clean it up yourself. A worktree you created yourself and started the session inside is left in place either way. To find a session’s worktree path, peek the session or attach and check its working directory. A [subagent](</docs/en/sub-agents>) the background session spawns inherits the session’s working directory, so its file edits land in the session’s worktree rather than your working copy. To give a subagent its own separate worktree instead, set [`isolation: worktree`](</docs/en/sub-agents#supported-frontmatter-fields>) in its frontmatter or pass `isolation: "worktree"` when spawning it. ### @@ -340,7 +338,7 @@ Set the model -The model name shown in the agent view header is the dispatch default. New sessions you start from the input use this model, which comes from the [`model` setting](</docs/en/settings#available-settings>) in your user settings. Set it by selecting a model in the [`/model` picker](</docs/en/model-config>), or edit the setting directly. To override the dispatch default for the whole agent view session, pass `--model` when opening agent view. See Permission mode, model, and effort. To change the dispatch default from inside agent view, type `/model` followed by a model name in the dispatch input and press `Enter`. The header updates to show that model with a `(session)` marker, and sessions you dispatch afterward use it. Type `/model default` to clear the override and return to the dispatch default. This override lasts for the rest of the current `claude agents` run, doesn’t write to your settings file, and requires Claude Code v2.1.172 or later. The following example dispatches one session on Opus and the next on Sonnet: +The model name shown in the agent view header is the dispatch default. New sessions you start from the input use this model, which comes from the [`model` setting](</docs/en/settings#available-settings>) in your user settings. Set it by selecting a model in the [`/model` picker](</docs/en/model-config>), or edit the setting directly. To override the dispatch default for the whole agent view session, pass `--model` when opening agent view. See Permission mode, model, and effort. To change the dispatch default from inside agent view, type `/model` followed by a model name in the dispatch input and press `Enter`. The header updates to show that model with a `(session)` marker, and sessions you dispatch afterward use it. Type `/model default` to clear the override and return to the dispatch default. This override lasts for the rest of the current `claude agents` run and doesn’t write to your settings file. The following example dispatches one session on Opus and the next on Sonnet: /model opus refactor auth @@ -363,15 +361,7 @@ claude agents --permission-mode plan --model opus --effort high -`--agent` sets the [subagent](</docs/en/sub-agents>) used when a dispatch prompt doesn’t name one, either with `@name` or as the first word. It defaults to the [`agent` setting](</docs/en/settings#available-settings>) if one is set, otherwise the built-in catch-all `claude` agent. Naming a subagent in the dispatch input overrides both. `claude agents` also accepts `--dangerously-skip-permissions` as shorthand for `--permission-mode bypassPermissions`, and `--allow-dangerously-skip-permissions` to make `bypassPermissions` available in each dispatched session’s `Shift+Tab` cycle without starting in that mode. Both match the [top-level CLI flags](</docs/en/cli-reference>). These flags were added across releases. Earlier versions reject them with an unknown-option error. - -Flag or setting| Minimum version ----|--- -`--permission-mode`, `--model`, `--effort`, `--dangerously-skip-permissions`| v2.1.142 -`--allow-dangerously-skip-permissions`| v2.1.143 -`--agent`, and honoring the `agent` setting for dispatched sessions| v2.1.157 - -Before v2.1.157, agent view ignores the `agent` setting and dispatches the built-in `claude` agent. The active defaults appear in the footer below the dispatch input. Without these flags, the session uses the `defaultMode` from that directory’s settings or the `permissionMode` from the dispatched [subagent’s frontmatter](</docs/en/sub-agents#supported-frontmatter-fields>), and the model shown in the agent view header. Using `bypassPermissions` or `auto` is refused until you have accepted that mode by running `claude` with it once interactively, since those modes let a session you aren’t watching act without approval. The same applies whether you pass the mode to `claude agents` or to `claude --bg --permission-mode`. +`--agent` sets the [subagent](</docs/en/sub-agents>) used when a dispatch prompt doesn’t name one, either with `@name` or as the first word. It defaults to the [`agent` setting](</docs/en/settings#available-settings>) if one is set, otherwise the built-in catch-all `claude` agent. Naming a subagent in the dispatch input overrides both. `claude agents` also accepts `--dangerously-skip-permissions` as shorthand for `--permission-mode bypassPermissions`, and `--allow-dangerously-skip-permissions` to make `bypassPermissions` available in each dispatched session’s `Shift+Tab` cycle without starting in that mode. Both match the [top-level CLI flags](</docs/en/cli-reference>). The active defaults appear in the footer below the dispatch input. Without these flags, the session uses the `defaultMode` from that directory’s settings or the `permissionMode` from the dispatched [subagent’s frontmatter](</docs/en/sub-agents#supported-frontmatter-fields>), and the model shown in the agent view header. Using `bypassPermissions` with `claude --bg --permission-mode` is refused until you have accepted the bypass disclaimer by running `claude --dangerously-skip-permissions` once interactively, since that mode lets a session you aren’t watching act without approval. Passing `--dangerously-skip-permissions` or `--permission-mode bypassPermissions` to `claude agents` shows the same disclaimer when you haven’t accepted it before, and accepting applies `bypassPermissions` to the sessions you launch from the view. Passing `--allow-dangerously-skip-permissions` shows the same disclaimer too, and accepting makes `bypassPermissions` available in the `Shift+Tab` cycle of those sessions without starting them in it. ### @@ -379,7 +369,7 @@ Settings, plugins, and MCP servers -Agent view accepts the same configuration flags as `claude` for loading settings, plugins, MCP servers, and additional directories. These flags require Claude Code v2.1.142 or later. Each flag applies to agent view itself and is passed through to every session you dispatch from it, so a plugin or MCP server you load this way is available in those sessions too. +Agent view accepts the same configuration flags as `claude` for loading settings, plugins, MCP servers, and additional directories. Each flag applies to agent view itself and is passed through to every session you dispatch from it, so a plugin or MCP server you load this way is available in those sessions too. Flag| Effect ---|--- @@ -405,7 +395,7 @@ ---|--- `claude agents`| Open agent view `claude agents --cwd <path>`| Open agent view scoped to sessions started under `<path>` -`claude agents --json`| Print active sessions as a JSON array and exit: every live session, plus background sessions that are still working or blocked even when their process has exited. Add `--all` to also include completed background sessions. Each entry has `cwd`, `kind`, and `startedAt`. Background entries also have `id`, usable with `claude attach`/`logs`/`stop`, and `state`: one of `working`, `blocked`, `done`, `failed`, or `stopped`. `pid` and `status` are present only while the process is alive, plus `waitingFor` when status is `waiting`, which says what the session is blocked on, such as `permission prompt` or `input needed`; `sessionId` and `name` appear when set. Combine with `--cwd <path>` to filter +`claude agents --json`| Print active sessions as a JSON array and exit: every live session, plus background sessions that are still working or blocked even when their process has exited. Add `--all` to also include completed background sessions. Each entry has `cwd`, `kind`, and `startedAt`. Background entries also have `id`, usable with `claude attach`/`logs`/`stop`, and `state`: one of `working`, `blocked`, `done`, `failed`, or `stopped`. `pid` and `status` are present only while the process is alive, plus `waitingFor` when status is `waiting`, which says what the session is blocked on, such as `permission prompt` or `input needed`; `sessionId` and `name` appear when set. An interactive entry you never named carries a default `name` built from its working directory’s name plus a two-character suffix, such as `my-app-3f`. Combine with `--cwd <path>` to filter `claude attach <id>`| Attach to a session in this terminal `claude logs <id>`| Print the session’s recent output `claude stop <id>`| Stop a session. Also accepts `claude kill` @@ -429,7 +419,7 @@ The supervisor process -Background sessions are hosted by a per-user supervisor process, separate from your terminal and from agent view. The supervisor starts automatically the first time you background a session or open agent view, and you don’t manage it directly. The supervisor keeps one pre-warmed worker process ready so a dispatch from agent view or `claude --bg` starts without the delay of a cold launch. When you dispatch, the supervisor assigns the pre-warmed worker to your session, applies that session’s directory, settings, and credentials to it, and then starts a replacement for the next dispatch. If no healthy pre-warmed worker is available, the supervisor launches a fresh process instead. The supervisor and its sessions authenticate with the same stored credentials as your interactive sessions and make no additional network connections beyond the model API. Provider selection variables such as `CLAUDE_CODE_USE_BEDROCK` and `ANTHROPIC_DEFAULT_*_MODEL` aliases are read from the shell that dispatched each session and are applied to its worker. A background session doesn’t inherit gateway endpoint variables such as `ANTHROPIC_BASE_URL`, the equivalent Bedrock, Vertex, and Foundry base URL variables, or a paired `ANTHROPIC_AUTH_TOKEN` from the shell that started the supervisor or from the dispatching shell. The session uses your stored credentials and any `env` values in the project directory’s [settings](</docs/en/settings>) instead. To point background sessions in a project at an [LLM gateway](</docs/en/llm-gateway>), set `ANTHROPIC_BASE_URL` in that project’s `.claude/settings.json` `env` block rather than exporting it in your shell. Before v2.1.174, a background session inherited these variables from the supervisor’s launch shell, so it could use the gateway you had configured in that shell instead of the one configured for the project directory. Each background session is its own Claude Code process, managed by the supervisor rather than tied to your terminal. A session that’s actively working, waiting for your input, or has a terminal attached keeps its process running. A running background shell command, subagent, dynamic workflow, or monitor counts as active work, so a long-running process such as a dev server keeps the session alive. Once a session finishes and sits unattached for about an hour, the supervisor stops its process to free resources. A session you have pinned with `Ctrl+T` is exempt and keeps its process running while idle. The transcript and state stay on disk either way, and the next time you attach, peek, or reply to a stopped session, the supervisor starts a fresh process from where it left off. When every session has finished and no terminal is connected, the supervisor itself exits and starts again the next time you need it. An empty row left over from pressing `←` that was never given a prompt is removed entirely after about five minutes so the list clears on its own. Sessions started with `claude --bg` and sessions waiting on a setup prompt such as a trust dialog aren’t removed this way. When the host runs low on memory, the supervisor stops idle non-pinned sessions first and stops idle pinned ones only if that freed nothing. The supervisor watches the installed Claude Code binary on disk and restarts into the new version after the regular [auto-updater](</docs/en/setup#auto-updates>) replaces it. This is a local file watch, not a network check. Background sessions are detached processes, so they keep running through the restart and the new supervisor reconnects to them. An idle pinned session is also restarted in place onto the new version so it picks up the update without you reattaching. +Background sessions are hosted by a per-user supervisor process, separate from your terminal and from agent view. The supervisor starts automatically the first time you background a session or open agent view, and you don’t manage it directly. The supervisor keeps one pre-warmed worker process ready so a dispatch from agent view or `claude --bg` starts without the delay of a cold launch. When you dispatch, the supervisor assigns the pre-warmed worker to your session, applies that session’s directory, settings, and credentials to it, and then starts a replacement for the next dispatch. If no healthy pre-warmed worker is available, the supervisor launches a fresh process instead. The supervisor and its sessions authenticate with the same stored credentials as your interactive sessions and make no additional network connections beyond the model API. Provider selection variables such as `CLAUDE_CODE_USE_BEDROCK` and `ANTHROPIC_DEFAULT_*_MODEL` aliases are read from the shell that dispatched each session and are applied to its worker. A background session doesn’t inherit gateway endpoint variables such as `ANTHROPIC_BASE_URL`, the equivalent Bedrock, Vertex, and Foundry base URL variables, or a paired `ANTHROPIC_AUTH_TOKEN` from the shell that started the supervisor or from the dispatching shell. The session uses your stored credentials and any `env` values in the project directory’s [settings](</docs/en/settings>) instead. To point background sessions in a project at an [LLM gateway](</docs/en/llm-gateway>), set `ANTHROPIC_BASE_URL` in that project’s `.claude/settings.json` `env` block rather than exporting it in your shell. Each background session is its own Claude Code process, managed by the supervisor rather than tied to your terminal. A session that’s actively working, waiting for your input, or has a terminal attached keeps its process running. A running background shell command, subagent, dynamic workflow, or monitor counts as active work, so a long-running process such as a dev server keeps the session alive. Once a session finishes and sits unattached for about an hour, the supervisor stops its process to free resources. A session you have pinned with `Ctrl+T` is exempt and keeps its process running while idle. The transcript and state stay on disk either way, and the next time you attach, peek, or reply to a stopped session, the supervisor starts a fresh process from where it left off. When every session has finished and no terminal is connected, the supervisor itself exits and starts again the next time you need it. Background shell commands and dynamic workflows the session started keep running when its process is stopped, restarted, or updated, including on Windows. The next process started for that session picks them back up, a shell command that finished in the meantime is reported as completed with its output, and a workflow resumes from where it left off. Shell commands started by a subagent and running [monitors](</docs/en/tools-reference#monitor-tool>) still stop with the process, and deleting the session stops everything it handed off. To stop background shell commands and workflows with the process too, set the [`CLAUDE_CODE_DISABLE_BG_EXIT_HANDOFF`](</docs/en/env-vars#variables>) environment variable to `1`. If a restarted session comes back showing only its original prompt because Claude Code misread its transcript as empty, the conversation transcript is renamed with an `.orphaned-` suffix instead of deleted, so it stays on your machine. An empty row left over from pressing `←` that was never given a prompt is removed entirely after about five minutes so the list clears on its own. Sessions started with `claude --bg` and sessions waiting on a setup prompt such as a trust dialog aren’t removed this way. When the host runs low on memory, the supervisor stops idle non-pinned sessions first and stops idle pinned ones only if that freed nothing. The supervisor watches the installed Claude Code binary on disk and restarts into the new version after the regular [auto-updater](</docs/en/setup#auto-updates>) replaces it. This is a local file watch, not a network check. Background sessions are detached processes, so they keep running through the restart and the new supervisor reconnects to them. An idle pinned session is also restarted in place onto the new version so it picks up the update without you reattaching. ### @@ -446,7 +436,7 @@ `~/.claude/jobs/<id>/state.json`| Per-session state shown in agent view `~/.claude/jobs/<id>/tmp/`| Per-session scratch directory. Writes here don’t prompt for permission. Removed when the session is deleted -Each background session has the `CLAUDE_JOB_DIR` environment variable set to its `~/.claude/jobs/<id>` directory, so shell commands the session runs can write temporary files to `$CLAUDE_JOB_DIR/tmp` without colliding with parallel sessions. To inspect this state without reading the files directly, run `claude daemon status`. It reports whether the supervisor is reachable, its process ID and version, the socket directory, and how many background sessions are live. `/doctor` includes a summary of the same check. The command also warns when the running supervisor is on a different version than the `claude` you invoked, which happens after an update the supervisor hasn’t restarted into yet. The warning shows both versions and tells you to run `claude daemon stop --any` to pick up the new version. When Claude Code is installed as an OS service, the suggested command is `claude daemon stop` without the flag. On Windows, `claude daemon status` surfaces the underlying file error when the daemon’s pipe-key file is locked or unreadable instead of reporting a generic connection failure. +Each background session has the `CLAUDE_JOB_DIR` environment variable set to its `~/.claude/jobs/<id>` directory, so shell commands the session runs can write temporary files to `$CLAUDE_JOB_DIR/tmp` without colliding with parallel sessions. To inspect this state without reading the files directly, run `claude daemon status`. It reports whether the supervisor is reachable, its process ID and version, the socket directory, and how many background sessions are live. `/doctor` includes a summary of the same check. The command also warns when the running supervisor is on a different version than the `claude` you invoked, which happens after an update the supervisor hasn’t restarted into yet. The warning shows both versions and tells you to run `claude daemon stop --any` to pick up the new version. When Claude Code is installed as an OS service, the suggested command is `claude daemon stop` without the flag. Sessions survive that version mismatch intact: an older Claude Code version that updates a session’s `state.json` preserves fields it doesn’t recognize and keeps the session listed. On Windows, `claude daemon status` surfaces the underlying file error when the daemon’s pipe-key file is locked or unreadable instead of reporting a generic connection failure. ### @@ -468,7 +458,7 @@ `claude agents` lists subagents instead of opening agent view -If `claude agents` prints a count followed by your configured subagents and then exits, agent view is unavailable in your environment. Earlier versions didn’t open agent view in every environment, including when connected through Bedrock, Vertex AI, or Foundry. Run `claude update` to install the latest version. If agent view still doesn’t open after updating, check whether it has been turned off by a setting or environment variable. +If `claude agents` prints a count followed by your configured subagents and then exits, agent view is unavailable in your environment. Run `claude update` to install the latest version. If agent view still doesn’t open after updating, check whether it has been turned off by a setting or environment variable. ### @@ -482,9 +472,9 @@ ​ -Cannot open agents because work is running in the background - -If pressing `←` to background the current session shows `Cannot open agents — N still running in the background`, the session has in-flight work such as a subagent, a dynamic workflow, or a background shell command, and the shortcut won’t silently abandon it. Run `/tasks` to see what’s running, then `/bg` to confirm abandoning them. See From inside a session for what does and doesn’t transfer when you background. +Backgrounding shows a `Background this session?` dialog + +If pressing `←` to background the current session shows a `Background this session?` dialog, the session has in-flight work that can’t move to the background session, such as a running [monitor](</docs/en/tools-reference#monitor-tool>), and Claude Code won’t silently stop it. The dialog names the work that will be stopped and, separately, counts the tasks that carry over. Run `/tasks` to see everything that’s running, then confirm to background anyway or choose `Stay` to let the work finish first. See From inside a session for which task kinds carry over and which are stopped. ### @@ -512,7 +502,7 @@ claude daemon stop --any --keep-workers -The new supervisor reconnects to the running sessions. Without `--keep-workers`, the command ends the background sessions too. The `--any` flag confirms you want to stop a supervisor that started on demand rather than as an installed service, which is the default. On Windows, if the supervisor doesn’t respond to the stop request, the command prints its process ID. End that process with `taskkill /PID <pid>` to finish the recovery. Background sessions are still preserved when you passed `--keep-workers`. +The new supervisor reconnects to the running sessions. Without `--keep-workers`, the command ends the background sessions too. The `--any` flag confirms you want to stop a supervisor that started on demand rather than as an installed service, which is the default. A supervisor that starts but can’t accept connections exits and releases its lock on its own, so the next `claude agents` starts a fresh one without this manual stop. The steps above apply when a running supervisor stalls. On Windows, if the supervisor doesn’t respond to the stop request, the command prints its process ID. End that process with `taskkill /PID <pid>` to finish the recovery. Background sessions are still preserved when you passed `--keep-workers`. ### @@ -520,11 +510,11 @@ Dispatch fails with `Could not resolve authentication method` -If a background dispatch fails with `Could not resolve authentication method` while interactive sessions authenticate normally, the worker that received the dispatch did not pick up credentials. On v2.1.174 and later the supervisor supplies a fresh credential snapshot when it assigns a pre-warmed worker, so this error means no stored credential was available to the supervisor process itself. Confirm you have run `/login` or configured an API key, then stop the supervisor: +If a background dispatch fails with `Could not resolve authentication method` while interactive sessions authenticate normally, the worker that received the dispatch did not pick up credentials. The supervisor supplies a fresh credential snapshot when it assigns a pre-warmed worker, so this error means no stored credential was available to the supervisor process itself. Confirm you have run `/login` or configured an API key, then stop the supervisor: claude daemon stop --any --keep-workers -The next `claude agents` or `claude --bg` starts a fresh supervisor that reads your stored credentials. If you authenticate with an environment variable such as `ANTHROPIC_API_KEY` rather than `/login`, run that next command from a shell where the variable is set. See the [error reference](</docs/en/errors#could-not-resolve-authentication-method>) for the full list of causes and fixes. Before v2.1.174, a pre-warmed worker that sat idle could surface this error when it was assigned to a dispatch even when your credentials were valid. Upgrade to recover. +The next `claude agents` or `claude --bg` starts a fresh supervisor that reads your stored credentials. If you authenticate with an environment variable such as `ANTHROPIC_API_KEY` rather than `/login`, run that next command from a shell where the variable is set. See the [error reference](</docs/en/errors#could-not-resolve-authentication-method>) for the full list of causes and fixes. ### @@ -540,7 +530,7 @@ A session is slow to respond after attaching -Once a session has finished and sat unattached for about an hour, the supervisor stops its process to free resources. Attaching starts a fresh process from where it left off, which takes a moment. Sessions that are working, waiting on you, or pinned are not stopped this way, so pin a session with `Ctrl+T` to keep it responsive. +Once a session has finished and sat unattached for about an hour, the supervisor stops its process to free resources. Attaching starts a fresh process from where it left off and switches to the session immediately while the process restarts. Sessions that are working, waiting on you, or pinned aren’t stopped this way, so pin a session with `Ctrl+T` to keep it responsive. ### @@ -573,3 +563,25 @@ * [Run agents in parallel](</docs/en/agents>): compare agent view with subagents, agent teams, and worktrees * [Agent teams](</docs/en/agent-teams>): coordinate multiple sessions that message each other * [Claude Code on the web](</docs/en/claude-code-on-the-web>): run sessions in a managed cloud environment instead of locally + +## + +​ + +Version history + +Agent view has evolved quickly during research preview. If you are on an older Claude Code version, some behavior on this page may differ; in particular, `claude agents` rejects flags it doesn’t yet support with an `unknown option` error. The table below lists when each flag and behavior was added. + +Version| Change +---|--- +v2.1.196| A single `←` press backgrounds a foreground session; earlier versions required two presses, with a footer hint and a confirm. `--dangerously-skip-permissions` passed to `claude agents` shows the bypass disclaimer instead of being silently dropped. Interactive sessions you never named carry a default name such as `my-app-3f` in session listings and `claude agents --json`. Background shell commands and dynamic workflows survive the session’s process being stopped, restarted, or updated, including on Windows; set `CLAUDE_CODE_DISABLE_BG_EXIT_HANDOFF=1` to turn the handoff off. A transcript misread as empty on restart is renamed with an `.orphaned-` suffix instead of deleted. +v2.1.195| In-flight work carries over when you background a session on Windows too; set `CLAUDE_DISABLE_ADOPT=1` to stop it instead. The `Completed` group fills the remaining vertical space and the header compacts on short terminals. An older Claude Code version no longer drops newer sessions’ `state.json` fields or hides those sessions from `claude agents`. Attaching to a stopped session switches immediately instead of showing a blank screen for up to five seconds. A supervisor that can’t accept connections exits and releases its lock on its own. +v2.1.174| Background sessions no longer inherit gateway endpoint variables such as `ANTHROPIC_BASE_URL` from the supervisor’s launch shell; the supervisor supplies a fresh credential snapshot to pre-warmed workers, fixing spurious `Could not resolve authentication method` errors. +v2.1.172| `/model` in the dispatch input sets a session-scoped dispatch model override. +v2.1.161| Row summaries show a `done/total` count for parallel work items; the peek panel names the longest-running parallel work item. +v2.1.157| `claude agents` accepts `--agent`; dispatched sessions honor the `agent` setting. +v2.1.145| Voice dictation supported in the peek-panel reply input and the dispatch input. +v2.1.143| `worktree.bgIsolation` setting added; `claude agents` accepts `--allow-dangerously-skip-permissions`. +v2.1.142| `claude agents` accepts `--permission-mode`, `--model`, `--effort`, `--dangerously-skip-permissions`, `--settings`, `--add-dir`, `--plugin-dir`, `--mcp-config`, and `--strict-mcp-config`. +v2.1.141| `claude agents` accepts `--cwd` to scope the list to one project. +v2.1.139| Agent view introduced as a research preview.
modified Claude Code on Amazon Bedrock View current →
--- a/amazon-bedrock.md +++ b/amazon-bedrock.md @@ -426,6 +426,14 @@ ​ +Zero token counts in /context + +The `/context` command counts tokens for each tool group by sending the tool schemas to the Bedrock count-tokens API. On Claude Code versions before v2.1.196, Bedrock rejected that request because the schemas carried fields its count-tokens API doesn’t accept, so every tool group showed 0 tokens. Other rows in the breakdown, such as messages and memory files, aren’t affected. Update to v2.1.196 or later. + +### + +​ + Mantle endpoint errors If `/status` does not show `Amazon Bedrock (Mantle)` after you set `CLAUDE_CODE_USE_MANTLE`, the variable is not reaching the process. Confirm it is exported in the shell where you launched `claude`, or set it in the `env` block of your [settings file](</docs/en/settings>). A `403` from the Mantle endpoint with valid credentials means your AWS account has not been granted access to the model you requested. Contact your AWS account team to request access. A `400` that names the model ID means that model is not served on Mantle. Mantle has its own model lineup separate from the standard Bedrock catalog, so inference profile IDs such as `us.anthropic.claude-sonnet-4-6` will not work. Use a Mantle-format ID, or enable both endpoints so Claude Code routes each request to the endpoint where the model is available.
modified Authentication View current →
--- a/authentication.md +++ b/authentication.md @@ -12,6 +12,7 @@ * **Claude for Teams or Enterprise** : log in with the Claude.ai account your team admin invited you to. * **Claude Console** : log in with your Console credentials. Your admin must have invited you first. * **Cloud providers** : if your organization uses [Amazon Bedrock](</docs/en/amazon-bedrock>), [Google Vertex AI](</docs/en/google-vertex-ai>), or [Microsoft Foundry](</docs/en/microsoft-foundry>), set the required environment variables before running `claude`. No browser login is needed. + * **Cloud gateway** : if your organization runs a self-hosted [Claude apps gateway](</docs/en/claude-apps-gateway>), sign in with corporate SSO through `/login`. The gateway-issued token is the session’s only credential. To log out and re-authenticate, type `/logout` at the Claude Code prompt. If you’re having trouble logging in, see [authentication troubleshooting](</docs/en/troubleshoot-install#login-and-authentication>). @@ -25,6 +26,7 @@ * Claude for Teams or Enterprise, recommended for most teams * Claude Console + * [Claude apps gateway](</docs/en/claude-apps-gateway>), a self-hosted gateway that signs developers in with your IdP and routes inference to the cloud provider you configure * [Amazon Bedrock](</docs/en/amazon-bedrock>) * [Google Vertex AI](</docs/en/google-vertex-ai>) * [Microsoft Foundry](</docs/en/microsoft-foundry>) @@ -141,7 +143,7 @@ * On Windows, credentials are stored in `%USERPROFILE%\.claude\.credentials.json` and inherit the access controls of your user profile directory, which restricts the file to your user account by default. * If you’ve set the `CLAUDE_CONFIG_DIR` environment variable on Linux or Windows, the `.credentials.json` file lives under that directory instead. * Claude Code manages `.credentials.json` through `/login` and `/logout`. To route requests through a custom API endpoint, set the [`ANTHROPIC_BASE_URL`](</docs/en/env-vars>) environment variable instead. - * **Supported authentication types** : Claude.ai credentials, Claude API credentials, Azure Auth, Bedrock Auth, and Vertex Auth. + * **Supported authentication types** : Claude.ai credentials, Claude API credentials, Azure Auth, Bedrock Auth, Vertex Auth, and [Claude apps gateway](</docs/en/claude-apps-gateway>) session tokens. * **Custom credential scripts** : the [`apiKeyHelper`](</docs/en/settings#available-settings>) setting can be configured to run a shell script that returns an API key. * **Refresh intervals** : by default, `apiKeyHelper` is called after 5 minutes or on HTTP 401 response. Set `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` environment variable for custom refresh intervals. * **Slow helper notice** : if `apiKeyHelper` takes longer than 10 seconds to return a key, Claude Code displays a warning notice in the prompt bar showing the elapsed time. If you see this notice regularly, check whether your credential script can be optimized. @@ -163,7 +165,7 @@ 5. `CLAUDE_CODE_OAUTH_TOKEN` environment variable. A long-lived OAuth token generated by `claude setup-token`. Use this for CI pipelines and scripts where browser login isn’t available. 6. Subscription OAuth credentials from `/login`. This is the default for Claude Pro, Max, Team, and Enterprise users. -If you have an active Claude subscription but also have `ANTHROPIC_API_KEY` set in your environment, the API key takes precedence once approved. This can cause authentication failures if the key belongs to a disabled or expired organization. Run `unset ANTHROPIC_API_KEY` to fall back to your subscription, and check `/status` to confirm which method is active. [Claude Code on the Web](</docs/en/claude-code-on-the-web>) always uses your subscription credentials. `ANTHROPIC_API_KEY` and `ANTHROPIC_AUTH_TOKEN` in the sandbox environment do not override them. +A signed-in [Claude apps gateway](</docs/en/claude-apps-gateway>) session sits outside this list: it is a provider selection like Bedrock or Vertex, and it outranks them. When a gateway session exists, the CLI authenticates with the gateway token even if `CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX`, or `CLAUDE_CODE_USE_FOUNDRY` is set, and the bearer token, API key, and `apiKeyHelper` entries above are not used. If you have an active Claude subscription but also have `ANTHROPIC_API_KEY` set in your environment, the API key takes precedence once approved. This can cause authentication failures if the key belongs to a disabled or expired organization. Run `unset ANTHROPIC_API_KEY` to fall back to your subscription, and check `/status` to confirm which method is active. [Claude Code on the Web](</docs/en/claude-code-on-the-web>) always uses your subscription credentials. `ANTHROPIC_API_KEY` and `ANTHROPIC_AUTH_TOKEN` in the sandbox environment do not override them. ###
modified Configure auto mode View current →
--- a/auto-mode-config.md +++ b/auto-mode-config.md @@ -1,12 +1,13 @@ [Auto mode](</docs/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. -Auto mode is available to all users on the Anthropic API. On Amazon Bedrock, Google Cloud Vertex AI, and Microsoft Foundry, you must first [set `CLAUDE_CODE_ENABLE_AUTO_MODE`](</docs/en/permission-modes#enable-auto-mode-on-bedrock-vertex-ai-or-foundry>). If Claude Code reports auto mode as unavailable for your account, check the [full requirements](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>), which also cover the supported models and Owner enablement on Team and Enterprise plans. +Auto mode is available to all users on the Anthropic API. On Amazon Bedrock, Google Cloud Vertex AI, Microsoft Foundry, and signed-in [Claude apps gateway](</docs/en/claude-apps-gateway>) sessions, you must first [set `CLAUDE_CODE_ENABLE_AUTO_MODE`](</docs/en/permission-modes#enable-auto-mode-on-bedrock-vertex-ai-or-foundry>). If Claude Code reports auto mode as unavailable for your account, check the [full requirements](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>), which also cover the supported models and Owner enablement on Team and Enterprise plans. By 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`. For how to enable auto mode and what it blocks by default, see [Permission modes](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>). This page is the configuration reference. This page covers how to: * Choose where to set rules across CLAUDE.md, user settings, and managed settings * Define trusted infrastructure with `autoMode.environment` * Override the block and allow rules when the defaults don’t fit your pipeline + * Route all shell commands through the classifier with `autoMode.classifyAllShell` * Inspect your effective config with the `claude auto-mode` subcommands * Review denials so you know what to add next @@ -35,7 +36,12 @@ Define trusted infrastructure -For most organizations, `autoMode.environment` is the only field you need to set. It tells the classifier which repos, buckets, and domains are trusted: the classifier uses it to decide what “external” means, so any destination not listed is a potential exfiltration target. The default environment list trusts the working repo and its configured remotes. To add your own entries alongside that default, include the literal string `"$defaults"` in the array. The default entries are spliced in at that position, so your custom entries can go before or after them. +For most organizations, `autoMode.environment` is the only field you need to set. It tells the classifier which repos, buckets, and domains are trusted: the classifier uses it to decide what “external” means, so any destination not listed is a potential exfiltration target. As of Claude Code v2.1.195, `claude auto-mode defaults` prints two kinds of environment entry. + + * **Trust slots** : name what the classifier treats as inside your boundary. The slots are Trusted repo, Source control, Trusted internal domains, Trusted cloud buckets, Key internal services, and Internal package registry. The repo and source-control entries default to the working repository and its configured remotes. Every other trust slot defaults to `None configured`, so nothing else is trusted until you add it. + * **Sensitivity slots** : name what the protective rules treat as high-risk. The slots are PII / regulated-data locations, Sensitive remote targets, and Protected IaC scopes. Each defaults to a broad heuristic, such as treating any host or namespace whose name carries `prod` or `production` as a sensitive remote target, so the protective rules are active before you configure anything. Naming concrete targets in a sensitivity slot makes those rules apply to the named targets instead of the heuristic. + +Versions before v2.1.195 print only the first five trust slots. To add your own entries alongside the defaults, include the literal string `"$defaults"` in the array. The default entries are spliced in at that position, so your custom entries can go before or after them. The following example keeps the default entries and adds an organization’s repos, buckets, domains, and services. { "autoMode": { @@ -56,9 +62,13 @@ * **Cloud providers and trusted buckets** : bucket names or prefixes that Claude should be able to read from and write to * **Trusted internal domains** : hostnames for APIs, dashboards, and services inside your network, like `*.internal.example.com` * **Key internal services** : CI, artifact registries, internal package indexes, incident tooling + * **Internal package registry** : the private npm, PyPI, or other registry that installs should route through, so installs that bypass it for a public registry get blocked + * **PII / regulated-data locations** : the buckets, databases, or paths that hold personal or regulated data, so the classifier protects those locations instead of guessing from content + * **Sensitive remote targets** : the namespaces, hosts, or containers that count as production, so remote shells and port-forwards into them need your explicit approval + * **Protected IaC scopes** : the infrastructure resources whose apply or destroy should always require you to name the change * **Additional context** : regulated-industry constraints, multi-tenant infrastructure, or compliance requirements that affect what the classifier should treat as risky -A useful starting template: fill in the bracketed fields and remove any lines that don’t apply. +The Internal package registry, PII / regulated-data locations, Sensitive remote targets, and Protected IaC scopes entries require Claude Code v2.1.195 or later. Earlier versions still read them as plain context but don’t have the built-in rules that target them. A useful starting template: fill in the bracketed fields and remove any lines that don’t apply. { "autoMode": { @@ -129,6 +139,24 @@ ​ +Route all shell commands through the classifier + +By default, narrow Bash and PowerShell allow rules such as `Bash(npm test)` carry over into auto mode and resolve before the classifier runs. Auto mode suspends only the broad rules that grant arbitrary code execution, such as `Bash(*)` or wildcarded interpreters. This means a narrow rule can still let a destructive argument through without the classifier seeing it, for example a script path or flag the rule’s prefix didn’t anticipate. Set `autoMode.classifyAllShell` to `true` to suspend every Bash and PowerShell allow rule while auto mode is active, so the classifier evaluates every shell command regardless of your allow list. + + { + "autoMode": { + "classifyAllShell": true + } + } + +This trades latency for coverage: a command that an allow rule would have approved instantly now waits for a classifier decision, and each shell command counts as a classifier call. The setting applies only while auto mode is active, and your allow rules behave normally in other permission modes. + +`autoMode.classifyAllShell` requires Claude Code v2.1.193 or later. Earlier versions ignore the key and continue to carry narrow shell allow rules into auto mode. + +## + +​ + Inspect the defaults and your effective config Three CLI subcommands help you inspect and validate your configuration. Print the built-in `environment`, `allow`, `soft_deny`, and `hard_deny` rules as JSON: @@ -151,7 +179,7 @@ Review denials -When auto mode denies a tool call, the denial is recorded in `/permissions` under the Recently denied tab. Press `r` on a denied action to mark it for retry: when you exit the dialog, Claude Code sends a message telling the model it may retry that tool call and resumes the conversation. Repeated denials for the same destination usually mean the classifier is missing context. Add that destination to `autoMode.environment`, then run `claude auto-mode config` to confirm it took effect. To react to denials programmatically, use the [`PermissionDenied` hook](</docs/en/hooks#permissiondenied>). +When auto mode denies a tool call, the denial is recorded in `/permissions` under the Recently denied tab. Press `r` on a denied action to mark it for retry: when you exit the dialog, Claude Code sends a message telling the model it may retry that tool call and resumes the conversation. In Claude Code v2.1.193 and later, the classifier’s reason for each denial appears alongside the blocked tool call in the transcript, in the denial notification, and under each entry on the Recently denied tab. Use the reason to decide whether the fix is an `environment` entry, an `allow` exception, or retrying with explicit intent in your next message. Repeated denials for the same destination usually mean the classifier is missing context. Add that destination to `autoMode.environment`, then run `claude auto-mode config` to confirm it took effect. To react to denials programmatically, use the [`PermissionDenied` hook](</docs/en/hooks#permissiondenied>). ##
added Claude apps gateway for Amazon Bedrock, Google Cloud, and Microsoft Foundry View current →
Show diff (316 lines)
--- a/claude-apps-gateway.md +++ b/claude-apps-gateway.md @@ -0,0 +1,313 @@ +If a third-party cloud isn’t a requirement, [Claude for Enterprise](</docs/en/authentication#claude-for-teams-or-enterprise>) is usually the better fit: richer admin capabilities, such as SCIM provisioning, and nothing to host. Claude for Enterprise subscriptions are available through AWS Marketplace, where purchases can count toward an AWS spend commitment. The gateway is designed for organizations that must route inference through their own cloud provider, for example to meet [data residency](</docs/en/claude-apps-gateway-deploy#compliance-posture>) requirements. + +Claude apps gateway is a self-hosted service that sits between your developers’ Claude Code clients and your model provider. Developers sign in with your corporate identity provider (IdP) instead of holding API keys or cloud credentials. The gateway holds the upstream credential, enforces model access and [managed settings](</docs/en/permissions#managed-settings>) by IdP group, and relays usage telemetry to your own observability stack. It is included in the `claude` binary, so the same executable that runs Claude Code on a laptop runs the gateway server with `claude gateway --config gateway.yaml`. This page covers: + + * Why Claude apps gateway, what it adds over running your own, and when something else fits better + * A quickstart with prerequisites that takes a gateway from zero to a signed-in developer + * Connecting developers, including setting the gateway URL through managed settings + * Availability and limitations covering which Claude Code features work through the gateway and what the server supports + +Companion pages go deeper. The [configuration reference](</docs/en/claude-apps-gateway-config>) covers every option in the YAML file the quickstart writes, and the [deployment guide](</docs/en/claude-apps-gateway-deploy>) covers per-IdP setup, Kubernetes and Cloud Run deployment, and operations. + +## + +​ + +Why Claude apps gateway + +The [gateway overview](</docs/en/gateways>) covers what a gateway does and why you’d run one. Claude apps gateway is Anthropic’s own gateway, built into the `claude` binary and tested alongside each Claude Code release, so it forwards the headers and request fields Claude Code sends without operators maintaining a separate allowlist. Once deployed it gives you: + + * **Credentials** : the upstream API key or cloud credential lives only in your infrastructure. Developers authenticate with corporate SSO and receive short-lived bearer tokens, so offboarding happens in your IdP. Deprovision a user and their gateway access expires within the session lifetime, one hour by default. + * **Access control** : your IdP groups map to model allowlists and [managed settings](</docs/en/permissions#managed-settings>) policies. The gateway enforces model access server-side, rejecting requests for non-granted models, and selects each group’s managed settings policy, which the CLI applies at the [managed settings tier](</docs/en/settings#settings-precedence>). Different teams get different models, tools, and permissions, and a developer can’t override what their policy locks. + * **Settings delivery** : the gateway delivers managed settings to signed-in clients itself, taking the place of [server-managed settings](</docs/en/server-managed-settings>) from the claude.ai admin console. + * **Telemetry** : each configured destination, such as Datadog, Splunk, or ClickHouse, receives [OpenTelemetry Protocol (OTLP) metrics](</docs/en/monitoring-usage>) with token counts, model, user identity, and latency by default, with logs and traces as per-destination opt-ins. + * **Upstream routing** : clients speak the Anthropic Messages API to the gateway, and the gateway translates for each upstream, whether Bedrock, Google Cloud’s Agent Platform, Foundry, or the Anthropic API, with failover between them. You can change regions, providers, or failover order without developers noticing or reconfiguring. + +The gateway’s own data plane sends nothing to Anthropic infrastructure unless the Anthropic API is a configured upstream. You control where telemetry, audit logs, managed settings, and your developers’ IdP identity go, and the gateway sends none of them to Anthropic. For the remaining traffic the CLI process can send and how to close it, see [Compliance posture](</docs/en/claude-apps-gateway-deploy#compliance-posture>). + +For which Claude Code features work through the gateway and what the server itself supports, see Availability and limitations below. For decisions such as cost, bypass, running multiple gateways, and serverless platforms, see the [deployment guide](</docs/en/claude-apps-gateway-deploy#deployment>). + +### + +​ + +Other gateway implementations + +If you already run an LLM gateway or API gateway that meets your needs, keep using it; [Other LLM gateways](</docs/en/llm-gateway>) covers configuring Claude Code against it. The [gateway protocol reference](</docs/en/llm-gateway-protocol>) documents the contract Claude Code expects from any gateway: the endpoints it calls, the headers and body fields to forward, and what stops working when they’re stripped. A running Claude apps gateway serves a superset of that contract at `GET /protocol`, adding the Claude apps gateway-specific endpoints for SSO sign-in, managed settings delivery, and telemetry. Fetch it with `curl https://claude-gateway.internal.example.com/protocol` from any deployed gateway, such as the one the quickstart below produces. Breaking changes to the protocol are announced in advance, but indefinite backwards compatibility isn’t guaranteed. + +## + +​ + +Quickstart + +This quickstart walks the minimal path: register an OAuth client in your IdP, write a `gateway.yaml`, run the gateway alongside Postgres with Docker Compose, and verify sign-in end to end. It uses an Amazon Bedrock upstream; Google Cloud’s Agent Platform, Foundry, and the Anthropic API are equally supported by swapping the `upstreams` block as shown in the [configuration reference](</docs/en/claude-apps-gateway-config#upstreams>). At the end you have a gateway a developer can `/login` to. + +**Deploy on your private network.** Claude Code only connects to a gateway whose address is private. This is a security guard, because a trusted gateway can push settings that run commands on developer machines. Put the gateway behind an internal load balancer or VPN and give it a hostname that resolves to private IPs only. + +### + +​ + +Prerequisites + +Have these in place before you start: + +You need| Details +---|--- +Claude Code v2.1.195 or later| The `claude gateway` subcommand and the gateway sign-in flow ship in v2.1.195. Earlier public builds don’t include them. Both the machine running the gateway server and each developer’s machine must be on v2.1.195 or later; run `claude update` to get the latest release. +OpenID Connect (OIDC) identity provider| Okta, Microsoft Entra ID, Google Workspace, Keycloak, or Dex, or any other OIDC-compliant IdP such as PingFederate. The gateway runs standard OIDC discovery and the authorization-code flow against it. SAML and LDAP are not supported. +PostgreSQL 14 or later| Backs the device sign-in flow, where the browser callback writes and the polling CLI reads, plus rate-limit counters. Any managed Postgres works, including the smallest tier. Without spend limits configured, the gateway stores a few KB of short-lived auth state; with [spend limits](</docs/en/claude-apps-gateway-spend-limits>), it also holds durable spend, audit, and identity tables that should be backed up. TLS via `?sslmode=require` is recommended. +Model upstream| Amazon Bedrock credentials, Google Cloud credentials, a Microsoft Foundry resource, or an Anthropic API key. Multiple upstreams are supported with failover. +HTTPS| The gateway must be reachable over `https://` from developer laptops and from any browser used for sign-in; the gateway serves the device-verification page on the same listener. Either provide a TLS cert via `listen.tls`, or run behind a TLS-terminating ingress and set `listen.public_url`. A plain `http://` origin is accepted only on loopback, for local development. +Private-network address| At `/login`, Claude Code requires the gateway’s hostname or IP address to resolve only to private addresses: RFC 1918, CGNAT `100.64.0.0/10`, IPv6 ULA `fc00::/7`, or loopback for local development. The check runs on each resolved IP, so if any address the name resolves to is public, `/login` rejects the URL. If developer machines route HTTPS through a corporate proxy, sign-in also requires the proxy host to resolve to private addresses; if it doesn’t, add the gateway host to `NO_PROXY` so the CLI connects directly. +Linux runtime| The gateway server runs only on the native Linux binary. macOS works for local development. Windows is not supported as a server platform. + +The gateway server requires the native `claude` binary; download a pinned release as described in [Install Claude Code](</docs/en/setup>). The server uses runtime features that aren’t available when Claude Code runs under Node. If you see `requires the native binary` at boot, switch to one of the standalone install methods. + +### + +​ + +Steps + +1 + +Register an OAuth client in your IdP + +Decide the gateway’s hostname first, because the redirect URI must match it. Create a new OIDC web application and set the redirect URI to `https://claude-gateway.<your-domain>/oauth/callback`, where the host is the same value you set as [`listen.public_url`](</docs/en/claude-apps-gateway-config#listen>) in step 3. Note the `client_id` and `client_secret`. Per-IdP instructions are in [Identity provider setup](</docs/en/claude-apps-gateway-deploy#identity-provider-setup>). + +2 + +Provision a PostgreSQL database + +Any Postgres 14 or later works, including the smallest managed tier. The gateway runs its own schema migrations at boot, so the database user needs `CREATE TABLE` permission. If your security policy prohibits DDL from application roles, pre-create the schema instead; see [`store`](</docs/en/claude-apps-gateway-config#store>). + +3 + +Write gateway.yaml + +Secrets are read via `${ENV_VAR}` expansion so the file itself can live in version control. Use a `public_url` hostname that resolves to a private IP on your network, because `/login` rejects public addresses. The minimal config has five sections, and every other field has a default: + +gateway.yaml + + listen: + host: 0.0.0.0 + port: 8080 + # Required behind any TLS-terminating proxy. Used for the IdP + # redirect_uri and the discovery document. + public_url: https://claude-gateway.internal.example.com + + oidc: + issuer: https://login.example.com # must serve /.well-known/openid-configuration + client_id: 0oa1example2 + client_secret: ${OIDC_CLIENT_SECRET} + allowed_email_domains: [example.com] # reject id_tokens outside your org + userinfo_fallback: true # for IdPs whose id_token omits email/groups; harmless otherwise + + session: + jwt_secret: ${GATEWAY_JWT_SECRET} # openssl rand -base64 32 + ttl_hours: 1 # also bounds revocation latency on IdP deprovision + + store: + postgres_url: ${GATEWAY_POSTGRES_URL} # add ?sslmode=require for managed Postgres + + upstreams: + - provider: bedrock + region: us-east-1 + auth: {} # empty: AWS default credential chain + # (IRSA, EC2/ECS task role, env vars, ~/.aws) + + # Models are translated per upstream automatically. The built-in catalog + # maps claude-opus-4-8 to us.anthropic.claude-opus-4-8 and so on for every + # Bedrock-supported Claude model. Set false and add a `models:` list to + # expose only specific models. + auto_include_builtin_models: true + +This config is enough for a working sign-in loop with the default Bedrock model catalog. Once it’s running, add per-group RBAC and managed settings via [`managed.policies`](</docs/en/claude-apps-gateway-config#managed>), telemetry fan-out via [`telemetry`](</docs/en/claude-apps-gateway-config#telemetry>), and multi-upstream failover, provisioned-throughput ARNs, or non-US regions via [`models`](</docs/en/claude-apps-gateway-config#models>). + +The Bedrock upstream needs an AWS principal with `bedrock:InvokeModel` and `bedrock:InvokeModelWithResponseStream` on both the `inference-profile/us.anthropic.*` ARNs and the underlying `foundation-model/anthropic.*` ARNs, and model access enabled in the Bedrock console for the Claude models you want. Supply the credential with IRSA on EKS, an ECS task role, or an EC2 instance profile rather than static keys. The [`upstreams` reference](</docs/en/claude-apps-gateway-config#upstreams>) has the full IAM details, the cross-cloud credential matrix, and the `auth` blocks for the other providers. + +4 + +Run it + +Build a container image around the `claude` binary that meets the [image requirements](</docs/en/claude-apps-gateway-deploy#container-image>), then run it alongside Postgres: + +docker-compose.yaml + + services: + gateway: + image: <your-registry>/claude-gateway:<version> + ports: ["8080:8080"] + volumes: ["./gateway.yaml:/etc/claude/gateway.yaml:ro"] + environment: + OIDC_CLIENT_SECRET: ${OIDC_CLIENT_SECRET} + GATEWAY_JWT_SECRET: ${GATEWAY_JWT_SECRET} + GATEWAY_POSTGRES_URL: postgres://gw:pw@postgres/gateway + # AWS credentials: in production, omit these and use an instance + # role. For local Compose testing, pass through your own: + AWS_ACCESS_KEY_ID: ${AWS_ACCESS_KEY_ID} + AWS_SECRET_ACCESS_KEY: ${AWS_SECRET_ACCESS_KEY} + AWS_SESSION_TOKEN: ${AWS_SESSION_TOKEN} + depends_on: + postgres: + condition: service_healthy + postgres: + image: postgres:16-alpine + environment: { POSTGRES_USER: gw, POSTGRES_PASSWORD: pw, POSTGRES_DB: gateway } + healthcheck: + test: ["CMD-SHELL", "pg_isready -U gw"] + interval: 5s + volumes: ["pgdata:/var/lib/postgresql/data"] + volumes: { pgdata: } + +The gateway is a single Linux binary that reads the config, runs OIDC discovery against your IdP, applies its Postgres schema migrations, builds upstream clients, and starts listening. Boot is fail-closed for the config, the Postgres connection with a 5-second timeout, OIDC discovery, and upstream client construction. If any of those is unreachable or misconfigured, the gateway exits with an error rather than serving traffic in a degraded state.A successful boot doesn’t validate the inference path, because Bedrock and Agent Platform instance credentials resolve on the first request, not at boot.Watch stderr for the boot sequence. Log lines use the format `[gateway] <timestamp> <level> <message>`, audit events are single-line JSON with an `evt` field, and a startup banner, omitted below, prints between the migration and listening lines. You should see, in order: + + {"ts":"2026-06-10T17:03:21.114Z","evt":"config.load","path":"/etc/claude/gateway.yaml","sha256":"…"} + [gateway] 2026-06-10T17:03:21.408Z info migration 1 applied + [gateway] 2026-06-10T17:03:21.512Z info claude gateway listening on http://0.0.0.0:8080 + +If boot exits before the `claude gateway listening on` line, the last line of stderr names the problem: + + * an unreachable Postgres + * a Postgres role without DDL permission + * an unreachable or invalid OIDC discovery document + * a config schema violation with the offending field path + +Fix it and restart.If you already have a TLS-terminating ingress, skip Compose and run the binary directly with `claude gateway --config gateway.yaml`. Set `public_url` to the ingress origin and bind `listen` to a loopback or cluster-internal address. + +5 + +Verify the auth surface + +Three checks confirm the gateway can authenticate a real user before you hand it to a developer.The examples use the gateway’s public URL; for the local Compose setup without an ingress, substitute `http://localhost:8080` in the first two checks. The third check opens `verification_uri_complete`, which is built from `public_url`, so for local Compose set `public_url: http://localhost:8080` in `gateway.yaml`, and add `http://localhost:8080/oauth/callback` as a second redirect URI on the OAuth client from step 1, because the gateway builds the IdP `redirect_uri` from `public_url`. The verification link then opens in your local browser.In Windows PowerShell, run `curl.exe`; the bare `curl` is an alias for `Invoke-WebRequest` and rejects these flags.First, fetch the discovery document, which confirms the gateway is up, the config is valid, and all boot checks passed: + + curl -s https://claude-gateway.internal.example.com/.well-known/oauth-authorization-server | jq + + { + "issuer": "https://claude-gateway.internal.example.com", + "device_authorization_endpoint": "…/oauth/device_authorization", + "token_endpoint": "…/oauth/token", + "grant_types_supported": ["urn:ietf:params:oauth:grant-type:device_code", "refresh_token"] + } + +The response includes additional fields, such as `response_types_supported` and `scopes_supported`.Second, request a device authorization, which confirms the device sign-in flow works and Postgres is reachable and writable: + + curl -s -X POST https://claude-gateway.internal.example.com/oauth/device_authorization | jq + + { + "device_code": "…", + "user_code": "WDJB-MJHT", + "verification_uri": "https://claude-gateway.internal.example.com/device", + "verification_uri_complete": "https://claude-gateway.internal.example.com/device?user_code=WDJB-MJHT", + "expires_in": 600, + "interval": 5 + } + +Third, test the browser leg by opening `verification_uri_complete` in a browser and confirming the code. You should be redirected to your IdP’s sign-in page, and after signing in, land back on the gateway with a signed-in confirmation.Use the first failing check to locate the problem: + + * **First check fails** : boot didn’t complete; check stderr + * **Second check fails** : Postgres isn’t reachable from the gateway or the role can’t write; check the connection string and grants + * **Third check doesn’t reach the IdP** : check that the IdP’s redirect URI matches `https://<gateway>/oauth/callback` exactly + * **Third check reaches the IdP but bounces back with an error** : read the gateway’s audit log, which records every auth rejection with the reason, such as `email domain not allowed` + +6 + +Log a developer in + +This last step happens on a developer machine, not the server. Set `forceLoginMethod` to `"gateway"` and `forceLoginGatewayUrl` to your gateway’s `public_url` in that machine’s [managed settings file](</docs/en/settings#settings-files>), then run `/login`, press Enter on the **Cloud gateway** screen, and complete the browser sign-in. Set the gateway URL below covers distributing both keys at scale. + +## + +​ + +Connect developers + +Developers connect from their own laptops with one browser sign-in, using their corporate work account. They don’t need a claude.ai account, an API key, or a subscription, because requests to the model go through the gateway using the organization’s upstream credential. Connection is driven by the [client-side managed settings](</docs/en/claude-apps-gateway-config#client-side-managed-settings>) you push via MDM, so there is no manual setup on the developer side; this section covers what the admin configures. The CLI fingerprints the gateway’s TLS leaf certificate on first connect and pins it per hostname. Publish the expected SHA-256 fingerprint alongside the gateway URL so developers have something to compare against. Get the fingerprint from the certificate file with `openssl x509 -noout -fingerprint -sha256 -in cert.pem`; the `/login` prompt shows the first 16 characters of the digest as lowercase hexadecimal with no separators. When the certificate rotates, every developer sees the trust prompt again, so treat rotations as a planned event and republish the fingerprint. Once signed in, the [model picker](</docs/en/model-config>) shows the models in the developer’s `availableModels` allowlist, managed settings apply at startup and refresh hourly, and telemetry routes to your collector. Sessions refresh silently before `ttl_hours` expiry, and a failed refresh after IdP deprovisioning prompts a re-login. + +### + +​ + +Set the gateway URL + +Set both keys in the per-OS [managed settings file](</docs/en/settings#settings-files>) you deploy via MDM or directly on disk, and `/login` opens directly on the **Cloud gateway** screen with the URL filled in: + + { + "forceLoginMethod": "gateway", + "forceLoginGatewayUrl": "https://claude-gateway.internal.example.com" + } + +The developer presses Enter to connect. The first-connect TLS fingerprint prompt still appears. There is no gateway option in the login picker for a developer to select manually, and `forceLoginGatewayUrl` is ignored in a developer’s own settings files. `forceLoginMethod` alone, without a URL, leaves the developer at a “Contact your IT administrator” message. Both keys belong in the file you push to machines, not in the gateway’s `managed.policies[].cli` block, which only reaches clients that are already connected. + +### + +​ + +CI pipelines and remote machines + +There is no service-token flow for unattended pipelines. Gateway sign-in always runs the browser device flow, so a CI job with no developer to approve the sign-in can’t authenticate; configure those against your provider directly. Once a developer has signed in, every Claude Code invocation on that machine uses the gateway session, including non-interactive `claude -p` runs and sessions started by the Agent SDK, and the [gateway policy applies to all of them](</docs/en/claude-apps-gateway-config#managed>). The device flow separates the polling CLI from the approving browser, so a remote development box with no display still works: the developer runs `/login` over SSH on the remote machine and opens the verification link in the browser on their laptop. + +### + +​ + +What’s enforced on developers + +These guarantees apply to every signed-in gateway session. + + * **Model access** : requests for models the policy doesn’t grant return 400, and the `/model` picker is filtered to the policy’s `availableModels` allowlist. Set [`enforceAvailableModels: true`](</docs/en/model-config#default-model-behavior>) in the policy so the Default option resolves to a model inside `availableModels` instead of to Claude Code’s built-in default; without it, Default stays selectable and is rejected at request time if that model isn’t granted. + * **Telemetry destination** : when [telemetry forwarding](</docs/en/claude-apps-gateway-config#telemetry>) is configured, the OTLP export endpoint is pinned to the gateway, and the gateway-pushed configuration overrides locally set `OTEL_*` variables. + * **Credentials** : the gateway token is the session’s only credential. `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_API_KEY`, `apiKeyHelper`, and any earlier claude.ai login are ignored while signed in, so developers don’t need to log out of claude.ai first. + * **Managed settings** : locked keys can’t be overridden locally. The CLI applies the policy at startup and on each hourly poll. + * **Startup** : signed-in sessions exit at startup with an error after about 10 seconds when the gateway is unreachable, rather than starting without their settings. + * **Deprovisioning** : a session whose user is disabled in the IdP expires within `ttl_hours` when the next refresh fails. + +### + +​ + +What the organization can see + +Usage telemetry carries the developer’s identity, token counts, model, and latency to the organization’s collector. The gateway doesn’t log or store prompt or completion content. Whether richer telemetry such as logs and traces is collected, which can include commands and file paths, is the organization’s [per-destination choice](</docs/en/claude-apps-gateway-config#telemetry>). + +## + +​ + +Availability and limitations + +The table covers which Claude Code features work when developers connect through the gateway, and what the gateway server itself supports. Where something isn’t supported, the Notes column gives the alternative. The gateway delivers the [`anthropic-beta`](<https://platform.claude.com/docs/en/api/beta-headers>) values the CLI sends to every upstream, so operators don’t maintain a beta allowlist. For Bedrock, which ignores the header, the gateway moves the values into the request body’s `anthropic_beta` field; the other upstreams receive the header as sent. The CLI’s gateway-session beta set omits first-party-only betas and the extended-cache-ttl beta, which is why those rows below show as not available. + +Feature| Status| Notes +---|---|--- +Inference forwarding (Bedrock, Agent Platform, Foundry, Anthropic)| Available| With per-upstream model translation and failover. The Bedrock upstream uses the `bedrock-runtime` endpoint and the AWS default credential chain; the Bedrock [Mantle endpoint](</docs/en/amazon-bedrock#use-the-mantle-endpoint>) is not a supported upstream. +Model access and managed settings by IdP group| Available| Model access is enforced server-side; managed settings are delivered per IdP group and applied by the CLI at the [managed settings tier](</docs/en/settings#settings-precedence>) +Telemetry fan-out (OTLP/HTTP)| Available| Identity-stamped per export; both protobuf and JSON encodings +OIDC identity providers| Available| Any OIDC-compliant IdP; the gateway runs standard OIDC discovery and the authorization-code flow. See [Identity provider setup](</docs/en/claude-apps-gateway-deploy#identity-provider-setup>) for per-IdP configuration +Per-user and per-group spend limits| Available| See [Spend limits](</docs/en/claude-apps-gateway-spend-limits>) +Server-side web search| Not available| The CLI can’t see which upstream provider the gateway routes to, so it can’t verify web search support and disables WebSearch on gateway sessions +Standard prompt caching| Available| `cache_control` breakpoints are forwarded to every upstream +1-hour cache TTL| Not available| The CLI omits the extended-cache-ttl beta on gateway sessions, because not every upstream the gateway can route to supports the 1-hour TTL, so prompt caching through the gateway uses the 5-minute TTL; see the beta-header note above +Auto mode| Available with opt-in| Follows the [third-party provider rules](</docs/en/permission-modes#enable-auto-mode-on-bedrock-vertex-ai-or-foundry>): set `CLAUDE_CODE_ENABLE_AUTO_MODE=1`, deliverable through the managed policy `env` block, and only the Opus models eligible on third-party providers can use it +First-party-only optimizations such as global cache scope and token-efficient tools| Not available| The CLI doesn’t enable them on gateway sessions; see the beta-header note above +OTLP/gRPC| Not supported| OTLP over HTTP only +SAML, LDAP, and other non-OIDC auth| Not supported| OIDC only. Front with an OIDC bridge if needed +Multi-tenant (multiple OIDC issuers)| Not supported| One issuer per gateway. Run separate instances +Windows server| Not supported| Deploy on Linux. macOS for local development only +Helm chart| Not available| The gateway runs as a standard stateless Deployment; see the [deployment guide](</docs/en/claude-apps-gateway-deploy#kubernetes>) +Admin UI| Not available| Configuration is the YAML file; redeploy to change it + +## + +​ + +Next steps + +The quickstart leaves you with a minimal config running under Docker Compose. To take it further: + + * Expand `gateway.yaml` beyond the minimal config, for example to add per-group RBAC, multi-upstream failover, or telemetry destinations. The [configuration reference](</docs/en/claude-apps-gateway-config>) covers every option. + * Move from Compose to a production deployment on Kubernetes or Cloud Run, set up your IdP properly, and review the security model. The [deployment and operations guide](</docs/en/claude-apps-gateway-deploy>) covers per-IdP setup, container image requirements, health probes, and troubleshooting. + * Put spend caps on individual developers or groups so a runaway workload can’t consume your whole commitment. [Spend limits](</docs/en/claude-apps-gateway-spend-limits>) covers the admin API and how enforcement works. + * For a complete worked example on Google Cloud, with Cloud Run, Cloud SQL, and Secret Manager, see [Deploy on Google Cloud](</docs/en/claude-apps-gateway-on-gcp>).
added Claude apps gateway configuration View current →
Show diff (722 lines)
--- a/claude-apps-gateway-config.md +++ b/claude-apps-gateway-config.md @@ -0,0 +1,719 @@ +A Claude apps gateway deployment is configured by one YAML file, conventionally `gateway.yaml`. The file defines everything the gateway does: where it listens, how developers sign in, where inference goes, and which policies and telemetry apply. This page is the reference for every option in that file. To write your first one, start from the [quickstart](</docs/en/claude-apps-gateway#quickstart>), which builds a minimal working config and runs it; once you have a config you’re happy with, the [deployment guide](</docs/en/claude-apps-gateway-deploy>) covers containerizing and hosting it on Kubernetes, Cloud Run, or your own platform. The gateway reads the file once, at startup, with `claude gateway --config /path/to/gateway.yaml`. Every option is validated against a schema at boot, so a malformed config fails at start with a field-level error rather than at first use. The complete example at the end of this page exercises every section. + +## + +​ + +File structure + +Five sections are required. Every other section is optional, and an omitted section takes its defaults. Unknown keys fail boot, so a typo surfaces as a named error rather than a silently ignored setting. **Required sections:** + + * `listen`: bind address, public URL, TLS termination + * `oidc`: your identity provider (IdP), including issuer, client, claim mapping, and who may sign in + * `session`: the bearer tokens the gateway mints, with secret and lifetime + * `store`: PostgreSQL, for device grants and rate-limit counters + * `upstreams`: where inference goes, whether Anthropic, Bedrock, Agent Platform, or Foundry + +**Optional sections:** + + * `admin`: Admin API auth and retention for spend limits + * `enforcement`: spend-limit fail-open or fail-closed behavior + * `models` and `auto_include_builtin_models`: admin-curated model list and per-upstream IDs + * `managed`: managed settings policies by IdP group + * `telemetry`: OTLP forwarding to your observability stack + * `access_control`, `limits`, `timeouts`, `rate_limits`: IP allow/deny, request size caps, upstream time-to-first-byte, and per-IP sign-in limits + +## + +​ + +Secret expansion + +Don’t write secrets such as `client_secret`, `jwt_secret`, or `postgres_url` directly in `gateway.yaml`. Reference them with one of the forms below, and the gateway resolves the value at boot from an environment variable or a file: + +Form| Resolves to| Use for +---|---|--- +`${VAR}`| The environment variable `VAR`. Boot fails if undefined.| Container environment variables, AWS Secrets Manager via env injection +`${file:/path}`| File contents, trimmed| Kubernetes Secret volume mounts, Vault Agent, SOPS + +## + +​ + +Required sections + +### + +​ + +`listen` + +The `listen` block controls where the gateway serves: the bind address and port, the externally visible origin, and optional TLS termination. + +Field| Required| Description +---|---|--- +`host`| No| Bind address. Default `0.0.0.0`. +`port`| No| Bind port. Default `8080`. +`public_url`| Behind a proxy| The externally visible `https://` origin, used to build the IdP `redirect_uri` and discovery metadata. Required behind any TLS-terminating proxy such as an ALB, Ingress, or Cloud Run, because the gateway doesn’t trust `X-Forwarded-*` headers when constructing its own origin; they are client-spoofable. `trusted_proxies` below governs client-IP resolution only. Also required to enable telemetry, because the gateway builds the OTLP endpoint it pushes to clients from this URL. +`tls.cert` / `tls.key`| No| PEM paths if the gateway terminates TLS itself +`trusted_proxies`| No| CIDRs or IPs of load balancers in front of the gateway. When set, the gateway trusts `X-Forwarded-For` only from these peers and records the real client IP for per-IP rate limiting and audit. Equivalent to nginx `set_real_ip_from`. + +### + +​ + +`oidc` + +OpenID Connect (OIDC) is the SSO protocol the gateway uses with your identity provider; see [Identity provider setup](</docs/en/claude-apps-gateway-deploy#identity-provider-setup>) for what to register on the IdP side. The `oidc` block connects the gateway to your identity provider and decides who can sign in. It names the issuer and OAuth client, maps the claims that carry email and groups, and restricts sign-in by email domain or group. + +Field| Required| Description +---|---|--- +`issuer`| Yes| OIDC discovery base. Must serve discovery at `/.well-known/openid-configuration`. Use HTTPS in production; the gateway accepts an `http://` issuer. A loopback issuer such as `http://localhost:8081` is rejected by the [SSRF guard](</docs/en/claude-apps-gateway-deploy#threat-model-summary>) unless `CLAUDE_GATEWAY_ALLOW_LOOPBACK=1` is set in the gateway’s environment. +`client_id` / `client_secret`| Yes| From your OAuth client registration +`allowed_email_domains`| No| Reject id_tokens whose `email` claim isn’t in one of these domains, case-insensitive. Defense-in-depth against multi-tenant IdP misconfiguration. Independent of this setting, an id_token whose `email_verified` claim is explicitly `false` is always rejected. +`allowed_groups`| No| Restrict sign-in to members of these IdP groups, matched against `groups_claim`. A user in an allowed email domain but in none of these groups is rejected. Requires the IdP to emit the groups claim. +`groups_claim`| No| Which id_token claim carries group membership. Default `groups`. Microsoft Entra emits app roles under `roles`. Accepts a flat key or an RFC 6901 JSON Pointer such as `/resource_access/gateway/roles` for nested claims. +`google_groups`| No| Look up the signed-in user’s groups through the Google Workspace Admin SDK Directory API, because Google’s id_token carries no groups claim. Set `service_account_json_path` to a service-account key file with domain-wide delegation on the `https://www.googleapis.com/auth/admin.directory.group.readonly` scope, and `admin_email` to a Workspace administrator the service account impersonates; the Directory API requires a real admin subject. Each user’s group email addresses become their groups claim, so `allowed_groups` and `managed.policies.match.groups` match on group emails. +`email_claim`| No| Which id_token claim carries the user’s email. Default `email`. Some IdPs, such as ADFS and Entra B2C, emit `upn` or `preferred_username` instead. Accepts a flat key, a JSON Pointer, or a list of fallback keys where the first present key is used. +`scopes`| No| Full override of the OIDC scopes the gateway requests. Default `[openid, profile, email, offline_access]`. Set when your IdP rejects scopes it doesn’t recognize, or requires a custom scope to emit groups or email. Must include `openid`. Dropping `offline_access` disables refresh tokens, so developers re-run the browser login every `session.ttl_hours`. See [Identity provider setup](</docs/en/claude-apps-gateway-deploy#identity-provider-setup>) for per-IdP scope recipes such as Google’s refresh-token flow. +`extra_auth_params`| No| Extra query parameters appended to the IdP authorization request, verbatim. This is the override mechanism for IdP-specific behavior, such as `access_type: offline` for Google refresh tokens, `domain_hint` for some Entra tenants, or `acr_values` for step-up flows. Cannot override the gateway-managed protocol params: `state`, `nonce`, `redirect_uri`, PKCE, `scope`, `response_type`, `response_mode`, and `client_id`. +`userinfo_fallback`| No| When the id_token omits email or groups, fetch them from `/userinfo`. Needed for Keycloak lightweight access tokens, the Okta org server, and ADFS minimal tokens. The id_token stays authoritative; userinfo only fills gaps. Default `false`. +`use_pkce`| No| Send a PKCE (S256) challenge on the authorization request. Default `true`. Set `false` only if your IdP rejects PKCE for this confidential client. +`clock_skew_seconds`| No| Tolerate clock drift when validating id_token time claims. Default `0`, which is strict. Raise if you see “token expired / not yet valid” errors right after sign-in due to host/IdP clock skew. +`token_endpoint_auth_method`| No| Override the token-endpoint auth method. Accepts `client_secret_basic` or `client_secret_post`. Auto-negotiated by default. +`id_token_signed_response_alg`| No| Expected id_token signing algorithm. Default `RS256`. Set for IdPs that sign with ES256, PS256, or EdDSA. +`additional_authorized_parties`| No| Extra `azp` values to accept beyond `client_id`, for Keycloak broker and token-exchange flows +`discovery_url`| No| Fetch the discovery document from this URL instead of deriving it from `issuer`, for IdPs behind a proxy that rewrites the issuer host. The path must contain `/.well-known/`. +`form_action_origins`| No| Additional origins for the `/device` page’s `Content-Security-Policy: form-action` directive. The gateway already allows `'self'` and the discovered `authorization_endpoint` origin, but Chrome enforces `form-action` against the entire redirect chain. If your IdP redirects through a second host, such as Azure AD federated to ADFS, hub-spoke Okta, or a corporate SSO interceptor, list every origin the authorization request may redirect through. +`ca_cert_pem`| No| PEM CA cert that replaces the system trust store for IdP requests only. Use for Keycloak or Dex behind corporate PKI. + +### + +​ + +`session` + +The `session` block shapes the bearer tokens the gateway mints after sign-in: the secret that signs them and how long they live. + +Field| Required| Description +---|---|--- +`jwt_secret`| Yes| At least 32 bytes of entropy, for example from `openssl rand -base64 32`. Signs the gateway’s HS256 bearer tokens. Accepts a single string or an array for rotation: index 0 signs and all entries verify. To rotate, prepend a new secret, wait `ttl_hours`, then drop the old one. +`ttl_hours`| No| Gateway bearer token lifetime. Default `1`. The CLI silently refreshes before expiry when the IdP issues refresh tokens. A shorter lifetime deprovisions faster; a longer one makes fewer IdP round-trips. If your IdP can’t issue refresh tokens because `offline_access` is unavailable, there is no silent refresh, so raise this to `8` or `12` to avoid sending developers back to the browser login every hour. + +### + +​ + +`store` + +The `store` block points the gateway at its PostgreSQL database, which holds device grants and rate-limit counters. + +Field| Required| Description +---|---|--- +`postgres_url`| Yes| `postgres://` or `postgresql://` URL. Required: the device-grant rendezvous, where the browser callback writes and the polling CLI reads, needs cross-replica state. The gateway runs its own schema migrations at boot, so the role needs `CREATE TABLE` on the target schema. If your security policy prohibits DDL from the application role, run the migrations with an admin role, initially and again whenever a new release ships migrations, and grant the app role `SELECT, INSERT, UPDATE, DELETE` on the gateway’s tables. See [Upgrades](</docs/en/claude-apps-gateway-deploy#upgrades>) and [Postgres](</docs/en/claude-apps-gateway-deploy#postgres>). +`username`| No| Overrides the user in `postgres_url` +`password`| No| Database credential. Set it here rather than in `postgres_url` so the credential stays out of the URL. Accepts any characters and takes precedence over URL credentials. +`max_connections`| No| Postgres connection-pool size per replica. Default `5`, which is conservative and friendly to shared databases. With spend limits enabled, the hot path does a few operations per inference request, so raise it for a dedicated database under load, and keep replicas × this below the database’s `max_connections`. + +For local development, point `postgres_url` at a throwaway Postgres container, for example `docker run --rm -p 5432:5432 -e POSTGRES_HOST_AUTH_METHOD=trust postgres`. + +### + +​ + +`upstreams` + +`upstreams` is an ordered list. The gateway forwards inference to the first upstream that resolves the requested model. On `5xx`, `429`, or timeout it fails over to the next; other `4xx` doesn’t, because those errors are attributable to the request rather than the upstream. Multiple upstreams of the same provider must set a distinct `name:`. Bedrock, Agent Platform, and Foundry clients are built once at startup, and their SDKs refresh credentials internally, so rotating cloud credentials doesn’t require a restart. Static Anthropic API keys and bearers are read at startup; see Anthropic API. + +#### + +​ + +Anthropic API + +The minimal Anthropic upstream is an API key from the [Claude Console](<https://platform.claude.com>): + + upstreams: + - provider: anthropic + auth: + api_key: ${ANTHROPIC_API_KEY} + # OR an OAuth bearer (e.g. a Workload-Identity-Federation-exchanged token): + # oauth_token: ${file:/var/run/secrets/anthropic-oauth-token} + # base_url: https://api.anthropic.com # default; override for a forward proxy + +The two credential forms differ in the header they send: + + * **`api_key`** : sends `x-api-key`. Rotate it in the Claude Console and update the env var. + * **`oauth_token`** : sends `Authorization: Bearer`. Use the bearer form when your org issues short-lived tokens instead of long-lived API keys. The bearer is read once at startup, so refresh by remounting the secret and restarting. + +Instead of a static key or bearer, you can use Workload Identity Federation. Create a federation rule by following the [Workload Identity Federation guide](<https://platform.claude.com/docs/en/manage-claude/workload-identity-federation>), then mount your workload’s OIDC JWT as a file, such as a Kubernetes projected service-account token or a CI platform’s id-token. The gateway exchanges the JWT for a short-lived bearer and refreshes it automatically. The token file is re-read on every exchange, so rotated projected tokens are picked up without a restart. + + upstreams: + - provider: anthropic + auth: + federation_rule_id: ${ANTHROPIC_FEDERATION_RULE_ID} + organization_id: ${ANTHROPIC_ORGANIZATION_ID} + identity_token_file: /var/run/secrets/anthropic/id-token + # workspace_id: wrkspc_... # required if the rule covers >1 workspace + # service_account_id: svac_... # optional expected-target check + +#### + +​ + +Amazon Bedrock + +For the client-side Bedrock deployment that the gateway replaces or fronts, see [Claude Code on Amazon Bedrock](</docs/en/amazon-bedrock>). The gateway-side upstream: + + upstreams: + - provider: bedrock + region: us-east-1 + auth: {} # preferred: AWS default credential chain + # OR explicit credentials: + # auth: + # aws_access_key_id: ${AWS_AKID} + # aws_secret_access_key: ${AWS_SK} + # aws_session_token: ${AWS_ST} + # OR a Bedrock API bearer token: + # auth: + # aws_bearer_token: ${AWS_BEARER_TOKEN} + # Override the bedrock-runtime endpoint for FIPS or VPC-endpoint deployments: + # base_url: https://bedrock-runtime-fips.us-east-1.amazonaws.com + +An empty `auth` block uses the AWS SDK’s default credential chain: env vars, `~/.aws/credentials`, ECS task role, EC2 instance metadata, or IRSA on EKS. In production, give the gateway pod an IAM role instead of embedding static keys in a container image. + +Setup| How +---|--- +IAM permissions| Grant the gateway’s principal `bedrock:InvokeModel` and `bedrock:InvokeModelWithResponseStream` on both the inference-profile ARNs and the underlying foundation-model ARNs. For the built-in catalog in US regions: `arn:aws:bedrock:<region>:<account>:inference-profile/us.anthropic.*` and `arn:aws:bedrock:*::foundation-model/anthropic.*`. +Model access| In the Bedrock console, per region, request and enable model access for the Claude models you want. Cross-region inference profiles (`us.anthropic.*`) require model access in each region the profile spans. +EKS (IRSA)| Create an IAM role with the policy above and a trust policy for your cluster’s OIDC provider scoped to the gateway’s service account. Annotate the service account with `eks.amazonaws.com/role-arn: arn:aws:iam::<acct>:role/claude-gateway`. `auth: {}` picks it up. +ECS / EC2| Attach the IAM role to the task definition or instance profile. `auth: {}` picks it up. +Anywhere else| Pass credentials via the `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN` env vars, or set them explicitly in `auth:` with `${VAR}` expansion +Region| `region:` is the API endpoint region. Cross-region inference profiles route across the geo (US, EU, APAC) regardless of which one you pick. For non-US regions or provisioned-throughput ARNs, add a `models:` block with the right per-upstream IDs. + +#### + +​ + +Google Cloud Agent Platform + +For the equivalent client-side setup, see [Claude Code on Google Cloud](</docs/en/google-vertex-ai>). The gateway-side upstream: + + upstreams: + - provider: vertex + region: us-east5 + project_id: example-prod + auth: {} # preferred: Application Default Credentials + # OR a service account key file: + # auth: { service_account_json: /secrets/sa.json } + # Override the aiplatform endpoint for Private Service Connect: + # base_url: https://us-east5-aiplatform.p.googleapis.com + +An empty `auth` block uses Application Default Credentials: `GOOGLE_APPLICATION_CREDENTIALS`, GCE metadata, or GKE Workload Identity. Service-account JSON key files are supported but discouraged; use Workload Identity or attach a service account to the GCE or Cloud Run instance. Set `region: global` to use [Agent Platform’s global endpoint](<https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations>) instead of a regional one. Google then routes each request to an available region, so you don’t track per-region model availability. Setting a specific region pins every request to it. + +Setup| How +---|--- +IAM permissions| Grant the gateway’s service account `roles/aiplatform.user` on the project, or a custom role with `aiplatform.endpoints.predict`. Enable the Agent Platform API (`aiplatform.googleapis.com`). +Model access| In Model Garden, enable the Claude models for your project. They publish to specific regions; check the model card for supported regions. +GKE (Workload Identity)| Bind a GCP service account to the gateway’s Kubernetes service account and annotate the KSA with `iam.gke.io/gcp-service-account: claude-gateway@<proj>.iam.gserviceaccount.com`. `auth: {}` picks it up. +Cloud Run / GCE| Set the service’s service account to one with `roles/aiplatform.user`. `auth: {}` picks it up. +Anywhere else| `auth: { service_account_json: /secrets/sa.json }`, the path to a JSON key file mounted as a secret. The field takes a file path, not the key contents, so no `${file:…}` expansion is involved. + +#### + +​ + +Microsoft Foundry + +For the client-side Foundry deployment, see [Claude Code on Microsoft Foundry](</docs/en/microsoft-foundry>). The gateway-side upstream: + + upstreams: + - provider: foundry + resource: example-foundry # https://example-foundry.services.ai.azure.com + auth: { use_azure_ad: true } # preferred: DefaultAzureCredential / Managed Identity + # OR an API key: + # auth: + # api_key: ${FOUNDRY_API_KEY} + +`use_azure_ad: true` resolves through `DefaultAzureCredential`: Managed Identity on AKS, ACI, or App Service; the Azure CLI; or environment credentials. API keys work but are project-wide and don’t rotate automatically. Foundry’s endpoint is derived from `resource:`; set the optional `base_url` to override it for sovereign clouds such as Azure Government. + +Setup| How +---|--- +RBAC| Grant the gateway’s identity `Azure AI User` or `Cognitive Services User` on the Foundry resource +Deployments| Foundry uses admin-chosen deployment names, not canonical model IDs. Add a `models:` block mapping each canonical ID to your deployment name. +AKS (workload identity)| Federate a User-Assigned Managed Identity with the cluster’s OIDC issuer and bind it to the gateway’s service account. `use_azure_ad: true` picks it up via `WorkloadIdentityCredential`. +ACI / App Service| Enable system-assigned or user-assigned managed identity on the resource. `use_azure_ad: true` picks it up. +Anywhere else| `auth: { api_key: "${FOUNDRY_API_KEY}" }`. Quote `${…}` inside `{ }`. + +#### + +​ + +Multiple upstreams + +The same provider can appear more than once with a distinct `name:`. This covers different regions, different accounts via different credential chains, provisioned throughput versus on-demand, and cross-provider fallback. The gateway tries upstreams in order. `5xx`, `429`, timeouts, and missing-endpoint (`501`) fail over; other `4xx` doesn’t. `429` is per-upstream capacity, so provisioned-throughput (PT) exhaustion fails over to on-demand. An upstream that can’t resolve the requested model is skipped without a network round-trip. This example routes a provisioned-throughput Bedrock allotment first, overflows to on-demand and a second account, and falls back to the Anthropic API last: + + upstreams: + # Primary: provisioned throughput in your home region. + - name: bedrock-pt + provider: bedrock + region: us-east-1 + auth: {} + # Overflow: on-demand cross-region. + - name: bedrock-od + provider: bedrock + region: us-west-2 + auth: {} + # Different account: a separate Bedrock allotment via assumed-role creds. + - name: bedrock-acct2 + provider: bedrock + region: us-east-1 + auth: + aws_access_key_id: ${ACCT2_AKID} + aws_secret_access_key: ${ACCT2_SK} + # Last resort: direct Anthropic API. + - name: anthropic-fallback + provider: anthropic + auth: + api_key: ${ANTHROPIC_API_KEY} + + # Per-upstream model IDs are keyed on the upstream's `name:`; an upstream + # without a `name:` defaults to its provider string (e.g. `bedrock`). Any + # upstream not listed for a model is skipped, which is how you route a model + # to provisioned throughput while everything else stays on-demand. + models: + - id: claude-opus-4-8 + label: Claude Opus 4.8 + upstream_model: + bedrock-pt: arn:aws:bedrock:us-east-1:111111111111:provisioned-model/abcdef + bedrock-od: us.anthropic.claude-opus-4-8 + bedrock-acct2: us.anthropic.claude-opus-4-8 + anthropic-fallback: claude-opus-4-8 + +Lever| How +---|--- +Different regions| One Bedrock upstream per region, each with its own `region:`. With `auto_include_builtin_models: true` the cross-region inference profiles route automatically; for region-pinned deployments use a `models:` block. +Different accounts| One Bedrock upstream per account, each with its own credentials in `auth:`. The default chain (`auth: {}`) uses the pod’s identity; for a second account, set explicit credentials or a bearer token. +Provisioned throughput| Map the model to the provisioned-throughput ARN in `models:` for that upstream’s name. Other upstreams keep the on-demand ID, so PT capacity is exhausted before failing over. +VPC / FIPS endpoints| Set `base_url:` on the upstream to your VPC endpoint or FIPS endpoint URL +Model-scoped routing| Omit an upstream from a model’s `upstream_model:` map and that upstream is skipped for that model. For example, route Opus to provisioned throughput and Sonnet and Haiku to on-demand. + +Failing over between cloud providers, or to the direct Anthropic API, changes which agreement, geography, and other terms govern the request. The CLI applies the same feature gating to gateways regardless of which upstream serves a given request, so failover doesn’t send a body field an upstream would reject. + +## + +​ + +Optional sections + +### + +​ + +`admin` + +Optional. Enables `/v1/organizations/spend_limits`, which mirrors Anthropic’s public Admin API, and per-developer spend enforcement on `/v1/messages`. See [Spend limits](</docs/en/claude-apps-gateway-spend-limits>) for how caps are set and enforced; this section covers the `gateway.yaml` keys that turn the feature on and tune it. + + admin: + # Named static API keys for the admin endpoints, sent as x-api-key. + # The id appears in the audit log as admin-key:<id> so each key is + # attributable. Array for rotation: add the new key, roll clients, + # remove the old. + write_keys: + - { id: terraform, key: "${GATEWAY_ADMIN_WRITE_KEY_TF}" } + - { id: ci, key: "${GATEWAY_ADMIN_WRITE_KEY_CI}" } + read_keys: + - { id: reporting, key: "${GATEWAY_ADMIN_READ_KEY}" } + # IdP groups granted full admin via the normal gateway JWT (no API key). + admin_groups: [platform-finops] + blocked_message: request an increase at https://go.example.com/claude-limits + +Field| Required| Description +---|---|--- +`write_keys`| No| Array of `{id, key}`. An `x-api-key` matching one of these can list, set, and delete spend limits. Key values must be at least 32 characters; `id`s must be unique across `read_keys` and `write_keys`. +`read_keys`| No| Array of `{id, key}`. Read-only: every `GET` endpoint, including listing caps, fetching one by ID, and reading [`/effective`](</docs/en/claude-apps-gateway-spend-limits#%2Feffective>) and [`/audit`](</docs/en/claude-apps-gateway-spend-limits#%2Faudit>). +`admin_groups`| No| IdP group names. A gateway JWT whose `groups` claim includes one of these has full admin access, read and write, and audits as `oidc:<sub>`. Use this for human admins; use API keys for machines. +`blocked_message`| No| Appended verbatim to the `429 billing_error` a blocked developer sees. Write the whole instruction, such as a URL or a Slack channel. Unset, the error is `spend limit reached`. +`audit_retention_days`| No| Default `365`. Older `admin_audit` rows are swept. +`spend_retention_months`| No| Default `13`. `spend` counter rows older than this are swept. The default keeps a full year plus the current partial month for year-over-year reporting. +`identity_retention_days`| No| Default `90`. Last-seen TTL for `principal_emails` rows, which hold each developer’s email, display name, and groups (PII). Deliberately shorter than spend retention so a deprovisioned identity ages out while its anonymous spend counters remain. +`group_limit_mode`| No| `min` (default) or `max`. When a developer is in several groups with caps, `min` enforces the most restrictive and `max` the least. Used by both enforcement and `/effective`. + +### + +​ + +`enforcement` + +The `enforcement` block controls how spend-limit checks behave when the store is unavailable. + +Field| Required| Description +---|---|--- +`fail_closed_on_error`| No| Default `false`. Spend enforcement fails open on a Postgres outage, so inference stays up. Set `true` to fail closed: over-cap developers are blocked, but so is everyone else if the store is unreachable. Has no effect without an `admin:` block. + +### + +​ + +`models` + +The `models` block is an optional admin-curated model list, served at `/v1/models` and used to translate model IDs per upstream. It is required for non-US Bedrock regions, Bedrock provisioned-throughput ARNs, and Foundry deployment names. + + auto_include_builtin_models: true # false: expose only the list below + models: + - id: claude-opus-4-8 + label: Claude Opus 4.8 + # description: optional text shown in clients that surface it + upstream_model: + anthropic: claude-opus-4-8 + bedrock: us.anthropic.claude-opus-4-8 # or an inference-profile ARN + foundry: your-opus-deployment-name + +### + +​ + +`managed` + +The `managed` block defines role-based access policies keyed on IdP groups or email domain. Policies are evaluated in order; the first match is selected, then merged onto the `match: {}` catch-all base described below. They are served per-user at `GET /managed/settings` with ETag/304 caching. + + managed: + policies: + # Specific groups first. + - match: { groups: [eng-contractors] } + cli: + availableModels: [claude-sonnet-4-6] + permissions: { deny: ["WebFetch", "WebSearch"] } + # Default catch-all last: matches everyone who authenticated. + - match: {} + cli: + availableModels: [claude-opus-4-8, claude-sonnet-4-6, claude-haiku-4-5] + +A `match: {}` catch-all, conventionally listed last, is treated as a base layer. Every other policy inherits any key it doesn’t set from the catch-all, so per-role entries only need to list what differs from the org default. The merge rules depend on the key type: + + * **Allow-lists** : `availableModels` and `permissions.allow`. A specific policy’s list fully replaces the base’s. + * **Deny-lists and hook arrays** : `permissions.deny`, `permissions.ask`, `disabledMcpjsonServers`, `deniedMcpServers`, `blockedMarketplaces`, and every `hooks` event-type array. These take the union of base and policy, so an org-wide deny or audit hook can’t be accidentally dropped by a per-role override. + * **Record-typed keys** : `env`, `modelOverrides`, and `skillOverrides`. These shallow-merge, so a per-role `env` block overrides keys it sets and inherits the rest from the base. + +`availableModels` is also enforced server-side at `/v1/messages`, so a denied model returns `400` regardless of what the client sends. + +Matcher| Behavior +---|--- +`match: {}`| Matches every authenticated user. Start with one of these and add group-scoped policies above it later. +`match: { groups: [a, b] }`| Matches if the JWT’s `groups` claim contains any of the listed groups. Case-sensitive: groups must match the IdP’s exact casing. +`match: { email_domain: example.com }`| Matches the part after the last `@` in the JWT’s `email` claim, case-insensitive. Accepts one domain per policy. +`match: { groups: [a], email_domain: example.com }`| Both conditions must match + +An authenticated user who matches no policy gets the gateway’s defaults, which means every model in the catalog and no managed settings. Add a `match: {}` catch-all last if you want a guaranteed default policy. + +The gateway keeps no user directory of its own. It authorizes each request from the user’s IdP token, reading group membership from the token’s `groups` claim and evaluating policies against it. There is no roster to enumerate and no accounts to pre-create, and therefore no SCIM endpoint, because there is nothing for SCIM to sync into.Run user and group lifecycle management at the source of truth, which is your IdP’s native SCIM provisioning or a dedicated identity-governance platform. Membership and deprovisioning governed there flow into the gateway automatically through the token. If you want SCIM provisioning of Claude accounts themselves, that is a [Claude for Enterprise](</docs/en/admin-setup>) capability.Two propagation clocks apply: + + * **Policy contents** : editing a policy and redeploying reaches connected clients on their next managed-settings poll, within an hour + * **Group membership** : changing a user’s group membership changes which policy matches them. This takes effect on the next session re-mint, meaning the next silent refresh, bounded by `session.ttl_hours`. + +#### + +​ + +What goes in `cli` + +Each `cli` value is a complete Claude Code `managed-settings.json` document, the same schema you would deploy via MDM or `/etc/claude-code/managed-settings.json`, expressed here as YAML. The CLI applies the delivered document at the managed tier, above user and project settings. The gateway validates each document against the CLI’s settings schema at boot, so an unrecognized top-level key or a recognized key with a malformed value fails boot with an error naming every offending key. Deliberately open parts of the schema still accept arbitrary values, because newer clients may recognize entries the gateway’s schema doesn’t. These open keys are `env`, `pluginConfigs`, and keys nested under `permissions`. Because validation uses the schema bundled with the gateway’s installed version, putting a top-level settings key introduced by a newer Claude Code release into managed config requires upgrading the gateway first. Smoke-test a new policy on one client before rolling it out. The full key reference is in [Claude Code settings](</docs/en/settings#available-settings>). The keys most operators reach for first: + + managed: + policies: + - match: {} + cli: + # Model access (also enforced server-side at /v1/messages) + availableModels: [claude-opus-4-8, claude-sonnet-4-6, claude-haiku-4-5] + + # Permission policy + permissions: + deny: + - "WebFetch" + - "Read(./.env)" + - "Read(./secrets/**)" + disableBypassPermissionsMode: disable # blocks --dangerously-skip-permissions + allowManagedPermissionRulesOnly: true # ignore user/project permission rules + + # Environment pushed into the CLI process. DISABLE_UPDATES blocks + # background and manual updates; DISABLE_AUTOUPDATER stops only + # background updates. + env: + DISABLE_UPDATES: "1" # pin versions via your own distribution + + # Org-wide hooks. Hook commands run on developer machines, not the + # gateway, so the path must exist on every client OS in the policy. + hooks: + PostToolUse: + - matcher: "Edit|Write" + hooks: + - { type: command, command: /usr/local/bin/audit-edit.sh } + +Key| Enforced by| Effect +---|---|--- +`availableModels`| Gateway + CLI| Model allowlist. Also checked at `/v1/messages`, so a patched client can’t bypass it. +`permissions.allow` / `.deny`| CLI| Tool and command rules. See [Permissions](</docs/en/permissions>). +`permissions.disableBypassPermissionsMode`| CLI| Set to `disable` to block [`bypassPermissions`](</docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode>), the mode that auto-approves every tool call, and the `--dangerously-skip-permissions` flag +`allowManagedPermissionRulesOnly`| CLI| When `true`, user and project permission rules are ignored; only rules from this document apply +`env`| CLI| Environment variables merged into the CLI process. Use for telemetry, auto-update, and model-name overrides. +`hooks`| CLI| Org-wide [hooks](</docs/en/hooks>) + +Because these settings arrive over the network, the CLI shows each developer a one-time security approval dialog before applying anything that can run a shell command or alter where traffic goes. The dialog covers: + + * `hooks` + * `env` variables that aren’t on the CLI’s built-in safe list + * shell-execution settings such as `apiKeyHelper` and `statusLine` + * managed CLAUDE.md content + +The safe list determines which `env` variables apply without approval: + + * **On the safe list** : auto-update and model-name vars + * **Not on the safe list** : proxy vars, base-URL vars, and `OTEL_EXPORTER_OTLP_ENDPOINT` + +The gateway’s telemetry configuration pushes `OTEL_EXPORTER_OTLP_ENDPOINT`, so setting `telemetry.forward_to` triggers the dialog on each interactive client. Non-interactive runs with the `-p` flag skip the dialog and apply settings without approval. The dialog protects the developer’s machine from a compromised or hostile gateway, not the organization from the developer, so the `-p` skip is intentional rather than a gap. If a developer declines, Claude Code exits rather than applying the policy. Pushing a new hook or non-safe env var to a broad policy therefore means an approval prompt on every matching developer’s next startup. The `cli` key was named `settings` in earlier releases. That spelling is still accepted as an alias, but new deployments should use `cli`. + +#### + +​ + +Precedence with other managed sources + +If a device also has a local `managed-settings.json` or MDM-delivered policy, the managed sources don’t merge. The highest-priority source provides all policy settings, ranked in this order with highest priority first: + + 1. The [policy helper](</docs/en/settings#compute-managed-settings-with-a-policy-helper>) + 2. Gateway-delivered settings + 3. MDM, via the HKLM registry on Windows or a plist on macOS + 4. The `managed-settings.json` file + 5. The HKCU registry, on Windows only + +Embedding hosts can supply policy through the SDK `managedSettings` option. It is ignored by default and applies only when a managed source opts in with [`parentSettingsBehavior: "merge"`](</docs/en/settings#available-settings>), filtered so it can tighten policy but not loosen it. The only exception is the following keys, which are honored when any admin source above the user-writable HKCU tier sets them, regardless of which source provides the rest of the policy: + + * `sandbox.network.allowManagedDomainsOnly` and `sandbox.filesystem.allowManagedReadPathsOnly`: when locked, the corresponding allowlists are unioned across sources + * [`allowAllClaudeAiMcps`](</docs/en/settings#available-settings>): allow-only override for the claude.ai MCP server allowlist + * `sandbox.bwrapPath` and `sandbox.socatPath`: filesystem paths to the [sandbox](</docs/en/sandboxing>) helper binaries + +Every other key, including `allowManagedPermissionRulesOnly` and `disableBypassPermissionsMode`, comes from the highest-priority source only. See [Settings precedence](</docs/en/settings#settings-precedence>) for the same rule on the settings page. Gateway policies apply to every Claude Code invocation on the machine, including non-interactive `claude -p` runs and sessions spawned by the Agent SDK. If the gateway is unreachable at startup, signed-in sessions exit with an error rather than running without their policy. + +`mcpServers` inside a policy’s `cli` block is rejected at gateway boot. Per-group MCP distribution is not available; deploy MCP servers via the file-based `managed-mcp.json` on each device or let developers add them locally. + +### + +​ + +`telemetry` + +The CLI sends OpenTelemetry Protocol (OTLP) over HTTP metrics, logs, and, when enabled, traces to the gateway, which relays them verbatim to each configured destination. See [Monitoring usage](</docs/en/monitoring-usage>) for the metrics and events the CLI emits. The CLI stamps each export with the authenticated user’s identity, read from the gateway-issued JWT: the `user.id`, `user.email`, and `user.groups` attributes. Per-developer cost and usage attribution therefore works with no developer-side configuration. + + telemetry: + forward_to: + - url: https://otel-collector.internal.example.com + headers: + Authorization: ${OTLP_TOKEN} + # Per-signal opt-in. Default: metrics only. + metrics: true + logs: false + traces: false + - url: https://api.datadoghq.com/api/v2/otlp + headers: + DD-API-KEY: ${DD_API_KEY} + +Each destination opts into `metrics`, `logs`, and `traces` independently, and the default is metrics only. The signals differ in sensitivity: + + * **Metrics** : aggregate counters such as token counts, request counts, and latency + * **Logs and traces** : can carry full bash commands, tool inputs, and file paths, covering anything Claude Code does on a developer’s machine + +Enable logs and traces only on destinations with the access controls and retention policy that data warrants. + +Telemetry is off in the CLI by default. Configuring `telemetry.forward_to` together with `listen.public_url` turns it on. The gateway pushes five env vars to every connected client through `/managed/settings`: + + * `CLAUDE_CODE_ENABLE_TELEMETRY=1` + * `OTEL_METRICS_EXPORTER=otlp` + * `OTEL_LOGS_EXPORTER=otlp` + * `OTEL_TRACES_EXPORTER=otlp` + * `OTEL_EXPORTER_OTLP_ENDPOINT=<public_url>` + +The pushed endpoint is built from the public URL, so metrics and logs need no OTEL configuration from developers or policies. The pushed configuration is applied at the managed tier, overriding `OTEL_*` variables a developer sets locally. [Traces](</docs/en/monitoring-usage#traces-beta>) additionally require `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1` on each client. The gateway doesn’t push that variable, so set it through a managed policy’s `env` block. It isn’t on the CLI’s safe list, so delivering it through a policy is covered by the same security approval dialog that the pushed OTLP endpoint already triggers. Both protobuf and JSON OTLP encodings are relayed, and any OpenTelemetry-compatible backend works as a destination. + +### + +​ + +HTTP tuning + +Four optional top-level blocks, `access_control`, `limits`, `timeouts`, and `rate_limits`, tune the HTTP surface. The defaults suit most deployments. + +Block| Key| Default| Description +---|---|---|--- +`access_control`| `allow_cidrs` / `deny_cidrs`| empty| Inbound IP allow/deny by client address, after `trusted_proxies` resolution. `deny_cidrs` is checked first; a client it matches is rejected even if `allow_cidrs` also matches. If `allow_cidrs` is non-empty the gateway is default-deny. `/healthz` and `/readyz` are exempt from `allow_cidrs`. +`limits`| `max_request_bytes`| 32 MiB| Max inbound request body; oversize requests get `413` before the body is buffered. Raise for large file or image requests. +`limits`| `max_request_header_bytes`| unset| When set, oversize headers return `431` +`limits`| `max_url_length`| unset| When set, an over-long URL returns `414` +`timeouts`| `upstream_ttfb_ms`| 120000| Max wait for the upstream’s response headers (time to first byte). The response body then streams with no wall-clock cap. Applies to the direct Anthropic upstream path; Bedrock, Agent Platform, and Foundry are bounded by their provider SDK’s own timeout. +`rate_limits`| `device_authorization.max` / `.window_seconds`| 30 / 600| Per-IP rate limit on the unauthenticated device-authorization endpoint. Raise for a large org behind a shared egress IP or NAT. These limits apply only to the device-grant sign-in flow, not to `/v1/messages` inference. See [User-code brute-force resistance](</docs/en/claude-apps-gateway-deploy#user-code-brute-force-resistance>). +`rate_limits`| `device_verify.max` / `.window_seconds`| 10 / 600| Per-IP rate limit on `user_code` submissions at `/device` + +## + +​ + +Complete example + +This full reference config exercises every core section; the HTTP tuning blocks keep their defaults. Copy it, delete what you don’t need, and fill in your values. The config in the [Quickstart](</docs/en/claude-apps-gateway#quickstart>) is a minimal version of this. + +gateway.yaml + + # Run with: + # claude gateway --config gateway.yaml + # + # Operational log verbosity is controlled by the CLAUDE_GATEWAY_LOG_LEVEL + # environment variable (info | warn | error; default info). It does not + # affect audit events, which are always emitted. + + listen: + host: 0.0.0.0 + port: 8080 + public_url: https://claude-gateway.internal.example.com + # Omit the tls block when running behind a TLS-terminating ingress. + # tls: + # cert: /certs/gateway.crt + # key: /certs/gateway.key + # trusted_proxies: + # - 10.0.0.0/8 + + oidc: + issuer: https://example.okta.com + client_id: 0oa1example2 + client_secret: ${OIDC_CLIENT_SECRET} + allowed_email_domains: + - example.com + # Required when the issuer is the Okta org server, whose id_tokens + # can omit email and groups; the gateway fills them from /userinfo. + userinfo_fallback: true + # allowed_groups: [claude-code-users] + # Okta emits groups only when the `groups` scope is requested and the + # app's groups claim filter allows them. The contractors policy below + # matches on groups, so the scope is requested here. + scopes: [openid, profile, email, offline_access, groups] + # extra_auth_params: { access_type: offline, prompt: consent } # Google + # groups_claim: groups # Entra app roles: use `roles` + # email_claim: email + + session: + jwt_secret: ${GATEWAY_JWT_SECRET} # openssl rand -base64 32 + # ttl_hours: 1 + + store: + postgres_url: ${GATEWAY_POSTGRES_URL} + # max_connections: 5 + + # Enables /v1/organizations/spend_limits (mirrors the Anthropic Admin API) + # and per-developer spend enforcement on /v1/messages. Omit to disable. + # Caps themselves are set via the admin API, not here. + # admin: + # write_keys: + # - { id: terraform, key: "${GATEWAY_ADMIN_WRITE_KEY_TF}" } + # read_keys: + # - { id: reporting, key: "${GATEWAY_ADMIN_READ_KEY}" } + # admin_groups: [platform-finops] + # blocked_message: request an increase at https://go.example.com/claude-limits + # # audit_retention_days: 365 + # # spend_retention_months: 13 + # # identity_retention_days: 90 + # # group_limit_mode: min + + # enforcement: + # fail_closed_on_error: false + + upstreams: + - provider: anthropic + auth: + api_key: ${ANTHROPIC_API_KEY} + + # - provider: bedrock + # region: us-east-1 + # auth: {} + + # - provider: vertex + # region: us-east5 + # project_id: example-prod + # auth: {} + + # - provider: foundry + # resource: example-foundry + # auth: { use_azure_ad: true } + + auto_include_builtin_models: true + models: + - id: claude-opus-4-8 + label: Claude Opus 4.8 + upstream_model: + anthropic: claude-opus-4-8 + # bedrock: us.anthropic.claude-opus-4-8 + # vertex: claude-opus-4-8 + # foundry: <your-opus-deployment-name> + - id: claude-sonnet-4-6 + label: Claude Sonnet 4.6 + upstream_model: + anthropic: claude-sonnet-4-6 + - id: claude-haiku-4-5 + label: Claude Haiku 4.5 + upstream_model: + anthropic: claude-haiku-4-5 + + managed: + policies: + - match: { groups: [contractors] } + cli: + availableModels: [claude-haiku-4-5] + # Constrain the Default picker option to availableModels instead of + # the tier default, so contractors don't get a 400 on the default. + enforceAvailableModels: true + # allow auto-approves these tools; it does not block the rest. + # Add deny rules to restrict tools. + permissions: { allow: [Read, Grep] } + - match: {} + cli: + availableModels: [claude-opus-4-8, claude-sonnet-4-6, claude-haiku-4-5] + permissions: + allow: [Read, Grep, Bash, Edit] + deny: ["WebFetch"] + env: { HTTP_PROXY: http://proxy.example.com:8080 } + + telemetry: + forward_to: + - url: https://otel.internal.example.com:4318 + headers: + Authorization: Bearer ${OTEL_TOKEN} + +## + +​ + +Client-side managed settings + +Everything above configures the gateway server. Pointing developer machines at it is configured separately, on each device, through Claude Code’s [managed settings](</docs/en/settings#settings-files>). The gateway can’t push these keys itself, because they’re what tell the client where the gateway is. For the CLI, set both keys in the per-OS `managed-settings.json`: + + { + "forceLoginMethod": "gateway", + "forceLoginGatewayUrl": "https://claude-gateway.internal.example.com" + } + +Deploy that file to each device, typically via your MDM platform. The file path differs by platform: + +Platform| Path +---|--- +macOS| `/Library/Application Support/ClaudeCode/managed-settings.json`, or the `com.anthropic.claudecode` managed preferences domain +Linux and WSL| `/etc/claude-code/managed-settings.json` +Windows| `C:\Program Files\ClaudeCode\managed-settings.json`, or Group Policy via the HKLM registry + +`forceLoginGatewayUrl`, and the `"gateway"` value of `forceLoginMethod`, are honored only from the admin-controlled managed tier. A developer setting them in their own `~/.claude/settings.json` has no effect. + +## + +​ + +Related + + * [Claude apps gateway overview](</docs/en/claude-apps-gateway>): quickstart and developer connection + * [Deployment guide](</docs/en/claude-apps-gateway-deploy>): IdP setup, container image, Kubernetes and Cloud Run, and operations + * [Spend limits](</docs/en/claude-apps-gateway-spend-limits>): per-developer caps and the Admin API
added Claude apps gateway deployment and operations View current →
Show diff (298 lines)
--- a/claude-apps-gateway-deploy.md +++ b/claude-apps-gateway-deploy.md @@ -0,0 +1,295 @@ +This page covers the operational side of running [Claude apps gateway](</docs/en/claude-apps-gateway>): registering an OAuth client in your identity provider (IdP), deploying the gateway as a container, and running it day-to-day. For every option in the `gateway.yaml` file the gateway reads at boot, see the [Configuration reference](</docs/en/claude-apps-gateway-config>). A production deployment follows four steps in order, and the sections below match them. The first two are where you make choices; the second two are reference material to consult once it’s running. + + 1. Set up your identity provider: register the OAuth client and check the per-IdP notes for Okta, Entra, and Google + 2. Deploy the gateway: build a pinned container image and run it on Kubernetes, Cloud Run, or your own platform. This section also covers cost, bypass, multiple-gateway, and serverless decisions + 3. Set up operations: logs, health probes, outage behavior, secret rotation, and upgrades. Reference for when you’re setting up monitoring and runbooks + 4. Review the security posture: what data flows where, the threat model, and compliance answers. Reference for a security review + +If a sign-in or boot fails along the way, go straight to Troubleshooting, which is keyed on the error you see. + +**Deploy on your private network.** Claude Code only connects to a gateway whose address is private. This is a security guard, because a trusted gateway can push settings that run commands on developer machines. Put the gateway behind an internal load balancer or VPN and give it a hostname that resolves to private IPs only. + +## + +​ + +Identity provider setup + +Register a confidential OAuth/OpenID Connect (OIDC) web application with a single redirect URI, `https://<gateway>/oauth/callback`, and assign it to the users or groups who should have gateway access. Any OIDC-compliant IdP works: Okta, Microsoft Entra ID, Google Workspace, Keycloak, Dex, PingFederate, and others. The IdP must meet three requirements: + + * Serves `/.well-known/openid-configuration`, over HTTPS in production; the gateway accepts an [`http://` issuer](</docs/en/claude-apps-gateway-config#oidc>), and a loopback issuer additionally requires `CLAUDE_GATEWAY_ALLOW_LOOPBACK=1` + * Supports the authorization-code flow. PKCE (Proof Key for Code Exchange) is on by default; disable it with `oidc.use_pkce: false` for IdPs that don’t support it + * Returns `email` and optionally `groups` in the id_token, or serves them from the userinfo endpoint with `oidc.userinfo_fallback: true` + +For private PKI, set `oidc.ca_cert_pem`. A few providers handle email and group claims differently: + + * **Okta** : the org authorization server at `https://example.okta.com` returns a thin id_token that omits `email` and `groups`, so set `oidc.userinfo_fallback: true` whenever you use it as `issuer`. A custom authorization server such as `https://example.okta.com/oauth2/default` that includes `email` and optionally `groups` in the id_token emits them directly and needs no fallback. Okta emits `groups` only when the `groups` scope is requested in `oidc.scopes` and the app’s groups claim filter allows it; `userinfo_fallback` can’t fill a claim the IdP wasn’t asked for. + * **Microsoft Entra ID** : `issuer` = `https://login.microsoftonline.com/<tenant-id>/v2.0`. Entra emits group Object IDs rather than names, so use the GUIDs in `managed.policies.match.groups`, or use App Roles for human-readable names. If your tenant emits roles under `roles` instead of `groups`, set `oidc.groups_claim: roles`. + * **Google Workspace** : `issuer` = `https://accounts.google.com`. Google’s id_token doesn’t carry groups. To use group-based `allowed_groups` or `managed.policies` with Google as the IdP, configure [`oidc.google_groups`](</docs/en/claude-apps-gateway-config#oidc>), which looks up each user’s groups through the Admin SDK Directory API using a service account with domain-wide delegation. Without it, use `oidc.allowed_email_domains` for membership gating and `managed.policies.match.email_domain` for policy assignment. Google also ignores the standard `offline_access` scope. For refresh tokens, set `oidc.scopes: [openid, profile, email]` and `oidc.extra_auth_params: { access_type: offline, prompt: consent }`. + +For support with an identity provider not covered above, see Troubleshooting. + +Refresh tokens let the gateway renew a developer’s session silently, without sending the developer back to the browser. They also drive deprovisioning, because when the IdP disables a user, the next refresh fails and the session ends within `ttl_hours`. The gateway requests `offline_access` by default to get a refresh token. If your IdP requires explicit consent for offline access, configure the OAuth client to allow it.If your IdP can’t issue refresh tokens at all, the gateway still works, but there is no silent renewal, so developers re-run the browser login when their session expires. To keep that from happening every hour, raise [`session.ttl_hours`](</docs/en/claude-apps-gateway-config#session>) to `8` or `12`. The tradeoff is deprovisioning latency, because without refresh tokens a disabled user keeps access until the longer TTL elapses. + +## + +​ + +Deployment + +The gateway is a single Linux binary. It scales horizontally because replicas are stateless and Postgres is the shared coordination layer. Run it however you run stateless services in your environment. The rest of this section states what the image needs, with short notes for Kubernetes and Cloud Run. The gateway is designed to run inside your network, because it holds your upstream credential and acts as the single egress point for inference. It can run anywhere your developers and your IdP can reach over HTTPS; treat it like any other service holding a production credential. A few decisions shape the deployment beyond where it runs: + + * **Cost** : there is no separate license or per-seat fee for the gateway; it’s part of the `claude` binary. You pay for inference through your existing cloud or Anthropic commitment, plus the compute for the container and your telemetry collector. + * **Bypass** : the gateway doesn’t enforce that the only route to a model goes through it. A developer with their own credential can still call the provider directly, so closing that path is a network policy decision, for example blocking egress to `api.anthropic.com` except from the gateway. Blocking that egress also breaks the [WebFetch domain safety check](</docs/en/data-usage#webfetch-domain-safety-check>), which calls `api.anthropic.com` from each developer’s machine; set `skipWebFetchPreflight: true` in the managed policy to disable it. + * **Multiple gateways** : each gateway is a separate deployment with its own config. The CLI stores its trust fingerprint and credentials per gateway hostname, so different teams can connect to different gateways without conflict. To serve multiple OIDC issuers, run separate instances. + * **Serverless** : Cloud Run works; set `min-instances: 1` to avoid cold OIDC discovery. Lambda and Cloud Functions don’t, because the gateway is a long-running HTTP server. + +Every production topology here puts an L7 proxy, such as an Ingress, Cloud Run’s front end, or an ALB, in front of plain-HTTP replicas. Set [`listen.trusted_proxies`](</docs/en/claude-apps-gateway-config#listen>) to the proxy’s source ranges so the gateway reads client IPs from `X-Forwarded-For`. The gateway honors the header only when the TCP peer is trusted; the [Google Cloud worked example](</docs/en/claude-apps-gateway-on-gcp>) has concrete values per topology. Without trusted proxies, every request appears to come from the proxy’s IP, which collapses per-IP rate limits into one shared bucket and records the proxy’s IP in audit events. + +### + +​ + +Container image + +Build your own image around the native `claude` binary from the standard Claude Code release: + + 1. Download the Linux build for your image architecture from a pinned release; see [Install a specific version](</docs/en/setup#install-a-specific-version>) for the download URL. + 2. Verify it against the release’s GPG-signed `manifest.json` as described in [Binary integrity and code signing](</docs/en/setup#binary-integrity-and-code-signing>). + 3. Copy it into the build context. + +Mirror the release into your internal registry if your builds can’t reach the release host, and pin the version your fleet runs. Beyond the binary, the image needs: + + * **A glibc-based image** : the glibc build’s only dynamic dependencies are glibc libraries. Musl-based images need the `linux-x64-musl` or `linux-arm64-musl` build plus additional packages; see [Alpine Linux setup](</docs/en/setup#alpine-linux-and-musl-based-distributions>). + * **A writable state directory** : the gateway runs as any user, but minimal images have no writable home. Set `CLAUDE_CONFIG_DIR` to a writable path such as `/tmp/.claude`. + * **The container command** : `claude gateway --config /etc/claude/gateway.yaml`, with the config file mounted read-only and secrets supplied as environment variables; the gateway listens on `listen.port`, default `8080`. + +### + +​ + +Kubernetes + +Run the gateway as a Deployment, like any stateless service: + + * Mount the config from a ConfigMap and secrets from a Secret; reference secrets in the YAML via `${file:/path/to/secret}` or as environment variables + * Terminate TLS at the Ingress and set `listen.public_url` to the Ingress hostname + * Point the readiness probe at `GET /readyz` and the liveness probe at `GET /healthz` + +**Workload identity** Prefer the platform’s workload identity over static keys: IRSA on EKS for Bedrock, Workload Identity on GKE for Agent Platform, and workload identity on AKS for Foundry. Set `auth: {}` in the upstream block, or `use_azure_ad: true` for Foundry, and the gateway picks up the pod’s identity through that provider’s default credential chain. For a cross-cloud pairing, such as a Bedrock upstream on GKE, set explicit credentials in the upstream’s `auth` block instead. The [`upstreams` reference](</docs/en/claude-apps-gateway-config#upstreams>) has per-platform setup details. + +### + +​ + +Cloud Run + +Configure the service as follows: + + * Leave `listen.port` at its default of `8080`, which matches Cloud Run’s default `PORT`, or set `port: ${PORT}` + * Set `public_url` to the externally reachable origin. For production this is normally an internal load balancer’s hostname, because `/login` [rejects public addresses](</docs/en/claude-apps-gateway#prerequisites>) and the `*.run.app` URL resolves to one, so the Cloud Run URL alone works only for a `curl` or browser smoke test. The exception is a network where `*.run.app` resolves privately through Private Service Connect and a Cloud DNS private zone; in that topology the Cloud Run URL is a valid `public_url`. The [Google Cloud worked example](</docs/en/claude-apps-gateway-on-gcp#deploy-the-gateway>) covers both. + * Mount the config as a secret volume + * Set `min-instances: 1` to avoid a cold OIDC discovery on first request + +For a complete worked example on Google Cloud, covering Cloud Run or GKE, Cloud SQL, and Secret Manager, see [Deploy on Google Cloud](</docs/en/claude-apps-gateway-on-gcp>). + +### + +​ + +Push the gateway URL to developer machines + +Once the gateway is serving, push `forceLoginMethod` and `forceLoginGatewayUrl` to each developer’s machine through managed settings, via MDM or by writing the per-OS `managed-settings.json` directly. Without this, `/login` shows the standard account picker with no gateway option. See [Client-side managed settings](</docs/en/claude-apps-gateway-config#client-side-managed-settings>) for the file paths. + +## + +​ + +Operations + +Once the gateway is serving traffic, day-to-day operation is reading its logs, probing its health, and rotating its secrets on your schedule. The subsections cover each, plus what Postgres holds and how upgrades and rollbacks behave. + +### + +​ + +Logs + +The gateway writes two streams to stderr, both JSON-friendly: + + * **Audit events** : single-line JSON per security-relevant event. Pipe stderr to your log aggregator. The events emitted include `config.load`, `session.mint`, `session.refresh`, `device.authorize`, `device.verify`, `auth.denied`, `access.denied`, `inference`, `managed.serve`, `spend.blocked`, and `admin.denied`. Fields vary by event: + * Successful mint and refresh events carry `sub`, `email`, `client_ip`, and the result + * Denial events carry the reason, path, and client IP, since no identity exists at denial + * `inference` records which upstream served the request and the response status + * `admin.denied` records a rejected admin-API auth attempt with the reason (`invalid_key` or `no_credentials`), client IP, method, and path, without the presented key material + * **Operational logs** : human-readable `[gateway]`-prefixed lines for boot, warnings, and upstream errors. The `CLAUDE_GATEWAY_LOG_LEVEL` environment variable controls verbosity and accepts `info`, `warn`, or `error`, with `info` as the default. It doesn’t affect audit events, which are always emitted. + +### + +​ + +Health + +The gateway serves `GET /healthz` as a liveness probe and `GET /readyz` as a readiness probe; `/readyz` verifies the store is reachable. Both are exempt from `access_control.allow_cidrs`, so probes keep working on a locked-down listener. The OAuth discovery document at `/.well-known/oauth-authorization-server` also returns `200` only after config load, OIDC discovery, upstream client construction, and Postgres migration all succeed, so it doubles as an end-to-end boot check. A running gateway also serves a description of the paths and request shapes it accepts at `<public_url>/protocol`, matched to the version you’re running. The contents aren’t stable across releases. + +### + +​ + +Outage behavior + +If Postgres goes down, the gateway itself keeps serving signed-in developers and new sign-ins fail. Whether developers actually keep working depends on how your orchestrator handles readiness: + + * **Existing sessions** : bearer tokens validate locally with the JWT secret, session refreshes don’t touch the store, and the gateway process can still serve inference + * **New sign-ins** : fail until Postgres recovers, because the device flow and its rate-limit counters live in Postgres + * **[Spend-limit enforcement](</docs/en/claude-apps-gateway-spend-limits#postgres-availability>)** : fails open by default during the outage, so inference still flows; flip it to fail closed if you’d rather block than run unmetered + * **Readiness** : `/readyz` reports not-ready during the outage, so orchestrators that gate traffic on readiness remove every replica from rotation at once. In that topology all traffic, including inference the gateway could still serve, fails at the load balancer until Postgres recovers. The liveness probe on `/healthz` keeps passing, so replicas aren’t restarted. Point the readiness probe at `/healthz` instead if you’d rather signed-in developers keep working through a store outage; the cost is that new sign-ins fail against a replica that still reports ready. + +If your IdP goes down, existing sessions work until `ttl_hours`, and new logins and refreshes fail. Set a longer `ttl_hours` if your IdP has frequent maintenance windows. + +### + +​ + +JWT secret rotation + +Rotate the signing secret in three steps so existing sessions stay valid: + + 1. Generate a new secret. Prepend it to the `session.jwt_secret` array. + 2. Roll the deployment. New tokens sign with the new secret; old tokens still verify. + 3. After `ttl_hours` plus a margin, remove the old secret and roll again. + +Rotation is also the only way to force sessions out before they expire: bearer tokens validate locally against the JWT secret, so there is no per-session revocation. Replacing the secret outright, without keeping the old one in the array, invalidates every outstanding session at once. For individual offboarding, deprovision the user in your IdP; their session ends within `ttl_hours`. + +### + +​ + +Postgres + +The gateway holds five tables, all created by its boot-time migrations: + +Table| Contents| Retention +---|---|--- +`kv`| Device grants (10-minute TTL) and rate-limit counters| TTL per row +`spend`| Per-principal period-to-date spend counters, in cents| `admin.spend_retention_months`, default 13 +`spend_limits`| Configured spend caps| Until deleted via the API +`admin_audit`| Admin API mutation trail| `admin.audit_retention_days`, default 365 +`principal_emails`| Each principal’s last-seen email, display name, and IdP groups. Contains PII.| `admin.identity_retention_days` since last activity, default 90 + +A 30-second loop expires `kv` rows past their TTL, and an hourly sweep enforces the retention windows on the spend tables, so nothing grows without bound. Without [spend limits](</docs/en/claude-apps-gateway-spend-limits>) configured, only `kv` is written. If your security policy prohibits DDL from the application role, pre-create these tables and `_migrations` with an admin role and grant the app role `SELECT, INSERT, UPDATE, DELETE` on each. With spend limits in use, a lost database means lost spend tracking and caps, not only developer re-logins, so run regular backups. To erase one departed developer immediately rather than waiting on retention, run `DELETE FROM principal_emails WHERE principal = '<sub>'` directly; that removes the only table holding their email, name, and groups. `spend` and `admin_audit` rows reference the pseudonymous OIDC `sub` only. + +### + +​ + +Upgrades + +Replicas are stateless, so a rolling restart is safe at any time. The gateway runs schema migrations at boot, which means deploying the new binary self-migrates the database. If the database role can’t run DDL, pre-create the schema, including the `_migrations` table seeded to the current version; otherwise boot fails attempting `CREATE TABLE`. Migrations are append-only, so rolling back to a prior binary that knows fewer migrations is safe; it ignores the extra rows. Rollback also re-validates the YAML against the older binary’s schema, so a config that adopted a key introduced by the newer release fails boot on the older one. Remove the new key before rolling back. Because you pin the gateway’s version in your own image, fixes in new Claude Code releases, including security fixes, reach your deployment only when you update the pin and redeploy. Include the gateway in the same patching cadence you use for other services that hold production credentials. + +## + +​ + +Security + +This section answers the questions a security review asks: what data flows through the gateway and where it goes, which attacks the design defends against, and which answers belong in a compliance questionnaire. + +### + +​ + +Data flow + +Data| Path| Sent to Anthropic by the gateway +---|---|--- +Inference (prompts, completions)| CLI → gateway → your upstream| Only if the Anthropic API is a configured upstream +Telemetry (OTLP metrics, plus [opt-in logs and traces](</docs/en/claude-apps-gateway-config#telemetry>))| CLI → gateway → your collector| Never +Identity (email, groups, sub)| IdP → gateway → JWT → CLI; the CLI stamps it on OTLP exports| Never +Managed settings| Your gateway YAML → CLI| Never +Audit log| Gateway stderr → your aggregator| Never + +### + +​ + +Threat model summary + +The gateway sits inside your network perimeter, but individual developer laptops aren’t treated as trusted. The design accounts for this in three ways: + + * Developers hold short-lived JWTs instead of raw upstream keys. The CLI-to-gateway leg uses the RFC 8628 device grant, and the gateway’s authorization-code exchange with the IdP runs PKCE in the default configuration, so an intercepted IdP authorization code is useless. + * The device-verification page enforces same-origin POST and a per-IP rate limit per RFC 8628 §5.1. See User-code brute-force resistance. + * Outbound requests go through a server-side request forgery (SSRF) guard that resolves DNS, blocks link-local and cloud-metadata addresses plus loopback by default, and pins the connection to the resolved IP, so operator-influenced URLs such as the IdP and OTLP destinations can’t be redirected to cloud metadata endpoints. RFC 1918 private ranges are deliberately allowed, because IdPs and OTLP collectors commonly live on private IPs. For local development against a loopback IdP or collector, set `CLAUDE_GATEWAY_ALLOW_LOOPBACK=1` in the gateway’s environment; leave it unset in production. + +If you add your own egress controls, the gateway must reach the metadata server whenever it uses instance-metadata credentials such as workload identity. Two threats are out of scope because they are your infrastructure to secure: + + * **A compromised gateway host** : the host both holds the upstream credential and distributes [managed settings](</docs/en/claude-apps-gateway-config#managed>) to every connected developer, so control over the gateway’s configuration is comparable to control over your MDM. The CLI’s one-time approval dialog for shell-capable settings limits silent changes but doesn’t replace host security. + * **A malicious OIDC provider** : the provider signs the id_tokens the gateway trusts, so it can assert any identity. Vetting and securing your IdP is your responsibility. + +### + +​ + +User-code brute-force resistance + +The `user_code` a developer types into the `/device` verification page is 8 characters drawn from a 20-character alphabet, which yields 20⁸ or about 2.56×10¹⁰ combinations, and it expires after 10 minutes. The gateway applies per-IP rate limits on the device-grant endpoints, configurable via [`rate_limits`](</docs/en/claude-apps-gateway-config#http-tuning>). Raise the limits if many developers sign in from a single shared corporate NAT address. The limits apply only to the sign-in flow, not to inference. + +### + +​ + +Compliance posture + + * **Data residency** : the gateway’s own data plane sends nothing to Anthropic unless the Anthropic API is a configured upstream; when it is, your existing data-handling agreement applies to the inference path. Telemetry, audit, identity, and settings go only to the destinations you configure. + * **Host-process traffic** : the host process is the Claude Code CLI, which can send startup analytics and update checks to Anthropic. For strict-egress deployments, set `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1` in the gateway’s container environment. + * **Client analytics** : the CLI disables its own usage analytics while signed in to a gateway, and error reporting is off by default on third-party API surfaces. + * **Client machines** : developers’ CLIs still send WebFetch hostname checks and version checks to Anthropic unless `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1` and `skipWebFetchPreflight: true` are set. See [data usage](</docs/en/data-usage>). + * **Survey ratings** : the gateway credential disables the Anthropic-bound rating sink, so ratings aren’t sent to Anthropic. + * **Transcript sharing** : choosing Yes on a survey’s transcript-share prompt writes a local file under `~/.claude/feedback-bundles/` instead of uploading to Anthropic. + * **Client updates** : update checks are separate from gateway traffic. Pin versions through your own distribution and set `DISABLE_UPDATES` if laptops must not fetch releases. `DISABLE_AUTOUPDATER` stops only background updates while `claude update` still works. + * **TLS** : serve `public_url` over HTTPS in production, either from the gateway’s own listener via `listen.tls` or from a TLS-terminating ingress in front of plain-HTTP replicas with `listen.public_url` set. The gateway doesn’t refuse plain HTTP. The IdP must serve HTTPS in production, and Postgres supports `?sslmode=require`. Set `Strict-Transport-Security` at your ingress. + * **Vulnerability disclosure** : follow [Reporting security issues](</docs/en/security#reporting-security-issues>) + +## + +​ + +Troubleshooting + +For questions and feedback, use [Claude Code support](<https://support.claude.com/en/collections/14445694-claude-code>), or open an issue on the [Claude Code GitHub repository](<https://github.com/anthropics/claude-code/issues>). When reporting a problem, include: + + * **Gateway issue** : the gateway’s stderr for the relevant window, your `gateway.yaml` with secrets redacted, the gateway version, shown on the landing page at `/` and in the `x-cc-gateway-version` response header on `/managed/settings`, and what changed recently + * **Login issue** : the developer runs `claude --debug-file ./claude-debug.txt`, reproduces, and sends that file plus the gateway’s audit log for the same window + * **Inference issue** : the model requested, the upstreams configured, and the gateway’s audit log for the request, which records which upstream served it and the response status + +Symptom| Cause| Fix +---|---|--- +A developer’s `/login` shows the standard account picker instead of the **Cloud gateway** screen| `forceLoginMethod` or `forceLoginGatewayUrl` isn’t set in managed settings on that machine| Deploy the [managed settings file](</docs/en/claude-apps-gateway#set-the-gateway-url>) to the device; `/login` reads the gateway URL from there +Startup shows `Gateway login is configured in managed settings, but this Claude Code build does not include Cloud gateway support.`| The installed Claude Code build predates gateway support| Have the developer update Claude Code to a release that includes Cloud gateway support +CLI `/login`: `Gateway hosts must be on your organization's private network; <host> resolves to the public (or unrecognized) address <ip>`| The gateway hostname resolves to at least one public IP address. Claude Code checks each resolved address and requires every one to be private. A common cause is a dual-stack name where one family resolves to a public address, including AWS internal dual-stack load balancers, which return public-range AAAA addresses| Have the gateway name resolve only to private addresses on developer machines. For a dual-stack name, drop the public-range record or serve a separate internal-only DNS name. See the [private-network prerequisite](</docs/en/claude-apps-gateway#prerequisites>). +CLI `/login`: `Gateway login requires a direct connection and does not support connecting through an HTTP proxy`| An `HTTPS_PROXY` or `HTTP_PROXY` applies to the gateway host and the proxy’s hostname resolves to a public address. A proxy whose host resolves only to private addresses is allowed and doesn’t trigger this error| Add the gateway host to `NO_PROXY` on the developer’s machine so the connection is direct, or use a proxy whose hostname resolves to private addresses +CLI `/login`: `Could not resolve gateway host <host>`| The machine can’t resolve the gateway’s internal DNS name, typically because it isn’t on the corporate network| Have the developer connect to your network or VPN, then retry `/login` +Boot exits with a config validation error naming `store.postgres_url`| No Postgres configured; the gateway requires Postgres| Set `store.postgres_url`. For local development, use a throwaway container: `docker run --rm -p 5432:5432 -e POSTGRES_HOST_AUTH_METHOD=trust postgres`. +Boot exits: `requires the native binary`| Running under Node instead of the native binary| Install Claude Code with one of the [standalone install methods](</docs/en/setup>) +Boot exits with an OIDC discovery error after `config.load`| `oidc.issuer` unreachable, or TLS chain not trusted| Check the issuer is reachable from the pod and serves `/.well-known/openid-configuration`. Set `ca_cert_pem` for private PKI. +Boot exits with a Postgres permission error| App role lacks `CREATE TABLE`| Pre-create the schema with an admin role and grant DML to the app role, or grant DDL temporarily for boots that apply new migrations +`/oauth/callback` shows “Sign-in could not be completed”| Email domain rejected, id_token validation failed, or `email_verified` is explicitly `false`, which the gateway always rejects with no override| Check `allowed_email_domains` and that the IdP returns a verified `email` claim. For `email_verified: false`, fix the IdP-side verification. If your IdP emits email under a different claim name, set `oidc.email_claim`. +Log: `token exchange failed: id_token missing email claim`| The IdP isn’t including `email` in the id_token by default. This rejection fires only when `allowed_email_domains` is set; without it, a missing email mints a session with no email| Configure the IdP to emit `email` in the id_token. Okta: add `email` to a custom authorization server’s ID-token claims. Entra: add `email` as an optional claim on the app registration. PingFederate: enable an OpenID Connect Policy that emits `email`. If the IdP serves `email` from the userinfo endpoint but won’t include it in the id_token, such as the Okta org authorization server, set `oidc.userinfo_fallback: true`. +Every Bedrock request returns 502; log shows `Could not load credentials from any providers`| On EC2, IMDSv2’s default hop limit of 1 blocks the instance-metadata request from inside the container. Boot and `/readyz` pass anyway because the AWS SDK resolves instance credentials on the first request, not at client construction| Raise the hop limit with `aws ec2 modify-instance-metadata-options --instance-id <id> --http-put-response-hop-limit 2`, or set it in the launch template. The change applies to every container on the instance. Prefer ECS task roles where available, which read credentials from the ECS container-credentials endpoint and avoid the change entirely, or apply the change on a dedicated gateway instance to limit the exposure. +IdP error: unknown or unsupported scope| The IdP rejects scopes it doesn’t recognize| Set `oidc.scopes` to exactly the list your IdP accepts; it must include `openid`. The default is `openid profile email offline_access`. +Sessions don’t silently renew after setting `oidc.scopes`| `offline_access` was dropped from the override| Add `offline_access` back if your IdP supports it. Without a refresh token, developers re-run the browser login every `session.ttl_hours`. +Browser shows “This request came from another site and was blocked”| Cross-site form POST, blocked as CSRF protection. Expected for embedded or proxied pages| Open the verification link directly +Chrome blocks the Approve button with “Refused to send form data … violates … Content Security Policy directive: form-action”, but the same page works in Safari or Firefox| Chrome enforces `form-action` against the entire redirect chain. Your IdP redirects onward to a second host that isn’t allowlisted.| Add each additional origin in the redirect chain to `oidc.form_action_origins`. Open Chrome DevTools → Console on the Approve page to see which origin was blocked. +Sign-in completes at the IdP but the callback fails, with a CSP error in Chrome or “this sign-in link has expired” in Safari| The IdP returned the code via `response_mode=form_post`, which auto-submits it cross-origin via POST to `/oauth/callback`. Chrome blocks that under a strict CSP; Safari allows the submit but the callback reads only the query string.| Make sure your IdP honors `response_mode=query`, which the gateway requests explicitly so the callback is a plain redirect +Login works locally but fails behind an ALB| `public_url` not set, so the IdP gets the inner `http://` origin as `redirect_uri`| Set `listen.public_url` to the external `https://` origin +Developer sees the trust prompt repeatedly| TLS cert is rotating per replica or per request| Use a stable cert at the ingress, or terminate TLS once and run replicas over plain HTTP internally +CLI `/login`: “Could not verify the gateway’s TLS certificate” or `SELF_SIGNED_CERT_IN_CHAIN`| Gateway’s TLS chain is signed by a private CA not in the CLI host’s trust store| Claude Code reads the OS trust store by default on the native binary and on Node 22.15 or later; [`CLAUDE_CODE_CERT_STORE`](</docs/en/network-config#ca-certificate-store>) controls this behavior. If the CA is installed in the OS trust store, ensure developers are on a current runtime. Otherwise set `NODE_EXTRA_CA_CERTS` to the CA certificate PEM before launching. The first-connect fingerprint prompt still applies. + +## + +​ + +Related + + * [Claude apps gateway overview](</docs/en/claude-apps-gateway>): quickstart and developer connection + * [Configuration reference](</docs/en/claude-apps-gateway-config>): every `gateway.yaml` option
added Deploy Claude apps gateway on Google Cloud View current →
Show diff (309 lines)
--- a/claude-apps-gateway-on-gcp.md +++ b/claude-apps-gateway-on-gcp.md @@ -0,0 +1,306 @@ +This page walks through one way to run Claude apps gateway on Google Cloud. The configuration is a working example for customer-managed infrastructure rather than a supported production deployment; use it to see how the pieces fit together before adapting it to your own environment. For the platform-agnostic requirements, see the [deployment guide](</docs/en/claude-apps-gateway-deploy>). + +This example provisions Claude apps gateway on Google Cloud with Google Cloud’s Agent Platform as the model upstream, using either Cloud Run or GKE for compute. Google Workspace is the example identity provider (IdP), but any OpenID Connect (OIDC) compliant IdP works; only the `oidc` block changes. See [Identity provider setup](</docs/en/claude-apps-gateway-deploy#identity-provider-setup>) for per-IdP details. + +## + +​ + +What you’ll build + +The reference configuration provisions: + + * **Cloud Run** service or **GKE** Deployment running the gateway container + * **Artifact Registry** repository for the gateway image + * **Cloud SQL for PostgreSQL** instance, private IP only, for the gateway’s [store](</docs/en/claude-apps-gateway-config#store>) + * **Secret Manager** secrets for `gateway.yaml`, the JWT signing key, the OIDC client secret, and the Postgres URL + * **Service account** with `roles/aiplatform.user`, attached directly on Cloud Run or bound via Workload Identity on GKE + * **Internal Application Load Balancer** on Cloud Run, or an internal **GKE Ingress** of class `gce-internal` on GKE, for HTTPS + +## + +​ + +Prerequisites + + * A GCP project with billing enabled, and permission to create the resources above + * The `gcloud` CLI, authenticated with `gcloud auth login`, and Docker installed locally + * For the GKE track: `kubectl`, and a GKE cluster on the VPC created in the walkthrough below + * Access to the Claude models you need in Model Garden, in a region that publishes them + * A Google Workspace OAuth 2.0 web-application client with redirect URI `https://<gateway-host>/oauth/callback`; see [Identity provider setup](</docs/en/claude-apps-gateway-deploy#identity-provider-setup>) + * A TLS hostname for the gateway, typically an internal DNS name pointing at the load balancer + +Set the project and region once: + + export PROJECT_ID=<your-project> + export REGION=us-east5 # a region where the Claude models you need are published in Model Garden + gcloud config set project "$PROJECT_ID" + +## + +​ + +Deploy the gateway + +The steps below provision the full deployment with `gcloud` commands. + +1 + +Enable APIs + +Enable the service APIs the walkthrough uses: + + gcloud services enable \ + aiplatform.googleapis.com \ + artifactregistry.googleapis.com \ + sqladmin.googleapis.com \ + secretmanager.googleapis.com \ + iamcredentials.googleapis.com \ + iam.googleapis.com \ + compute.googleapis.com \ + servicenetworking.googleapis.com \ + run.googleapis.com \ + container.googleapis.com + +The APIs you need depend on the deployment path: + + * `compute` and `servicenetworking`: needed for the private-IP Cloud SQL path + * `run`: Cloud Run only + * `container`: GKE only + +2 + +Create the service account and grant IAM + +The gateway runs as a dedicated service account with permission to call Agent Platform. It reaches Cloud SQL over the VPC with a password user, so no Cloud SQL IAM role is required: + + gcloud iam service-accounts create claude-gateway --display-name="Claude apps gateway" + SA="claude-gateway@${PROJECT_ID}.iam.gserviceaccount.com" + + gcloud projects add-iam-policy-binding "$PROJECT_ID" \ + --member="serviceAccount:${SA}" --role="roles/aiplatform.user" --condition=None + +Then enable the Claude models for the project in Model Garden; models publish to specific regions, so check each model card. + +3 + +Build and push the image to Artifact Registry + +Build the image per the [container image requirements](</docs/en/claude-apps-gateway-deploy#container-image>), using the `linux-x64` glibc binary, and push it: + + gcloud artifacts repositories create claude-gateway \ + --repository-format=docker --location="$REGION" + gcloud auth configure-docker "${REGION}-docker.pkg.dev" --quiet + + # Cloud Run requires linux/amd64. --provenance=false avoids a buildx OCI + # image index that Cloud Run rejects. + docker build --platform=linux/amd64 --provenance=false \ + -t "${REGION}-docker.pkg.dev/${PROJECT_ID}/claude-gateway/gateway:<version>" . + docker push "${REGION}-docker.pkg.dev/${PROJECT_ID}/claude-gateway/gateway:<version>" + +4 + +Provision Cloud SQL for PostgreSQL + +Create the instance on a VPC via Private Services Access so it has no public IP; this also satisfies projects where `constraints/sql.restrictPublicIp` is enforced: + + VPC=cc-gateway-vpc + gcloud compute networks create "$VPC" --subnet-mode=custom + gcloud compute networks subnets create cc-gateway-subnet \ + --network="$VPC" --region="$REGION" --range=10.0.0.0/24 + + # Private Services Access: one-time per VPC + gcloud compute addresses create "google-managed-services-${VPC}" \ + --global --purpose=VPC_PEERING --prefix-length=16 --network="$VPC" + gcloud services vpc-peerings connect \ + --service=servicenetworking.googleapis.com \ + --ranges="google-managed-services-${VPC}" --network="$VPC" + + gcloud sql instances create claude-gateway-db \ + --database-version=POSTGRES_16 --tier=db-g1-small --region="$REGION" \ + --network="projects/${PROJECT_ID}/global/networks/${VPC}" --no-assign-ip + gcloud sql databases create claude_gateway --instance=claude-gateway-db + PGPASS="$(openssl rand -hex 24)" + gcloud sql users create gateway --instance=claude-gateway-db --password="$PGPASS" + + PRIVATE_IP="$(gcloud sql instances describe claude-gateway-db \ + --format='value(ipAddresses[0].ipAddress)')" + GATEWAY_POSTGRES_URL="postgres://gateway:${PGPASS}@${PRIVATE_IP}:5432/claude_gateway?sslmode=require" + +The Cloud Run or GKE runtime must be on, or routed into, this VPC. + +5 + +Write gateway.yaml + +The `upstreams` block points at Agent Platform with `auth: {}`, so the gateway authenticates via Application Default Credentials from the runtime service account. See the [configuration reference](</docs/en/claude-apps-gateway-config>) for every field.Two `listen` fields depend on what fronts the gateway: + + * `public_url`: required behind Cloud Run or a GKE Ingress. The gateway builds the IdP `redirect_uri` and its discovery document only from this value, never from `X-Forwarded-*` headers. + * `trusted_proxies`: the front end’s source ranges. The gateway honors `X-Forwarded-For` only when the TCP peer is in this list, then walks the chain past trusted hops, so per-IP sign-in rate limits and audit events record developer IPs instead of the load balancer’s. + +Set `trusted_proxies` to match your front end. An external GKE Ingress of class `gce` isn’t listed: it provisions a public forwarding-rule address, which the `/login` [private-network check](</docs/en/claude-apps-gateway#prerequisites>) rejects. + +Front end| `trusted_proxies` +---|--- +Cloud Run reached directly, no load balancer| `[169.254.0.0/16]` +Internal Application Load Balancer in front of Cloud Run| `169.254.0.0/16` plus your proxy-only subnet’s CIDR +GKE internal Ingress, class `gce-internal`| Your proxy-only subnet’s CIDR + +The example below uses the internal-load-balancer-in-front-of-Cloud-Run values. + +gateway.yaml + + listen: + host: 0.0.0.0 + port: 8080 + public_url: https://claude-gateway.internal.example.com + trusted_proxies: [169.254.0.0/16, <your-proxy-only-subnet-cidr>] + + oidc: + issuer: https://accounts.google.com + client_id: <your-oauth-client-id> + client_secret: ${OIDC_CLIENT_SECRET} # GKE: ${file:/secrets/oidc-client-secret} + allowed_email_domains: [example.com] + # Google ignores offline_access; these yield refresh tokens: + scopes: [openid, profile, email] + extra_auth_params: { access_type: offline, prompt: consent } + + session: + jwt_secret: ${GATEWAY_JWT_SECRET} # GKE: ${file:/secrets/jwt-secret} + + store: + postgres_url: ${GATEWAY_POSTGRES_URL} # GKE: ${file:/secrets/postgres-url} + + upstreams: + - provider: vertex + region: <your-region> # must match $REGION + project_id: <your-project> + auth: {} # ADC via the runtime service account + +Google id_tokens carry no `groups` claim. To use group-based policies in [`managed.policies`](</docs/en/claude-apps-gateway-config#managed>) with Google Workspace as the IdP, configure [`oidc.google_groups`](</docs/en/claude-apps-gateway-config#oidc>), which looks up each user’s groups through the Admin SDK Directory API using a service account with domain-wide delegation. Without it, match on `email_domain` instead. + +6 + +Store secrets in Secret Manager + +Create four secrets and grant `roles/secretmanager.secretAccessor` to the `claude-gateway` service account: + +Secret| Source +---|--- +`gateway-jwt-secret`| `openssl rand -base64 32` +`gateway-oidc-client-secret`| Google Cloud Console → OAuth client +`gateway-postgres-url`| `$GATEWAY_POSTGRES_URL` from the Cloud SQL step +`gateway-config`| the full `gateway.yaml` from the previous step + +How the secrets reach the container differs by track: + + * On GKE they mount as files via the Secret Manager CSI driver, and `gateway.yaml` references `${file:/secrets/...}`. + * On Cloud Run, which can’t mount multiple secrets into one directory, `gateway.yaml` mounts as a file and the other three inject as environment variables, so `gateway.yaml` references `${GATEWAY_JWT_SECRET}`, `${OIDC_CLIENT_SECRET}`, and `${GATEWAY_POSTGRES_URL}` instead. + +7 + +Deploy + + * Cloud Run + + * GKE + +The command below deploys for production behind an internal load balancer. + + gcloud run deploy claude-gateway \ + --image="${REGION}-docker.pkg.dev/${PROJECT_ID}/claude-gateway/gateway:<version>" \ + --region="$REGION" \ + --service-account="claude-gateway@${PROJECT_ID}.iam.gserviceaccount.com" \ + --min-instances=1 \ + --timeout=3600 \ + --ingress=internal-and-cloud-load-balancing \ + --network="$VPC" --subnet=cc-gateway-subnet --vpc-egress=private-ranges-only \ + --set-secrets=/etc/claude/gateway.yaml=gateway-config:latest,GATEWAY_JWT_SECRET=gateway-jwt-secret:latest,OIDC_CLIENT_SECRET=gateway-oidc-client-secret:latest,GATEWAY_POSTGRES_URL=gateway-postgres-url:latest \ + --no-invoker-iam-check + +Direct VPC egress, via `--network`, `--subnet`, and `--vpc-egress=private-ranges-only`, lets the service reach the Cloud SQL private IP directly. Public egress to the Agent Platform endpoints and `accounts.google.com` goes directly to the internet rather than through the VPC, so no Cloud NAT is needed.The invoker IAM check must be open or disabled. The gateway runs its own OIDC and its clients carry no GCP token, so Cloud Run’s invoker check has to admit unauthenticated requests. The gateway’s OIDC sign-in authenticates the request once it reaches the container, with `allowed_email_domains` gating which domains may sign in.Two flags admit unauthenticated requests: + + * `--no-invoker-iam-check`: disables the check with no `allUsers` binding to manage, and works under Domain Restricted Sharing + * `--allow-unauthenticated`: grants `allUsers` the `run.invoker` role; use it if your organization doesn’t allow `--no-invoker-iam-check` + +Ingress restriction via `--ingress` is a separate, independent layer from the invoker check; keep it set to limit the service to your corporate network.By default the Cloud Run `*.run.app` URL resolves to a public address, which the `/login` [private-network check](</docs/en/claude-apps-gateway#prerequisites>) rejects. Two topologies give developers a privately resolvable hostname, and Cloud Run provisions neither for you: + + * **Internal Application Load Balancer** , the topology the deploy command above assumes: deploy with `--ingress=internal-and-cloud-load-balancing`, provision an internal Application Load Balancer in front of the service with an internal DNS name and certificate, and set `listen.public_url` to that hostname. + * **Internal-only ingress with no load balancer** : deploy with `--ingress=internal` and leave `listen.public_url` as the `*.run.app` URL, the default in the reference assets below. For `*.run.app` to resolve privately, your network team must already operate a Private Service Connect endpoint for Google APIs, a Cloud DNS private zone resolving `*.run.app` to it, and on-premises routing to that endpoint. + +Google’s [private networking guide for Cloud Run](<https://cloud.google.com/run/docs/securing/private-networking>) covers the infrastructure both options need. Verify sign-in once the gateway is serving on a private hostname; until then, confirm the container booted from its logs in Cloud Run.Update the OAuth client’s authorized redirect URI to `<public_url>/oauth/callback` before the first sign-in. Redeploy after changing `public_url`, because the gateway builds its public origin only from that setting and ignores `X-Forwarded-Host` and `X-Forwarded-Proto`. `X-Forwarded-For` is honored for client IPs only when `listen.trusted_proxies` is set. + +The cluster must be on the `$VPC` created in the Cloud SQL step so pods can reach the database’s private IP; VPC peering alone doesn’t work, because Cloud SQL private IP is itself a peered network and peering is non-transitive. To create a new cluster on that VPC, pass `--network="$VPC" --subnetwork=cc-gateway-subnet` to `gcloud container clusters create`.Enable Workload Identity on the cluster and its node pools, then bind the Google service account to the Kubernetes service account so pods inherit its credentials: + + gcloud container clusters update <cluster> --region="$REGION" \ + --workload-pool="${PROJECT_ID}.svc.id.goog" + # On a Standard cluster, existing node pools also need GKE_METADATA; + # Autopilot enables this by default. + gcloud container node-pools update <pool> --cluster=<cluster> \ + --region="$REGION" --workload-metadata=GKE_METADATA + + kubectl create namespace claude-gateway + kubectl create serviceaccount gateway -n claude-gateway + + gcloud iam service-accounts add-iam-policy-binding \ + "claude-gateway@${PROJECT_ID}.iam.gserviceaccount.com" \ + --role roles/iam.workloadIdentityUser \ + --member "serviceAccount:${PROJECT_ID}.svc.id.goog[claude-gateway/gateway]" + + kubectl annotate serviceaccount gateway -n claude-gateway \ + iam.gke.io/gcp-service-account="claude-gateway@${PROJECT_ID}.iam.gserviceaccount.com" + +Deploy the gateway as a standard Deployment plus a Service and an internal Ingress, class `gce-internal`, as described in [Kubernetes deployment](</docs/en/claude-apps-gateway-deploy#kubernetes>), with: + + * `serviceAccountName: gateway` + * the Secret Manager CSI driver mounting secrets at `/secrets` + * the readiness probe pointed at `GET /readyz` + +Attach a BackendConfig with a raised `timeoutSec` to the gateway Service: the load balancer backend service behind GKE Ingress defaults to a 30-second timeout, which cuts off long streaming responses.Don’t apply an egress NetworkPolicy that blocks `169.254.169.254` on a Workload Identity cluster; the pod must reach the metadata server for credentials. The gateway’s built-in [SSRF guard](</docs/en/claude-apps-gateway-deploy#threat-model-summary>) is the defense there.The gateway logs a boot warning that the metadata endpoint is reachable and suggests applying an egress NetworkPolicy. Under Workload Identity that warning is expected, because the pod needs the endpoint. + +8 + +Push the gateway URL to developer machines + +The gateway is now running, but developers can’t reach it from `/login` until the gateway URL is on their machines. Set `forceLoginMethod` and `forceLoginGatewayUrl` in the [managed settings file](</docs/en/claude-apps-gateway#set-the-gateway-url>) you deploy to each device via MDM. There is no gateway option in the login picker for a developer to select manually. + +## + +​ + +Terraform reference + +The [reference deployment assets](<https://github.com/anthropics/claude-code/tree/main/examples/gateway/gcp>) automate the Cloud Run track on this page; the config and image assets apply to both tracks: + + * `setup.sh`: an idempotent `gcloud` provisioner that walks the full Cloud Run path, from enabling APIs through the first deploy + * `terraform/`: the same deployment as infrastructure-as-code, for a greenfield deploy: a targeted apply to create the Artifact Registry repo, then build and push the image, then a full apply + * `gateway.yaml.example` and a `Dockerfile` for the distroless runtime image + +The artifacts default Cloud Run ingress to `internal`, so no load balancer is required. To match this page’s production-behind-an-ALB deployment, run `setup.sh` with `INGRESS=internal-and-cloud-load-balancing`, or set the Terraform variable `ingress` to `INGRESS_TRAFFIC_INTERNAL_LOAD_BALANCER`. The artifacts also default the invoker layer to an `allUsers` `run.invoker` grant rather than `--no-invoker-iam-check`, the inverse of this page’s walkthrough; either works, and the choice depends on your organization’s policy constraints. The assets are provided as working examples, not as a supported production artifact; review and adapt them to your environment. + +## + +​ + +Troubleshooting + +For gateway boot and login errors, see the platform-agnostic [troubleshooting table](</docs/en/claude-apps-gateway-deploy#troubleshooting>). The entries below are specific to Google Cloud. + +Symptom| Cause| Fix +---|---|--- +Cloud Run returns `403 Forbidden` before reaching the container| The invoker IAM check is still enabled| Deploy with `--no-invoker-iam-check`, or grant `allUsers` the `run.invoker` role with `--allow-unauthenticated` +`--no-invoker-iam-check` rejected with `invoker_iam_disabled is not currently available`| Blocked by `constraints/run.managed.requireInvokerIam`| Use `--allow-unauthenticated`. If Domain Restricted Sharing via `constraints/iam.allowedPolicyMemberDomains` blocks that too, use the GKE track, which exposes the gateway at the network layer with no `allUsers` binding. +`Container manifest type … must support amd64/linux` at deploy| Image was built on a non-amd64 host, or buildx emitted an OCI image index| Build with `--platform=linux/amd64 --provenance=false` +Gateway boot exits with a Postgres connection-timeout error on Cloud Run| Service isn’t attached to the VPC, or Cloud SQL has no private IP on that VPC; the store stops waiting after 5 seconds| Deploy with `--network` and `--subnet` for Direct VPC egress, and create the Cloud SQL instance with `--no-assign-ip` and `--network` pointing at the same VPC +Agent Platform requests return `403 PERMISSION_DENIED`| Runtime isn’t using the `claude-gateway` service account, or the model isn’t enabled in Model Garden for the project| Set `--service-account` on Cloud Run or bind Workload Identity on GKE, and enable each Claude model in Model Garden for the target region +Streaming responses cut off after a fixed duration| Front-end request timeout: the load balancer backend service behind GKE Ingress defaults to 30 seconds and Cloud Run to 300 seconds| Attach a BackendConfig with a raised `timeoutSec` on GKE, or deploy with `--timeout=3600` on Cloud Run + +## + +​ + +Next steps + + * [Configuration reference](</docs/en/claude-apps-gateway-config>): every `gateway.yaml` option, including `managed.policies` and `telemetry` + * [Deployment and operations](</docs/en/claude-apps-gateway-deploy>): IdP setup, health checks, JWT secret rotation, upgrades, and the security model + * [Claude apps gateway overview](</docs/en/claude-apps-gateway>): quickstart and connecting developers
added Claude apps gateway spend limits View current →
Show diff (153 lines)
--- a/claude-apps-gateway-spend-limits.md +++ b/claude-apps-gateway-spend-limits.md @@ -0,0 +1,150 @@ +Spend limits cap how much each developer can spend through your [Claude apps gateway](</docs/en/claude-apps-gateway>) in a given day, week, or month. When a developer passes their cap, the gateway returns `429` on their next request and blocks them until the period resets or an admin raises the cap. Use spend limits to give each developer, group, or the whole organization a ceiling on a credential everyone shares. A Claude apps gateway forwards all inference through one shared upstream credential, so your provider’s bill attributes everything to that credential, not to individual developers. Without per-developer limits, one runaway agent fleet can spend the organization’s entire commitment. Spend limits are the gateway’s per-developer view and circuit breaker on top of that shared bill. + +## + +​ + +Set a cap + +With the [`admin:`](</docs/en/claude-apps-gateway-config#admin>) block configured in `gateway.yaml`, the gateway serves an admin API at `/v1/organizations/spend_limits` and enforces caps live on every inference request. Caps themselves are set through that API, not in `gateway.yaml`; each `POST /v1/organizations/spend_limits` request creates or replaces one cap from `{scope, amount, period}`. The API mirrors the wire shapes of Anthropic’s public [Admin API](<https://platform.claude.com/docs/en/manage-claude/admin-api>) spend-limits endpoints, so an HTTP client written against that contract can target the gateway by changing its base URL. This request sets an org-wide default of $500 per month for every developer: + + curl -sS https://claude-gateway.internal.example.com/v1/organizations/spend_limits \ + -H "x-api-key: $GATEWAY_ADMIN_WRITE_KEY" \ + -H "Content-Type: application/json" \ + -d '{"scope": {"type": "organization"}, "amount": "50000", "period": "monthly"}' + +This request layers a tighter $100-per-day cap on each member of the `contractors` group: + + curl -sS https://claude-gateway.internal.example.com/v1/organizations/spend_limits \ + -H "x-api-key: $GATEWAY_ADMIN_WRITE_KEY" \ + -H "Content-Type: application/json" \ + -d '{"scope": {"type": "rbac_group", "rbac_group_id": "contractors"}, "amount": "10000", "period": "daily"}' + +Field| Values| Description +---|---|--- +`scope.type`| `user`, `rbac_group`, `organization`| `user` targets one developer by their OpenID Connect (OIDC) `sub`, the stable user ID your identity provider assigns; pass it as `scope.user_id`. `rbac_group` targets an [IdP group](</docs/en/claude-apps-gateway-config#managed>) by name; pass it as `scope.rbac_group_id`. `organization` is the org-wide default. The gateway accepts all three; Anthropic’s public `POST` is user-only today. +`amount`| Whole-number string of USD cents, or `null`| `null` is unlimited. `"0"` is a zero cap, which blocks every request. +`period`| `daily`, `weekly`, `monthly`| A scope can hold one cap per period, and each enforces independently: a developer is blocked if over any of them. + +A group or organization cap is a per-seat default that each member inherits, not a shared pool. Per period, a developer’s effective cap resolves in this order: a per-user override, then the most restrictive of their group caps, then the org default, then unlimited. [`admin.group_limit_mode: max`](</docs/en/claude-apps-gateway-config#admin>) flips the multi-group tie-break to least-restrictive instead. + +### + +​ + +Authenticate to the admin API + +Send one of: + + * An `x-api-key` header matching a key in [`admin.write_keys`](</docs/en/claude-apps-gateway-config#admin>) for full access, or `admin.read_keys` for `GET`-only access. Each key carries an `id` that appears in the audit log as `admin-key:<id>`, so give Terraform, CI, and each automation its own. + * A gateway bearer token whose `groups` claim includes one of [`admin.admin_groups`](</docs/en/claude-apps-gateway-config#admin>). This is full access and audits as `oidc:<sub>`, so prefer it for human admins. + +## + +​ + +How enforcement works + +On each `/v1/messages` request, the gateway resolves the developer’s caps and period-to-date spend in one Postgres query. If they’re over any cap, the request returns `429` with `error.type: billing_error` and the header `x-should-retry: false`. The message is `spend limit reached`, followed by your [`admin.blocked_message`](</docs/en/claude-apps-gateway-config#admin>) if set. `/v1/messages/count_tokens` is exempt. Token counting is free, so it runs regardless of cap state. After each response, a usage meter reads token counts off the response as it streams to the client, prices them at USD list price, and increments Postgres counters for all three period buckets. The meter is a single reader on the stream, so the client’s bytes are untouched and a metering failure doesn’t break the response. Spend limits estimate spend from token counts at USD list price; they’re a circuit breaker, not an invoice. For authoritative billing, reconcile against your provider’s own usage reporting, such as the Anthropic Usage & Cost Admin API, invocation logs on Bedrock, or Cloud Monitoring on Google Cloud. Pricing uses the same table the Claude Code CLI uses for its own cost display, with the same model-ID canonicalization across Anthropic, Bedrock (`us.anthropic.…-v1:0`), Agent Platform (`claude-…@date`), and Foundry ID forms. A model ID the table can’t place, such as a Foundry deployment name or an inference-profile ARN, is priced at the unknown-model default tier of $5/$25 per million input/output tokens rather than zero, so an unrecognized ID can’t bypass a cap by going unmetered. The gateway warns at boot and once per ID at runtime when a model prices through the fallback. Client aborts are billed too. The upstream reports output tokens only in the stream’s terminal frame, so an aborted stream doesn’t carry them. The meter keeps a conservative floor estimate from the streamed content size, about four characters per token, and bills it when and only when the terminal usage frame is missing. A complete stream always bills the upstream-reported count. Without this, a capped developer could stream output and abort each request immediately before the end, spending without ever being counted. + +### + +​ + +Postgres availability + +The pre-check queries Postgres with a two-second timeout. If the store is unreachable or times out, enforcement fails open by default: the request proceeds and the gateway logs a warning. Set [`enforcement.fail_closed_on_error: true`](</docs/en/claude-apps-gateway-config#enforcement>) to fail closed instead, which returns the same `429 billing_error` with the message `spend limit unavailable`. Fail-open keeps a store outage from becoming an inference outage; fail-closed guarantees no unmetered spend. + +## + +​ + +Admin API reference + +The endpoints below are served under `/v1/organizations/spend_limits`. + +Method and path| Description +---|--- +`GET /v1/organizations/spend_limits`| List configured caps. Query: `?limit=&after_id=&before_id=`. +`POST /v1/organizations/spend_limits`| Create or replace a cap for `{scope, period}`. +`GET /v1/organizations/spend_limits/{id}`| Fetch one cap by its `spl_`-prefixed ID. +`DELETE /v1/organizations/spend_limits/{id}`| Delete one cap. Returns `{type: "spend_limit_deleted", id}`. +`GET /v1/organizations/spend_limits/effective`| Resolved cap and to-date spend per principal per period. +`GET /v1/organizations/spend_limits/audit`| Admin mutation trail, newest-first. Query: `?limit=`. + +Conventions mirror Anthropic’s Admin API: + + * A `type` on every object + * `spl_`-prefixed IDs + * Amounts as whole-number strings of USD cents; `POST` rejects any other `currency` with `400` + * The `{type: "error", error: {type, message}, request_id}` error envelope + * A `request-id` response header on every admin response, success or error, matching the body’s `request_id` + +Every mutation writes a before/after row to `admin_audit` in the same transaction, attributed to `admin-key:<id>` or `oidc:<sub>`. The gateway serves the spend-limits endpoints only. Other Admin API surfaces, such as the `spend_limit_increase_requests` queue, aren’t part of the gateway’s admin API. + +### + +​ + +`/effective` + +`GET /v1/organizations/spend_limits/effective` returns Anthropic’s `SpendSummary` schema: each row is a principal for a period, with the resolved cap, period-to-date spend, and an `actor` object. Gateway-specific differences: + + * `user_id` is the OIDC `sub`. + * `actor.name` and `actor.email_address` are `null` until the principal’s first inference request through the gateway. The gateway has no user directory; it records last-seen values from each user’s own session JWT. + * Each row also carries a `groups` array, the principal’s last-seen IdP groups. This is a gateway extension so an admin UI can show every cap tier that applies; Anthropic-shaped clients ignore it. + * Without a `user_ids[]` filter, it lists principals with recorded spend, because the gateway can’t enumerate all org members. + +Group-sourced caps resolve against those last-seen groups with the same `group_limit_mode` tie-break that enforcement uses, so the viewer shows the cap that actually applies. + +Query parameter| Description +---|--- +`user_ids[]`| Repeatable. Filter to specific principals by OIDC `sub`. +`period[]`| Repeatable. Filter to `daily`, `weekly`, or `monthly` rows. +`sort`| `spend_desc` lists top spenders first. Requires exactly one `period[]`. +`q`| Case-insensitive substring filter over the OIDC `sub`, last-seen email, and last-seen display name. +`limit` / `page`| Page size, 1–1000 with a default of 20, and the opaque cursor from the previous response’s `next_page`. + +`q=` and `user_ids[]=` ride GET query strings, so any fronting proxy or load balancer captures them in its access logs. If your PII log policy is strict, scrub these parameters there. + +### + +​ + +`/audit` + +Returns the spend-limit mutation trail: who changed which cap, before/after snapshots, and the optional reason, newest-first. `has_more` is exact. This endpoint follows the local Admin API conventions rather than a first-party wire shape. + +### + +​ + +Pagination + +The raw list pages by `after_id` and `before_id`, which are mutually exclusive `spl_…` IDs; results are ordered by creation and `has_more` reflects the traversal direction. `/effective` pages by the opaque `next_page` token passed back as `?page=`, with principals ordered ascending so pages stay stable while spend is being recorded. `limit` is 1–1000, default 20, on both. + +## + +​ + +Data lifecycle + +The gateway holds four spend-related tables; an hourly sweep enforces the retention windows: + +Table| Contents| Retention +---|---|--- +`spend`| Per-principal period-to-date counters in cents| [`admin.spend_retention_months`](</docs/en/claude-apps-gateway-config#admin>), default 13 +`spend_limits`| The configured caps| Until deleted via the API +`admin_audit`| The mutation trail| [`admin.audit_retention_days`](</docs/en/claude-apps-gateway-config#admin>), default 365 +`principal_emails`| Each principal’s last-seen email, display name, and IdP groups. Contains PII.| [`admin.identity_retention_days`](</docs/en/claude-apps-gateway-config#admin>) since last activity, default 90 + +`identity_retention_days` is deliberately shorter than `spend_retention_months`: a deprovisioned identity stops refreshing and ages out, while its anonymous spend counters remain for year-over-year reporting. When a developer leaves, delete any per-user cap via `DELETE /v1/organizations/spend_limits/{id}`; their spend and identity rows age out on the retention windows above. To erase one person immediately, for offboarding or a data subject access request (DSAR), run `DELETE FROM principal_emails WHERE principal = '<sub>'` directly against the gateway database. That removes the only table holding their email, name, and groups. The `spend` and `admin_audit` rows reference the pseudonymous OIDC `sub` only and age out on their own windows. + +## + +​ + +Related + + * [`admin` and `enforcement` configuration](</docs/en/claude-apps-gateway-config#admin>): enabling the admin API and tuning retention + * [Deployment guide](</docs/en/claude-apps-gateway-deploy#postgres>): Postgres schema and backup guidance
modified Use Claude Code on the web View current →
--- a/claude-code-on-the-web.md +++ b/claude-code-on-the-web.md @@ -559,6 +559,7 @@ * *.sentry.io * downloads.sentry-cdn.com * http-intake.logs.datadoghq.com + * browser-intake-us5-datadoghq.com * *.datadoghq.com * *.datadoghq.eu * api.honeycomb.io @@ -603,7 +604,7 @@ claude --remote "Fix the authentication bug in src/auth/login.ts" -This creates a new cloud session on claude.ai. The session clones your current directory’s GitHub remote at your current branch, so push first if you have local commits, since the VM clones from GitHub rather than your machine. `--remote` works with a single repository at a time. The task runs in the cloud while you continue working locally. +This creates a new cloud session on claude.ai. The session clones your current directory’s GitHub remote at your current branch, so push first if you have local commits, since the VM clones from GitHub rather than your machine. `--remote` works with a single repository at a time. The task runs in the cloud while you continue working locally. As of v2.1.195, the CLI shows a live checklist of setup steps, such as cloning the repository and running your setup script, while the cloud container starts. Messages you type while the container is provisioning are queued and sent once the session is ready. `--remote` creates cloud sessions. `--remote-control` is unrelated: it exposes a local CLI session for monitoring from the web. See [Remote Control](</docs/en/remote-control>).
modified CLI reference View current →
--- a/cli-reference.md +++ b/cli-reference.md @@ -16,6 +16,7 @@ `claude -c -p "query"`| Continue via SDK| `claude -c -p "Check for type errors"` `claude -r "<session>" "query"`| Resume session by ID or name| `claude -r "auth-refactor" "Finish this PR"` `claude update`| Update to latest version| `claude update` +`claude gateway`| Start the self-hosted [Claude apps gateway](</docs/en/claude-apps-gateway>) server, for administrators deploying SSO and policy in front of Claude Code on Bedrock, Vertex AI, or Foundry. Requires `--config` pointing at a [`gateway.yaml`](</docs/en/claude-apps-gateway-config>). Available in Claude Code v2.1.195 and later.| `claude gateway --config gateway.yaml` `claude install [version]`| Install or reinstall the native binary. Accepts a version like `2.1.118`, or `stable` or `latest`. See [Install a specific version](</docs/en/setup#install-a-specific-version>)| `claude install stable` `claude auth login`| Sign in to your Anthropic account. Use `--email` to pre-fill your email address, `--sso` to force SSO authentication, and `--console` to sign in with Anthropic Console for API usage billing instead of a Claude subscription| `claude auth login --console` `claude auth logout`| Log out from your Anthropic account| `claude auth logout`
modified Commands View current →
--- a/commands.md +++ b/commands.md @@ -46,6 +46,8 @@ `/cost`| Alias for `/usage` `/debug [description]`| **[Skill](</docs/en/skills#bundled-skills>).** Enable debug logging for the current session and troubleshoot issues by reading the session debug log. Debug logging is off by default unless you started with `claude --debug`, so running `/debug` mid-session starts capturing logs from that point forward. Optionally describe the issue to focus the analysis `/deep-research <question>`| **[Workflow](</docs/en/workflows#bundled-workflows>).** Fan out web searches on a question, fetch and cross-check sources, and synthesize a cited report +`/design-login`| Authorize design-system access for `/design-sync` with your claude.ai account +`/design-sync [hint]`| **[Skill](</docs/en/skills#bundled-skills>).** Convert your repo’s React design system and upload it to [Claude Design](<https://claude.ai/design>), so designs it produces use your real components. Optionally name the design system, for example `/design-sync Acme DS`. A first-time sync verifies every component and can take a few hours on a large repo. Available on the Anthropic API; on Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry the underlying tool can’t reach claude.ai, so the command is unavailable `/desktop`| Continue the current session in the Claude Code Desktop app. Requires macOS or Windows and a Claude subscription. Alias: `/app` `/diff`| Open an interactive diff viewer showing uncommitted changes and per-turn diffs. Use left/right arrows to switch between the current git diff and individual Claude turns, and up/down to browse files `/doctor`| Diagnose and verify your Claude Code installation and settings. Results show with status icons. Press `f` to have Claude fix any reported issues
modified Let Claude use your computer from the CLI View current →
--- a/computer-use.md +++ b/computer-use.md @@ -106,7 +106,7 @@ One session at a time -Computer use holds a machine-wide lock while active. If another Claude Code session is already using your computer, new attempts fail with a message telling you which session holds the lock. Finish or exit that session first. +Computer use holds a machine-wide lock from the first computer use action until the session that took it exits. As of v2.1.195, finishing the task doesn’t release the lock; only exiting the session does. If another Claude Code session is already using your computer, new attempts fail with a message telling you which session holds the lock. Exit that session first. ### @@ -130,7 +130,7 @@ Stop at any time -When Claude acquires the lock, a macOS notification appears: “Claude is using your computer · press Esc to stop.” Press `Esc` anywhere to abort the current action immediately, or press `Ctrl+C` in the terminal. Either way, Claude releases the lock, unhides your apps, and returns control to you. A second notification appears when Claude is done. +When Claude acquires the lock, a macOS notification appears: “Claude is using your computer · press Esc to stop.” Press `Esc` anywhere to abort the current action immediately, or press `Ctrl+C` in the terminal. Either way, Claude stops, unhides your apps, and returns control to you. The session keeps the computer use lock until it exits. A second notification appears when Claude is done. ## @@ -225,7 +225,7 @@ ”Computer use is in use by another Claude session” -Another Claude Code session holds the lock. Finish the task in that session or exit it. If the other session crashed, the lock is released automatically when Claude detects the process is no longer running. +Another Claude Code session holds the lock, which it keeps until it exits. Exit that session. If the other session crashed, the lock is released automatically when Claude detects the process is no longer running. ###
modified Manage costs effectively View current →
--- a/costs.md +++ b/costs.md @@ -33,7 +33,7 @@ When you first authenticate Claude Code with your Claude Console account, a workspace called “Claude Code” is automatically created for you. This workspace provides centralized cost tracking and management for all Claude Code usage in your organization. You cannot create API keys for this workspace; it is exclusively for Claude Code authentication and usage.For organizations with custom rate limits, Claude Code traffic in this workspace counts toward your organization’s overall API rate limits. You can set a [workspace rate limit](<https://platform.claude.com/docs/en/api/rate-limits#setting-lower-limits-for-workspaces>) on this workspace’s Limits page in the Claude Console to cap Claude Code’s share and protect other production workloads. -On Bedrock, Vertex, and Foundry, Claude Code does not send metrics from your cloud. Organizations that already route Claude Code through an [LLM gateway](</docs/en/llm-gateway>) can track spend there, since the gateway sees every request. +On Bedrock, Vertex, and Foundry, Claude Code doesn’t send metrics from your cloud. A self-hosted [Claude apps gateway](</docs/en/claude-apps-gateway>) provides per-user usage attribution, OTLP metrics with token counts, and [per-user spend limits](</docs/en/claude-apps-gateway-spend-limits>) on these providers. Organizations that route Claude Code through a different [LLM gateway](</docs/en/llm-gateway>) can track spend at the gateway instead, since it sees every request. ###
modified Data usage View current →
--- a/data-usage.md +++ b/data-usage.md @@ -36,7 +36,7 @@ When you see the “How is Claude doing this session?” prompt in Claude Code, responding to this survey, including selecting “Dismiss”, records only your rating. We do not collect or store any conversation transcripts, inputs, outputs, or other session data as part of the rating prompt itself. Unlike thumbs up/down feedback or `/feedback` reports, this session quality survey is a simple product satisfaction metric. After the rating prompt, you may see a separate follow-up asking “Can Anthropic look at your session transcript to help us improve Claude Code?”. This is an optional second step distinct from the rating: - * **Yes** : uploads your conversation transcript, any subagent transcripts, and the raw session log file from disk to Anthropic. Known API key and token patterns are redacted before upload. Source code, file contents, and other conversation content are uploaded as-is. Shared transcripts are retained for up to 6 months. + * **Yes** : uploads your conversation transcript, any subagent transcripts, and the raw session log file from disk to Anthropic. Known API key and token patterns are redacted before upload. Source code, file contents, and other conversation content are uploaded as-is. Shared transcripts are retained for up to 6 months. On Bedrock, Vertex AI, Foundry, and signed-in [Claude apps gateway](</docs/en/claude-apps-gateway>) sessions, Yes writes the same payload to a local archive under `~/.claude/feedback-bundles/` instead of uploading; nothing leaves your machine until you forward that file. * **No** : declines without sending anything * **Don’t ask again** : declines and stops this follow-up from appearing in future sessions @@ -116,7 +116,7 @@ Default behaviors by API provider -By default, error reporting, telemetry, and bug reporting are disabled when using Bedrock, Vertex, Foundry, or Claude Platform on AWS. Session quality surveys and the WebFetch domain safety check are exceptions and run regardless of provider. 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: +By default, error reporting, telemetry, and bug reporting are disabled when using Bedrock, Vertex, Foundry, or Claude Platform on AWS. Session quality surveys and the WebFetch domain safety check are exceptions and run regardless of provider. On a signed-in [Claude apps gateway](</docs/en/claude-apps-gateway>) session, usage analytics, error reporting, and survey ratings to Anthropic are disabled by the gateway credential itself, with no setting to re-enable them. You can opt out of all non-essential traffic, including surveys, at once by setting `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`. This variable does not affect the WebFetch check, which has its own opt-out. Here are the full default behaviors: Service| Claude API| Vertex API| Bedrock API| Foundry API| Claude Platform on AWS ---|---|---|---|---|---
modified Debug your configuration View current →
--- a/debug-your-config.md +++ b/debug-your-config.md @@ -16,7 +16,7 @@ `/hooks`| Active hook configurations `/mcp`| Connected MCP servers and their status `/permissions`| Resolved allow and deny rules currently in effect -`/doctor`| Configuration diagnostics: invalid keys, schema errors, installation health +`/doctor`| Configuration diagnostics: invalid keys, schema errors, installation health. As of v2.1.196, also reports duplicate [subagent](</docs/en/sub-agents>) names defined in the same scope and marks which one is active `/debug [issue]`| Enables debug logging for the session and prompts Claude to diagnose using the log output and settings paths `/status`| Active settings sources, including whether managed settings are in effect
modified Launch sessions from links View current →
--- a/deep-links.md +++ b/deep-links.md @@ -49,7 +49,7 @@ Parameter| Description ---|--- `q`| Text to pre-fill in the prompt box. [URL-encode](<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent>) the value. Use `%0A` for line breaks in multi-line prompts. Maximum 5,000 characters. -`cwd`| Absolute path to use as the working directory. Network and UNC paths are rejected. +`cwd`| Absolute path to use as the working directory. Network and UNC paths are rejected, and so are paths that contain invisible or bidirectional control characters. `repo`| A GitHub `owner/name` slug. Claude Code resolves it to a local clone it has seen before and starts there. If you have no matching clone, the session opens in your home directory instead. `cwd` and `repo` are two ways to set the working directory. If you pass both, `cwd` takes precedence and `repo` is ignored, even if the `cwd` path does not exist. The following link points at a repository called `acme/payments` with a two-line diagnostic prompt. Replace `acme/payments` with your repository’s `owner/name` slug when you build your own:
modified Discover and install prebuilt plugins through marketplaces View current →
--- a/discover-plugins.md +++ b/discover-plugins.md @@ -236,7 +236,7 @@ Add from other Git hosts -Add any git repository by providing the full URL. This works with any Git host, including GitLab, Bitbucket, and self-hosted servers. Include the `.git` suffix so Claude Code clones the repository rather than treating the URL as a direct link to a hosted `marketplace.json` file. Using HTTPS: +Add any git repository by providing the full URL. This works with any Git host, including GitLab, Bitbucket, and self-hosted servers. Include the `.git` suffix so Claude Code clones the repository rather than treating the URL as a direct link to a hosted `marketplace.json` file. Include the `https://` prefix as well. Claude Code v2.1.196 and later reject a host typed without it, such as `gitlab.com/company/plugins.git`, as an invalid GitHub `owner/repo` shorthand, and the error tells you to add the prefix. Earlier versions misread it as a GitHub repository path and fail at clone time. Using HTTPS: /plugin marketplace add https://gitlab.com/company/plugins.git @@ -280,17 +280,17 @@ Install plugins -Once you’ve added marketplaces, you can install plugins directly. The command installs to user scope by default: +Once you’ve added marketplaces, you can install plugins directly: /plugin install plugin-name@marketplace-name -To choose a different [installation scope](</docs/en/settings#configuration-scopes>), use the interactive UI: run `/plugin`, go to the **Discover** tab, and press **Enter** on a plugin. You’ll see options for: +The command opens that plugin’s details, where you choose an [installation scope](</docs/en/settings#configuration-scopes>). You see the same choices when you run `/plugin`, go to the **Discover** tab, and press **Enter** on a plugin: * **User scope** (default): install for yourself across all projects * **Project scope** : install for all collaborators on this repository, which adds the plugin to `.claude/settings.json` * **Local scope** : install for yourself in this repository only, not shared with collaborators -You may also see plugins with **managed** scope. These are installed by administrators via [managed settings](</docs/en/settings#settings-files>) and can’t be modified. +To install without an interactive step, use the [`claude plugin install`](</docs/en/plugins-reference#plugin-install>) shell command, which installs to user scope unless you pass `--scope`. You may also see plugins with **managed** scope. These are installed by administrators via [managed settings](</docs/en/settings#settings-files>) and can’t be modified. Make sure you trust a plugin before installing it. Anthropic doesn’t control what MCP servers, files, or other software are included in plugins and can’t verify that they work as intended. Check each plugin’s homepage for more information. @@ -318,7 +318,7 @@ /plugin enable plugin-name@marketplace-name -Completely remove a plugin: +In these identifiers, `plugin-name` is the plugin’s `name` in the [marketplace entry](</docs/en/plugin-marketplaces#plugin-entries>), which can differ from the `name` in the plugin’s own `plugin.json`. As of Claude Code v2.1.195, **Enable** and **Disable** in the `/plugin` interface work for plugins whose two names differ, and `/plugin enable` and `/plugin disable` accept either name. When you disable such a plugin in an earlier version, Claude Code reports `already disabled` and leaves it enabled. Completely remove a plugin: /plugin uninstall plugin-name@marketplace-name @@ -406,7 +406,7 @@ Configure team marketplaces -Team admins can set up automatic marketplace installation for projects by adding marketplace configuration to `.claude/settings.json`. When team members trust the repository folder, Claude Code prompts them to install these marketplaces and plugins. Add `extraKnownMarketplaces` to your project’s `.claude/settings.json`: +Team admins can set up automatic marketplace installation for projects by adding marketplace configuration to `.claude/settings.json`. When team members trust the repository folder, Claude Code prompts them to install these marketplaces and plugins. As of Claude Code v2.1.195, this install step applies on every path that loads plugins. A plugin that only the project’s `.claude/settings.json` enables, and that comes from an external source such as a GitHub repository or npm package, doesn’t load until the team member installs it. Until then, Claude Code reports the plugin as not installed and shows the `claude plugin install` command to run. Add `extraKnownMarketplaces` to your project’s `.claude/settings.json`: { "extraKnownMarketplaces": {
modified Environment variables View current →
Show diff (101 lines)
--- a/env-vars.md +++ b/env-vars.md @@ -90,7 +90,7 @@ `ANTHROPIC_AWS_API_KEY`| Workspace API key for [Claude Platform on AWS](</docs/en/claude-platform-on-aws>), generated in the AWS Console. Sent as `x-api-key` and takes precedence over AWS SigV4 `ANTHROPIC_AWS_BASE_URL`| Override the [Claude Platform on AWS](</docs/en/claude-platform-on-aws>) endpoint URL. Use for custom regions or when routing through an [LLM gateway](</docs/en/llm-gateway>). Defaults to `https://aws-external-anthropic.{AWS_REGION}.api.aws` `ANTHROPIC_AWS_WORKSPACE_ID`| Required for [Claude Platform on AWS](</docs/en/claude-platform-on-aws>). Sent on every request as the `anthropic-workspace-id` header -`ANTHROPIC_BASE_URL`| Override the API endpoint to route requests through a proxy or gateway. When set to a non-first-party host, [MCP tool search](</docs/en/mcp#scale-with-mcp-tool-search>) is disabled by default. Set `ENABLE_TOOL_SEARCH=true` if your proxy forwards `tool_reference` blocks +`ANTHROPIC_BASE_URL`| Override the API endpoint to route requests through a proxy or gateway. When set to a non-first-party host, [MCP tool search](</docs/en/mcp#scale-with-mcp-tool-search>) is disabled by default. Set `ENABLE_TOOL_SEARCH=true` if your proxy forwards `tool_reference` blocks. As of v2.1.196, [Remote Control](</docs/en/remote-control#requirements>) is disabled when this points at a host other than `api.anthropic.com`, matching its behavior on Bedrock, Vertex AI, and Foundry `ANTHROPIC_BEDROCK_BASE_URL`| Override the Bedrock endpoint URL. Use for custom Bedrock endpoints or when routing through an [LLM gateway](</docs/en/llm-gateway>). See [Amazon Bedrock](</docs/en/amazon-bedrock>) `ANTHROPIC_BEDROCK_MANTLE_BASE_URL`| Override the Bedrock Mantle endpoint URL. See [Mantle endpoint](</docs/en/amazon-bedrock#use-the-mantle-endpoint>) `ANTHROPIC_BEDROCK_SERVICE_TIER`| Bedrock [service tier](<https://docs.aws.amazon.com/bedrock/latest/userguide/service-tiers-inference.html>) (`default`, `flex`, or `priority`). Sent as the `X-Amzn-Bedrock-Service-Tier` header. See [Amazon Bedrock](</docs/en/amazon-bedrock#service-tiers>) @@ -150,7 +150,7 @@ `CLAUDE_CODE_ATTRIBUTION_HEADER`| Set to `0` to omit the attribution block (client version and prompt fingerprint) from the start of the system prompt. Disabling it improves prompt-cache hit rates when routing through an [LLM gateway](</docs/en/llm-gateway>). Anthropic API caching is unaffected `CLAUDE_CODE_AUTO_COMPACT_WINDOW`| Set the context capacity in tokens used for auto-compaction calculations. Defaults to the model’s context window: 200K for standard models or 1M for [extended context](</docs/en/model-config#extended-context>) models. Use a lower value like `500000` on a 1M model to treat the window as 500K for compaction purposes. The value is capped at the model’s actual context window. `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` is applied as a percentage of this value. Setting this variable decouples the compaction threshold from the status line’s `used_percentage`, which always uses the model’s full context window `CLAUDE_CODE_AUTO_CONNECT_IDE`| Override automatic [IDE connection](</docs/en/vs-code>). By default, Claude Code connects automatically when launched inside a supported IDE’s integrated terminal. Set to `false` to prevent this. Set to `true` to force a connection attempt when auto-detection fails, such as when tmux obscures the parent terminal. Takes precedence over the [`autoConnectIde`](</docs/en/settings#global-config-settings>) global config setting -`CLAUDE_CODE_CERT_STORE`| Comma-separated list of CA certificate sources for TLS connections. `bundled` is the Mozilla CA set shipped with Claude Code. `system` is the operating system trust store. Default is `bundled,system` +`CLAUDE_CODE_CERT_STORE`| Comma-separated list of CA certificate sources for TLS connections. `bundled` is the Mozilla CA set shipped with Claude Code. `system` is the operating system trust store, read only on runtimes with `tls.getCACertificates`: the native binary, or Node 22.15 or later for npm installs. See [CA certificate store](</docs/en/network-config#ca-certificate-store>). Default is `bundled,system` `CLAUDE_CODE_CHILD_SESSION`| Set to `1` in subprocesses Claude Code spawns via the Bash, PowerShell, and Monitor tools, [hook](</docs/en/hooks>) commands, and [status line](</docs/en/statusline>) commands. Not set for stdio [MCP server](</docs/en/mcp>) subprocesses, which are long-lived and outlive the session that spawned them. Unlike `CLAUDECODE`, this is only set by Claude Code itself when it launches a subprocess and not by IDE extensions, so it reliably distinguishes a nested session from a top-level `claude` launched in an IDE-integrated terminal. A nested interactive `claude` TUI started this way is automatically excluded from `--resume`, `--continue`, up-arrow history, and the `claude agents` list. Non-interactive `claude -p` sessions still persist. Set `CLAUDE_CODE_FORCE_SESSION_PERSISTENCE=1` to override this exclusion. Requires Claude Code v2.1.172 or later `CLAUDE_CODE_CLIENT_CERT`| Path to client certificate file for mTLS authentication `CLAUDE_CODE_CLIENT_KEY`| Path to client private key file for mTLS authentication @@ -167,6 +167,8 @@ `CLAUDE_CODE_DISABLE_ATTACHMENTS`| Set to `1` to disable attachment processing. File mentions with `@` syntax are sent as plain text instead of being expanded into file content `CLAUDE_CODE_DISABLE_AUTO_MEMORY`| Set to `1` to disable [auto memory](</docs/en/memory#auto-memory>). Set to `0` to force auto memory on even when `--bare` mode or [`autoMemoryEnabled: false`](</docs/en/settings#available-settings>) would otherwise disable it. When disabled, Claude does not create or load auto memory files `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS`| Set to `1` to disable all background task functionality, including the `run_in_background` parameter on Bash and subagent tools, auto-backgrounding, and the Ctrl+B shortcut +`CLAUDE_CODE_DISABLE_BG_EXIT_HANDOFF`| Set to `1` to stop a [background session’s](</docs/en/agent-view>) running background shell commands and dynamic workflows when the [supervisor](</docs/en/agent-view#the-supervisor-process>) stops, restarts, or updates that session’s process, instead of handing them to the session’s next process. Affects only that handoff: backgrounding a session with `←` or [`/background`](</docs/en/agent-view#from-inside-a-session>) still carries in-flight work over, and `CLAUDE_DISABLE_ADOPT` turns off both. Requires Claude Code v2.1.196 or later +`CLAUDE_CODE_DISABLE_BG_SHELL_PRESSURE_REAP`| Set to `1` to stop Claude Code from terminating [background shell commands](</docs/en/interactive-mode#background-bash-commands>) when the operating system reports memory pressure. By default, on macOS and Linux, Claude Code terminates a background shell started in the main session on a memory-pressure signal once the session has been idle for 30 minutes and no turn or subagent is running. Windows has no memory-pressure signal, so this variable has no effect there. Requires Claude Code v2.1.193 or later `CLAUDE_CODE_DISABLE_BUNDLED_SKILLS`| Set to `1` to disable the [skills](</docs/en/skills>) and workflows that ship with Claude Code: bundled skills and workflows are removed entirely, while built-in slash commands like `/init` stay typable but are hidden from the model. Skills from plugins, `.claude/skills/`, and `.claude/commands/` are unaffected. Equivalent to the [`disableBundledSkills`](</docs/en/settings#available-settings>) setting; `0` does not override it `CLAUDE_CODE_DISABLE_CLAUDE_MDS`| Set to `1` to prevent loading any CLAUDE.md memory files into context, including user, project, and auto-memory files `CLAUDE_CODE_DISABLE_CRON`| Set to `1` to disable [scheduled tasks](</docs/en/scheduled-tasks>). The `/loop` skill and cron tools become unavailable and any already-scheduled tasks stop firing, including tasks that are already running mid-session @@ -177,8 +179,10 @@ `CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS`| Set to `1` to remove built-in commit and PR workflow instructions and the git status snapshot from Claude’s system prompt. Useful when using your own git workflow skills. Takes precedence over the [`includeGitInstructions`](</docs/en/settings#available-settings>) setting when set `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 Bedrock, Vertex, or Foundry `CLAUDE_CODE_DISABLE_MOUSE`| Set to `1` to disable mouse tracking in [fullscreen rendering](</docs/en/fullscreen>). Keyboard scrolling with `PgUp` and `PgDn` still works. Use this to keep your terminal’s native copy-on-select behavior +`CLAUDE_CODE_DISABLE_MOUSE_CLICKS`| Set to `1` to disable click, drag, and hover handling in [fullscreen rendering](</docs/en/fullscreen>) while keeping mouse-wheel scrolling. Use this when you want wheel scroll to work inside Claude Code but don’t want clicks to position the cursor, expand tool output, or open links. `CLAUDE_CODE_DISABLE_MOUSE` takes precedence when both are set. Requires Claude Code v2.1.195 or later `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`| Equivalent of setting `DISABLE_AUTOUPDATER`, `DISABLE_FEEDBACK_COMMAND`, `DISABLE_ERROR_REPORTING`, and `DISABLE_TELEMETRY` `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 +`CLAUDE_CODE_DISABLE_NOTIFICATION_PRESENCE_CHECK`| Set to `1` to send the `PushNotification` tool’s desktop notification even while you are typing in or focused on the terminal. By default the tool skips both the desktop notification and the [mobile push](</docs/en/remote-control#mobile-push-notifications>) when it detects recent keyboard activity or terminal focus. This variable disables only that local check, so the server can still suppress the mobile push when it detects that you are active. Requires Claude Code v2.1.193 or later `CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL`| Set to `1` to skip automatic addition of the official plugin marketplace on first run `CLAUDE_CODE_DISABLE_POLICY_SKILLS`| Set to `1` to skip loading skills from the system-wide managed skills directory. Useful for container or CI sessions that should not load operator-provisioned skills `CLAUDE_CODE_DISABLE_TERMINAL_TITLE`| Set to `1` to disable automatic terminal title updates based on conversation context. In Agent SDK and `claude -p` sessions, this also skips the background Haiku request that generates the session title @@ -186,7 +190,7 @@ `CLAUDE_CODE_DISABLE_VIRTUAL_SCROLL`| Set to `1` to disable virtual scrolling in [fullscreen rendering](</docs/en/fullscreen>) and render every message in the transcript. Use this if scrolling in fullscreen mode shows blank regions where messages should appear `CLAUDE_CODE_DISABLE_WORKFLOWS`| Set to `1` to disable [workflows](</docs/en/workflows#turn-workflows-off>). Equivalent to the [`disableWorkflows`](</docs/en/settings#available-settings>) setting `CLAUDE_CODE_EFFORT_LEVEL`| Set the effort level for supported models. Values: `low`, `medium`, `high`, `xhigh`, `max`, or `auto` to use the model default. Available levels depend on the model. Takes precedence over `/effort` and the `effortLevel` setting. See [Adjust effort level](</docs/en/model-config#adjust-effort-level>) -`CLAUDE_CODE_ENABLE_AUTO_MODE`| Set to `1` to make [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) available on Amazon Bedrock, Google Cloud Vertex AI, and Microsoft Foundry. Requires Claude Code v2.1.158 or later. Has no effect on the Anthropic API, where auto mode is available by default. See [Enable auto mode on Bedrock, Vertex AI, or Foundry](</docs/en/permission-modes#enable-auto-mode-on-bedrock-vertex-ai-or-foundry>) +`CLAUDE_CODE_ENABLE_AUTO_MODE`| Set to `1` to make [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) available on Amazon Bedrock, Google Cloud Vertex AI, Microsoft Foundry, and signed-in [Claude apps gateway](</docs/en/claude-apps-gateway>) sessions. Requires Claude Code v2.1.158 or later. Has no effect on the Anthropic API, where auto mode is available by default. See [Enable auto mode on Bedrock, Vertex AI, or Foundry](</docs/en/permission-modes#enable-auto-mode-on-bedrock-vertex-ai-or-foundry>) `CLAUDE_CODE_ENABLE_AWAY_SUMMARY`| Override [session recap](</docs/en/interactive-mode#session-recap>) availability. Set to `0` to force recaps off regardless of the `/config` toggle. Set to `1` to force recaps on when [`awaySummaryEnabled`](</docs/en/settings#available-settings>) is `false`. Takes precedence over the setting and `/config` toggle `CLAUDE_CODE_ENABLE_BACKGROUND_PLUGIN_REFRESH`| Set to `1` to refresh plugin state at turn boundaries in [non-interactive mode](</docs/en/headless>) after a background install completes. Off by default because the refresh changes the system prompt mid-session, which invalidates [prompt caching](</docs/en/prompt-caching>) for that turn `CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL`| Set to `1` to route the “How is Claude doing?” session quality survey to your own [OpenTelemetry collector](</docs/en/monitoring-usage>) when Anthropic-bound nonessential traffic is blocked. Survey ratings are emitted only as OTEL events to your configured collector. No survey data is sent to Anthropic in this mode. Applies when `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, `DISABLE_TELEMETRY`, or `DO_NOT_TRACK` is set, and has no effect otherwise. `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY` and the organization product feedback policy take precedence @@ -212,7 +216,7 @@ `CLAUDE_CODE_IDE_HOST_OVERRIDE`| Override the host address used to connect to the IDE extension. By default Claude Code auto-detects the correct address, including WSL-to-Windows routing `CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL`| Skip auto-installation of IDE extensions. Equivalent to setting [`autoInstallIdeExtension`](</docs/en/settings#global-config-settings>) to `false` `CLAUDE_CODE_IDE_SKIP_VALID_CHECK`| Set to `1` to skip validation of IDE lockfile entries during connection. Use when auto-connect fails to find your IDE despite it running -`CLAUDE_CODE_MAX_CONTEXT_TOKENS`| Override the context window size Claude Code assumes for the active model. 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 +`CLAUDE_CODE_MAX_CONTEXT_TOKENS`| Override the context window size Claude Code assumes for the active model. 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 `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](</docs/en/costs#reduce-token-usage>) triggers `CLAUDE_CODE_MAX_RETRIES`| Override the number of times to retry failed API requests (default: 10). Capped at 15 as of v2.1.186. For unattended sessions that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG` instead `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 @@ -225,7 +229,7 @@ `CLAUDE_CODE_OAUTH_REFRESH_TOKEN`| OAuth refresh token for Claude.ai authentication. When set, `claude auth login` exchanges this token directly instead of opening a browser. Requires `CLAUDE_CODE_OAUTH_SCOPES`. Useful for provisioning authentication in automated environments `CLAUDE_CODE_OAUTH_SCOPES`| Space-separated OAuth scopes the refresh token was issued with, such as `"user:profile user:inference user:sessions:claude_code"`. Required when `CLAUDE_CODE_OAUTH_REFRESH_TOKEN` is set `CLAUDE_CODE_OAUTH_TOKEN`| OAuth access token for Claude.ai authentication. Alternative to `/login` for SDK and automated environments. Takes precedence over keychain-stored credentials. Generate one with [`claude setup-token`](</docs/en/authentication#generate-a-long-lived-token>) -`CLAUDE_CODE_OPUS_4_6_FAST_MODE_OVERRIDE`| Removed in v2.1.160 and now a no-op. Previously pinned [fast mode](</docs/en/fast-mode>) to Claude Opus 4.6 instead of the current default +`CLAUDE_CODE_OPUS_4_6_FAST_MODE_OVERRIDE`| Removed in v2.1.160 and now a no-op. Previously pinned [fast mode](</docs/en/fast-mode>) to Claude Opus 4.6 instead of the current default. Opus 4.6 no longer supports fast mode `CLAUDE_CODE_OTEL_DIAG_STDERR`| Set to `1` to write OpenTelemetry exporter diagnostic errors to stderr. By default these errors only appear with `--debug`, so a misconfigured exporter such as a Prometheus port collision otherwise fails silently. Requires Claude Code v2.1.179 or later. See [Monitoring](</docs/en/monitoring-usage>) `CLAUDE_CODE_OTEL_FLUSH_TIMEOUT_MS`| Timeout in milliseconds for flushing pending OpenTelemetry spans (default: 5000). See [Monitoring](</docs/en/monitoring-usage>) `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS`| Interval for refreshing dynamic OpenTelemetry headers in milliseconds (default: 1740000 / 29 minutes). See [Dynamic headers](</docs/en/monitoring-usage#dynamic-headers>) @@ -263,7 +267,7 @@ `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 `CLAUDE_CODE_SKIP_VERTEX_AUTH`| Skip Google authentication for Vertex (for example, when using an LLM gateway) `CLAUDE_CODE_STOP_HOOK_BLOCK_CAP`| Maximum number of consecutive times a [Stop](</docs/en/hooks#stop>) or [SubagentStop](</docs/en/hooks#subagentstop>) hook may block the turn from ending before Claude Code overrides it and ends the turn anyway (default: 8). Set to `0` to disable the cap. Raise this if your hook legitimately needs more iterations to resolve -`CLAUDE_CODE_SUBAGENT_MODEL`| See [Model configuration](</docs/en/model-config>) +`CLAUDE_CODE_SUBAGENT_MODEL`| See [Model configuration](</docs/en/model-config>). As of v2.1.196, setting it to `inherit` is the same as leaving it unset; earlier versions treated `inherit` as an override that forced every subagent onto the main conversation’s model `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB`| Set to `1` to strip Anthropic and cloud provider credentials from subprocess environments (Bash tool, hooks, MCP stdio servers). The parent Claude process keeps these credentials for API calls, but child processes cannot read them, reducing exposure to prompt injection attacks that attempt to exfiltrate secrets via shell expansion. On Linux, this also runs Bash subprocesses in an isolated PID namespace so they cannot read host process environments via `/proc`; as a side effect, `ps`, `pgrep`, and `kill` cannot see or signal host processes. `claude-code-action` sets this automatically when `allowed_non_write_users` is configured `CLAUDE_CODE_SYNC_PLUGIN_INSTALL`| Set to `1` in non-interactive mode (the `-p` flag) to wait for plugin installation to complete before the first query. Without this, plugins install in the background and may not be available on the first turn. Combine with `CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS` to bound the wait `CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS`| Timeout in milliseconds for synchronous plugin installation. When exceeded, Claude Code proceeds without plugins and logs an error. No default: without this variable, synchronous installation waits until complete @@ -283,13 +287,14 @@ `CLAUDE_CODE_USE_POWERSHELL_TOOL`| Controls the PowerShell tool. On Windows without Git Bash, the tool is enabled automatically; set to `0` to disable it. On Windows with Git Bash installed, the tool is rolling out progressively: set to `1` to opt in or `0` to opt out. On Linux, macOS, and WSL, set to `1` to enable it, which requires `pwsh` on your `PATH`. When enabled on Windows, Claude can run PowerShell commands natively instead of routing through Git Bash. See [PowerShell tool](</docs/en/tools-reference#powershell-tool>) `CLAUDE_CODE_USE_VERTEX`| Use [Vertex](</docs/en/google-vertex-ai>) `CLAUDE_CONFIG_DIR`| Override the configuration directory (default: `~/.claude`). All settings, credentials, session history, and plugins are stored under this path. Useful for running multiple accounts side by side: for example, `alias claude-work='CLAUDE_CONFIG_DIR=~/.claude-work claude'` +`CLAUDE_DISABLE_ADOPT`| Set to `1` to stop in-flight background work instead of carrying it over when you background a session by pressing `←` or with [`/background`](</docs/en/agent-view#from-inside-a-session>). Claude Code asks you to confirm before backgrounding, then stops the tasks that would otherwise carry over. Requires Claude Code v2.1.195 or later `CLAUDE_EFFORT`| Set automatically in Bash tool subprocesses and hook commands to the active [effort level](</docs/en/model-config#adjust-effort-level>) for the turn: `low`, `medium`, `high`, `xhigh`, or `max`. Ultracode is not a distinct level and reports as `xhigh`. Matches the `effort.level` field passed to [hooks](</docs/en/hooks>). Only set when the current model supports the effort parameter `CLAUDE_ENABLE_BYTE_WATCHDOG`| Set to `1` to force-enable the byte-level streaming idle watchdog, or set to `0` to force-disable it. When unset, the watchdog is enabled by default for direct Anthropic API and [Claude Platform on AWS](</docs/en/claude-platform-on-aws>) connections. The byte watchdog aborts a connection when no bytes arrive on the wire for 180 seconds by default on direct Anthropic API connections, 300 seconds on Claude Platform on AWS and when enabled on Bedrock, or for the value of `CLAUDE_STREAM_IDLE_TIMEOUT_MS` when that is set, which is clamped to a minimum of 5 minutes, independent of the event-level watchdog `CLAUDE_ENABLE_BYTE_WATCHDOG_BEDROCK`| Set to `1` to enable the byte-level streaming idle watchdog on Amazon Bedrock `vnd.amazon.eventstream` responses. Off by default. Configure the timeout with `CLAUDE_STREAM_IDLE_TIMEOUT_MS` -`CLAUDE_ENABLE_STREAM_WATCHDOG`| Set to `1` to force-enable the event-level streaming idle watchdog, or set to `0` to force-disable it. When unset, the default is server-controlled on the direct Anthropic API and off on other providers. As of v2.1.169, providers other than the direct Anthropic API and Claude Platform on AWS also have a default-on 5-minute body idle timeout independent of this variable; see `API_FORCE_IDLE_TIMEOUT`. On Bedrock, you can also enable the independent byte-level watchdog with `CLAUDE_ENABLE_BYTE_WATCHDOG_BEDROCK`; the two run together when both are set. Configure the timeout with `CLAUDE_STREAM_IDLE_TIMEOUT_MS` +`CLAUDE_ENABLE_STREAM_WATCHDOG`| Set to `0` to force-disable the event-level streaming idle watchdog, or set to `1` to force-enable it. When unset, the watchdog is on by default for all providers. Before v2.1.196, the unset default was server-controlled on the direct Anthropic API and off on other providers. As of v2.1.169, providers other than the direct Anthropic API and Claude Platform on AWS also have a default-on 5-minute body idle timeout independent of this variable; see `API_FORCE_IDLE_TIMEOUT`. On Bedrock, you can also enable the independent byte-level watchdog with `CLAUDE_ENABLE_BYTE_WATCHDOG_BEDROCK`; the two run together when both are set. Configure the timeout with `CLAUDE_STREAM_IDLE_TIMEOUT_MS` `CLAUDE_ENV_FILE`| Path to a shell script whose contents Claude Code runs before each Bash command in the same shell process, so exports in the file are visible to the command. Use to persist virtualenv or conda activation across commands. Also populated dynamically by [SessionStart](</docs/en/hooks#persist-environment-variables>), [Setup](</docs/en/hooks#setup>), [CwdChanged](</docs/en/hooks#cwdchanged>), and [FileChanged](</docs/en/hooks#filechanged>) hooks `CLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX`| Prefix for auto-generated [Remote Control](</docs/en/remote-control>) session names when no explicit name is provided. Defaults to your machine’s hostname, producing names like `myhost-graceful-unicorn`. The `--remote-control-session-name-prefix` CLI flag sets the same value for a single invocation -`CLAUDE_STREAM_IDLE_TIMEOUT_MS`| Timeout in milliseconds before the streaming idle watchdog closes a stalled connection. When you set this variable explicitly, the minimum is `300000` (5 minutes); lower values are silently clamped to absorb extended thinking pauses and proxy buffering. When unset, the event-level watchdog defaults to 300 seconds and the byte-level watchdog defaults to 180 seconds on direct Anthropic API connections (300 seconds on Claude Platform on AWS and other providers). The unset 180-second byte-watchdog default is a separate value and is not subject to the 5-minute clamp. For the event-level watchdog on third-party providers, requires `CLAUDE_ENABLE_STREAM_WATCHDOG=1`; the body idle timeout described under `API_FORCE_IDLE_TIMEOUT` applies independently. On Bedrock, also applies when `CLAUDE_ENABLE_BYTE_WATCHDOG_BEDROCK=1` +`CLAUDE_STREAM_IDLE_TIMEOUT_MS`| Timeout in milliseconds before the streaming idle watchdog closes a stalled connection. When you set this variable explicitly, the minimum is `300000` (5 minutes); lower values are silently clamped to absorb extended thinking pauses and proxy buffering. When unset, the event-level watchdog defaults to 300 seconds and the byte-level watchdog defaults to 180 seconds on direct Anthropic API connections (300 seconds on Claude Platform on AWS and other providers). The unset 180-second byte-watchdog default is a separate value and is not subject to the 5-minute clamp. The body idle timeout described under `API_FORCE_IDLE_TIMEOUT` applies independently. On Bedrock, also applies when `CLAUDE_ENABLE_BYTE_WATCHDOG_BEDROCK=1` `DEBUG`| Set to `1` to enable debug mode, equivalent to launching with [`--debug`](</docs/en/cli-reference#cli-flags>). Debug logs are written to `~/.claude/debug/<session-id>.txt`, or to the path set by `CLAUDE_CODE_DEBUG_LOGS_DIR`. Only the truthy values `1`, `true`, `yes`, and `on` enable debug mode, so namespace patterns like `DEBUG=express:*` set for other tools do not trigger it `DISABLE_AUTOUPDATER`| Set to `1` to disable automatic background updates. Manual `claude update` still works. Use `DISABLE_UPDATES` to block both `DISABLE_AUTO_COMPACT`| Set to `1` to disable automatic compaction when approaching the context limit. The manual `/compact` command remains available. Use when you want explicit control over when compaction occurs @@ -336,6 +341,7 @@ `MCP_TIMEOUT`| Timeout in milliseconds for MCP server startup (default: 30000, or 30 seconds) `MCP_TOOL_TIMEOUT`| Timeout in milliseconds for MCP tool execution (default: 100000000, about 28 hours). A per-server `timeout` field in `.mcp.json` overrides this for that server. For the env variable, values below 1000 are floored to one second; for the per-server field, values below 1000 are ignored `NO_PROXY`| List of domains and IPs to which requests will be directly issued, bypassing proxy +`OTEL_LOG_ASSISTANT_RESPONSES`| Set to `1` to include the model’s response text on `assistant_response` OpenTelemetry log events. When unset, the value of `OTEL_LOG_USER_PROMPTS` is used instead. Set to `0` to keep responses redacted even when `OTEL_LOG_USER_PROMPTS` is set. Requires Claude Code v2.1.193 or later. See [Monitoring](</docs/en/monitoring-usage#assistant-response-event>) `OTEL_LOG_RAW_API_BODIES`| Emit Anthropic Messages API request and response JSON as `api_request_body` / `api_response_body` log events. Set to `1` for inline bodies truncated at 60 KB, or `file:<dir>` to write untruncated bodies to disk and emit a `body_ref` path instead. Disabled by default; bodies include the entire conversation history. See [Monitoring](</docs/en/monitoring-usage#api-request-body-event>) `OTEL_LOG_TOOL_CONTENT`| Set to `1` to include tool input and output content in OpenTelemetry span events. Disabled by default to protect sensitive data. See [Monitoring](</docs/en/monitoring-usage>) `OTEL_LOG_TOOL_DETAILS`| Set to `1` to include tool input arguments, MCP server names, raw error strings on tool failures, the refusal `category` on `api_refusal` events, and other tool details in OpenTelemetry traces and logs. Disabled by default to protect PII. See [Monitoring](</docs/en/monitoring-usage>)
modified Error reference View current →
--- a/errors.md +++ b/errors.md @@ -30,6 +30,7 @@ `Your organization has disabled API key authentication`| Authentication `Your organization has disabled Claude subscription access`| Authentication `Routines are disabled by your organization's policy`| Authentication +`Remote Control is only available when using Claude via api.anthropic.com`| Authentication `OAuth token revoked` / `OAuth token has expired`| Authentication `does not meet scope requirement user:profile`| Authentication `Unable to connect to API`| Network @@ -396,6 +397,21 @@ ​ +Remote Control requires the Anthropic API + +The session isn’t talking to the Anthropic API directly, so there is no claude.ai backend for [Remote Control](</docs/en/remote-control>) to pair with. + + Remote Control is only available when using Claude via api.anthropic.com. + +This appears on Amazon Bedrock, Google Vertex AI, and Microsoft Foundry. As of v2.1.196 it also appears when [`ANTHROPIC_BASE_URL`](</docs/en/env-vars>) points at a host other than `api.anthropic.com`, such as an [LLM gateway](</docs/en/llm-gateway>) or proxy, even when you sign in with claude.ai. **What to do:** + + * Unset `ANTHROPIC_BASE_URL` and restart the session, or start Remote Control from a session that talks to the Anthropic API directly + * For this and the other Remote Control startup messages, see [Troubleshoot Remote Control](</docs/en/remote-control#troubleshooting>) + +### + +​ + OAuth token revoked or expired Your saved login is no longer valid. A revoked token means you signed out everywhere or an admin removed access; an expired token means the automatic refresh failed mid-session.
modified Fullscreen rendering View current →
--- a/fullscreen.md +++ b/fullscreen.md @@ -163,7 +163,7 @@ CLAUDE_CODE_NO_FLICKER=1 CLAUDE_CODE_DISABLE_MOUSE=1 claude -With mouse capture disabled, keyboard scrolling with `PgUp`, `PgDn`, `Ctrl+Home`, and `Ctrl+End` still works, and your terminal handles selection natively. You lose click-to-position-cursor, click-to-expand tool output, URL clicking, and wheel scrolling inside Claude Code. +With mouse capture disabled, keyboard scrolling with `PgUp`, `PgDn`, `Ctrl+Home`, and `Ctrl+End` still works, and your terminal handles selection natively. You lose click-to-position-cursor, click-to-expand tool output, URL clicking, and wheel scrolling inside Claude Code. To keep wheel scrolling but turn off click, drag, and hover handling, set `CLAUDE_CODE_DISABLE_MOUSE_CLICKS=1` instead. Requires Claude Code v2.1.195 or later. `CLAUDE_CODE_DISABLE_MOUSE` takes precedence when both variables are set. With clicks disabled, Claude Code still captures the mouse, so the wheel and touchpad scroll the conversation but left clicks do nothing inside Claude Code. You still need to hold your terminal’s key for native click-and-drag selection. Right-click and middle-click paste continue to work on terminals that support them. ##
added Run Claude Code through a gateway View current →
--- a/gateways.md +++ b/gateways.md @@ -0,0 +1,75 @@ +A gateway is a proxy your organization runs between Claude Code and a model provider. Claude Code sends API traffic to the gateway instead of directly to the provider, and the gateway forwards it using a credential your organization holds. Developers authenticate to the gateway rather than holding provider credentials, so authentication, usage tracking, budgets, and audit logging happen in one place you control. Claude Code includes a self-hosted gateway, [Claude apps gateway](</docs/en/claude-apps-gateway>), in the `claude` binary, so you don’t have to adopt a separate gateway product to run one. If your organization already runs an [LLM gateway](</docs/en/llm-gateway>), Claude Code works with that too. This page covers: + + * How a gateway sits between Claude Code and your provider + * Choosing between Claude apps gateway and a gateway you already run + * How gateways interact with claude.ai subscriptions + * What’s configured separately from the gateway + +## + +​ + +How a gateway works + +Each developer’s Claude Code is pointed at the gateway’s address and authenticates with a gateway-issued credential. The gateway authenticates the developer, applies whatever access and budget rules you configure, and forwards the request to your provider with the organization’s credential. The provider can be Anthropic’s API or a [cloud provider](</docs/en/third-party-integrations>) such as Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry; the gateway’s configuration decides. With Claude apps gateway, or another gateway that exposes a single Anthropic-format endpoint, changing provider doesn’t require touching developer machines. + +Two kinds of credential are involved: + + * **Developer credential** : each developer holds their own, issued by the gateway. It authenticates them to the gateway and identifies them in usage tracking + * **Provider credential** : the gateway holds one credential for your provider account, shared by all forwarded traffic + +## + +​ + +Choose a gateway + +Claude Code works with Anthropic’s own gateway or with a gateway your organization already runs. + +### + +​ + +Claude apps gateway + +Claude apps gateway is Anthropic’s self-hosted gateway, included in the `claude` binary. It routes to Amazon Bedrock, Google Cloud, Microsoft Foundry, or the Anthropic API as the upstream. Developers sign in with your corporate identity provider through `/login`, the gateway enforces model access and [managed settings](</docs/en/permissions#managed-settings>) by IdP group, and it emits [OpenTelemetry Protocol (OTLP)](</docs/en/monitoring-usage>) usage metrics to your own observability stack. Because it is built and tested alongside each Claude Code release, it forwards the headers and request fields Claude Code sends. A gateway maintained separately needs its [forwarding rules updated](</docs/en/llm-gateway-protocol#forward-as-open-lists>) as those headers and fields change with each release; Claude apps gateway releases with the CLI, so there is no list to keep current. See [Availability and limitations](</docs/en/claude-apps-gateway#availability-and-limitations>) for the small set of features that behave differently on a gateway session. The gateway sign-in is a browser SSO step, and there is no service-token flow, so a CI pipeline with no developer to approve the sign-in can’t authenticate through it; configure those against your provider directly. Agent SDK sessions and `claude -p` runs on a machine where a developer has signed in use that machine’s gateway session and are governed by its policies. See [CI pipelines and remote machines](</docs/en/claude-apps-gateway#ci-pipelines-and-remote-machines>). See [Claude apps gateway](</docs/en/claude-apps-gateway>) to deploy it. + +### + +​ + +Other gateways + +If your organization already runs an LLM gateway or API gateway, you can use it instead. Anthropic doesn’t endorse, maintain, or audit other gateway products, and doesn’t support routing Claude Code to non-Claude models through any gateway. See [Other LLM gateways](</docs/en/llm-gateway>) for the admin rollout checklist, what a gateway must implement, and how to point Claude Code at it. + +## + +​ + +Subscriptions and gateways + +When developers connect through a gateway with a gateway credential, usage is billed to your organization’s provider account at API rates, and their claude.ai subscriptions aren’t used or charged. Setting [`ANTHROPIC_AUTH_TOKEN`](</docs/en/env-vars>) for a gateway you run, or signing in to a Claude apps gateway with `/login`, turns off subscription login for that session. Every request forwarded under that credential is charged to the account behind the gateway’s provider credential. The exception is setting only `ANTHROPIC_BASE_URL`, with no gateway credential. Requests still route through the gateway, but a saved claude.ai login stays the active credential, so the subscription’s usage limits and billing apply. [Other LLM gateways](</docs/en/llm-gateway#subscriptions-and-gateways>) covers that configuration and what the gateway has to forward for it to work. + +## + +​ + +Configure separately from the gateway + +A gateway routes model API requests. A few things you might expect it to handle are configured elsewhere: + + * **Which model answers** : pick the model with the `/model` command or [model environment variables](</docs/en/model-config#setting-your-model>). The gateway decides where requests go, not which model the developer selects. Claude apps gateway can bound the choice with a per-group `availableModels` allowlist, but the developer still picks within it. + * **Other network traffic** : Claude Code itself sends version checks and downloads directly to Anthropic, separate from the gateway path. Whether the optional client telemetry stream is also on depends on your provider; the [telemetry defaults table](</docs/en/data-usage#telemetry-services>) covers each case. On a signed-in Claude apps gateway session, the gateway credential disables the Anthropic-bound analytics and, when [telemetry forwarding](</docs/en/claude-apps-gateway-config#telemetry>) is configured, pins OTLP export to the gateway. Your network still needs egress to the [required domains](</docs/en/network-config>), or set [`CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`](</docs/en/env-vars>) to turn off the optional streams. + * **Corporate HTTP proxies** : an `HTTPS_PROXY` sits between Claude Code and every server it talks to, including the gateway. If your network requires one, [configure the proxy](</docs/en/network-config>) in addition to the gateway. For Claude apps gateway specifically, [sign-in checks that the proxy host is also on a private network](</docs/en/claude-apps-gateway#prerequisites>); if it isn’t, add the gateway host to `NO_PROXY` so the CLI connects to it directly. + +## + +​ + +Next steps + +The next page depends on who runs the gateway. Anthropic’s gateway runs from the `claude` binary and has its own setup guide; a gateway your organization already runs has a protocol to implement and an admin rollout checklist. + + * [Claude apps gateway](</docs/en/claude-apps-gateway>) to deploy Anthropic’s self-hosted gateway with SSO sign-in and OTLP telemetry + * [Other LLM gateways](</docs/en/llm-gateway>) for what a gateway your organization already runs must implement, and how to point Claude Code at it + * [Set up Claude Code for your organization](</docs/en/admin-setup>) for the wider rollout decisions a gateway is one part of
modified Hooks reference View current →
Show diff (101 lines)
--- a/hooks.md +++ b/hooks.md @@ -181,10 +181,10 @@ Matcher value| Evaluated as| Example ---|---|--- `"*"`, `""`, or omitted| Match all| fires on every occurrence of the event -Only letters, digits, `_`, spaces, `,`, and `|`| Exact string, or list of exact strings separated by `|` or `,` with optional surrounding whitespace| `Bash` matches only the Bash tool; `Edit|Write` and `Edit, Write` each match either tool exactly -Contains any other character| JavaScript regular expression| `^Notebook` matches any tool starting with Notebook; `mcp__memory__.*` matches every tool from the `memory` server - -Comma separators and the surrounding whitespace tolerance require Claude Code v2.1.191 or later. The `FileChanged` and `StopFailure` events accept only `|` as the list separator and treat `,` as a literal character; all other events listed in the table that follows accept `|` or `,`. The `FileChanged` event does not follow these rules when building its watch list. See FileChanged. Each event type matches on a different field: +Only letters, digits, `_`, `-`, spaces, `,`, and `|`| Exact string, or list of exact strings separated by `|` or `,` with optional surrounding whitespace| `Bash` matches only the Bash tool; `Edit|Write` and `Edit, Write` each match either tool exactly; `code-reviewer` matches only that agent type +Contains any other character| JavaScript regular expression, unanchored| `^Notebook` matches any tool whose name starts with `Notebook`; `mcp__memory__.*` matches every tool from the `memory` server + +A matcher on the regular-expression path is tested with JavaScript’s `RegExp.prototype.test`, which succeeds on a match anywhere in the value. `Edit.*` matches both `Edit` and `NotebookEdit`; wrap the pattern in `^` and `$`, as in `^Edit$`, when you need a whole-string match. Comma separators and the surrounding whitespace tolerance require Claude Code v2.1.191 or later. Hyphens in the exact-match set require Claude Code v2.1.195 or later. On earlier versions a hyphenated name like `code-reviewer` is evaluated as an unanchored regular expression, so it also fires for `senior-code-reviewer`; anchor it as `^code-reviewer$` on those versions to match only that name. `FileChanged` and `StopFailure` 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. Every other event with matcher support in the table that follows accepts `|` or `,`. The `FileChanged` event does not follow these rules when building its watch list. See FileChanged. Each event type matches on a different field: Event| What the matcher filters| Example matcher values ---|---|--- @@ -193,7 +193,7 @@ `Setup`| which CLI flag triggered setup| `init`, `maintenance` `SessionEnd`| why the session ended| `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` `Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response` -`SubagentStart`| agent type| `general-purpose`, `Explore`, `Plan`, or custom agent names +`SubagentStart`| agent type| `general-purpose`, `Explore`, `Plan`, custom agent names, or plugin-scoped names like `^my-plugin:reviewer$` `PreCompact`, `PostCompact`| what triggered compaction| `manual`, `auto` `SubagentStop`| agent type| same values as `SubagentStart` `ConfigChange`| configuration source| `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills` @@ -224,7 +224,7 @@ } } -`UserPromptSubmit`, `PostToolBatch`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, and `CwdChanged` don’t support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored. For tool events, you can filter more narrowly by setting the `if` field on individual hook handlers. `if` uses [permission rule syntax](</docs/en/permissions>) to match against the tool name and arguments together, so `"Bash(git *)"` runs when any subcommand of the Bash input matches `git *` and `"Edit(*.ts)"` runs only for TypeScript files. +`UserPromptSubmit`, `PostToolBatch`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `MessageDisplay`, and `CwdChanged` don’t support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored. For tool events, you can filter more narrowly by setting the `if` field on individual hook handlers. `if` uses [permission rule syntax](</docs/en/permissions>) to match against the tool name and arguments together, so `"Bash(git *)"` runs when any subcommand of the Bash input matches `git *` and `"Edit(*.ts)"` runs only for TypeScript files. #### @@ -238,12 +238,13 @@ * `mcp__filesystem__read_file`: Filesystem server’s read file tool * `mcp__github__search_repositories`: GitHub server’s search tool -To match every tool from a server, append `.*` to the server prefix. The `.*` is required: a matcher like `mcp__memory` contains only letters and underscores, so it is compared as an exact string and matches no tool. +To match every tool from a server, append `.*` to the server prefix. The `.*` is required: a matcher like `mcp__memory` or `mcp__brave-search` contains only exact-match characters, so it is compared as an exact string and matches no tool. * `mcp__memory__.*` matches all tools from the `memory` server + * `mcp__brave-search__.*` matches all tools from a server whose name contains a hyphen * `mcp__.*__write.*` matches any tool whose name starts with `write` from any server -This example logs all memory server operations and validates write operations from any MCP server: +Hyphens in the exact-match set require Claude Code v2.1.195 or later. On earlier versions a bare hyphenated prefix like `mcp__brave-search` is evaluated as an unanchored regular expression and matches every tool from that server. The `mcp__brave-search__.*` form works on every version. This example logs all memory server operations and validates write operations from any MCP server: { "hooks": { @@ -328,7 +329,7 @@ `args`| no| Argument list. When present, `command` is resolved as an executable and spawned directly with `args` as the argument vector, with no shell involved. See Exec form and shell form `async`| no| If `true`, runs in the background without blocking. See Run hooks in the background `asyncRewake`| no| If `true`, runs in the background and wakes Claude on exit code 2. Implies `async`. The hook’s stderr, or stdout if stderr is empty, is shown to Claude as a system reminder so it can react to a long-running background failure -`shell`| no| Shell to use for this hook. Accepts `"bash"` (default) or `"powershell"`. Setting `"powershell"` runs the command via PowerShell on Windows. Does not require `CLAUDE_CODE_USE_POWERSHELL_TOOL` since hooks spawn PowerShell directly. Ignored when `args` is set +`shell`| no| Shell to use for this hook. Accepts `"bash"` or `"powershell"`. Defaults to `"bash"`, or to `"powershell"` on Windows when Git Bash isn’t installed. Setting `"powershell"` runs the command via PowerShell on Windows. Does not require `CLAUDE_CODE_USE_POWERSHELL_TOOL` since hooks spawn PowerShell directly. Ignored when `args` is set ##### Exec form and shell form @@ -564,6 +565,7 @@ Field| Description ---|--- `session_id`| Current session identifier +`prompt_id`| UUID identifying the user prompt currently being processed. Matches the [`prompt.id` attribute on OpenTelemetry events](</docs/en/monitoring-usage#event-correlation-attributes>), so you can correlate hook output with telemetry for a single prompt. Absent until the first user input. Requires Claude Code v2.1.196 or later `transcript_path`| Path to conversation JSON `cwd`| Current working directory when the hook is invoked `permission_mode`| Current [permission mode](</docs/en/permissions#permission-modes>): `"default"`, `"plan"`, `"acceptEdits"`, `"auto"`, `"dontAsk"`, or `"bypassPermissions"`. Not all events receive this field: see each event’s JSON example below to check @@ -575,12 +577,13 @@ Field| Description ---|--- `agent_id`| Unique identifier for the subagent. Present only when the hook fires inside a subagent call. Use this to distinguish subagent hook calls from main-thread calls. -`agent_type`| Agent name (for example, `"Explore"` or `"security-reviewer"`). Present when the session uses `--agent` or the hook fires inside a subagent. For subagents, the subagent’s type takes precedence over the session’s `--agent` value. For [custom subagents](</docs/en/sub-agents>), this is the `name` field from the agent’s frontmatter, not the filename. +`agent_type`| Agent name (for example, `"Explore"` or `"security-reviewer"`). Present when the session uses `--agent` or the hook fires inside a subagent. For subagents, the subagent’s type takes precedence over the session’s `--agent` value. For [custom subagents](</docs/en/sub-agents>), this is the `name` field from the agent’s frontmatter, not the filename. For subagents shipped by a [plugin](</docs/en/plugins>), this is the plugin-scoped identifier such as `my-plugin:reviewer`, not the bare frontmatter name. See SubagentStart for how to write a matcher against a plugin-scoped name. Only `SessionStart` hooks can receive a `model` field, and it is not guaranteed to be present. There is no `$CLAUDE_MODEL` environment variable. A hook process inherits the parent environment, so it can read `$ANTHROPIC_MODEL` if you set it in your shell, but that value does not change when you switch models with `/model` during a session. For example, a `PreToolUse` hook for a Bash command receives this on stdin: { "session_id": "abc123", + "prompt_id": "550e8400-e29b-41d4-a716-446655440000", "transcript_path": "/home/user/.claude/projects/.../transcript.jsonl", "cwd": "/home/user/my-project", "permission_mode": "default", @@ -1040,7 +1043,7 @@ UserPromptSubmit -Runs when the user submits a prompt, before Claude processes it. This allows you to add additional context based on the prompt/conversation, validate prompts, or block certain types of prompts. `UserPromptSubmit` hooks have a default timeout of 30 seconds for `command`, `http`, and `mcp_tool` types, shorter than the 600-second default for those types on most other events. Because this hook runs before every prompt and blocks model processing until it completes, a stuck hook stalls the session. If your hook needs more time, set the `timeout` field in the hook entry. +Runs when the user submits a prompt, before Claude processes it. This allows you to add additional context based on the prompt/conversation, validate prompts, or block certain types of prompts. `UserPromptSubmit` hooks have a default timeout of 30 seconds for `command`, `http`, and `mcp_tool` types, shorter than the 600-second default for those types on most other events. Because this hook runs before every prompt and blocks model processing until it completes, a stuck hook stalls the session. If your hook needs more time, set the `timeout` field in the hook entry. A `UserPromptSubmit` hook that reaches its timeout is canceled and its output, including any `additionalContext`, is discarded. The prompt still reaches Claude without that context. As of v2.1.196, the transcript shows a notice naming the hook, the timeout that fired, and that the output was discarded. Earlier versions cancel the hook with no notice. #### @@ -1879,7 +1882,7 @@ SubagentStart -Runs when a Claude Code subagent is spawned via the Agent tool. Supports matchers to filter by agent type name. For built-in agents, this is the agent name like `general-purpose`, `Explore`, or `Plan`. For [custom subagents](</docs/en/sub-agents>), this is the `name` field from the agent’s frontmatter, not the filename. +Runs when a Claude Code subagent is spawned via the Agent tool. Supports matchers to filter by agent type name. For built-in agents, this is the agent name like `general-purpose`, `Explore`, or `Plan`. For [custom subagents](</docs/en/sub-agents>), this is the `name` field from the agent’s frontmatter, not the filename. For subagents shipped by a [plugin](</docs/en/plugins>), the agent type is the plugin-scoped identifier such as `my-plugin:reviewer`, not the bare frontmatter name. The colon places a plugin-scoped name on the regular-expression path, so anchor the matcher with `^` and `$` for an exact match: `^my-plugin:reviewer$`. ####
modified Hosting the Agent SDK View current →
--- a/hosting.md +++ b/hosting.md @@ -176,7 +176,7 @@ * **Transcripts only** : `SessionStore` mirrors transcripts, not `CLAUDE.md` memory files or other working-directory artifacts. Mount a shared volume or sync those separately. * **Mirror, not replacement** : the subprocess writes to local disk first, and the store receives a copy of each batch. Local writes remain authoritative. - * **`mirror_error` messages**: if the store rejects or times out, the SDK emits a `{ type: "system", subtype: "mirror_error" }` message and continues the query without retry. Alert on these if store durability matters. + * **`mirror_error` messages**: a batch the store rejects is sent up to three times in total, with a short backoff before each retry; a timed-out call isn’t retried. If the batch still fails, the SDK drops it, emits a `{ type: "system", subtype: "mirror_error" }` message, and continues the query. Alert on these if store durability matters. ###
modified Interactive mode View current →
--- a/interactive-mode.md +++ b/interactive-mode.md @@ -309,8 +309,9 @@ * Output is written to a file and Claude can retrieve it using the Read tool * Background tasks have unique IDs for tracking and output retrieval - * Background tasks are automatically cleaned up when Claude Code exits + * Background tasks are automatically cleaned up when Claude Code exits. Backgrounding the session instead of exiting it hands them to the background session, where they keep running. See [background a running session](</docs/en/agent-view#from-inside-a-session>) * Background tasks are automatically terminated if output exceeds 5GB, with a note in stderr explaining why + * As of v2.1.193, on macOS and Linux, running background tasks are terminated when the operating system signals memory pressure, provided the session has been idle for at least 30 minutes with no turn or subagent running. Set [`CLAUDE_CODE_DISABLE_BG_SHELL_PRESSURE_REAP`](</docs/en/env-vars>) to `1` to turn this off To disable all background task functionality, set the `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` environment variable to `1`. See [Environment variables](</docs/en/env-vars>) for details. **Common backgrounded commands:** @@ -339,6 +340,7 @@ * Supports the same `Ctrl+B` backgrounding for long-running commands * Doesn’t require Claude to interpret or approve the command * Supports history-based autocomplete: type a partial command and press `Tab` to complete from previous `!` commands in the current project + * Supports live file path autocomplete as of v2.1.193 on all platforms: type a token containing a forward slash, such as `./src/` or `~/`, to see a dropdown of matching files and directories, then press `Tab` to accept. Use forward slashes on Windows too; the dropdown is triggered by `/`, not `\` * Exit with `Escape`, `Backspace`, or `Ctrl+U` on an empty prompt * Pasting text that starts with `!` into an empty prompt enters shell mode automatically, matching typed `!` behavior
modified JetBrains IDEs View current →
--- a/jetbrains.md +++ b/jetbrains.md @@ -253,7 +253,7 @@ Security considerations -When Claude Code runs in a JetBrains IDE with auto-edit permissions enabled, it may be able to modify IDE configuration files that can be automatically executed by your IDE. This may increase the risk of running Claude Code in auto-edit mode and allow bypassing Claude Code’s permission prompts for bash execution. When running in JetBrains IDEs, consider: +When Claude Code runs in a JetBrains IDE in [`acceptEdits` permission mode](</docs/en/permission-modes#auto-approve-file-edits-with-acceptedits-mode>), it may be able to modify IDE configuration files that can be automatically executed by your IDE. This may increase the risk of running Claude Code in `acceptEdits` mode and allow bypassing Claude Code’s permission prompts for bash execution. When running in JetBrains IDEs, consider: * Using manual approval mode for edits * Taking extra care to ensure Claude is only used with trusted prompts
modified Other LLM gateways View current →
--- a/llm-gateway.md +++ b/llm-gateway.md @@ -1,8 +1,10 @@ -An LLM gateway is a proxy your organization runs between Claude Code and a model provider. Claude Code sends API traffic to the gateway, and the gateway forwards it to the provider using a credential your organization controls. +This section covers using a gateway product your organization already runs, rather than [Claude apps gateway](</docs/en/claude-apps-gateway>). For what a gateway is, how it sits between Claude Code and your provider, and how to choose between Claude apps gateway and another product, see the [gateway overview](</docs/en/gateways>). * If you’re a developer connecting to an existing gateway: [connect Claude Code to your gateway](</docs/en/llm-gateway-connect>) * If you’re an admin rolling out a gateway for your organization: [deploy and distribute a gateway](</docs/en/llm-gateway-rollout>) * If you’re configuring a gateway product: the [gateway protocol reference](</docs/en/llm-gateway-protocol>) + +Any gateway that exposes a [supported API format](</docs/en/llm-gateway-protocol#api-formats>) works. Anthropic doesn’t endorse, maintain, or audit third-party gateway products, and doesn’t support routing Claude Code to non-Claude models through any gateway. Deploy the gateway following its own documentation, then complete the Claude Code side with the rollout steps below. ## @@ -18,22 +20,7 @@ * **Audit logging** : log every model request for compliance * **Provider switching** : change the provider in gateway configuration, without touching developer machines -All of these except provider switching apply whether the upstream is Anthropic’s API or a [cloud provider](</docs/en/third-party-integrations>). The tradeoff is that the gateway becomes infrastructure your organization operates. Claude Code adds capabilities with each release, and a gateway that doesn’t forward them breaks the corresponding features, so the gateway product needs to be kept updated as Claude Code evolves. The [gateway protocol reference](</docs/en/llm-gateway-protocol>) covers what to forward. - -## - -​ - -How a gateway works - -By default, Claude Code sends requests directly to Anthropic’s API at `api.anthropic.com`. To route through a gateway, set `ANTHROPIC_BASE_URL` to the gateway’s address; Claude Code sends the same requests there instead. The gateway authenticates the developer, attaches your organization’s provider credential, and forwards each request to whichever provider it’s configured for. `ANTHROPIC_BASE_URL` is the address variable for most gateways. A gateway that fronts a specific cloud provider, such as Bedrock, Vertex, Foundry, or the Claude Platform on AWS, uses that provider’s base URL variable instead; [API formats](</docs/en/llm-gateway-protocol#api-formats>) lists which variable goes with each configuration. - -Two kinds of credential are involved: - - * **Developer credentials** : each developer holds their own, issued by the gateway. It authenticates them to the gateway and identifies them in usage tracking - * **Provider credential** : the gateway holds one credential for your provider account, shared by all forwarded traffic. You don’t provision provider keys per developer - -The gateway forwards each request to the provider you configure, such as the Anthropic API, [Amazon Bedrock](</docs/en/amazon-bedrock>), [Google Vertex AI](</docs/en/google-vertex-ai>), [Microsoft Foundry](</docs/en/microsoft-foundry>), or the [Claude Platform on AWS](</docs/en/claude-platform-on-aws>). Because Claude Code talks only to the gateway, the provider choice is the gateway’s configuration, not the client’s. +All of these except provider switching apply whether the upstream is Anthropic’s API or a [cloud provider](</docs/en/third-party-integrations>). Provider switching without reconfiguring developer machines also depends on the gateway exposing a single [Anthropic-format endpoint](</docs/en/llm-gateway-protocol#api-formats>) regardless of upstream; a gateway that exposes a provider’s own format ties the client configuration to that provider. The tradeoff is that the gateway becomes infrastructure your organization operates. Claude Code adds capabilities with each release, and a gateway that doesn’t forward them breaks the corresponding features, so the gateway product needs to be kept updated as Claude Code evolves. The [gateway protocol reference](</docs/en/llm-gateway-protocol>) covers what to forward. ## @@ -54,29 +41,9 @@ ​ -Third-party gateways - -Any gateway that exposes a [supported API format](</docs/en/llm-gateway-protocol#api-formats>) works. Anthropic doesn’t endorse, maintain, or audit third-party gateway products. Deploy them following their own documentation, then complete the Claude Code side of the rollout with the [rollout steps](</docs/en/llm-gateway-rollout>). - -## - -​ - Subscriptions and gateways -While a [gateway credential variable](</docs/en/llm-gateway-connect#set-the-credential-variable>) or `apiKeyHelper` is active, a developer’s claude.ai subscription isn’t used: the credential replaces the subscription login for that session, and the subscription’s usage limits don’t apply. That traffic is billed per token to whoever owns the credential the gateway forwards, such as your organization’s Anthropic Console account, or your Bedrock, Vertex, or Foundry account when the gateway routes there. Setting only `ANTHROPIC_BASE_URL`, without a gateway credential, doesn’t replace the subscription. Requests still route through the gateway, but a saved claude.ai login remains the active credential, so its usage limits and billing apply. Gateways that pass this traffic on to Anthropic must forward the OAuth capability in `anthropic-beta`; see the [request headers reference](</docs/en/llm-gateway-protocol#request-headers>). - -## - -​ - -Configure separately from the gateway - -A gateway determines where model API requests are sent. Model selection, the rest of Claude Code’s network traffic, and corporate proxies are configured separately: - - * **Model selection** : the base URL decides where requests go, not which model answers them. Pick the model with the `/model` command or the model environment variables; see [how to set your model](</docs/en/model-config#setting-your-model>) - * **Client-side traffic** : version checks and optional client telemetry, both disabled with [`CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`](</docs/en/env-vars>), and login traffic when a claude.ai or Console login is in use, go to Anthropic’s update and authentication endpoints rather than the gateway. See [network access requirements](</docs/en/network-config#network-access-requirements>) for the domains - * **Corporate proxies** : a proxy set with `HTTPS_PROXY` sits between Claude Code and every server it talks to, including the gateway. If your network requires a proxy, configure both; see [proxy configuration](</docs/en/network-config#proxy-configuration>) +While a [gateway credential variable](</docs/en/llm-gateway-connect#set-the-credential-variable>) or `apiKeyHelper` is active, a developer’s claude.ai subscription isn’t used: the credential replaces the subscription login for that session, and the subscription’s usage limits don’t apply. That traffic is billed per token to whoever owns the credential the gateway forwards, such as your organization’s Anthropic Console account, or your Bedrock, Agent Platform, or Foundry account when the gateway routes there. [`ANTHROPIC_BASE_URL`](</docs/en/llm-gateway-connect#set-the-base-url-and-credential>) is the variable that points Claude Code at the gateway. Setting only that variable, without a gateway credential, doesn’t replace the subscription. Requests still route through the gateway, but a saved claude.ai login remains the active credential, so its usage limits and billing apply. Gateways that pass this traffic on to Anthropic must forward the OAuth capability in `anthropic-beta`; see the [request headers reference](</docs/en/llm-gateway-protocol#request-headers>). ## @@ -84,7 +51,8 @@ Related pages + * [Gateway overview](</docs/en/gateways>): how a gateway works and how to choose between Claude apps gateway and another product + * [Claude apps gateway](</docs/en/claude-apps-gateway>): Anthropic’s self-hosted gateway with SSO sign-in and OTLP telemetry * [Connect Claude Code to an LLM gateway](</docs/en/llm-gateway-connect>): set the base URL and credential on your own machine, with per-surface configuration and a troubleshooting table * [Roll out an LLM gateway for your organization](</docs/en/llm-gateway-rollout>): the admin checklist for deploying a gateway, issuing developer credentials, and distributing managed settings * [Gateway protocol reference](</docs/en/llm-gateway-protocol>): what Claude Code sends to a gateway, for operators configuring one, covering endpoints, headers to forward, and feature pass-through - * [Set up Claude Code for your organization](</docs/en/admin-setup>): the wider rollout decisions a gateway is one part of, including policy enforcement and usage visibility
modified Connect Claude Code to an LLM gateway View current →
--- a/llm-gateway-connect.md +++ b/llm-gateway-connect.md @@ -217,7 +217,7 @@ with: anthropic_api_key: ${{ secrets.GATEWAY_API_KEY }} -For a bearer-token gateway, pass the same secret as both the `anthropic_api_key` input and `ANTHROPIC_AUTH_TOKEN` in the workflow `env` block. The action requires `anthropic_api_key`, `CLAUDE_CODE_OAUTH_TOKEN`, or workload identity federation before it launches Claude Code, and it doesn’t read `ANTHROPIC_AUTH_TOKEN`, so the input satisfies that launch check while the env variable puts the key in the `Authorization` header the gateway reads. The copy in `x-api-key` is ignored: +For a bearer-token gateway, pass the same secret twice: as the `anthropic_api_key` input and as `ANTHROPIC_AUTH_TOKEN` in the workflow `env` block. The action requires `anthropic_api_key`, `CLAUDE_CODE_OAUTH_TOKEN`, or workload identity federation before it launches Claude Code, and it doesn’t read `ANTHROPIC_AUTH_TOKEN`, so the input is there only to satisfy that launch check. The env variable is what puts the key in the `Authorization` header the gateway reads; the copy in `x-api-key` is ignored: env: ANTHROPIC_BASE_URL: https://llm-gateway.example.com @@ -262,7 +262,10 @@ Slack, web, and Remote Control -[Claude Code in Slack](</docs/en/slack>) and [Claude Code on the web](</docs/en/claude-code-on-the-web>) are Anthropic-hosted products that always use Anthropic’s API; they aren’t part of a gateway deployment. Gateway variables set in a cloud session’s environment configuration are not applied. If your traffic must stay on the gateway, don’t enable these surfaces for those users. [Remote Control](</docs/en/remote-control>) and [voice dictation](</docs/en/voice-dictation>) both rely on a claude.ai identity: Remote Control to pair a live session with your account, and voice dictation to reach the claude.ai transcription endpoint. They are unavailable while `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or an `apiKeyHelper` is active. To use either, unset the gateway credential and log in with claude.ai instead; `/doctor` names the variable to unset. +[Claude Code in Slack](</docs/en/slack>) and [Claude Code on the web](</docs/en/claude-code-on-the-web>) are Anthropic-hosted products that always use Anthropic’s API; they aren’t part of a gateway deployment. Gateway variables set in a cloud session’s environment configuration are not applied. If your traffic must stay on the gateway, don’t enable these surfaces for those users. [Remote Control](</docs/en/remote-control>) and [voice dictation](</docs/en/voice-dictation>) both rely on a claude.ai identity: Remote Control to pair a live session with your account, and voice dictation to reach the claude.ai transcription endpoint. They are unavailable while `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or an `apiKeyHelper` is active. As of v2.1.196, Remote Control is also disabled while `ANTHROPIC_BASE_URL` points at a non-Anthropic host, so signing in with claude.ai isn’t enough on its own. To restore either feature, log in with claude.ai and unset the gateway variables it checks. `/doctor` names the credential variable to unset. + + * Voice dictation: unset the gateway credential + * Remote Control: unset the gateway credential and `ANTHROPIC_BASE_URL` ## @@ -292,7 +295,7 @@ { "env": { - "ANTHROPIC_CUSTOM_HEADERS": "X-Org-Route: prod\nX-Tenant: acme" + "ANTHROPIC_CUSTOM_HEADERS": "X-Org-Route: prod\nX-Tenant: example" } } @@ -345,7 +348,7 @@ Route to a cloud provider through a gateway -These configurations point Claude Code at a gateway through a provider-specific base URL variable in place of `ANTHROPIC_BASE_URL`. Bedrock and Vertex gateways accept those providers’ native request formats; Foundry and Claude Platform on AWS gateways accept the Anthropic Messages format and differ only in which base URL variable reaches them. Use one only if your gateway team specifically named Bedrock, Vertex, Foundry, or the Claude Platform on AWS. If the verification request above returned JSON, you can skip this section. Set the block for the provider your gateway team named. The skip-auth variables tell Claude Code not to sign requests with provider credentials, since the gateway holds those. If the gateway needs its own token, add `ANTHROPIC_AUTH_TOKEN` after the block, except for Foundry, which uses `ANTHROPIC_FOUNDRY_API_KEY` as shown. +These configurations point Claude Code at a gateway through a provider-specific base URL variable in place of `ANTHROPIC_BASE_URL`. Bedrock and Agent Platform gateways accept those providers’ native request formats; Foundry and Claude Platform on AWS gateways accept the Anthropic Messages format and differ only in which base URL variable reaches them. Use one only if your gateway team specifically named Bedrock, Agent Platform, Foundry, or the Claude Platform on AWS. If the verification request above returned JSON, you can skip this section. Set the block for the provider your gateway team named. The skip-auth variables tell Claude Code not to sign requests with provider credentials, since the gateway holds those. If the gateway needs its own token, add `ANTHROPIC_AUTH_TOKEN` after the block, except for Foundry, which uses `ANTHROPIC_FOUNDRY_API_KEY` as shown. #### @@ -369,7 +372,7 @@ ​ -Google Vertex AI +Google Cloud’s Agent Platform * Bash or Zsh
modified Gateway protocol reference View current →
Show diff (161 lines)
--- a/llm-gateway-protocol.md +++ b/llm-gateway-protocol.md @@ -1,4 +1,4 @@ -This page documents the requests Claude Code sends to a gateway, including the endpoints it calls, the headers and body fields the gateway must forward, and which features stop working when it doesn’t. It is written for operators configuring a gateway product to work with Claude Code. +This page documents the requests Claude Code sends to a gateway, including the endpoints it calls, the headers and body fields the gateway must forward, and which features stop working when it doesn’t. It is written for operators configuring a gateway product to work with Claude Code. A running [Claude apps gateway](</docs/en/claude-apps-gateway>) serves a machine-readable version of this contract at `GET /protocol`, covering the same forwarding requirements plus the Claude apps gateway-specific endpoints for SSO sign-in, managed-settings delivery, and telemetry. Claude apps gateway runs from the same `claude` binary as the CLI, so the [Claude apps gateway quickstart](</docs/en/claude-apps-gateway#quickstart>) is the shortest path to a running instance you can fetch the spec from. * To roll out an existing or third-party gateway for your organization, see [Roll out an LLM gateway](</docs/en/llm-gateway-rollout>) * If you’re an individual developer authenticating Claude Code to a gateway with a credential you were given, see [Connect Claude Code to an LLM gateway](</docs/en/llm-gateway-connect>) @@ -24,13 +24,13 @@ API formats -A gateway must expose at least one of the following API formats to Claude Code clients. Which format Claude Code speaks is determined by the client’s configuration: the variable in the Selected by column of the table below points Claude Code at your gateway in that format. +A gateway must expose at least one of the following API formats to Claude Code clients. Which format Claude Code speaks is determined by the client’s configuration: the variable in the Selected by column of the table below points Claude Code at your gateway in that format. Agent Platform is Google Cloud’s Claude endpoint, formerly Vertex AI; its variable names keep the `VERTEX` spelling. Format| Selected by| Endpoints| Forward unchanged ---|---|---|--- Anthropic Messages| `ANTHROPIC_BASE_URL`| `/v1/messages`, `/v1/messages/count_tokens` (optional)| `anthropic-beta` and `anthropic-version` request headers Bedrock InvokeModel| `ANTHROPIC_BEDROCK_BASE_URL` with `CLAUDE_CODE_USE_BEDROCK=1`| `/model/{model}/invoke`, `/model/{model}/invoke-with-response-stream`| `anthropic_beta` and `anthropic_version` request body fields -Vertex rawPredict| `ANTHROPIC_VERTEX_BASE_URL` with `CLAUDE_CODE_USE_VERTEX=1`| `:rawPredict`, `:streamRawPredict`, `count-tokens:rawPredict` (optional)| `anthropic-beta` and `anthropic-version` request headers, and the `anthropic_version` request body field +Agent Platform rawPredict| `ANTHROPIC_VERTEX_BASE_URL` with `CLAUDE_CODE_USE_VERTEX=1`| `:rawPredict`, `:streamRawPredict`, `count-tokens:rawPredict` (optional)| `anthropic-beta` and `anthropic-version` request headers, and the `anthropic_version` request body field ### @@ -46,7 +46,7 @@ Optional endpoints and startup traffic -Token-counting endpoints are the only optional ones: when they’re absent, Claude Code estimates context usage locally. Inference requests post to `/v1/messages?beta=true`, so match on the path, not the full URL. The Vertex method suffixes attach to the publisher model path, as in `/projects/{project}/locations/{location}/publishers/anthropic/models/{model}:streamRawPredict`. A gateway also sees best-effort startup traffic it can reject without breaking anything: a `HEAD /` connectivity probe, and on Bedrock-format gateways a `GET /inference-profiles?type=SYSTEM_DEFINED` request. +Token-counting endpoints are the only optional ones: when they’re absent, Claude Code estimates context usage locally. Inference requests post to `/v1/messages?beta=true`, so match on the path, not the full URL. The Agent Platform method suffixes attach to the publisher model path, as in `/projects/{project}/locations/{location}/publishers/anthropic/models/{model}:streamRawPredict`. A gateway also sees best-effort startup traffic it can reject without breaking anything: a `HEAD /` connectivity probe, and on Bedrock-format gateways a `GET /inference-profiles?type=SYSTEM_DEFINED` request. ### @@ -64,8 +64,8 @@ Which format the client speaks determines what your gateway receives. The common failure mode is a mismatch between the format the client sends to your gateway and the format the upstream provider behind it accepts. - * When the client speaks the Bedrock or Vertex format, Claude Code sends only the subset of its full capability set that those providers accept - * When the client speaks the Anthropic Messages format, Claude Code sends the full set, even if your gateway forwards to a Bedrock or Vertex upstream + * When the client speaks the Bedrock or Agent Platform format, Claude Code sends only the subset of its full capability set that those providers accept + * When the client speaks the Anthropic Messages format, Claude Code sends the full set, even if your gateway forwards to a Bedrock or Agent Platform upstream Bridging that difference is your gateway’s job. Feature pass-through describes what breaks when it doesn’t. @@ -80,13 +80,13 @@ Header| Description ---|--- `Authorization`, `x-api-key`| The developer’s gateway credential, in one or both headers depending on which [credential variable](</docs/en/llm-gateway-connect#set-the-credential-variable>) they set -`anthropic-version`| API version, currently `2023-06-01`. Bedrock- and Vertex-format requests also carry the `anthropic_version` body field, whose value is the provider dialect string, not this header’s value -`anthropic-beta`| Comma-separated capability values for the request. Forward the header verbatim; do not allowlist individual values, because the set changes with Claude Code releases. When the developer authenticates with a claude.ai login, which is possible when `ANTHROPIC_BASE_URL` is set without a gateway credential variable, this header also carries an OAuth capability that the upstream requires, and stripping it fails those requests with `401` +`anthropic-version`| API version, currently `2023-06-01`. Bedrock- and Agent Platform-format requests also carry the `anthropic_version` body field, whose value is the provider dialect string, not this header’s value +`anthropic-beta`| Comma-separated capability values for the request. Forward the header verbatim; don’t allowlist individual values, because the set changes with Claude Code releases. When the developer authenticates with a claude.ai login, which is possible when `ANTHROPIC_BASE_URL` is set without a gateway credential variable, this header also carries an OAuth capability that the upstream requires, and stripping it fails those requests with `401` `x-claude-code-session-id`| A unique identifier for the current Claude Code session. Use it to aggregate all requests from one session without parsing request bodies `x-claude-code-agent-id`| Identifier of the [subagent](</docs/en/sub-agents>) that issued the request, present only on requests from an agent Claude Code spawned inside the session. Use it with the session ID to attribute cost to parallel agents `x-claude-code-parent-agent-id`| Identifier of the agent that spawned the requesting agent, present only for nested agents -Subagent IDs are generated fresh for each spawn. Teammate agents, the named members of an [agent team](</docs/en/agent-teams>), reuse a stable name-based ID across reconnections. In both cases the ID identifies an agent, not a person or a device, so do not treat the agent ID header as a user identifier. If your developers set `ANTHROPIC_CUSTOM_HEADERS`, those headers appear on requests as well. +Subagent IDs are generated fresh for each spawn. Teammate agents, the named members of an [agent team](</docs/en/agent-teams>), reuse a stable name-based ID across reconnections. In both cases the ID identifies an agent, not a person or a device, so don’t treat the agent ID header as a user identifier. If your developers set `ANTHROPIC_CUSTOM_HEADERS`, those headers appear on requests as well. ### @@ -94,7 +94,7 @@ Forward as open lists -Treat the headers and body fields as open lists, not closed ones. Claude Code gains capabilities over releases, and they arrive as new `anthropic-beta` values, new request body fields, and occasionally new `anthropic-*` or `x-claude-code-*` headers. When forwarding to an Anthropic-format upstream, pass `anthropic-*` request headers and request body fields through unchanged rather than allowlisting the ones you see today. A gateway pinned to an observed list strips the next capability’s header or field and breaks it on the release that introduces it. The exception is a non-Anthropic upstream such as Bedrock or Vertex, where bridging the schema difference is the gateway’s job; see feature pass-through. +Treat the headers and body fields as open lists, not closed ones. Claude Code gains capabilities over releases, and they arrive as new `anthropic-beta` values, new request body fields, and occasionally new `anthropic-*` or `x-claude-code-*` headers. When forwarding to an Anthropic-format upstream, pass `anthropic-*` request headers and request body fields through unchanged rather than allowlisting the ones you see today. A gateway pinned to an observed list strips the next capability’s header or field and breaks it on the release that introduces it. The exception is a non-Anthropic upstream such as Bedrock or Agent Platform, where bridging the schema difference is the gateway’s job; see feature pass-through. ## @@ -102,7 +102,7 @@ System prompt attribution block -Claude Code prepends a short attribution block to the system prompt containing the client version and a fingerprint derived from the conversation. The `api.anthropic.com` endpoint strips the block before processing, so it does not affect first-party prompt caching; any other upstream receives it as part of the prompt. Anthropic and the cloud providers’ Claude endpoints read it for attribution, so to omit it set [`CLAUDE_CODE_ATTRIBUTION_HEADER=0`](</docs/en/env-vars>) rather than stripping it in the gateway. From Claude Code v2.1.181, the block is stable for the lifetime of a conversation when requests route through a custom base URL, so a gateway-side prompt cache keyed on the full request body works without disabling it. Before v2.1.181 the block included a per-request token; on those versions, set `CLAUDE_CODE_ATTRIBUTION_HEADER=0` if your gateway implements such a cache. +Claude Code prepends a short attribution block to the system prompt containing the client version and a fingerprint derived from the conversation. The `api.anthropic.com` endpoint strips the block before processing, so it doesn’t affect first-party prompt caching; any other upstream receives it as part of the prompt. Anthropic and the cloud providers’ Claude endpoints read it for attribution, so to omit it set [`CLAUDE_CODE_ATTRIBUTION_HEADER=0`](</docs/en/env-vars>) rather than stripping it in the gateway. From Claude Code v2.1.181, the block is stable for the lifetime of a conversation when requests route through a custom base URL, so a gateway-side prompt cache keyed on the full request body works without disabling it. Before v2.1.181 the block included a per-request token; on those versions, set `CLAUDE_CODE_ATTRIBUTION_HEADER=0` if your gateway implements such a cache. ## @@ -110,7 +110,7 @@ Feature pass-through -Claude Code treats an `ANTHROPIC_BASE_URL` gateway as an Anthropic-format endpoint and sends it the beta headers and request body fields it sends to `api.anthropic.com`, except a small set of diagnostics and defaults reserved for direct connections. Capabilities that add body fields pair them with a beta header, and the pair travels together. A gateway that strips the header while passing the body, or forwards an Anthropic-format body to an upstream with a different schema, produces hard `400` errors; only when both halves are absent together does the feature turn off quietly. A gateway that rewrites or redacts request bodies for content inspection breaks the pairing the same way stripping does, so inspect without modifying. The table notes where a feature deviates from the pairing. Fine-grained tool streaming is one of the direct-connection defaults: it is off by default whenever requests route through a custom base URL, and a gateway receives it when developers set [`CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING=1`](</docs/en/env-vars>). +Claude Code treats an `ANTHROPIC_BASE_URL` gateway as an Anthropic-format endpoint and sends it the beta headers and request body fields it sends to `api.anthropic.com`, except a small set of diagnostics and defaults reserved for direct connections, such as the fine-grained tool streaming default covered below. That set varies by release, so don’t depend on its contents. Capabilities that add body fields pair them with a beta header, and the pair travels together. A gateway that strips the header while passing the body, or forwards an Anthropic-format body to an upstream with a different schema, produces hard `400` errors; only when both halves are absent together does the feature turn off quietly. A gateway that rewrites or redacts request bodies for content inspection breaks the pairing the same way stripping does, so inspect without modifying. The table notes where a feature deviates from the pairing. Fine-grained tool streaming is one of the direct-connection defaults: it is off by default whenever requests route through a custom base URL, and a gateway receives it when developers set [`CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING=1`](</docs/en/env-vars>). Feature| Header and body pair| Symptom when broken| Remediation ---|---|---|--- @@ -118,7 +118,7 @@ [Context management](<https://platform.claude.com/docs/en/build-with-claude/context-management>)| Context management beta header pairs with the `context_management` body field| `400` with `Extra inputs are not permitted`. Common when a gateway accepts Anthropic-format requests but forwards them to Bedrock| Forward both, or [`CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`](</docs/en/env-vars>) [Extended context](<https://platform.claude.com/docs/en/build-with-claude/context-windows#1m-token-context-window>) and [interleaved thinking](<https://platform.claude.com/docs/en/build-with-claude/extended-thinking#interleaved-thinking>)| Beta headers only, no body field| Silently unavailable when the header is stripped; the upstream never sees the capability request| Forward `anthropic-beta` verbatim Beta [tool fields](<https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview>)| Tool-related beta headers pair with tool schema fields such as `strict` and `defer_loading`| `400` naming the unrecognized tool schema field when the body passes through without its header| Forward both, or `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1` -[Effort](<https://platform.claude.com/docs/en/build-with-claude/effort>) and [structured outputs](<https://platform.claude.com/docs/en/build-with-claude/structured-outputs>)| The `output_config` body field carries effort, structured-output format, and task budget settings; each pairs with its own beta header| `400` naming `output_config`, often `Extra inputs are not permitted`, on Bedrock and Vertex upstreams| Forward the field and its headers together +[Effort](<https://platform.claude.com/docs/en/build-with-claude/effort>) and [structured outputs](<https://platform.claude.com/docs/en/build-with-claude/structured-outputs>)| The `output_config` body field carries effort, structured-output format, and task budget settings; each pairs with its own beta header| `400` naming `output_config`, often `Extra inputs are not permitted`, on Bedrock and Agent Platform upstreams| Forward the field and its headers together [Token counting](<https://platform.claude.com/docs/en/build-with-claude/token-counting>)| No beta pairing; uses the `count_tokens` endpoint| Claude Code falls back to estimating context usage locally| Expose the endpoint if you want exact counts The `ANTHROPIC_DEFAULT_*_MODEL_SUPPORTED_CAPABILITIES` [variables](</docs/en/model-config>) declare model capabilities only in the provider configurations: `CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX`, `CLAUDE_CODE_USE_FOUNDRY`, and [`CLAUDE_CODE_USE_MANTLE`](</docs/en/amazon-bedrock#use-the-mantle-endpoint>). They have no effect behind an `ANTHROPIC_BASE_URL` gateway. @@ -129,7 +129,7 @@ Automatic retry and error forwarding -Claude Code retries automatically after some upstream rejections and disables the rejected capability for the rest of the conversation. Rejections of the `thinking` field, of [thinking signatures](<https://platform.claude.com/docs/en/build-with-claude/extended-thinking>), and of mid-conversation system messages all recover this way. Context management and tool schema field rejections do not retry; those `400` errors reach the developer. The retry logic matches on the upstream’s error wording, so forward error response bodies unmodified. A gateway that wraps upstream errors in its own envelope breaks the recovery path even when it preserves the status code. +Claude Code retries automatically after some upstream rejections and disables the rejected capability for the rest of the conversation. Rejections of the `thinking` field, of [thinking signatures](<https://platform.claude.com/docs/en/build-with-claude/extended-thinking>), and of mid-conversation system messages all recover this way. Context management and tool schema field rejections don’t retry; those `400` errors reach the developer. The retry logic matches on the upstream’s error wording, so forward error response bodies unmodified. A gateway that wraps upstream errors in its own envelope breaks the recovery path even when it preserves the status code. ### @@ -137,7 +137,7 @@ Disable pre-release capabilities -`CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1` stops Claude Code from sending pre-release capabilities and their body fields on every provider, including context management and the beta tool fields. It does not affect adaptive reasoning, which is selected by model rather than by beta, and it never suppresses the OAuth capability that subscription authentication requires. The set of capabilities Claude Code sends grows over releases. For current beta header strings, see the [beta headers reference](<https://platform.claude.com/docs/en/api/beta-headers>); test your gateway against new Claude Code releases rather than pinning to an observed list. +`CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1` stops Claude Code from sending pre-release capabilities and their body fields on every provider, including context management and the beta tool fields. It doesn’t affect adaptive reasoning, which is selected by model rather than by beta, and it never suppresses the OAuth capability that subscription authentication requires. The set of capabilities Claude Code sends grows over releases. For current beta header strings, see the [beta headers reference](<https://platform.claude.com/docs/en/api/beta-headers>); test your gateway against new Claude Code releases rather than pinning to an observed list. ## @@ -145,7 +145,7 @@ Model discovery -When `ANTHROPIC_BASE_URL` points at a gateway that exposes the Anthropic Messages format, Claude Code can query the gateway’s `/v1/models` endpoint at startup and add the returned models to the `/model` picker. Developers enable it by setting [`CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1`](</docs/en/env-vars>), in their own environment or through managed settings. Discovery is off by default so that gateways backed by a shared API key do not surface every model the key can access to every user. This requires Claude Code v2.1.129 or later. +When `ANTHROPIC_BASE_URL` points at a gateway that exposes the Anthropic Messages format, Claude Code can query the gateway’s `/v1/models` endpoint at startup and add the returned models to the `/model` picker. Developers enable it by setting [`CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1`](</docs/en/env-vars>), in their own environment or through managed settings. Discovery is off by default so that gateways backed by a shared API key don’t surface every model the key can access to every user. This requires Claude Code v2.1.129 or later. ### @@ -153,7 +153,7 @@ When discovery runs -Discovery applies only to the Anthropic Messages format. It does not run when: +Discovery applies only to the Anthropic Messages format. It doesn’t run when: * Any `CLAUDE_CODE_USE_*` provider variable is set, even if `ANTHROPIC_BASE_URL` is also set * `ANTHROPIC_BASE_URL` is unset or points at `api.anthropic.com` @@ -165,7 +165,7 @@ Request and response -The request is `GET /v1/models?limit=1000` with a 3-second timeout, and any redirect is treated as failure so the credential cannot leak to a redirect target. A gateway that responds slowly or redirects `/v1/models`, even `http` to `https`, fails discovery silently; serve the endpoint directly at the configured base URL. The discovery request sends exactly one credential header: +The request is `GET /v1/models?limit=1000` with a 3-second timeout, and any redirect is treated as failure so the credential can’t leak to a redirect target. A gateway that responds slowly or redirects `/v1/models`, even `http` to `https`, fails discovery silently; serve the endpoint directly at the configured base URL. The discovery request sends exactly one credential header: * `ANTHROPIC_AUTH_TOKEN` as a bearer token, when set * Otherwise the resolved API key, including an [`apiKeyHelper`](</docs/en/llm-gateway-connect#rotate-credentials-with-apikeyhelper>) value, in the `x-api-key` header @@ -185,7 +185,7 @@ Picker entries and caching -The picker is the interactive model list that opens when a developer runs `/model` in Claude Code. Each discovered entry is labeled “From gateway” and uses `display_name` when provided. A discovered ID is skipped only when it exactly matches a row already in the picker, or when both the discovered and existing IDs resolve to [Fable](</docs/en/model-config#work-with-fable-5>). Built-in rows are keyed on aliases such as `sonnet`, so a discovered ID such as `claude-sonnet-4-6` adds its own “From gateway” row alongside the built-in entry. The [`availableModels` managed setting](</docs/en/settings#available-settings>) bounds what discovery can add. Results are cached to `~/.claude/cache/gateway-models.json`, or `%USERPROFILE%\.claude\cache\gateway-models.json` on Windows, and refreshed on each startup. If the request fails or the gateway does not implement `/v1/models`, the picker falls back to the cached list from the previous startup or to the built-in model list. If your gateway serves Claude models under aliases that don’t match the discovery filter, developers can add those aliases manually with the [model configuration](</docs/en/model-config>) variables. +The picker is the interactive model list that opens when a developer runs `/model` in Claude Code. Each discovered entry is labeled “From gateway” and uses `display_name` when provided. The [`availableModels` managed setting](</docs/en/settings#available-settings>) bounds what discovery can add. A discovered ID is skipped only when it exactly matches a row already in the picker, or when both the discovered and existing IDs resolve to [Fable](</docs/en/model-config#work-with-fable-5>). Built-in rows are keyed on aliases such as `sonnet`, so a discovered ID such as `claude-sonnet-4-6` adds its own “From gateway” row alongside the built-in entry rather than replacing it. Results are cached to `~/.claude/cache/gateway-models.json`, or `%USERPROFILE%\.claude\cache\gateway-models.json` on Windows, and refreshed on each startup. If the request fails or the gateway doesn’t implement `/v1/models`, the picker falls back to the cached list from the previous startup or to the built-in model list. If your gateway serves Claude models under aliases that don’t match the discovery filter, developers can add those aliases manually with the [model configuration](</docs/en/model-config>) variables. ## @@ -195,7 +195,8 @@ For the rest of the gateway documentation set and the underlying API references: - * [LLM gateways overview](</docs/en/llm-gateway>): what a gateway is and how it interacts with claude.ai subscriptions + * [Gateway overview](</docs/en/gateways>): what a gateway is and how to choose between Claude apps gateway and another product + * [Other LLM gateways](</docs/en/llm-gateway>): how to roll out a gateway your organization runs and how it interacts with claude.ai subscriptions * [Roll out an LLM gateway for your organization](</docs/en/llm-gateway-rollout>): the admin checklist that uses this contract * [Connect Claude Code to an LLM gateway](</docs/en/llm-gateway-connect>): per-developer configuration and the troubleshooting table * [Beta headers reference](<https://platform.claude.com/docs/en/api/beta-headers>): the current set of `anthropic-beta` values
modified Roll out an LLM gateway for your organization View current →
--- a/llm-gateway-rollout.md +++ b/llm-gateway-rollout.md @@ -14,7 +14,7 @@ * A gateway deployed on your infrastructure, serving HTTPS at the exact address you’ll distribute to developers, not an address that redirects to it, and configured to route Claude model names to your provider * A provider credential for the gateway to forward with: * For the Anthropic API: an API key from the [Claude Console](<https://platform.claude.com/settings/keys>) - * For a cloud provider: cloud credentials with model access. See the prerequisites on the [Amazon Bedrock](</docs/en/amazon-bedrock#prerequisites>), [Google Vertex AI](</docs/en/google-vertex-ai#prerequisites>), or [Microsoft Foundry](</docs/en/microsoft-foundry#prerequisites>) page + * For a cloud provider: cloud credentials with model access. See the prerequisites on the [Amazon Bedrock](</docs/en/amazon-bedrock#prerequisites>), [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai#prerequisites>), or [Microsoft Foundry](</docs/en/microsoft-foundry#prerequisites>) page * A way to deliver settings files to developer machines, such as MDM or configuration management * If you don’t have one yet, [how settings reach devices](</docs/en/admin-setup#decide-how-settings-reach-devices>) compares the options @@ -163,9 +163,9 @@ `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 `ANTHROPIC_CUSTOM_HEADERS`| Adds extra HTTP headers to every API request| Your gateway requires a tenant or routing header on every request `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 -`CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS`| Stops Claude Code sending pre-release capability headers and body fields| Your gateway forwards to a Bedrock or Vertex upstream that rejects beta fields; see Gateway requirements -`ANTHROPIC_MODEL` or [`ANTHROPIC_DEFAULT_HAIKU_MODEL`](</docs/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](</docs/en/costs#background-token-usage>) to a different model. Route both the override names and Claude Code’s default names at the gateway, since some sub-calls can request the default name regardless of the override -`ANTHROPIC_BEDROCK_BASE_URL`, `ANTHROPIC_VERTEX_BASE_URL`, `ANTHROPIC_FOUNDRY_BASE_URL`, or `ANTHROPIC_AWS_BASE_URL` with the [variables for that provider](</docs/en/llm-gateway-connect#route-to-a-cloud-provider-through-a-gateway>)| Point Claude Code at the gateway through a provider-specific base URL. Bedrock and Vertex also switch to those providers’ native request format| Your gateway fronts Bedrock, Vertex, Foundry, or the Claude Platform on AWS; see [API formats](</docs/en/llm-gateway-protocol#api-formats>) +`CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS`| Stops Claude Code sending pre-release capability headers and body fields| Your gateway forwards to a Bedrock or Agent Platform upstream that rejects beta fields; see Gateway requirements +`ANTHROPIC_MODEL` or [`ANTHROPIC_DEFAULT_HAIKU_MODEL`](</docs/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](</docs/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](</docs/en/model-config>) covers which model each part of a session uses +`ANTHROPIC_BEDROCK_BASE_URL`, `ANTHROPIC_VERTEX_BASE_URL`, `ANTHROPIC_FOUNDRY_BASE_URL`, or `ANTHROPIC_AWS_BASE_URL` with the [variables for that provider](</docs/en/llm-gateway-connect#route-to-a-cloud-provider-through-a-gateway>)| Point Claude Code at the gateway through a provider-specific base URL. Bedrock and Agent Platform also switch to those providers’ native request format| Your gateway fronts Bedrock, Agent Platform, Foundry, or the Claude Platform on AWS; see [API formats](</docs/en/llm-gateway-protocol#api-formats>) #### @@ -182,7 +182,7 @@ "apiKeyHelper": "/usr/local/bin/get-gateway-key" } -Add the conditional variables from the table to the same `env` block. A managed `ANTHROPIC_BASE_URL` is enforced and cannot be overridden by a developer’s shell export, since Claude Code applies it over the process environment and lower-precedence settings. Do not include `forceLoginMethod` or `forceLoginOrgUUID` in managed settings alongside a gateway credential. On Claude Code v2.1.146 and later, either key blocks `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, and `apiKeyHelper` at startup, so developers see `This machine's managed settings require a first-party login` and cannot proceed. [Server-managed settings](</docs/en/server-managed-settings#platform-availability>) delivery requires a direct connection to `api.anthropic.com`, so it does not reach gateway-routed sessions. Gateway deployments use this file-based managed settings path, which enforces the same keys. For the credential, distribute one [`apiKeyHelper`](</docs/en/llm-gateway-connect#rotate-credentials-with-apikeyhelper>) command in the managed settings file as shown above; the command authenticates to your secrets store as the local developer, so each machine receives its own key. Alternatively, deliver each developer their key through your existing secrets process and have them set `ANTHROPIC_AUTH_TOKEN` themselves. Some environments need separate delivery: +Add the conditional variables from the table to the same `env` block. A managed `ANTHROPIC_BASE_URL` is enforced and cannot be overridden by a developer’s shell export, since Claude Code applies it over the process environment and lower-precedence settings. Do not include `forceLoginMethod` or `forceLoginOrgUUID` in managed settings alongside a gateway credential. On Claude Code v2.1.146 and later, either key, with any value, blocks `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, and `apiKeyHelper` at startup, so developers see `This machine's managed settings require a first-party login` and cannot proceed. [Server-managed settings](</docs/en/server-managed-settings#platform-availability>) delivery requires a direct connection to `api.anthropic.com`, so it does not reach gateway-routed sessions. Gateway deployments use this file-based managed settings path, which enforces the same keys. For the credential, distribute one [`apiKeyHelper`](</docs/en/llm-gateway-connect#rotate-credentials-with-apikeyhelper>) command in the managed settings file as shown above; the command authenticates to your secrets store as the local developer, so each machine receives its own key. Alternatively, deliver each developer their key through your existing secrets process and have them set `ANTHROPIC_AUTH_TOKEN` themselves. Some environments need separate delivery: * The desktop app reads gateway routing only from its MDM-delivered third-party inference configuration; deploy that file alongside managed settings so desktop sessions route through the gateway too. See the [desktop third-party configuration docs](<https://claude.com/docs/cowork/3p/configuration>) and the [desktop gateway docs](<https://claude.com/docs/cowork/3p/gateway>) * CI runners need `ANTHROPIC_BASE_URL` and the credential set in the [runner’s environment](</docs/en/llm-gateway-connect#configure-each-surface>)
modified Connect Claude Code to tools via MCP View current →
--- a/mcp.md +++ b/mcp.md @@ -146,7 +146,14 @@ # (within Claude Code) Check server status /mcp -Project-scoped servers from `.mcp.json` that are awaiting your approval appear in `claude mcp list` as `⏸ Pending approval`. Run `claude` interactively to review and approve them. `claude mcp get <name>` shows pending servers as `⏸ Pending approval` and rejected servers as `✗ Rejected`. The `/mcp` panel shows the tool count next to each connected server and flags servers that advertise the tools capability but expose no tools. If your request needs tools from a server that is still connecting in the background, Claude waits for that server before continuing. With tool search enabled, which is the default, the wait happens inside the `ToolSearch` call. In configurations without tool search, such as Vertex AI, a custom `ANTHROPIC_BASE_URL`, or `ENABLE_TOOL_SEARCH=false`, Claude uses the `WaitForMcpServers` tool instead. The server name `workspace` is reserved for internal use. If your configuration defines a server with that name, Claude Code skips it at load time and shows a warning asking you to rename it. +Project-scoped servers from `.mcp.json` that are awaiting your approval appear in `claude mcp list` as `⏸ Pending approval`. Run `claude` interactively to review and approve them. `claude mcp get <name>` shows pending servers as `⏸ Pending approval` and rejected servers as `✗ Rejected`. As of v2.1.196, `claude mcp list` and `claude mcp get` read `.mcp.json` approvals only from settings files that aren’t checked into the repository until you trust the workspace by running `claude` in it and accepting the workspace trust dialog. A cloned repository can’t approve its own servers: [`enableAllProjectMcpServers` or `enabledMcpjsonServers`](</docs/en/settings#available-settings>) committed to the project’s `.claude/settings.json` is ignored in an untrusted folder, and the server stays at `⏸ Pending approval` instead of being connected and health-checked. Approvals from these sources still apply in an untrusted folder: + + * your user `~/.claude/settings.json` + * managed settings + * settings passed with `--settings` + * `.claude/settings.local.json`, as long as git doesn’t track it + +A `disabledMcpjsonServers` entry in any settings file still rejects the server. The `/mcp` panel shows the tool count next to each connected server and flags servers that advertise the tools capability but expose no tools. If your request needs tools from a server that is still connecting in the background, Claude waits for that server before continuing. With tool search enabled, which is the default, the wait happens inside the `ToolSearch` call. In configurations without tool search, such as Vertex AI, a custom `ANTHROPIC_BASE_URL`, or `ENABLE_TOOL_SEARCH=false`, Claude uses the `WaitForMcpServers` tool instead. The server name `workspace` is reserved for internal use. If your configuration defines a server with that name, Claude Code skips it at load time and shows a warning asking you to rename it. ### @@ -449,7 +456,7 @@ Authenticate with remote MCP servers -Many cloud-based MCP servers require authentication. Claude Code supports OAuth 2.0 for secure connections. Claude Code marks a remote server as needing authentication when the server responds with `401 Unauthorized` or `403 Forbidden`. Either status code flags the server in `/mcp` so you can complete the OAuth flow. A custom server that returns a `WWW-Authenticate` header pointing to its authorization server gets the same automatic discovery as any other remote server. If you configured `headers.Authorization` for the server and the server rejects that header, Claude Code reports the connection as failed instead of falling back to OAuth. Check that the token is valid for the MCP endpoint, or remove the header to use the OAuth flow. +Many cloud-based MCP servers require authentication. Claude Code supports OAuth 2.0 for secure connections. Claude Code marks a remote server as needing authentication when the server responds with `401 Unauthorized` or `403 Forbidden`. Either status code flags the server in `/mcp` so you can complete the OAuth flow. As of v2.1.195, when a token refresh fails because the server rejects the stored refresh token, Claude Code immediately shows a notice pointing at `/mcp`. The connected server’s menu there offers Re-authenticate, so you can sign in again before the next tool call fails. A custom server that returns a `WWW-Authenticate` header pointing to its authorization server gets the same automatic discovery as any other remote server. As of v2.1.193, Claude Code also shows a startup notice when one or more configured servers need authentication, so you don’t have to open `/mcp` to discover which servers need sign-in. In non-interactive mode there’s no `/mcp` panel, so Claude Code can’t run the OAuth flow for you. As of v2.1.196, when a configured server needs authentication during a `claude -p` or Agent SDK run with tool search enabled, which is the default, Claude Code tells Claude that the server’s tools are unavailable until you authorize it. Claude can then name the server that needs sign-in instead of responding as if the server weren’t configured. Complete the sign-in from an interactive session with `/mcp` or `claude mcp login <name>`. If you configured `headers.Authorization` for the server and the server rejects that header, Claude Code reports the connection as failed instead of falling back to OAuth. Check that the token is valid for the MCP endpoint, or remove the header to use the OAuth flow. 1 @@ -611,7 +618,7 @@ } } -`oauth.scopes` takes precedence over both `authServerMetadataUrl` and the scopes the server discovers at `/.well-known`. Leave it unset to let the MCP server determine the requested scope set. If the authorization server advertises `offline_access` in `scopes_supported`, Claude Code appends it to the pinned scopes so the access token can be refreshed without a new browser sign-in. If the server later returns a 403 `insufficient_scope` for a tool call, Claude Code re-authenticates with the same pinned scopes. Widen `oauth.scopes` when a tool you need requires a scope outside the pinned set. +`oauth.scopes` takes precedence over both `authServerMetadataUrl` and the scopes the server discovers at `/.well-known`. Leave it unset to let the MCP server determine the requested scope set. As of v2.1.196, when `oauth.scopes` isn’t set, Claude Code requests the scope provided by the server’s `WWW-Authenticate` header or its protected resource metadata, and sends no `scope` parameter when neither provides one. It no longer requests the full `scopes_supported` catalog from automatically discovered authorization server metadata. Requesting that catalog made identity providers that advertise admin-only or template scopes reject the authorization request with an `invalid_scope` error. Metadata fetched from a configured `authServerMetadataUrl` still supplies its `scopes_supported` as the requested scopes. If the authorization server advertises `offline_access` in `scopes_supported`, Claude Code appends it to the pinned scopes so the access token can be refreshed without a new browser sign-in. If the server later returns a 403 `insufficient_scope` for a tool call, Claude Code re-authenticates with the same pinned scopes. Widen `oauth.scopes` when a tool you need requires a scope outside the pinned set. ### @@ -649,14 +656,15 @@ * The command runs in a shell with a 10-second timeout * Dynamic headers override any static `headers` with the same name -The helper runs fresh on each connection, at session start and on reconnect. There is no caching, so your script is responsible for any token reuse. Claude Code sets these environment variables when executing the helper: +The helper runs fresh on each connection, at session start and on reconnect. There is no caching, so your script is responsible for any token reuse. As of v2.1.193, if a tool call returns `401 Unauthorized` or `403 Forbidden`, Claude Code automatically re-runs the helper, reconnects with the fresh headers, and retries the call once. Claude Code marks the server as needing authentication in `/mcp` only if that retry also fails. Claude Code sets these environment variables when executing the helper: Variable| Value ---|--- `CLAUDE_CODE_MCP_SERVER_NAME`| the name of the MCP server `CLAUDE_CODE_MCP_SERVER_URL`| the URL of the MCP server - -Use these to write a single helper script that serves multiple MCP servers. +`CLAUDE_PLUGIN_ROOT`| the plugin’s root directory. Set only when a [plugin](</docs/en/plugins-reference#mcp-servers>) provides the server + +Use these to write a single helper script that serves multiple MCP servers. For a plugin-provided server, the helper also runs with its working directory set to the plugin root, so a relative `headersHelper` path resolves inside the plugin directory rather than against the session’s working directory. Requires Claude Code v2.1.195 or later. `headersHelper` executes arbitrary shell commands. When defined at project or local scope, it only runs after you accept the workspace trust dialog.
modified Model configuration View current →
--- a/model-config.md +++ b/model-config.md @@ -72,7 +72,7 @@ * `Enter`: switch model and save as your default * `s`: switch model for this session only -Typing `/model <name>` directly behaves like `Enter`. Project and managed settings still take precedence and reapply on the next launch. In v2.1.144 through v2.1.152, `/model` applied to the current session only and `d` in the picker saved a default. The `--model` flag and `ANTHROPIC_MODEL` environment variable apply only to the session you launch with them. To run different models in different terminals at the same time, launch each one with its own `--model` flag rather than switching with `/model`. Resumed 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 that model has been retired or is excluded by `availableModels`, the session falls through to the normal precedence order. This prevents another session’s `/model` choice from changing the model on resume. When the active model at startup comes from project or managed settings rather than your own selection, the startup header shows which settings file set it. Run `/model` to override; the project or managed setting reapplies on the next launch. When the requested model has a scheduled retirement date or is automatically remapped to a newer version, Claude Code shows a warning that names the requested model. Interactive sessions show it as a startup notice. From v2.1.182, the same warning is written to stderr in [non-interactive mode](</docs/en/headless>) when using the default text output format. The check also covers a `model` set in [subagent frontmatter](</docs/en/sub-agents>). The stderr warning is suppressed for `--output-format json` and `stream-json`; read the actual model from the `modelUsage` field of the [result message](</docs/en/headless#get-structured-output>) instead. Example usage: +Typing `/model <name>` directly behaves like `Enter`. Project and managed settings still take precedence and reapply on the next launch. In v2.1.144 through v2.1.152, `/model` applied to the current session only and `d` in the picker saved a default. The `--model` flag and `ANTHROPIC_MODEL` environment variable apply only to the session you launch with them. To run different models in different terminals at the same time, launch each one with its own `--model` flag rather than switching with `/model`. Resumed 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`, the session falls through to the normal precedence order. This prevents another session’s `/model` choice from changing the model on resume. A model you pick for the new launch with `--model` or `ANTHROPIC_MODEL` still takes precedence over the restored model. As of v2.1.195, so does an `ANTHROPIC_DEFAULT_OPUS_MODEL` family variable. When the active model at startup comes from project or managed settings rather than your own selection, the startup header shows which settings file set it. Run `/model` to override; the project or managed setting reapplies on the next launch. When the requested model has a scheduled retirement date or is automatically remapped to a newer version, Claude Code shows a warning that names the requested model. Interactive sessions show it as a startup notice. From v2.1.182, the same warning is written to stderr in [non-interactive mode](</docs/en/headless>) when using the default text output format. The check also covers a `model` set in [subagent frontmatter](</docs/en/sub-agents>). The stderr warning is suppressed for `--output-format json` and `stream-json`; read the actual model from the `modelUsage` field of the [result message](</docs/en/headless#get-structured-output>) instead. Example usage: # Start with Opus claude --model opus @@ -137,7 +137,7 @@ Default model behavior -The Default option in the model picker is not affected by `availableModels` unless `enforceAvailableModels` is also set. On its own, `availableModels` leaves Default available, resolving to the system’s runtime default based on the user’s subscription tier. If the tier default is a model you intend to restrict, set `enforceAvailableModels` as well. An empty `availableModels` array never engages the Default-model enforcement: with `availableModels: []`, named model selections are blocked but the Default model for the account type remains usable regardless of `enforceAvailableModels`. +The Default option in the model picker is not affected by `availableModels` unless `enforceAvailableModels` is also set. On its own, `availableModels` leaves Default available, resolving to the system’s runtime default for the account. If that default is a model you intend to restrict, set `enforceAvailableModels` as well. An empty `availableModels` array never engages the Default-model enforcement: with `availableModels: []`, named model selections are blocked but the Default model for the account type remains usable regardless of `enforceAvailableModels`. ### @@ -160,7 +160,7 @@ Control the model users run on -The `model` setting is an initial selection, not enforcement. It sets which model is active when a session starts, but users can still open `/model` and pick Default, which resolves to the system default for their tier regardless of what `model` is set to, unless `enforceAvailableModels` redirects it. To fully control the model experience, combine these settings: +The `model` setting is an initial selection, not enforcement. It sets which model is active when a session starts, but users can still open `/model` and pick Default, which resolves to the system’s runtime default regardless of what `model` is set to, unless `enforceAvailableModels` redirects it. To fully control the model experience, combine these settings: * **`availableModels`** : restricts which named models users can switch to * **`enforceAvailableModels`** : extends the `availableModels` allowlist to the Default option, so Default cannot resolve to a model outside the list
modified Monitoring View current →
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -83,6 +83,7 @@ `OTEL_METRIC_EXPORT_INTERVAL`| Export interval in milliseconds (default: 60000)| `5000`, `60000` `OTEL_LOGS_EXPORT_INTERVAL`| Logs export interval in milliseconds (default: 5000)| `1000`, `10000` `OTEL_LOG_USER_PROMPTS`| Enable logging of user prompt content (default: disabled)| `1` to enable +`OTEL_LOG_ASSISTANT_RESPONSES`| Enable logging of assistant response text on `assistant_response` events (default: disabled). When unset, falls back to the value of `OTEL_LOG_USER_PROMPTS`. Requires Claude Code v2.1.193 or later| `1` to enable, `0` to keep redacted `OTEL_LOG_TOOL_DETAILS`| Enable logging of tool parameters and input arguments in tool events and trace span attributes: Bash commands, MCP server and tool names, skill names, and tool input. Also enables custom, plugin, and MCP command names on `user_prompt` events (default: disabled)| `1` to enable `OTEL_LOG_TOOL_CONTENT`| Enable logging of tool input and output content in span events (default: disabled). Requires tracing. Content is truncated at 60 KB| `1` to enable `OTEL_LOG_RAW_API_BODIES`| Emit the full Anthropic Messages API request and response JSON as `api_request_body` / `api_response_body` log events (default: disabled). Bodies include the entire conversation history. Enabling this implies consent to everything `OTEL_LOG_USER_PROMPTS`, `OTEL_LOG_TOOL_DETAILS`, and `OTEL_LOG_TOOL_CONTENT` would reveal| `1` for inline bodies truncated at 60 KB, or `file:<dir>` for untruncated bodies on disk with a `body_ref` pointer in the event @@ -414,7 +415,7 @@ `terminal.type`| Terminal type, such as `iTerm.app`, `vscode`, `cursor`, or `tmux`| Always included when detected Keys from `OTEL_RESOURCE_ATTRIBUTES`| Custom attributes you set, such as `department` or `team.id`. See Multi-team organization support| `OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES` (default: true) -Events additionally include the following attributes. These are never attached to metrics because they would cause unbounded cardinality: +When Claude Code is signed in to a [Claude apps gateway](</docs/en/claude-apps-gateway>), the CLI stamps exports with the authenticated identity from the gateway session: `user.id` is the IdP subject rather than an anonymous installation identifier, `user.email` is the signed-in email, and `user.groups` carries IdP group membership as a comma-separated string. Each export also carries `identity.source: gateway-oidc`. The gateway identity is applied last, so `user.*` and `identity.*` keys set through `OTEL_RESOURCE_ATTRIBUTES` are ignored on gateway sessions. Events additionally include the following attributes. These are never attached to metrics because they would cause unbounded cardinality: * `prompt.id`: UUID correlating a user prompt with all subsequent events until the next prompt. See Event correlation attributes. * `workspace.host_paths`: host workspace directories selected in the desktop app, as a string array @@ -590,6 +591,24 @@ * `prompt`: Prompt content. Redacted by default. Set `OTEL_LOG_USER_PROMPTS=1` to include it * `command_name`: Command name when the prompt invokes one. Built-in and bundled command names such as `compact` or `debug` are emitted as-is; aliases such as `reset` emit as typed rather than the canonical name. Custom, plugin, and MCP command names collapse to `custom` or `mcp` unless `OTEL_LOG_TOOL_DETAILS=1` is set * `command_source`: Origin of the command when present: `builtin`, `custom`, or `mcp`. Plugin-provided commands report as `custom` + +#### + +​ + +Assistant response event + +Logged after each API request that returns text content from the model. Only the response’s text blocks are included; thinking blocks and tool-use blocks are excluded. Requires Claude Code v2.1.193 or later. **Event Name** : `claude_code.assistant_response` **Attributes** : + + * All standard attributes + * `event.name`: `"assistant_response"` + * `event.timestamp`: ISO 8601 timestamp + * `event.sequence`: monotonically increasing counter for ordering events within a session + * `response_length`: Length of the response text in characters + * `response`: Response text, truncated at 60 KB. Redacted to `<REDACTED>` by default. Set `OTEL_LOG_ASSISTANT_RESPONSES=1` to include it. When `OTEL_LOG_ASSISTANT_RESPONSES` is unset, `OTEL_LOG_USER_PROMPTS` controls it instead, so set `OTEL_LOG_ASSISTANT_RESPONSES=0` to keep responses redacted while prompt logging is on + * `model`: Model identifier (for example, “claude-sonnet-4-6”) + * `request_id`: Anthropic API request ID from the response’s `request-id` header. Present only when the API returns one + * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name #### @@ -1136,7 +1155,7 @@ Attribute actions to users -The standard attributes on each event include the authenticated user’s identity: `user.email`, `user.account_uuid`, `user.account_id`, and `organization.id` when signed in with a Claude account, plus the installation-scoped `user.id` and the per-session `session.id`. MCP tool calls, Bash commands, and file edits are therefore attributed to the developer who started the session. Claude Code doesn’t act under a separate service account; the identity recorded on each event is the developer’s own Claude account. When Claude Code authenticates with a direct API key, or against Bedrock, Vertex AI, or Microsoft Foundry, there is no Claude account in the session and only `user.id` and `session.id` are populated. In these deployments, attach user identity yourself with `OTEL_RESOURCE_ATTRIBUTES`, set per user through the managed settings file or a launch wrapper: +The standard attributes on each event include the authenticated user’s identity: `user.email`, `user.account_uuid`, `user.account_id`, and `organization.id` when signed in with a Claude account, plus `user.id` and the per-session `session.id`. `user.id` is an installation-scoped identifier, except on [Claude apps gateway](</docs/en/claude-apps-gateway>) sessions, where it is the IdP subject from the gateway-issued token. MCP tool calls, Bash commands, and file edits are therefore attributed to the developer who started the session. Claude Code doesn’t act under a separate service account; the identity recorded on each event is the developer’s own Claude account, or the developer’s IdP identity on a [Claude apps gateway](</docs/en/claude-apps-gateway>) session. When Claude Code authenticates with a direct API key, or against Bedrock, Vertex AI, or Microsoft Foundry, there is no Claude account in the session and only `user.id` and `session.id` are populated. In these deployments, attach user identity yourself with `OTEL_RESOURCE_ATTRIBUTES`, set per user through the managed settings file or a launch wrapper. Claude apps gateway sessions need none of this: the CLI stamps the IdP identity automatically, as described in Standard attributes. export OTEL_RESOURCE_ATTRIBUTES="enduser.id=jdoe@example.com,enduser.directory_id=S-1-5-21-..." @@ -1274,6 +1293,7 @@ * Raw file contents and code snippets are not included in metrics or events. Trace spans are a separate data path: see the `OTEL_LOG_TOOL_CONTENT` bullet below * When authenticated via OAuth, `user.email` is included in telemetry attributes. If this is a concern for your organization, work with your telemetry backend to filter or redact this field * User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1` + * Assistant response text is not collected by default. Only response length is recorded. To include response text, set `OTEL_LOG_ASSISTANT_RESPONSES=1`. Like all OpenTelemetry data from Claude Code, the response text is sent only to the OTel endpoint you configure, never to Anthropic. When this variable is unset, `OTEL_LOG_USER_PROMPTS` is used as a fallback, so set `OTEL_LOG_ASSISTANT_RESPONSES=0` if you want prompt content without response content * Tool input arguments and parameters are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. This data is sent only to the OTEL endpoint you configure, never to Anthropic. Arguments may still contain sensitive values, so configure your telemetry backend to filter or redact these attributes as needed. When enabled: * `tool_result` and `tool_decision` events include a `tool_parameters` attribute with Bash commands, MCP server and tool names, and skill names. Fields such as `full_command` are emitted untruncated * `tool_result` events additionally include a `tool_input` attribute with file paths, URLs, search patterns, and other arguments. Individual values over 512 characters are truncated and the total is bounded to ~4 K characters
modified Enterprise network configuration View current →
--- a/network-config.md +++ b/network-config.md @@ -51,7 +51,7 @@ CA certificate store -By default, Claude Code trusts both its bundled Mozilla CA certificates and your operating system’s certificate store. Enterprise TLS-inspection proxies such as CrowdStrike Falcon and Zscaler work without additional configuration when their root certificate is installed in the OS trust store. `CLAUDE_CODE_CERT_STORE` accepts a comma-separated list of sources. Recognized values are `bundled` for the Mozilla CA set shipped with Claude Code and `system` for the operating system trust store. The default is `bundled,system`. To trust only the bundled Mozilla CA set: +By default, Claude Code trusts both its bundled Mozilla CA certificates and your operating system’s certificate store. Reading the OS store requires a runtime with `tls.getCACertificates`: the native installer always has it, and npm installs need Node 22.15 or later. On older Node versions, only the bundled set and `NODE_EXTRA_CA_CERTS` apply. Enterprise TLS-inspection proxies such as CrowdStrike Falcon and Zscaler work without additional configuration when their root certificate is installed in the OS trust store and the runtime can read it. `CLAUDE_CODE_CERT_STORE` accepts a comma-separated list of sources. Recognized values are `bundled` for the Mozilla CA set shipped with Claude Code and `system` for the operating system trust store. The default is `bundled,system`. To trust only the bundled Mozilla CA set: export CLAUDE_CODE_CERT_STORE=bundled @@ -107,7 +107,7 @@ `*.claudeusercontent.com`| Viewing [artifacts](</docs/en/artifacts>) on claude.ai. The viewer loads each artifact’s content from a sandboxed subdomain of this origin. Required in the viewer’s browser, not by the CLI itself `raw.githubusercontent.com`| Changelog feed for [`/release-notes`](</docs/en/commands>) and the release notes shown after updating; plugin marketplace install counts -If you install Claude Code through npm or manage your own binary distribution, end users may not need access to `downloads.claude.ai` or `storage.googleapis.com`. Claude Code also sends optional operational telemetry by default, which you can disable with environment variables. See [Telemetry services](</docs/en/data-usage#telemetry-services>) for how to disable it before finalizing your allowlist. When using [Amazon Bedrock](</docs/en/amazon-bedrock>), [Google Vertex AI](</docs/en/google-vertex-ai>), or [Microsoft Foundry](</docs/en/microsoft-foundry>), model traffic and authentication go to your provider instead of `api.anthropic.com`, `claude.ai`, or `platform.claude.com`. The WebFetch tool still calls `api.anthropic.com` for its [domain safety check](</docs/en/data-usage#webfetch-domain-safety-check>) unless you set `skipWebFetchPreflight: true` in [settings](</docs/en/settings>). [Claude Code on the web](</docs/en/claude-code-on-the-web>) and [Code Review](</docs/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>). For self-hosted [GitHub Enterprise Server](</docs/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. +If you install Claude Code through npm or manage your own binary distribution, end users may not need access to `downloads.claude.ai` or `storage.googleapis.com`. Claude Code also sends optional operational telemetry by default, which you can disable with environment variables. See [Telemetry services](</docs/en/data-usage#telemetry-services>) for how to disable it before finalizing your allowlist. When using [Amazon Bedrock](</docs/en/amazon-bedrock>), [Google Vertex AI](</docs/en/google-vertex-ai>), [Microsoft Foundry](</docs/en/microsoft-foundry>), or a signed-in [Claude apps gateway](</docs/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](</docs/en/data-usage#webfetch-domain-safety-check>) unless you set `skipWebFetchPreflight: true` in [settings](</docs/en/settings>). [Claude Code on the web](</docs/en/claude-code-on-the-web>) and [Code Review](</docs/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>). For self-hosted [GitHub Enterprise Server](</docs/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. ##
modified Choose a permission mode View current →
--- a/permission-modes.md +++ b/permission-modes.md @@ -39,7 +39,7 @@ **During a session** : press `Shift+Tab` to cycle `default` → `acceptEdits` → `plan`. The current mode appears in the status bar. Not every mode is in the default cycle: - * `auto`: appears when your account meets the auto mode requirements; cycling to auto shows an opt-in prompt until you accept it, or select **No, don’t ask again** to remove auto from the cycle + * `auto`: appears when your account meets the auto mode requirements; cycling to it switches modes without a confirmation prompt * `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 it * `dontAsk`: never appears in the cycle; set it with `--permission-mode dontAsk` @@ -150,8 +150,8 @@ * **Plan** : All plans. * **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 lock it off by setting `permissions.disableAutoMode` to `"disable"` in [managed settings](</docs/en/permissions#managed-settings>). - * **Model** : on the Anthropic API, Claude Opus 4.6 or later, or Sonnet 4.6. On Amazon Bedrock, Google Cloud Vertex AI, and Microsoft Foundry, only Claude Opus 4.7 and Opus 4.8. Older models, including Sonnet 4.5, Opus 4.5, Haiku, and claude-3 models, are not supported on any provider. - * **Provider** : available by default on the Anthropic API. On Amazon Bedrock, Google Cloud Vertex AI, and Microsoft Foundry, auto mode is off until you set `CLAUDE_CODE_ENABLE_AUTO_MODE`. + * **Model** : on the Anthropic API, Claude Opus 4.6 or later, or Sonnet 4.6. On Amazon Bedrock, Google Cloud Vertex AI, Microsoft Foundry, and signed-in [Claude apps gateway](</docs/en/claude-apps-gateway>) sessions, only Claude Opus 4.7 and Opus 4.8. Older models, including Sonnet 4.5, Opus 4.5, Haiku, and claude-3 models, are not supported on any provider. + * **Provider** : available by default on the Anthropic API. On Amazon Bedrock, Google Cloud Vertex AI, Microsoft Foundry, and signed-in Claude apps gateway sessions, auto mode is off until you set `CLAUDE_CODE_ENABLE_AUTO_MODE`. If 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](</docs/en/errors#auto-mode-cannot-determine-the-safety-of-an-action>). If you set `defaultMode: "auto"` in [settings](</docs/en/settings#available-settings>) and the session starts in `default` mode with no error, the setting is likely in `.claude/settings.json` or `.claude/settings.local.json`. Claude Code v2.1.142 and later ignore `auto` from those files so a repository cannot grant itself auto mode. Move it to `~/.claude/settings.json`. @@ -161,7 +161,7 @@ Enable auto mode on Bedrock, Vertex AI, or Foundry -On [Amazon Bedrock](</docs/en/amazon-bedrock>), [Google Cloud Vertex AI](</docs/en/google-vertex-ai>), and [Microsoft Foundry](</docs/en/microsoft-foundry>), auto mode does not appear in the `Shift+Tab` cycle until `CLAUDE_CODE_ENABLE_AUTO_MODE` is set to `1`. The variable works in Claude Code v2.1.158 and later. Only Claude Opus 4.7 and Opus 4.8 are supported on these providers. To enable it for one developer, add the variable to the `env` block in `~/.claude/settings.json`: +On [Amazon Bedrock](</docs/en/amazon-bedrock>), [Google Cloud Vertex AI](</docs/en/google-vertex-ai>), [Microsoft Foundry](</docs/en/microsoft-foundry>), and signed-in [Claude apps gateway](</docs/en/claude-apps-gateway>) sessions, auto mode does not appear in the `Shift+Tab` cycle until `CLAUDE_CODE_ENABLE_AUTO_MODE` is set to `1`. The variable works in Claude Code v2.1.158 and later. Only Claude Opus 4.7 and Opus 4.8 are supported on these providers. To enable it for one developer, add the variable to the `env` block in `~/.claude/settings.json`: { "env": { @@ -169,7 +169,7 @@ } } -To enable it for your organization, add the same `env` block to [managed settings](</docs/en/settings#settings-files>). Once the variable is set, auto mode appears in the `Shift+Tab` cycle for every session. To make it the default starting mode, also set `"permissions": {"defaultMode": "auto"}` in user or managed settings. On these providers, Claude Code ignores `defaultMode: "auto"` unless `CLAUDE_CODE_ENABLE_AUTO_MODE` is also set. To prevent developers from enabling auto mode, set `disableAutoMode` to `"disable"` in managed settings. This overrides the enable variable. If you connect through an [LLM gateway](</docs/en/llm-gateway>) configured with `ANTHROPIC_BASE_URL`, auto mode may already be reachable without the enable variable, because the gateway routes requests through the Anthropic API. The `disableAutoMode` setting applies the same way in that configuration. +To enable it for your organization, add the same `env` block to [managed settings](</docs/en/settings#settings-files>). Once the variable is set, auto mode appears in the `Shift+Tab` cycle for every session. To make it the default starting mode, also set `"permissions": {"defaultMode": "auto"}` in user or managed settings. On these providers, Claude Code ignores `defaultMode: "auto"` unless `CLAUDE_CODE_ENABLE_AUTO_MODE` is also set. To prevent developers from enabling auto mode, set `disableAutoMode` to `"disable"` in managed settings. This overrides the enable variable. If you connect through an [LLM gateway](</docs/en/llm-gateway>) configured with `ANTHROPIC_BASE_URL`, auto mode may already be reachable without the enable variable, because the gateway routes requests through the Anthropic API. This does not apply to a signed-in [Claude apps gateway](</docs/en/claude-apps-gateway>) session, which is its own provider class and requires the enable variable. The `disableAutoMode` setting applies the same way in either configuration. ### @@ -191,6 +191,23 @@ * `git commit --amend` when the commit at HEAD was not created in this session * `terraform destroy`, `pulumi destroy`, `cdk destroy`, or `terragrunt destroy`, and applying a plan that destroys resources +Claude Code v2.1.195 and later block more categories by default. Several depend on [environment](</docs/en/auto-mode-config#define-trusted-infrastructure>) entries, such as sensitive remote targets and protected IaC scopes, that you can narrow to concrete names. + + * Writing to a secret manager, or changing DNS records or TLS certificates + * Merging a pull request no human has approved, approving Claude’s own pull request, or disabling CI checks + * Posting a comment that is itself a command to automation, such as `atlantis apply` or a bot’s `/deploy` or `/merge` + * Toggling, ramping, or deleting a production feature flag + * Applying infrastructure changes to a protected IaC scope, or draining and removing cluster nodes + * Writes to a shared compute cluster that reach beyond the resource you named, such as a label selector or `--all` that catches other users’ jobs + * Creating Kubernetes resources that run on every node or intercept cluster traffic, such as DaemonSets and admission webhooks + * Interactive shells or port-forwards into a sensitive remote target + * Opening a tunnel or reverse shell that makes a local service reachable from the public internet + * Printing a live credential or token into the transcript or a file + * Accessing a PII or regulated-data location, or copying data out of one + * Routing a package install around your internal package registry to a public registry + * Running a command with a flag that disarms a safety guard, like `--insecure` + * [Claude in Chrome](</docs/en/chrome>) browser actions that could send page content, cookies, or credentials off-origin + **Allowed by default** : * Local file operations in your working directory @@ -198,6 +215,14 @@ * Reading `.env` and sending credentials to their matching API * Read-only HTTP requests * Pushing to the branch you started on or one Claude created + +Claude Code v2.1.195 and later also allow these by default: + + * Deleting the exact jobs Claude created earlier in the same session + * Reading, reviewing, or writing security-related code, configs, and threat models as part of your task + * Messages between agents working together in the same multi-agent session + * Sending data to the trusted domains, buckets, and services you list in [`environment`](</docs/en/auto-mode-config#define-trusted-infrastructure>). This covers data flow only, not destructive or credential operations on the same infrastructure + * [Claude in Chrome](</docs/en/chrome>) navigation to a trusted internal domain, localhost, or a URL you named Sandbox network access requests are routed through the classifier rather than allowed by default. Run `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](</docs/en/auto-mode-config>).
modified Configure permissions View current →
--- a/permissions.md +++ b/permissions.md @@ -422,7 +422,7 @@ Managed settings -For organizations that need centralized control over Claude Code configuration, administrators can deploy managed settings that can’t be overridden by user or project settings. These policy settings follow the same format as regular settings files and can be delivered through MDM/OS-level policies, managed settings files, or [server-managed settings](</docs/en/server-managed-settings>). See [settings files](</docs/en/settings#settings-files>) for delivery mechanisms and file locations. +For organizations that need centralized control over Claude Code configuration, administrators can deploy managed settings that can’t be overridden by user or project settings. These policy settings follow the same format as regular settings files and can be delivered through MDM/OS-level policies, managed settings files, [server-managed settings](</docs/en/server-managed-settings>), or a self-hosted [Claude apps gateway](</docs/en/claude-apps-gateway>). See [settings files](</docs/en/settings#settings-files>) for delivery mechanisms and file locations. ### @@ -441,6 +441,7 @@ `allowManagedPermissionRulesOnly`| When `true`, prevents user and project settings from defining `allow`, `ask`, or `deny` permission rules. Only rules in managed settings apply. Doesn’t affect the MCP server allowlist; for that, set `allowManagedMcpServersOnly` `blockedMarketplaces`| Blocklist of marketplace sources. Blocked sources are checked before downloading, so they never touch the filesystem. See [managed marketplace restrictions](</docs/en/plugin-marketplaces#managed-marketplace-restrictions>) `channelsEnabled`| Allow [channels](</docs/en/channels>) for the organization. See [enterprise controls](</docs/en/channels#enterprise-controls>) for the default on each plan +`disableSideloadFlags`| Reject the `--plugin-dir`, `--plugin-url`, `--agents`, and `--mcp-config` CLI flags at startup. Without this, users can bypass `strictKnownMarketplaces` for a single run by passing these flags. See [`disableSideloadFlags`](</docs/en/settings#available-settings>). Requires Claude Code v2.1.193 or later `forceRemoteSettingsRefresh`| When `true`, blocks CLI startup until remote managed settings are freshly fetched and exits if the fetch fails. See [fail-closed enforcement](</docs/en/server-managed-settings#enforce-fail-closed-startup>) `pluginTrustMessage`| Custom message appended to the plugin trust warning shown before installation `sandbox.filesystem.allowManagedReadPathsOnly`| When `true`, only `filesystem.allowRead` paths from managed settings are respected. `denyRead` still merges from all sources
modified Constrain plugin dependency versions View current →
--- a/plugin-dependencies.md +++ b/plugin-dependencies.md @@ -76,7 +76,12 @@ claude plugin tag --push -The `claude plugin tag` command derives the tag name from the plugin’s manifest and the enclosing marketplace entry. Before creating the tag, it validates the plugin contents, checks that `plugin.json` and the marketplace entry agree on the version, requires a clean working tree under the plugin directory, and refuses if the tag already exists. Add `--dry-run` to see what would be tagged without creating it. Running `git tag secrets-vault--v2.1.0` directly is equivalent if you keep `plugin.json` and the marketplace entry in sync yourself. The plugin name prefix lets one marketplace repository host multiple plugins with independent version lines. The `--v` separator is parsed as a prefix match on the full plugin name, so plugin names that contain hyphens are handled correctly. When you install a plugin that declares `{ "name": "secrets-vault", "version": "~2.1.0" }`, Claude Code lists the marketplace’s tags, filters to those starting with `secrets-vault--v`, and fetches the highest version satisfying `~2.1.0`. If no matching tag exists, the dependent plugin is disabled with an error listing the available versions. The resolved tag’s semver is recorded separately from `plugin.json`’s `version`, so constraint checks use the tag that was actually fetched even if `plugin.json` at that commit has a stale value. The cache directory name for a tag-resolved install includes a 12-character commit-SHA suffix, so if a maintainer force-moves a tag to a different commit, the next install gets a fresh cache directory instead of reusing stale content. +The `claude plugin tag` command derives the tag name from the plugin’s manifest and the enclosing marketplace entry. Before creating the tag, it validates the plugin contents, checks that `plugin.json` and the marketplace entry agree on the version, requires a clean working tree under the plugin directory, and refuses if the tag already exists. Add `--dry-run` to see what would be tagged without creating it. Running `git tag secrets-vault--v2.1.0` directly is equivalent if you keep `plugin.json` and the marketplace entry in sync yourself. The plugin name prefix lets one marketplace repository host multiple plugins with independent version lines. The `--v` separator is parsed as a prefix match on the full plugin name, so plugin names that contain hyphens are handled correctly. When you install a plugin that declares `{ "name": "secrets-vault", "version": "~2.1.0" }`, Claude Code lists the marketplace’s tags, filters to those starting with `secrets-vault--v`, and fetches the highest version satisfying `~2.1.0`. If no matching tag exists, the dependent plugin is disabled with an error listing the available versions. A marketplace added as a local folder path resolves tags the same way when the folder is a git repository. This requires Claude Code v2.1.196 or later. In two cases Claude Code installs the dependency from the folder’s current contents instead: + + * Earlier versions don’t read tags from a local-folder marketplace, so a constrained dependency loads only if that copy satisfies the range. + * A local folder that isn’t a git repository has no tags, regardless of version. + +The resolved tag’s semver is recorded separately from `plugin.json`’s `version`, so constraint checks use the tag that was actually fetched even if `plugin.json` at that commit has a stale value. The cache directory name for a tag-resolved install includes a 12-character commit-SHA suffix, so if a maintainer force-moves a tag to a different commit, the next install gets a fresh cache directory instead of reusing stale content. For `npm` marketplace sources, the constraint does not control which version is fetched, since tag-based resolution applies only to git-backed sources. The constraint is still checked at load time, and the dependent plugin is disabled with `dependency-version-unsatisfied` if the installed version does not satisfy it.
modified Create and distribute a plugin marketplace View current →
Show diff (101 lines)
--- a/plugin-marketplaces.md +++ b/plugin-marketplaces.md @@ -41,7 +41,6 @@ --- description: Review code for bugs, security, and performance - disable-model-invocation: true --- Review the code I've selected or the recent changes for: @@ -190,6 +189,7 @@ `version`| string| Marketplace manifest version `metadata.pluginRoot`| string| Base directory prepended to relative plugin source paths (for example, `"./plugins"` lets you write `"source": "formatter"` instead of `"source": "./plugins/formatter"`) `allowCrossMarketplaceDependenciesOn`| array| Other marketplaces that plugins in this marketplace may depend on. Dependencies from a marketplace not listed here are blocked at install. See [Depend on a plugin from another marketplace](</docs/en/plugin-dependencies#depend-on-a-plugin-from-another-marketplace>). +`renames`| object| Map from a former plugin `name` to its current name, or to `null` if the plugin was removed. Lets existing users migrate automatically when you rename or remove an entry in `plugins`. See Rename or remove a plugin. Requires Claude Code v2.1.193 or later. `description` and `version` are also accepted under `metadata` for backward compatibility. @@ -583,8 +583,8 @@ Test your marketplace locally before sharing: - /plugin marketplace add ./my-local-marketplace - /plugin install test-plugin@my-local-marketplace + /plugin marketplace add ./my-marketplace + /plugin install quality-review-plugin@my-plugins For the full range of add commands (GitHub, Git URLs, local paths, remote URLs), see [Add marketplaces](</docs/en/discover-plugins#add-marketplaces>). @@ -652,7 +652,7 @@ Managed marketplace restrictions -For organizations requiring strict control over plugin sources, administrators can restrict which plugin marketplaces users are allowed to add using the [`strictKnownMarketplaces`](</docs/en/settings#strictknownmarketplaces>) setting in managed settings. When `strictKnownMarketplaces` is configured in managed settings, the restriction behavior depends on the value: +For organizations requiring strict control over plugin sources, administrators can restrict which plugin marketplaces users are allowed to add using the [`strictKnownMarketplaces`](</docs/en/settings#strictknownmarketplaces>) setting in managed settings. To also reject the CLI flags that sideload plugins, agents, and MCP servers for a single run, pair it with [`disableSideloadFlags`](</docs/en/settings#available-settings>). When `strictKnownMarketplaces` is configured in managed settings, the restriction behavior depends on the value: Value| Behavior ---|--- @@ -825,6 +825,38 @@ A plugin can constrain its dependencies to a semver range so that updates to a dependency don’t break the dependent plugin. See [Constrain plugin dependency versions](</docs/en/plugin-dependencies>) for the `{plugin-name}--v{version}` git-tag convention, range syntax, and how multiple constraints on the same dependency are combined. +### + +​ + +Rename or remove a plugin + +A plugin’s `name` is its stable identifier. Users reference it in `enabledPlugins`, `pluginConfigs`, and `/plugin install` commands, so changing it breaks every existing install. To change the label shown in the UI without breaking installs, set `displayName` and keep `name` unchanged. If you must change a plugin’s `name`, or you remove a plugin from the `plugins` array, add a top-level `renames` entry so existing users migrate instead of seeing a `plugin-not-found` error. Automatic migration requires Claude Code v2.1.193 or later. Map each former name to its current name, or to `null` if the plugin no longer exists. The following example renames `formatter` to `code-formatter` and records that `legacy-linter` was removed: + + { + "name": "acme-tools", + "owner": { "name": "Acme" }, + "plugins": [ + { "name": "code-formatter", "source": "./plugins/code-formatter" } + ], + "renames": { + "formatter": "code-formatter", + "legacy-linter": null + } + } + +When a user starts Claude Code with the old name still in their settings, Claude Code follows the `renames` map: + + * If the entry points to a new name, Claude Code loads the plugin under its new name and shows a one-line notice such as `Renamed to "code-formatter" in the "acme-tools" marketplace`. It then rewrites the old key to the new key in the user, project, and local settings scopes for both `enabledPlugins` and `pluginConfigs`, so the notice appears once. + * For a `null` entry, Claude Code drops the old key and the notice reports that the plugin was removed from the marketplace. + * If the renamed plugin uses a remote source such as `github` or `npm`, Claude Code reports `plugin-cache-miss` after the rename and the user must run `/plugin install` once to fetch it under the new name. + +Treat `renames` as append-only history: keep old entries in place even after you expect every user to have migrated. Claude Code follows chains, so if you later rename `code-formatter` to `formatter-pro`, add a second entry rather than editing the first. A user who still has the original `formatter` enabled then resolves through both entries to `formatter-pro`. Run `claude plugin validate .` after editing the map; it rejects any entry whose chain forms a cycle or doesn’t terminate at `null` or a name listed in `plugins`. + +Managed and policy settings are read-only to Claude Code, so plugins enabled there can’t be rewritten automatically. The renamed plugin still loads each session, but the rename notice recurs until an administrator updates `enabledPlugins` in the managed settings file to use the new name. The same applies to plugins enabled through other read-only sources such as `--add-dir`. + +Earlier versions of Claude Code ignore the `renames` field and report `plugin-not-found` for the old name. + ## ​ @@ -871,7 +903,7 @@ * `<source>`: GitHub `owner/repo` shorthand, git URL, remote URL to a `marketplace.json` file, or local directory path. To pin to a branch or tag, append `@ref` to the GitHub shorthand or `#ref` to a git URL -**Options:** +A URL must include its scheme. As of Claude Code v2.1.196, a host typed without one, such as `gitlab.example.com/team/plugins`, is rejected as an invalid `owner/repo` shorthand and the error tells you to add `https://` or use `./` for a local path. Earlier versions misread it as a GitHub repository path and fail at clone time with a GitHub not-found error. **Options:** Option| Description| Default ---|---|--- @@ -987,7 +1019,13 @@ Marketplace validation errors -Run `claude plugin validate .` or `/plugin validate .` from your marketplace directory to check for issues. When pointed at a marketplace directory, the validator checks `marketplace.json` only: schema, duplicate plugin names, source path traversal, and version mismatches against each referenced `plugin.json`. To validate an individual plugin’s `plugin.json` and its skill, agent, command, and hook files, run the command against the plugin directory itself, for example `claude plugin validate ./plugins/my-plugin`. Common errors: +Run `claude plugin validate .` or `/plugin validate .` from your marketplace directory to check for issues. When pointed at a marketplace directory, the validator checks `marketplace.json` for schema errors, duplicate plugin names, and source path traversal. For each entry whose `source` is a local path, it also validates that plugin’s own `plugin.json` and warns when the entry’s `version` doesn’t match the one in `plugin.json`. Problems found in a plugin’s `plugin.json` are prefixed with the entry index, in the form `plugins[2] plugin.json →`. As of Claude Code v2.1.196, the per-entry pass also: + + * includes plugins whose `source` is `.` + * runs when `marketplace.json` is outside a `.claude-plugin` directory, resolving sources against the file’s own directory + * reports each entry’s problems even when another part of the file has schema errors + +Earlier versions skip plugins at the marketplace root and only descend from a `.claude-plugin/marketplace.json`. To validate an individual plugin’s `plugin.json` and its skill, agent, command, and hook files, run the command against the plugin directory itself, for example `claude plugin validate ./plugins/my-plugin`. Common errors: Error| Cause| Solution ---|---|---
modified Plugins reference View current →
--- a/plugins-reference.md +++ b/plugins-reference.md @@ -418,7 +418,7 @@ Field| Type| Description| Example ---|---|---|--- -`name`| string| Unique identifier (kebab-case, no spaces)| `"deployment-tools"` +`name`| string| Unique identifier (kebab-case, no spaces). When a [marketplace entry](</docs/en/plugin-marketplaces#plugin-entries>) lists the plugin under a different name, the marketplace entry name is what `enabledPlugins` keys and `/plugin` use| `"deployment-tools"` This name is used for namespacing components. For example, in the UI, the agent `agent-creator` for the plugin with name `plugin-dev` will appear as `plugin-dev:agent-creator`.
modified Agent SDK reference - Python View current →
--- a/python.md +++ b/python.md @@ -898,6 +898,7 @@ fork_session: bool = False agents: dict[str, AgentDefinition] | None = None setting_sources: list[SettingSource] | None = None + skills: list[str] | Literal["all"] | None = None sandbox: SandboxSettings | None = None plugins: list[SdkPluginConfig] = field(default_factory=list) max_thinking_tokens: int | None = None # Deprecated: use thinking instead @@ -971,7 +972,7 @@ * `API_TIMEOUT_MS`: per-request timeout on the Anthropic client, in milliseconds. Default `600000`. Applies to the main loop and all subagents. * `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff. For unattended runs that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG=1` to retry capacity errors indefinitely. * `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents launched with `run_in_background`. Default `600000`. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents. - * `CLAUDE_ENABLE_STREAM_WATCHDOG=1` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. When `CLAUDE_ENABLE_STREAM_WATCHDOG` is unset, the default is server-controlled on the direct Anthropic API and off on other providers. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. The aborted request goes through the normal retry path. + * `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. The aborted request goes through the normal retry path. ### @@ -1208,7 +1209,7 @@ "low", # Minimal thinking, fastest responses "medium", # Moderate thinking "high", # Deep reasoning - "xhigh", # Extended reasoning (Opus 4.8 and Opus 4.7; falls back to "high" on other models) + "xhigh", # Extended reasoning; falls back to "high" on models that don't support it "max", # Maximum effort ] @@ -2645,10 +2646,11 @@ Monitor -**Tool name:** `Monitor` Runs a background script and delivers each stdout line to Claude as an event so it can react without polling. Monitor follows the same permission rules as Bash. See the [Monitor tool reference](</docs/en/tools-reference#monitor-tool>) for behavior and provider availability. **Input:** - - { - "command": str, # Shell script; each stdout line is an event, exit ends the watch +**Tool name:** `Monitor` Runs a background source and delivers each event to Claude so it can react without polling: `command` runs a script and emits one event per stdout line, and `ws` opens a WebSocket and emits one event per text frame. Provide exactly one of `command` or `ws`. When Monitor runs a command, it follows the same permission rules as Bash; a WebSocket watch prompts for approval separately. The `ws` source requires Claude Code v2.1.195 or later. See the [Monitor tool reference](</docs/en/tools-reference#monitor-tool>) for behavior and provider availability. **Input:** + + { + "command": str | None, # Shell script; each stdout line is an event, exit ends the watch + "ws": dict | None, # WebSocket source: {"url": str, "protocols": list[str] | None}; each text frame is an event "description": str, # Short description shown in notifications "timeout_ms": int | None, # Kill after this deadline (default 300000, max 3600000) "persistent": bool | None, # Run for the lifetime of the session; stop with TaskStop
modified Quickstart View current →
--- a/quickstart.md +++ b/quickstart.md @@ -76,6 +76,7 @@ * [Claude Pro, Max, Team, or Enterprise](<https://claude.com/pricing?utm_source=claude_code&utm_medium=docs&utm_content=quickstart_login>) (recommended) * [Claude Console](<https://console.anthropic.com/>) (API access with pre-paid credits). On first login, a “Claude Code” workspace is automatically created in the Console for centralized cost tracking. * [Amazon Bedrock, Google Vertex AI, or Microsoft Foundry](</docs/en/third-party-integrations>) (enterprise cloud providers) + * A self-hosted [Claude apps gateway](</docs/en/claude-apps-gateway>), if your organization runs one: your admin pre-configures the gateway URL, and `/login` opens directly on the **Cloud gateway** screen for you to sign in with corporate SSO Once logged in, your credentials are stored and you won’t need to log in again.
modified Continue local sessions from any device with Remote Control View current →
--- a/remote-control.md +++ b/remote-control.md @@ -22,6 +22,7 @@ * **Subscription** : available on Pro, Max, Team, and Enterprise plans. API keys are not supported. On Team and Enterprise, an Owner must first enable the Remote Control toggle in [Claude Code admin settings](<https://claude.ai/admin-settings/claude-code>). * **Authentication** : run `claude` and use `/login` to sign in through claude.ai if you haven’t already. + * **API endpoint** : not available on Amazon Bedrock, Google Vertex AI, or Microsoft Foundry. As of v2.1.196, Remote Control is also disabled when [`ANTHROPIC_BASE_URL`](</docs/en/env-vars>) points at a host other than `api.anthropic.com`, such as an [LLM gateway](</docs/en/llm-gateway>) or proxy. Unset the variable to use Remote Control. * **Workspace trust** : run `claude` in your project directory at least once to accept the workspace trust dialog. ## @@ -120,7 +121,7 @@ Enable Remote Control for all sessions -By default, Remote Control only activates when you explicitly run `claude remote-control`, `claude --remote-control`, or `/remote-control`. To enable it automatically for every interactive session, run `/config` inside Claude Code and set **Enable Remote Control for all sessions** to `true`. Set it back to `false` to disable. In the Desktop app, you can also toggle this from **Settings → Claude Code → Enable remote control by default**. With this setting on, each interactive Claude Code process registers one remote session. If you run multiple instances, each one gets its own environment and session. To run multiple concurrent sessions from a single process, use server mode instead. +Remote Control only activates when you explicitly run `claude remote-control`, `claude --remote-control`, or `/remote-control`, unless auto-connect is turned on. To enable it automatically for every interactive session, run `/config` inside Claude Code and set **Enable Remote Control for all sessions** to `true`. Set it to `false` to never auto-connect, or leave it unset to follow your organization’s default. In the Desktop app, you can also toggle this from **Settings → Claude Code → Enable remote control by default**. With this setting on, each interactive Claude Code process registers one remote session. If you run multiple instances, each one gets its own environment and session. To run multiple concurrent sessions from a single process, use server mode instead. ## @@ -310,6 +311,14 @@ ​ +”Remote Control is only available when using Claude via api.anthropic.com” + +The session isn’t talking to the Anthropic API directly, so there is no claude.ai backend to pair with. This happens on Amazon Bedrock, Google Vertex AI, and Microsoft Foundry. As of v2.1.196 it also happens when [`ANTHROPIC_BASE_URL`](</docs/en/env-vars>) points at a host other than `api.anthropic.com`, such as an [LLM gateway](</docs/en/llm-gateway>) or proxy, even if you sign in with claude.ai. Unset `ANTHROPIC_BASE_URL` and restart the session to use Remote Control. + +### + +​ + ”Remote Control is disabled by your organization’s policy” This error has four distinct causes. Run `/status` first to see which login method and subscription you’re using.
modified Run prompts on a schedule View current →
--- a/scheduled-tasks.md +++ b/scheduled-tasks.md @@ -38,7 +38,12 @@ Prompt only| `/loop check the deploy`| Your prompt runs at an interval Claude chooses each iteration Interval only, or nothing| `/loop`| The built-in maintenance prompt runs, or your `loop.md` if one exists -You can also pass another command as the prompt, for example `/loop 20m /review-pr 1234`, to re-run a saved skill or command each iteration. +You can also pass a skill as the prompt, for example `/loop 20m /review-pr 1234`, to re-run that skill each iteration. As of v2.1.196, a scheduled fire only runs skills that Claude is [allowed to invoke on its own](</docs/en/skills#control-who-invokes-a-skill>). The following reach Claude as plain text instead of executing: + + * built-in commands such as `/permissions`, `/model`, or `/clear` + * skills marked [`disable-model-invocation: true`](</docs/en/skills#frontmatter-reference>) + * skills withheld from Claude by a [`skillOverrides`](</docs/en/skills#override-skill-visibility-from-settings>) setting or a `Skill` [deny rule](</docs/en/skills#restrict-claude%E2%80%99s-skill-access>) + * [MCP prompts](</docs/en/mcp#use-mcp-prompts-as-commands>) such as `/mcp__github__list_prs`; skills an MCP server exposes still run ### @@ -220,7 +225,7 @@ Session-scoped scheduling has inherent constraints: - * Tasks only fire while Claude Code is running and idle. Closing the terminal or letting the session exit stops them firing. + * Tasks only fire while Claude Code is running and idle. Closing the terminal or letting the session exit stops them firing. [Backgrounding the session](</docs/en/agent-view#from-inside-a-session>) carries `/loop` tasks over to a background session, which keeps running without a terminal. * No catch-up for missed fires. If a task’s scheduled time passes while Claude is busy on a long-running request, it fires once when Claude becomes idle, not once per missed interval. * Starting a fresh conversation clears all session-scoped tasks. Resuming with `claude --resume` or `claude --continue` restores tasks that have not expired: recurring tasks within seven days of creation, and one-shot tasks whose scheduled time has not yet passed. Background Bash and monitor tasks are never restored on resume.
modified Configure server-managed settings View current →
--- a/server-managed-settings.md +++ b/server-managed-settings.md @@ -149,7 +149,7 @@ Settings precedence -Server-managed settings and [endpoint-managed settings](</docs/en/settings#settings-files>) both occupy the highest tier in the Claude Code [settings hierarchy](</docs/en/settings#settings-precedence>). No other settings level can override them, including command line arguments. Within the managed tier, the first source that delivers a non-empty configuration wins. Server-managed settings are checked first, then endpoint-managed settings. Sources do not merge: if server-managed settings deliver any keys at all, endpoint-managed settings are ignored entirely. If server-managed settings deliver nothing, endpoint-managed settings apply. If you clear your server-managed configuration in the admin console with the intent of falling back to an endpoint-managed plist or registry policy, be aware that cached settings persist on client machines until the next successful fetch. Run `/status` to see which managed source is active. +Server-managed settings and [endpoint-managed settings](</docs/en/settings#settings-files>) both occupy the highest tier in the Claude Code [settings hierarchy](</docs/en/settings#settings-precedence>). No other settings level can override them, including command line arguments. Within the managed tier, a configured [`policyHelper`](</docs/en/settings#compute-managed-settings-with-a-policy-helper>) preempts every other managed source, including server-managed settings: its output becomes the only managed configuration for the run. Otherwise the first source that delivers a non-empty configuration wins. Server-managed settings are checked first, then endpoint-managed settings. Sources do not merge: if server-managed settings deliver any keys at all, other endpoint-managed settings are ignored. One exception applies: a small set of [cross-source lock keys](</docs/en/settings#settings-precedence>), such as the sandbox allowlist locks, is honored when any admin-controlled managed source sets them; the user-writable HKCU registry tier is excluded. If server-managed settings deliver nothing, endpoint-managed settings apply. If you clear your server-managed configuration in the admin console with the intent of falling back to an endpoint-managed plist or registry policy, be aware that cached settings persist on client machines until the next successful fetch. Run `/status` to see which managed source is active. ### @@ -210,6 +210,7 @@ * **Shell command settings** : settings that execute shell commands * **Custom environment variables** : variables not in the known safe allowlist * **Hook configurations** : any hook definition + * **Managed CLAUDE.md content** : a `claudeMd` value delivered through managed settings When these settings are present, users see a security dialog explaining what is being configured. Users must approve to proceed. If a user rejects the settings, Claude Code exits. @@ -227,7 +228,9 @@ * Google Vertex AI * Microsoft Foundry * [Claude Platform on AWS](</docs/en/claude-platform-on-aws>) - * Custom API endpoints via `ANTHROPIC_BASE_URL` or [LLM gateways](</docs/en/llm-gateway>) + * Custom API endpoints via `ANTHROPIC_BASE_URL` or third-party [LLM gateways](</docs/en/llm-gateway>) + +For Bedrock, Vertex AI, and Foundry deployments, a self-hosted [Claude apps gateway](</docs/en/claude-apps-gateway>) provides the equivalent remote managed-settings delivery: gateway-signed-in clients fetch managed settings from the gateway instead of `api.anthropic.com`. The failure semantics differ at startup: a gateway client that can’t reach the gateway exits with an error instead of falling back to cached settings, while the hourly background refresh is fail-open on both channels. ##
modified Persist sessions to external storage View current →
--- a/session-storage.md +++ b/session-storage.md @@ -179,7 +179,7 @@ Mirror writes are best-effort -If `append()` rejects or times out, the error is logged, a `{ type: "system", subtype: "mirror_error" }` message is emitted into the iterator, and the query continues. The local transcript is already durable on disk, so a store outage does not interrupt the agent or lose data locally. Batches that fail are not retried, so monitor for `mirror_error` if you need to detect store data loss. +If `append()` rejects, the SDK retries the batch up to two more times with a short backoff, for at most three attempts in total. A call that times out isn’t retried, since the original call may still land. If the batch still fails, the error is logged, a `{ type: "system", subtype: "mirror_error" }` message is emitted into the iterator, the batch is dropped, and the query continues. The local transcript is already durable on disk, so a store outage doesn’t interrupt the agent or lose data locally. Monitor for `mirror_error` if you need to detect store data loss. Because a retried batch can re-deliver entries that already landed, deduplicate by `entry.uuid` in your `append()` implementation. ###
modified Manage sessions View current →
--- a/sessions.md +++ b/sessions.md @@ -24,7 +24,7 @@ Where the session picker looks -Sessions 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`. From v2.1.169, moving a session with [`/cd`](</docs/en/commands>) relocates it to the new directory’s project storage, so it appears in that directory’s picker afterward. Use `Ctrl+W` to widen to all worktrees of the repository or `Ctrl+A` to widen to every project on this machine. Selecting a session from another worktree of the same repository resumes it in place. Selecting a session from an unrelated project copies a `cd` and resume command to your clipboard instead. Resuming by name resolves across the current repository and its worktrees. Both forms look for an exact match and resume it directly even if it lives in a different worktree: +Sessions 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. From v2.1.169, moving a session with [`/cd`](</docs/en/commands>) relocates it to the new directory’s project storage, so it appears in that directory’s picker afterward. As of v2.1.196, a moved session stays out of the old directory’s picker even after a crash or forced exit. On earlier versions, it could also reappear in the old directory’s list after an exit that wasn’t clean when the old path contained special characters such as underscores. Selecting a session from another worktree of the same repository resumes it in place. Selecting a session from an unrelated project copies a `cd` and resume command to your clipboard instead. Resuming by name resolves across the current repository and its worktrees. Both forms look for an exact match and resume it directly even if it lives in a different worktree: Command| Exact match| Ambiguous name ---|---|--- @@ -46,7 +46,7 @@ From the session picker| Highlight a session and press `Ctrl+R` On plan accept| Accepting a plan in [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>) names the session from the plan content unless you’ve already set one -Once a session is named, return to it with `claude --resume <name>` or `/resume <name>`. See Resume a session for how name resolution behaves across worktrees. +Once a session is named, return to it with `claude --resume <name>` or `/resume <name>`. See Resume a session for how name resolution behaves across worktrees. Interactive sessions you never name still get a default display name when they start. Requires Claude Code v2.1.196 or later. The default combines the working directory’s name with a two-character suffix, for example `my-app-3f`, and identifies the session in listings of running sessions, such as [agent view](</docs/en/agent-view>) and `claude agents --json` output. The default isn’t a resume handle: `claude --resume <name>`, `/resume <name>`, and the session picker match only names you set. Naming the session replaces the default. ## @@ -107,7 +107,7 @@ Export and locate session data -Run `/export` to copy the current conversation to your clipboard or save it as a plain-text file, with messages and tool outputs rendered as readable text. Pass a filename to write directly to that file. +Run `/export` to open a menu that lets you copy the current conversation to your clipboard or save it as a plain-text file, with messages and tool outputs rendered as readable text. Pass a filename to skip the menu and write directly to that file. ###
modified Claude Code settings View current →
Show diff (131 lines)
--- a/settings.md +++ b/settings.md @@ -100,7 +100,7 @@ * `.claude/settings.json` for settings that are checked into source control and shared with your team * `.claude/settings.local.json` for settings that are not checked in, useful for personal preferences and experimentation. When Claude Code creates `.claude/settings.local.json`, it configures git to ignore the file. If you create the file yourself, add it to your gitignore manually. * **Managed settings** : For organizations that need centralized control, Claude Code supports multiple delivery mechanisms for managed settings. All use the same JSON format and cannot be overridden by user or project settings: - * **Server-managed settings** : delivered from Anthropic’s servers via the Claude.ai admin console. See [server-managed settings](</docs/en/server-managed-settings>). + * **Server-managed settings** : delivered remotely at sign-in, either from Anthropic’s servers via the claude.ai admin console or from a self-hosted [Claude apps gateway](</docs/en/claude-apps-gateway>). See [server-managed settings](</docs/en/server-managed-settings>). * **MDM/OS-level policies** : delivered through native device management on macOS and Windows: * macOS: `com.anthropic.claudecode` managed preferences domain. The plist’s top-level keys mirror `managed-settings.json`, with nested settings as dictionaries and arrays as plist arrays. Deploy via configuration profiles in Jamf, Iru (Kandji), or similar MDM tools. * Windows: `HKLM\SOFTWARE\Policies\ClaudeCode` registry key with a `Settings` value (REG_SZ or REG_EXPAND_SZ) containing JSON (deployed via Group Policy or Intune) @@ -215,6 +215,7 @@ `autoMemoryDirectory`| Custom directory for [auto memory](</docs/en/memory#storage-location>) storage. Accepts an absolute path or a `~/`-prefixed path. From project or local settings, this is honored only after you accept the workspace trust dialog, since a cloned repository can supply this file| `"~/my-memory-dir"` `autoMemoryEnabled`| **Default** : `true`. Enable [auto memory](</docs/en/memory#enable-or-disable-auto-memory>). When `false`, Claude does not read from or write to the auto memory directory. You can also toggle this with `/memory` during a session. To disable via environment variable, set [`CLAUDE_CODE_DISABLE_AUTO_MEMORY`](</docs/en/env-vars>) in `env`| `false` `autoMode`| Customize what the [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) classifier blocks and allows. Contains `environment`, `allow`, `soft_deny`, and `hard_deny` arrays of prose rules. Include the literal string `"$defaults"` in an array to inherit the built-in rules at that position. See [Configure auto mode](</docs/en/auto-mode-config>). Not read from shared project settings| `{"soft_deny": ["$defaults", "Never run terraform apply"]}` +`autoMode.classifyAllShell`| **Default** : `false`. When `true`, suspends every Bash and PowerShell allow rule while auto mode is active so all shell commands route through the classifier, not only rules that match arbitrary-code-execution patterns. See [Route all shell commands through the classifier](</docs/en/auto-mode-config#route-all-shell-commands-through-the-classifier>). Requires Claude Code v2.1.193 or later| `true` `autoScrollEnabled`| **Default** : `true`. In [fullscreen rendering](</docs/en/fullscreen>), follow new output to the bottom of the conversation. Appears in `/config` as **Auto-scroll**. Permission prompts still scroll into view when this is off| `false` `autoUpdatesChannel`| **Default** : `"latest"`. Release channel to follow for updates. Use `"stable"` for a version that is typically about one week old and skips versions with major regressions, or `"latest"` for the most recent release. To disable auto-updates entirely, set [`DISABLE_AUTOUPDATER`](</docs/en/setup#disable-auto-updates>) in `env`| `"stable"` `availableModels`| Restrict which models users can select for the main session, [subagents](</docs/en/sub-agents>), [skills](</docs/en/skills>), and the [advisor](</docs/en/advisor>). Does not affect the Default option unless `enforceAvailableModels` is also set. See [Restrict model selection](</docs/en/model-config#restrict-model-selection>)| `["sonnet", "haiku"]` @@ -239,21 +240,24 @@ `disableDeepLinkRegistration`| Set to `"disable"` to prevent Claude Code from registering the `claude-cli://` protocol handler with the operating system on startup. [Deep links](</docs/en/deep-links>) let external tools open a Claude Code session with a pre-filled prompt. Useful in environments where protocol handler registration is restricted or managed separately| `"disable"` `disabledMcpjsonServers`| List of specific MCP servers from `.mcp.json` files to reject| `["filesystem"]` `disableRemoteControl`| Disable [Remote Control](</docs/en/remote-control>): blocks `claude remote-control`, the `--remote-control` flag, auto-start, and the in-session toggle. Typically placed in [managed settings](</docs/en/permissions#managed-settings>) for per-device MDM enforcement, but works from any scope. Requires Claude Code v2.1.128 or later| `true` +`disableSideloadFlags`| (Managed settings only) Reject the `--plugin-dir`, `--plugin-url`, `--agents`, and `--mcp-config` CLI flags at startup, which users could otherwise pass to bypass `strictKnownMarketplaces` for a single run. Also rejects these flags from any surface that spawns the CLI with them internally, currently [Cowork](</docs/en/desktop>) local sessions in the desktop app. A `--mcp-config` whose servers are all in-process `type: "sdk"` entries is still accepted, so the Agent SDK and VS Code extension keep working. Doesn’t block `claude mcp add`, `.mcp.json`, or SDK `setMcpServers()`; pair with [`allowedMcpServers`](</docs/en/managed-mcp>) for per-server MCP control. Requires Claude Code v2.1.193 or later| `true` `disableSkillShellExecution`| Disable inline shell execution for `!`...`` and ````!` blocks in [skills](</docs/en/skills>) and custom commands from user, project, plugin, or additional-directory sources. Commands are replaced with `[shell command execution disabled by policy]` instead of being run. Bundled and managed skills are not affected. Most useful in [managed settings](</docs/en/permissions#managed-settings>) where users cannot override it| `true` `disableWorkflows`| **Default** : `false`. Disable [dynamic workflows](</docs/en/workflows#turn-workflows-off>) and the bundled workflow commands. Equivalent to setting `CLAUDE_CODE_DISABLE_WORKFLOWS` to `1`| `true` `editorMode`| **Default** : `"normal"`. Key binding mode for the input prompt: `"normal"` or `"vim"`. Appears in `/config` as **Editor mode**| `"vim"` `effortLevel`| Persist the [effort level](</docs/en/model-config#adjust-effort-level>) across sessions. Accepts `"low"`, `"medium"`, `"high"`, or `"xhigh"`. Written automatically when you run `/effort` with one of those values. `--effort` and [`CLAUDE_CODE_EFFORT_LEVEL`](</docs/en/env-vars>) override this for one session. See [Adjust effort level](</docs/en/model-config#adjust-effort-level>) for supported models| `"xhigh"` -`enableAllProjectMcpServers`| Automatically approve all MCP servers defined in project `.mcp.json` files| `true` -`enabledMcpjsonServers`| List of specific MCP servers from `.mcp.json` files to approve| `["memory", "github"]` +`enableAllProjectMcpServers`| Automatically approve all MCP servers defined in project `.mcp.json` files. As of v2.1.196, `claude mcp list` and `claude mcp get` honor this key in an untrusted folder only from [settings files that aren’t checked into the repository](</docs/en/mcp#managing-your-servers>)| `true` +`enableArtifact`| Enable or disable the [Artifact](</docs/en/artifacts>) tool for this user. When unset, the default follows the feature’s [availability](</docs/en/artifacts#availability>) for your account. The **Artifacts** row in `/config` writes this key. A managed `disableArtifact` and your organization’s [admin setting](</docs/en/artifacts#manage-artifacts-for-your-organization>) take precedence, and the key is ignored in project and local settings (`.claude/settings.json`, `.claude/settings.local.json`), which a repository could otherwise commit. Requires Claude Code v2.1.196 or later| `true` +`enabledMcpjsonServers`| List of specific MCP servers from `.mcp.json` files to approve. As of v2.1.196, `claude mcp list` and `claude mcp get` honor this key in an untrusted folder only from [settings files that aren’t checked into the repository](</docs/en/mcp#managing-your-servers>)| `["memory", "github"]` `enforceAvailableModels`| Extend the `availableModels` allowlist to the Default model. When `true` in managed settings and `availableModels` is a non-empty array, the Default option falls back to the first allowlisted entry that is available. Has no effect when `availableModels` is unset or empty. See [Enforce the allowlist for the Default model](</docs/en/model-config#enforce-the-allowlist-for-the-default-model>). Requires Claude Code v2.1.175 or later| `true` -`env`| Environment variables applied to every session and to subprocesses Claude Code spawns from it. As of v2.1.143, `NO_COLOR` and `FORCE_COLOR` set here are passed to subprocesses but do not change Claude Code’s own interface colors. Set those in your shell before launching `claude` to change interface colors| `{"FOO": "bar"}` +`env`| Environment variables applied to every session and to subprocesses Claude Code spawns from it. As of v2.1.143, `NO_COLOR` and `FORCE_COLOR` set here are passed to subprocesses but do not change Claude Code’s own interface colors. Set those in your shell before launching `claude` to change interface colors. As of v2.1.195, identity variables that Claude Code’s hosting environments set, for example `CLAUDE_CODE_REMOTE` and `CLAUDE_CODE_ACCOUNT_UUID`, are ignored when set here| `{"FOO": "bar"}` `fallbackModel`| Fallback model(s) to try in order when the primary model is overloaded or unavailable. Claude Code switches to the next available model in the chain for the rest of the turn and shows a notice. `"default"` expands to the default model. Chains are capped at three models; extra entries are ignored. Unlike most array settings, this key does not merge across settings files: the highest-precedence file that defines it supplies the entire chain. The [`--fallback-model`](</docs/en/cli-reference#cli-flags>) flag overrides this for one session. See [Fallback model chains](</docs/en/model-config#fallback-model-chains>)| `["claude-sonnet-4-6", "claude-haiku-4-5"]` `fastModePerSessionOptIn`| When `true`, fast mode does not persist across sessions. Each session starts with fast mode off, requiring users to enable it with `/fast`. The user’s fast mode preference is still saved. See [Require per-session opt-in](</docs/en/fast-mode#require-per-session-opt-in>)| `true` `feedbackSurveyRate`| Probability (0–1) that the [session quality survey](</docs/en/data-usage#session-quality-surveys>) appears when eligible. Set to `0` to suppress entirely, or set [`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY`](</docs/en/env-vars>) in `env`. Useful when using Bedrock, Vertex, or Foundry where the default sample rate does not apply| `0.05` `fileCheckpointingEnabled`| **Default** : `true`. Snapshot files before each edit so [`/rewind`](</docs/en/checkpointing>) can restore them. Appears in `/config` as **Rewind code (checkpoints)**. To disable via environment variable, set [`CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING`](</docs/en/env-vars>) in `env`| `false` `fileSuggestion`| Configure a custom script for `@` file autocomplete. See File suggestion settings| `{"type": "command", "command": "~/.claude/file-suggestion.sh"}` `footerLinksRegexes`| Render extra clickable badges in the footer when a regex matches turn output. Each entry has a `pattern`, a `url` template with `{name}` placeholders filled from named capture groups, and an optional `label`. Read from user, `--settings` flag, and managed settings only. See Footer link badges for URL constraints, scheme allowlist, and limits. Requires Claude Code v2.1.176 or later| `[{"type": "regex", "pattern": "\\b(?<key>PROJ-\\d+)\\b", "url": "https://issues.example.com/browse/{key}", "label": "{key}"}]` -`forceLoginMethod`| Use `claudeai` to restrict login to Claude.ai accounts, `console` to restrict login to Claude Console accounts. When set in managed settings, sessions authenticated by `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or `apiKeyHelper` are blocked at startup, since neither value can be satisfied without first-party OAuth. Third-party provider sessions such as Bedrock, Vertex, and Foundry are not blocked: they authenticate against your cloud provider rather than Anthropic| `claudeai` +`forceLoginMethod`| Use `claudeai` to restrict login to Claude.ai accounts, `console` to restrict login to Claude Console accounts, or `gateway` to restrict login to a cloud gateway; see [Claude apps gateway](</docs/en/claude-apps-gateway>). When set to any value in managed settings, sessions authenticated by `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or `apiKeyHelper` are blocked at startup, since an environment credential cannot satisfy the required login method. Third-party provider sessions such as Bedrock, Vertex, and Foundry are not blocked: they authenticate against your cloud provider rather than Anthropic| `claudeai` +`forceLoginGatewayUrl`| Pre-fills and locks the gateway URL on the `/login` Cloud gateway screen. Either this key or `forceLoginMethod: "gateway"` surfaces that screen; set both so the URL is filled in. Honored only at the managed policy tier; ignored in user and project settings. See [Claude apps gateway](</docs/en/claude-apps-gateway#set-the-gateway-url>)| `"https://claude-gateway.example.com"` `forceLoginOrgUUID`| Require login to belong to a specific Anthropic organization. Accepts a single UUID string, which also pre-selects that organization during login, or an array of UUIDs where any listed organization is accepted without pre-selection. When set in managed settings, login fails if the authenticated account does not belong to a listed organization, and sessions authenticated by `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or `apiKeyHelper` are blocked at startup since organization membership cannot be verified for them. Third-party provider sessions such as Bedrock, Vertex, and Foundry are not blocked: use your cloud IAM to restrict which cloud accounts can be used. An empty array fails closed and blocks login with a misconfiguration message| `"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"` or `["xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy"]` `forceRemoteSettingsRefresh`| (Managed settings only) Block CLI startup until remote managed settings are freshly fetched from the server. If the fetch fails, the CLI exits rather than continuing with cached or no settings. When not set, startup continues without waiting for remote settings. See [fail-closed enforcement](</docs/en/server-managed-settings#enforce-fail-closed-startup>)| `true` `gcpAuthRefresh`| Custom script that refreshes GCP Application Default Credentials when they expire or cannot be loaded. See [advanced credential configuration](</docs/en/google-vertex-ai#advanced-credential-configuration>)| `gcloud auth application-default login` @@ -262,7 +266,6 @@ `includeGitInstructions`| **Default** : `true`. Include built-in commit and PR workflow instructions and the git status snapshot in Claude’s system prompt. Set to `false` to remove both, for example when using your own git workflow skills. The `CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS` environment variable takes precedence over this setting when set| `false` `inputNeededNotifEnabled`| **Default** : `false`. When [Remote Control](</docs/en/remote-control>) is connected, send a push notification to your phone when a permission prompt or question is waiting for your input. Appears in `/config` as **Push when actions required**. See [Mobile push notifications](</docs/en/remote-control#mobile-push-notifications>). Requires Claude Code v2.1.119 or later| `true` `language`| Configure Claude’s preferred response language (e.g., `"japanese"`, `"spanish"`, `"french"`). Claude will respond in this language by default. Also sets the language for [voice dictation](</docs/en/voice-dictation#change-the-dictation-language>) and auto-generated session titles. As of v2.1.176, when not set, session titles match the language of your conversation| `"japanese"` -`maxSkillDescriptionChars`| **Default** : `1536`. Per-skill character cap on the combined `description` and `when_to_use` text in the [skill listing](</docs/en/skills#skill-descriptions-are-cut-short>) Claude sees each turn. Text longer than this is truncated. Raise to keep long descriptions intact at the cost of more context per turn; lower to fit more skills under `skillListingBudgetFraction`. Requires Claude Code v2.1.105 or later| `2048` `minimumVersion`| Floor that prevents background auto-updates and `claude update` from installing a version below this one. Switching from the `"latest"` channel to `"stable"` via `/config` prompts you to stay on the current version or allow the downgrade. Choosing to stay sets this value. Also useful in [managed settings](</docs/en/permissions#managed-settings>) to pin an organization-wide minimum. For a hard floor that blocks startup entirely, see `requiredMinimumVersion`| `"2.1.100"` `model`| Override the default model to use for Claude Code. `--model` and [`ANTHROPIC_MODEL`](</docs/en/model-config#environment-variables>) override this for one session| `"claude-sonnet-4-6"` `modelOverrides`| Map Anthropic model IDs to provider-specific model IDs such as Bedrock inference profile ARNs. Each model picker entry uses its mapped value when calling the provider API. See [Override model IDs per version](</docs/en/model-config#override-model-ids-per-version>)| `{"claude-opus-4-6": "arn:aws:bedrock:..."}` @@ -286,17 +289,18 @@ `showThinkingSummaries`| **Default** : `false`. Show [extended thinking](</docs/en/model-config#extended-thinking>) summaries in interactive sessions. When unset or `false`, thinking blocks are redacted by the API and shown as a collapsed stub. Redaction only changes what you see, not what the model generates: to reduce thinking spend, [lower the budget or disable thinking](</docs/en/model-config#extended-thinking>) instead. This setting has no effect in non-interactive mode (`-p`), the Agent SDK, or IDE extensions such as VS Code| `true` `showTurnDuration`| **Default** : `true`. Show turn duration messages after responses, e.g. “Cooked for 1m 6s”. Appears in `/config` as **Show turn duration**| `false` `skillListingBudgetFraction`| **Default** : `0.01` (1%). Fraction of the model’s context window reserved for the [skill listing](</docs/en/skills#skill-descriptions-are-cut-short>) Claude sees each turn. When the listing exceeds the budget, descriptions for the least-used skills are collapsed to bare names so Claude can still invoke them but won’t see why. Raise to keep more descriptions visible at the cost of more context per turn. `/doctor` shows the current truncation count and which skills are affected. Requires Claude Code v2.1.105 or later| `0.02` +`skillListingMaxDescChars`| **Default** : `1536`. Per-skill character cap on the combined `description` and `when_to_use` text in the [skill listing](</docs/en/skills#skill-descriptions-are-cut-short>) Claude sees each turn. Text longer than this is truncated. Raise to keep long descriptions intact at the cost of more context per turn; lower to fit more skills under `skillListingBudgetFraction`. Requires Claude Code v2.1.105 or later| `2048` `skillOverrides`| Per-skill visibility overrides keyed by skill name. Value is `"on"`, `"name-only"`, `"user-invocable-only"`, or `"off"`. Lets you hide or collapse a skill without editing its SKILL.md. Does not apply to plugin skills, which are managed through `/plugin`. The `/skills` menu writes these to `.claude/settings.local.json`. See [Override skill visibility from settings](</docs/en/skills#override-skill-visibility-from-settings>). Requires Claude Code v2.1.129 or later| `{"legacy-context": "name-only", "deploy": "off"}` `skipWebFetchPreflight`| Skip the [WebFetch domain safety check](</docs/en/data-usage#webfetch-domain-safety-check>) that sends each requested hostname to `api.anthropic.com` before fetching. Set to `true` in environments that block traffic to Anthropic, such as Bedrock, Vertex AI, or Foundry deployments with restrictive egress. When skipped, WebFetch attempts any URL without consulting the blocklist| `true` `spinnerTipsEnabled`| **Default** : `true`. Show tips in the spinner while Claude is working. Set to `false` to disable tips| `false` `spinnerTipsOverride`| Override spinner tips with custom strings. `tips`: array of tip strings. `excludeDefault`: if `true`, only show custom tips; if `false` or absent, custom tips are merged with built-in tips| `{ "excludeDefault": true, "tips": ["Use our internal tool X"] }` `spinnerVerbs`| Customize the action verbs shown while a turn is in progress. Set `mode` to `"replace"` to use only your verbs, or `"append"` to add them to the defaults| `{"mode": "append", "verbs": ["Pondering", "Crafting"]}` `sshConfigs`| SSH connections to show in the [Desktop](</docs/en/desktop#pre-configure-ssh-connections-for-your-team>) environment dropdown. Each entry requires `id`, `name`, and `sshHost`; `sshPort`, `sshIdentityFile`, and `startDirectory` are optional. When set in managed settings, connections are read-only for users. Read from managed and user settings only| `[{"id": "dev-vm", "name": "Dev VM", "sshHost": "user@dev.example.com"}]` -`statusLine`| Configure a custom status line to display context. See [`statusLine` documentation](</docs/en/statusline>)| `{"type": "command", "command": "~/.claude/statusline.sh"}` +`statusLine`| Configure a custom status line to display context. The object’s optional `padding`, `refreshInterval`, and `hideVimModeIndicator` fields control spacing, periodic re-runs, and whether the built-in vim mode indicator below the prompt is hidden. See [`statusLine` documentation](</docs/en/statusline#manually-configure-a-status-line>)| `{"type": "command", "command": "~/.claude/statusline.sh"}` `strictKnownMarketplaces`| (Managed settings only) Allowlist of plugin marketplace sources. Undefined = no restrictions, empty array = lockdown. Enforced on marketplace add and on plugin install, update, refresh, and auto-update, so a marketplace added before the policy was set cannot be used to fetch plugins. See [Managed marketplace restrictions](</docs/en/plugin-marketplaces#managed-marketplace-restrictions>)| `[{ "source": "github", "repo": "acme-corp/plugins" }]` `strictPluginOnlyCustomization`| (Managed settings only) Block skills, agents, hooks, and MCP servers from user and project sources, so they can only come from plugins or managed settings. `true` locks all four surfaces; an array locks only the named ones. See `strictPluginOnlyCustomization`| `["skills", "hooks"]` `syntaxHighlightingDisabled`| Disable syntax highlighting in diffs, code blocks, and file previews| `true` -`teammateMode`| **Default** : `in-process`. How [agent team](</docs/en/agent-teams>) teammates display: `in-process`, `auto` (split panes when running inside tmux or iTerm2, in-process otherwise), `tmux` (split panes using tmux or iTerm2, detected from your terminal), or `iterm2` (iTerm2 native split panes via the `it2` CLI, added in v2.1.186). The default changed from `auto` in v2.1.179. `--teammate-mode` overrides this for one session. See [choose a display mode](</docs/en/agent-teams#choose-a-display-mode>)| `"auto"` +`teammateMode`| **Default** : `in-process`. How [agent team](</docs/en/agent-teams>) teammates display: `in-process`, `auto` (split panes when running inside tmux, or inside iTerm2 with `it2` on your `PATH`; in-process otherwise), `tmux` (split panes using tmux or iTerm2, detected from your terminal), or `iterm2` (iTerm2 native split panes via the `it2` CLI, added in v2.1.186). The default changed from `auto` in v2.1.179. `--teammate-mode` overrides this for one session. See [choose a display mode](</docs/en/agent-teams#choose-a-display-mode>)| `"auto"` `terminalProgressBarEnabled`| **Default** : `true`. Show the terminal progress bar in supported terminals: ConEmu, Ghostty 1.2.0+, and iTerm2 3.6.6+. Appears in `/config` as **Terminal progress bar**| `false` `theme`| **Default** : `"dark"`. Color theme for the interface: `"auto"`, `"dark"`, `"light"`, `"dark-daltonized"`, `"light-daltonized"`, `"dark-ansi"`, `"light-ansi"`, or a custom theme reference such as `"custom:<slug>"` or `"custom:<plugin-name>:<slug>"`. See [Create a custom theme](</docs/en/terminal-config#create-a-custom-theme>). Appears in `/config` as **Theme**| `"dark"` `tui`| Terminal UI renderer. Use `"fullscreen"` for the flicker-free [alt-screen renderer](</docs/en/fullscreen>) with virtualized scrollback. Use `"default"` for the classic main-screen renderer. Set via `/tui`. You can also set the [`CLAUDE_CODE_NO_FLICKER`](</docs/en/env-vars>) environment variable. Background sessions opened from [agent view](</docs/en/agent-view>) always use the fullscreen renderer regardless of this setting| `"fullscreen"` @@ -605,7 +609,7 @@ "appendSystemPrompt": "Always cite the internal style guide." } -When the helper emits `managedSettings`, that object replaces the file-based managed settings for the run. When the helper exits non-zero at startup, Claude Code prints the error and refuses to start, so a helper that needs outage resilience should serve from its own cache and exit `0`. +When the helper emits `managedSettings`, that object becomes the only managed settings source for the run, taking precedence over remote, MDM, and file-based sources. When the helper exits non-zero at startup, Claude Code prints the error and refuses to start, so a helper that needs outage resilience should serve from its own cache and exit `0`. ### @@ -618,7 +622,7 @@ 1. **Managed settings** ([server-managed](</docs/en/server-managed-settings>), MDM/OS-level policies, or [managed settings](</docs/en/settings#settings-files>)) * Policies deployed by IT through server delivery, MDM configuration profiles, registry policies, or managed settings files * Cannot be overridden by any other level, including command line arguments - * Within the managed tier, precedence is: server-managed > MDM/OS-level policies > file-based (`managed-settings.d/*.json` \+ `managed-settings.json`) > HKCU registry (Windows only). Only one managed source is used; sources do not merge across tiers. Within the file-based tier, drop-in files and the base file are merged together. + * Within the managed tier, precedence is: `policyHelper` output, which when configured is the only managed source used > remote (claude.ai [server-managed](</docs/en/server-managed-settings>) or [Claude apps gateway](</docs/en/claude-apps-gateway>)-delivered) > MDM/OS-level policies > file-based (`managed-settings.d/*.json` \+ `managed-settings.json`) > HKCU registry (Windows only). Only one managed source is used; sources do not merge across tiers, with one exception: the sandbox lock keys `sandbox.network.allowManagedDomainsOnly` and `sandbox.filesystem.allowManagedReadPathsOnly`, with their associated allowlists, `allowAllClaudeAiMcps`, and the sandbox binary paths `sandbox.bwrapPath` and `sandbox.socatPath` are honored when any admin-controlled managed source sets them; the user-writable HKCU tier is excluded. Within the file-based tier, drop-in files and the base file are merged together. * Embedding hosts such as Claude Desktop can supply policy via the SDK `managedSettings` option. By default this is ignored when an admin-deployed managed source is present: server-managed settings, an MDM or OS-level policy, or a managed settings file. The user-writable HKCU registry fallback does not count as an admin-deployed source. Administrators can opt in by setting `parentSettingsBehavior` to `"merge"`. The embedder’s values are filtered so they can tighten managed policy but not loosen it. 2. **Command line arguments** * Temporary overrides for a specific session. JSON passed via `--settings <file-or-json>` merges with file-based settings using the same rules as the other layers: a key set here overrides the same key in local, project, or user settings, and omitting a key leaves the lower-layer value in place @@ -642,7 +646,7 @@ Verify active settings -Run `/status` inside Claude Code to see which settings sources are active. Inside the menu, the **Status** tab includes a `Setting sources` line that lists each layer Claude Code loaded for the current session, such as `User settings` or `Project local settings`. When [managed settings](</docs/en/admin-setup#decide-how-settings-reach-devices>) are in effect, the entry shows the delivery channel in parentheses, for example `Enterprise managed settings (remote)`, `(plist)`, `(HKLM)`, `(HKCU)`, or `(file)`. A layer appears in the list only when that source is loaded with at least one key, so an empty list means no settings sources were found. The `Setting sources` line confirms which sources are being read. It does not show which layer supplied each individual key. The **Config** tab in the same dialog is an editor for a fixed set of toggles such as theme and verbose output, not a view of your `settings.json` contents. If a settings file contains errors, such as invalid JSON or a value that fails validation, `/status` lists the affected files. Run `/doctor` to see the details for each error. +Run `/status` inside Claude Code to see which settings sources are active. Inside the menu, the **Status** tab includes a `Setting sources` line that lists each layer Claude Code loaded for the current session, such as `User settings` or `Project local settings`. When [managed settings](</docs/en/admin-setup#decide-how-settings-reach-devices>) are in effect, the entry shows the delivery channel in parentheses, for example `Enterprise managed settings (remote)`, `(plist)`, `(HKLM)`, `(HKCU)`, or `(file)`. The `remote` channel covers both claude.ai server-managed settings and [Claude apps gateway](</docs/en/claude-apps-gateway>)-delivered policies. A layer appears in the list only when that source is loaded with at least one key, so an empty list means no settings sources were found. The `Setting sources` line confirms which sources are being read. It does not show which layer supplied each individual key. The **Config** tab in the same dialog is an editor for a fixed set of toggles such as theme and verbose output, not a view of your `settings.json` contents. If a settings file contains errors, such as invalid JSON or a value that fails validation, `/status` lists the affected files. Run `/doctor` to see the details for each error. ### @@ -745,7 +749,7 @@ * **Local settings** (`.claude/settings.local.json`): Per-machine overrides, gitignored when Claude Code creates it * **Managed settings** (`managed-settings.json`): Organization-wide policy overrides that block installation at all scopes and hide the plugin from the marketplace -Project settings take precedence over user settings, so setting a plugin to `false` in `~/.claude/settings.json` does not disable a plugin that the project’s `.claude/settings.json` enables. To opt out of a project-enabled plugin on your machine, set it to `false` in `.claude/settings.local.json` instead.Plugins force-enabled by managed settings cannot be disabled this way, since managed settings override local settings. +Project settings take precedence over user settings, so setting a plugin to `false` in `~/.claude/settings.json` does not disable a plugin that the project’s `.claude/settings.json` enables. To opt out of a project-enabled plugin on your machine, set it to `false` in `.claude/settings.local.json` instead.Plugins force-enabled by managed settings cannot be disabled this way, since managed settings override local settings.Enabling a plugin from an external source such as a GitHub repository or npm package in a project’s `.claude/settings.json` doesn’t install it for other people. As of Claude Code v2.1.195, every path that loads plugins asks each user to [install and trust the plugin](</docs/en/discover-plugins#configure-team-marketplaces>) before it runs. **Example** : @@ -852,7 +856,7 @@ { "source": "github", "repo": "acme-corp/security-tools", "ref": "v2.0" } { "source": "github", "repo": "acme-corp/plugins", "ref": "main", "path": "marketplace" } -Fields: `repo` (required), `ref` (optional: branch/tag/SHA), `path` (optional: subdirectory) +Fields: `repo` (required), `ref` (optional: branch or tag), `path` (optional: subdirectory) 2. **Git repositories** : @@ -860,7 +864,7 @@ { "source": "git", "url": "https://bitbucket.org/acme-corp/plugins.git", "ref": "production" } { "source": "git", "url": "ssh://git@git.example.com/plugins.git", "ref": "v3.1", "path": "approved" } -Fields: `url` (required), `ref` (optional: branch/tag/SHA), `path` (optional: subdirectory) +Fields: `url` (required), `ref` (optional: branch or tag), `path` (optional: subdirectory) 3. **URL-based marketplaces** :
modified Extend Claude with skills View current →
--- a/skills.md +++ b/skills.md @@ -217,7 +217,7 @@ `when_to_use`| No| Additional context for when Claude should invoke the skill, such as trigger phrases or example requests. Appended to `description` in the skill listing and counts toward the 1,536-character cap. `argument-hint`| No| Hint shown during autocomplete to indicate expected arguments. Example: `[issue-number]` or `[filename] [format]`. `arguments`| No| Named positional arguments for `$name` substitution in the skill content. Accepts a space-separated string or a YAML list. Names map to argument positions in order. -`disable-model-invocation`| No| Set to `true` to prevent Claude from automatically loading this skill. Use for workflows you want to trigger manually with `/name`. Also prevents the skill from being [preloaded into subagents](</docs/en/sub-agents#preload-skills-into-subagents>). Default: `false`. +`disable-model-invocation`| No| Set to `true` to prevent Claude from automatically loading this skill. Use for workflows you want to trigger manually with `/name`. Also prevents the skill from being [preloaded into subagents](</docs/en/sub-agents#preload-skills-into-subagents>). As of v2.1.196, also prevents the skill from running when a [scheduled task](</docs/en/scheduled-tasks>) fires with the skill as its prompt. Default: `false`. `user-invocable`| No| Set to `false` to hide from the `/` menu. Use for background knowledge users shouldn’t invoke directly. Default: `true`. `allowed-tools`| No| Tools Claude can use without asking permission when this skill is active. Accepts a space- or comma-separated string, or a YAML list. `disallowed-tools`| No| Tools removed from Claude’s available pool while this skill is active. Use for autonomous skills that should never call certain tools, such as `AskUserQuestion` for a background loop. Accepts a space- or comma-separated string, or a YAML list. The restriction clears when you send your next message. @@ -264,8 +264,9 @@ `${CLAUDE_SESSION_ID}`| The current session ID. Useful for logging, creating session-specific files, or correlating skill output with sessions. `${CLAUDE_EFFORT}`| The current effort level: `low`, `medium`, `high`, `xhigh`, or `max`. Ultracode is not a distinct level and reports as `xhigh`. Use this to adapt skill instructions to the active effort setting. `${CLAUDE_SKILL_DIR}`| The directory containing the skill’s `SKILL.md` file. For plugin skills, this is the skill’s subdirectory within the plugin, not the plugin root. Use this in bash injection commands to reference scripts or files bundled with the skill, regardless of the current working directory. - -Indexed arguments use shell-style quoting, so wrap multi-word values in quotes to pass them as a single argument. For example, `/my-skill "hello world" second` makes `$0` expand to `hello world` and `$1` to `second`. The `$ARGUMENTS` placeholder always expands to the full argument string as typed. To include a literal `$` before a digit, `ARGUMENTS`, or a declared argument name, such as `$1.00` in prose, escape it with a backslash: `\$1.00`. A backslash before any other `$` is left unchanged. Only a single backslash directly before the token escapes it. A doubled backslash such as `\\$1` leaves both backslashes in place, and `$1` still expands to the argument value. **Example using substitutions:** +`${CLAUDE_PROJECT_DIR}`| The project root directory. This is the same path [hooks](</docs/en/hooks#reference-scripts-by-path>) and MCP servers receive as `CLAUDE_PROJECT_DIR`. Use this to reference project-local scripts or files, such as `${CLAUDE_PROJECT_DIR}/.claude/hooks/helper.sh`, independent of where the skill is installed. + +The `${CLAUDE_PROJECT_DIR}` substitution requires Claude Code v2.1.196 or later. It applies to both the skill body and the `allowed-tools` frontmatter, so a permission rule like `Bash(${CLAUDE_PROJECT_DIR}/scripts/lint.sh *)` resolves to the same path the skill body uses. Indexed arguments use shell-style quoting, so wrap multi-word values in quotes to pass them as a single argument. For example, `/my-skill "hello world" second` makes `$0` expand to `hello world` and `$1` to `second`. The `$ARGUMENTS` placeholder always expands to the full argument string as typed. To include a literal `$` before a digit, `ARGUMENTS`, or a declared argument name, such as `$1.00` in prose, escape it with a backslash: `\$1.00`. A backslash before any other `$` is left unchanged. Only a single backslash directly before the token escapes it. A doubled backslash such as `\\$1` leaves both backslashes in place, and `$1` still expands to the argument value. **Example using substitutions:** --- name: session-logger @@ -816,7 +817,7 @@ Skill descriptions are cut short -Skill descriptions are loaded into context so Claude knows what’s available. All skill names are always included, but if you have many skills, descriptions are shortened to fit the character budget, which can strip the keywords Claude needs to match your request. The budget scales at 1% of the model’s context window. When it overflows, descriptions for the skills you invoke least are dropped first, so the skills you actually use keep their full text. Run `/doctor` to see how many skill descriptions are being shortened or dropped and which skills are affected. To raise the budget, set the [`skillListingBudgetFraction`](</docs/en/settings#available-settings>) setting (e.g. `0.02` = 2%) or the `SLASH_COMMAND_TOOL_CHAR_BUDGET` environment variable to a fixed character count. To free budget for other skills, set low-priority entries to `"name-only"` in `skillOverrides` so they list without a description. You can also trim the `description` and `when_to_use` text at the source: put the key use case first, since each entry’s combined text is capped at 1,536 characters regardless of budget. The cap is configurable with [`maxSkillDescriptionChars`](</docs/en/settings#available-settings>). +Skill descriptions are loaded into context so Claude knows what’s available. All skill names are always included, but if you have many skills, descriptions are shortened to fit the character budget, which can strip the keywords Claude needs to match your request. The budget scales at 1% of the model’s context window. When it overflows, descriptions for the skills you invoke least are dropped first, so the skills you actually use keep their full text. Run `/doctor` to see how many skill descriptions are being shortened or dropped and which skills are affected. As of v2.1.196, the Skills row in `/context` reports the size of the listing after the budget is applied, so it matches what the model receives. Earlier versions counted the full text of every description, so the row could show a value several times larger than the budget `/doctor` reports. To raise the budget, set the [`skillListingBudgetFraction`](</docs/en/settings#available-settings>) setting (e.g. `0.02` = 2%) or the `SLASH_COMMAND_TOOL_CHAR_BUDGET` environment variable to a fixed character count. To free budget for other skills, set low-priority entries to `"name-only"` in `skillOverrides` so they list without a description. You can also trim the `description` and `when_to_use` text at the source: put the key use case first, since each entry’s combined text is capped at 1,536 characters regardless of budget. The cap is configurable with [`skillListingMaxDescChars`](</docs/en/settings#available-settings>). ##
modified Customize your status line View current →
--- a/statusline.md +++ b/statusline.md @@ -164,6 +164,7 @@ `rate_limits.five_hour.resets_at`, `rate_limits.seven_day.resets_at`| Unix epoch seconds when the 5-hour or 7-day rate limit window resets `session_id`| Unique session identifier `session_name`| Custom session name set with the `--name` flag or `/rename`. Absent if no custom name has been set +`prompt_id`| UUID identifying the user prompt currently being processed. Matches the [`prompt.id` attribute on OpenTelemetry events](</docs/en/monitoring-usage#event-correlation-attributes>). Absent until the first user input. Requires Claude Code v2.1.196 or later `transcript_path`| Path to conversation transcript file `version`| Claude Code version `output_style.name`| Name of the current output style @@ -185,6 +186,7 @@ "cwd": "/current/working/directory", "session_id": "abc123...", "session_name": "my-session", + "prompt_id": "550e8400-e29b-41d4-a716-446655440000", "transcript_path": "/path/to/transcript.jsonl", "model": { "id": "claude-opus-4-8", @@ -265,6 +267,7 @@ **Fields that may be absent** (not present in JSON): * `session_name`: appears only when a custom name has been set with `--name` or `/rename` + * `prompt_id`: appears only after the first user input * `workspace.git_worktree`: appears only when the current directory is inside a linked git worktree * `workspace.repo`: appears only inside a git repository with an `origin` remote configured * `effort`: appears only when the current model supports the reasoning effort parameter
modified Create custom subagents View current →
--- a/sub-agents.md +++ b/sub-agents.md @@ -175,7 +175,7 @@ `~/.claude/agents/`| All your projects| 4| Interactive or manual Plugin’s `agents/` directory| Where plugin is enabled| 5 (lowest)| Installed with [plugins](</docs/en/plugins>) -**Project subagents** (`.claude/agents/`) are ideal for subagents specific to a codebase. Check them into version control so your team can use and improve them collaboratively. Project subagents are discovered by walking up from the current working directory, so every `.claude/agents/` between there and the repository root is scanned. As of v2.1.178, when more than one of these nested directories defines the same `name`, Claude Code uses the definition closest to the working directory. Directories added with `--add-dir` are also scanned: a `.claude/agents/` folder inside an added directory loads alongside project subagents. See [Additional directories](</docs/en/permissions#additional-directories-grant-file-access-not-configuration>) for which other configuration types load from `--add-dir`. To share subagents across projects without `--add-dir`, use `~/.claude/agents/` or a [plugin](</docs/en/plugins>). **User subagents** (`~/.claude/agents/`) are personal subagents available in all your projects. Claude Code scans `.claude/agents/` and `~/.claude/agents/` recursively, so you can organize definitions into subfolders such as `agents/review/` or `agents/research/`. The subdirectory path doesn’t affect how a subagent is identified or invoked, because identity comes only from the `name` frontmatter field. Keep `name` values unique across the whole tree: if two files within one scope declare the same name, Claude Code keeps one and discards the other without warning. Plugin `agents/` directories are also scanned recursively. Unlike project and user scopes, a subfolder inside a plugin’s `agents/` directory becomes part of the scoped identifier: a file at `agents/review/security.md` in plugin `my-plugin` registers as `my-plugin:review:security`. **CLI-defined subagents** are passed as JSON when launching Claude Code. They exist only for that session and aren’t saved to disk, making them useful for quick testing or automation scripts. You can define multiple subagents in a single `--agents` call: +**Project subagents** (`.claude/agents/`) are ideal for subagents specific to a codebase. Check them into version control so your team can use and improve them collaboratively. Project subagents are discovered by walking up from the current working directory, so every `.claude/agents/` between there and the repository root is scanned. As of v2.1.178, when more than one of these nested directories defines the same `name`, Claude Code uses the definition closest to the working directory. Directories added with `--add-dir` are also scanned: a `.claude/agents/` folder inside an added directory loads alongside project subagents. See [Additional directories](</docs/en/permissions#additional-directories-grant-file-access-not-configuration>) for which other configuration types load from `--add-dir`. To share subagents across projects without `--add-dir`, use `~/.claude/agents/` or a [plugin](</docs/en/plugins>). **User subagents** (`~/.claude/agents/`) are personal subagents available in all your projects. Claude Code scans `.claude/agents/` and `~/.claude/agents/` recursively, so you can organize definitions into subfolders such as `agents/review/` or `agents/research/`. The subdirectory path doesn’t affect how a subagent is identified or invoked, because identity comes only from the `name` frontmatter field. Keep `name` values unique across the whole tree: if two files within one scope declare the same name, Claude Code loads only one of them. As of v2.1.196, running `/doctor` reports same-scope duplicate agent names and shows which definition is active. Plugin `agents/` directories are also scanned recursively. Unlike project and user scopes, a subfolder inside a plugin’s `agents/` directory becomes part of the scoped identifier: a file at `agents/review/security.md` in plugin `my-plugin` registers as `my-plugin:review:security`. **CLI-defined subagents** are passed as JSON when launching Claude Code. They exist only for that session and aren’t saved to disk, making them useful for quick testing or automation scripts. You can define multiple subagents in a single `--agents` call: * macOS, Linux, WSL @@ -279,12 +279,12 @@ When Claude invokes a subagent, it can also pass a `model` parameter for that specific invocation. Claude Code resolves the subagent’s model in this order: - 1. The [`CLAUDE_CODE_SUBAGENT_MODEL`](</docs/en/model-config#environment-variables>) environment variable, if set + 1. The [`CLAUDE_CODE_SUBAGENT_MODEL`](</docs/en/model-config#environment-variables>) environment variable, when set to a model alias or model ID 2. The per-invocation `model` parameter 3. The subagent definition’s `model` frontmatter 4. The main conversation’s model -The environment variable, per-invocation parameter, and frontmatter values are checked against your organization’s [`availableModels`](</docs/en/model-config#restrict-model-selection>) allowlist. A value that resolves to an excluded model is not used and the subagent runs on the inherited model instead. +As of v2.1.196, setting `CLAUDE_CODE_SUBAGENT_MODEL` to `inherit` is the same as leaving it unset: resolution continues with the per-invocation `model` parameter, then the frontmatter. In earlier versions, `inherit` forced subagents onto the main conversation’s model and ignored both of those sources. The environment variable, per-invocation parameter, and frontmatter values are checked against your organization’s [`availableModels`](</docs/en/model-config#restrict-model-selection>) allowlist. A value that resolves to an excluded model is not used and the subagent runs on the inherited model instead. ### @@ -600,7 +600,7 @@ `SubagentStart`| Agent type name| When a subagent begins execution `SubagentStop`| Agent type name| When a subagent completes -Both events support matchers to target specific agent types by name. This example runs a setup script only when the `db-agent` subagent starts, and a cleanup script when any subagent stops: +Both events support matchers to target specific agent types by name. The matcher value is the agent’s frontmatter `name` for project-level and user-level subagents, or the plugin-scoped identifier such as `my-plugin:db-agent` for [plugin subagents](</docs/en/plugins>). A scoped name contains a colon, so it is evaluated as an [unanchored regular expression](</docs/en/hooks#matcher-patterns>); anchor it with `^` and `$`, as in `^my-plugin:db-agent$`, to match only that agent. This example runs a setup script only when the `db-agent` subagent starts, and a cleanup script when any subagent stops: { "hooks": { @@ -622,7 +622,7 @@ } } -See [Hooks](</docs/en/hooks>) for the complete hook configuration format. +A hyphenated matcher like `db-agent` matches exactly on Claude Code v2.1.195 or later. On earlier versions it is evaluated as an unanchored regular expression and also fires for any agent type that contains it, such as `prod-db-agent`; anchor it as `^db-agent$` on those versions. See [Hooks](</docs/en/hooks>) for the complete hook configuration format. ## @@ -766,7 +766,7 @@ Spawn nested subagents -As of Claude Code v2.1.172, a subagent can spawn its own subagents. Use this when a delegated task itself splits into parallel subtasks, such as a reviewer subagent that dispatches a verifier per finding, so the intermediate output never reaches your main conversation. Only the top-level subagent’s summary returns to you. A nested subagent is configured the same way as a top-level one and resolves from the same scopes. The subagent panel below the prompt input shows the full tree: each row displays a `(+N)` count of descendants, and opening a row shows that subagent’s direct children with a path back to `main`. The Running tab in `/agents` lists running subagents as a flat list. Depth is counted as the number of subagent levels below the main conversation, regardless of whether each level runs in the foreground or background. A subagent at depth five doesn’t receive the Agent tool and can’t spawn further. The limit is fixed and not configurable. As of Claude Code v2.1.187, a background subagent’s depth is fixed when it is first spawned, and resuming it later doesn’t change that depth. For example, if your main conversation spawns subagent A, and A spawns a background subagent B at depth two, B is still at depth two when you resume it directly from the main conversation. Resuming a subagent from a shallower context doesn’t let it spawn additional levels that the depth limit already prevented. To prevent a specific subagent from spawning others, omit `Agent` from its `tools` list or add it to `disallowedTools`. A fork still can’t spawn another fork. It can spawn other subagent types, and those count toward the depth limit. +As of Claude Code v2.1.172, a subagent can spawn its own subagents. Use this when a delegated task itself splits into parallel subtasks, such as a reviewer subagent that dispatches a verifier per finding, so the intermediate output never reaches your main conversation. Only the top-level subagent’s summary returns to you. A nested subagent is configured the same way as a top-level one and resolves from the same scopes. The subagent panel below the prompt input shows the full tree: each row displays a `(+N)` count of descendants, and as of v2.1.193, opening a row shows that subagent’s siblings and direct children with a path back to `main`. The Running tab in `/agents` lists running subagents as a flat list. Depth is counted as the number of subagent levels below the main conversation, regardless of whether each level runs in the foreground or background. A subagent at depth five doesn’t receive the Agent tool and can’t spawn further. The limit is fixed and not configurable. As of Claude Code v2.1.187, a background subagent’s depth is fixed when it is first spawned, and resuming it later doesn’t change that depth. For example, if your main conversation spawns subagent A, and A spawns a background subagent B at depth two, B is still at depth two when you resume it directly from the main conversation. Resuming a subagent from a shallower context doesn’t let it spawn additional levels that the depth limit already prevented. To prevent a specific subagent from spawning others, omit `Agent` from its `tools` list or add it to `disallowedTools`. A fork still can’t spawn another fork. It can spawn other subagent types, and those count toward the depth limit. ###
modified Enterprise deployment overview View current →
--- a/third-party-integrations.md +++ b/third-party-integrations.md @@ -21,6 +21,7 @@ * [Claude for Teams or Enterprise](</docs/en/authentication#claude-for-teams-or-enterprise>) * [Anthropic Console](</docs/en/authentication#claude-console-authentication>) + * [Claude apps gateway](</docs/en/claude-apps-gateway>), a self-hosted gateway that adds IdP sign-in in front of Amazon Bedrock, Google Vertex AI, Microsoft Foundry, or the Anthropic API * [Amazon Bedrock](</docs/en/amazon-bedrock>) * [Claude Platform on AWS](</docs/en/claude-platform-on-aws>) * [Google Vertex AI](</docs/en/google-vertex-ai>)
modified Tools reference View current →
--- a/tools-reference.md +++ b/tools-reference.md @@ -18,15 +18,17 @@ `Grep`| Searches for patterns in file contents. See Grep tool behavior| No `ListMcpResourcesTool`| Lists resources exposed by connected [MCP servers](</docs/en/mcp>)| No `LSP`| Code intelligence via language servers: jump to definitions, find references, report type errors and warnings. See LSP tool behavior| No -`Monitor`| Runs a command in the background and feeds each output line back to Claude, so it can react to log entries, file changes, or polled status mid-conversation. See Monitor tool| Yes +`Monitor`| Runs a command in the background and feeds each output line back to Claude, so it can react to log entries, file changes, or polled status mid-conversation. Can also open a WebSocket and treat each incoming message as an event. See Monitor tool| Yes `NotebookEdit`| Modifies Jupyter notebook cells. See NotebookEdit tool behavior| Yes `PowerShell`| Executes PowerShell commands natively. See PowerShell tool for availability| Yes `PushNotification`| Sends a desktop notification, and a phone push when [Remote Control](</docs/en/remote-control>) is connected, so a long-running task or [scheduled task](</docs/en/scheduled-tasks>) can reach you when you step away. Push delivery runs through Anthropic-hosted infrastructure, which is not accessible from Amazon Bedrock, Google Vertex AI, or Microsoft Foundry| No `Read`| Reads the contents of files. See Read tool behavior| No `ReadMcpResourceTool`| Reads a specific MCP resource by URI| No `RemoteTrigger`| Creates, updates, runs, and lists [Routines](</docs/en/routines>) on claude.ai. Backs the `/schedule` command. Routines live on claude.ai and require a Pro, Max, Team, or Enterprise plan, so this tool is not accessible from Amazon Bedrock, Google Vertex AI, or Microsoft Foundry| No +`ReportFindings`| Reports code-review findings as a structured list, with a file, summary, and failure scenario per finding, so Claude Code can render them instead of printing them as text. Claude calls it when active code-review instructions tell it to. Requires Claude Code v2.1.196 or later| No `ScheduleWakeup`| Reschedules the next iteration of a [self-paced `/loop`](</docs/en/scheduled-tasks#let-claude-choose-the-interval>). Claude calls this at the end of each iteration to pick when the next one runs, between one minute and one hour out; you don’t call it directly. The pending wakeup appears in `session_crons` in [Stop hook input](</docs/en/hooks#stop-input>). Not available on Amazon Bedrock, Google Vertex AI, or Microsoft Foundry, where a `/loop` prompt with no interval runs on a fixed schedule instead| No `SendMessage`| Sends a message to an [agent team](</docs/en/agent-teams>) teammate, or [resumes a subagent](</docs/en/sub-agents#resume-subagents>) by its agent ID. Stopped subagents auto-resume in the background. Structured team-protocol messages require agent teams| No +`SendUserFile`| Sends files from the session to you with an optional caption, so a generated report, diagram, screenshot, or built artifact reaches your device instead of only being mentioned in the transcript. As of v2.1.196, the optional `display` input controls presentation: `render` opens the file inline in the client, `attach` shows a download card only, and when unset the client decides by file type. Available when a [Remote Control](</docs/en/remote-control>) client is connected or the session runs in a managed cloud environment such as [Claude Code on the web](</docs/en/claude-code-on-the-web>). Delivery runs through Anthropic-hosted infrastructure, so the tool is not available on Amazon Bedrock, Google Vertex AI, or Microsoft Foundry| No `ShareOnboardingGuide`| Uploads `ONBOARDING.md` and returns a share link teammates can open in Claude Code. Called from `/team-onboarding` after the guide is written. Available to claude.ai subscribers on Pro, Max, Team, and Enterprise plans| Yes `Skill`| Executes a [skill](</docs/en/skills#control-who-invokes-a-skill>) within the main conversation| Yes `TaskCreate`| Creates a new task in the task list| No @@ -188,8 +190,33 @@ * Poll a PR or CI job and report when its status changes * Watch a directory for file changes * Track output from any long-running script you point it at - -Claude writes a small script for the watch, runs it in the background, and receives each output line as it arrives. You keep working in the same session and Claude interjects when an event lands. Stop a monitor by asking Claude to cancel it or by ending the session. Monitor uses the same [permission rules as Bash](</docs/en/permissions#tool-specific-permission-rules>), so `allow` and `deny` patterns you have set for Bash apply here too. It is not available on Amazon Bedrock, Google Vertex AI, or Microsoft Foundry. It is also not available when `DISABLE_TELEMETRY` or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is set. Plugins can declare monitors that start automatically when the plugin is active, instead of asking Claude to start them. See [plugin monitors](</docs/en/plugins-reference#monitors>). + * Connect to a WebSocket feed and report each message as it arrives + +For most watches, Claude writes a small script, runs it in the background, and receives each output line as it arrives. For a server that already pushes events, Claude can open a WebSocket instead of running a script. You keep working in the same session and Claude interjects when an event arrives. Stop a monitor by asking Claude to cancel it or by ending the session. When Monitor runs a command, it uses the same [permission rules as Bash](</docs/en/permissions#tool-specific-permission-rules>), so `allow` and `deny` patterns you have set for Bash apply here too. The WebSocket source has its own approval prompt. The tool is not available on Amazon Bedrock, Google Vertex AI, or Microsoft Foundry. It is also not available when `DISABLE_TELEMETRY` or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is set. Plugins can declare monitors that start automatically when the plugin is active, instead of asking Claude to start them. See [plugin monitors](</docs/en/plugins-reference#monitors>). + +### + +​ + +WebSocket source + +The WebSocket source requires Claude Code v2.1.195 or later. + +When a server already pushes events over a WebSocket, Claude can connect to it directly instead of writing a polling script. Each kind of socket activity either becomes an event or ends the watch: + + * **Text messages** : each one becomes one event, even when the message spans multiple lines. + * **Binary messages** : not passed through. Claude receives a placeholder line such as `[binary frame, 512 bytes]` instead. + * **Messages larger than 1 MiB** : the watch ends, so subscribe to a filtered feed where one exists. + * **Socket close** : the watch ends and Claude receives the close code. + +A WebSocket watch takes a `ws` input in place of `command`, and a single Monitor call can’t combine the two. The `ws` input has two fields: + +Field| Required| Description +---|---|--- +`url`| Yes| The endpoint to connect to. Must be a `ws://` or `wss://` URL with no embedded credentials or whitespace, using ASCII characters only +`protocols`| No| WebSocket subprotocol names to offer during the handshake. Each entry must be a valid subprotocol token, and the list can’t contain duplicates + +The `timeout_ms` and `persistent` inputs behave the same as they do for a command: the watch ends at the deadline unless `persistent` is set, and `TaskStop` cancels it early. Opening a WebSocket prompts for approval, and the prompt doesn’t offer an option to skip future prompts for the same host. Claude Code denies URLs that point at a private, link-local, or cloud-metadata address, including hostnames that resolve to one. It also denies hosts in `sandbox.network.deniedDomains`, and when [`allowManagedDomainsOnly`](</docs/en/settings#sandbox-settings>) is set in managed settings, any host outside the managed allowlist. ## @@ -241,7 +268,7 @@ * `"shell": "powershell"` on individual [command hooks](</docs/en/hooks#command-hook-fields>): runs that hook in PowerShell. Hooks spawn PowerShell directly, so this works regardless of `CLAUDE_CODE_USE_POWERSHELL_TOOL`. * `shell: powershell` in [skill frontmatter](</docs/en/skills#frontmatter-reference>): runs `!`command`` blocks in PowerShell. Requires the PowerShell tool to be enabled. -The same main-session working-directory reset behavior described under the Bash tool section applies to PowerShell commands, including the `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` environment variable. +The same main-session working-directory reset behavior described under the Bash tool section applies to PowerShell commands, including the `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` environment variable. As of v2.1.196, the PowerShell tool matches the Bash tool’s handling of search and diff exit codes. Exit code 1 from `grep`, `egrep`, `fgrep`, and `git grep` means no matches, and exit code 1 from `git diff` means differences exist, so these results aren’t reported to Claude as command failures. ### @@ -262,7 +289,7 @@ The Read tool takes a file path and returns the contents with line numbers. Claude is instructed to always pass absolute paths. By default, Read returns the file from the start. When a whole-file read exceeds the token limit, Read returns the first page with a `PARTIAL view` notice that tells Claude how much of the file it received and how to read more with `offset` and `limit`. A read that passes an explicit `offset` or `limit` and still exceeds the token limit returns an error. Read handles several file types beyond plain text: - * **Images** : PNG, JPG, and other image formats are returned as visual content that Claude can see, not as raw bytes. Claude Code resizes and recompresses large images to fit the model’s image size limits before sending them, so Claude may see a downscaled version of a large screenshot. If Claude misses fine pixel-level detail in a large image, ask it to crop the region of interest first, for example with ImageMagick via Bash. + * **Images** : PNG, JPG, and other image formats are returned as visual content that Claude can see, not as raw bytes. Claude Code resizes and recompresses large images to fit the model’s image size limits before sending them, so Claude may see a downscaled version of a large screenshot. As of v2.1.196, an image that is still larger than 500KB after that resize is re-encoded as a JPEG at reduced quality with its pixel dimensions unchanged. If Claude misses fine pixel-level detail in a large image, ask it to crop the region of interest first, for example with ImageMagick via Bash. * **PDFs** : Claude reads short `.pdf` files whole. For PDFs longer than 10 pages, it reads in ranges with a `pages` parameter, such as `"1-5"`, up to 20 pages at a time. * **Jupyter notebooks** : `.ipynb` files return all cells with their outputs, including code, markdown, and visualizations.
modified Agent SDK reference - TypeScript View current →
--- a/typescript.md +++ b/typescript.md @@ -569,7 +569,7 @@ * `API_TIMEOUT_MS`: per-request timeout on the Anthropic client, in milliseconds. Default `600000`. Applies to the main loop and all subagents. * `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`, capped at `15`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff. For unattended runs that need to wait through longer outages, set `CLAUDE_CODE_RETRY_WATCHDOG=1` to retry capacity errors indefinitely. * `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents launched with `run_in_background`. Default `600000`. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents. - * `CLAUDE_ENABLE_STREAM_WATCHDOG=1` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. When `CLAUDE_ENABLE_STREAM_WATCHDOG` is unset, the default is server-controlled on the direct Anthropic API and off on other providers. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. The aborted request goes through the normal retry path. + * `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. The aborted request goes through the normal retry path. ### @@ -590,6 +590,7 @@ setMaxThinkingTokens(maxThinkingTokens: number | null): Promise<void>; applyFlagSettings(settings: { [K in keyof Settings]?: Settings[K] | null }): Promise<void>; initializationResult(): Promise<SDKControlInitializeResponse>; + reinitialize(): Promise<SDKControlInitializeResponse>; supportedCommands(): Promise<SlashCommand[]>; supportedModels(): Promise<ModelInfo[]>; supportedAgents(): Promise<AgentInfo[]>; @@ -618,6 +619,7 @@ `setMaxThinkingTokens()`| _Deprecated:_ Use the `thinking` option instead. Changes the maximum thinking tokens `applyFlagSettings(settings)`| Merges settings into the session’s flag settings layer at runtime (only available in streaming input mode). See `applyFlagSettings()` `initializationResult()`| Returns the full initialization result including supported commands, models, account info, and output style configuration +`reinitialize()`| Re-sends the `initialize` control request to the running CLI and returns a fresh result instead of the cached first-connect result. Use it after a transport gap, such as reattaching to a session after a disconnect, so pending permission requests reach your `canUseTool` callback again. Make the callback idempotent per request ID, because a request whose response was lost is dispatched again. Requires Claude Code v2.1.195 or later `supportedCommands()`| Returns available slash commands `supportedModels()`| Returns available models with display info `supportedAgents()`| Returns available subagents as `AgentInfo``[]` @@ -697,7 +699,7 @@ fast_mode_state?: "off" | "cooldown" | "on"; }; -When a client sends `initialize` to a session that is already running, the control-response wrapper also carries an optional `pending_permission_requests` array. The field is on the response wrapper itself, not in the `SDKControlInitializeResponse` payload above. Each entry is a complete `control_request` message with the same `{ type: "control_request", request_id, request }` shape the session streams for permission requests while running. These are requests that were issued before the client connected and are still awaiting a reply, so read this array to surface in-flight permission prompts immediately; they will not be re-sent. +When a client sends `initialize` to a session that is already running, the control-response wrapper also carries an optional `pending_permission_requests` array. The field is on the response wrapper itself, not in the `SDKControlInitializeResponse` payload above. Each entry is a complete `control_request` message with the same `{ type: "control_request", request_id, request }` shape the session streams for permission requests while running. These are requests that were issued before the client connected and are still awaiting a reply. The SDK reads the array for you and dispatches each entry to your `canUseTool` callback, the same redelivery that `reinitialize()` triggers after a transport gap. Handle repeated request IDs idempotently, because an entry can repeat a request the callback already received before the connection dropped. ### @@ -1530,11 +1532,14 @@ session_id: string; transcript_path: string; cwd: string; + prompt_id?: string; permission_mode?: string; effort?: { level: string }; agent_id?: string; agent_type?: string; }; + +The `prompt_id` field is a UUID identifying the user prompt currently being processed. It matches the [`prompt.id` attribute on OpenTelemetry events](</docs/en/monitoring-usage#event-correlation-attributes>) and is absent until the first user input. Requires Claude Code v2.1.196 or later. #### @@ -2038,13 +2043,17 @@ **Tool name:** `Monitor` type MonitorInput = { - command: string; + command?: string; + ws?: { + url: string; + protocols?: string[]; + }; description: string; timeout_ms?: number; persistent?: boolean; }; -Runs a background script and delivers each stdout line to Claude as an event so it can react without polling. Set `persistent: true` for session-length watches such as log tails. Monitor follows the same permission rules as Bash. See the [Monitor tool reference](</docs/en/tools-reference#monitor-tool>) for behavior and provider availability. +Runs a background source and delivers each event to Claude so it can react without polling: `command` runs a script and emits one event per stdout line, and `ws` opens a WebSocket and emits one event per text frame. Provide exactly one of `command` or `ws`. The `ws` source requires Claude Code v2.1.195 or later. Set `persistent: true` for session-length watches such as log tails. When Monitor runs a command, it follows the same permission rules as Bash; a WebSocket watch prompts for approval separately. See the [Monitor tool reference](</docs/en/tools-reference#monitor-tool>) for behavior and provider availability. ###
modified Voice dictation View current →
--- a/voice-dictation.md +++ b/voice-dictation.md @@ -10,7 +10,14 @@ Requirements -Voice dictation streams your recorded audio to Anthropic’s servers for transcription. Audio is not processed locally. The speech-to-text service is only available when you authenticate with a Claude.ai account, and is not available when Claude Code is configured to use an Anthropic API key directly, Amazon Bedrock, Google Vertex AI, or Microsoft Foundry. Voice dictation is also not available when your organization has HIPAA compliance enabled. Transcription does not consume Claude messages or tokens and does not count toward the limits shown in `/usage`. See [data usage](</docs/en/data-usage>) for how Anthropic handles your data. Voice dictation also needs local microphone access, so it does not work in remote environments such as [Claude Code on the web](</docs/en/claude-code-on-the-web>) or SSH sessions. In WSL, voice dictation requires WSLg for audio access. WSLg is included with WSL2 when installed from the Microsoft Store on Windows 10 or 11. If WSLg is not available, for example on WSL1, run Claude Code in native Windows instead. Audio recording uses a built-in native module on macOS, Linux, and Windows. On Linux, if the native module cannot load, Claude Code falls back to `arecord` from ALSA utils or `rec` from SoX. If neither is available, `/voice` prints an install command for your package manager. The Claude Code [VS Code extension](</docs/en/vs-code>) also supports voice dictation with the same Claude.ai account requirement. It is not available in VS Code Remote sessions, including SSH, Dev Containers, and Codespaces, because the microphone is on your local machine and the extension runs on the remote host. +Voice dictation streams your recorded audio to Anthropic’s servers for transcription. Audio is not processed locally. It needs all of the following: + + * **A Claude.ai account** : the speech-to-text service is only available when you authenticate with one, and is not available when Claude Code is configured to use an Anthropic API key directly, Amazon Bedrock, Google Vertex AI, or Microsoft Foundry. + * **An organization without HIPAA compliance enabled** : `/voice` shows `Voice mode is disabled by your organization's policy` when this restriction applies. + * **A local microphone** : voice dictation does not work in remote environments such as [Claude Code on the web](</docs/en/claude-code-on-the-web>) or SSH sessions. + * **WSLg, if you run Claude Code in WSL** : WSLg is included with WSL2 when installed from the Microsoft Store on Windows 10 or 11. If WSLg is not available, for example on WSL1, run Claude Code in native Windows instead. + +Transcription does not consume Claude messages or tokens and does not count toward the limits shown in `/usage`. See [data usage](</docs/en/data-usage>) for how Anthropic handles your data. Audio recording uses a built-in native module on macOS, Linux, and Windows. On Linux, if the native module cannot load, Claude Code falls back to `arecord` from ALSA utils or `rec` from SoX. If neither is available, `/voice` prints an install command for your package manager. The Claude Code [VS Code extension](</docs/en/vs-code>) also supports voice dictation with the same Claude.ai account requirement. It is not available in VS Code Remote sessions, including SSH, Dev Containers, and Codespaces, because the microphone is on your local machine and the extension runs on the remote host. ## @@ -67,7 +74,7 @@ Tap to record and send -Tap mode toggles recording with a single keypress: tap once to start, speak, then tap again to send the prompt. There is no warmup, and you don’t need to keep the key held. Enable tap mode with `/voice tap`. With the prompt input empty, tap `Space` to start recording. The footer shows a live waveform while recording. Tap `Space` again to stop. Claude Code inserts the transcript and submits the prompt automatically when the transcript is at least three words long. Shorter transcripts are inserted but not submitted, so an accidental tap does not send a stray word. The first tap only starts recording when the prompt input is empty, so you can still type spaces normally while composing a message. The second tap stops recording regardless of input contents. Recording also stops automatically after 15 seconds of silence or two minutes total. +Tap mode toggles recording with a single keypress: tap once to start, speak, then tap again to send the prompt. There is no warmup, and you don’t need to keep the key held. Enable tap mode with `/voice tap`. With the prompt input empty, tap `Space` to start recording. The footer shows a live waveform while recording. Tap `Space` again to stop. Claude Code inserts the transcript and submits the prompt automatically when the transcript is at least three words long. Shorter transcripts are inserted but not submitted, so an accidental tap does not send a stray word. The three-word threshold counts words for languages written without spaces. As of v2.1.195, Japanese, Chinese, and Thai transcripts count individual words, so they auto-submit in tap mode and in hold mode with `autoSubmit`. Earlier versions counted a transcript with no spaces as one word and never submitted it automatically. The first tap only starts recording when the prompt input is empty, so you can still type spaces normally while composing a message. The second tap stops recording regardless of input contents. Recording also stops automatically after 15 seconds of silence or two minutes total. ## @@ -141,8 +148,10 @@ Common issues when voice dictation does not activate or record: * **`Voice mode requires a Claude.ai account`** : you are authenticated with an API key or a third-party provider. Run `/login` to sign in with a Claude.ai account. + * **`Voice mode is disabled by your organization's policy`** : your organization’s compliance configuration disables voice dictation, as described in Requirements. Contact your organization administrator to confirm whether voice dictation is available for your organization. * **`Microphone access is denied`** : grant microphone permission to your terminal in system settings. On macOS, go to System Settings → Privacy & Security → Microphone and enable your terminal app, then run `/voice` again. On Windows, go to Settings → Privacy & security → Microphone and turn on microphone access for desktop apps, then run `/voice` again. If your terminal isn’t listed in the macOS settings, see Terminal not listed in macOS Microphone settings. * **`No audio recording tool found` on Linux**: the native audio module could not load and no fallback is installed. Install SoX with the command shown in the error message, for example `sudo apt-get install sox`. + * **`Voice mode requires a microphone, but SoX could not open an audio capture device`** : SoX is installed, but the host has no audio capture device, for example a headless server or a container. Run Claude Code on a machine with a microphone. As of v2.1.195, Claude Code on Linux reports this message in that situation; earlier versions asked you to install SoX even when it was already installed. * **`Voice mode could not find a working audio recorder in WSL`** : WSLg routes audio through PulseAudio rather than an ALSA device, so SoX needs its PulseAudio backend installed explicitly. Run `sudo apt install sox libsox-fmt-pulse`. Installing `sox` alone pulls in the ALSA backend, which cannot record on WSL because there is no `/dev/snd` device. * **`Voice input is failing repeatedly and has been paused`** : voice dictation hit several start-up failures in a row and stopped attempting new sessions until one succeeds. This usually means the microphone or audio stack on this host can’t capture audio, for example a headless server, a remote shell with no audio passthrough, or a denied microphone permission. Confirm a working input device, fix the underlying cause from the entries above, then trigger voice again. * **Nothing happens when holding`Space` in hold mode**: watch the prompt input while you hold. If spaces keep accumulating, voice dictation is likely off; run `/voice hold` to enable it. If only one or two spaces appear and then nothing, voice dictation is on but hold detection is not triggering. Hold detection requires your terminal to send key-repeat events, so it can’t detect a held key if key-repeat is disabled at the OS level. Switch to tap mode with `/voice tap` to avoid the key-repeat requirement.
modified Orchestrate subagents at scale with dynamic workflows View current →
--- a/workflows.md +++ b/workflows.md @@ -57,7 +57,7 @@ Read the report -When the run finishes, the report lands in your session. It cites the sources each claim came from, with claims that didn’t survive cross-checking already filtered out. +When the run finishes, the report lands in your session. It cites the sources each claim came from, with claims that didn’t survive cross-checking already filtered out.As of v2.1.196, when the verifier agents can’t check a claim, such as after a rate limit or API error, the report lists that claim as unverified instead of counting it as refuted. To run a workflow for your own task, have Claude write one, and once a run does what you wanted you can save it as a command of your own.