added Week 30 · July 20–24, 2026 View current →
--- a/2026-w30.md +++ b/2026-w30.md @@ -0,0 +1,63 @@ +Releases [v2.1.214 → v2.1.219](</docs/en/changelog#2-1-214>)3 features · July 20–24 + +Claude Opus 5new model + +Claude Opus 5 is the new default Opus model in Claude Code. It’s the default on Max, Team Premium, Enterprise pay-as-you-go, and the Anthropic API, and on Claude Platform on AWS, Amazon Bedrock, and Google Cloud’s Agent Platform. On the Anthropic API and on Max, Team, and Enterprise plans, Opus 5 runs with a [1M-token context window](</docs/en/model-config#extended-context>); on Amazon Bedrock and Google Cloud’s Agent Platform, select the 1M model variant. Fast mode moves to Opus 5 at $10/$50 per MTok. Requires v2.1.219 or later. + +Switch to Opus 5 by name, or pick it from the model picker: + +Claude Code + + > /model claude-opus-5 + +[Model configuration](</docs/en/model-config#available-models>) + +iOS Simulator in Claude Code DesktopDesktop + +Claude Code Desktop on macOS gets an iOS Simulator pane, in public beta on Pro, Max, and Team plans. When Claude builds, launches, or checks your app in a simulator, the pane opens next to the conversation and streams the device screen live, so you can watch Claude tap through the app to verify its changes or drive the device yourself. Requires Xcode with the iOS platform installed, and Claude Desktop v1.24012.0 or later. + +Ask Claude to run or test your app, and the pane opens when the app launches: + +Claude Code + + > Build the app and run it in the simulator to check the onboarding flow. + +[Test iOS apps in the simulator](</docs/en/desktop-ios-simulator#run-your-app-in-the-simulator>) + +Claude Security pluginplugin + +The Claude Security plugin runs a multi-agent vulnerability scan of your codebase inside a Claude Code session: agents map your architecture, build a threat model, hunt for vulnerabilities, and independently review every finding before writing the report to a `CLAUDE-SECURITY-<timestamp>/` directory. Scan a whole repository or only a branch’s diff, a pull request, or a single commit, then turn the findings you choose into reviewed patches that you apply yourself. + +Install the plugin from the official Anthropic marketplace, run `/reload-plugins`, then start a scan with `/claude-security`: + +Claude Code + + > /plugin install claude-security@claude-plugins-official + +[Scan and fix your codebase](</docs/en/claude-security#scan-and-fix-your-codebase>) + +Other wins + +[`/code-review`](</docs/en/code-review#review-a-diff-locally>) now runs as a background subagent with its own context window, so review work stays out of your conversation and the findings arrive when it completes + +`/verify`, `/code-review`, and `/deep-research` run only when you invoke them; Claude no longer launches them on its own + +[Emoji shortcodes](</docs/en/interactive-mode#emoji-shortcodes>) autocomplete in the prompt input: type `:heart:` to insert an emoji, or two or more characters after `:` for suggestions; turn it off with `emojiCompletionEnabled` + +Skills with `context: fork` [run in the background](</docs/en/skills#run-skills-in-a-subagent>) by default, and `background: false` in the skill’s frontmatter waits for the result in the same turn + +A session runs up to 20 subagents concurrently by default; change the [limit](</docs/en/sub-agents#concurrent-subagent-limit>) with `CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS` + +`--max-budget-usd` now enforces the cap on subagents: once spend reaches it, Claude can’t start more and running background subagents stop + +New [`sandbox.filesystem.disabled`](</docs/en/sandboxing#disable-filesystem-isolation>) setting skips filesystem isolation while keeping network egress control + +In auto mode, the checks for dangerous `rm` commands, background jobs, and suspicious Windows paths no longer open permission dialogs; the auto-mode classifier adjudicates them instead + +Bash permission checks fail closed on more shell forms, including file-descriptor redirects, Zsh variable subscripts in `[[ ]]` comparisons, `help` and `man` invocations that could run unsafe options, and commands over 10,000 characters + +[Fast mode](</docs/en/fast-mode>) no longer supports Opus 4.7: `/fast` now applies to Opus 5 and Opus 4.8 + +Long-running tool calls emit a periodic progress heartbeat instead of going silent + +[Full changelog for v2.1.214–v2.1.219 →](</docs/en/changelog#2-1-214>)
added Week 32 · August 3–7, 2026 View current →
--- a/2026-w32.md +++ b/2026-w32.md @@ -0,0 +1,77 @@ +Releases [v2.1.220 → v2.1.224](</docs/en/changelog#2-1-220>)3 features · August 3–7 + +Cross-session messagingv2.1.224 + +Your Claude Code sessions can now message each other. Claude discovers your other sessions with the `ListAgents` tool and sends with `SendMessage`, either when you ask it to or on its own, such as after a change in one session affects what another is working on. A message is text Claude writes for the other session, never your conversation history or files. Available on macOS and Linux. Requires v2.1.224 or later. + +With two sessions open on the same machine, ask one of them to pass something along: + +Claude Code + + Tell the session working on the payments API that users.name is now users.display_name + +The other session shows a `Message from` row once Claude has read the message; press `Ctrl+O` to expand it. To see which sessions Claude can reach, run `/list-agents`. + +[Message another session](</docs/en/cross-session-messaging#message-another-session>) + +Self-hosted environmentsv2.1.224 + +Self-hosted environments run Claude Code cloud sessions on your organization’s own infrastructure, in public beta on Team and Enterprise plans. Run `claude self-hosted-runner` on your machines or containers to turn them into runners. When someone picks your environment while starting a session from claude.ai, the mobile or desktop apps, or `claude --cloud`, that session runs inside your network, with access to your internal services. An Owner or admin turns on **Allow self-hosted environments** in [admin settings](<https://claude.ai/admin-settings/cloud-environments>) first. + +Signed in as an Owner or admin, run the guided setup, which walks you through creating the environment and starts a runner: + +terminal + + claude self-hosted-runner setup + +The environment shows **Healthy** in admin settings once the runner registers. + +[Self-hosted environments quickstart](</docs/en/self-hosted-environments-quickstart#set-up-an-environment-and-runner>) + +Auto mode becomes the defaultCLI + +Starting August 14, auto mode is the default permission mode for new sessions on Pro, Max, and Team plans. If you set a default mode yourself, it stays in place unless you accept the one-time switch prompt, and a default your organization manages doesn’t change. You can still switch modes at any time. Already in effect on those plans: the classifier calls auto mode makes no longer count toward your usage limits. + +To start every session in auto mode before the switch, set it as your default in your user settings: + +~/.claude/settings.json + + { + "permissions": { + "defaultMode": "auto" + } + } + +New sessions then show `auto mode on` in the status bar. + +[Auto mode requirements and controls](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) + +Other wins + +The VS Code extension gets [Focus view](</docs/en/vs-code#extension-settings>), which hides tool activity behind one expandable row per turn; toggle it from the command menu or with `Ctrl+Alt+F` (`Ctrl+Option+F` on Mac) + +Sandbox credential files accept [`mode: “mask”`](</docs/en/sandboxing#mask-credential-files>) on Linux and WSL2, so sandboxed commands read a sentinel copy while the sandbox proxy substitutes the real value on egress; credential masking also gains `extract`, JWT-aware `decode`, and AWS SigV4 re-signing options + +Marketplaces can distribute a plugin as a [zip archive](</docs/en/plugin-marketplaces#zip-archives>) with the new `archive` source, downloaded over HTTPS with an optional SHA-256 pin, so installs work without git or npm + +`/review` is now an alias of [`/code-review`](</docs/en/code-review#review-a-diff-locally>), and `/code-review` with no effort level reuses the level you typed last + +A session you copy with [`/fork`](</docs/en/agent-view#copy-the-session-with-%2Ffork>) now makes its code changes in a worktree of its own instead of the original session’s checkout + +Plugins you install from [`/plugin`](</docs/en/discover-plugins#install-plugins>) activate in the current session when it’s safe to do so; the install summary reports `Plugin is now active.` or tells you to run `/reload-plugins` + +[Background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) that changed code in a worktree now commit and push before finishing, open a draft pull request only when the task calls for one, and follow the git instructions in your `CLAUDE.md` + +The 200-subagent-per-session cap is removed, so long-running sessions no longer refuse new subagents; the [concurrency](</docs/en/sub-agents#concurrent-subagent-limit>) and depth limits still apply + +A repository’s checked-in settings can no longer turn on [Remote Control auto-connect](</docs/en/remote-control#enable-remote-control-for-all-sessions>); set `remoteControlAtStartup` in your user or managed settings instead, and project and local settings can only turn it off + +[Worktree isolation](</docs/en/worktrees#how-claude-code-enforces-isolation>) now blocks not only file edits but also Bash commands and git redirects that reach the main checkout, in every session type and in the session’s subagents + +A Bash command can no longer hide part of itself from permission checks, and tab or invisible-Unicode padding no longer hides part of a command from the approval dialog + +PreToolUse auto-allow hooks no longer bypass tool restrictions in Claude Code’s internal side tasks such as summaries and compaction + +The [Ultraplan](</docs/en/ultraplan>) research preview is removed, including the `/ultraplan` command and the `ultraplan` keyword; use plan mode or Claude Code on the web instead + +[Full changelog for v2.1.220–v2.1.224 →](</docs/en/changelog#2-1-220>)
modified How the agent loop works View current →
--- a/agent-loop.md +++ b/agent-loop.md @@ -190,7 +190,7 @@ Max turns (`max_turns` / `maxTurns`)| Maximum tool-use round trips| No limit Max budget (`max_budget_usd` / `maxBudgetUsd`)| Maximum cost before stopping| No limit -When either limit is hit, the SDK returns a `ResultMessage` with a corresponding error subtype (`error_max_turns` or `error_max_budget_usd`). See Handle the result for how to check these subtypes and [`ClaudeAgentOptions`](</docs/en/agent-sdk/python#claudeagentoptions>) / [`Options`](</docs/en/agent-sdk/typescript#options>) for syntax. The budget cap covers [subagents](</docs/en/agent-sdk/subagents>): their spend counts toward the total. Once spend reaches the cap, spawning another subagent fails with `Budget limit reached`, and Claude Code stops any background subagents still running. The cap-enforcement behaviors require Claude Code v2.1.217 or later. With [streaming input](</docs/en/agent-sdk/streaming-vs-single-mode>), a message you send while a turn is still running stays queued when that turn ends at the max-turns limit, and it starts its own turn with its own max-turns limit. Before v2.1.205, a message that arrived on the turn’s final iteration could be consumed into the ending turn and lost without ever reaching the model. +When either limit is hit, the SDK returns a `ResultMessage` with a corresponding error subtype (`error_max_turns` or `error_max_budget_usd`). See Handle the result for how to check these subtypes and [`ClaudeAgentOptions`](</docs/en/agent-sdk/python#claudeagentoptions>) / [`Options`](</docs/en/agent-sdk/typescript#options>) for syntax. The budget cap covers [subagents](</docs/en/agent-sdk/subagents>): their spend counts toward the total. Once spend reaches the cap, spawning another subagent fails with `Budget limit reached`, and Claude Code stops any background subagents still running. The cap-enforcement behaviors require Claude Code v2.1.217 or later. With [streaming input](</docs/en/agent-sdk/streaming-vs-single-mode>), a message you send while a turn is still running stays queued when that turn ends at the max-turns limit, and it starts its own turn with its own max-turns limit. ###
modified Run agents in parallel View current →
--- a/agents.md +++ b/agents.md @@ -10,7 +10,7 @@ In every approach the workers are Claude sessions. To involve a different tool, expose it to Claude as an [MCP server](</docs/en/mcp>). Three more tools support this work without being a way to run agents themselves: * [Worktrees](</docs/en/worktrees>) give each session a separate git checkout, so parallel sessions never edit the same files. Use them for sessions you run yourself. Agent view moves each dispatched session into its own worktree automatically, and subagents you spawn can each get one too. - * [Cross-session messaging](</docs/en/cross-session-messaging>) lets Claude list your other Claude Code sessions and message them on this machine, or reply to your sessions on other machines or on [Claude Code on the web](</docs/en/claude-code-on-the-web>), so sessions you run yourself can pass findings and status between themselves. + * [Cross-session messaging](</docs/en/cross-session-messaging>) lets Claude list and message your other Claude Code sessions on this machine, on another machine, or on [Claude Code on the web](</docs/en/claude-code-on-the-web>), so sessions you run yourself can pass findings and status between themselves. * [`/batch`](</docs/en/commands>) is a [skill](</docs/en/skills>) that has Claude split one large change into 5 to 30 worktree-isolated subagents that each open a pull request. It’s a packaged use of subagents and worktrees, not a separate coordination style. A few other features run Claude without you driving each step, but they solve a different problem than splitting work across agents:
modified Claude Code changelog View current →
--- a/changelog.md +++ b/changelog.md @@ -1,4 +1,16 @@ This page is generated from the [CHANGELOG.md on GitHub](<https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md>). Run `claude --version` to check your installed version. + +​ + +2.1.227 + +August 10, 2026 + + * Fixed feature flags being evaluated without the user’s subscription tier when a session started with an expired login token, which could wrongly prompt Max plan users to enable usage credits for Fable + * Fixed every Bash command failing under `claude-code-action` with `allowed_non_write_users` on GitHub-hosted runners + * Fixed `/tui` bringing back a conversation that had been rewound to before its first message + * Improved slash-command menu: blue now marks only the selected row, matched characters are bolded instead of recolored, and emoji or accented names keep their glyphs + * Improved performance: fewer event-loop stalls on file-not-found suggestions and at-mention size checks ​
modified Claude apps gateway configuration View current →
--- a/claude-apps-gateway-config.md +++ b/claude-apps-gateway-config.md @@ -84,8 +84,17 @@ `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/`. +`use_proxy`| No| Send the gateway’s own IdP requests through the forward proxy in `HTTPS_PROXY` or `HTTP_PROXY`, honoring `NO_PROXY`. Unset or `false`, those requests go direct. Requires v2.1.227 or later; see IdP requests through a forward proxy below. `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| The PEM-encoded CA certificate itself, not a path to a file. It replaces the system trust store for IdP requests only. To load a mounted file, write `${file:/etc/gateway/idp-ca.pem}`. Use for Keycloak or Dex behind corporate PKI. + +#### + +​ + +IdP requests through a forward proxy + +The inference upstreams honor `HTTPS_PROXY` and `HTTP_PROXY` on every version. The gateway’s own requests to the IdP, discovery, JWKS, token, and userinfo, go direct unless you set `oidc.use_proxy: true`, which requires v2.1.227 or later. When a proxy variable is set, `use_proxy` is unset, and the issuer isn’t covered by `NO_PROXY`, the gateway keeps those requests direct and logs a notice at boot asking you to choose; `use_proxy: false` keeps them direct and silences the notice. With `use_proxy: true`, the pod resolves each IdP endpoint’s hostname itself and asks the proxy to `CONNECT` to the resolved IP address, so the proxy must accept `CONNECT` to the IP address of every host the discovery document names, not only the issuer. Use an `http://` proxy URL. `ca_cert_pem` and the [SSRF guard](</docs/en/claude-apps-gateway-deploy#threat-model-summary>) apply on the proxied path as well. ###
modified Claude apps gateway deployment and operations View current →
--- a/claude-apps-gateway-deploy.md +++ b/claude-apps-gateway-deploy.md @@ -278,7 +278,7 @@ 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 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. If the pod reaches the IdP only through a forward proxy, set [`oidc.use_proxy: true`](</docs/en/claude-apps-gateway-config#idp-requests-through-a-forward-proxy>); on versions before v2.1.227, give the pod a direct route to each of the IdP’s endpoints instead. Boot exits with a Postgres permission error| The database role lacks DDL rights on its schema| Grant the role `CREATE` on the gateway’s schema so it can create and alter its tables at boot `/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`.
modified Claude apps gateway spend limits View current →
--- a/claude-apps-gateway-spend-limits.md +++ b/claude-apps-gateway-spend-limits.md @@ -45,7 +45,7 @@ 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. Caps reset on UTC calendar boundaries: daily at 00:00 UTC, weekly at 00:00 UTC on Monday, and monthly at 00:00 UTC on the first of the month. `/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 Amazon 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, Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry ID forms, such as Bedrock’s `us.anthropic.…-v1:0` and Agent Platform’s `claude-…@date`. The meter resolves each request’s rate tier in order: +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. Caps reset on UTC calendar boundaries: daily at 00:00 UTC, weekly at 00:00 UTC on Monday, and monthly at 00:00 UTC on the first of the month. `/v1/messages/count_tokens` is exempt. Token counting is free, so it runs regardless of cap state. A running gateway serves a protocol description at `<public_url>/protocol` that lists the exact usage-limit response headers and the shape of the blocked `429`. Requires v2.1.227 or later. 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 Amazon 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, Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry ID forms, such as Bedrock’s `us.anthropic.…-v1:0` and Agent Platform’s `claude-…@date`. The meter resolves each request’s rate tier in order: 1. Exact rates for the upstream model ID, the model string the gateway sends to the provider. When the table recognizes it, such as `us.anthropic.claude-…`, the meter prices the request by the model that served it. 2. Rates for the configured [`models[].id`](</docs/en/claude-apps-gateway-config#models>) you mapped to the upstream ID. This step covers upstream strings that carry no model name, such as an Amazon Bedrock application-inference-profile ARN or a Microsoft Foundry deployment name, and requires Claude Code v2.1.218 or later on the gateway server.
modified Use Claude Code features in the SDK View current →
--- a/claude-code-features.md +++ b/claude-code-features.md @@ -65,7 +65,7 @@ `"user"`| User CLAUDE.md, `~/.claude/rules/*.md`, user skills, user settings| `~/.claude/` `"local"`| CLAUDE.local.md, `.claude/settings.local.json`| `<cwd>/.claude/` for `settings.local.json`; `<cwd>` and every parent directory for CLAUDE.local.md -Omitting `settingSources` is equivalent to `["user", "project", "local"]`. The `cwd` option determines where the SDK looks for project-level inputs. CLAUDE.md and rules load from `<cwd>` and from every parent directory. Skills load from `<cwd>` and from every parent directory up to the repository root. Project `settings.json` and hooks load only from `<cwd>/.claude/` with no parent-directory fallback. +Omitting `settingSources` is equivalent to `["user", "project", "local"]`. The `cwd` option determines where the SDK looks for project-level inputs. Project `settings.json` and hooks load only from `<cwd>/.claude/` with no parent-directory fallback. ### @@ -164,8 +164,6 @@ Skills must be created as filesystem artifacts (`.claude/skills/<name>/SKILL.md`). The SDK does not have a programmatic API for registering skills. See [Agent Skills in the SDK](</docs/en/agent-sdk/skills>) for full details. -For more on creating and using skills, see [Agent Skills in the SDK](</docs/en/agent-sdk/skills>). - ## ​ @@ -177,7 +175,7 @@ * **Filesystem hooks:** shell commands defined in `settings.json`, loaded when `settingSources` includes the relevant source. These are the same hooks you’d configure for [interactive Claude Code sessions](</docs/en/hooks-guide>). * **Programmatic hooks:** callback functions passed directly to `query()`. These run in your application process and can return structured decisions. See [Control execution with hooks](</docs/en/agent-sdk/hooks>). -Both types execute during the same hook lifecycle. If you already have hooks in your project’s `.claude/settings.json` and you set `settingSources: ["project"]`, those hooks run automatically in the SDK with no extra configuration. Hook callbacks receive the tool input and return a decision dict. Returning `{}` means allow the tool to proceed. To block execution, return a `hookSpecificOutput` object with `permissionDecision: "deny"` and a `permissionDecisionReason`. The reason is sent to Claude as the tool result. The top-level `decision` and `reason` fields are deprecated for `PreToolUse`. See the [hooks guide](</docs/en/agent-sdk/hooks>) for the full callback signature and return types. +Both types execute during the same hook lifecycle. If you already have hooks in your project’s `.claude/settings.json` and you set `settingSources: ["project"]`, those hooks run automatically in the SDK with no extra configuration. Hook callbacks receive the tool input and return a decision dict. Returning `{}` means allow the tool to proceed. To block execution, return a `hookSpecificOutput` object with `permissionDecision: "deny"` and a `permissionDecisionReason`. The reason is sent to Claude as the tool result. See the [hooks guide](</docs/en/agent-sdk/hooks>) for the full callback signature and return types. Python
modified Claude Tag View current →
--- a/claude-tag.md +++ b/claude-tag.md @@ -1 +1 @@ -Claude Tag is a Slack integration that runs `@Claude` in your team’s channels as your organization’s shared identity with admin-configured access. Anyone in a channel can tag `@Claude` into a thread and assign it a task. Read the [Claude Tag documentation](<https://claude.com/docs/claude-tag/overview>) on claude.com to set it up and start using it. Claude Tag is available on Team and Enterprise plans, and is distinct from the earlier [Claude Code in Slack](</docs/en/slack>), which runs each session under an individual user’s account. On Pro and Max plans, where Claude Tag isn’t available, Claude Code in Slack remains the setup path. +[Claude Tag](<https://claude.com/product/tag>) is a Slack integration that runs `@Claude` in your team’s channels as your organization’s shared identity with admin-configured access. Anyone in a channel can tag `@Claude` into a thread and assign it a task. Read the [Claude Tag documentation](<https://claude.com/docs/claude-tag/overview>) on claude.com to set it up and start using it. Claude Tag is available on Team and Enterprise plans, and is distinct from the earlier [Claude Code in Slack](</docs/en/slack>), which runs each session under an individual user’s account. On Pro and Max plans, where Claude Tag isn’t available, Claude Code in Slack remains the setup path.
modified Explore the context window View current →
--- a/context-window.md +++ b/context-window.md @@ -66,11 +66,13 @@ * A `k` or `M` suffix, such as `500k` or `1M` * A bare number from 100 to 1000, meaning thousands, so `200` sets 200,000 -The environment variable accepts only the plain token count. Claude Code caps the window at the model’s context window. With no window size set in any of these places, Claude Code compacts when the conversation reaches the model’s context limit, except in these sessions, which compact earlier: +The environment variable accepts only the plain token count. Claude Code caps the window at the model’s context window. With no window size set in any of these places, Claude Code compacts when the conversation reaches the model’s context limit, except in these sessions: * [Cloud sessions](</docs/en/claude-code-on-the-web>) compact as the conversation approaches the model’s limit * Sonnet 4.6 and Opus 4.6 without [extended context](</docs/en/model-config#extended-context>) compact at the 200K boundary, and so do Opus 4.8 and Opus 5 when they run with a 200K context window, such as on Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry - * Sonnet 5 compacts at the model’s [default threshold](</docs/en/model-config#sonnet-5-context-window>) + * When you set [`CLAUDE_CODE_DISABLE_1M_CONTEXT=1`](</docs/en/env-vars>), models with a native 1M window, such as Sonnet 5 and Fable 5, compact at the 200K boundary. Before v2.1.223, Claude Code held only Sonnet 5, Opus 4.8, and Opus 5 sessions to 200K + * Sonnet 5 compacts at the [threshold for its configuration](</docs/en/model-config#sonnet-5-context-window>) + * Sessions on a model ID Claude Code doesn’t recognize, such as an [LLM gateway](</docs/en/llm-gateway>) alias, compact at the context window Claude Code assumes for the ID. If the ID doesn’t start with `claude-`, set [`CLAUDE_CODE_MAX_CONTEXT_TOKENS`](</docs/en/env-vars>) to correct the assumed window while keeping proactive compaction. Set [`CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT=1`](</docs/en/env-vars>) to have Claude Code compact only after the API rejects the conversation with Anthropic’s too-long error; that recovery doesn’t run when a gateway [rewrites the error](</docs/en/llm-gateway-connect#troubleshoot-gateway-errors>) ##
modified Manage costs effectively View current →
--- a/costs.md +++ b/costs.md @@ -56,8 +56,8 @@ Your role| What `/usage-credits` does ---|--- -Pro or Max subscriber| Opens your billing settings in the browser -Team or Enterprise member with billing access| Opens your organization’s usage settings in the browser +Pro or Max subscriber| Opens [**Settings > Usage**](<https://claude.ai/settings/usage>) on claude.ai in the browser. In its **Usage credits** section you can turn usage credits on or off and check your credit balance, this month’s spend, and your monthly spend limit +Team or Enterprise member with billing access| Opens your organization’s usage settings, [**Admin settings > Usage**](<https://claude.ai/admin-settings/usage>), in the browser Team or Enterprise member without billing access| Asks you to confirm, then sends a request to your organization’s admins. Before v2.1.211, Claude Code sent the request without a confirmation step For Team and Enterprise members without billing access, the confirmation appears only in interactive sessions: in non-interactive mode with the `-p` flag and from [Remote Control](</docs/en/remote-control>), the command sends no request and tells you to run it in an interactive session instead. If you run `/usage-credits` again while your earlier request is waiting on an admin, Claude Code tells you a request has already been sent rather than sending a duplicate. After an admin dismisses your request, running the command again sends a new one. Before v2.1.222, a dismissed request also blocked new requests. On Pro and Max plans, when you reach your spend limit with usage credits still available, Claude Code prompts you to raise or remove the limit without leaving the CLI. If the server rejects the change, see [Could not update your spend limit](</docs/en/errors#could-not-update-your-spend-limit>). @@ -68,7 +68,7 @@ Manage costs for your organization -Which controls you have depends on how your organization accesses Claude Code: a Claude for Teams or Enterprise plan, the Claude Console, or a cloud provider. On Teams and Enterprise plans, usage draws from each member’s seat allowance. On the Console and on cloud providers, usage is billed per token to your organization. If your organization mixes sign-in methods, each developer is metered according to the one they authenticated with. The table maps each setup to where you see spend, where you cap it, and how you pull per-user numbers. +Which controls you have depends on how your organization accesses Claude Code: a Claude for Teams or Enterprise plan, the Claude Console, or a cloud provider. On Teams and Enterprise plans, usage draws from each member’s seat allowance. On the Console and on cloud providers, usage is billed per token to your organization. If your organization mixes sign-in methods, each developer is metered according to the one they authenticated with. The table maps each setup to where you see spend, where you cap it, and how you pull per-user numbers. On an individual Pro or Max plan you have no organization to manage, so track your own usage-credit spend, including [fast mode](</docs/en/fast-mode#see-where-fast-mode-spend-appears>), under Add usage credits to your subscription. Your setup| See spend| Cap spend| Per-user reporting ---|---|---|---
modified Message your other Claude Code sessions View current →
--- a/cross-session-messaging.md +++ b/cross-session-messaging.md @@ -13,7 +13,7 @@ * **Hand over a finding** : when one session discovers a breaking change or makes a decision, Claude summarizes it for the session working on the affected area, instead of you re-explaining it there. * **Coordinate parallel worktrees** : when sessions work the same repository in separate [worktrees](</docs/en/worktrees>), Claude can tell the other sessions what landed. * **Get status from long-running work** : have a migration or test run report back to the session you’re watching, or ask it yourself from there. - * **Reply across machines** : answer a message that arrived from one of your sessions on another machine or on the web. Across machines, Claude can only reply. It can’t start the exchange. + * **Message across machines** : reach one of your sessions on another machine or on the web. Use messaging between independent sessions that you start and steer yourself. Claude Code has a dedicated feature for each of the other ways to run or reach multiple sessions, so use the one built for what you’re doing instead: @@ -63,9 +63,10 @@ * **Subagents** : agents running inside the current session. [Agent team](</docs/en/agent-teams>) teammates aren’t listed; Claude messages them through the team’s own roster. * **Your other local sessions** : Claude Code sessions running on the same machine, including [background sessions](</docs/en/agent-view>). A session appears only when it binds an inbox socket. - * **Sessions beyond this machine** : shown while [Remote Control](</docs/en/remote-control>) is connected and labeled `Remote Control`. These are your sessions on other machines and your [Claude Code on the web](</docs/en/claude-code-on-the-web>) sessions. Claude can’t send a message to start a conversation with one of these sessions. It can only reply to a message that arrived from one of them. See Message sessions on other machines. - -A session answers to the name you set with the [`/rename`](</docs/en/commands>) command or the [`--name`](</docs/en/cli-reference#cli-flags>) flag. When you don’t set one, Claude Code names the session itself. An interactive session gets a name derived from its working directory’s folder name, such as `myapp-3f`. Two sessions can end up with the same name. The `/list-agents` output shows each local session’s working directory, which tells same-named sessions apart when they run in different directories. Claude’s own listing adds a short identifier to each row and uses it in the address when names collide. + * **Your cloud sessions** : your [Claude Code on the web](</docs/en/claude-code-on-the-web>) sessions. These appear when this session has cloud access: a claude.ai login on the first-party Anthropic API and an organization policy that allows cloud sessions. + * **Your Remote Control sessions on other machines** : shown while this session is connected to [Remote Control](</docs/en/remote-control>), and labeled `Remote Control`. + +Claude addresses a session beyond this machine by name, the same as a local session. See Message sessions on other machines for how those messages travel. A session answers to the name you set with the [`/rename`](</docs/en/commands>) command or the [`--name`](</docs/en/cli-reference#cli-flags>) flag. When you don’t set one, Claude Code names the session itself. An interactive session gets a name derived from its working directory’s folder name, such as `myapp-3f`. Two sessions can end up with the same name. The `/list-agents` output shows each local session’s working directory, which tells same-named sessions apart when they run in different directories. Claude’s own listing adds a short identifier to each row and uses it in the address when names collide. ### @@ -73,15 +74,15 @@ Message sessions on other machines -Where the other session runs decides how a message travels and what Claude here can send: - -Where the other session runs| How the message travels| What Claude here can send ----|---|--- -On this machine| Over a per-session socket, never through Anthropic servers| New messages and replies -On another of your machines| Through Anthropic servers, arriving over that machine’s [Remote Control](</docs/en/remote-control>) connection| Replies only -On [Claude Code on the web](</docs/en/claude-code-on-the-web>)| Through Anthropic servers, straight to the cloud session| Replies only - -Same-machine delivery works wherever the feature is enabled. Each session registers itself in files on disk and binds its inbox socket there. When Claude lists or messages your local sessions, Claude Code reads those files to find them, so two sessions can reach each other only when they can see the same files. A container has its own filesystem, so a session inside it and a session on the host can’t reach each other. Two sessions inside the same container can still message each other, including on a [self-hosted runner](</docs/en/self-hosted-environments>). A reply needs a reply address, and almost every message carries one. A reply to a session beyond this machine, sent while the replying session isn’t connected to Remote Control, still goes through as a direct request to Anthropic servers, but it arrives without a reply address, so the receiver can’t answer it. Claude is told as much when it sends. To require your approval before any message goes beyond this machine, set `isolatePeerMachines`. +How a message travels, and whether it passes through Anthropic servers, depends on where the target session runs: + +Where the other session runs| How the message travels +---|--- +On this machine| Over a per-session socket, never through Anthropic servers +On another of your machines| Through Anthropic servers, arriving over that machine’s [Remote Control](</docs/en/remote-control>) connection +On [Claude Code on the web](</docs/en/claude-code-on-the-web>)| Through Anthropic servers, straight to the cloud session + +Starting a conversation with a session on another of your machines requires Claude Code v2.1.225 or later and a target that appears in the listing. Before v2.1.225, Claude could only reply to a message that arrived from one. Same-machine delivery works wherever the feature is enabled. Each session registers itself in files on disk and binds its inbox socket there. When Claude lists or messages your local sessions, Claude Code reads those files to find them, so two sessions can reach each other only when they can see the same files. A container has its own filesystem, so a session inside it and a session on the host can’t reach each other. Two sessions inside the same container can still message each other, including on a [self-hosted runner](</docs/en/self-hosted-environments>). A reply needs a reply address, and almost every message carries one. A message to a session beyond this machine, sent while the sending session isn’t connected to Remote Control, still goes through as a direct request to Anthropic servers, but it arrives without a reply address, so the receiver can’t answer it. Claude is told as much when it sends. To require your approval before any message goes beyond this machine, set `isolatePeerMachines`. ## @@ -102,7 +103,7 @@ What a message looks like -When the message arrives, it appears in the conversation with its sender, queued while Claude is mid-turn or starting a new turn right away when the session is idle. Once Claude has read it, Claude Code collapses it to a one-line `Message from` row, which `Ctrl+O` expands. A message is a piece of text one Claude writes to another. Claude receives it with the sender’s name and a reply address, except for a one-way cross-machine reply, which carries no reply address. You see the name and the text, and the receiving session gets only that text, never the sender’s conversation history or files. This example is a message one Claude wrote to another, as the receiving session sees it: +When the message arrives, it appears in the conversation with its sender, queued while Claude is mid-turn or starting a new turn right away when the session is idle. Once Claude has read it, Claude Code collapses it to a one-line `Message from` row, which `Ctrl+O` expands. A message is a piece of text one Claude writes to another. Claude receives it with the sender’s name and a reply address, except for a one-way cross-machine message, which carries no reply address. You see the name and the text, and the receiving session gets only that text, never the sender’s conversation history or files. This example is a message one Claude wrote to another, as the receiving session sees it: Schema migration finished: the new column is tenant_id, and rebasing on main is safe now. @@ -141,7 +142,7 @@ Non-interactive sessions -Claude Code binds an inbox socket for a [`claude -p`](</docs/en/headless>) session like an interactive one, so a long-running `-p` worker can receive messages and appears in the listing. When you start a session in [bare mode](</docs/en/headless#start-faster-with-bare-mode>), Claude Code doesn’t bind the socket, so that session can’t receive messages and doesn’t appear in the agent list. A `-p` session can’t show the approval dialog. A held message stays held there. Claude Code delivers it only if a later mode or settings change allows it, under the same rules as above. To let a `-p` worker take messages unattended, start it with `crossSessionInbound` set to `accept` in its `--settings` value. An `accept` in your user settings also works but applies to every session you run. +Claude Code binds an inbox socket for a [`claude -p`](</docs/en/headless>) session like an interactive one, so a long-running `-p` worker can receive messages and appears in the listing. When you start a session in [bare mode](</docs/en/headless#start-faster-with-bare-mode>), Claude Code doesn’t bind the socket, so that session can’t receive messages and doesn’t appear in the agent list. A `-p` session can’t show the approval dialog. When the inbound default holds a message there, Claude Code delivers it if a later mode or settings change allows it, and otherwise drops it when the [`dialogExpiry`](</docs/en/settings#available-settings>) deadline passes and reports the expiry to the sender. Before v2.1.225, a held message stayed held in a `-p` session, with no sender notice and no expiry. To let a `-p` worker take messages unattended, start it with `crossSessionInbound` set to `accept` in its `--settings` value. An `accept` in your user settings also works but applies to every session you run. ### @@ -179,7 +180,7 @@ "isolatePeerMachines": true } -With this set, Claude Code asks for your approval before Claude’s reply to a session beyond this machine leaves, even in `bypassPermissions` mode, which skips ordinary permission prompts. A `true` from any settings scope applies, so a checked-in project file can turn the requirement on but not off. Messages between sessions on the same machine don’t prompt. +With this set, Claude Code asks for your approval before Claude’s message to a session beyond this machine leaves, even in `bypassPermissions` mode, which skips ordinary permission prompts. A `true` from any settings scope applies, so a checked-in project file can turn the requirement on but not off. Messages between sessions on the same machine don’t prompt. ### @@ -218,7 +219,12 @@ To check a session, type `/list-agents`, also available as `/peers`. The result separates a session that doesn’t have the feature from a session where something narrower blocked a message, such as a missing `SendMessage` tool or a refused send: * **`/list-agents` isn’t recognized**: the session doesn’t have cross-session messaging. Work through the requirements above, starting with `claude --version` for the version requirement. - * **`/list-agents` works but a send didn’t arrive**: messaging is on, and something narrower applies. A permission deny rule removes the `SendMessage` and `ListAgents` tools, the receiving session’s inbound controls can hold or drop what you send it, and a session beyond this machine is reply-only. + * **`/list-agents` works but a send didn’t arrive**: messaging is on, and something narrower applies: + * **Deny rules** : a permission deny rule removes the `SendMessage` and `ListAgents` tools. + * **Inbound controls** : the receiving session’s inbound controls can hold or drop what you send it. + * **Cloud session missing** : a cloud session appears only when this session has cloud access. + * **Other-machine session missing** : a session on another of your machines appears only when it runs with [Remote Control](</docs/en/remote-control>) and this session is connected as well. + * **Starting a conversation** : Message sessions on other machines covers starting a conversation with a session beyond this machine. In a session with messaging, `/status` also shows a `Peer address` row with the session’s own inbox address. @@ -241,7 +247,7 @@ * [Subagents](</docs/en/sub-agents#resume-subagents>) and [agent teams](</docs/en/agent-teams#messages-between-agents>): messaging within a single session or team * [Background agents](</docs/en/agent-view>): dispatch and monitor the parallel sessions you might message - * [Remote Control](</docs/en/remote-control>): connect the sessions that cross-machine messaging travels through + * [Remote Control](</docs/en/remote-control>): connect this session to reach your sessions on other machines * [Settings](</docs/en/settings#available-settings>): `crossSessionInbound`, `isolatePeerMachines`, and `dialogExpiry` * [Permission modes](</docs/en/permission-modes>): the modes behind the inbound default’s two classes * [Tools reference](</docs/en/tools-reference>): the `ListAgents` and `SendMessage` rows in the tools table
modified Give Claude custom tools View current →
--- a/custom-tools.md +++ b/custom-tools.md @@ -1,4 +1,4 @@ -Custom tools extend the Agent SDK by letting you define your own functions that Claude can call during a conversation. Using the SDK’s in-process MCP server, you can give Claude access to databases, external APIs, domain-specific logic, or any other capability your application needs. This guide covers how to define tools with input schemas and handlers, bundle them into an MCP server, pass them to `query`, and control which tools Claude can access. It also covers error handling, tool annotations, and returning non-text content like images. +Custom tools extend the Agent SDK by letting you define your own functions that Claude can call during a conversation. Using the SDK’s in-process MCP server, you can give Claude access to databases, external APIs, domain-specific logic, or any other capability your application needs. ##
modified Desktop application View current →
--- a/desktop.md +++ b/desktop.md @@ -392,7 +392,7 @@ Work across sessions -Claude can list your other Code tab sessions, read what each has been doing, and send messages between them. Ask in plain language: “which session touched the auth refactor?”, “what did the API session conclude?”, or “tell the payments session the schema changed”. You can also ask Claude to rename or archive a session. Claude archives a session the same way the sidebar’s archive icon does, so ask it to clean up sessions whose PRs have merged. Through this surface, Claude sees only the sessions the desktop app runs itself: local, SSH, and [WSL](</docs/en/desktop-wsl>) sessions in the Code tab. Claude doesn’t see cloud sessions, or sessions you started from the terminal CLI or the VS Code extension, even in worktrees of the same project, so with nine terminal worktrees open and two desktop sessions, Claude answering in one of them reports the one other desktop session. Claude never lists the session you’re asking from. By default it sees the 20 most recently active sessions and skips archived sessions unless you ask for them. In sessions where [cross-session messaging](</docs/en/cross-session-messaging>) is enabled, Claude can separately list and message your other Claude Code sessions on the machine, including terminal sessions. When Claude messages another session through this surface, Claude Code shows it there as a card labeled with the sending session’s title and a link back, so you can always tell where a message came from. If the receiving session is mid-task, Claude Code holds the message and Claude reads it once the current work finishes. Claude can’t deliver to an archived session, and tells you when a message doesn’t go through. Claude Code applies three safety behaviors across sessions: +Claude can list your other Code tab sessions, read what each has been doing, and send messages between them. Ask in plain language: “which session touched the auth refactor?”, “what did the API session conclude?”, or “tell the payments session the schema changed”. You can also ask Claude to rename or archive a session. Claude archives a session the same way the sidebar’s archive icon does, so ask it to clean up sessions whose PRs have merged. Through this surface, Claude sees only the sessions the desktop app runs itself: local, SSH, and [WSL](</docs/en/desktop-wsl>) sessions in the Code tab. Claude doesn’t see cloud sessions, or sessions you started from the terminal CLI or the VS Code extension, even in worktrees of the same project, so with nine terminal worktrees open and two desktop sessions, Claude answering in one of them reports the one other desktop session. Claude never lists the session you’re asking from. By default it sees the 20 most recently active sessions and skips archived sessions unless you ask for them. [Cross-session messaging](</docs/en/cross-session-messaging>) separately lets Claude message [your other Claude Code sessions](</docs/en/cross-session-messaging#see-which-sessions-claude-can-reach>), including terminal sessions. When Claude messages another session through this surface, Claude Code shows it there as a card labeled with the sending session’s title and a link back, so you can always tell where a message came from. If the receiving session is mid-task, Claude Code holds the message and Claude reads it once the current work finishes. Claude can’t deliver to an archived session, and tells you when a message doesn’t go through. Claude Code applies three safety behaviors across sessions: * Before archiving any session, Claude asks you first. You see the approval card in every permission mode, including Auto and Bypass permissions. * Through this surface, Claude can’t send cross-session messages from a session nobody is watching, such as a scheduled-task run, and can’t deliver messages into one.
modified Test iOS apps in the simulator View current →
--- a/desktop-ios-simulator.md +++ b/desktop-ios-simulator.md @@ -1,4 +1,4 @@ -The iOS Simulator pane is in public beta in Claude Code Desktop on macOS. It’s available on Pro, Max, and Team plans, and not available on the Enterprise plan. +The iOS Simulator pane is in public beta in Claude Code Desktop on macOS. It’s available on Pro, Max, Team, and Enterprise plans. The iOS Simulator pane shows your app running in Apple’s iOS Simulator next to your conversation in Claude Code Desktop. When Claude builds, installs, launches, or checks your app in a simulator, the pane opens automatically and streams the device screen live. Use it to watch Claude run and test your app, or to tap through the app yourself while Claude keeps working. The simulator pane drives the simulator directly, so it doesn’t need [computer use](</docs/en/desktop#let-claude-use-your-computer>) and never takes over your screen or hides your other windows. From the CLI, Claude reaches the iOS Simulator through [computer use](</docs/en/computer-use#test-a-simulator-flow>) instead, which controls the simulator on your screen the same way you would with a mouse.
modified Environment variables View current →
--- a/env-vars.md +++ b/env-vars.md @@ -330,7 +330,7 @@ `CLAUDE_CODE_TEAM_TEARDOWN_PARK_TIMEOUT_MS`| Override, in milliseconds, how long a non-interactive session waits at exit for its [agent team](</docs/en/agent-teams>) to finish tearing down. Accepts 1000 to 60000; an out-of-range value is ignored and the default of 10000 applies. Requires Claude Code v2.1.206 or later `CLAUDE_CODE_TMPDIR`| Override the temp directory used for internal temp files. Claude Code appends `/claude-{uid}/` on Unix or `/claude/` on Windows to this path. Default: `/tmp` on macOS, `os.tmpdir()` on Linux and Windows. As of v2.1.161, on macOS and Linux, [sandboxed](</docs/en/sandboxing>) Bash subprocesses receive a short fallback `$TMPDIR` under the system default when your override is a long path, since some tools fail when temp paths get too long. Unsandboxed Bash commands inherit your shell’s `$TMPDIR` unchanged. Claude Code’s own temp files always use your override `CLAUDE_CODE_TMUX_TRUECOLOR`| Set to any non-empty value, such as `1`, to allow 24-bit truecolor output inside tmux. **Setting it to`0` or `false` still allows truecolor**, unlike most on/off variables; unset the variable to restore the 256-color clamp. By default, Claude Code clamps to 256 colors when `$TMUX` is set because tmux does not pass through truecolor escape sequences unless configured to. Set this after adding `set -ga terminal-overrides ',*:Tc'` to your `~/.tmux.conf`. See [Terminal configuration](</docs/en/terminal-config>) for other tmux settings -`CLAUDE_CODE_USER_DIALOG_TIMEOUT_MS`| Deadline in milliseconds for dialogs Claude Code forwards to a remote client, such as a [Remote Control](</docs/en/remote-control>) or SDK host, and for the approval dialog for a [held cross-session message](</docs/en/cross-session-messaging#control-inbound-messages>), before Claude Code cancels them; permission prompts and `AskUserQuestion` questions use their own flows and aren’t governed by it. Overrides the [`dialogExpiry`](</docs/en/settings#available-settings>) setting; `0` or a negative value disables the deadline +`CLAUDE_CODE_USER_DIALOG_TIMEOUT_MS`| Deadline in milliseconds for dialogs Claude Code forwards to a remote client, such as a [Remote Control](</docs/en/remote-control>) or SDK host, and for a [held cross-session message](</docs/en/cross-session-messaging#control-inbound-messages>) awaiting approval, before Claude Code cancels the dialog or drops the default-held message; permission prompts and `AskUserQuestion` questions use their own flows and aren’t governed by it. Overrides the [`dialogExpiry`](</docs/en/settings#available-settings>) setting; `0` or a negative value disables the deadline `CLAUDE_CODE_USE_ANTHROPIC_AWS`| Use [Claude Platform on AWS](</docs/en/claude-platform-on-aws>) `CLAUDE_CODE_USE_BEDROCK`| Use [Amazon Bedrock](</docs/en/amazon-bedrock>) `CLAUDE_CODE_USE_FOUNDRY`| Use [Microsoft Foundry](</docs/en/microsoft-foundry>) @@ -348,7 +348,7 @@ `CLAUDE_PID`| Claude Code sets this to its own process ID in the subprocesses it spawns: Bash and PowerShell tool commands and hook commands. On Linux, the Bash tool’s shell integration uses it to refuse a `pkill` pattern that would match the Claude Code process itself; see [the error reference](</docs/en/errors#pkill-pattern-matches-the-claude-code-process>). Read it from your own scripts to identify or signal the parent Claude Code process deliberately. Requires Claude Code v2.1.214 or later `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 event- and byte-level streaming idle watchdogs close 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, and the byte-level watchdog caps the value at 30 minutes. `CLAUDE_BYTE_STREAM_IDLE_TIMEOUT_MS` takes precedence over this variable for the byte-level watchdog. For the per-watchdog unset defaults, see [Streaming idle watchdogs](</docs/en/network-config#streaming-idle-watchdogs>) -`CLAUDE_SUBAGENT_BG_SHELL_MAX_MS`| Maximum lifetime in milliseconds for a [background shell command](</docs/en/interactive-mode#background-bash-commands>) that a [subagent](</docs/en/sub-agents>) started, after which Claude Code terminates the command. Default `3600000` (60 minutes). Setting `0` doesn’t disable the cap: Claude Code applies the 60-minute default instead. Claude Code doesn’t apply a lifetime cap to background commands in the main session; `CLAUDE_CODE_DISABLE_BG_SHELL_PRESSURE_REAP` covers the separate memory-pressure limit that applies to them. Requires Claude Code v2.1.133 or later +`CLAUDE_SUBAGENT_BG_SHELL_MAX_MS`| Maximum lifetime in milliseconds for a [background shell command](</docs/en/interactive-mode#background-bash-commands>) that a [subagent](</docs/en/sub-agents>) started. Default `3600000` (60 minutes). When you set `0`, Claude Code applies the default instead of removing the cap. Claude Code doesn’t cap main-session background commands this way; see [How backgrounding works](</docs/en/interactive-mode#how-backgrounding-works>) for the memory-pressure limit that covers them `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. Overrides the [`autoCompactEnabled`](</docs/en/settings#available-settings>) setting
modified Speed up responses with fast mode View current →
--- a/fast-mode.md +++ b/fast-mode.md @@ -55,6 +55,18 @@ Fast mode pricing is flat across the full 1M token context window. For the standard Opus rate to compare against, see the [Claude pricing reference](<https://platform.claude.com/docs/en/about-claude/pricing>). The first time you enable fast mode in a conversation, you pay the full fast mode uncached input token price for the entire conversation context. The deeper into a conversation you are, the more this costs, so enabling fast mode from the start is cheaper. The cost applies once per conversation, so toggling fast mode off and on again later does not repeat it. For the mechanism, see [how fast mode interacts with the prompt cache](</docs/en/prompt-caching#turning-on-fast-mode>). +### + +​ + +See where fast mode spend appears + +You see fast mode spend in a different place depending on how you signed in, so first run [`/status`](</docs/en/commands>) to check. If it shows a `Login method` row such as `Claude Max account`, you signed in with a Claude subscription. If it shows an `API key` row instead, your requests bill to a Claude Console organization. + + * **Pro and Max** : you pay for fast mode from your usage credits. Go to [**Settings > Usage**](<https://claude.ai/settings/usage>) on claude.ai, where the **Usage credits** section shows how much you’ve spent in usage credits this month. That figure includes fast mode but doesn’t break it out separately. + * **Team and Enterprise** : your organization pays for your fast mode usage from its usage credits. For where your organization sees that spend, see [Claude for Teams and Enterprise](</docs/en/costs#claude-for-teams-and-enterprise>). + * **Claude Console** : your organization pays for fast mode with the rest of its API usage. On the Console [Usage](<https://platform.claude.com/usage>) and [Cost](<https://platform.claude.com/cost>) pages, select **Speed (Research Preview)** in the **Group by** menu to separate fast mode from standard-speed usage. You see that option only when the selected date range includes fast mode usage. + ## ​ @@ -97,10 +109,11 @@ Fast mode requires all of the following: * **Anthropic API or subscription only** : fast mode is available through the Anthropic Console API and for Claude subscription plans using usage credits. It is not available on Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or Claude Platform on AWS. - * **Usage credits turned on** : your account must have usage credits turned on, which allows billing beyond your plan’s included usage. For individual accounts, turn this on in your [Console billing settings](<https://platform.claude.com/settings/billing>). For Team and Enterprise, an admin must turn on usage credits for the organization. + * **Usage credits turned on for subscription plans** : on a Pro, Max, Team, or Enterprise plan, your account must have [usage credits](</docs/en/costs#add-usage-credits-to-your-subscription>) turned on, which allows billing beyond your plan’s included usage. Until they’re on, `/fast` shows “Fast mode requires usage credits · /usage-credits to turn them on”. On Pro and Max, turn them on in the **Usage credits** section of [**Settings > Usage**](<https://claude.ai/settings/usage>) on claude.ai, or run `/usage-credits` to open that page. On Team and Enterprise, a member with billing access turns them on for the organization at [**Admin settings > Usage**](<https://claude.ai/admin-settings/usage>), and a member without it runs `/usage-credits` to send the organization’s admins a request. Fast mode usage draws directly from usage credits, even if you have remaining usage on your plan. This means fast mode tokens do not count against your plan’s included usage and are charged at the fast mode rate from the first token. + * **Paid Console organization** : Claude Console accounts don’t use usage credits, and your organization pays for fast mode per token with the rest of its API usage. On the Console’s free Evaluation plan, `/fast` shows “Fast mode unavailable during evaluation. Please purchase credits.” To clear it, purchase credits in your [Console billing settings](<https://platform.claude.com/settings/billing>). * **Owner enablement for Team and Enterprise** : fast mode is disabled by default for Team and Enterprise organizations. An Owner must explicitly enable fast mode before users can access it. If fast mode has not been enabled for your organization, the `/fast` command will show “Fast mode has been disabled by your organization.” If your organization’s [`availableModels`](</docs/en/model-config#restrict-model-selection>) allowlist excludes the fast-mode Opus model, `/fast` is refused with “is not in your organization’s allowed models”. The exception is a session already running on an allowed Opus model that supports fast mode: `/fast` enables fast mode on your current model instead of switching models.
modified Feature availability View current →
--- a/feature-availability.md +++ b/feature-availability.md @@ -91,7 +91,7 @@ 3 Explicit intervals such as `/loop every 2 hours` work on every provider. On Amazon Bedrock, Claude Platform on AWS, Google Cloud’s Agent Platform, and Microsoft Foundry, `/loop` cannot pick its own interval or supply the default maintenance prompt, so a prompt with no interval runs every 10 minutes, and `/loop` with no arguments shows the usage message. See [Scheduled tasks](</docs/en/scheduled-tasks>). 4 Subject to your agreement with the cloud provider. 5 Dashboard and API only. [Contribution metrics](</docs/en/analytics#enable-contribution-metrics>) requires a claude.ai Team or Enterprise organization. -6 Requires Claude Code v2.1.224 or later. WSL 2 counts as Linux; native Windows isn’t supported. Same-machine messaging only, unless the session also meets the [Remote Control requirements](</docs/en/remote-control#requirements>): cross-machine messages travel over Remote Control, which API key authentication doesn’t support. See [Message sessions on other machines](</docs/en/cross-session-messaging#message-sessions-on-other-machines>). +6 Requires Claude Code v2.1.224 or later. WSL 2 counts as Linux; native Windows isn’t supported. With API key authentication, same-machine messaging only. Reaching your [Claude Code on the web](</docs/en/claude-code-on-the-web>) sessions requires [cloud access](</docs/en/cross-session-messaging#see-which-sessions-claude-can-reach>), and reaching your sessions on other machines requires meeting the [Remote Control requirements](</docs/en/remote-control#requirements>); both need a claude.ai sign-in. See [Message sessions on other machines](</docs/en/cross-session-messaging#message-sessions-on-other-machines>). If you authenticate through an [LLM gateway](</docs/en/llm-gateway>), feature availability matches the underlying provider the gateway forwards to. Some Anthropic-only features such as the [Advisor](</docs/en/advisor>) work only if the gateway forwards requests intact to the Anthropic API.
modified Rewind file changes with checkpointing View current →
--- a/file-checkpointing.md +++ b/file-checkpointing.md @@ -12,13 +12,7 @@ How checkpointing works -When you enable file checkpointing, the SDK creates backups of files before modifying them through the Write, Edit, or NotebookEdit tools. User messages in the response stream include a checkpoint UUID that you can use as a restore point. Checkpoint works with these built-in tools that the agent uses to modify files: - -Tool| Description ----|--- -Write| Creates a new file or overwrites an existing file with new content -Edit| Makes targeted edits to specific parts of an existing file -NotebookEdit| Modifies cells in Jupyter notebooks (`.ipynb` files) +When you enable file checkpointing, the SDK creates backups of files before modifying them through the Write, Edit, or NotebookEdit tools. User messages in the response stream include a checkpoint UUID that you can use as a restore point. File rewinding restores files on disk to a previous state. It does not rewind the conversation itself. The conversation history and context remain intact after calling `rewindFiles()` (TypeScript) or `rewind_files()` (Python). @@ -659,13 +653,6 @@ main(); -This example demonstrates the complete checkpointing workflow: - - 1. **Enable checkpointing** : configure the SDK with `enable_file_checkpointing=True` and `permission_mode="acceptEdits"` to auto-approve file edits - 2. **Capture checkpoint data** : as the agent runs, store the first user message UUID (your restore point) and the session ID - 3. **Prompt for rewind** : after the agent finishes, check your utility file to see the doc comments, then decide if you want to undo the changes - 4. **Resume and rewind** : if yes, resume the session with an empty prompt and call `rewind_files()` to restore the original file - 3 Run the example
modified Intercept and control agent behavior with hooks View current →
Show diff (4225 lines)
--- a/hooks.md +++ b/hooks.md @@ -1,3316 +1,918 @@ -For a quickstart guide with examples, see [Automate actions with hooks](</docs/en/hooks-guide>). - -Hooks are user-defined shell commands, HTTP endpoints, or LLM prompts that execute automatically at specific points in Claude Code’s lifecycle. Hooks run wherever Claude Code runs: sessions in the terminal, IDE extensions, the [Desktop app](</docs/en/desktop-quickstart>), and [Claude Code on the web](</docs/en/claude-code-on-the-web>) all fire the same hook events. Use this reference to look up event schemas, configuration options, JSON input/output formats, and advanced features like async hooks, HTTP hooks, and MCP tool hooks. +Hooks are callback functions that run your code in response to agent events, like a tool being called, a session starting, or execution stopping. With hooks, you can: + + * **Block dangerous operations** before they execute, like destructive shell commands or unauthorized file access + * **Log and audit** every tool call for compliance, debugging, or analytics + * **Transform inputs and outputs** to sanitize data, inject credentials, or redirect file paths + * **Require human approval** for sensitive actions like database writes or API calls + * **Track session lifecycle** to manage state, clean up resources, or send notifications ## ​ -Hook lifecycle - -Claude Code runs hooks at specific points during a session. When an event fires and a matcher matches, Claude Code passes JSON context about the event to your hook handler. For command hooks, input arrives on stdin. For HTTP hooks, it arrives as the POST request body. Your handler can then inspect the input, take action, and optionally return a decision. Events fall into three cadences: - - * once per session: `SessionStart` and `SessionEnd` - * once per turn: `UserPromptSubmit`, `Stop`, and `StopFailure` - * on every tool call inside the agentic loop: `PreToolUse` and `PostToolUse`, except [`EndConversation`](</docs/en/tools-reference#endconversation-tool-behavior>) calls, which skip both - -The table below summarizes when each event fires. The Hook events section documents the full input schema and decision control options for each one. - -Event| When it fires ----|--- -`SessionStart`| When a session begins or resumes -`Setup`| When you start Claude Code with `--init-only`, or with `--init` or `--maintenance` in `-p` mode. For one-time preparation in CI or scripts -`UserPromptSubmit`| When you submit a prompt, before Claude processes it -`UserPromptExpansion`| When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion -`PreToolUse`| Before a tool call executes. Can block it -`PermissionRequest`| When a tool call needs a permission decision -`PermissionDenied`| When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call -`PostToolUse`| After a tool call succeeds -`PostToolUseFailure`| After a tool call fails -`PostToolBatch`| After a full batch of parallel tool calls resolves, before the next model call -`Notification`| When Claude Code sends a notification -`MessageDisplay`| While assistant message text is displayed -`SubagentStart`| When a subagent is spawned -`SubagentStop`| When a subagent finishes -`TaskCreated`| When a task is being created via `TaskCreate` -`TaskCompleted`| When a task is being marked as completed -`Stop`| When Claude finishes responding -`StopFailure`| When the turn ends due to an API error. Output and exit code are ignored -`TeammateIdle`| When an [agent team](</docs/en/agent-teams>) teammate is about to go idle -`InstructionsLoaded`| When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session -`ConfigChange`| When a configuration file changes during a session -`CwdChanged`| When the working directory changes, for example when Claude executes a `cd` command. Useful for reactive environment management with tools like direnv -`DirectoryAdded`| When a working directory is added mid-session via `/add-dir` or the SDK `register_repo_root` control request -`FileChanged`| When a watched file changes on disk. The `matcher` field specifies which filenames to watch -`WorktreeCreate`| When a worktree is being created via `--worktree`, `isolation: "worktree"`, or for a background session. Replaces default git behavior -`WorktreeRemove`| When a worktree is being removed at session exit, when a subagent finishes, or when you delete a background session -`PreCompact`| Before context compaction -`PostCompact`| After context compaction completes -`Elicitation`| When an MCP server requests user input during a tool call -`ElicitationResult`| After a user responds to an MCP elicitation, before the response is sent back to the server -`SessionEnd`| When a session terminates - -### - -​ - -How a hook resolves - -To see how these pieces fit together, consider this `PreToolUse` hook that blocks destructive shell commands. - - * macOS/Linux - - * Windows (PowerShell) - -The `matcher` narrows to Bash tool calls and the `if` condition narrows further to Bash subcommands matching `rm *`, so `block-rm.sh` only spawns when both filters match: - - { - "hooks": { - "PreToolUse": [ - { - "matcher": "Bash", - "hooks": [ - { - "type": "command", - "if": "Bash(rm *)", - "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.sh", - "args": [] - } +How hooks work + +1 + +An event fires + +Something happens during agent execution and the SDK fires an event: a tool is about to be called (`PreToolUse`), a tool returned a result (`PostToolUse`), a subagent started or stopped, the agent is idle, or execution finished. See the full list of events. + +2 + +The SDK collects registered hooks + +The SDK checks for hooks registered for that event type. This includes callback hooks you pass in `options.hooks` and shell command hooks from settings files when the corresponding [`settingSources`](</docs/en/agent-sdk/typescript#settingsource>) or [`setting_sources`](</docs/en/agent-sdk/python#settingsource>) entry is enabled, which it is for default `query()` options. + +3 + +Matchers filter which hooks run + +If a hook has a `matcher` pattern (like `"Write|Edit"`), the SDK tests it against the event’s target (for example, the tool name). Hooks without a matcher run for every event of that type. + +4 + +Callback functions execute + +Each matching hook’s callback function receives input about what’s happening: the tool name, its arguments, the session ID, and other event-specific details. + +5 + +Your callback returns a decision + +After performing any operations (logging, API calls, validation), your callback returns an output object that tells the agent what to do: allow the operation, block it, modify the input, or inject context into the conversation. + +The following example puts these steps together. It registers a `PreToolUse` hook (step 1) with a `"Write|Edit"` matcher (step 3) so the callback only fires for file-writing tools. When triggered, the callback receives the tool’s input (step 4), checks if the file path targets a `.env` file, and returns `permissionDecision: "deny"` to block the operation (step 5): + +Python + +TypeScript + + import asyncio + from claude_agent_sdk import ( + AssistantMessage, + ClaudeSDKClient, + ClaudeAgentOptions, + HookMatcher, + ResultMessage, + ) + + # Define a hook callback that receives tool call details + async def protect_env_files(input_data, tool_use_id, context): + # Extract the file path from the tool's input arguments + file_path = input_data["tool_input"].get("file_path", "") + file_name = file_path.split("/")[-1] + + # Block the operation if targeting a .env file + if file_name == ".env": + return { + "hookSpecificOutput": { + "hookEventName": input_data["hook_event_name"], + "permissionDecision": "deny", + "permissionDecisionReason": "Cannot modify .env files", + } + } + + # Return empty object to allow the operation + return {} + + async def main(): + options = ClaudeAgentOptions( + hooks={ + # Register the hook for PreToolUse events + # The matcher filters to only Write and Edit tool calls + "PreToolUse": [HookMatcher(matcher="Write|Edit", hooks=[protect_env_files])] + } + ) + + async with ClaudeSDKClient(options=options) as client: + await client.query("Create a .env file with the standard local development database configuration") + async for message in client.receive_response(): + # Filter for assistant and result messages + if isinstance(message, (AssistantMessage, ResultMessage)): + print(message) + + asyncio.run(main()) + + import { query, HookCallback, PreToolUseHookInput } from "@anthropic-ai/claude-agent-sdk"; + + // Define a hook callback with the HookCallback type + const protectEnvFiles: HookCallback = async (input, toolUseID, { signal }) => { + // Cast input to the specific hook type for type safety + const preInput = input as PreToolUseHookInput; + + // Cast tool_input to access its properties (typed as unknown in the SDK) + const toolInput = preInput.tool_input as Record<string, unknown>; + const filePath = toolInput?.file_path as string; + const fileName = filePath?.split("/").pop(); + + // Block the operation if targeting a .env file + if (fileName === ".env") { + return { + hookSpecificOutput: { + hookEventName: preInput.hook_event_name, + permissionDecision: "deny", + permissionDecisionReason: "Cannot modify .env files" + } + }; + } + + // Return empty object to allow the operation + return {}; + }; + + for await (const message of query({ + prompt: "Create a .env file with the standard local development database configuration", + options: { + hooks: { + // Register the hook for PreToolUse events + // The matcher filters to only Write and Edit tool calls + PreToolUse: [{ matcher: "Write|Edit", hooks: [protectEnvFiles] }] + } + } + })) { + // Filter for assistant and result messages + if (message.type === "assistant" || message.type === "result") { + console.log(message); + } + } + +When you run either script, Claude attempts to create the `.env` file, the hook denies the tool call, and Claude’s final response explains that it can’t create `.env` files. + +## + +​ + +Available hooks + +The SDK provides hooks for different stages of agent execution. Some hooks are available in both SDKs, while others are TypeScript-only. + +Hook Event| Python SDK| TypeScript SDK| What triggers it| Example use case +---|---|---|---|--- +`PreToolUse`| Yes| Yes| Tool call request (can block or modify)| Block dangerous shell commands +`PostToolUse`| Yes| Yes| Tool execution result| Log all file changes to audit trail +`PostToolUseFailure`| Yes| Yes| Tool execution failure| Handle or log tool errors +`PostToolBatch`| No| Yes| A full batch of tool calls resolves, once per batch before the next model call| Inject conventions once for the whole batch +`UserPromptSubmit`| Yes| Yes| User prompt submission| Inject additional context into prompts +[`UserPromptExpansion`](</docs/en/hooks#userpromptexpansion>)| No| Yes| A user-typed command, or an MCP prompt, expands into a prompt before it reaches Claude. Doesn’t fire when Claude invokes a skill itself| Block a command from direct invocation or add context when a skill is typed +`MessageDisplay`| No| Yes| An assistant message with text completes, once per message with the full message text| Redact or reformat the displayed text without changing the transcript +`Stop`| Yes| Yes| Agent execution stop| Save session state before exit +`StopFailure`| No| Yes| The turn ends with an API error instead of a normal stop| Log failures or send alerts +`SubagentStart`| Yes| Yes| Subagent initialization| Track parallel task spawning +`SubagentStop`| Yes| Yes| Subagent completion| Aggregate results from parallel tasks +`PreCompact`| Yes| Yes| Conversation compaction request| Archive full transcript before summarizing +`PostCompact`| No| Yes| Conversation compaction completes| Log the generated summary +`PermissionRequest`| Yes| Yes| A tool call needs a permission decision| Custom permission handling +`PermissionDenied`| No| Yes| The auto mode classifier denies a tool call| Log classifier denials or tell the model it may retry +`SessionStart`| No| Yes| Session initialization| Initialize logging and telemetry +`SessionEnd`| No| Yes| Session termination| Clean up temporary resources +`Notification`| Yes| Yes| Agent status messages| Send agent status updates to Slack or PagerDuty +`Setup`| No| Yes| Session setup/maintenance| Run initialization tasks +`TeammateIdle`| No| Yes| Teammate becomes idle| Reassign work or notify +`TaskCreated`| No| Yes| A task is created via the `TaskCreate` tool| Enforce task naming conventions +`TaskCompleted`| No| Yes| Background task completes| Aggregate results from parallel tasks +`Elicitation`| No| Yes| An MCP server requests user input mid-task| Respond to MCP input requests programmatically +`ElicitationResult`| No| Yes| A user responds to an MCP elicitation| Modify or block the response before it returns to the server +`ConfigChange`| No| Yes| Configuration file changes| Reload settings dynamically +`InstructionsLoaded`| No| Yes| A `CLAUDE.md` or rules file is loaded into context| Audit which instruction files load +`WorktreeCreate`| No| Yes| Git worktree created| Track isolated workspaces +`WorktreeRemove`| No| Yes| Git worktree removed| Clean up workspace resources +`CwdChanged`| No| Yes| The working directory changes during a session| Reload environment variables per directory +`FileChanged`| No| Yes| A watched file is modified, created, or deleted| Reload configuration when project files change +`DirectoryAdded`| No| Yes| A working directory is added during a session| Install dependencies for a repository added mid-session + +## + +​ + +Configure hooks + +To configure a hook, pass it in the `hooks` field of your agent options (`ClaudeAgentOptions` in Python, the `options` object in TypeScript). This snippet assumes you have already defined a hook callback, like `protect_env_files` in Python or `protectEnvFiles` in TypeScript from the example above: + +Python + +TypeScript + + options = ClaudeAgentOptions( + hooks={"PreToolUse": [HookMatcher(matcher="Bash", hooks=[my_callback])]} + ) + + async with ClaudeSDKClient(options=options) as client: + await client.query("Your prompt") + async for message in client.receive_response(): + print(message) + + for await (const message of query({ + prompt: "Your prompt", + options: { + hooks: { + PreToolUse: [{ matcher: "Bash", hooks: [myCallback] }] + } + } + })) { + console.log(message); + } + +The `hooks` option is a dictionary in Python or an object in TypeScript, where: + + * **Keys** : hook event names such as `'PreToolUse'`, `'PostToolUse'`, and `'Stop'` + * **Values** : arrays of matchers, each containing an optional filter pattern and your callback functions + +### + +​ + +Matchers + +Use matchers to filter when your callbacks fire. The `matcher` field matches against a different value depending on the hook event type. For example, tool-based hooks match against the tool name, while `Notification` hooks match against the notification type. See the [Claude Code hooks reference](</docs/en/hooks#matcher-patterns>) for the full list of matcher values for each event type. SDK matchers follow the same rules as [matchers in settings files](</docs/en/hooks#matcher-patterns>). A matcher containing only letters, digits, `_`, `-`, spaces, `,`, and `|` is compared as an exact string, with alternatives separated by `|` or `,` and optional surrounding whitespace, so `Write|Edit` and `Write, Edit` each match exactly those two tools and `code-reviewer` matches only that agent type. A matcher of `*`, an empty string, or omitting the matcher entirely matches every occurrence of the event. A matcher containing any other character is evaluated as an unanchored regular expression, so `^mcp__` matches every MCP tool and `Edit.*` matches both `Edit` and `NotebookEdit`. Wrap a regular expression in `^` and `$` when you need a whole-string match. 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; use `mcp__memory__.*` to match every tool from that server. Hyphens in the exact-match set require a Claude Code runtime of v2.1.195 or later. On earlier versions a hyphenated name like `code-reviewer` is evaluated as an unanchored regular expression and must be anchored as `^code-reviewer$` to match exactly. `StopFailure` and `FileChanged` use a narrower exact-match set of letters, digits, `_`, and `|` only. A hyphen, space, or comma in a matcher for those two events keeps it on the regular-expression path, and only `|` separates alternatives, so write `rate_limit|overloaded`, not `rate_limit, overloaded`. `FileChanged` additionally uses its matcher to build the watch list of literal filenames; see [FileChanged in the hooks reference](</docs/en/hooks#filechanged>). + +Option| Type| Default| Description +---|---|---|--- +`matcher`| `string`| `undefined`| Pattern matched against the event’s filter field, following the comparison rules above. For tool hooks, this is the tool name. Built-in tools include `Bash`, `Read`, `Write`, `Edit`, `Glob`, `Grep`, `WebFetch`, `Agent`, and others (see [Tool Input Types](</docs/en/agent-sdk/typescript#tool-input-types>) for the full list). MCP tools use the pattern `mcp__<server>__<action>`. +`hooks`| `HookCallback[]`| -| Required. Array of callback functions to execute when the pattern matches +`timeout`| `number`| `undefined`| Timeout in seconds. When omitted, Claude Code applies the event’s default timeout: 10 minutes for most events, 30 seconds for `UserPromptSubmit`. Claude Code uses shorter limits for a few events, such as 10 seconds for `MessageDisplay` and a 1.5-second default [budget](</docs/en/hooks#sessionend-input>) for `SessionEnd`. Your SDK callbacks follow the `command` hook defaults + +Use the `matcher` pattern to target specific tools whenever possible. A matcher with `'Bash'` only runs for Bash commands, while omitting the pattern runs your callbacks for every occurrence of the event. For tool-based hooks, matchers only filter by tool name, not by file paths or other arguments. To filter by file path, check `tool_input.file_path` inside your callback. + +**Discovering tool names:** See [Tool Input Types](</docs/en/agent-sdk/typescript#tool-input-types>) for the full list of built-in tool names, or add a hook without a matcher to log all tool calls your session makes.**MCP tool naming:** MCP tools always start with `mcp__` followed by the server name and action: `mcp__<server>__<action>`. For example, if you configure a server named `playwright`, its tools are named `mcp__playwright__browser_screenshot`, `mcp__playwright__browser_click`, and so on. The server name comes from the key you use in the `mcpServers` configuration. + +### + +​ + +Callback functions + +#### + +​ + +Inputs + +Every hook callback receives three arguments: + + * **Input data:** a typed object containing event details. Each hook type has its own input shape. For example, `PreToolUseHookInput` includes `tool_name` and `tool_input`, while `NotificationHookInput` includes `message`. See the full type definitions in the [TypeScript](</docs/en/agent-sdk/typescript#hookinput>) and [Python](</docs/en/agent-sdk/python#hookinput>) SDK references. + * All hook inputs share `session_id`, `cwd`, and `hook_event_name`. + * `agent_id` and `agent_type` are populated when the hook fires inside a subagent. In TypeScript, these are on the base hook input and available to all hook types. In Python, they are optional fields on `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, and `PermissionRequest`, and required fields on `SubagentStart` and `SubagentStop`. + * **Tool use ID** (`str | None` / `string | undefined`): correlates `PreToolUse` and `PostToolUse` events for the same tool call. + * **Context:** in TypeScript, contains a `signal` property (`AbortSignal`) for cancellation. In Python, this argument is reserved for future use. + +#### + +​ + +Outputs + +Your callback returns an object with two categories of fields: + + * **Top-level fields** work the same on every event: `systemMessage` shows a message to the user, and `continue` (`continue_` in Python) determines whether the agent keeps running after this hook. + * **`hookSpecificOutput`** controls the current operation. The fields inside depend on the hook event type. For `PreToolUse` hooks, this is where you set `permissionDecision` (`"allow"`, `"deny"`, `"ask"`, or `"defer"`), `permissionDecisionReason`, and `updatedInput`. Returning `"defer"` ends the query so you can [resume it later](</docs/en/hooks#defer-a-tool-call-for-later>). For `PostToolUse` hooks, you can set `additionalContext` to append information to the tool result. To replace the tool’s output before Claude sees it, set `updatedToolOutput`, which works for any tool in both SDKs. The older `updatedMCPToolOutput` field replaces MCP tool output only and is deprecated. + +Return `{}` to allow the operation without changes. SDK callback hooks use the same JSON output format as [Claude Code shell command hooks](</docs/en/hooks#json-output>), which documents every field and event-specific option. For the SDK type definitions, see the [TypeScript](</docs/en/agent-sdk/typescript#synchookjsonoutput>) and [Python](</docs/en/agent-sdk/python#synchookjsonoutput>) SDK references. + +When multiple hooks or permission rules apply, `deny` takes priority over `defer`, which takes priority over `ask`, which takes priority over `allow`. If any hook returns `deny`, the operation is blocked regardless of other hooks. + +#### + +​ + +Asynchronous output + +By default, the agent waits for your hook to return before proceeding. If your hook performs a side effect, such as logging or sending a webhook, and doesn’t need to influence the agent’s behavior, you can return an async output instead. This tells the agent to continue immediately without waiting for the hook to finish. In this snippet, `send_to_logging_service` in Python and `sendToLoggingService` in TypeScript stand in for any logging function you define: + +Python + +TypeScript + + async def async_hook(input_data, tool_use_id, context): + # Start a background task, then return immediately + asyncio.create_task(send_to_logging_service(input_data)) + return {"async_": True, "asyncTimeout": 30000} + + const asyncHook: HookCallback = async (input, toolUseID, { signal }) => { + // Start a background task, then return immediately + sendToLoggingService(input).catch(console.error); + return { async: true, asyncTimeout: 30000 }; + }; + +Field| Type| Description +---|---|--- +`async`| `true`| Signals async mode. The agent proceeds without waiting. In Python, use `async_` to avoid the reserved keyword. +`asyncTimeout`| `number`| Optional timeout in milliseconds for the background operation + +Async outputs can’t block, modify, or inject context into the operation since the agent has already moved on. Use them only for side effects like logging, metrics, or notifications. + +## + +​ + +Examples + +Several examples in this section show only the callback function. To run one, register the callback under the matching event in the `hooks` field of your options, as shown in Configure hooks. + +### + +​ + +Modify tool input + +This example intercepts Write tool calls and rewrites the `file_path` argument to prepend `/sandbox`, redirecting all file writes to a sandboxed directory. The callback returns `updatedInput` with the modified path and `permissionDecision: 'allow'` to auto-approve the rewritten operation: + +Python + +TypeScript + + async def redirect_to_sandbox(input_data, tool_use_id, context): + if input_data["hook_event_name"] != "PreToolUse": + return {} + + if input_data["tool_name"] == "Write": + original_path = input_data["tool_input"].get("file_path", "") + return { + "hookSpecificOutput": { + "hookEventName": input_data["hook_event_name"], + "permissionDecision": "allow", + "updatedInput": { + **input_data["tool_input"], + "file_path": f"/sandbox{original_path}", + }, + } + } + return {} + + const redirectToSandbox: HookCallback = async (input, toolUseID, { signal }) => { + if (input.hook_event_name !== "PreToolUse") return {}; + + const preInput = input as PreToolUseHookInput; + const toolInput = preInput.tool_input as Record<string, unknown>; + if (preInput.tool_name === "Write") { + const originalPath = toolInput.file_path as string; + return { + hookSpecificOutput: { + hookEventName: preInput.hook_event_name, + permissionDecision: "allow", + updatedInput: { + ...toolInput, + file_path: `/sandbox${originalPath}` + } + } + }; + } + return {}; + }; + +Pair `updatedInput` with `permissionDecision: 'allow'` to auto-approve the modified input, or `permissionDecision: 'ask'` to show it to the user. If you omit `permissionDecision`, the modified input still applies and flows through the normal permission evaluation. With `'defer'`, `updatedInput` is ignored. Always return a new object rather than mutating the original `tool_input`. + +To confirm the redirect, set the prefix to a path you can write to, such as `./sandbox` or `/tmp/sandbox` (macOS doesn’t allow creating a root-level `/sandbox` directory), then ask the agent to write a file: the Write tool’s result in the message stream names the path with your sandbox prefix rather than the one Claude requested. + +### + +​ + +Add context and block a tool + +This example blocks writes to the `/etc` directory and explains why to both the model and the user: + + * `permissionDecision: 'deny'` stops the tool call. + * `permissionDecisionReason` tells the model why, so it avoids retrying. + * `systemMessage` shows the user what happened. + +Python + +TypeScript + + async def block_etc_writes(input_data, tool_use_id, context): + file_path = input_data["tool_input"].get("file_path", "") + + if file_path.startswith("/etc"): + return { + # Top-level field: message shown to the user + "systemMessage": "Remember: system directories like /etc are protected.", + # hookSpecificOutput: block the operation + "hookSpecificOutput": { + "hookEventName": input_data["hook_event_name"], + "permissionDecision": "deny", + "permissionDecisionReason": "Writing to /etc is not allowed", + }, + } + return {} + + const blockEtcWrites: HookCallback = async (input, toolUseID, { signal }) => { + const preInput = input as PreToolUseHookInput; + const toolInput = preInput.tool_input as Record<string, unknown>; + const filePath = toolInput?.file_path as string; + + if (filePath?.startsWith("/etc")) { + return { + // Top-level field: message shown to the user + systemMessage: "Remember: system directories like /etc are protected.", + // hookSpecificOutput: block the operation + hookSpecificOutput: { + hookEventName: preInput.hook_event_name, + permissionDecision: "deny", + permissionDecisionReason: "Writing to /etc is not allowed" + } + }; + } + return {}; + }; + +### + +​ + +Auto-approve specific tools + +By default, the agent may prompt for permission before using certain tools. This example auto-approves read-only filesystem tools (Read, Glob, Grep) by returning `permissionDecision: 'allow'`, letting them run without user confirmation while leaving all other tools subject to normal permission checks: + +Python + +TypeScript + + async def auto_approve_read_only(input_data, tool_use_id, context): + if input_data["hook_event_name"] != "PreToolUse": + return {} + + read_only_tools = ["Read", "Glob", "Grep"] + if input_data["tool_name"] in read_only_tools: + return { + "hookSpecificOutput": { + "hookEventName": input_data["hook_event_name"], + "permissionDecision": "allow", + "permissionDecisionReason": "Read-only tool auto-approved", + } + } + return {} + + const autoApproveReadOnly: HookCallback = async (input, toolUseID, { signal }) => { + if (input.hook_event_name !== "PreToolUse") return {}; + + const preInput = input as PreToolUseHookInput; + const readOnlyTools = ["Read", "Glob", "Grep"]; + if (readOnlyTools.includes(preInput.tool_name)) { + return { + hookSpecificOutput: { + hookEventName: preInput.hook_event_name, + permissionDecision: "allow", + permissionDecisionReason: "Read-only tool auto-approved" + } + }; + } + return {}; + }; + +### + +​ + +Register multiple hooks + +When an event fires, all matching hooks run in parallel. For permission decisions, the most restrictive result applies: a single `deny` blocks the tool call regardless of what the other hooks return. Because completion order is non-deterministic, write each hook to act independently rather than relying on another hook having run first. The example below registers three independent checks for every tool call: + +Python + +TypeScript + + options = ClaudeAgentOptions( + hooks={ + "PreToolUse": [ + HookMatcher(hooks=[authorization_check]), + HookMatcher(hooks=[input_validator]), + HookMatcher(hooks=[audit_logger]), ] + } + ) + + const options = { + hooks: { + PreToolUse: [ + { hooks: [authorizationCheck] }, + { hooks: [inputValidator] }, + { hooks: [auditLogger] } + ] + } + }; + +### + +​ + +Filter with multi-tool matchers + +Use multi-tool matchers to share one callback across related tools. This example registers three matchers with different scopes: + + * A pipe-separated exact list (`Write|Edit|NotebookEdit`) triggers `file_security_hook` only for file modification tools. + * A regex (`^mcp__`) triggers `mcp_audit_hook` for any MCP tool whose name starts with `mcp__`. + * An omitted matcher triggers `global_logger` for every tool call regardless of name. + +Python + +TypeScript + + options = ClaudeAgentOptions( + hooks={ + "PreToolUse": [ + # Match file modification tools + HookMatcher(matcher="Write|Edit|NotebookEdit", hooks=[file_security_hook]), + # Match all MCP tools + HookMatcher(matcher="^mcp__", hooks=[mcp_audit_hook]), + # Match everything (no matcher) + HookMatcher(hooks=[global_logger]), + ] + } + ) + + const options = { + hooks: { + PreToolUse: [ + // Match file modification tools + { matcher: "Write|Edit|NotebookEdit", hooks: [fileSecurityHook] }, + + // Match all MCP tools + { matcher: "^mcp__", hooks: [mcpAuditHook] }, + + // Match everything (no matcher) + { hooks: [globalLogger] } + ] + } + }; + +### + +​ + +Track subagent activity + +Use `SubagentStop` hooks to monitor when subagents finish their work. See the full input type in the [TypeScript](</docs/en/agent-sdk/typescript#hookinput>) and [Python](</docs/en/agent-sdk/python#hookinput>) SDK references. This example logs a summary each time a subagent completes: + +Python + +TypeScript + + async def subagent_tracker(input_data, tool_use_id, context): + # Log subagent details when it finishes + print(f"[SUBAGENT] Completed: {input_data['agent_id']}") + print(f" Transcript: {input_data['agent_transcript_path']}") + print(f" Tool use ID: {tool_use_id}") + print(f" Stop hook active: {input_data.get('stop_hook_active')}") + return {} + + options = ClaudeAgentOptions( + hooks={"SubagentStop": [HookMatcher(hooks=[subagent_tracker])]} + ) + + import { HookCallback, SubagentStopHookInput } from "@anthropic-ai/claude-agent-sdk"; + + const subagentTracker: HookCallback = async (input, toolUseID, { signal }) => { + // Cast to SubagentStopHookInput to access subagent-specific fields + const subInput = input as SubagentStopHookInput; + + // Log subagent details when it finishes + console.log(`[SUBAGENT] Completed: ${subInput.agent_id}`); + console.log(` Transcript: ${subInput.agent_transcript_path}`); + console.log(` Tool use ID: ${toolUseID}`); + console.log(` Stop hook active: ${subInput.stop_hook_active}`); + return {}; + }; + + const options = { + hooks: { + SubagentStop: [{ hooks: [subagentTracker] }] + } + }; + +### + +​ + +Make HTTP requests from hooks + +Hooks can perform asynchronous operations like HTTP requests. Catch errors inside your hook instead of letting them propagate, since an unhandled exception can interrupt the agent. This example sends a webhook after each tool completes, logging which tool ran and when. The hook catches errors so a failed webhook doesn’t interrupt the agent: + +Python + +TypeScript + + import asyncio + import json + import urllib.request + from datetime import datetime + + def _send_webhook(tool_name): + """Synchronous helper that POSTs tool usage data to an external webhook.""" + data = json.dumps( + { + "tool": tool_name, + "timestamp": datetime.now().isoformat(), + } + ).encode() + req = urllib.request.Request( + "https://api.example.com/webhook", + data=data, + headers={"Content-Type": "application/json"}, + method="POST", + ) + urllib.request.urlopen(req) + + async def webhook_notifier(input_data, tool_use_id, context): + # Only fire after a tool completes (PostToolUse), not before + if input_data["hook_event_name"] != "PostToolUse": + return {} + + try: + # Run the blocking HTTP call in a thread to avoid blocking the event loop + await asyncio.to_thread(_send_webhook, input_data["tool_name"]) + except Exception as e: + # Log the error but don't raise. A failed webhook shouldn't stop the agent + print(f"Webhook request failed: {e}") + + return {} + + import { query, HookCallback, PostToolUseHookInput } from "@anthropic-ai/claude-agent-sdk"; + + const webhookNotifier: HookCallback = async (input, toolUseID, { signal }) => { + // Only fire after a tool completes (PostToolUse), not before + if (input.hook_event_name !== "PostToolUse") return {}; + + try { + await fetch("https://api.example.com/webhook", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + tool: (input as PostToolUseHookInput).tool_name, + timestamp: new Date().toISOString() + }), + // Pass signal so the request cancels if the hook times out + signal + }); + } catch (error) { + // Handle cancellation separately from other errors + if (error instanceof Error && error.name === "AbortError") { + console.log("Webhook request cancelled"); + } + // Don't re-throw. A failed webhook shouldn't stop the agent + } + + return {}; + }; + + // Register as a PostToolUse hook + for await (const message of query({ + prompt: "Refactor the auth module", + options: { + hooks: { + PostToolUse: [{ hooks: [webhookNotifier] }] + } + } + })) { + console.log(message); + } + +To confirm the hook fires, point the webhook URL at an endpoint you can watch and send a prompt that uses a tool: the hook sends a POST with the tool name and timestamp after each tool completes. + +### + +​ + +Forward notifications to Slack + +Use `Notification` hooks to receive system notifications from the agent and forward them to external services. Notifications fire for event types such as: + + * `permission_prompt` when Claude needs permission + * `idle_prompt` when Claude is waiting for input + * `auth_success` when authentication completes + * `elicitation_dialog`, `elicitation_complete`, and `elicitation_response` for user-prompt elicitation flows + +In headless SDK sessions, only the elicitation events `elicitation_complete` and `elicitation_response` fire this hook; the other types are emitted by interactive UI that SDK sessions don’t run. Permission requests, for example, go to the `canUseTool` callback instead. Each notification includes a `message` field with a human-readable description and optionally a `title`. This example forwards every notification to a Slack channel. It requires a [Slack incoming webhook URL](<https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/>), which you create by adding an app to your Slack workspace and enabling incoming webhooks: + +Python + +TypeScript + + import asyncio + import json + import urllib.request + + from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, HookMatcher + + def _send_slack_notification(message): + """Synchronous helper that sends a message to Slack via incoming webhook.""" + data = json.dumps({"text": f"Agent status: {message}"}).encode() + req = urllib.request.Request( + "https://hooks.slack.com/services/YOUR/WEBHOOK/URL", + data=data, + headers={"Content-Type": "application/json"}, + method="POST", + ) + urllib.request.urlopen(req) + + async def notification_handler(input_data, tool_use_id, context): + try: + # Run the blocking HTTP call in a thread to avoid blocking the event loop + await asyncio.to_thread(_send_slack_notification, input_data.get("message", "")) + except Exception as e: + print(f"Failed to send notification: {e}") + + # Return empty object. Notification hooks don't modify agent behavior + return {} + + async def main(): + options = ClaudeAgentOptions( + hooks={ + # Register the hook for Notification events (no matcher needed) + "Notification": [HookMatcher(hooks=[notification_handler])], + }, + ) + + async with ClaudeSDKClient(options=options) as client: + await client.query("Analyze this codebase") + async for message in client.receive_response(): + print(message) + + asyncio.run(main()) + + import { query, HookCallback, NotificationHookInput } from "@anthropic-ai/claude-agent-sdk"; + + // Define a hook callback that sends notifications to Slack + const notificationHandler: HookCallback = async (input, toolUseID, { signal }) => { + // Cast to NotificationHookInput to access the message field + const notification = input as NotificationHookInput; + + try { + // POST the notification message to a Slack incoming webhook + await fetch("https://hooks.slack.com/services/YOUR/WEBHOOK/URL", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + text: `Agent status: ${notification.message}` + }), + // Pass signal so the request cancels if the hook times out + signal + }); + } catch (error) { + if (error instanceof Error && error.name === "AbortError") { + console.log("Notification cancelled"); + } else { + console.error("Failed to send notification:", error); + } + } + + // Return empty object. Notification hooks don't modify agent behavior + return {}; + }; + + // Register the hook for Notification events (no matcher needed) + for await (const message of query({ + prompt: "Analyze this codebase", + options: { + hooks: { + Notification: [{ hooks: [notificationHandler] }] + } + } + })) { + console.log(message); + } + +When a `Notification` event fires, the hook posts the notification’s `message`, prefixed with `Agent status:`, to the channel your webhook targets. + +## + +​ + +Fix common issues + +### + +​ + +Hook not firing + + * Verify the hook event name is correct and case-sensitive (`PreToolUse`, not `preToolUse`) + * Check that your matcher pattern matches the tool name exactly + * Ensure the hook is under the correct event type in `options.hooks` + * For non-tool hooks that support matchers, like `Notification` and `SubagentStop`, matchers match against different fields, and `Stop` ignores matchers entirely (see [matcher patterns](</docs/en/hooks#matcher-patterns>)) + * Hooks may not fire when the agent hits the [`max_turns`](</docs/en/agent-sdk/python#claudeagentoptions>) limit because the session ends before hooks can execute + +### + +​ + +Matcher not filtering as expected + +Matchers only match tool names, not file paths or other arguments. To filter by file path, check `tool_input.file_path` inside your hook: + + const myHook: HookCallback = async (input, toolUseID, { signal }) => { + const preInput = input as PreToolUseHookInput; + const toolInput = preInput.tool_input as Record<string, unknown>; + const filePath = toolInput?.file_path as string; + if (!filePath?.endsWith(".md")) return {}; // Skip non-markdown files + // Process markdown files... + return {}; + }; + +### + +​ + +Hook timeout + +Claude Code runs each callback with a timeout, which you set in seconds with the `timeout` field on its `HookMatcher`. When you don’t set one, Claude Code uses the event’s default: 600 seconds for most events, 30 seconds for `UserPromptSubmit`, and 10 seconds for `MessageDisplay`. Claude Code runs `SessionEnd` callbacks during shutdown under the shorter [SessionEnd timeout budget](</docs/en/hooks#sessionend-input>). When a callback exceeds its timeout, Claude Code cancels it and treats it as a failed hook: it discards the callback’s output and the session continues rather than hanging. What happens next depends on the event: + + * `PreToolUse`: Claude Code doesn’t run the tool call, Claude receives a tool result stating the hook didn’t respond before its timeout, and the turn continues. If another `PreToolUse` hook returned an explicit deny, Claude receives that denial instead of the timeout error. Before v2.1.210, Claude Code reported the timeout to Claude as a user rejection, which made unattended sessions stop and wait for input. + * `PostToolUse` and `PostToolUseFailure`: Claude Code keeps the tool result and the turn continues. + * `UserPromptSubmit` and [`UserPromptExpansion`](</docs/en/hooks#userpromptexpansion>): Claude Code blocks the prompt with a message naming the hook and the timeout, and the session continues. Because a callback on these events can act as a policy gate, Claude Code never lets a timed-out prompt through unscreened. Before v2.1.208, Claude Code ended the query with `error_during_execution` when a callback on these events timed out. + * `Stop` and `SubagentStop`: Claude Code shows a warning and the agent stops normally. + * Other events, such as `Notification` and `PreCompact`: Claude Code logs the failure and continues. + +If you interrupt the query while a callback is pending, Claude Code cancels the pending tool call. Before v2.1.208, the tool call could still proceed if you interrupted during a pending `PreToolUse` callback. If your callback needs more time, set a higher `timeout` on its `HookMatcher`. In TypeScript, use the `AbortSignal` from the third callback argument to handle cancellation gracefully when the timeout fires. + +### + +​ + +Tool blocked unexpectedly + + * Check all `PreToolUse` hooks for `permissionDecision: 'deny'` returns + * Add logging to your hooks to see what `permissionDecisionReason` they’re returning + * Verify matcher patterns aren’t too broad: an empty matcher matches all tools + +### + +​ + +Modified input not applied + + * Ensure `updatedInput` is inside `hookSpecificOutput`, not at the top level: + + return { + hookSpecificOutput: { + hookEventName: "PreToolUse", + permissionDecision: "allow", + updatedInput: { command: "new command" } } - ] - } - } - -The script reads the JSON input from stdin, extracts the command, and returns a `permissionDecision` of `"deny"` if it contains `rm -rf`. Save it to `.claude/hooks/block-rm.sh` in your project and make it executable with `chmod +x .claude/hooks/block-rm.sh` so Claude Code can run it: - - #!/bin/bash - # .claude/hooks/block-rm.sh - COMMAND=$(jq -r '.tool_input.command') - - if echo "$COMMAND" | grep -q 'rm -rf'; then - jq -n '{ - hookSpecificOutput: { - hookEventName: "PreToolUse", - permissionDecision: "deny", - permissionDecisionReason: "Destructive command blocked by hook" - } - }' - else - exit 0 # no decision; normal permission flow applies - fi - -This script, like the other Bash examples on this page that parse JSON input, uses `jq`, so install `jq` and make sure it is on your `PATH` before trying them. - -The matcher `Bash|PowerShell` covers the PowerShell tool as well as Bash. A single `if` rule matches only one tool’s calls, so each tool gets its own handler: the first narrows to Bash subcommands matching `rm *`, the second to PowerShell commands matching `Remove-Item *`. Both run the same script through `powershell.exe`: - - { - "hooks": { - "PreToolUse": [ - { - "matcher": "Bash|PowerShell", - "hooks": [ - { - "type": "command", - "if": "Bash(rm *)", - "command": "powershell.exe", - "args": [ - "-NoProfile", - "-ExecutionPolicy", - "Bypass", - "-File", - "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.ps1" - ] - }, - { - "type": "command", - "if": "PowerShell(Remove-Item *)", - "command": "powershell.exe", - "args": [ - "-NoProfile", - "-ExecutionPolicy", - "Bypass", - "-File", - "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.ps1" - ] - } - ] - } - ] - } - } - -The `-NoProfile` flag skips loading your PowerShell profile so the hook starts fast, and `-ExecutionPolicy Bypass` lets PowerShell run the local script file.The script reads the JSON input from stdin, extracts the command, and returns a `permissionDecision` of `"deny"` if it contains `rm -rf` or `Remove-Item` followed by `-Recurse`. Save it to `.claude/hooks/block-rm.ps1` in your project: - - # .claude/hooks/block-rm.ps1 - $callInput = [Console]::In.ReadToEnd() | ConvertFrom-Json - $command = $callInput.tool_input.command - - if ($command -match 'rm -rf|Remove-Item.*-Recurse') { - @{ - hookSpecificOutput = @{ - hookEventName = "PreToolUse" - permissionDecision = "deny" - permissionDecisionReason = "Destructive command blocked by hook" - } - } | ConvertTo-Json - } else { - exit 0 # no decision; normal permission flow applies - } - -Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"` against the macOS/Linux config. Here’s what happens: - -1 - -Event fires - -The `PreToolUse` event fires. Claude Code sends the tool input as JSON on stdin to the hook: - - { "tool_name": "Bash", "tool_input": { "command": "rm -rf /tmp/build" }, ... } - -2 - -Matcher checks - -The matcher `"Bash"` matches the tool name, so this hook group activates. If you omit the matcher or use `"*"`, the group activates on every occurrence of the event. - -3 - -If condition checks - -The `if` condition `"Bash(rm *)"` matches because `rm -rf /tmp/build` is a subcommand matching `rm *`, so this handler spawns. If the command had been `npm test`, the `if` check would fail and `block-rm.sh` would never run, avoiding the process spawn overhead. The `if` field is optional; without it, every handler in the matched group runs. - -4 - -Hook handler runs - -The script inspects the full command and finds `rm -rf`, so it prints a decision to stdout: - - { - "hookSpecificOutput": { - "hookEventName": "PreToolUse", - "permissionDecision": "deny", - "permissionDecisionReason": "Destructive command blocked by hook" - } - } - -If the command had been a safer `rm` variant like `rm file.txt`, the script would hit `exit 0` instead. Exit code 0 with no output means the hook has no decision to report, so the tool call continues through the normal [permission flow](</docs/en/permissions>). The hook can deny the call, but staying silent doesn’t approve it. - -5 - -Claude Code acts on the result - -Claude Code reads the JSON decision, blocks the tool call, and shows Claude the reason. - -The Configuration section below documents the full schema, and each hook event section documents what input your command receives and what output it can return. + }; + + * Don’t pair `updatedInput` with `permissionDecision: 'defer'`, which drops the modified input. Omitting `permissionDecision` is fine: the modified input still applies through the normal permission evaluation. You can also return `'allow'` to auto-approve the modified input or `'ask'` to show it to the user for approval + * Include `hookEventName` in `hookSpecificOutput` to identify which hook type the output is for + +### + +​ + +Session hooks not available in Python + +`SessionStart` and `SessionEnd` can be registered as SDK callback hooks in TypeScript, but aren’t available in the Python SDK because its `HookEvent` type omits them. In Python, they are only available as [shell command hooks](</docs/en/hooks#hook-events>) defined in settings files such as `.claude/settings.json`. To load shell command hooks from your SDK application, include the appropriate setting source with [`setting_sources`](</docs/en/agent-sdk/python#settingsource>) or [`settingSources`](</docs/en/agent-sdk/typescript#settingsource>): + +Python + +TypeScript + + options = ClaudeAgentOptions( + setting_sources=["project"], # Loads .claude/settings.json including hooks + ) + + const options = { + settingSources: ["project"] // Loads .claude/settings.json including hooks + }; + +To run initialization logic as a Python SDK callback instead, use the first message from `client.receive_response()` as your trigger. + +### + +​ + +Subagent permission prompts multiplying + +When spawning multiple subagents, each one may request permissions separately for its own tool calls. To avoid repeated prompts, use `PreToolUse` hooks to auto-approve specific tools, or configure permission rules, which subagents [inherit from the parent conversation](</docs/en/sub-agents#permission-modes>). + +### + +​ + +Recursive hook loops with subagents + +A `UserPromptSubmit` hook that spawns subagents can create infinite loops if those subagents trigger the same hook. To prevent this: + + * Check for a subagent indicator in the hook input before spawning + * Use a shared variable or session state to track whether you’re already inside a subagent + * Scope hooks to only run for the top-level agent session + +### + +​ + +systemMessage not appearing in output + +The `systemMessage` field shows a message to the user, not the model. By default the SDK surfaces hook output in the message stream only for `SessionStart` and `Setup` hooks, so a message from any other hook event doesn’t appear unless you set `includeHookEvents` (`include_hook_events` in Python). To pass context to the model instead, return [`additionalContext`](</docs/en/hooks#add-context-for-claude>). If you need to surface hook decisions to your application reliably, log them separately or use a dedicated output channel. ## ​ -Configuration - -Hooks are defined in JSON settings files. The configuration has three levels of nesting: - - 1. Choose a hook event to respond to, like `PreToolUse` or `Stop` - 2. Add a matcher group to filter when it fires, like “only for the Bash tool” - 3. Define one or more hook handlers to run when matched - -See How a hook resolves above for a complete walkthrough with an annotated example. - -This page uses specific terms for each level: **hook event** for the lifecycle point, **matcher group** for the filter, and **hook handler** for the shell command, HTTP endpoint, MCP tool, prompt, or agent that runs. “Hook” on its own refers to the general feature. - -### - -​ - -Hook locations - -Where you define a hook determines its scope: - -Location| Scope| Shareable ----|---|--- -`~/.claude/settings.json`| All your projects| No, local to your machine -`.claude/settings.json`| Single project| Yes, can be committed to the repo -`.claude/settings.local.json`| Single project| No, gitignored when Claude Code saves a setting to it -Managed policy settings| Organization-wide| Yes, admin-controlled -[Plugin](</docs/en/plugins>) `hooks/hooks.json`| When plugin is enabled| Yes, bundled with the plugin -[Skill](</docs/en/skills>) or [agent](</docs/en/sub-agents>) frontmatter| While the component is active| Yes, defined in the component file - -Cloud sessions on [Claude Code on the web](</docs/en/claude-code-on-the-web>) don’t read your local `~/.claude/settings.json`; hooks there come from the repo and from your organization’s server-managed settings. See [what carries over from your setup](</docs/en/cloud-environments#what-carries-over-from-your-setup>) for which files reach a cloud session. For details on settings file resolution, see [settings](</docs/en/settings>). Hooks from settings files, managed policy settings, and plugins also run inside [subagents](</docs/en/sub-agents>). When a subagent calls a tool, tool events such as `PreToolUse` and `PostToolUse` fire the same configured hooks as in the main conversation, and the input carries the `agent_id` and `agent_type` common input fields that identify the subagent. Enterprise administrators can use `allowManagedHooksOnly` to block user, project, and plugin hooks. Hooks from plugins force-enabled in managed settings `enabledPlugins` are exempt. See [Hook configuration](</docs/en/settings#hook-configuration>). Hook entries merge across settings levels rather than replacing each other: user, project, and local settings add their own hooks without removing managed ones, and the `disableAllHooks` setting can’t disable managed hooks from outside managed settings. The [HTTP hook allowlists](</docs/en/settings#hook-configuration>) apply to hooks from every source, including managed policy settings: - - * `allowedHttpHookUrls`: when defined at any settings level, Claude Code runs an HTTP hook handler only if its URL matches the merged allowlist - * `httpHookAllowedEnvVars`: when defined, Claude Code interpolates only the environment variables on that list into hook headers - -### - -​ - -Matcher patterns - -The `matcher` field filters when hooks fire. How a matcher is evaluated depends on the characters it contains: - -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; `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 doesn’t 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 ----|---|--- -`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied`| tool name| `Bash`, `Edit|Write`, `mcp__.*` -`SessionStart`| how the session started| `startup`, `resume`, `clear`, `compact`, `fork` -`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`, `agent_needs_input`, `agent_completed` -`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` -`CwdChanged`| no matcher support| always fires on every directory change -`DirectoryAdded`| how the directory was added| `slash_command`, `register_repo_root` -`FileChanged`| literal filenames to watch (see FileChanged)| `.envrc|.env` -`StopFailure`| error type| `rate_limit`, `overloaded`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, `unknown` -`InstructionsLoaded`| load reason| `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact` -`UserPromptExpansion`| command name| your skill or command names -`Elicitation`| MCP server name| your configured MCP server names -`ElicitationResult`| MCP server name| same values as `Elicitation` -`UserPromptSubmit`, `PostToolBatch`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `MessageDisplay`| no matcher support| always fires on every occurrence - -The matcher runs against a field from the JSON input that Claude Code sends to your hook on stdin. For tool events, that field is `tool_name`. Each hook event section lists the full set of matcher values and the input schema for that event. This example runs a linting script only when Claude writes or edits a file: - - { - "hooks": { - "PostToolUse": [ - { - "matcher": "Edit|Write", - "hooks": [ - { - "type": "command", - "command": "/path/to/lint-check.sh" - } - ] - } - ] - } - } - -If you add a `matcher` field to an event without matcher support, 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. - -#### - -​ - -Match MCP tools - -[MCP](</docs/en/mcp>) server tools appear as regular tools in tool events (`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied`), so you can match them the same way you match any other tool name. MCP tools follow the naming pattern `mcp__<server>__<tool>`, for example: - - * `mcp__memory__create_entities`: Memory server’s create entities tool - * `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` 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 - -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. Tools from a [plugin-bundled MCP server](</docs/en/mcp#plugin-provided-mcp-servers>) use a scoped server segment that includes the plugin name: `mcp__plugin_<plugin-name>_<server-name>__<tool>`. A matcher written against the bare server key never fires for these tools. For a plugin named `my-plugin` that bundles a server under the key `db`, a `query` tool appears as `mcp__plugin_my-plugin_db__query`, so the matcher for every tool from that server is `mcp__plugin_my-plugin_db__.*`. Use the same scoped tool name in a handler’s `if` field. See [Plugin-provided MCP servers](</docs/en/mcp#plugin-provided-mcp-servers>) for how the scoped name is built. This example logs all memory server operations and validates write operations from any MCP server: - - { - "hooks": { - "PreToolUse": [ - { - "matcher": "mcp__memory__.*", - "hooks": [ - { - "type": "command", - "command": "echo 'Memory operation initiated' >> ~/mcp-operations.log" - } - ] - }, - { - "matcher": "mcp__.*__write.*", - "hooks": [ - { - "type": "command", - "command": "/home/user/scripts/validate-mcp-write.py" - } - ] - } - ] - } - } - -### - -​ - -Hook handler fields - -Each object in the inner `hooks` array is a hook handler: the shell command, HTTP endpoint, MCP tool, LLM prompt, or agent that runs when the matcher matches. There are five types: - - * **Command hooks** (`type: "command"`): run a shell command. Your script receives the event’s JSON input on stdin and communicates results back through exit codes and stdout. - * **HTTP hooks** (`type: "http"`): send the event’s JSON input as an HTTP POST request to a URL. The endpoint communicates results back through the response body using the same JSON output format as command hooks. - * **MCP tool hooks** (`type: "mcp_tool"`): call a tool on an already-connected [MCP server](</docs/en/mcp>). The tool’s text output is treated like command-hook stdout. - * **Prompt hooks** (`type: "prompt"`): send a prompt to a Claude model for single-turn evaluation. The model returns a yes/no decision as JSON. See Prompt-based hooks. - * **Agent hooks** (`type: "agent"`): spawn a subagent that can use tools like Read, Grep, and Glob to verify conditions before returning a decision. Agent hooks are experimental and may change. See Agent-based hooks. - -All matching hooks run in parallel. If you define the same handler in more than one settings file, it runs once. A plugin’s or skill’s copy of the same handler stays separate. Handlers run in the current directory with Claude Code’s environment. The `$CLAUDE_CODE_REMOTE` environment variable is set to `"true"` in remote web environments and not set in the local CLI. As of v2.1.199, [`$CLAUDE_CODE_BRIDGE_SESSION_ID`](</docs/en/env-vars>) is set to the [Remote Control](</docs/en/remote-control>) session ID while the local session has an active Remote Control connection. - -#### - -​ - -Common fields - -These fields apply to all hook types: - -Field| Required| Description ----|---|--- -`type`| yes| `"command"`, `"http"`, `"mcp_tool"`, `"prompt"`, or `"agent"` -`if`| no| Permission rule syntax to filter when this hook runs, such as `"Bash(git *)"` or `"Edit(*.ts)"`. The hook command only runs if the tool call matches the pattern. See the Bash matching table below for how Bash patterns evaluate against subcommands, `$()`, and backticks. Only evaluated on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. On other events, a hook with `if` set never runs. Uses the same syntax as [permission rules](</docs/en/permissions>) -`timeout`| no| Seconds before canceling. Defaults: 600 for `command`, `http`, and `mcp_tool`; 30 for `prompt`; 60 for `agent`. `UserPromptSubmit` lowers the `command`, `http`, and `mcp_tool` default to 30, and `MessageDisplay` lowers it to 10. `SessionEnd` hooks share a 1.5-second budget; if your settings set a longer per-hook `timeout`, Claude Code raises the budget to match, up to 60 seconds -`statusMessage`| no| Custom spinner message displayed while the hook runs -`once`| no| If `true`, runs once per session then is removed. Only honored for hooks declared in skill frontmatter; ignored in settings files and agent frontmatter - -The `if` field holds exactly one permission rule. There is no `&&`, `||`, or list syntax for combining rules; to apply multiple conditions, define a separate hook handler for each. In an `if` condition for a file tool, a single-segment directory pattern like `"Edit(src/**)"` matches only the `src` directory in the working directory and the files under it. To match a directory named `src` at any depth, write `"Edit(**/src/**)"`. Before v2.1.214, `"Edit(src/**)"` matched a directory named `src` at any depth under the working directory. For Bash patterns, whether your hook command runs depends on the shape of the pattern and the Bash command Claude is invoking. Leading `VAR=value` assignments are stripped before matching. - -`if` pattern| Bash command| Hook runs?| Why ----|---|---|--- -`Bash(git *)`| `FOO=bar git push`| yes| leading assignments are stripped; `git push` matches -`Bash(git *)`| `npm test && git push`| yes| each subcommand is checked; `git push` matches -`Bash(rm *)`| `echo $(rm -rf /)`| yes| commands inside `$()` and backticks are checked; `rm -rf /` matches -`Bash(rm *)`| `echo $(date)`| no| no subcommand matches `rm *` -`Bash(git push *)`| `echo $(date)`| yes| patterns that specify more than the command name run the hook anyway on `$()`, backticks, or `$VAR` - -The filter also fails open, running your hook regardless of pattern, when the Bash command can’t be parsed. Because the `if` filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny. - -#### - -​ - -Command hook fields - -In addition to the common fields, command hooks accept these fields: - -Field| Required| Description ----|---|--- -`command`| yes| Shell command to execute. With `args`, the executable to spawn directly. See Exec form and shell form -`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"` 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 - -A command hook runs as exec form when `args` is set, and shell form when `args` is omitted. Set `args` whenever the hook references a path placeholder, since each element is passed as one argument with no quoting. Omit `args` when you need shell features like pipes or `&&`, or when neither concern applies. **Exec form** runs when `args` is present. Claude Code resolves `command` as an executable on `PATH` and spawns it directly with `args` as the argument vector. There is no shell, so each `args` element is one argument exactly as written, and path placeholders like `${CLAUDE_PLUGIN_ROOT}` are substituted into `command` and into each `args` element as plain strings. Special characters such as apostrophes, `$`, and backticks pass through verbatim because there is no shell to interpret them. No shell tokenization happens on any platform. **Shell form** runs when `args` is absent. The `command` string is passed to a shell: `sh -c` on macOS and Linux, Git Bash on Windows, or PowerShell when Git Bash isn’t installed. Set the `shell` field to choose explicitly. The shell tokenizes the string, expands variables, and interprets pipes, `&&`, redirects, and globs. - -On Windows, exec form requires `command` to resolve to a real executable such as a `.exe`. The `.cmd` and `.bat` shims that npm, npx, eslint, and other tools install in `node_modules/.bin` are not executables and can’t be spawned without a shell. To run them in exec form, invoke the underlying script with `node` directly, for example `"command": "node", "args": ["${CLAUDE_PLUGIN_ROOT}/node_modules/eslint/bin/eslint.js"]`. The `node` plus script-path pattern works on every platform because `node.exe` is a real binary. To run a `.cmd` or `.bat` shim by name, use shell form. - -This example runs a Node script bundled with a plugin. Exec form passes the resolved script path as one argument with no quoting: - - { - "type": "command", - "command": "node", - "args": ["${CLAUDE_PLUGIN_ROOT}/scripts/format.js", "--fix"] - } - -The equivalent shell form needs quoting to handle paths with spaces or special characters: - - { - "type": "command", - "command": "node \"${CLAUDE_PLUGIN_ROOT}\"/scripts/format.js --fix" - } - -Both forms support the same path placeholders, and both export them as the environment variables `CLAUDE_PROJECT_DIR`, `CLAUDE_PLUGIN_ROOT`, and `CLAUDE_PLUGIN_DATA` on the spawned process, so a script can read `process.env.CLAUDE_PLUGIN_ROOT` regardless of how it was launched. Plugin hooks additionally substitute [`${user_config.*}`](</docs/en/plugins-reference#user-configuration>) values, in exec form only: the value is substituted into `command` and into each `args` element as a plain string, so no shell re-parses it. A shell-form plugin hook whose `command` references `${user_config.*}` fails with an [error](</docs/en/errors#plugin-command-references-user-config>) instead of running. To use an option value from a shell-form hook, read the `$CLAUDE_PLUGIN_OPTION_<KEY>` environment variable, such as `$CLAUDE_PLUGIN_OPTION_WEBHOOK_URL` for a `webhook_url` option, or set `args` to switch the hook to exec form. Before v2.1.207, shell-form plugin hook commands also substituted `${user_config.*}`. - -In exec form, `command` is the executable name or path only. If `command` is a bare name with no path separator and contains whitespace alongside `args`, Claude Code logs a warning because the spawn will fail: there is no executable named `node script.js`. Move the extra tokens into `args`. Absolute paths with spaces, such as `C:\Program Files\nodejs\node.exe`, are a single valid executable and don’t trigger the warning. - -#### - -​ - -HTTP hook fields - -In addition to the common fields, HTTP hooks accept these fields: - -Field| Required| Description ----|---|--- -`url`| yes| URL to send the POST request to -`headers`| no| Additional HTTP headers as key-value pairs. Values support environment variable interpolation using `$VAR_NAME` or `${VAR_NAME}` syntax. Only variables listed in `allowedEnvVars` are resolved -`allowedEnvVars`| no| List of environment variable names that may be interpolated into header values. References to unlisted variables are replaced with empty strings. Required for any env var interpolation to work - -Claude Code sends the hook’s JSON input as the POST request body with `Content-Type: application/json`. The response body uses the same JSON output format as command hooks. Error handling differs from command hooks; see HTTP response handling. This example sends `PreToolUse` events to a local validation service, authenticating with a token from the `MY_TOKEN` environment variable: - - { - "hooks": { - "PreToolUse": [ - { - "matcher": "Bash", - "hooks": [ - { - "type": "http", - "url": "http://localhost:8080/hooks/pre-tool-use", - "timeout": 30, - "headers": { - "Authorization": "Bearer $MY_TOKEN" - }, - "allowedEnvVars": ["MY_TOKEN"] - } - ] - } - ] - } - } - -#### - -​ - -MCP tool hook fields - -In addition to the common fields, MCP tool hooks accept these fields: - -Field| Required| Description ----|---|--- -`server`| yes| Name of a configured MCP server. For a [plugin-bundled server](</docs/en/mcp#plugin-provided-mcp-servers>), this is the scoped name `plugin:<plugin-name>:<server-name>`, such as `plugin:my-plugin:db`, not the bare server key. The server must already be connected; the hook never triggers an OAuth or connection flow -`tool`| yes| Name of the tool to call on that server -`input`| no| Arguments passed to the tool. String values support `${path}` substitution from the hook’s JSON input, such as `"${tool_input.file_path}"` - -The tool’s text content is treated like command-hook stdout: if it parses as valid JSON output it is processed as a decision, otherwise it is shown as plain text. If the named server is not connected, or the tool returns `isError: true`, the hook produces a non-blocking error and execution continues. MCP tool hooks are available on every hook event once Claude Code has connected to your MCP servers. `SessionStart` and `Setup` typically fire before servers finish connecting, so hooks on those events should expect the “not connected” error on first run. This example calls the `security_scan` tool on the `my_server` MCP server after each `Write` or `Edit`, passing the edited file’s path: - - { - "hooks": { - "PostToolUse": [ - { - "matcher": "Write|Edit", - "hooks": [ - { - "type": "mcp_tool", - "server": "my_server", - "tool": "security_scan", - "input": { "file_path": "${tool_input.file_path}" } - } - ] - } - ] - } - } - -#### - -​ - -Prompt and agent hook fields - -In addition to the common fields, prompt and agent hooks accept these fields: - -Field| Required| Description ----|---|--- -`prompt`| yes| Prompt text to send to the model. Use `$ARGUMENTS` as a placeholder for the hook input JSON. Escape with a backslash to include literal text: `\$1.00` renders as `$1.00` -`model`| no| Model to use for evaluation. Defaults to a fast model - -### - -​ - -Reference scripts by path - -Use these placeholders to reference hook scripts relative to the project or plugin root, regardless of the working directory when the hook runs: - - * `${CLAUDE_PROJECT_DIR}`: the project root. Claude Code also sets this variable in the environment of [stdio MCP servers](</docs/en/mcp#option-3-add-a-local-stdio-server>) and plugin LSP servers. - * `${CLAUDE_PLUGIN_ROOT}`: the plugin’s installation directory, for scripts bundled with a [plugin](</docs/en/plugins>). Changes on each plugin update. - * `${CLAUDE_PLUGIN_DATA}`: the plugin’s [persistent data directory](</docs/en/plugins-reference#persistent-data-directory>), for dependencies and state that should survive plugin updates. - -Prefer exec form for any hook that references a path placeholder. In shell form, wrap each placeholder in double quotes. - - * Project scripts - - * Plugin scripts - -This example uses `${CLAUDE_PROJECT_DIR}` to run a style checker from the project’s `.claude/hooks/` directory after any `Write` or `Edit` tool call: - - { - "hooks": { - "PostToolUse": [ - { - "matcher": "Write|Edit", - "hooks": [ - { - "type": "command", - "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/check-style.sh", - "args": [] - } - ] - } - ] - } - } - -Define plugin hooks in `hooks/hooks.json` with an optional top-level `description` field. When a plugin is enabled, its hooks merge with your user and project hooks.This example runs a formatting script bundled with the plugin: - - { - "description": "Automatic code formatting", - "hooks": { - "PostToolUse": [ - { - "matcher": "Write|Edit", - "hooks": [ - { - "type": "command", - "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh", - "args": [], - "timeout": 30 - } - ] - } - ] - } - } - -See the [plugin components reference](</docs/en/plugins-reference#hooks>) for details on creating plugin hooks. - -### - -​ - -Hooks in skills and agents - -In addition to settings files and plugins, hooks can be defined directly in [skills](</docs/en/skills>) and [subagents](</docs/en/sub-agents>) using frontmatter. These hooks are scoped to the component’s lifecycle and only run when that component is active. All hook events are supported. For subagents, `Stop` hooks are automatically converted to `SubagentStop` since that is the event that fires when a subagent completes. Hooks use the same configuration format as settings-based hooks but are scoped to the component’s lifetime and cleaned up when it finishes. This skill defines a `PreToolUse` hook that runs a security validation script before each `Bash` command: - - --- - name: secure-operations - description: Perform operations with security checks - hooks: - PreToolUse: - - matcher: "Bash" - hooks: - - type: command - command: "./scripts/security-check.sh" - --- - -Subagents use the same format in their YAML frontmatter. Frontmatter hooks in a project subagent run only after you accept the [workspace trust dialog](</docs/en/permissions#project-allow-rules-and-workspace-trust>) for the folder the agent file came from; see [which scopes are exempt](</docs/en/sub-agents#hooks-in-subagent-frontmatter>). Before v2.1.218, these hooks could run from folders you hadn’t trusted. - -### - -​ - -The `/hooks` menu - -Type `/hooks` in Claude Code to open a read-only browser for your configured hooks. The menu shows every hook event with a count of configured hooks, lets you drill into matchers, and shows the full details of each hook handler. Use it to verify configuration, check which settings file a hook came from, or inspect a hook’s command, prompt, or URL. The menu displays all five hook types: `command`, `prompt`, `agent`, `http`, and `mcp_tool`. Each hook is labeled with a `[type]` prefix and a source indicating where it was defined: - - * `User Settings`: from `~/.claude/settings.json` - * `Project Settings`: from `.claude/settings.json` - * `Local Settings`: from `.claude/settings.local.json` - * `Plugin Hooks`: from a plugin’s `hooks/hooks.json` - * `Session Hooks`: registered in memory for the current session - * `Built-in Hooks`: registered internally by Claude Code - -Selecting a hook opens a detail view showing its event, matcher, type, source file, and the full command, prompt, or URL. The menu is read-only: to add, modify, or remove hooks, edit the settings JSON directly or ask Claude to make the change. - -### - -​ - -Disable or remove hooks - -To remove a hook, delete its entry from the settings JSON file. To temporarily disable all hooks without removing them, set `"disableAllHooks": true` in your settings file. There is no way to disable an individual hook while keeping it in the configuration. The `disableAllHooks` setting respects the managed settings hierarchy. If an administrator has configured hooks through managed policy settings, `disableAllHooks` set in user, project, or local settings can’t disable those managed hooks. Only `disableAllHooks` set at the managed settings level can disable managed hooks. Direct edits to hooks in settings files are normally picked up automatically by the file watcher. - -## - -​ - -Hook input and output - -Command hooks receive JSON data via stdin and communicate results through exit codes, stdout, and stderr. HTTP hooks receive the same JSON as the POST request body and communicate results through the HTTP response body. This section covers fields and behavior common to all events. Each event’s section under Hook events includes its specific input schema and decision control options. On macOS and Linux, command hooks run in their own session without a controlling terminal as of v2.1.139. The hook process and any child processes can’t open `/dev/tty` or send escape sequences directly to the Claude Code interface. Windows has no `/dev/tty`. To surface a message to the user on any platform, return `systemMessage` in JSON output. To trigger a desktop notification, set a window title, or ring the bell, return `terminalSequence` instead. - -### - -​ - -Common input fields - -Hook events receive these fields as JSON, in addition to event-specific fields documented in each hook event section. For command hooks, this JSON arrives via stdin. For HTTP hooks, it arrives as the POST request body. - -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. The transcript file is written asynchronously and may lag the in-memory conversation, so it may not yet include the current turn’s most recent messages when a hook fires. Hooks that need the final assistant text of the current turn should use `last_assistant_message` on Stop and SubagentStop instead of reading the transcript -`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"`. The mode labeled **Manual** arrives as `"default"`, never as `"manual"`, so scripts that match `"default"` keep working. Not all events receive this field. Check the JSON example in each hook event section -`effort`| Object with a `level` field holding the active [effort level](</docs/en/model-config#adjust-effort-level>) for the turn: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. If the requested model effort exceeds what the current model supports, this is the downgraded level the model actually used. Ultracode is not a distinct level and reports as `"xhigh"`. The object matches the [status line](</docs/en/statusline#available-data>) `effort` field. Present for events that fire within a tool-use context, such as `PreToolUse`, `PostToolUse`, `Stop`, and `SubagentStop`, when the current model supports the effort parameter. The level is also available to hook commands and the Bash tool as the `$CLAUDE_EFFORT` environment variable. -`hook_event_name`| Name of the event that fired - -When running with `--agent` or inside a subagent, two additional fields are included: - -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. See SubagentStart for the values custom and plugin subagents report and 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 doesn’t change when you switch models with `/model` during a session. One set of variables is not inherited: Claude Code [removes `OTEL_*` exporter variables from every subprocess it spawns](</docs/en/monitoring-usage#administrator-configuration>), including hooks. 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", - "hook_event_name": "PreToolUse", - "tool_name": "Bash", - "tool_input": { - "command": "npm test", - "description": "Run test suite", - "timeout": 120000, - "run_in_background": false - }, - "tool_use_id": "toolu_01ABC123..." - } - -The `tool_name`, `tool_input`, and `tool_use_id` fields are event-specific. Each hook event section documents the additional fields for that event. - -### - -​ - -Exit code output - -The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored. **Exit 0** means success. Claude Code parses stdout for JSON output fields. JSON output is only processed on exit 0. For most events, stdout is written to the debug log but not shown in the transcript. The exceptions are `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart`, where stdout is added as context that Claude can see and act on. Stderr from a hook that exits 0 goes to the debug log only, never the transcript, and Claude never sees it. To read it yourself, enable debug logging. To surface a warning to Claude from a `PostToolUse` or `PostToolUseFailure` hook, exit 2 instead so Claude sees the stderr even though the tool already ran. **Exit 2** means a blocking error. Claude Code ignores stdout and any JSON in it. Instead, stderr text is fed back to Claude as an error message. The effect depends on the event: `PreToolUse` blocks the tool call, `UserPromptSubmit` rejects the prompt, and so on. See exit code 2 behavior for the full list. A hook that exits 2 while printing JSON that fails JSON output schema validation still blocks: Claude Code uses stderr as the blocking reason and records the validation failure in the debug log. Before v2.1.214, Claude Code treated that combination as a non-blocking error and the action proceeded. **Any other exit code** is a non-blocking error for most hook events. The action proceeds, and the transcript shows a `<hook name> hook error` notice followed by the first line of stderr, prefixed with `Failed with non-blocking status code:`. To capture the full stderr, enable debug logging. For example, a hook command script that blocks dangerous Bash commands: - - #!/bin/bash - # Reads JSON input from stdin, checks the command - input=$(cat) - command=$(jq -r '.tool_input.command' <<<"$input") - - if [[ "$command" == rm* ]]; then - echo "Blocked: rm commands are not allowed" >&2 - exit 2 # Blocking error: tool call is prevented - fi - - exit 0 # No decision: the normal permission flow applies - -For most hook events, only exit code 2 blocks the action. Claude Code treats exit code 1 as a non-blocking error and proceeds with the action, even though 1 is the conventional Unix failure code. If your hook is meant to enforce a policy, use `exit 2`. The exception is `WorktreeCreate`, where any non-zero exit code aborts worktree creation. - -#### - -​ - -Exit code 2 behavior per event - -Exit code 2 is the way a hook signals “stop, don’t do this.” The effect depends on the event, because some events represent actions that can be blocked (like a tool call that hasn’t happened yet) and others represent things that already happened or can’t be prevented. - -Hook event| Can block?| What happens on exit 2 ----|---|--- -`PreToolUse`| Yes| Blocks the tool call -`PermissionRequest`| Yes| Denies the permission -`UserPromptSubmit`| Yes| Blocks prompt processing and erases the prompt -`UserPromptExpansion`| Yes| Blocks the expansion -`Stop`| Yes| Prevents Claude from stopping, continues the conversation -`SubagentStop`| Yes| Prevents the subagent from stopping -`TeammateIdle`| Yes| Prevents the teammate from going idle, so it continues working -`TaskCreated`| Yes| Rolls back the task creation -`TaskCompleted`| Yes| Prevents the task from being marked as completed -`ConfigChange`| Yes| Blocks the configuration change from taking effect (except `policy_settings`) -`StopFailure`| No| Output and exit code are ignored -`PostToolUse`| No| Shows stderr to Claude; the tool already ran -`PostToolUseFailure`| No| Shows stderr to Claude; the tool already failed -`PostToolBatch`| Yes| Stops the agentic loop before the next model call -`PermissionDenied`| No| Exit code and stderr are ignored because the denial already occurred. Use JSON `hookSpecificOutput.retry: true` to tell the model it may retry -`Notification`| No| Shows stderr to user only -`SubagentStart`| No| Shows stderr to user only -`SessionStart`| No| Shows stderr to user only -`Setup`| No| Shows stderr to user only -`SessionEnd`| No| Shows stderr to user only -`CwdChanged`| No| Shows stderr to user only -`DirectoryAdded`| No| Stderr goes to the debug log; the directory is already added -`FileChanged`| No| Shows stderr to user only -`PreCompact`| Yes| Blocks compaction -`PostCompact`| No| Shows stderr to user only -`Elicitation`| Yes| Denies the elicitation -`ElicitationResult`| Yes| Blocks the response (action becomes decline) -`WorktreeCreate`| Yes| Any non-zero exit code causes worktree creation to fail -`WorktreeRemove`| No| Failures are logged in debug mode only -`InstructionsLoaded`| No| Exit code is ignored -`MessageDisplay`| No| The original text is displayed - -For `SessionStart`, `Setup`, and `SubagentStart`, the exit code 2 stderr renders in the transcript as a `<hook name> hook error` notice, the same way a non-blocking error does. Claude doesn’t see it, and the session or subagent proceeds. For `SubagentStart`, the notice appears in the subagent’s own transcript, not in the parent conversation. - -### - -​ - -HTTP response handling - -HTTP hooks use HTTP status codes and response bodies instead of exit codes and stdout: - - * **2xx with an empty body** : success, equivalent to exit code 0 with no output - * **2xx with a plain text body** : success, the text is added as context - * **2xx with a JSON body** : success, parsed using the same JSON output schema as command hooks - * **Non-2xx status** : non-blocking error, execution continues - * **Connection failure or timeout** : non-blocking error, execution continues - -Unlike command hooks, HTTP hooks can’t signal a blocking error through status codes alone. To block a tool call or deny a permission, return a 2xx response with a JSON body containing the appropriate decision fields. - -### - -​ - -JSON output - -Exit codes only let you block or stay silent, but JSON output gives you finer-grained control. Instead of exiting with code 2 to block, exit 0 and print a JSON object to stdout. Claude Code reads specific fields from that JSON to control behavior, including decision control for blocking, allowing, or escalating to the user. - -You must choose one approach per hook, not both: either use exit codes alone for signaling, or exit 0 and print JSON for structured control. Claude Code only processes JSON on exit 0. If you exit 2, any JSON is ignored. - -Your hook’s stdout must contain only the JSON object. If your shell profile prints text on startup, it can interfere with JSON parsing. See [JSON validation failed](</docs/en/hooks-guide#json-validation-failed>) in the troubleshooting guide. Hook output strings, including `additionalContext`, `systemMessage`, and plain stdout, are capped at 10,000 characters. Output that exceeds this limit is saved to a file and replaced with a preview and file path, the same way a large valid Bash result is handled under [Output limits](</docs/en/tools-reference#output-limits>). The JSON object supports three kinds of fields: - - * **Universal fields** like `continue` work across all events. These are listed in the table below. - * **Top-level`decision` and `reason`** are used by some events to block or provide feedback. - * **`hookSpecificOutput`** is a nested object for events that need richer control. It requires a `hookEventName` field set to the event name. - -Field| Default| Description ----|---|--- -`continue`| `true`| If `false`, Claude stops processing entirely after the hook runs. Takes precedence over any event-specific decision fields -`stopReason`| none| Message shown to the user when `continue` is `false`. Not shown to Claude -`suppressOutput`| `false`| If `true`, hides the hook’s stdout from the transcript. Stdout still appears in the debug log -`systemMessage`| none| Warning message shown to the user -`terminalSequence`| none| A terminal escape sequence for Claude Code to emit on your behalf, such as a desktop notification, window title, or bell. Restricted to OSC `0`/`1`/`2`/`9`/`99`/`777` and BEL. If the value contains anything outside the allowlist, the field is ignored. Use this instead of writing to `/dev/tty`, which is unavailable to hooks - -To stop Claude entirely regardless of event type: - - { "continue": false, "stopReason": "Build failed, fix errors before continuing" } - -For `PreToolUse` and `PostToolUse` hooks, the stop applies even when the tool call fails or completes while Claude is still streaming a response. - -#### - -​ - -Emit terminal notifications - -The `terminalSequence` field requires Claude Code v2.1.141 or later. Hooks run without a controlling terminal, so writing escape sequences directly to `/dev/tty` fails. Instead, return the escape sequence in the `terminalSequence` field and Claude Code emits it for you through its own terminal write path. This is race-free, works inside tmux and GNU screen, and works on Windows where there is no `/dev/tty`. The field accepts a string of one or more allowlisted escape sequences: - - * OSC `0`, `1`, `2`: window and icon titles - * OSC `9`: iTerm2, ConEmu, Windows Terminal, and WezTerm notifications, including `9;4` taskbar progress - * OSC `99`: Kitty notifications - * OSC `777`: urxvt, Ghostty, and Warp notifications - * Bare BEL - -Sequences may be terminated with BEL or with ST. Anything outside the allowlist, including CSI cursor and color sequences, OSC palette sequences, OSC 8 hyperlinks, OSC 52 clipboard writes, and OSC 1337, is rejected and the field is ignored. The example below fires a desktop notification from a `Notification` hook. The escape sequence is built with `printf` octal escapes so the control bytes never appear on the shell command line, and `jq -n --arg` builds the JSON output so quotes, backslashes, and newlines in the notification message are escaped correctly: - - #!/bin/bash - # Notification hook: ping the desktop when Claude Code needs attention. - input=$(cat) - title="Claude Code" - body=$(jq -r '.message // "Needs your attention"' <<<"$input") - seq=$(printf '\033]777;notify;%s;%s\007' "$title" "$body") - jq -nc --arg seq "$seq" '{terminalSequence: $seq}' - -The `{ "terminalSequence": "..." }` shape is the same from any shell or language. On Windows, build the escape string in PowerShell or a script and emit the same JSON object. - -`terminalSequence` is the supported replacement for hooks that previously wrote escape sequences directly to `/dev/tty`. The allowlist is restricted to sequences that can’t move the cursor or alter colors, so a hook can never corrupt an on-screen prompt. - -#### - -​ - -Add context for Claude - -The `additionalContext` field passes a string from your hook into Claude’s context window. Claude Code wraps the string in a system reminder and inserts it into the conversation at the point where the hook fired. Claude reads the reminder on the next model request, but it doesn’t appear as a chat message in the interface. Return `additionalContext` inside `hookSpecificOutput` alongside the event name: - - { - "hookSpecificOutput": { - "hookEventName": "PostToolUse", - "additionalContext": "This file is generated. Edit src/schema.ts and run `bun generate` instead." - } - } - -Where the reminder appears depends on the event: - - * SessionStart, Setup, and SubagentStart: at the start of the conversation, before the first prompt - * UserPromptSubmit and UserPromptExpansion: alongside the submitted prompt - * PreToolUse, PostToolUse, PostToolUseFailure, and PostToolBatch: next to the tool result - * Stop and SubagentStop: at the end of the turn. The conversation continues so Claude can act on the feedback. See Stop decision control - -When several hooks return `additionalContext` for the same event, Claude receives all of the values. If a value exceeds 10,000 characters, Claude Code writes the full text to a file in the session directory and passes Claude the file path with a short preview instead. Use `additionalContext` for information Claude should know about the current state of your environment or the operation that just ran: - - * **Environment state** : the current branch, deployment target, or active feature flags - * **Conditional project rules** : which test command applies to the file just edited, which directories are read-only in this worktree - * **External data** : open issues assigned to you, recent CI results, content fetched from an internal service - -For instructions that never change, prefer [CLAUDE.md](</docs/en/memory>). It loads without running a script and is the standard place for static project conventions. Write the text as factual statements rather than imperative system instructions. Phrasing such as “The deployment target is production” or “This repo uses `bun test`” reads as project information. Text framed as out-of-band system commands can trigger Claude’s prompt-injection defenses, which causes Claude to surface the text to you instead of treating it as context. Claude Code saves the injected text in the session transcript. For mid-session events like `PostToolUse` or `UserPromptSubmit`, when you resume with `--continue` or `--resume`, Claude Code replays the saved text rather than re-running the hook for past turns, so values like timestamps or commit SHAs become stale. `SessionStart` hooks run again on resume with `source` set to `"resume"`, or `"fork"` if you added `--fork-session`, so they can refresh their context. - -#### - -​ - -Decision control - -Not every event supports blocking or controlling behavior through JSON. The events that do each use a different set of fields to express that decision. Use this table as a quick reference before writing a hook: - -Events| Decision pattern| Key fields ----|---|--- -UserPromptSubmit, UserPromptExpansion, PostToolUse, PostToolUseFailure, PostToolBatch, Stop, SubagentStop, ConfigChange, PreCompact| Top-level `decision`| `decision: "block"`, `reason`. Stop and SubagentStop also accept `hookSpecificOutput.additionalContext` for non-error feedback that continues the conversation -TeammateIdle, TaskCreated, TaskCompleted| Exit code or `continue: false`| Exit code 2 blocks the action with stderr feedback. JSON `{"continue": false, "stopReason": "..."}` also stops the teammate entirely, matching `Stop` hook behavior -PreToolUse| `hookSpecificOutput`| `permissionDecision` (allow/deny/ask/defer), `permissionDecisionReason` -PermissionRequest| `hookSpecificOutput`| `decision.behavior` (allow/deny) -PermissionDenied| `hookSpecificOutput`| `retry: true` tells the model it may retry the denied tool call -WorktreeCreate| path return| Command hook prints path on stdout; HTTP hook returns `hookSpecificOutput.worktreePath`. Hook failure or missing path fails creation -Elicitation| `hookSpecificOutput`| `action` (accept/decline/cancel), `content` (form field values for accept) -ElicitationResult| `hookSpecificOutput`| `action` (accept/decline/cancel), `content` (form field values override) -MessageDisplay| `hookSpecificOutput`| `displayContent` replaces the displayed text on screen. Display-only: the transcript and what Claude sees keep the original -SessionStart, Setup, SubagentStart| Context only| `hookSpecificOutput.additionalContext` adds context for Claude. SessionStart also accepts `initialUserMessage`, `watchPaths`, `sessionTitle`, and `reloadSkills`. No blocking or decision control -WorktreeRemove, Notification, SessionEnd, PostCompact, InstructionsLoaded, StopFailure, CwdChanged, DirectoryAdded, FileChanged| None| No decision control. Used for side effects like logging or cleanup - -A few events can also rewrite content rather than only allow or block it: - - * `PreToolUse`: `updatedInput` directly under `hookSpecificOutput` replaces a tool’s arguments before it runs. See PreToolUse decision control - * `PermissionRequest`: `updatedInput` inside the `decision` object. See PermissionRequest decision control - * `PostToolUse`: `updatedToolOutput` replaces the tool’s result. See PostToolUse decision control - * `UserPromptSubmit`: can’t replace the prompt; it only injects `additionalContext` alongside it - -For redaction or transformation use cases, intercept at `PreToolUse` for outbound tool inputs and `PostToolUse` for inbound tool results. Here are examples of each pattern in action: - - * Top-level decision - - * PreToolUse - - * PermissionRequest - -The only value for `decision` is `"block"`. To allow the action to proceed, omit `decision` from your JSON, or exit 0 without any JSON at all: - - { - "decision": "block", - "reason": "Test suite must pass before proceeding" - } - -Uses `hookSpecificOutput` for richer control: allow, deny, or escalate to the user. You can also modify tool input before it runs or inject additional context for Claude. See PreToolUse decision control for the full set of options. - - { - "hookSpecificOutput": { - "hookEventName": "PreToolUse", - "permissionDecision": "deny", - "permissionDecisionReason": "Database writes are not allowed" - } - } - -Uses `hookSpecificOutput` to allow or deny a permission request on behalf of the user. When allowing, you can also modify the tool’s input or apply permission rules so the user isn’t prompted again. See PermissionRequest decision control for the full set of options. - - { - "hookSpecificOutput": { - "hookEventName": "PermissionRequest", - "decision": { - "behavior": "allow", - "updatedInput": { - "command": "npm run lint" - } - } - } - } - -For extended examples including Bash command validation, prompt filtering, and auto-approval scripts, see [What you can automate](</docs/en/hooks-guide#what-you-can-automate>) in the guide and the [Bash command validator reference implementation](<https://github.com/anthropics/claude-code/blob/main/examples/hooks/bash_command_validator_example.py>). - -## - -​ - -Hook events - -Each event corresponds to a point in Claude Code’s lifecycle where hooks can run. The sections below are ordered to match the lifecycle: from session setup through the agentic loop to session end. Each section describes when the event fires, what matchers it supports, the JSON input it receives, and how to control behavior through output. - -### - -​ - -SessionStart - -Runs when Claude Code starts a new session or resumes an existing session. Useful for loading development context like existing issues or recent changes to your codebase, or setting up environment variables. For static context that doesn’t require a script, use [CLAUDE.md](</docs/en/memory>) instead. SessionStart runs on every session, so keep these hooks fast. Only `type: "command"` and `type: "mcp_tool"` hooks are supported. The matcher value corresponds to how the session was initiated: - -Matcher| When it fires ----|--- -`startup`| New session -`resume`| `--resume`, `--continue`, or `/resume` -`clear`| `/clear` -`compact`| Auto or manual compaction -`fork`| A new session forked from an existing one: `--fork-session` with `--resume` or `--continue`, the `/fork` background copy, or `/branch` - -Before v2.1.214, forked sessions reported source `"resume"`. - -#### - -​ - -SessionStart input - -In addition to the common input fields, SessionStart hooks receive `source` and optionally `model`, `agent_type`, and `session_title`: - -Field| Description ----|--- -`source`| How the session started: `"startup"` for new sessions, `"resume"` for resumed sessions, `"clear"` after `/clear`, `"compact"` after compaction, or `"fork"` for a new session forked from an existing one -`model`| The active model identifier. It can be omitted, for example after `/clear` or when a session is restored through conversation recovery, so check for the field before reading it -`agent_type`| The agent name, present when you start Claude Code with `claude --agent <name>` -`session_title`| The current session title if one is already set, for example via `--name` or `/rename`. A hook that emits `sessionTitle` can check `session_title` first to avoid overwriting a title the user set explicitly - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "hook_event_name": "SessionStart", - "source": "startup", - "model": "claude-sonnet-5" - } - -#### - -​ - -SessionStart decision control - -Any text your hook script prints to stdout is added as context for Claude. In addition to the JSON output fields available to all hooks, you can return these event-specific fields: - -Field| Description ----|--- -`additionalContext`| String added to Claude’s context at the start of the conversation, before the first prompt. See Add context for Claude for how the text is delivered and what to put in it -`initialUserMessage`| String used as the first user message of the session. Applies in [non-interactive mode](</docs/en/headless>) with the `-p` flag, where it becomes the first turn even if no prompt is provided. If a prompt is provided, it follows as the next turn. Unlike `additionalContext`, which attaches to an existing turn, this creates the turn -`sessionTitle`| Sets the session title, with the same effect as `/rename`. Use to name sessions automatically from the launch folder, git branch, or worktree name. Applies when `source` is `"startup"`, `"resume"`, or `"fork"`; ignored on `"clear"` and `"compact"` -`watchPaths`| Array of absolute paths to watch for FileChanged events during this session -`reloadSkills`| Boolean. When `true`, Claude Code re-scans the [skill](</docs/en/skills>) and command directories after the SessionStart hooks complete, so skills the hook installed are available in the same session, starting with the first prompt - - { - "hookSpecificOutput": { - "hookEventName": "SessionStart", - "additionalContext": "Current branch: feat/auth-refactor\nUncommitted changes: src/auth.ts, src/login.tsx\nActive issue: #4211 Migrate to OAuth2", - "sessionTitle": "auth-refactor" - } - } - -Since plain stdout already reaches Claude for this event, a hook that only loads context can print to stdout directly without building JSON. Use the JSON form when you need to combine context with other fields such as `suppressOutput` or `sessionTitle`. Use `reloadSkills` when a SessionStart hook installs or updates skills. Skill discovery normally runs before SessionStart hooks finish, so files the hook writes into `~/.claude/skills/` or `.claude/skills/` would otherwise only appear in the next session. This example syncs a shared skills repository and requests the re-scan: - - #!/bin/bash - - git -C ~/.claude/skills/team-skills pull --quiet 2>/dev/null || \ - git clone --quiet https://git.example.com/your-org/team-skills.git ~/.claude/skills/team-skills - - echo '{"hookSpecificOutput": {"hookEventName": "SessionStart", "reloadSkills": true}}' - -The repository URL is a placeholder; replace it with your own skills repository. With the placeholder, the clone fails and prints a `fatal:` message to stderr. Stderr from a SessionStart hook that exits 0 is informational only, so the `reloadSkills` request still applies. - -#### - -​ - -Persist environment variables - -SessionStart hooks have access to the `CLAUDE_ENV_FILE` environment variable, which provides a file path where you can persist environment variables for subsequent Bash commands. To set individual environment variables, write `export` statements to `CLAUDE_ENV_FILE`. Use append (`>>`) to preserve variables set by other hooks: - - #!/bin/bash - - if [ -n "$CLAUDE_ENV_FILE" ]; then - echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE" - echo 'export DEBUG_LOG=true' >> "$CLAUDE_ENV_FILE" - echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE" - fi - - exit 0 - -To capture all environment changes from setup commands, compare the exported variables before and after: - - #!/bin/bash - - ENV_BEFORE=$(export -p | sort) - - # Run your setup commands that modify the environment - source ~/.nvm/nvm.sh - nvm use 20 - - if [ -n "$CLAUDE_ENV_FILE" ]; then - ENV_AFTER=$(export -p | sort) - comm -13 <(echo "$ENV_BEFORE") <(echo "$ENV_AFTER") >> "$CLAUDE_ENV_FILE" - fi - - exit 0 - -`CLAUDE_ENV_FILE` is available for SessionStart, Setup, CwdChanged, and FileChanged hooks. Other hook types don’t have access to this variable. - -### - -​ - -Setup - -Fires only when you launch Claude Code with `--init-only`, or with `--init` or `--maintenance` in [non-interactive mode](</docs/en/headless>) with the `-p` flag. It doesn’t fire on normal startup. Use it for one-time dependency installation or scheduled cleanup that you trigger explicitly from CI or scripts, separate from normal session startup. For per-session initialization, use SessionStart instead. The matcher value corresponds to the CLI flag that triggered the hook: - -Matcher| When it fires ----|--- -`init`| `claude --init-only` or `claude -p --init` -`maintenance`| `claude -p --maintenance` - -When you run `claude --init-only`, Claude Code runs Setup hooks and `SessionStart` hooks with the `startup` matcher, then exits without starting a conversation. `--init` and `--maintenance` fire Setup hooks only when you combine them with `-p`. In an interactive session, those two flags don’t currently fire Setup hooks. When you start or continue a conversation with `-p`, you also need to supply a prompt, as an argument or piped on stdin. You can skip the prompt when a `SessionStart` hook supplies `initialUserMessage` or when you resume a session with a deferred tool call. On success, `--init-only` prints nothing to the terminal. To confirm the hooks ran, start with `claude --debug-file <path> --init-only`, replacing `<path>` with a log file location, and check the log for the Setup and SessionStart hook entries. Because Setup doesn’t fire on every launch, a plugin that needs a dependency installed can’t rely on Setup alone. The practical pattern is to check for the dependency on first use and install on miss, for example a hook or skill that tests for `${CLAUDE_PLUGIN_DATA}/node_modules` and runs `npm install` if absent. See the [persistent data directory](</docs/en/plugins-reference#persistent-data-directory>) for where to store installed dependencies. - -#### - -​ - -Setup input - -In addition to the common input fields, Setup hooks receive a `trigger` field set to either `"init"` or `"maintenance"`: - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "hook_event_name": "Setup", - "trigger": "init" - } - -#### - -​ - -Setup decision control - -Setup hooks can’t block. Any non-zero exit code, including 2, surfaces stderr to the user as a `<hook name> hook error` notice, and execution continues. In [non-interactive mode](</docs/en/headless>), hook output appears only when you launch with `--verbose`. To pass information into Claude’s context, return `additionalContext` in JSON output; plain stdout is written to the debug log only. In addition to the JSON output fields available to all hooks, you can return these event-specific fields: - -Field| Description ----|--- -`additionalContext`| String added to Claude’s context. Multiple hooks’ values are concatenated - - { - "hookSpecificOutput": { - "hookEventName": "Setup", - "additionalContext": "Dependencies installed: node_modules, .venv" - } - } - -Setup hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in SessionStart hooks. Only `type: "command"` and `type: "mcp_tool"` hooks are supported. - -### - -​ - -InstructionsLoaded - -Fires when a `CLAUDE.md` or `.claude/rules/*.md` file is loaded into context. This event fires at session start for eagerly-loaded files and again later when files are lazily loaded, for example when Claude accesses a subdirectory that contains a nested `CLAUDE.md` or when conditional rules with `paths:` frontmatter match. The hook doesn’t support blocking or decision control. It runs asynchronously for observability purposes. The matcher runs against `load_reason`. For example, use `"matcher": "session_start"` to fire only for files loaded at session start, or `"matcher": "path_glob_match|nested_traversal"` to fire only for lazy loads. - -#### - -​ - -InstructionsLoaded input - -In addition to the common input fields, InstructionsLoaded hooks receive these fields: - -Field| Description ----|--- -`file_path`| Absolute path to the instruction file that was loaded -`memory_type`| Scope of the file: `"User"`, `"Project"`, `"Local"`, or `"Managed"` -`load_reason`| Why the file was loaded: `"session_start"`, `"nested_traversal"`, `"path_glob_match"`, `"include"`, or `"compact"`. The `"compact"` value fires when instruction files are re-loaded after a compaction event -`globs`| Path glob patterns from the file’s `paths:` frontmatter, if any. Present only for `path_glob_match` loads -`trigger_file_path`| Path to the file whose access triggered this load, for lazy loads -`parent_file_path`| Path to the parent instruction file that included this one, for `include` loads - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl", - "cwd": "/Users/my-project", - "hook_event_name": "InstructionsLoaded", - "file_path": "/Users/my-project/CLAUDE.md", - "memory_type": "Project", - "load_reason": "session_start" - } - -#### - -​ - -InstructionsLoaded decision control - -InstructionsLoaded hooks have no decision control. They can’t block or modify instruction loading. Use this event for audit logging, compliance tracking, or observability. - -### - -​ - -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. A `UserPromptSubmit` command, HTTP, or MCP tool hook that reaches its timeout is canceled and its output, including any `additionalContext`, is discarded. The prompt still reaches Claude without that context. The transcript shows a notice naming the hook, the timeout that fired, and that the output was discarded. An [Agent SDK callback hook](</docs/en/agent-sdk/hooks>) on `UserPromptSubmit` that reaches its timeout blocks the prompt with a message naming the hook and the timeout, because a callback there can be acting as a policy gate that must not fail open. The session continues. Before v2.1.208, a callback timeout on that event ended the turn with an execution error. - -#### - -​ - -UserPromptSubmit input - -In addition to the common input fields, UserPromptSubmit hooks receive the `prompt` field containing the text the user submitted. - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "permission_mode": "default", - "hook_event_name": "UserPromptSubmit", - "prompt": "Write a function to calculate the factorial of a number" - } - -#### - -​ - -UserPromptSubmit decision control - -`UserPromptSubmit` hooks can control whether a user prompt is processed and add context. All JSON output fields are available. There are two ways to add context to the conversation on exit code 0: - - * **Plain text stdout** : any non-JSON text written to stdout is added as context - * **JSON with`additionalContext`**: use the JSON format below for more control. The `additionalContext` field is added as context - -Plain stdout is shown as hook output in the transcript. The `additionalContext` value is injected as a system reminder that Claude reads without a visible transcript entry. To block a prompt, return a JSON object with `decision` set to `"block"`: - -Field| Description ----|--- -`decision`| `"block"` prevents the prompt from being processed and erases it from context. Omit to allow the prompt to proceed -`reason`| Shown to the user when `decision` is `"block"`. Not added to context -`additionalContext`| String added to Claude’s context alongside the submitted prompt. See Add context for Claude -`sessionTitle`| Sets the session title. Use to name sessions automatically based on the prompt content -`suppressOriginalPrompt`| If `true` when `decision` is `"block"`, omits the original prompt text from the block message shown to the user - - { - "decision": "block", - "reason": "Explanation for decision", - "hookSpecificOutput": { - "hookEventName": "UserPromptSubmit", - "additionalContext": "My additional context here", - "sessionTitle": "My session title" - } - } - -### - -​ - -UserPromptExpansion - -Runs when a user-typed command expands into a prompt before reaching Claude. Use this to block specific commands from direct invocation, inject context for a particular skill, or log which commands users invoke. For example, a hook matching `deploy` can block `/deploy` unless an approval file is present, or a hook matching a review skill can append the team’s review checklist as `additionalContext`. This event covers the path `PreToolUse` doesn’t: a `PreToolUse` hook matching the `Skill` tool fires only when Claude calls the tool, but typing `/skillname` directly bypasses `PreToolUse`. `UserPromptExpansion` fires on that direct path. Matches on `command_name`. Leave the matcher empty to fire on every prompt-type command. - -#### - -​ - -UserPromptExpansion input - -In addition to the common input fields, UserPromptExpansion hooks receive `expansion_type`, `command_name`, `command_args`, `command_source`, and the original `prompt` string. The `expansion_type` field is `slash_command` for skill and custom commands, or `mcp_prompt` for MCP server prompts. - - { - "session_id": "abc123", - "transcript_path": "/Users/.../00893aaf.jsonl", - "cwd": "/Users/...", - "permission_mode": "default", - "hook_event_name": "UserPromptExpansion", - "expansion_type": "slash_command", - "command_name": "example-skill", - "command_args": "arg1 arg2", - "command_source": "plugin", - "prompt": "/example-skill arg1 arg2" - } - -#### - -​ - -UserPromptExpansion decision control - -`UserPromptExpansion` hooks can block the expansion or add context. All JSON output fields are available. - -Field| Description ----|--- -`decision`| `"block"` prevents the command from expanding. Omit to allow it to proceed -`reason`| Shown to the user when `decision` is `"block"` -`additionalContext`| String added to Claude’s context alongside the expanded prompt. See Add context for Claude - - { - "decision": "block", - "reason": "This slash command is not available", - "hookSpecificOutput": { - "hookEventName": "UserPromptExpansion", - "additionalContext": "Additional context for this expansion" - } - } - -### - -​ - -MessageDisplay - -Runs while an assistant message streams to the screen. Claude Code displays the message in increments: each time a batch of newly completed lines is ready to render, the hook runs once with those lines and Claude Code renders the hook’s replacement text in their place. A long message produces several calls; a short message may produce only one. Use MessageDisplay to: - - * strip markdown for a minimal display - * transform the text an Agent SDK application shows its users - * redact API keys or internal hostnames from Claude’s responses - -Claude Code holds each batch until your hook returns, so keep the hook fast. If the hook fails or times out, Claude Code displays the original text. The default timeout for this event is 10 seconds; if your hook needs more time, set the `timeout` field in the hook entry. MessageDisplay is display-only: the replacement text changes only what is rendered on screen. The transcript and what Claude sees keep the original text, so Claude never sees the replacement, and verbose mode shows the original. The hook receives assistant message text only, so tool results and the text you type render unchanged. MessageDisplay doesn’t support matchers and fires for every assistant message that streams text; messages with no text, such as tool-call-only responses, don’t trigger it. In non-interactive runs, including Agent SDK queries and `claude -p`, MessageDisplay runs once per assistant message instead of once per batch of lines. The single call arrives after the message completes and carries the full message text: `index` is `0`, `final` is `true`, and `delta` holds the entire message. A hook that collects the `delta` text for each message receives the same total text in both modes. - -#### - -​ - -MessageDisplay input - -In addition to the common input fields, MessageDisplay hooks receive identifiers for the turn and message, the position of this call within the message, and the new text in `delta`. Batch boundaries depend on how the text streams, so use `index` and `final` to track progress through a message rather than expecting lines to be grouped a particular way. - -Field| Description ----|--- -`turn_id`| UUID of the current turn -`message_id`| UUID of the assistant message being displayed. Stable across every batch of the same message. This is not the API `msg_…` id, so it can’t be correlated with transcript message ids -`index`| Zero-based index of this batch within the message -`final`| `true` on the message’s last batch. Each message has exactly one final batch -`delta`| The newly completed lines since the prior batch, terminating newlines included. Always whole lines, except the final batch which may end mid-line. In interactive runs, the final batch’s delta is empty when the message ends on a newline, so treat `final`, not a non-empty delta, as the end-of-message signal. In Agent SDK and `claude -p` runs, the single call carries the entire message - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl", - "cwd": "/Users/my-project", - "hook_event_name": "MessageDisplay", - "turn_id": "0c9e6a2f-7d41-4f4e-9a15-3f4f7c2b8d10", - "message_id": "5b2a9c8e-1f63-4d8a-b7c4-9e0d2a6f1c3b", - "index": 0, - "final": false, - "delta": "Here is the plan:\n" - } - -#### - -​ - -MessageDisplay output - -In addition to the JSON output fields available to all hooks, MessageDisplay hooks can return `displayContent` to replace the delta on screen: - -Field| Description ----|--- -`displayContent`| Text displayed in place of the delta. Omit it to display the original - -MessageDisplay hooks have no decision control. They can’t block the message or change what is stored in the transcript or sent to Claude. This example strips markdown formatting from Claude’s responses for a plain-text display. The script reads each batch from stdin, removes bold markers and inline code backticks from `delta`, and returns the result as `displayContent`. - - * macOS/Linux - - * Windows (PowerShell) - -Register a command hook for the event in your settings file: - - { - "hooks": { - "MessageDisplay": [ - { - "hooks": [ - { - "type": "command", - "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/plain-display.sh", - "args": [] - } - ] - } - ] - } - } - -Save this script to `.claude/hooks/plain-display.sh` in your project and make it executable with `chmod +x`: - - #!/bin/bash - jq '{hookSpecificOutput: {hookEventName: "MessageDisplay", displayContent: (.delta | gsub("\\*\\*"; "") | gsub("`"; ""))}}' - -Register a command hook that runs the script through PowerShell: - - { - "hooks": { - "MessageDisplay": [ - { - "hooks": [ - { - "type": "command", - "command": "powershell.exe", - "args": [ - "-NoProfile", - "-ExecutionPolicy", - "Bypass", - "-File", - "${CLAUDE_PROJECT_DIR}/.claude/hooks/plain-display.ps1" - ] - } - ] - } - ] - } - } - -The `-NoProfile` flag skips loading your PowerShell profile so the hook starts fast, and `-ExecutionPolicy Bypass` lets PowerShell run the local script file.Save this script to `.claude/hooks/plain-display.ps1` in your project: - - $batch = [Console]::In.ReadToEnd() | ConvertFrom-Json - $text = $batch.delta -replace '\*\*', '' -replace '`', '' - @{ - hookSpecificOutput = @{ - hookEventName = "MessageDisplay" - displayContent = $text - } - } | ConvertTo-Json - -Batches with no markdown pass through unchanged. If the script fails, for example because `jq` is missing, Claude Code displays the original text and notes the failure only in debug output, not in the session. - -### - -​ - -PreToolUse - -Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `PowerShell`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Agent`, `WebFetch`, `WebSearch`, `AskUserQuestion`, `ExitPlanMode`, and any MCP tool names. - -PreToolUse runs only when Claude calls a tool. Files you [reference with `@` in your prompt](</docs/en/common-workflows#reference-files-and-directories>) are added without any tool call: Claude Code inserts their contents while building the prompt, so no PreToolUse hook fires for them, including hooks matching `Read`. To block specific paths from `@` references, use a [`Read` deny rule](</docs/en/permissions#read-and-edit>) instead.PreToolUse also doesn’t fire for [`EndConversation`](</docs/en/tools-reference#endconversation-tool-behavior>). - -Use PreToolUse decision control to allow, deny, ask, or defer the tool call. An [Agent SDK callback hook](</docs/en/agent-sdk/hooks>) on `PreToolUse` that exceeds its timeout blocks the tool call, and Claude receives an error result naming the timeout. An explicit deny returned by another hook still takes precedence. - -#### - -​ - -PreToolUse input - -In addition to the common input fields, PreToolUse hooks receive `tool_name`, `tool_input`, and `tool_use_id`. For the file tools `Write`, `Edit`, and `Read`, `tool_input.file_path` is always absolute: - - * Claude Code expands `~` and relative paths before hooks run, so a hook that matches on paths can’t be bypassed via `~` or a relative spelling of the same path - * On Windows, the path arrives with backslash separators, even when your hook runs under Git Bash where `$PWD` looks like `/c/project` - * A comparison written with forward slashes, such as a `/src/` check, never matches a backslash path, and the tool call proceeds as if the hook had nothing to block - * Normalize separators before comparing: `FILE_PATH="${FILE_PATH//\\//}"` in Bash, or `file_path.replace("\\", "/")` in Python, then match a path segment such as `/src/` rather than anchoring with `^`, since the path is absolute - -A `Write` call on Windows delivers: - - { - "hook_event_name": "PreToolUse", - "tool_name": "Write", - "tool_input": { - "file_path": "C:\\project\\src\\index.ts", - "content": "..." - }, - ... - } - -The `tool_input` fields depend on the tool: - -##### Bash - -Executes shell commands. - -Field| Type| Example| Description ----|---|---|--- -`command`| string| `"npm test"`| The shell command to execute -`description`| string| `"Run test suite"`| Optional description of what the command does -`timeout`| number| `120000`| Optional timeout in milliseconds. Values above the [maximum](</docs/en/tools-reference#bash-tool-behavior>) are reduced to the maximum rather than rejected -`run_in_background`| boolean| `false`| Whether to run the command in background - -##### PowerShell - -Executes PowerShell commands. See the [PowerShell tool](</docs/en/tools-reference#powershell-tool>) for availability by platform. The fields match the Bash tool, with the command string in `command`: - -Field| Type| Example| Description ----|---|---|--- -`command`| string| `"Get-ChildItem -Recurse"`| The PowerShell command to execute -`description`| string| `"List files recursively"`| Optional description of what the command does -`timeout`| number| `120000`| Optional timeout in milliseconds -`run_in_background`| boolean| `false`| Whether to run the command in background - -Match `Bash|PowerShell` in hooks that inspect shell commands, so they cover both tools: - - * On Windows, wherever the PowerShell tool is enabled, Claude treats PowerShell as the primary shell and routes shell commands through it. - * On Windows without Git Bash, the tool is enabled automatically and Claude Code doesn’t register the Bash tool at all. - * A hook that matches only `Bash` never fires there. - -##### Write - -Creates or overwrites a file. - -Field| Type| Example| Description ----|---|---|--- -`file_path`| string| `"/path/to/file.txt"`| Absolute path to the file to write -`content`| string| `"file content"`| Content to write to the file - -##### Edit - -Replaces a string in an existing file. - -Field| Type| Example| Description ----|---|---|--- -`file_path`| string| `"/path/to/file.txt"`| Absolute path to the file to edit -`old_string`| string| `"original text"`| Text to find and replace -`new_string`| string| `"replacement text"`| Replacement text -`replace_all`| boolean| `false`| Whether to replace all occurrences - -##### Read - -Reads file contents. - -Field| Type| Example| Description ----|---|---|--- -`file_path`| string| `"/path/to/file.txt"`| Absolute path to the file to read -`offset`| number| `10`| Optional line number to start reading from -`limit`| number| `50`| Optional number of lines to read - -##### Glob - -Finds files matching a glob pattern. - -Field| Type| Example| Description ----|---|---|--- -`pattern`| string| `"**/*.ts"`| Glob pattern to match files against -`path`| string| `"/path/to/dir"`| Optional directory to search in. Defaults to current working directory - -##### Grep - -Searches file contents with regular expressions. - -Field| Type| Example| Description ----|---|---|--- -`pattern`| string| `"TODO.*fix"`| Regular expression pattern to search for -`path`| string| `"/path/to/dir"`| Optional file or directory to search in -`glob`| string| `"*.ts"`| Optional glob pattern to filter files -`output_mode`| string| `"content"`| `"content"`, `"files_with_matches"`, or `"count"`. Defaults to `"files_with_matches"` -`-i`| boolean| `true`| Case insensitive search -`multiline`| boolean| `false`| Enable multiline matching - -##### WebFetch - -Fetches and processes web content. - -Field| Type| Example| Description ----|---|---|--- -`url`| string| `"https://example.com/api"`| URL to fetch content from -`prompt`| string| `"Extract the API endpoints"`| Prompt to run on the fetched content - -##### WebSearch - -Searches the web. - -Field| Type| Example| Description ----|---|---|--- -`query`| string| `"react hooks best practices"`| Search query -`allowed_domains`| array| `["docs.example.com"]`| Optional: only include results from these domains -`blocked_domains`| array| `["spam.example.com"]`| Optional: exclude results from these domains - -##### Agent - -Spawns a [subagent](</docs/en/sub-agents>). - -Field| Type| Example| Description ----|---|---|--- -`prompt`| string| `"Find all API endpoints"`| The task for the agent to perform -`description`| string| `"Find API endpoints"`| Short description of the task -`subagent_type`| string| `"Explore"`| Type of specialized agent to use -`model`| string| `"sonnet"`| Optional model alias to override the default - -In `PostToolUse`, `tool_response` for a completed Agent call carries the subagent’s final text along with usage telemetry. Read these fields to record per-subagent cost from a hook: - -Field| Type| Example| Description ----|---|---|--- -`status`| string| `"completed"`| `"completed"` for foreground subagents, `"async_launched"` for background subagents. As of v2.1.198, subagents run in the background by default, so an omitted `run_in_background` also produces `"async_launched"` -`agentId`| string| `"a4d2c8f1e0b3a297"`| Identifier for the subagent run -`content`| array| `[{"type": "text", "text": "Found 12 endpoints..."}]`| The subagent’s final text blocks -`resolvedModel`| string| `"claude-sonnet-4-5"`| Model the subagent started on, which may differ from the requested model. Requires Claude Code v2.1.174 or later -`modelsUsed`| array| `["claude-sonnet-4-5", "claude-haiku-4-5"]`| Models used in order, with consecutive repeats collapsed; set only when the model was swapped mid-run. Requires Claude Code v2.1.212 or later -`totalTokens`| number| `12450`| Total tokens billed across the subagent’s turns -`totalDurationMs`| number| `48211`| Wall-clock duration of the subagent run -`totalToolUseCount`| number| `7`| Count of tool calls the subagent made -`usage`| object| `{"input_tokens": 8320, ...}`| Per-type token breakdown: `input_tokens`, `output_tokens`, `cache_creation_input_tokens`, `cache_read_input_tokens` - -For background subagents, the tool returns when the task moves to the background, so `tool_response` carries no usage fields: a background launch returns immediately, and a foreground task that Claude Code backgrounds mid-run returns at that transition. It has `status: "async_launched"`, `agentId`, `description`, `prompt`, `outputFile`, and `resolvedModel`. On a `completed` response, `resolvedModel` names the model the subagent started on, which can differ from the `model` value in `tool_input`, such as when `availableModels` or another override applies. It requires Claude Code v2.1.174 or later. On an `async_launched` response, `resolvedModel` names the model in use when the agent moved to the background, so a swap that happened before backgrounding is reflected there. `modelsUsed` and the backgrounding-time `resolvedModel` behavior require Claude Code v2.1.212 or later. - -##### AskUserQuestion - -Asks the user one to four multiple-choice questions. - -Field| Type| Example| Description ----|---|---|--- -`questions`| array| `[{"question": "Which framework?", "header": "Framework", "options": [{"label": "React"}], "multiSelect": false}]`| Questions to present, each with a `question` string, short `header`, `options` array, and optional `multiSelect` flag -`answers`| object| `{"Which framework?": "React"}`| Optional. Maps question text to the selected option label. Multi-select answers join labels with commas. Claude doesn’t set this field; supply it via `updatedInput` to answer programmatically - -##### ExitPlanMode - -Presents a plan and asks the user to approve it before Claude leaves [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>). Claude writes the plan to a file on disk before calling the tool, so the literal `tool_input` from the model is typically empty. Claude Code injects the plan content and file path before passing the input to hooks. - -Field| Type| Example| Description ----|---|---|--- -`plan`| string| `"## Refactor auth\n1. Extract..."`| Plan content in Markdown. Injected from the plan file on disk -`planFilePath`| string| `"/Users/.../plans/refactor-auth.md"`| Path to the plan file. Injected -`allowedPrompts`| array| `[{"tool": "Bash", "prompt": "run tests"}]`| Deprecated. Claude Code accepts the field but ignores it. Before v2.1.205, it carried prompt-based permissions Claude requested to implement the plan - -In `PostToolUse`, `tool_response` is an object with `plan` and `filePath` fields holding the approved plan, plus internal status flags. Read `tool_response.plan` for the plan content rather than re-reading the file from disk. - -#### - -​ - -PreToolUse decision control - -`PreToolUse` hooks can control whether a tool call proceeds. Unlike other hooks that use a top-level `decision` field, PreToolUse returns its decision inside a `hookSpecificOutput` object. This gives it richer control: four outcomes (allow, deny, ask, or defer) plus the ability to modify tool input before execution. - -Field| Description ----|--- -`permissionDecision`| `"allow"` skips the permission prompt, except for tools that require user interaction and connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>). `"deny"` prevents the tool call. `"ask"` prompts the user to confirm. `"defer"` exits gracefully so the tool can be resumed later. [Deny and ask rules](</docs/en/permissions#manage-permissions>) are still evaluated regardless of what the hook returns -`permissionDecisionReason`| For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude. For `"defer"`, ignored -`updatedInput`| Modifies the tool’s input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones. Combine with `"allow"` to auto-approve, or `"ask"` to show the modified input to the user. For `"defer"`, ignored -`additionalContext`| String added to Claude’s context alongside the tool result. Ignored when `permissionDecision` is `"defer"`. See Add context for Claude - -When multiple PreToolUse hooks return different decisions, precedence is `deny` > `defer` > `ask` > `allow`. When a hook returns `"ask"`, the permission prompt displayed to the user includes a label identifying where the hook came from: for example, `[User]`, `[Project]`, `[Plugin]`, or `[Local]`. This helps users understand which configuration source is requesting confirmation. A hook’s `"ask"` also forces a permission prompt in [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>): the classifier can still deny the tool call, but it can’t approve the call silently. Before v2.1.211, the classifier could approve a Bash command running outside the [sandbox](</docs/en/sandboxing>) without showing the prompt the hook requested; the classifier still applied its own safety rules to that command, and a hook `"deny"` was always honored. - - { - "hookSpecificOutput": { - "hookEventName": "PreToolUse", - "permissionDecision": "allow", - "permissionDecisionReason": "My reason here", - "updatedInput": { - "field_to_modify": "new value" - }, - "additionalContext": "Current environment: production. Proceed with caution." - } - } - -`AskUserQuestion` and `ExitPlanMode` require user interaction and normally block in [non-interactive mode](</docs/en/headless>) with the `-p` flag. Returning `permissionDecision: "allow"` together with `updatedInput` satisfies that requirement: the hook reads the tool’s input from stdin, collects the answer through your own UI, and returns it in `updatedInput` so the tool runs without prompting. Returning `"allow"` alone is not sufficient for these tools. For `AskUserQuestion`, echo back the original `questions` array and add an `answers` object mapping each question’s text to the chosen answer. As of v2.1.199, an MCP tool whose server marks it with [`_meta["anthropic/requiresUserInteraction"]`](</docs/en/mcp#require-approval-for-a-specific-tool>) is stricter: a hook can’t skip its approval prompt with `"allow"`, with or without `updatedInput`, because Claude Code can’t confirm the hook collected the interaction the tool needs. - -PreToolUse previously used top-level `decision` and `reason` fields, but these are deprecated for this event. Use `hookSpecificOutput.permissionDecision` and `hookSpecificOutput.permissionDecisionReason` instead. The deprecated values `"approve"` and `"block"` map to `"allow"` and `"deny"` respectively. Other events like PostToolUse and Stop continue to use top-level `decision` and `reason` as their current format. - -#### - -​ - -Defer a tool call for later - -`"defer"` is for integrations that run `claude -p` as a subprocess and read its JSON output, such as an Agent SDK app or a custom UI built on top of Claude Code. It lets that calling process pause Claude at a tool call, collect input through its own interface, and resume where it left off. Claude Code honors this value only in [non-interactive mode](</docs/en/headless>) with the `-p` flag. In interactive sessions it logs a warning and ignores the hook result. The `AskUserQuestion` tool is the typical case: Claude wants to ask the user something, but there is no terminal to answer in. The round trip works like this: - - 1. Claude calls `AskUserQuestion`. The `PreToolUse` hook fires. - 2. The hook returns `permissionDecision: "defer"`. The tool doesn’t execute. The process exits with `stop_reason: "tool_deferred"` and the pending tool call preserved in the transcript. - 3. The calling process reads `deferred_tool_use` from the SDK result, surfaces the question in its own UI, and waits for an answer. - 4. The calling process runs `claude -p --resume <session-id>`. The same tool call fires `PreToolUse` again. - 5. The hook returns `permissionDecision: "allow"` with the answer in `updatedInput`. The tool executes and Claude continues. - -The `deferred_tool_use` field carries the tool’s `id`, `name`, and `input`. The `input` is the parameters Claude generated for the tool call, captured before execution: - - { - "type": "result", - "subtype": "success", - "stop_reason": "tool_deferred", - "session_id": "abc123", - "deferred_tool_use": { - "id": "toolu_01abc", - "name": "AskUserQuestion", - "input": { "questions": [{ "question": "Which framework?", "header": "Framework", "options": [{"label": "React"}, {"label": "Vue"}], "multiSelect": false }] } - } - } - -There is no timeout or retry limit. The session remains on disk until you resume it, subject to the [`cleanupPeriodDays`](</docs/en/settings#available-settings>) retention sweep that deletes session files after 30 days by default. If the answer is not ready when you resume, the hook can return `"defer"` again and the process exits the same way. The calling process controls when to break the loop by eventually returning `"allow"` or `"deny"` from the hook. `"defer"` only works when Claude makes a single tool call in the turn. If Claude makes several tool calls at once, `"defer"` is ignored with a warning and the tool proceeds through the normal permission flow. The constraint exists because resume can only re-run one tool: there is no way to defer one call from a batch without leaving the others unresolved. If the deferred tool is no longer available when you resume, the process exits with `stop_reason: "tool_deferred_unavailable"` and `is_error: true` before the hook fires. This happens when an MCP server that provided the tool is not connected for the resumed session. The `deferred_tool_use` payload is still included so you can identify which tool went missing. - -`--resume` restores the permission mode that was active when the tool was deferred, so you don’t need to pass `--permission-mode` again. The exceptions are `plan` and `bypassPermissions`, which are never carried over, and `auto`, which is restored only when your account still meets the [auto mode requirements](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>). Passing `--permission-mode` explicitly on resume overrides the restored value. - -### - -​ - -PermissionRequest - -Runs when Claude Code is about to ask you for permission. In sessions that can’t show a prompt, such as background subagents in [non-interactive mode](</docs/en/headless>), Claude Code still runs these hooks, and if no hook returns a decision, it denies the tool call. Use PermissionRequest decision control to allow or deny on behalf of the user. Matches on tool name, same values as PreToolUse. - -#### - -​ - -PermissionRequest input - -PermissionRequest hooks receive `tool_name` and `tool_input` fields like PreToolUse hooks, but without `tool_use_id`. An optional `permission_suggestions` array contains the “always allow” options the user would normally see in the permission dialog. PreToolUse hooks run before every tool call, whether or not it needs permission. PermissionRequest hooks run only when Claude Code is about to ask you for permission, or when it would otherwise auto-deny a call that can’t prompt. Neither event fires for [`EndConversation`](</docs/en/tools-reference#endconversation-tool-behavior>). - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "permission_mode": "default", - "hook_event_name": "PermissionRequest", - "tool_name": "Bash", - "tool_input": { - "command": "rm -rf node_modules", - "description": "Remove node_modules directory" - }, - "permission_suggestions": [ - { - "type": "addRules", - "rules": [{ "toolName": "Bash", "ruleContent": "rm -rf node_modules" }], - "behavior": "allow", - "destination": "localSettings" - } - ] - } - -#### - -​ - -PermissionRequest decision control - -`PermissionRequest` hooks can allow or deny permission requests. In addition to the JSON output fields available to all hooks, your hook script can return a `decision` object with these event-specific fields: - -Field| Description ----|--- -`behavior`| `"allow"` grants the permission, `"deny"` denies it. [Deny and ask rules](</docs/en/permissions#manage-permissions>) are still evaluated, so a hook returning `"allow"` doesn’t override a matching deny rule -`updatedInput`| For `"allow"` only: modifies the tool’s input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones. The modified input is re-evaluated against deny and ask rules -`updatedPermissions`| For `"allow"` only: array of permission update entries to apply, such as adding an allow rule or changing the session permission mode -`message`| For `"deny"` only: tells Claude why the permission was denied -`interrupt`| For `"deny"` only: if `true`, stops Claude - - { - "hookSpecificOutput": { - "hookEventName": "PermissionRequest", - "decision": { - "behavior": "allow", - "updatedInput": { - "command": "npm run lint" - } - } - } - } - -#### - -​ - -Permission update entries - -The `updatedPermissions` output field and the `permission_suggestions` input field both use the same array of entry objects. Each entry has a `type` that determines its other fields, and a `destination` that controls where the change is written. - -`type`| Fields| Effect ----|---|--- -`addRules`| `rules`, `behavior`, `destination`| Adds permission rules. `rules` is an array of `{toolName, ruleContent?}` objects. Omit `ruleContent` to match the whole tool. `behavior` is `"allow"`, `"deny"`, or `"ask"` -`replaceRules`| `rules`, `behavior`, `destination`| Replaces all rules of the given `behavior` at the `destination` with the provided `rules` -`removeRules`| `rules`, `behavior`, `destination`| Removes matching rules of the given `behavior` -`setMode`| `mode`, `destination`| Changes the permission mode. Valid modes are `default`, `auto`, `acceptEdits`, `dontAsk`, `bypassPermissions`, `plan`, and `manual` as an alias for `default`. The `manual` alias requires Claude Code v2.1.200 or later -`addDirectories`| `directories`, `destination`| Adds working directories. `directories` is an array of path strings -`removeDirectories`| `directories`, `destination`| Removes working directories - -`setMode` with `bypassPermissions` only takes effect if the session was launched with bypass mode already available: `--dangerously-skip-permissions`, `--permission-mode bypassPermissions`, `--allow-dangerously-skip-permissions`, or `permissions.defaultMode: "bypassPermissions"` in settings, and the mode is not disabled by [`permissions.disableBypassPermissionsMode`](</docs/en/permissions#managed-settings>). Otherwise the update is a no-op. `bypassPermissions` is never persisted as `defaultMode` regardless of `destination`. - -The `destination` field on every entry determines whether the change stays in memory or persists to a settings file. - -`destination`| Writes to ----|--- -`session`| in-memory only, discarded when the session ends -`localSettings`| `.claude/settings.local.json` -`projectSettings`| `.claude/settings.json` -`userSettings`| `~/.claude/settings.json` - -A hook can echo one of the `permission_suggestions` it received as its own `updatedPermissions` output, which is equivalent to the user selecting that “always allow” option in the dialog. - -### - -​ - -PostToolUse - -Runs immediately after a tool completes successfully. Matches on tool name, same values as PreToolUse. - -#### - -​ - -PostToolUse input - -`PostToolUse` hooks fire after a tool has already executed successfully. The input includes both `tool_input`, the arguments sent to the tool, and `tool_response`, the result it returned. The exact schema for both depends on the tool. File-tool `tool_input` paths arrive in the same format as for PreToolUse: always absolute, with the platform’s native separators, so backslashes on Windows. - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "permission_mode": "default", - "hook_event_name": "PostToolUse", - "tool_name": "Write", - "tool_input": { - "file_path": "/path/to/file.txt", - "content": "file content" - }, - "tool_response": { - "filePath": "/path/to/file.txt", - "success": true - }, - "tool_use_id": "toolu_01ABC123...", - "duration_ms": 12 - } - -Field| Description ----|--- -`duration_ms`| Optional. Tool execution time in milliseconds. Excludes time spent in permission prompts and PreToolUse hooks - -#### - -​ - -PostToolUse decision control - -`PostToolUse` hooks can provide feedback to Claude after tool execution. In addition to the JSON output fields available to all hooks, your hook script can return these event-specific fields: - -Field| Description ----|--- -`decision`| `"block"` adds the `reason` next to the tool result. Claude still sees the original output; to replace it, use `updatedToolOutput` -`reason`| Explanation shown to Claude when `decision` is `"block"` -`additionalContext`| String added to Claude’s context alongside the tool result. See Add context for Claude -`updatedToolOutput`| Replaces the tool’s output with the provided value before it is sent to Claude. The value must match the tool’s output shape -`updatedMCPToolOutput`| Replaces the output for MCP tools only. Prefer `updatedToolOutput`, which works for all tools - -The example below replaces the output of a `Bash` call. The replacement value matches the `Bash` tool’s output shape: - - { - "hookSpecificOutput": { - "hookEventName": "PostToolUse", - "additionalContext": "Additional information for Claude", - "updatedToolOutput": { - "stdout": "[redacted]", - "stderr": "", - "interrupted": false, - "isImage": false - } - } - } - -`updatedToolOutput` only changes what Claude sees. The tool has already run by the time the hook fires, so any files written, commands executed, or network requests sent have already taken effect. Telemetry such as OpenTelemetry tool spans and analytics events also captures the original output before the hook runs. To prevent or modify a tool call before it runs, use a PreToolUse hook instead.The replacement value must match the tool’s output shape. Built-in tools return structured objects rather than plain strings. For example, `Bash` returns an object with `stdout`, `stderr`, `interrupted`, and `isImage` fields. For built-in tools, a value that doesn’t match the tool’s output schema is ignored and the original output is used. MCP tool output is passed through without schema validation. Stripping error details that Claude needs can cause it to proceed on a false assumption. - -### - -​ - -PostToolUseFailure - -Runs when a tool that started executing fails: the tool threw an error, or an MCP tool returned an error result. Use this to log failures, send alerts, or provide corrective feedback to Claude. Matches on tool name, same values as PreToolUse. - -This event doesn’t fire for tool calls rejected before execution: an unknown tool name, input that fails schema or tool-specific validation, or a permission denial. Validation rejections are returned as `tool_use_error` results and happen before hooks run, so they fire neither `PreToolUse` nor `PostToolUseFailure`. Permission denials fire `PreToolUse` but not this event; see PermissionDenied. - -#### - -​ - -PostToolUseFailure input - -PostToolUseFailure hooks receive the same `tool_name` and `tool_input` fields as PostToolUse, along with error information as top-level fields. For example, a failed `npm test` command might deliver: - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "permission_mode": "default", - "hook_event_name": "PostToolUseFailure", - "tool_name": "Bash", - "tool_input": { - "command": "npm test", - "description": "Run test suite" - }, - "tool_use_id": "toolu_01ABC123...", - "error": "Exit code 1\nError: Cannot find module 'express'", - "is_interrupt": false, - "duration_ms": 4187 - } - -Field| Description ----|--- -`error`| String describing what went wrong. The format depends on the tool that failed -`is_interrupt`| Optional boolean. True when the failure reached Claude Code as an abort rather than as an error the tool reported. Cancelling a running tool does not fire this hook; the tool result carries the interruption message instead -`duration_ms`| Optional. Tool execution time in milliseconds. Excludes time spent in permission prompts and PreToolUse hooks - -The `error` string is generally the same text Claude receives as the failed tool’s result. Its format varies by tool and failure. Key your hook on `tool_name`, `is_interrupt`, and the `Exit code N` first line; treat the rest of the string as display text, not a stable format. - - * For Bash and PowerShell, a command that ran and exited produces a first line `Exit code N`, then any output the command produced as one block with stdout and stderr interleaved - * A payload may also carry a bare failure message with no exit-code line, when Claude Code could not start the shell process itself - * Claude Code middle-truncates strings longer than 10,000 characters around a `... [N characters truncated] ...` marker, and can insert lines of its own, such as `Command timed out after 2m 0s` - -#### - -​ - -PostToolUseFailure decision control - -`PostToolUseFailure` hooks can provide context to Claude after a tool failure. In addition to the JSON output fields available to all hooks, your hook script can return these event-specific fields: - -Field| Description ----|--- -`additionalContext`| String added to Claude’s context alongside the error. See Add context for Claude - - { - "hookSpecificOutput": { - "hookEventName": "PostToolUseFailure", - "additionalContext": "Additional information about the failure for Claude" - } - } - -### - -​ - -PostToolBatch - -Runs once after every tool call in a batch has resolved, before Claude Code sends the next request to the model. `PostToolUse` fires once per tool, which means it fires concurrently when Claude makes parallel tool calls. `PostToolBatch` fires exactly once with the full batch, so it is the right place to inject context that depends on the set of tools that ran rather than on any single tool. There is no matcher for this event. - -#### - -​ - -PostToolBatch input - -In addition to the common input fields, PostToolBatch hooks receive `tool_calls`, an array describing every tool call in the batch: - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "permission_mode": "default", - "hook_event_name": "PostToolBatch", - "tool_calls": [ - { - "tool_name": "Read", - "tool_input": {"file_path": "/.../ledger/accounts.py"}, - "tool_use_id": "toolu_01...", - "tool_response": " 1\tfrom __future__ import annotations\n 2\t..." - }, - { - "tool_name": "Read", - "tool_input": {"file_path": "/.../ledger/transactions.py"}, - "tool_use_id": "toolu_02...", - "tool_response": " 1\tfrom __future__ import annotations\n 2\t..." - } - ] - } - -`tool_response` contains the same content the model receives in the corresponding `tool_result` block. The value is a serialized string or content-block array, exactly as the tool emitted it. For `Read`, that means line-number-prefixed text rather than raw file contents. Responses can be large, so parse only the fields you need. - -The `tool_response` shape differs from `PostToolUse`’s. `PostToolUse` passes the tool’s structured `Output` object, such as `{filePath: "...", success: true}` for `Write`; `PostToolBatch` passes the serialized `tool_result` content the model sees. - -#### - -​ - -PostToolBatch decision control - -`PostToolBatch` hooks can inject context for Claude. In addition to the JSON output fields available to all hooks, your hook script can return these event-specific fields: - -Field| Description ----|--- -`additionalContext`| Context string injected once before the next model call. See Add context for Claude for delivery details, what to put in it, and how resumed sessions handle past values - - { - "hookSpecificOutput": { - "hookEventName": "PostToolBatch", - "additionalContext": "These files are part of the ledger module. Run pytest before marking the task complete." - } - } - -Returning `decision: "block"` or `continue: false` stops the agentic loop before the next model call. - -### - -​ - -PermissionDenied - -Runs when the [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) classifier denies a tool call. This hook only fires in auto mode: it doesn’t run when you manually deny a permission dialog, when a `PreToolUse` hook blocks a call, or when a `deny` rule matches. Use it to log classifier denials, adjust configuration, or tell the model it may retry the tool call. Matches on tool name, same values as PreToolUse. - -#### - -​ - -PermissionDenied input - -In addition to the common input fields, PermissionDenied hooks receive `tool_name`, `tool_input`, `tool_use_id`, and `reason`. - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "permission_mode": "auto", - "hook_event_name": "PermissionDenied", - "tool_name": "Bash", - "tool_input": { - "command": "rm -rf /tmp/build", - "description": "Clean build directory" - }, - "tool_use_id": "toolu_01ABC123...", - "reason": "Blocked by classifier" - } - -Field| Description ----|--- -`reason`| The denial reason: the fixed text `Blocked by classifier` in most sessions, or the classifier’s written explanation when the session’s classifier model provides one. See [Review denials](</docs/en/auto-mode-config#review-denials>) - -#### - -​ - -PermissionDenied decision control - -PermissionDenied hooks can tell the model it may retry the denied tool call. Return a JSON object with `hookSpecificOutput.retry` set to `true`: - - { - "hookSpecificOutput": { - "hookEventName": "PermissionDenied", - "retry": true - } - } - -When `retry` is `true`, Claude Code adds a message to the conversation telling the model it may retry the tool call. The denial itself is not reversed. If your hook doesn’t return JSON, or returns `retry: false`, the denial stands and the model receives the original rejection message. - -### - -​ - -Notification - -Runs when Claude Code sends notifications. Matches on notification type. Omit the matcher to run hooks for all notification types. - -Matcher| When it fires ----|--- -`permission_prompt`| Claude needs you to approve a tool use -`idle_prompt`| Claude is done and waiting for your next prompt -`auth_success`| Authentication completes -`elicitation_dialog`| An MCP server opens an elicitation form -`elicitation_complete`| An MCP elicitation form is submitted or dismissed -`elicitation_response`| An MCP elicitation response is sent back to the server -`agent_needs_input`| A background session starts waiting on your input. Fires only while [agent view](</docs/en/agent-view>) is open in a terminal -`agent_completed`| A background session finishes or fails. Fires only while [agent view](</docs/en/agent-view>) is open in a terminal - -The `agent_needs_input` and `agent_completed` types require Claude Code v2.1.198 or later. Use separate matchers to run different handlers depending on the notification type. This configuration triggers a permission-specific alert script when Claude needs permission approval and a different notification when Claude has been idle: - - { - "hooks": { - "Notification": [ - { - "matcher": "permission_prompt", - "hooks": [ - { - "type": "command", - "command": "/path/to/permission-alert.sh" - } - ] - }, - { - "matcher": "idle_prompt", - "hooks": [ - { - "type": "command", - "command": "/path/to/idle-notification.sh" - } - ] - } - ] - } - } - -#### - -​ - -Notification input - -In addition to the common input fields, Notification hooks receive `message` with the notification text, an optional `title`, and `notification_type` indicating which type fired. - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "hook_event_name": "Notification", - "message": "Claude needs your permission", - "title": "Permission needed", - "notification_type": "permission_prompt" - } - -Notification hooks can’t block or modify notifications. They are intended for side effects such as forwarding the notification to an external service. The common JSON output fields such as `systemMessage` apply. - -### - -​ - -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. 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$`. - -#### - -​ - -SubagentStart input - -In addition to the common input fields, SubagentStart hooks receive `agent_id` with the unique identifier for the subagent and `agent_type` with the agent name that the matcher filters on. - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "hook_event_name": "SubagentStart", - "agent_id": "agent-abc123", - "agent_type": "Explore" - } - -SubagentStart hooks can’t block subagent creation, but they can inject context into the subagent. In addition to the JSON output fields available to all hooks, you can return: - -Field| Description ----|--- -`additionalContext`| String added to the subagent’s context at the start of its conversation, before its first prompt. See Add context for Claude - - { - "hookSpecificOutput": { - "hookEventName": "SubagentStart", - "additionalContext": "Follow security guidelines for this task" - } - } - -### - -​ - -SubagentStop - -Runs when a Claude Code subagent has finished responding. Matches on agent type, same values as SubagentStart. - -#### - -​ - -SubagentStop input - -In addition to the common input fields, SubagentStop hooks receive `stop_hook_active`, `agent_id`, `agent_type`, `agent_transcript_path`, and `last_assistant_message`. The `agent_type` field is the value used for matcher filtering. The `transcript_path` is the main session’s transcript, while `agent_transcript_path` is the subagent’s own transcript stored in a nested `subagents/` folder. The `last_assistant_message` field contains the text content of the subagent’s final response, so hooks can access it without parsing the transcript file. SubagentStop hooks also receive the `background_tasks` and `session_crons` arrays described under Stop input, available in Claude Code v2.1.145 or later. Both arrays are scoped to the parent session, not the subagent. - - { - "session_id": "abc123", - "transcript_path": "~/.claude/projects/.../abc123.jsonl", - "cwd": "/Users/...", - "permission_mode": "default", - "hook_event_name": "SubagentStop", - "stop_hook_active": false, - "agent_id": "def456", - "agent_type": "Explore", - "agent_transcript_path": "~/.claude/projects/.../abc123/subagents/agent-def456.jsonl", - "last_assistant_message": "Analysis complete. Found 3 potential issues...", - "background_tasks": [], - "session_crons": [] - } - -SubagentStop hooks use the same decision control format as Stop hooks, including `hookSpecificOutput.additionalContext` with `hookEventName` set to `"SubagentStop"`, for non-error feedback that keeps the subagent running. Returning `decision: "block"` with a `reason` keeps the subagent running and delivers `reason` to the subagent as its next instruction. To inject context into the parent session after a subagent returns, use a `PostToolUse` hook on the `Agent` tool instead. - -### - -​ - -TaskCreated - -Runs when a task is being created via the `TaskCreate` tool. Use this to enforce naming conventions, require task descriptions, or prevent certain tasks from being created. TaskCreated hooks don’t support matchers and fire on every occurrence. - -#### - -​ - -TaskCreated input - -In addition to the common input fields, TaskCreated hooks receive `task_id`, `task_subject`, and optionally `task_description`, `teammate_name`, and `team_name`. - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "permission_mode": "default", - "hook_event_name": "TaskCreated", - "task_id": "task-001", - "task_subject": "Implement user authentication", - "task_description": "Add login and signup endpoints", - "teammate_name": "implementer", - "team_name": "session-a1b2c3d4" - } - -Field| Description ----|--- -`task_id`| Identifier of the task being created -`task_subject`| Title of the task -`task_description`| Detailed description of the task. May be absent -`teammate_name`| Name of the teammate creating the task. May be absent -`team_name`| Deprecated. Session-derived team name; will be removed in a future release - -#### - -​ - -TaskCreated decision control - -TaskCreated hooks support two ways to control task creation: - - * **Exit code 2** : the task is not created and the stderr message is fed back to the model as feedback. - * **JSON`{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user. - -This example blocks tasks whose subjects don’t follow the required format: - - #!/bin/bash - INPUT=$(cat) - TASK_SUBJECT=$(echo "$INPUT" | jq -r '.task_subject') - - if [[ ! "$TASK_SUBJECT" =~ ^\[TICKET-[0-9]+\] ]]; then - echo "Task subject must start with a ticket number, e.g. '[TICKET-123] Add feature'" >&2 - exit 2 - fi - - exit 0 - -### - -​ - -TaskCompleted - -Runs when a task is being marked as completed. This fires in two situations: when any agent explicitly marks a task as completed through the TaskUpdate tool, or when an [agent team](</docs/en/agent-teams>) teammate finishes its turn with in-progress tasks. Use this to enforce completion criteria like passing tests or lint checks before a task can close. TaskCompleted hooks don’t support matchers and fire on every occurrence. - -#### - -​ - -TaskCompleted input - -In addition to the common input fields, TaskCompleted hooks receive `task_id`, `task_subject`, and optionally `task_description`, `teammate_name`, and `team_name`. - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "permission_mode": "default", - "hook_event_name": "TaskCompleted", - "task_id": "task-001", - "task_subject": "Implement user authentication", - "task_description": "Add login and signup endpoints", - "teammate_name": "implementer", - "team_name": "session-a1b2c3d4" - } - -Field| Description ----|--- -`task_id`| Identifier of the task being completed -`task_subject`| Title of the task -`task_description`| Detailed description of the task. May be absent -`teammate_name`| Name of the teammate completing the task. May be absent -`team_name`| Deprecated. Session-derived team name; will be removed in a future release - -#### - -​ - -TaskCompleted decision control - -TaskCompleted hooks support two ways to control task completion: - - * **Exit code 2** : the task is not marked as completed and the stderr message is fed back to the model as feedback. - * **JSON`{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user. - -This example runs tests and blocks task completion if they fail: - - #!/bin/bash - INPUT=$(cat) - TASK_SUBJECT=$(echo "$INPUT" | jq -r '.task_subject') - - # Run the test suite - if ! npm test 2>&1; then - echo "Tests not passing. Fix failing tests before completing: $TASK_SUBJECT" >&2 - exit 2 - fi - - exit 0 - -### - -​ - -Stop - -Runs when the main Claude Code agent has finished responding. Does not run if the stoppage occurred due to a user interrupt. API errors fire StopFailure instead. - -The [`/goal`](</docs/en/goal>) command is a built-in shortcut for a session-scoped prompt-based Stop hook. Use it when you want Claude to keep working until a condition holds without writing hook configuration. - -#### - -​ - -Stop input - -In addition to the common input fields, Stop hooks receive `stop_hook_active`, `last_assistant_message`, `background_tasks`, and `session_crons`. The `stop_hook_active` field is `true` when Claude Code is already continuing as a result of a stop hook. Check this value or process the transcript to avoid blocking on a condition that will never resolve. Claude Code overrides the hook and ends the turn after 8 consecutive blocks. The `last_assistant_message` field contains the text content of Claude’s final response, so hooks can access it without parsing the transcript file. For hooks that act on the just-completed turn, such as read-aloud or notification hooks, use this field rather than reading `transcript_path`: the transcript file isn’t guaranteed to include the final message at Stop time on all versions. The `background_tasks` and `session_crons` arrays, available in Claude Code v2.1.145 or later, let hooks distinguish “session is done” from “session is paused waiting for background work to wake it back up”. Both arrays are present when the task registry is reachable and are empty when nothing is in flight or scheduled. Each entry in `background_tasks` describes one in-flight task and uses these fields: - -Field| Description ----|--- -`id`| Task identifier -`type`| Friendly task-type label such as `shell`, `subagent`, `monitor`, `workflow`, `teammate`, `cloud session`, or `MCP task`. Each label identifies which Claude Code feature created the task. Falls back to the raw discriminant for unrecognized types -`status`| Current task status -`description`| Free-text description, capped at 1000 characters with an in-string `… [+N chars]` marker when clipped -`command`| Shell command line, capped at 1000 characters. Present only for `shell` tasks -`agent_type`| Subagent type name. Present only for `subagent` tasks -`server`| MCP server name. Present only for `monitor` and `MCP task` tasks -`tool`| MCP tool name. Present only for `monitor` and `MCP task` tasks -`name`| Workflow name. Present only for `workflow` tasks - -Each entry in `session_crons` describes one session-scoped scheduled wakeup, sourced from `CronCreate`, `ScheduleWakeup`, and `/loop`: - -Field| Description ----|--- -`id`| Cron task identifier -`schedule`| Cron expression, for example `0 9 * * 1-5` -`recurring`| `false` for one-shot wakeups whose schedule encodes a single fire time, `true` for tasks that re-fire on every match -`prompt`| Prompt submitted when the cron fires, capped at 1000 characters with the same `… [+N chars]` marker - -This example shows a Stop input with one in-flight shell task and one recurring cron: - - { - "session_id": "abc123", - "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "permission_mode": "default", - "hook_event_name": "Stop", - "stop_hook_active": true, - "last_assistant_message": "I've completed the refactoring. Here's a summary...", - "background_tasks": [ - { - "id": "task-001", - "type": "shell", - "status": "running", - "description": "tail logs", - "command": "tail -f /var/log/syslog" - } - ], - "session_crons": [ - { - "id": "cron-001", - "schedule": "0 9 * * 1-5", - "recurring": true, - "prompt": "check the build" - } - ] - } - -#### - -​ - -Stop decision control - -`Stop` and `SubagentStop` hooks can control whether Claude continues. In addition to the JSON output fields available to all hooks, your hook script can return these event-specific fields: - -Field| Description ----|--- -`decision`| `"block"` prevents Claude from stopping. Omit to allow Claude to stop -`reason`| Required when `decision` is `"block"`. Tells Claude why it should continue -`hookSpecificOutput.additionalContext`| Non-error feedback for Claude. The conversation continues so Claude can act on it, but unlike `decision: "block"` it is shown in the transcript as hook feedback rather than a hook error - - { - "decision": "block", - "reason": "Must be provided when Claude is blocked from stopping" - } - -Use `additionalContext` when the hook is working as designed and giving Claude guidance, such as “run the test suite before finishing”. It keeps the conversation going through the same loop protections as `decision: "block"`, namely the `stop_hook_active` input and the 8-consecutive-continuation cap, but the transcript labels it `Stop hook feedback` and no hook error notification is shown: - - { - "hookSpecificOutput": { - "hookEventName": "Stop", - "additionalContext": "Please run the test suite before finishing" - } - } - -### - -​ - -StopFailure - -Runs instead of Stop when the turn ends due to an API error. Output and exit code are ignored. Use this to log failures, send alerts, or take recovery actions when Claude can’t complete a response due to rate limits, authentication problems, or other API errors. - -#### - -​ - -StopFailure input - -In addition to the common input fields, StopFailure hooks receive `error`, optional `error_details`, and optional `last_assistant_message`. The `error` field identifies the error type and is used for matcher filtering. - -Field| Description ----|--- -`error`| Error type: `rate_limit`, `overloaded`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, or `unknown` -`error_details`| Additional details about the error, when available -`last_assistant_message`| The rendered error text shown in the conversation. Unlike `Stop` and `SubagentStop`, where this field holds Claude’s conversational output, for `StopFailure` it contains the API error string itself, such as `"API Error: Rate limit reached"` - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "hook_event_name": "StopFailure", - "error": "rate_limit", - "error_details": "429 Too Many Requests", - "last_assistant_message": "API Error: Rate limit reached" - } - -StopFailure hooks have no decision control. They run for notification and logging purposes only. - -### - -​ - -TeammateIdle - -Runs when an [agent team](</docs/en/agent-teams>) teammate is about to go idle after finishing its turn. Use this to enforce quality gates before a teammate stops working, such as requiring passing lint checks or verifying that output files exist. TeammateIdle hooks don’t support matchers and fire on every occurrence. - -#### - -​ - -TeammateIdle input - -In addition to the common input fields, TeammateIdle hooks receive `teammate_name` and `team_name`. - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "permission_mode": "default", - "hook_event_name": "TeammateIdle", - "teammate_name": "researcher", - "team_name": "session-a1b2c3d4" - } - -Field| Description ----|--- -`teammate_name`| Name of the teammate that is about to go idle -`team_name`| Deprecated. Session-derived team name; will be removed in a future release - -#### - -​ - -TeammateIdle decision control - -TeammateIdle hooks support two ways to control teammate behavior: - - * **Exit code 2** : the teammate receives the stderr message as feedback and continues working instead of going idle. - * **JSON`{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user. - -This example checks that a build artifact exists before allowing a teammate to go idle: - - #!/bin/bash - - if [ ! -f "./dist/output.js" ]; then - echo "Build artifact missing. Run the build before stopping." >&2 - exit 2 - fi - - exit 0 - -### - -​ - -ConfigChange - -Runs when a configuration file changes during a session. Use this to audit settings changes, enforce security policies, or block unauthorized modifications to configuration files. ConfigChange hooks fire for changes to settings files, managed policy settings, and skill files. The `source` field in the input tells you which type of configuration changed, and the optional `file_path` field provides the path to the changed file. The matcher filters on the configuration source: - -Matcher| When it fires ----|--- -`user_settings`| `~/.claude/settings.json` changes -`project_settings`| `.claude/settings.json` changes -`local_settings`| `.claude/settings.local.json` changes -`policy_settings`| Managed policy settings change -`skills`| A skill file in `.claude/skills/` changes - -This example logs all configuration changes for security auditing: - - { - "hooks": { - "ConfigChange": [ - { - "hooks": [ - { - "type": "command", - "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/audit-config-change.sh", - "args": [] - } - ] - } - ] - } - } - -#### - -​ - -ConfigChange input - -In addition to the common input fields, ConfigChange hooks receive `source` and optionally `file_path`. The `source` field indicates which configuration type changed, and `file_path` provides the path to the specific file that was modified. - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "hook_event_name": "ConfigChange", - "source": "project_settings", - "file_path": "/Users/.../my-project/.claude/settings.json" - } - -#### - -​ - -ConfigChange decision control - -ConfigChange hooks can block configuration changes from taking effect. Use exit code 2 or a JSON `decision` to prevent the change. When blocked, the new settings are not applied to the running session. - -Field| Description ----|--- -`decision`| `"block"` prevents the configuration change from being applied. Omit to allow the change -`reason`| Explanation shown to the user when `decision` is `"block"` - - { - "decision": "block", - "reason": "Configuration changes to project settings require admin approval" - } - -`policy_settings` changes can’t be blocked. Hooks still fire for `policy_settings` sources, so you can use them for audit logging, but any blocking decision is ignored. This ensures enterprise-managed settings always take effect. - -### - -​ - -CwdChanged - -Runs when the working directory changes during a session, for example when Claude executes a `cd` command. Use this to react to directory changes: reload environment variables, activate project-specific toolchains, or run setup scripts automatically. Pairs with FileChanged for tools like [direnv](<https://direnv.net/>) that manage per-directory environment. CwdChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in SessionStart hooks. CwdChanged doesn’t support matchers and fires on every directory change. - -#### - -​ - -CwdChanged input - -In addition to the common input fields, CwdChanged hooks receive `old_cwd` and `new_cwd`. - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl", - "cwd": "/Users/my-project/src", - "hook_event_name": "CwdChanged", - "old_cwd": "/Users/my-project", - "new_cwd": "/Users/my-project/src" - } - -#### - -​ - -CwdChanged output - -In addition to the JSON output fields available to all hooks, CwdChanged hooks can return `watchPaths` to dynamically set which file paths FileChanged watches: - -Field| Description ----|--- -`watchPaths`| Array of absolute paths. Replaces the current dynamic watch list. Paths from your `matcher` configuration are always watched. Returning an empty array clears the dynamic list, which is typical when entering a new directory - -CwdChanged hooks have no decision control. They can’t block the directory change. - -### - -​ - -DirectoryAdded - -Runs after you add a working directory mid-session with the `/add-dir` command, or after an SDK client adds one with the `register_repo_root` control request. Use this to prepare a newly added repository, for example by installing its dependencies. Claude Code doesn’t fire this event when: - - * You pass a directory with the `--add-dir` startup flag; SessionStart covers those directories - * You add a directory on the `/permissions` Workspace tab - * You add a directory that is already a working directory; the add fails with an error - -Claude Code fires DirectoryAdded after refreshing sandbox and permission state, so sandboxed tools already see the new directory when your hook runs. Hook commands themselves run unsandboxed. Claude Code doesn’t wait for the hook: the add completes immediately, and the hook runs in the background with the 600-second default timeout. The matcher filters on how the directory was added: - -Matcher| When it fires ----|--- -`slash_command`| You add a directory with `/add-dir` -`register_repo_root`| An SDK client adds a directory with the `register_repo_root` control request - -#### - -​ - -DirectoryAdded input - -In addition to the common input fields, DirectoryAdded hooks receive `directory` and `source`. - -Field| Description ----|--- -`directory`| Absolute path of the directory that was added -`source`| How the directory was added, `"slash_command"` for `/add-dir` or `"register_repo_root"` for the SDK control request - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl", - "cwd": "/Users/my-project", - "hook_event_name": "DirectoryAdded", - "directory": "/Users/my-other-repo", - "source": "slash_command" - } - -DirectoryAdded hooks have no decision control. They can’t block the add, which has already completed when the hook runs. Claude Code surfaces hook output differently per source: - - * `slash_command`: unlike on every other event, where you see the `systemMessage` and Claude doesn’t, Claude Code delivers the hook’s `systemMessage` to Claude as context on the next conversation turn. A count of failed hooks appears in the transcript; full failure output goes to the debug log - * `register_repo_root`: Claude Code writes `systemMessage` output and failure output to the debug log only - -### - -​ - -FileChanged - -Runs when a watched file changes on disk. Useful for reloading environment variables when project configuration files are modified. The `matcher` for this event serves two roles: - - * **Build the watch list** : the value is split on `|` and each segment is registered as a literal filename in the working directory, so `".envrc|.env"` watches exactly those two files. Regex patterns are not useful here: a value like `^\.env` would watch a file literally named `^\.env`. - * **Filter which hooks run** : when a watched file changes, the same value filters which hook groups run using the standard matcher rules against the changed file’s basename. - -FileChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in SessionStart hooks. - -#### - -​ - -FileChanged input - -In addition to the common input fields, FileChanged hooks receive `file_path` and `event`. - -Field| Description ----|--- -`file_path`| Absolute path to the file that changed -`event`| What happened: `"change"` for a modified file, `"add"` for a created file, or `"unlink"` for a deleted file - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl", - "cwd": "/Users/my-project", - "hook_event_name": "FileChanged", - "file_path": "/Users/my-project/.envrc", - "event": "change" - } - -#### - -​ - -FileChanged output - -In addition to the JSON output fields available to all hooks, FileChanged hooks can return `watchPaths` to dynamically update which file paths are watched: - -Field| Description ----|--- -`watchPaths`| Array of absolute paths. Replaces the current dynamic watch list. Paths from your `matcher` configuration are always watched. Use this when your hook script discovers additional files to watch based on the changed file - -FileChanged hooks have no decision control. They can’t block the file change from occurring. - -### - -​ - -WorktreeCreate - -Runs when a worktree is being created, whether from `claude --worktree`, from a [subagent using `isolation: "worktree"`](</docs/en/sub-agents#choose-the-subagent-scope>), or for a [background session](</docs/en/agent-view#how-file-edits-are-isolated>) that Claude Code isolates in its own worktree. By default Claude Code creates the isolated working copy with `git worktree`. Configuring a WorktreeCreate hook replaces that default git behavior, letting you use a different version control system like SVN, Perforce, or Mercurial. Because the hook replaces the default behavior entirely, [`.worktreeinclude`](</docs/en/worktrees#copy-gitignored-files-into-worktrees>) is not processed. If you need to copy local configuration files like `.env` into the new worktree, do it inside your hook script. The hook must return the path to the created worktree directory. Claude Code uses this path as the working directory for the isolated session. See WorktreeCreate output for how each hook type returns the path. This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own: - - { - "hooks": { - "WorktreeCreate": [ - { - "hooks": [ - { - "type": "command", - "command": "bash -c 'NAME=$(jq -r .name); DIR=\"$HOME/.claude/worktrees/$NAME\"; svn checkout https://svn.example.com/repo/trunk \"$DIR\" >&2 && echo \"$DIR\"'" - } - ] - } - ] - } - } - -The hook reads the worktree `name` from the JSON input on stdin, checks out a fresh copy into a new directory, and prints the directory path. The `echo` on the last line is what Claude Code reads as the worktree path. Redirect any other output to stderr so it doesn’t interfere with the path. - -#### - -​ - -WorktreeCreate input - -In addition to the common input fields, WorktreeCreate hooks receive the `name` field. This is a slug identifier for the new worktree, either specified by the user or auto-generated, for example `bold-oak-a3f2`. - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "hook_event_name": "WorktreeCreate", - "name": "feature-auth" - } - -#### - -​ - -WorktreeCreate output - -WorktreeCreate hooks don’t use the standard allow/block decision model. Instead, the hook’s success or failure determines the outcome. The hook must return the path to the created worktree directory: - - * **Command hooks** (`type: "command"`): print the path as the last non-empty line of stdout. Claude Code strips ANSI escape codes before reading that line, so shell startup banners printed before your `echo` are ignored. Redirect any other hook output to stderr. - * **HTTP hooks** (`type: "http"`): return `{ "hookSpecificOutput": { "hookEventName": "WorktreeCreate", "worktreePath": "/absolute/path" } }` in the response body. - -If the hook fails or produces no path, worktree creation fails with an error. Claude Code resolves a relative path against the directory the hook ran in, collapsing any `.` or `..` segments in it. If the resulting path isn’t a directory Claude Code can enter, the session prints an error naming the path and exits with code 1. Before v2.1.205, a relative path or a path that didn’t exist on disk crashed the session at startup, and with `-p` it stalled for about 30 seconds before exiting with code 0. Claude Code refuses an absolute path that contains `.` or `..` segments, and any path that passes through a symlink below the repository root, because a symlink committed to the repository could redirect the worktree outside it. The error names the rejected component. Return a normalized path that doesn’t pass through a symlink inside the repository. Before v2.1.216, worktree creation followed the hook’s path without this screening. - -### - -​ - -WorktreeRemove - -Runs when a worktree is being removed. This is the cleanup counterpart to WorktreeCreate. The event fires when: - - * you exit a `--worktree` session and choose to remove it - * a subagent with `isolation: "worktree"` finishes - * you delete a [background session](</docs/en/agent-view#what-deleting-a-session-removes>) whose worktree the hook created - -For git-based worktrees, Claude Code handles cleanup automatically with `git worktree remove`. If you configured a WorktreeCreate hook for a non-git version control system, pair it with a WorktreeRemove hook to handle cleanup. Without one, the worktree directory is left on disk. For a background-session delete, Claude Code verifies the stored worktree path before running the hook and refuses a path that is a symlink or passes through one below the repository root. The hook runs for a worktree that still contains files only when you confirm the delete in [agent view](</docs/en/agent-view#what-deleting-a-session-removes>); for such a worktree, [`claude rm`](</docs/en/agent-view#manage-sessions-from-the-shell>) keeps the session and worktree instead. Before v2.1.216, the hook ran on the stored path without these checks. Claude Code passes the path returned by WorktreeCreate as `worktree_path` in the hook input. This example reads that path and removes the directory: - - { - "hooks": { - "WorktreeRemove": [ - { - "hooks": [ - { - "type": "command", - "command": "bash -c 'jq -r .worktree_path | xargs rm -rf'" - } - ] - } - ] - } - } - -#### - -​ - -WorktreeRemove input - -In addition to the common input fields, WorktreeRemove hooks receive the `worktree_path` field, which is the absolute path to the worktree being removed. - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "hook_event_name": "WorktreeRemove", - "worktree_path": "/Users/.../my-project/.claude/worktrees/feature-auth" - } - -WorktreeRemove hooks have no decision control. They can’t block worktree removal but can perform cleanup tasks like removing version control state or archiving changes. Hook failures are logged in debug mode only. - -### - -​ - -PreCompact - -Runs before Claude Code is about to run a compact operation. The matcher value indicates whether compaction was triggered manually or automatically: - -Matcher| When it fires ----|--- -`manual`| `/compact` -`auto`| Auto-compact when the context window is full - -Exit with code 2 to block compaction. For a manual `/compact`, the stderr message is shown to the user. You can also block by returning JSON with `"decision": "block"`. Blocking automatic compaction has different effects depending on when it fires. If compaction was triggered proactively before the context limit, Claude Code skips it and the conversation continues uncompacted. If compaction was triggered to recover from a context-limit error already returned by the API, the underlying error surfaces and the current request fails. - -#### - -​ - -PreCompact input - -In addition to the common input fields, PreCompact hooks receive `trigger` and `custom_instructions`. For `manual`, `custom_instructions` contains what the user passes into `/compact`. For `auto`, `custom_instructions` is empty. - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "hook_event_name": "PreCompact", - "trigger": "manual", - "custom_instructions": "" - } - -### - -​ - -PostCompact - -Runs after Claude Code completes a compact operation. Use this event to react to the new compacted state, for example to log the generated summary or update external state. The same matcher values apply as for `PreCompact`: - -Matcher| When it fires ----|--- -`manual`| After `/compact` -`auto`| After auto-compact when the context window is full - -#### - -​ - -PostCompact input - -In addition to the common input fields, PostCompact hooks receive `trigger` and `compact_summary`. The `compact_summary` field contains the conversation summary generated by the compact operation. - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "hook_event_name": "PostCompact", - "trigger": "manual", - "compact_summary": "Summary of the compacted conversation..." - } - -PostCompact hooks have no decision control. They can’t affect the compaction result but can perform follow-up tasks. - -### - -​ - -SessionEnd - -Runs when a Claude Code session ends. Useful for cleanup tasks, logging session statistics, or saving session state. Supports matchers to filter by exit reason. The `reason` field in the hook input indicates why the session ended: - -Reason| Description ----|--- -`clear`| Session cleared with `/clear` command -`resume`| Session switched via interactive `/resume` -`logout`| User logged out -`prompt_input_exit`| User exited while prompt input was visible -`bypass_permissions_disabled`| Bypass permissions mode was disabled -`other`| Other exit reasons - -#### - -​ - -SessionEnd input - -In addition to the common input fields, SessionEnd hooks receive a `reason` field indicating why the session ended. See the reason table above for all values. - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "hook_event_name": "SessionEnd", - "reason": "other" - } - -SessionEnd hooks have no decision control. They can’t block session termination but can perform cleanup tasks. SessionEnd hooks have a default timeout of 1.5 seconds. This applies to session exit, `/clear`, and switching sessions via interactive `/resume`. If a hook needs more time, set a per-hook `timeout` in the hook configuration. The overall budget is automatically raised to the highest per-hook timeout configured in settings files, up to 60 seconds. Timeouts set on plugin-provided hooks don’t raise the budget. To override the budget explicitly, set the `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` environment variable in milliseconds. - - CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS=5000 claude - -### - -​ - -Elicitation - -Runs when an MCP server requests user input mid-task. By default, Claude Code shows an interactive dialog for the user to respond. Hooks can intercept this request and respond programmatically, skipping the dialog entirely. The matcher field matches against the MCP server name. - -#### - -​ - -Elicitation input - -In addition to the common input fields, Elicitation hooks receive `mcp_server_name`, `message`, and optional `mode`, `url`, `elicitation_id`, and `requested_schema` fields. For form-mode elicitation, the most common case: - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "permission_mode": "default", - "hook_event_name": "Elicitation", - "mcp_server_name": "my-mcp-server", - "message": "Please provide your credentials", - "mode": "form", - "requested_schema": { - "type": "object", - "properties": { - "username": { "type": "string", "title": "Username" } - } - } - } - -For URL-mode elicitation, used for browser-based authentication: - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "permission_mode": "default", - "hook_event_name": "Elicitation", - "mcp_server_name": "my-mcp-server", - "message": "Please authenticate", - "mode": "url", - "url": "https://auth.example.com/login" - } - -#### - -​ - -Elicitation output - -To respond programmatically without showing the dialog, return a JSON object with `hookSpecificOutput`: - - { - "hookSpecificOutput": { - "hookEventName": "Elicitation", - "action": "accept", - "content": { - "username": "alice" - } - } - } - -Field| Values| Description ----|---|--- -`action`| `accept`, `decline`, `cancel`| Whether to accept, decline, or cancel the request -`content`| object| Form field values to submit. Only used when `action` is `accept` - -Exit code 2 denies the elicitation and shows stderr to the user. - -### - -​ - -ElicitationResult - -Runs after a user responds to an MCP elicitation. Hooks can observe, modify, or block the response before it is sent back to the MCP server. The matcher field matches against the MCP server name. - -#### - -​ - -ElicitationResult input - -In addition to the common input fields, ElicitationResult hooks receive `mcp_server_name`, `action`, and optional `mode`, `elicitation_id`, and `content` fields. - - { - "session_id": "abc123", - "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", - "cwd": "/Users/...", - "permission_mode": "default", - "hook_event_name": "ElicitationResult", - "mcp_server_name": "my-mcp-server", - "action": "accept", - "content": { "username": "alice" }, - "mode": "form", - "elicitation_id": "elicit-123" - } - -#### - -​ - -ElicitationResult output - -To override the user’s response, return a JSON object with `hookSpecificOutput`: - - { - "hookSpecificOutput": { - "hookEventName": "ElicitationResult", - "action": "decline", - "content": {} - } - } - -Field| Values| Description ----|---|--- -`action`| `accept`, `decline`, `cancel`| Overrides the user’s action -`content`| object| Overrides form field values. Only meaningful when `action` is `accept` - -Exit code 2 blocks the response, changing the effective action to `decline`. - -## - -​ - -Prompt-based hooks - -In addition to command, HTTP, and MCP tool hooks, Claude Code supports prompt-based hooks (`type: "prompt"`) that use an LLM to evaluate whether to allow or block an action, and agent hooks (`type: "agent"`) that spawn an agentic verifier with tool access. Not all events support every hook type. Events that support all five hook types (`command`, `http`, `mcp_tool`, `prompt`, and `agent`): - - * `PermissionDenied` - * `PermissionRequest` - * `PostToolBatch` - * `PostToolUse` - * `PostToolUseFailure` - * `PreToolUse` - * `Stop` - * `SubagentStop` - * `TaskCompleted` - * `TaskCreated` - * `TeammateIdle` - * `UserPromptExpansion` - * `UserPromptSubmit` - -Events that support `command`, `http`, and `mcp_tool` hooks but not `prompt` or `agent`: - - * `ConfigChange` - * `CwdChanged` - * `DirectoryAdded` - * `Elicitation` - * `ElicitationResult` - * `FileChanged` - * `InstructionsLoaded` - * `Notification` - * `PostCompact` - * `PreCompact` - * `SessionEnd` - * `StopFailure` - * `SubagentStart` - * `WorktreeCreate` - * `WorktreeRemove` - -`SessionStart` and `Setup` support `command` and `mcp_tool` hooks. They don’t support `http`, `prompt`, or `agent` hooks. - -### - -​ - -How prompt-based hooks work - -Instead of executing a Bash command, prompt-based hooks: - - 1. Send the hook input and your prompt to a Claude model, Haiku by default - 2. The LLM responds with structured JSON containing a decision - 3. Claude Code processes the decision automatically - -### - -​ - -Prompt hook configuration - -Set `type` to `"prompt"` and provide a `prompt` string instead of a `command`. Use the `$ARGUMENTS` placeholder to inject the hook’s JSON input data into your prompt text. This `Stop` hook asks the LLM to evaluate whether all tasks are complete before allowing Claude to finish: - - { - "hooks": { - "Stop": [ - { - "hooks": [ - { - "type": "prompt", - "prompt": "Evaluate if Claude should stop: $ARGUMENTS. Check if all tasks are complete." - } - ] - } - ] - } - } - -Field| Required| Description ----|---|--- -`type`| yes| Must be `"prompt"` -`prompt`| yes| The prompt text to send to the LLM. Use `$ARGUMENTS` as a placeholder for the hook input JSON. If `$ARGUMENTS` is not present, input JSON is appended to the prompt -`model`| no| Model to use for evaluation. Defaults to a fast model -`timeout`| no| Timeout in seconds. Default: 30 -`continueOnBlock`| no| When the prompt returns `ok: false`, feed the reason back to Claude and continue the turn instead of stopping. Default: `false`. Implemented as `continue: true` on the resulting `decision: "block"`. See Response schema for per-event behavior - -### - -​ - -Response schema - -The LLM must respond with JSON containing: - - { - "ok": true | false, - "reason": "Explanation for the decision" - } - -Field| Description ----|--- -`ok`| `true` to allow. `false` produces a `decision: "block"`. See the per-event behavior below -`reason`| Required when `ok` is `false`. Used as the block reason - -What happens on `ok: false` depends on the event: - - * `Stop` and `SubagentStop`: the reason is fed back to Claude as its next instruction and the turn continues - * `PreToolUse`: the tool call is denied; by default the turn ends and the deny reason appears in the chat as a warning line. Set `continueOnBlock: true` to instead return the reason to Claude as the tool error so it can adjust and continue, equivalent to a command hook’s `permissionDecision: "deny"`. Before v2.1.210, the deny reason was returned to Claude as the tool error and the turn continued - * `PostToolUse`: by default the turn ends and the reason appears in the chat as a warning line. Set `continueOnBlock: true` to feed the reason back to Claude and continue the turn instead - * `PostToolBatch`, `UserPromptSubmit`, and `UserPromptExpansion`: the turn ends and the reason appears as a warning line. These events end the turn on `decision: "block"` regardless of `continue` - * `PostToolUseFailure` and `TaskCreated`: the reason is returned to Claude as a tool error and the turn continues, regardless of `continueOnBlock` - * `TaskCompleted`: when it fires because a task is marked completed during a turn, the reason is returned to Claude as a tool error and the turn continues, regardless of `continueOnBlock`. When it fires because a teammate stops, it behaves like `TeammateIdle` and halts the teammate by default - * `TeammateIdle`: by default the teammate stops and the reason appears as a warning line. Set `continueOnBlock: true` to feed the reason back to the teammate and keep it working instead - * `PermissionRequest`: `ok: false` has no effect. To deny an approval from a hook, use a command hook returning `hookSpecificOutput.decision.behavior: "deny"` - * `PermissionDenied`: `ok: false` has no effect because the denial already happened. The only output this event reads is `hookSpecificOutput.retry`, which prompt and agent hooks can’t set. They run on this event, but their output is discarded. Use a command hook to return `retry` - -If you need finer control on any event, use a command hook with the per-event fields described in Decision control. - -### - -​ - -Check multiple conditions before stopping - -This `Stop` hook uses a detailed prompt to check three conditions before allowing Claude to stop. `SubagentStop` hooks use the same format to evaluate whether a [subagent](</docs/en/sub-agents>) should stop. If `"ok"` is `false`, Claude continues working with the provided reason as its next instruction: - - { - "hooks": { - "Stop": [ - { - "hooks": [ - { - "type": "prompt", - "prompt": "You are evaluating whether Claude should stop working. Context: $ARGUMENTS\n\nAnalyze the conversation and determine if:\n1. All user-requested tasks are complete\n2. Any errors need to be addressed\n3. Follow-up work is needed\n\nRespond with JSON: {\"ok\": true} to allow stopping, or {\"ok\": false, \"reason\": \"your explanation\"} to continue working.", - "timeout": 30 - } - ] - } - ] - } - } - -## - -​ - -Agent-based hooks - -Agent hooks are experimental. Behavior and configuration may change in future releases. For production workflows, prefer command hooks. - -Agent-based hooks (`type: "agent"`) are like prompt-based hooks but with multi-turn tool access. Instead of a single LLM call, an agent hook spawns a subagent that can read files, search code, and inspect the codebase to verify conditions. Agent hooks support the same events as prompt-based hooks. - -### - -​ - -How agent hooks work - -When an agent hook fires: - - 1. Claude Code spawns a subagent with your prompt and the hook’s JSON input - 2. The subagent can use tools like Read, Grep, and Glob to investigate - 3. After up to 50 turns, the subagent returns a structured `{ "ok": true/false }` decision - 4. Claude Code processes the decision the same way as a prompt hook - -Agent hooks are useful when verification requires inspecting actual files or test output, not just evaluating the hook input data alone. - -### - -​ - -Agent hook configuration - -Set `type` to `"agent"` and provide a `prompt` string. The configuration fields are the same as prompt hooks, with a longer default timeout: - -Field| Required| Description ----|---|--- -`type`| yes| Must be `"agent"` -`prompt`| yes| Prompt describing what to verify. Use `$ARGUMENTS` as a placeholder for the hook input JSON -`model`| no| Model to use. Defaults to a fast model -`timeout`| no| Timeout in seconds. Default: 60 - -The response schema is the same as prompt hooks: `{ "ok": true }` to allow or `{ "ok": false, "reason": "..." }` to block. This `Stop` hook verifies that all unit tests pass before allowing Claude to finish: - - { - "hooks": { - "Stop": [ - { - "hooks": [ - { - "type": "agent", - "prompt": "Verify that all unit tests pass. Run the test suite and check the results. $ARGUMENTS", - "timeout": 120 - } - ] - } - ] - } - } - -## - -​ - -Run hooks in the background - -By default, hooks block Claude’s execution until they complete. For long-running tasks like deployments, test suites, or external API calls, set `"async": true` to run the hook in the background while Claude continues working. Async hooks can’t block or control Claude’s behavior: response fields like `decision`, `permissionDecision`, and `continue` have no effect, because the action they would have controlled has already completed. - -### - -​ - -Configure an async hook - -Add `"async": true` to a command hook’s configuration to run it in the background without blocking Claude. This field is only available on `type: "command"` hooks. This hook runs a test script after every `Write` tool call. Claude continues working immediately while `run-tests.sh` executes for up to 120 seconds. When the script finishes, its output is delivered on the next conversation turn: - - { - "hooks": { - "PostToolUse": [ - { - "matcher": "Write", - "hooks": [ - { - "type": "command", - "command": "/path/to/run-tests.sh", - "async": true, - "timeout": 120 - } - ] - } - ] - } - } - -The `timeout` field sets the maximum time in seconds for the background process. If not specified, async hooks use the same 10-minute default as sync hooks. You receive an async hook’s results only while the session runs: - - * In [non-interactive mode](</docs/en/headless>) with the `-p` flag, Claude Code kills any async hook still running at teardown and finalizes it with outcome `cancelled` - * If your hook’s work must outlive a `claude -p` session, start a fully detached process from it - -### - -​ - -How async hooks execute - -When an async hook fires, Claude Code starts the hook process and immediately continues without waiting for it to finish. The hook receives the same JSON input via stdin as a synchronous hook. After the background process exits, if the hook produced a JSON response with an `additionalContext` field, that content is delivered to Claude as context on the next conversation turn. A `systemMessage` field is shown to you, not to Claude. Claude Code validates that JSON response against the same output schema as synchronous hooks, and drops any field whose value has the wrong type, such as a `systemMessage` that isn’t a string, instead of delivering it. Run with `--debug` to see a warning naming each dropped field. Before v2.1.202, malformed JSON output from an async hook could crash the session, and the crash recurred each time the session was resumed. Async hook completion notifications are suppressed by default. To see them, enable verbose mode with `Ctrl+O` or start Claude Code with `--verbose`. - -### - -​ - -Run tests after file changes - -This hook starts a test suite in the background whenever Claude writes a file, then reports the results back to Claude when the tests finish. Save this script to `.claude/hooks/run-tests-async.sh` in your project and make it executable with `chmod +x`: - - #!/bin/bash - # run-tests-async.sh - - # Read hook input from stdin - INPUT=$(cat) - FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty') - - # Only run tests for source files - if [[ "$FILE_PATH" != *.ts && "$FILE_PATH" != *.js ]]; then - exit 0 - fi - - # Run tests and report results to Claude via additionalContext - RESULT=$(npm test 2>&1) - EXIT_CODE=$? - - if [ $EXIT_CODE -eq 0 ]; then - MSG="Tests passed after editing $FILE_PATH" - else - MSG="Tests failed after editing $FILE_PATH: $RESULT" - fi - jq -nc --arg msg "$MSG" '{hookSpecificOutput: {hookEventName: "PostToolUse", additionalContext: $msg}}' - -Then add this configuration to `.claude/settings.json` in your project root. The `async: true` flag lets Claude keep working while tests run: - - { - "hooks": { - "PostToolUse": [ - { - "matcher": "Write|Edit", - "hooks": [ - { - "type": "command", - "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/run-tests-async.sh", - "args": [], - "async": true, - "timeout": 300 - } - ] - } - ] - } - } - -### - -​ - -Limitations - -Async hooks have additional constraints compared to synchronous hooks: - - * Hook output is delivered on the next conversation turn. If the session is idle, the response waits until the next user interaction. Exception: an `asyncRewake` hook that exits with code 2 wakes Claude immediately even when the session is idle. - * Each execution creates a separate background process. There is no deduplication across multiple firings of the same async hook. - -## - -​ - -Security considerations - -### - -​ - -Disclaimer - -Command hooks execute shell commands with your full user permissions. They can modify, delete, or access any files your user account can access. Review and test all hook commands before adding them to your configuration. - -### - -​ - -Security best practices - -Keep these practices in mind when writing hooks: - - * **Validate and sanitize inputs** : never trust input data blindly - * **Always quote shell variables** : use `"$VAR"` not `$VAR` - * **Block path traversal** : check for `..` in file paths - * **Use absolute paths** : specify full paths for scripts. In exec form, use `${CLAUDE_PROJECT_DIR}` and the path needs no quoting. In shell form, wrap it in double quotes - * **Skip sensitive files** : avoid `.env`, `.git/`, keys, etc. - -## - -​ - -Windows PowerShell tool - -On Windows, you can run individual hooks in PowerShell by setting `"shell": "powershell"` on a command hook. Claude Code auto-detects `pwsh.exe`, the PowerShell 7 and later executable, and falls back to `powershell.exe` for Windows PowerShell 5.1. - - { - "hooks": { - "PostToolUse": [ - { - "matcher": "Write", - "hooks": [ - { - "type": "command", - "shell": "powershell", - "command": "Write-Host 'File written'" - } - ] - } - ] - } - } - -To reference the project root from a PowerShell shell-form command, write `${CLAUDE_PROJECT_DIR}` or `$env:CLAUDE_PROJECT_DIR`. As of v2.1.198, Claude Code rewrites the `${CLAUDE_PROJECT_DIR}`, `${CLAUDE_PLUGIN_ROOT}`, and `${CLAUDE_PLUGIN_DATA}` placeholders in a PowerShell shell-form command to PowerShell’s `${env:NAME}` form, whether the hook is defined in `settings.json`, a plugin, or a skill. PowerShell then resolves the value from the exported environment after parsing, so the placeholder works inside double-quoted strings but not inside single-quoted strings, where PowerShell never expands variables. Before v2.1.198, this rewrite applied only to plugin hooks. On earlier versions, a `settings.json` hook needs the `$env:` form or exec form, where `${CLAUDE_PROJECT_DIR}` is substituted in each `args` element regardless of where the hook is defined. Don’t write the bare `$CLAUDE_PROJECT_DIR` spelling in a PowerShell hook. PowerShell parses it as an undefined local variable and resolves it to `$null`, which leaves the script path without its project-root prefix. Claude Code doesn’t rewrite that form; it logs a warning in the debug log instead. The example below shows a `settings.json` hook that runs a project script with the `$env:` form, which works on every version: - - { - "type": "command", - "shell": "powershell", - "command": "& \"$env:CLAUDE_PROJECT_DIR\\.claude\\hooks\\check.ps1\"" - } - -## - -​ - -Debug hooks - -Hook execution details, including which hooks matched, their exit codes, and full stdout and stderr, are written to the debug log file. Start Claude Code with `claude --debug-file <path>` to write the log to a known location, or run `claude --debug` and read the log at `~/.claude/debug/<session-id>.txt`. The `--debug` flag doesn’t print to the terminal. For example, a `PostToolUse` hook on `Write` whose command prints `hook-ran` produces entries like: - - 2026-07-19T02:03:24.382Z [DEBUG] Hook output does not start with {, treating as plain text - 2026-07-19T02:03:24.382Z [DEBUG] Hook PostToolUse:Write (PostToolUse) success: - hook-ran - -For more granular hook matching details, set `CLAUDE_CODE_DEBUG_LOG_LEVEL=verbose` to see additional log lines such as hook matcher counts and query matching. For troubleshooting common issues like hooks not firing, Stop hooks that keep blocking, or configuration errors, see [Limitations and troubleshooting](</docs/en/hooks-guide#limitations-and-troubleshooting>) in the guide. For a broader diagnostic walkthrough covering `/context`, `/doctor`, and settings precedence, see [Debug your config](</docs/en/debug-your-config>). +Related resources + + * [Claude Code hooks reference](</docs/en/hooks>): full JSON input/output schemas, event documentation, and matcher patterns + * [Claude Code hooks guide](</docs/en/hooks-guide>): shell command hook examples and walkthroughs + * [TypeScript SDK reference](</docs/en/agent-sdk/typescript>): hook types, input/output definitions, and configuration options + * [Python SDK reference](</docs/en/agent-sdk/python>): hook types, input/output definitions, and configuration options + * [Permissions](</docs/en/agent-sdk/permissions>): control what your agent can do + * [Custom tools](</docs/en/agent-sdk/custom-tools>): build tools to extend agent capabilities
modified Automate actions with hooks View current →
--- a/hooks-guide.md +++ b/hooks-guide.md @@ -81,7 +81,7 @@ Get notified when Claude needs input -Get a desktop notification whenever Claude finishes working and needs your input, so you can switch to other tasks without checking the terminal. This hook uses the `Notification` event, which Claude Code fires when Claude is waiting for input or permission. Each tab below uses the platform’s native notification command. Add this to `~/.claude/settings.json`: +Get a desktop notification whenever Claude finishes working and needs your input, so you can switch to other tasks without checking the terminal. This hook uses the `Notification` event, which Claude Code fires when Claude is waiting for input or permission. See [when each notification type fires](</docs/en/hooks#notification>) for the exact timing. Each tab below uses the platform’s native notification command. Add this to `~/.claude/settings.json`: * macOS @@ -161,10 +161,11 @@ Matcher| Fires when ---|--- -`permission_prompt`| Claude needs you to approve a tool use -`idle_prompt`| Claude is done and waiting for your next prompt +`permission_prompt`| Claude needs you to approve a tool use and you haven’t typed for about 6 seconds +`idle_prompt`| Claude finished responding about 60 seconds ago and you haven’t typed since `auth_success`| Authentication completes -`elicitation_dialog`| An MCP server opens an elicitation form +`elicitation_dialog`| An MCP server opens an elicitation form and you haven’t typed for about 6 seconds +`elicitation_url_dialog`| An MCP server asks you to open a browser URL and you haven’t typed for about 6 seconds `elicitation_complete`| An MCP elicitation form is submitted or dismissed `elicitation_response`| An MCP elicitation response is sent back to the server `agent_needs_input`| A background session starts waiting on your input. Fires only while [agent view](</docs/en/agent-view>) is open @@ -629,7 +630,7 @@ `SessionStart`| how the session started| `startup`, `resume`, `clear`, `compact`, `fork` `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`, `agent_needs_input`, `agent_completed` +`Notification`| notification type| `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_url_dialog`, `elicitation_complete`, `elicitation_response`, `agent_needs_input`, `agent_completed` `SubagentStart`| agent type| `general-purpose`, `Explore`, `Plan`, or custom agent names `PreCompact`, `PostCompact`| what triggered compaction| `manual`, `auto` `SubagentStop`| agent type| same values as `SubagentStart`
modified Hosting the Agent SDK View current →
--- a/hosting.md +++ b/hosting.md @@ -1,4 +1,4 @@ -The Agent SDK spawns and supervises a `claude` CLI subprocess that owns a shell, a working directory, and session files on disk. Hosting it is not like hosting a stateless API wrapper. Every running agent is a long-lived process tied to local state, which shapes how you allocate resources, persist sessions, and scale across tenants. This page covers self-hosting on your own infrastructure: understand the subprocess model, choose a session pattern, provision the container, and handle production concerns like persistence, observability, auth, and multi-tenant isolation. For deployable Dockerfiles and Kubernetes manifests, see the [hosting cookbook](<https://github.com/anthropics/claude-cookbooks/tree/main/claude_agent_sdk/hosting>). If you do not need infrastructure control, custom isolation, or your own data plane, consider [Managed Agents](<https://platform.claude.com/docs/en/managed-agents/overview>) instead: a hosted REST API where Anthropic runs the agent and the sandbox, so your application sends events and streams back results with no hosting infrastructure to operate. +The Agent SDK spawns and supervises a `claude` CLI subprocess that owns a shell, a working directory, and session files on disk. Hosting it is not like hosting a stateless API wrapper. Every running agent is a long-lived process tied to local state, which shapes how you allocate resources, persist sessions, and scale across tenants. This page covers self-hosting on your own infrastructure. For deployable Dockerfiles and Kubernetes manifests, see the [hosting cookbook](<https://github.com/anthropics/claude-cookbooks/tree/main/claude_agent_sdk/hosting>). If you do not need infrastructure control, custom isolation, or your own data plane, consider [Managed Agents](<https://platform.claude.com/docs/en/managed-agents/overview>) instead: a hosted REST API where Anthropic runs the agent and the sandbox, so your application sends events and streams back results with no hosting infrastructure to operate. For security hardening beyond basic sandboxing, including network controls, credential management, and isolation options, see [Secure Deployment](</docs/en/agent-sdk/secure-deployment>). @@ -215,7 +215,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**: 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. + * **`mirror_error` messages**: when the SDK can’t deliver a batch to the store, it drops the batch, emits a `{ type: "system", subtype: "mirror_error" }` message, and continues the query. Alert on these if store durability matters. See [Mirror writes are best-effort](</docs/en/agent-sdk/session-storage#mirror-writes-are-best-effort>) for the retry and timeout behavior. ### @@ -259,7 +259,7 @@ agents per host = (host RAM - overhead) / (per-session RAM ceiling) -Measure the per-session ceiling by running a representative session to your target length under your expected tool load and recording peak RSS. The 1 GiB starting point in Resources is a floor, not the ceiling. Horizontal-scale routing depends on your pattern. For long-running sessions, where containers hold many sessions, run a pool of containers behind a load balancer and pin each session to one container using consistent hashing on `sessionId`. A pinned session keeps hitting the same container, and therefore the same running subprocess, until it is evicted or the container restarts. Large fanouts of concurrent [subagents](</docs/en/agent-sdk/subagents>) from a single session can hit API rate limits. Break the work into smaller batches rather than issuing one wide dispatch. +Measure the per-session ceiling by running a representative session to your target length under your expected tool load and recording peak RSS. The 1 GiB starting point in Resources is a floor, not the ceiling. Horizontal-scale routing depends on your pattern. For long-running sessions, where containers hold many sessions, run a pool of containers behind a load balancer and pin each session to one container using consistent hashing on `sessionId`. A pinned session keeps hitting the same container, and therefore the same running subprocess, until it is evicted or the container restarts. ###
modified What's new View current →
--- a/index.md +++ b/index.md @@ -1,4 +1,24 @@ The weekly dev digest highlights the features most likely to change how you work. Each entry includes runnable code, a short demo, and a link to the full docs. For every bug fix and minor improvement, see the [changelog](</docs/en/changelog>). + +​ + +Week 32 + +v2.1.220–v2.1.224 + +August 3–7, 2026 + +**Cross-session messaging** : on macOS and Linux, your Claude Code sessions can now message each other, so Claude passes a finding or a decision from one session to another instead of you re-explaining it.Also this week: **self-hosted environments** run Claude Code cloud sessions on infrastructure your organization operates, in public beta on Team and Enterprise plans; **auto mode** becomes the default permission mode for new sessions on Pro, Max, and Team plans starting August 14; and the **VS Code extension** gets Focus view.[Read the Week 32 digest →](</docs/en/whats-new/2026-w32>) + +​ + +Week 30 + +v2.1.214–v2.1.219 + +July 20–24, 2026 + +**Claude Opus 5** : the new default Opus model in Claude Code, with a 1M-token context window and fast mode at $10/$50 per MTok.Also this week: **Claude Code Desktop** opens an iOS Simulator pane in public beta so Claude can run your app and tap through it while you watch; the **Claude Security plugin** runs a multi-agent vulnerability scan of your codebase and turns the findings you pick into patches you apply yourself; and **`/code-review`** runs as a background subagent.[Read the Week 30 digest →](</docs/en/whats-new/2026-w30>) ​
modified Gateway protocol reference View current →
--- a/llm-gateway-protocol.md +++ b/llm-gateway-protocol.md @@ -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 Google Cloud’s 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. An Anthropic Messages-format gateway receives a `HEAD /api/hello` connection-warming probe, which Claude Code skips when an HTTP proxy or client certificate is configured. An Amazon Bedrock-format gateway receives a `GET /inference-profiles?type=SYSTEM_DEFINED` request and, when the configured model is an inference profile, `GET /inference-profiles/{profile}` lookups. The [fast mode](</docs/en/fast-mode>) availability check never appears in gateway logs: it calls `api.anthropic.com` directly rather than following `ANTHROPIC_BASE_URL`, so on a network that blocks direct egress to `api.anthropic.com`, fast mode can report a connectivity error while inference through the gateway keeps working. The [WebFetch domain safety check](</docs/en/data-usage#webfetch-domain-safety-check>) also calls `api.anthropic.com` directly. [Use fast mode behind proxies and LLM gateways](</docs/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways>) covers the variables that restore it. +Token-counting endpoints are the only optional ones: when they’re absent, Claude Code falls back to counting context usage through the inference endpoint instead. Inference requests post to `/v1/messages?beta=true`, so match on the path, not the full URL. The Google Cloud’s 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. An Anthropic Messages-format gateway receives a `HEAD /api/hello` connection-warming probe, which Claude Code skips when an HTTP proxy or client certificate is configured. An Amazon Bedrock-format gateway receives a `GET /inference-profiles?type=SYSTEM_DEFINED` request and, when the configured model is an inference profile, `GET /inference-profiles/{profile}` lookups. The [fast mode](</docs/en/fast-mode>) availability check never appears in gateway logs: it calls `api.anthropic.com` directly rather than following `ANTHROPIC_BASE_URL`, so on a network that blocks direct egress to `api.anthropic.com`, fast mode can report a connectivity error while inference through the gateway keeps working. The [WebFetch domain safety check](</docs/en/data-usage#webfetch-domain-safety-check>) also calls `api.anthropic.com` directly. [Use fast mode behind proxies and LLM gateways](</docs/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways>) covers the variables that restore it. ### @@ -128,7 +128,7 @@ [Extended context](<https://platform.claude.com/docs/en/build-with-claude/context-windows#context-window-sizes-by-model>) and [interleaved thinking](<https://platform.claude.com/docs/en/build-with-claude/extended-thinking#interleaved-thinking>)| Beta headers only, no body field| Silently unavailable when the header is stripped; the upstream never sees the capability request| Forward `anthropic-beta` verbatim 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 Amazon Bedrock and Google Cloud’s 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 +[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 counting context usage through the messages endpoint| Expose the endpoint so token counts don’t consume inference requests 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.
modified Connect to external tools with MCP View current →
Show diff (2118 lines)
--- a/mcp.md +++ b/mcp.md @@ -1,1209 +1,921 @@ -Claude Code can connect to hundreds of external tools and data sources through the [Model Context Protocol (MCP)](<https://modelcontextprotocol.io/introduction>), an open source standard for AI-tool integrations. MCP servers give Claude Code access to your tools, databases, and APIs. Connect a server when you find yourself copying data into chat from another tool, like an issue tracker or a monitoring dashboard. Once connected, Claude can read and act on that system directly instead of working from what you paste. If you’re connecting your first server, start with the [MCP quickstart](</docs/en/mcp-quickstart>) for a step-by-step walkthrough. This page is the full reference. - -## - -​ - -What you can do with MCP - -With MCP servers connected, you can ask Claude Code to: - - * **Implement features from issue trackers** : “Add the feature described in JIRA issue ENG-4521 and create a PR on GitHub.” - * **Analyze monitoring data** : “Check Sentry and Statsig to check the usage of the feature described in ENG-4521.” - * **Query databases** : “Find emails of 10 random users who used feature ENG-4521, based on our PostgreSQL database.” - * **Integrate designs** : “Update our standard email template based on the new Figma designs that were posted in Slack” - * **Automate workflows** : “Create Gmail drafts inviting these 10 users to a feedback session about the new feature.” - * **React to external events** : an MCP server can also act as a [channel](</docs/en/channels>) that pushes messages into your session, so Claude reacts to Telegram messages, Discord chats, or webhook events while you’re away. - -## - -​ - -Find and build MCP servers - -Browse reviewed connectors in the [Anthropic Directory](<https://claude.ai/directory>). Directory connectors use the same MCP infrastructure as Claude Code, so you can add any remote server listed there with `claude mcp add`. - -Verify you trust each server before connecting it. Servers that fetch external content can expose you to [prompt injection risk](</docs/en/security#protect-against-prompt-injection>). - -To build your own server, see the [MCP server guide](<https://modelcontextprotocol.io/docs/develop/build-server>) for protocol fundamentals and the [Claude connector building docs](<https://claude.com/docs/connectors/building>) for authentication, testing, and Directory submission. You can also have Claude scaffold a server for you with the official [`mcp-server-dev` plugin](<https://github.com/anthropics/claude-plugins-official/tree/main/plugins/mcp-server-dev>). - -1 - -Install the plugin - -In a Claude Code session, run: - - /plugin install mcp-server-dev@claude-plugins-official - -If the install fails, match the message Claude Code reports: - - * `Marketplace "claude-plugins-official" not found`: add the marketplace with `/plugin marketplace add anthropics/claude-plugins-official`, then retry the install. - * The plugin is not found in the marketplace: check the plugin name. Claude Code [refreshes a stale marketplace catalog and retries](</docs/en/discover-plugins#install-plugins>) before reporting this, so if you turned off [marketplace auto-update](</docs/en/discover-plugins#configure-auto-updates>), refresh manually with `/plugin marketplace update claude-plugins-official` and retry the install. - -Check the install summary: if it reports `Run /reload-plugins to activate.`, run that command. - -2 - -Run the build skill - - /mcp-server-dev:build-mcp-server - -Claude asks about your use case and scaffolds a remote HTTP or local stdio server. - -## - -​ - -Installing MCP servers - -MCP servers can be configured in several ways depending on your needs: - -### - -​ - -Option 1: Add a remote HTTP server - -HTTP servers are the recommended option for connecting to remote MCP servers. This is the most widely supported transport for cloud-based services. - - # Basic syntax - claude mcp add --transport http <name> <url> - - # Real example: Connect to Notion - claude mcp add --transport http notion https://mcp.notion.com/mcp - - # Example with Bearer token - claude mcp add --transport http secure-api https://api.example.com/mcp \ - --header "Authorization: Bearer your-token" - -When configuring MCP servers via JSON in `.mcp.json`, `~/.claude.json`, or `claude mcp add-json`, the `type` field accepts `streamable-http` as an alias for `http`. The MCP specification uses the name `streamable-http` for this transport, so configurations copied from server documentation work without modification. A JSON entry that has a `url` but no `type` is a configuration error, because Claude Code reads an entry with no `type` as a stdio server. Claude Code skips that server and reports `MCP server "<name>" has a "url" but no "type"; add "type": "http" (or "sse" / "ws") to this entry`. Before v2.1.202, Claude Code reported this misconfiguration as `command: expected string, received undefined`. In `--output-format stream-json` runs, Claude Code also reports a skipped `--mcp-config` entry in the `system/init` event’s [`mcp_server_errors` field](</docs/en/headless#stream-responses>), so scripts can detect that the server never loaded. This requires Claude Code v2.1.219 or later. - -### - -​ - -Option 2: Add a remote SSE server - -The SSE (Server-Sent Events) transport is deprecated. Use HTTP servers instead, where available. - -Some services still expose only an SSE endpoint. Use the same command as the HTTP transport, with `--transport sse`: - - # Basic syntax - claude mcp add --transport sse <name> <url> - - # Real example: Connect to Asana - claude mcp add --transport sse asana https://mcp.asana.com/sse - - # Example with authentication header - claude mcp add --transport sse private-api https://api.company.com/sse \ - --header "X-API-Key: your-key-here" - -### - -​ - -Option 3: Add a local stdio server - -Stdio servers run as local processes on your machine. They’re ideal for tools that need direct system access or custom scripts. Claude Code sets `CLAUDE_PROJECT_DIR` in the spawned server’s environment to the project root, so your server can resolve project-relative paths without depending on the working directory. This is the same directory hooks receive in their `CLAUDE_PROJECT_DIR` variable. Read it from inside your server process, for example `process.env.CLAUDE_PROJECT_DIR` in Node or `os.environ["CLAUDE_PROJECT_DIR"]` in Python. `CLAUDE_PROJECT_DIR` is the stable project root and doesn’t change when you add or remove working directories mid-session. A server that limits its own filesystem access to a set of allowed directories should implement the MCP `roots/list` request instead. Claude Code answers `roots/list` with the session’s launch directory plus every [additional working directory](</docs/en/permissions#working-directories>) you’ve granted with `--add-dir`, `/add-dir`, or the `additionalDirectories` setting. Claude Code sends `notifications/roots/list_changed` when that set changes. Before v2.1.203, `roots/list` returned only the launch directory and Claude Code didn’t send `notifications/roots/list_changed`. This variable is set in the server’s environment, not in Claude Code’s own environment, so referencing it via `${VAR}` expansion in the `command` or `args` of a project-scoped `.mcp.json` entry or a local- or user-scoped server entry in `~/.claude.json` requires a default such as `${CLAUDE_PROJECT_DIR:-.}`. Plugin-provided MCP configurations substitute `${CLAUDE_PROJECT_DIR}` directly and don’t need the default. - - # Basic syntax - claude mcp add [options] <name> -- <command> [args...] - - # Real example: Add Airtable server - claude mcp add --env AIRTABLE_API_KEY=YOUR_KEY --transport stdio airtable \ - -- npx -y airtable-mcp-server - -**Important: Separate server arguments with`--`**For stdio servers, the `--` (double dash) separates Claude’s own options, such as `--transport`, `--env`, and `--scope`, from the command and arguments that run the server. Everything after `--` is passed to the server untouched.For example: - - * `claude mcp add --transport stdio myserver -- npx server` → runs `npx server` - * `claude mcp add --env KEY=value --transport stdio myserver -- python server.py --port 8080` → runs `python server.py --port 8080` with `KEY=value` in environment - -Without `--`, Claude Code would try to parse the server’s flags, like `--port` above, as its own options.`--env` accepts multiple `KEY=value` pairs. If the server name comes directly after `--env`, the CLI reads the name as another pair and rejects it, so place at least one other option between `--env` and the server name, as in the examples above. - -### - -​ - -Option 4: Add a remote WebSocket server - -WebSocket servers hold a persistent bidirectional connection, which suits remote MCP servers that push events to Claude unprompted. Use HTTP instead when your server only responds to requests, since HTTP supports OAuth and the `claude mcp add --transport` flag, while WebSocket supports neither. Configure WebSocket servers in `.mcp.json` or with `claude mcp add-json`: - - claude mcp add-json events-server \ - '{"type":"ws","url":"wss://mcp.example.com/socket","headers":{"Authorization":"Bearer YOUR_TOKEN"}}' - -The `type: "ws"` entry accepts the same `url`, `headers`, `headersHelper`, `timeout`, and `alwaysLoad` fields as `http`. Authentication is header-only, so pass a static token in `headers` or generate one at connect time with `headersHelper`. The `claude mcp add --transport` flag doesn’t accept `ws`. - -### - -​ - -Managing your servers - -Once configured, you can manage your MCP servers with these commands: - - # List all configured servers - claude mcp list - - # Get details for a specific server - claude mcp get notion - - # Remove a server - claude mcp remove notion - - # (within Claude Code) Check server status - /mcp - -#### - -​ - -Server status - -`claude mcp add` confirms a successful add by printing an `Added ...` line, which means the configuration was written. `claude mcp list` then shows a health status next to each server it lists, such as `✔ Connected`, `! Needs authentication`, or `✘ Failed to connect`. A failure status means Claude Code couldn’t connect to that server, not that the list command failed. Project-scoped servers from `.mcp.json` that are awaiting your approval appear in `claude mcp list` and `claude mcp get <name>` as `⏸ Pending approval (run `claude` to approve)`. Run `claude` interactively to review and approve them. `claude mcp get <name>` shows rejected servers as `✘ Rejected (see disabledMcpjsonServers in settings)`. WebSocket servers don’t appear in `claude mcp list` output. Use `claude mcp get <name>` or the `/mcp` panel to check them. - -#### - -​ - -Project server approvals and workspace trust - -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` - -Approvals in an untracked `.claude/settings.local.json` also apply, but only after you accept a trust dialog for that folder or one of its parent directories: Claude Code runs git to check whether the file is tracked, and it runs that check only in a trusted folder. In a folder you’ve never trusted, the file’s approvals wait for the trust dialog unless the folder is your own configuration home: your home directory, or a directory whose `.claude` you’ve set as [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars>). Before v2.1.207, an untracked `.claude/settings.local.json` approved servers in a folder you’d never trusted. A `disabledMcpjsonServers` entry in any settings file still rejects the server. - -#### - -​ - -Server status detail - -In `/mcp`, a server’s menu, and the [`/plugin`](</docs/en/plugins>) manager, a remote (HTTP or SSE) server you’ve used before can show a `cached` status such as `cached 2h ago · connects on first use · 5 tools`. Claude Code loaded the server’s tool list from a previous session instead of connecting at startup, and it connects the server the first time Claude calls one of its tools. The tools are available from your first message, so you don’t need to do anything. To make every server connect at startup instead, set [`MCP_DISCOVERY_CACHE=0`](</docs/en/env-vars>). The discovery cache and its `cached` status require Claude Code v2.1.221 or later. When a server’s status is `✘ Failed to connect`, `claude mcp list` appends the failure detail to that status line, and `claude mcp get <name>` shows it on an `Issue:` line: the HTTP status or error code, plus any error text the server returned. The server’s detail view in `/mcp` includes the same server-reported text in its `Issue:` row. Claude Code redacts credential-like text from this detail and never includes the expanded server URL, which can carry secrets. Claude Code appends no detail to a `✘ Connection error` status, because the exception text it would print there can embed that URL. Before v2.1.219, both commands showed only the bare failure status, without the status code or the server’s error text. A remote server whose configuration has an empty `url` shows as `not configured` in `/mcp`, in `claude mcp list`, and in the [`/plugin`](</docs/en/plugins>) manager, and Claude Code doesn’t attempt to connect to it. A plugin can include a placeholder entry like this for a connector you configure later, so Claude Code doesn’t report it as an error or a setup issue. The server’s detail view in `/mcp` reads `No URL configured for this server`; set the entry’s `url` to connect it. Before v2.1.208, Claude Code reported an empty `url` as a configuration issue with a prompt to reconnect. - -#### - -​ - -Configuration warnings - -Claude Code also warns when an MCP config value carries hidden leading or trailing whitespace, which often comes from pasting a token with a trailing newline. Claude Code checks `command`, `url`, each `args` entry, and the values and key names under `env` and `headers`. Claude Code shows the warning in `claude mcp list` output and in `/mcp`, naming the affected fields without echoing their values, for example `Leading or trailing whitespace in: headers.Authorization`. Claude Code doesn’t trim the whitespace and uses the values exactly as written, so edit the configuration to remove it. Some server names are reserved for Claude Code’s built-in servers: `workspace`, `claude-in-chrome`, `computer-use`, `Claude Preview`, and `Claude Browser`. If your configuration defines a server with a reserved name, Claude Code skips it at load time and shows a warning asking you to rename it. `claude mcp add` rejects a reserved name with an error. `Claude Preview` and `Claude Browser` both name the built-in server that the [Claude Code desktop app’s preview pane](</docs/en/desktop#preview-your-app>) uses. Before v2.1.205, `Claude Browser` wasn’t reserved, so a user-configured server could register under that name. - -#### - -​ - -Tool availability - -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. How the wait happens depends on your configuration: - - * **Withtool search, the default**: the wait happens inside the `ToolSearch` call. - * **Without tool search** : Claude uses the `WaitForMcpServers` tool instead. Configurations without tool search include a custom `ANTHROPIC_BASE_URL`, `ENABLE_TOOL_SEARCH=false`, and a model earlier than the Claude 4.5 generation on Google Cloud’s Agent Platform. - * **On a Microsoft Foundry[deployment hosted on Azure](<https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry#hosting-options>)**: Claude starts on the tool-search path rather than with `WaitForMcpServers`, since Claude Code discovers the deployment’s server-side rejection only from the API. After Claude Code switches that deployment to upfront loading, tools from a server that finishes connecting become available on Claude’s next request. - -With tool search enabled, when a server finishes connecting while Claude is working, Claude Code lists the server’s tool names to Claude on its next request in the same turn. Claude can then search for and call those tools without waiting for your next message. - -### - -​ - -Disable a server without removing it - -Toggle a server off in the `/mcp` panel to stop Claude Code from connecting to it without losing its configuration. Claude Code still lists the server in `/mcp`, marked as disabled. When you toggle a server, Claude Code records your choice per project in `~/.claude.json`, in one of two lists that cover disjoint sets of servers: - - * `disabledMcpServers`: an opt-out list for user-configured servers, plugin servers, claude.ai connectors, and built-in servers that default to on. Claude Code doesn’t connect to a server you list here. When you disable a claude.ai connector with the per-project `/mcp` toggle described in Disable claude.ai connectors, Claude Code writes it to this list under its display name, for example `claude.ai Slack`. - * `enabledMcpServers`: an opt-in list for built-in servers that default to off, such as `computer-use`. Claude Code connects to a default-off server only when you list it here. - -Claude Code consults exactly one of the two lists for each server, so neither list overrides the other. If you add a regular server to `enabledMcpServers`, or a default-off built-in server to `disabledMcpServers`, Claude Code ignores the entry. `disabledMcpServers` and `enabledMcpServers` are unrelated to [`enabledMcpjsonServers` and `disabledMcpjsonServers`](</docs/en/settings#available-settings>), which control approval of servers defined in a project’s `.mcp.json` file. - -### - -​ - -Dynamic tool updates - -Claude Code supports MCP `list_changed` notifications, allowing MCP servers to dynamically update their available tools, prompts, and resources without requiring you to disconnect and reconnect. When an MCP server sends a `list_changed` notification, Claude Code automatically refreshes the available capabilities from that server. If a refresh request fails, Claude Code keeps the server’s previously discovered tools, prompts, and resources until a later refresh succeeds. Before v2.1.214, a transient error during the refresh replaced the server’s tools, prompts, and resources with an empty list. - -### - -​ - -Automatic reconnection - -If an HTTP or SSE server disconnects mid-session, Claude Code automatically reconnects with exponential backoff: up to five attempts, starting at a one-second delay and doubling each time. The server appears as pending in `/mcp` while reconnection is in progress. After five failed attempts the server is marked as failed and you can retry manually from `/mcp`. Stdio servers are local processes and are not reconnected automatically. The same backoff applies when an HTTP or SSE server fails its initial connection at startup. Claude Code retries the initial connection up to three times on transient errors such as a 5xx response, a connection refused, or a timeout, then marks the server as failed if it still can’t connect. Authentication and not-found errors are not retried because they require a configuration change to resolve. When a configured server fails to connect, Claude Code tells Claude which server failed and its connection error, including in `ToolSearch` results that find no matching tool, so Claude reports the connection failure in its response. Requires tool search, which is enabled by default. In configurations without tool search, such as a custom `ANTHROPIC_BASE_URL`, `ENABLE_TOOL_SEARCH=false`, or a model that doesn’t support tool search, and on Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry, Claude Code doesn’t report failed server connections to Claude. Before v2.1.205, Claude Code didn’t pass connection errors to Claude, and Claude could respond as if the failed server’s tools were never configured. As of v2.1.191, the capability discovery requests that run after a successful connection, such as `tools/list`, `prompts/list`, and `resources/list`, also retry transient network and server errors up to three times with short backoff. Authentication errors, 4xx responses, and request timeouts are not retried. - -### - -​ - -Push messages with channels - -An MCP server can also push messages directly into your session so Claude can react to external events like CI results, monitoring alerts, or chat messages. To enable this, your server declares the `claude/channel` capability and you opt it in with the `--channels` flag at startup. See [Channels](</docs/en/channels>) to use an officially supported channel, or [Channels reference](</docs/en/channels-reference>) to build your own. - -Tips: - - * Use the `-s` or `--scope` flag to specify where the configuration is stored: - * `local` (default): available only to you in the current project - * `project`: shared with everyone in the project via the `.mcp.json` file - * `user`: available to you across all projects - * Set environment variables with `-e` or `--env` flags (for example, `-e KEY=value`) - * The `--transport` and `--header` flags also accept `-t` and `-H` short forms - * Configure MCP server startup timeout using the `MCP_TIMEOUT` environment variable (for example, `MCP_TIMEOUT=10000 claude` sets a 10-second timeout) - * Set a per-server tool execution timeout by adding a `timeout` field in milliseconds to that server’s `.mcp.json` entry, for example `"timeout": 600000` for ten minutes. This overrides the `MCP_TOOL_TIMEOUT` environment variable for that server only - * Claude Code displays a warning when MCP tool output exceeds 10,000 tokens and limits output to 25,000 tokens by default. To raise the limit, set the `MAX_MCP_OUTPUT_TOKENS` environment variable (for example, `MAX_MCP_OUTPUT_TOKENS=50000`); the warning threshold is fixed. See MCP output limits and warnings - * Use `/mcp` to authenticate with remote servers that require OAuth 2.0 authentication - -The per-server `timeout` is a hard wall-clock limit per tool call, and progress notifications from the server don’t extend it. Values below 1000 are ignored and fall through to `MCP_TOOL_TIMEOUT`, or to its default of about 28 hours when that variable is unset. For an HTTP, SSE, or [claude.ai connector](</docs/en/mcp#use-mcp-servers-from-claude-ai>) server there is also a second, per-request timer that covers each request through to the server’s first response byte. That timer is 60 seconds unless you set the per-server `timeout` or `MCP_TOOL_TIMEOUT`; setting either to 60 seconds or higher raises the per-request timer to that value, a lower value doesn’t shorten it, and the 28-hour default of an unset `MCP_TOOL_TIMEOUT` never feeds it. Stdio and WebSocket servers have no per-request timer. Before v2.1.162, values below 1000 were floored to one second instead. A per-server `timeout` of at least 1000 also acts as a floor on the idle timeout described below: Claude Code never aborts that server’s tool calls for idleness sooner than the per-server `timeout`. Requires Claude Code v2.1.203 or later. A tool call to an MCP server that sends no response and no progress notification for the idle window aborts with an error instead of waiting for the wall-clock limit. The idle timeout requires Claude Code v2.1.187 or later. It applies to every server type except IDE servers and SDK in-process servers. The idle window defaults to five minutes for HTTP, SSE, WebSocket, and claude.ai connector servers, and to 30 minutes for stdio servers. Before v2.1.203, stdio servers were exempt from the idle timeout. Set the [`CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT`](</docs/en/env-vars>) environment variable in milliseconds to change the idle window, or set it to `0` to disable the check. These timeouts bound how long a call can run, not always how long it blocks the session: on Claude Code v2.1.212 or later, a main-conversation call that runs past two minutes moves to a background task first. See Automatic backgrounding of long tool calls. - -### - -​ - -Automatic backgrounding of long tool calls - -An MCP tool call in the main conversation that is still running after two minutes moves to a background task instead of blocking the session. Claude receives the task ID immediately and keeps working, and the result arrives as a task notification when the call settles. Automatic backgrounding requires Claude Code v2.1.212 or later. The task appears in [`/tasks`](</docs/en/commands#all-commands>), where you can also stop it, and it doesn’t survive exiting the session. The per-call limits still apply while the call runs in the background: the wall-clock limit set by the per-server `timeout` or [`MCP_TOOL_TIMEOUT`](</docs/en/env-vars>), and the idle timeout set by [`CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT`](</docs/en/env-vars>). Set the [`CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS`](</docs/en/env-vars>) environment variable in milliseconds to change the threshold, or set it to `0` to turn automatic backgrounding off. Setting `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` to `1` also turns it off, along with all other background task features. Some calls never move to the background: - - * Calls from [subagents](</docs/en/sub-agents>); Claude Code backgrounds only main-conversation calls - * Calls to IDE servers - * Calls in [non-interactive mode](</docs/en/headless>), unless `CLAUDE_AUTO_BACKGROUND_TASKS` is set to `1`, since a one-shot run can end before the result arrives - -A call waiting on an open elicitation dialog isn’t backgrounded while the dialog is open; the server is blocked on your input, not slow, so Claude Code defers the move until the dialog closes. - -### - -​ - -Plugin-provided MCP servers - -[Plugins](</docs/en/plugins>) can bundle MCP servers that provide tools and integrations when you enable the plugin. Plugin MCP servers work identically to user-configured servers. **How plugin MCP servers work** : - - * Plugins define MCP servers in `.mcp.json` at the plugin root or inline in `plugin.json` - * When you enable a plugin, Claude Code starts its MCP servers automatically - * Claude Code offers plugin MCP tools alongside manually configured MCP tools - * You add and remove plugin servers by installing or uninstalling the plugin, not with `/mcp` commands. You can still toggle an installed plugin server off in `/mcp`, which stops Claude Code from connecting to it without removing the plugin - -**Example plugin MCP configuration** : In `.mcp.json` at plugin root: +The [Model Context Protocol (MCP)](<https://modelcontextprotocol.io/docs/getting-started/intro>) is an open standard for connecting AI agents to external tools and data sources. With MCP, your agent can query databases, integrate with APIs like Slack and GitHub, and connect to other services without writing custom tool implementations. MCP servers can run as local processes, connect over HTTP, or execute directly within your SDK application. + +This page covers MCP configuration for the Agent SDK. To add MCP servers to the Claude Code CLI so they load in every project, see [MCP installation scopes](</docs/en/mcp#mcp-installation-scopes>). + +## + +​ + +Quickstart + +This example connects to the [Claude Code documentation](<https://code.claude.com/docs>) MCP server using HTTP transport and uses `allowedTools` with a wildcard to permit all tools from the server. + +TypeScript + +Python + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + for await (const message of query({ + prompt: "Use the docs MCP server to explain what hooks are in Claude Code", + options: { + mcpServers: { + "claude-code-docs": { + type: "http", + url: "https://code.claude.com/docs/mcp" + } + }, + allowedTools: ["mcp__claude-code-docs__*"] + } + })) { + if (message.type === "result" && message.subtype === "success") { + console.log(message.result); + } + } + + import asyncio + from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage + + async def main(): + options = ClaudeAgentOptions( + mcp_servers={ + "claude-code-docs": { + "type": "http", + "url": "https://code.claude.com/docs/mcp", + } + }, + allowed_tools=["mcp__claude-code-docs__*"], + ) + + async for message in query( + prompt="Use the docs MCP server to explain what hooks are in Claude Code", + options=options, + ): + if isinstance(message, ResultMessage) and message.subtype == "success": + print(message.result) + + asyncio.run(main()) + +The agent connects to the documentation server, searches for information about hooks, and returns the results. + +## + +​ + +Add an MCP server + +You can configure MCP servers in code when calling `query()`, or in a `.mcp.json` file loaded via `settingSources`. + +### + +​ + +In code + +Pass MCP servers directly in the `mcpServers` option: + +TypeScript + +Python + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + for await (const message of query({ + prompt: "List files in my project", + options: { + mcpServers: { + filesystem: { + command: "npx", + args: ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"] + } + }, + allowedTools: ["mcp__filesystem__*"] + } + })) { + if (message.type === "result" && message.subtype === "success") { + console.log(message.result); + } + } + + import asyncio + from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage + + async def main(): + options = ClaudeAgentOptions( + mcp_servers={ + "filesystem": { + "command": "npx", + "args": [ + "-y", + "@modelcontextprotocol/server-filesystem", + "/Users/me/projects", + ], + } + }, + allowed_tools=["mcp__filesystem__*"], + ) + + async for message in query(prompt="List files in my project", options=options): + if isinstance(message, ResultMessage) and message.subtype == "success": + print(message.result) + + asyncio.run(main()) + +### + +​ + +From a config file + +Create a `.mcp.json` file at your project root. The file is picked up when the `project` setting source is enabled, which it is for default `query()` options. If you set `settingSources` explicitly, include `"project"` for this file to load: { "mcpServers": { - "database-tools": { - "command": "${CLAUDE_PLUGIN_ROOT}/servers/db-server", - "args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"], - "env": { - "DB_URL": "${DB_URL}" - } - } - } - } - -Or inline in `plugin.json`: - - { - "name": "my-plugin", - "mcpServers": { - "plugin-api": { - "command": "${CLAUDE_PLUGIN_ROOT}/servers/api-server", - "args": ["--port", "8080"] - } - } - } - -**Plugin MCP features** : - - * **Automatic lifecycle** : servers connect and disconnect at these points: - * At session startup, Claude Code connects the servers for enabled plugins automatically. In `/mcp`, a remote (HTTP or SSE) plugin server you’ve used before can show the `cached` status instead; Claude Code connects it when Claude first calls one of its tools - * If you enable or disable a plugin during a session, run `/reload-plugins` to connect or disconnect its MCP servers. When you reload, Claude Code keeps the live connections of plugin servers whose configuration is unchanged, and does the same when you [replace the session’s MCP server list](</docs/en/agent-sdk/typescript#mcpsetserversresult>) from the Agent SDK without naming them. Before v2.1.210, Claude Code disconnected plugin-provided MCP servers that the new SDK server list didn’t name - * In [web sessions](</docs/en/claude-code-on-the-web>), an MCP call to a plugin server that isn’t connected yet, such as right after an idle session wakes, starts the server on demand and waits for it to connect. Before v2.1.211, plugin servers in a web session reconnected only when the next message started a turn, so MCP calls after an idle session woke failed until then - * **Path placeholders** : `${CLAUDE_PLUGIN_ROOT}` resolves to the plugin’s installation directory, `${CLAUDE_PLUGIN_DATA}` to its [persistent state](</docs/en/plugins-reference#persistent-data-directory>) directory, and `${CLAUDE_PROJECT_DIR}` to the stable project root. Substitution applies to: - * `stdio` servers: `command`, `args`, `env` - * `http`, `sse`, and `ws` servers: `url`, `headers`, and `headersHelper`. Before v2.1.195, `headersHelper` passed the placeholder through as a literal string - * **User environment access** : access to the same environment variables as manually configured servers - * **Multiple transport types** : support for stdio, SSE, HTTP, and WebSocket transports, though transport support may vary by server - -Plugin servers appear in `/mcp` with indicators showing they come from plugins. **Plugin MCP tool names** : Tools from a plugin-bundled MCP server include both the plugin name and the server key in their callable name. The full form is `mcp__plugin_<plugin-name>_<server-name>__<tool-name>`, where any character outside `A-Z`, `a-z`, `0-9`, `_`, and `-` is replaced with `_`. For the `database-tools` server bundled in a plugin named `my-plugin`, a `query` tool is callable as: - - mcp__plugin_my-plugin_database-tools__query - -Use this full name when referencing the tool in [permission rules](</docs/en/permissions>), a skill’s `allowed-tools` list, a [subagent’s `tools` field](</docs/en/sub-agents#available-tools>), or a [hook matcher](</docs/en/hooks#match-mcp-tools>). A hook matcher written against the bare server key, such as `mcp__database-tools__.*`, never fires for a plugin-bundled server. The server itself registers under the scoped name `plugin:<plugin-name>:<server-name>`, such as `plugin:my-plugin:database-tools`. Use that name where a configured server name is expected, such as an [`mcp_tool` hook’s `server` field](</docs/en/hooks#mcp-tool-hook-fields>). See the [plugin components reference](</docs/en/plugins-reference#mcp-servers>) for details on bundling MCP servers with plugins. - -## - -​ - -MCP installation scopes - -MCP servers can be configured at three scopes. The scope you choose controls which projects the server loads in and whether the configuration is shared with your team. Administrators can also deploy servers at the enterprise level via managed configuration. - -Scope| Loads in| Shared with team| Stored in ----|---|---|--- -Local| Current project only| No| `~/.claude.json` -Project| Current project only| Yes, via version control| `.mcp.json` in project root -User| All your projects| No| `~/.claude.json` - -### - -​ - -Local scope - -Local scope is the default. A local-scoped server loads only in the project where you added it and stays private to you. Claude Code stores it in `~/.claude.json` under that project’s path, so the same server won’t appear in your other projects. Use local scope for personal development servers, experimental configurations, or servers with credentials you don’t want in version control. - -The term “local scope” for MCP servers differs from general local settings. MCP local-scoped servers are stored in `~/.claude.json` (your home directory), while general local settings use `.claude/settings.local.json` (in the project directory). See [Settings](</docs/en/settings#settings-files>) for details on settings file locations. - - # Add a local-scoped server (default) - claude mcp add --transport http stripe https://mcp.stripe.com - - # Explicitly specify local scope - claude mcp add --transport http stripe --scope local https://mcp.stripe.com - -The command writes the server into the entry for your current project inside `~/.claude.json`. The example below shows the result when you run it from `/path/to/your/project`: - - { - "projects": { - "/path/to/your/project": { - "mcpServers": { - "stripe": { - "type": "http", - "url": "https://mcp.stripe.com" + "filesystem": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"] + } + } + } + +## + +​ + +Connection timing + +Claude Code registers the servers you pass in `options.mcpServers` at startup and emits the init message once the first-turn wait, if any, resolves. Servers loaded from settings files such as `.mcp.json` don’t get the full wait and commonly show `pending` at init. When each `options.mcpServers` server connects, and whether it delays the first turn, depends on its type: + +Server type| Delays the first turn?| First-turn wait timeout +---|---|--- +stdio server, or HTTP/SSE server without a cached tool list| Yes, until it connects| [`MCP_TIMEOUT`](</docs/en/env-vars>), 30 seconds by default; the connection fails at that deadline +Remote server with a cached tool list, saved by Claude Code from a previous connection| No; the cached tools are available from the first turn| None; connects on its first tool call, and that deferred connect has its own timeout +In-process SDK server| No; never delays the first turn| None + +To block startup itself at a separate, earlier phase than the first-turn wait, before the init message is sent: + + * Set [`MCP_CONNECTION_NONBLOCKING`](</docs/en/env-vars>) to `0` to block on the whole connection batch. Claude Code caps that wait at 5 seconds by default. Adjust the cap with the [`MCP_CONNECT_TIMEOUT_MS`](</docs/en/env-vars>) environment variable, in milliseconds. Servers still pending at that deadline keep connecting in the background. + * Set `alwaysLoad: true` on a server’s config to make its tools available at their full schemas on the first turn, [exempt from tool search deferral](</docs/en/mcp#exempt-a-server-from-deferral>). Claude Code waits at startup for that server’s tools, capped at the same deadline, while other servers keep connecting in the background; a remote server with a cached tool list supplies them without connecting, per the table above. + +The `system` message with subtype `init` reports each server’s status at the moment it’s emitted. Check for status `failed` or `needs-auth` when you want to detect servers that won’t be usable, rather than treating every status other than `connected` as a failure; see Error handling for the full status check. + +## + +​ + +Allow MCP tools + +MCP tools require explicit permission before Claude can use them. Without permission, Claude will see that tools are available but won’t be able to call them. + +### + +​ + +Tool naming convention + +MCP tools follow the naming pattern `mcp__<server-name>__<tool-name>`. For example, a GitHub server named `"github"` with a `list_issues` tool becomes `mcp__github__list_issues`. + +### + +​ + +Auto-approve with allowedTools + +Use `allowedTools` to auto-approve specific MCP tools so Claude can use them without a permission prompt: + +TypeScript + +Python + + const _ = { + options: { + mcpServers: { + // your servers + }, + allowedTools: [ + "mcp__github__*", // All tools from the github server + "mcp__db__query", // Only the query tool from db server + "mcp__slack__send_message" // Only send_message from slack server + ] + } + }; + + options = ClaudeAgentOptions( + mcp_servers={ + # your servers + }, + allowed_tools=[ + "mcp__github__*", # All tools from the github server + "mcp__db__query", # Only the query tool from db server + "mcp__slack__send_message", # Only send_message from slack server + ], + ) + +Wildcards (`*`) let you allow all tools from a server without listing each one individually. + +**Prefer`allowedTools` over permission modes for MCP access.** `permissionMode: "acceptEdits"` does not auto-approve MCP tools (only file edits and filesystem Bash commands). `permissionMode: "bypassPermissions"` does auto-approve MCP tools but also disables most other safety prompts, which is broader than necessary; see [How permissions are evaluated](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) for the prompts that remain. A wildcard in `allowedTools` grants exactly the MCP server you want and nothing more. See [Permission modes](</docs/en/agent-sdk/permissions#permission-modes>) for a full comparison. + +### + +​ + +Discover available tools + +To see what tools an MCP server provides, check the server’s documentation or inspect the `tools` array in the `system` init message. MCP tool names start with `mcp__`. Claude Code emits the init message after the first-turn connection wait for servers passed in `options.mcpServers`, so the `tools` array lists the `mcp__` tools of each such server that connected within the wait. A server with a cached tool list shows `pending` with its `mcp__` tools already listed and a connection made on first use. Any other server that hasn’t connected when the message is emitted, including settings-file servers that don’t get the full wait, shows its current status, such as `pending`, `failed`, or `needs-auth`, with its tools absent; see Error handling for the full status set. This filter prints the MCP tool names: + +TypeScript + +Python + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + const options = { + mcpServers: { + // your servers + }, + }; + + for await (const message of query({ prompt: "...", options })) { + if (message.type === "system" && message.subtype === "init") { + const mcpTools = message.tools.filter((name) => name.startsWith("mcp__")); + console.log("Available MCP tools:", mcpTools); + } + } + + import asyncio + from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage + + async def main(): + options = ClaudeAgentOptions( + mcp_servers={ + # your servers + }, + ) + async for message in query(prompt="...", options=options): + if isinstance(message, SystemMessage) and message.subtype == "init": + mcp_tools = [t for t in message.data.get("tools", []) if t.startswith("mcp__")] + print("Available MCP tools:", mcp_tools) + + asyncio.run(main()) + +You can also ask Claude to list the tools available from a server. + +## + +​ + +Transport types + +MCP servers communicate with your agent using different transport protocols. Check the server’s documentation to see which transport it supports: + + * If the docs give you a **command to run** (like `npx @modelcontextprotocol/server-filesystem`), use stdio + * If the docs give you a **URL** , use HTTP or SSE + * If you’re building your own tools in code, use an SDK MCP server + +### + +​ + +stdio servers + +Local processes that communicate via stdin/stdout. Use this for MCP servers you run on the same machine: + + * In code + + * .mcp.json + +TypeScript + +Python + + const _ = { + options: { + mcpServers: { + filesystem: { + command: "npx", + args: ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"] + } + }, + allowedTools: ["mcp__filesystem__read_file", "mcp__filesystem__list_directory"] + } + }; + + options = ClaudeAgentOptions( + mcp_servers={ + "filesystem": { + "command": "npx", + "args": [ + "-y", + "@modelcontextprotocol/server-filesystem", + "/Users/me/projects", + ], } - } - } - } - } - -### - -​ - -Project scope - -Project-scoped servers enable team collaboration by storing configurations in a `.mcp.json` file at your project’s root directory. When you add a project-scoped server, Claude Code automatically creates or updates this file with the appropriate configuration structure. Check `.mcp.json` into version control so everyone on your team gets the same MCP tools and services. - - # Add a project-scoped server - claude mcp add --transport http shared-server --scope project https://example.com/mcp - -The resulting `.mcp.json` file follows a standardized format: + }, + allowed_tools=["mcp__filesystem__read_file", "mcp__filesystem__list_directory"], + ) { "mcpServers": { - "shared-server": { - "type": "http", - "url": "https://example.com/mcp" - } - } - } - -For security reasons, Claude Code prompts for approval in interactive sessions before using project-scoped servers from `.mcp.json` files. To reset those approval choices, run `claude mcp reset-project-choices`. `claude -p` runs, [Agent SDK](</docs/en/headless>) sessions, and [cloud sessions](</docs/en/claude-code-on-the-web>) can’t show that prompt: Claude Code loads project-scoped servers there without asking. To keep a server out anyway, add it to [`disabledMcpjsonServers`](</docs/en/settings#available-settings>), which blocks it in every mode, or exclude project settings entirely with [`--setting-sources`](</docs/en/cli-reference>) or the SDK’s `settingSources` option. - -### - -​ - -User scope - -User-scoped servers are stored in `~/.claude.json` and provide cross-project accessibility, making them available across all projects on your machine while remaining private to your user account. This scope works well for personal utility servers, development tools, or services you frequently use across different projects. - - # Add a user server - claude mcp add --transport http hubspot --scope user https://mcp.hubspot.com/anthropic - -### - -​ - -Scope hierarchy and precedence - -When the same server is defined in more than one place, Claude Code connects to it once, using the definition from the highest-precedence source. The entire server entry from that source is used; fields are not merged across scopes. - - 1. Local scope - 2. Project scope - 3. User scope - 4. [Plugin-provided servers](</docs/en/plugins>) - 5. claude.ai connectors - -The three scopes match duplicates by name. Plugins and connectors match by endpoint, so one that points at the same URL or command as a server above is treated as a duplicate. If you open a local session in the [Desktop app’s Code tab](</docs/en/desktop#mcp-servers-from-the-claude-desktop-chat-app>) with the same stdio server name at the top level of `~/.claude.json` (user scope) and in `.mcp.json`, the Code tab uses the `~/.claude.json` definition. - -### - -​ - -Environment variable expansion in `.mcp.json` - -Claude Code supports environment variable expansion in `.mcp.json` files, allowing teams to share configurations while maintaining flexibility for machine-specific paths and sensitive values like API keys. **Supported syntax:** - - * `${VAR}`: expands to the value of environment variable `VAR` - * `${VAR:-default}`: expands to `VAR` if set, otherwise uses `default` - -**Expansion locations:** Environment variables can be expanded in: - - * `command`: the server executable path - * `args`: command-line arguments - * `env`: environment variables passed to the server - * `url`: for HTTP server types - * `headers`: for HTTP server authentication - -**Example with variable expansion:** + "filesystem": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"] + } + } + } + +### + +​ + +HTTP/SSE servers + +Use HTTP or SSE for cloud-hosted MCP servers and remote APIs: + + * In code + + * .mcp.json + +TypeScript + +Python + + const _ = { + options: { + mcpServers: { + "remote-api": { + type: "sse", + url: "https://api.example.com/mcp/sse", + headers: { + Authorization: `Bearer ${process.env.API_TOKEN}` + } + } + }, + allowedTools: ["mcp__remote-api__*"] + } + }; + + options = ClaudeAgentOptions( + mcp_servers={ + "remote-api": { + "type": "sse", + "url": "https://api.example.com/mcp/sse", + "headers": {"Authorization": f"Bearer {os.environ['API_TOKEN']}"}, + } + }, + allowed_tools=["mcp__remote-api__*"], + ) + + { + "mcpServers": { + "remote-api": { + "type": "sse", + "url": "https://api.example.com/mcp/sse", + "headers": { + "Authorization": "Bearer ${API_TOKEN}" + } + } + } + } + +For the streamable HTTP transport, use `"type": "http"` instead. In `.mcp.json` and other JSON config files, `"streamable-http"` is accepted as an alias for `"http"`. The programmatic `mcpServers` option accepts only `"http"`. + +### + +​ + +SDK MCP servers + +Define custom tools directly in your application code instead of running a separate server process. See the [custom tools guide](</docs/en/agent-sdk/custom-tools>) for implementation details. An SDK MCP server registered by an [`initialize` control request](</docs/en/agent-sdk/typescript#sdkcontrolinitializeresponse>) begins connecting as soon as Claude Code processes the request. + +## + +​ + +MCP tool search + +When you have many MCP tools configured, tool definitions can consume a significant portion of your context window. Tool search solves this by withholding tool definitions from context and loading only the ones Claude needs for each turn. Tool search is enabled by default. See [Tool search](</docs/en/agent-sdk/tool-search>) for configuration options, best practices, and using tool search with custom SDK tools. + +## + +​ + +Authentication + +Most MCP servers require authentication to access external services. Pass credentials through environment variables in the server configuration. + +### + +​ + +Pass credentials via environment variables + +Use the `env` field to pass API keys, tokens, and other credentials to the MCP server: + + * In code + + * .mcp.json + +TypeScript + +Python + + const _ = { + options: { + mcpServers: { + "api-server": { + command: "npx", + args: ["-y", "@your-org/api-mcp-server"], + env: { + API_KEY: process.env.API_KEY + } + } + }, + allowedTools: ["mcp__api-server__*"] + } + }; + + options = ClaudeAgentOptions( + mcp_servers={ + "api-server": { + "command": "npx", + "args": ["-y", "@your-org/api-mcp-server"], + "env": {"API_KEY": os.environ["API_KEY"]}, + } + }, + allowed_tools=["mcp__api-server__*"], + ) { "mcpServers": { "api-server": { - "type": "http", - "url": "${API_BASE_URL:-https://api.example.com}/mcp", - "headers": { - "Authorization": "Bearer ${API_KEY}" - } - } - } - } - -If a referenced environment variable isn’t set and has no default value, the config still loads: Claude Code reports a missing-variable warning for that server in `claude mcp list` output and uses the unexpanded `${VAR}` text as-is. Set the variable or add a `:-default` fallback so the server starts with the value you intend. - -## - -​ - -Practical examples - -### - -​ - -Example: Monitor errors with Sentry - -Sentry’s remote MCP server gives Claude access to the errors your applications report to Sentry. It authenticates through OAuth rather than an API key, so you don’t pass a credential when you add it. If you already added the `sentry` server in the [MCP quickstart](</docs/en/mcp-quickstart>), skip this command: running `claude mcp add` again with the same server name at the same scope fails with `MCP server sentry already exists in local config`. - - claude mcp add --transport http sentry https://mcp.sentry.dev/mcp - -Authenticate with your Sentry account: - - /mcp - -Follow the sign-in steps in your browser. Once you’re signed in, the `sentry` server shows `connected` in the `/mcp` menu. Then debug production issues: - - What are the most common errors in the last 24 hours? - - Show me the stack trace for error ID abc123 - - Which deployment introduced these new errors? - -### - -​ - -Example: Connect to GitHub for code reviews - -GitHub’s remote MCP server authenticates with a GitHub personal access token passed as a header. To get one, open your [GitHub token settings](<https://github.com/settings/personal-access-tokens>), generate a new fine-grained token with access to the repositories you want Claude to work with, then add the server: - - claude mcp add --transport http github https://api.githubcopilot.com/mcp/ \ - --header "Authorization: Bearer YOUR_GITHUB_PAT" - -Replace `YOUR_GITHUB_PAT` with your personal access token. The `claude mcp add` command saves the configuration without validating credentials, so a placeholder value is accepted here but the server fails to connect later. To verify the connection, run `/mcp` and check that the server shows `connected`. A server with bad credentials shows `failed`, and the failure detail includes the HTTP status the server returned, such as a 401. Then work with GitHub: - - Review PR #456 and suggest improvements - - Create a new issue for the bug we just found - - Show me all open PRs assigned to me - -### - -​ - -Example: Query your PostgreSQL database - -[DBHub](<https://github.com/bytebase/dbhub>), the `@bytebase/dbhub` package, is an MCP server that connects Claude to a relational database through the connection string you pass in `--dsn`. Use a read-only database user in the connection string so the queries Claude runs can’t modify data: - - claude mcp add --transport stdio db -- npx -y @bytebase/dbhub \ - --dsn "postgresql://readonly:pass@prod.db.com:5432/analytics" - -To confirm the server starts, run `/mcp` and check that `db` shows `connected`. Then query your database naturally: - - What's our total revenue this month? - - Show me the schema for the orders table - - Find customers who haven't made a purchase in 90 days - -## - -​ - -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`. What Claude Code shows depends on the server: - - * For a server you haven’t signed in to, either status code flags it in `/mcp` so you can complete the OAuth flow. - * For a claude.ai connector, a `401` caused by claude.ai rejecting your session token doesn’t flag the connector, because re-authorizing the connector can’t fix your login. Claude Code shows the [session-token-rejected state](</docs/en/errors#claude-ai-rejected-the-session-token>) instead. - -When a request to an OAuth server you already signed in to returns `401 Unauthorized`, Claude Code refreshes the stored token, reconnects, and retries the request once. It flags the server in `/mcp` only if that retry also fails. Before v2.1.206, a token refresh that failed for a transient reason, such as a network error, flagged an OAuth server as needing authentication for the rest of the session even though its refresh token was still valid. 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. 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. The notice requires Claude Code v2.1.193 or later. It counts only servers you can sign in to from Claude Code. Before v2.1.218, it also counted claude.ai connectors that weren’t connected in claude.ai, which you can connect only from claude.ai settings. 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 - -Add the server that requires authentication - -If you already added this server in the Sentry example or the [MCP quickstart](</docs/en/mcp-quickstart>), skip this step: running `claude mcp add` again with the same server name at the same scope fails with `MCP server sentry already exists in local config`. Otherwise, run: - - claude mcp add --transport http sentry https://mcp.sentry.dev/mcp - -2 - -Use the /mcp command within Claude Code - -In Claude Code, use the command: - - /mcp - -Then follow the steps in your browser to log in. - -Tips: - - * Authentication tokens are stored securely and refreshed automatically - * Use “Clear authentication” in the `/mcp` menu to revoke access - * If your browser doesn’t open automatically, copy the provided URL and open it manually - * If the browser redirect fails with a connection error after authenticating, paste the full callback URL from your browser’s address bar into the URL prompt that appears in Claude Code - * OAuth authentication works with HTTP servers - -### - -​ - -Authenticate from the command line - -From v2.1.186, `claude mcp login <name>` runs a configured server’s OAuth flow directly from your shell, so you don’t need to open the `/mcp` panel inside a session. - - claude mcp login sentry - -To clear stored credentials later, run `claude mcp logout <name>`. As of v2.1.191, the command detects when no local browser is available, such as during an SSH session or on Linux without a display server, and prints the authorization URL instead of trying to open a browser. Open the URL on your local machine, then paste the full redirect URL from your browser’s address bar back at the prompt. The command needs an interactive terminal for the paste step, so connect with `ssh -t`. Pass `--no-browser` to force the URL prompt even when a local browser is detected. - - claude mcp login sentry --no-browser - -### - -​ - -Use a fixed OAuth callback port - -Some MCP servers require a specific redirect URI registered in advance. By default, Claude Code picks a random available port for the OAuth callback. Use `--callback-port` to fix the port so it matches a pre-registered redirect URI of the form `http://localhost:PORT/callback`. You can use `--callback-port` on its own (with dynamic client registration) or together with `--client-id` (with pre-configured credentials). - - # Fixed callback port with dynamic client registration - claude mcp add --transport http \ - --callback-port 8080 \ - my-server https://mcp.example.com/mcp - -### - -​ - -Use pre-configured OAuth credentials - -Some MCP servers don’t support automatic OAuth setup via Dynamic Client Registration. If you see an error like “Incompatible auth server: does not support dynamic client registration,” the server requires pre-configured credentials. Claude Code also supports servers that use a Client ID Metadata Document (CIMD) instead of Dynamic Client Registration, and discovers these automatically. If automatic discovery fails, register an OAuth app through the server’s developer portal first, then provide the credentials when adding the server. - -1 - -Register an OAuth app with the server - -Create an app through the server’s developer portal and note your client ID and client secret.Many servers also require a redirect URI. If so, choose a port and register a redirect URI in the format `http://localhost:PORT/callback`. Use that same port with `--callback-port` in the next step. - -2 - -Add the server with your credentials - -Choose one of the following methods. The port used for `--callback-port` can be any available port. It needs to match the redirect URI you registered in the previous step. - - * claude mcp add - - * claude mcp add-json - - * claude mcp add-json (callback port only) - - * CI / env var - -Use `--client-id` to pass your app’s client ID. The `--client-secret` flag prompts for the secret with masked input: - - claude mcp add --transport http \ - --client-id your-client-id --client-secret --callback-port 8080 \ - my-server https://mcp.example.com/mcp - -Include the `oauth` object in the JSON config and pass `--client-secret` as a separate flag: - - claude mcp add-json my-server \ - '{"type":"http","url":"https://mcp.example.com/mcp","oauth":{"clientId":"your-client-id","callbackPort":8080}}' \ - --client-secret - -Use `--callback-port` without a client ID to fix the port while using dynamic client registration: - - claude mcp add-json my-server \ - '{"type":"http","url":"https://mcp.example.com/mcp","oauth":{"callbackPort":8080}}' - -Set the secret via environment variable to skip the interactive prompt: - - MCP_CLIENT_SECRET=your-secret claude mcp add --transport http \ - --client-id your-client-id --client-secret --callback-port 8080 \ - my-server https://mcp.example.com/mcp - -3 - -Authenticate in Claude Code - -Run `/mcp` in Claude Code and follow the browser login flow. - -Tips: - - * The client secret is stored securely in your system keychain (macOS) or a credentials file, not in your config - * If the server uses a public OAuth client with no secret, use only `--client-id` without `--client-secret` - * `--callback-port` can be used with or without `--client-id` - * These flags only apply to HTTP and SSE transports. They have no effect on stdio servers - * Use `claude mcp get <name>` to verify that OAuth credentials are configured for a server - -### - -​ - -Override OAuth metadata discovery - -Point Claude Code at a specific OAuth authorization server metadata URL to bypass the default discovery chain. Set `authServerMetadataUrl` when the MCP server’s standard endpoints error, or when you want to route discovery through an internal proxy. By default, Claude Code first checks RFC 9728 Protected Resource Metadata at `/.well-known/oauth-protected-resource`, then falls back to RFC 8414 authorization server metadata at `/.well-known/oauth-authorization-server`. Set `authServerMetadataUrl` in the `oauth` object of your server’s config in `.mcp.json`: + "command": "npx", + "args": ["-y", "@your-org/api-mcp-server"], + "env": { + "API_KEY": "${API_KEY}" + } + } + } + } + +The `${API_KEY}` syntax expands environment variables at runtime. + +### + +​ + +HTTP headers for remote servers + +For HTTP and SSE servers, pass authentication headers directly in the server configuration: + + * In code + + * .mcp.json + +TypeScript + +Python + + const _ = { + options: { + mcpServers: { + "secure-api": { + type: "http", + url: "https://api.example.com/mcp", + headers: { + Authorization: `Bearer ${process.env.API_TOKEN}` + } + } + }, + allowedTools: ["mcp__secure-api__*"] + } + }; + + options = ClaudeAgentOptions( + mcp_servers={ + "secure-api": { + "type": "http", + "url": "https://api.example.com/mcp", + "headers": {"Authorization": f"Bearer {os.environ['API_TOKEN']}"}, + } + }, + allowed_tools=["mcp__secure-api__*"], + ) { "mcpServers": { - "my-server": { + "secure-api": { "type": "http", - "url": "https://mcp.example.com/mcp", - "oauth": { - "authServerMetadataUrl": "https://auth.example.com/.well-known/openid-configuration" - } - } - } - } - -The URL must use `https://`. The metadata URL’s `scopes_supported` overrides the scopes the upstream server advertises. - -### - -​ - -Restrict OAuth scopes - -Set `oauth.scopes` to pin the scopes Claude Code requests during the authorization flow. This is the supported way to restrict an MCP server to a security-team-approved subset when the upstream authorization server advertises more scopes than you want to grant. The value is a single space-separated string, matching the `scope` parameter format in RFC 6749 §3.3. - - { - "mcpServers": { - "slack": { - "type": "http", - "url": "https://mcp.slack.com/mcp", - "oauth": { - "scopes": "channels:read chat:write search:read" - } - } - } - } - -`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. - -### - -​ - -Use dynamic headers for custom authentication - -If your MCP server uses an authentication scheme other than OAuth, such as Kerberos, short-lived tokens, or an internal SSO, use `headersHelper` to generate request headers at connection time. Claude Code runs the command and merges its output into the connection headers. - - { - "mcpServers": { - "internal-api": { - "type": "http", - "url": "https://mcp.internal.example.com", - "headersHelper": "/opt/bin/get-mcp-auth-headers.sh" - } - } - } - -The command can also be inline: - - { - "mcpServers": { - "internal-api": { - "type": "http", - "url": "https://mcp.internal.example.com", - "headersHelper": "echo '{\"Authorization\": \"Bearer '\"$(get-token)\"'\"}'" - } - } - } - -**Requirements:** - - * The command must write a JSON object of string key-value pairs to stdout - * The command runs in a shell with a 10-second timeout, from the session’s current working directory. Use an absolute path or a command on `PATH` for the script - * 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. 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 -`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. A plugin-provided `headersHelper` can’t reference the plugin’s [`${user_config.*}`](</docs/en/plugins-reference#user-configuration>) values, because the command runs through a shell. Claude Code reports the server as misconfigured with an [error](</docs/en/errors#plugin-command-references-user-config>) and doesn’t substitute the value. Put `${user_config.KEY}` in the server’s `headers` field instead, which isn’t shell-parsed, or have the helper script read the value from its own environment or a config file. Before v2.1.207, `headersHelper` substituted `${user_config.*}` values. - -`headersHelper` executes arbitrary shell commands. When defined at project or local scope, it only runs after you accept the workspace trust dialog. - -## - -​ - -Add MCP servers from JSON configuration - -If you have a JSON configuration for an MCP server, you can add it directly: - -1 - -Add an MCP server from JSON - - # Basic syntax - claude mcp add-json <name> '<json>' - - # Example: Adding an HTTP server with JSON configuration - claude mcp add-json weather-api '{"type":"http","url":"https://api.weather.com/mcp","headers":{"Authorization":"Bearer token"}}' - - # Example: Adding a stdio server with JSON configuration - claude mcp add-json local-weather '{"type":"stdio","command":"/path/to/weather-cli","args":["--api-key","abc123"],"env":{"CACHE_DIR":"/tmp"}}' - - # Example: Adding an HTTP server with pre-configured OAuth credentials - claude mcp add-json my-server '{"type":"http","url":"https://mcp.example.com/mcp","oauth":{"clientId":"your-client-id","callbackPort":8080}}' --client-secret - -2 - -Verify the server was added - - claude mcp get weather-api - -Tips: - - * Make sure the JSON is properly escaped in your shell - * The JSON must conform to the MCP server configuration schema - * You can use `--scope user` to add the server to your user configuration instead of the project-specific one - -## - -​ - -Import MCP servers from Claude Desktop - -If you’ve already configured MCP servers in Claude Desktop, you can import them: - -1 - -Import servers from Claude Desktop - - # Basic syntax - claude mcp add-from-claude-desktop - -2 - -Select which servers to import - -After running the command, you’ll see an interactive dialog that allows you to select which servers you want to import. - -3 - -Verify the servers were imported - - claude mcp list - -Server names added through `claude mcp` commands can contain only letters, numbers, hyphens, and underscores. Claude Desktop doesn’t apply that restriction, so a Claude Desktop server whose name contains any other character, such as a space, can’t be imported. The import reports each name it rejects and still imports the other servers you selected. Before v2.1.205, the first invalid name stopped the import and none of the selected servers were added. - -Tips: - - * This feature only works on macOS and Windows Subsystem for Linux (WSL) - * It reads the Claude Desktop configuration file from its standard location on those platforms - * Use the `--scope user` flag to add servers to your user configuration - * Imported servers keep the same names as in Claude Desktop when the name contains only letters, numbers, hyphens, and underscores. Claude Code reports a server whose name contains any other character and skips it - * If servers with the same names already exist, they get a numerical suffix (for example, `server_1`) - -## - -​ - -Use MCP servers from claude.ai - -If you’ve logged into Claude Code with a [claude.ai](<https://claude.ai>) account, MCP servers you’ve added in claude.ai, known as [connectors](<https://claude.com/docs/connectors>), are automatically available in Claude Code: - -1 - -Configure MCP servers in claude.ai - -Add servers at [claude.ai/customize/connectors](<https://claude.ai/customize/connectors>). On Team and Enterprise plans, only admins can add servers. - -2 - -Authenticate the MCP server - -Complete any required authentication steps in claude.ai. - -3 - -View and manage servers in Claude Code - -In Claude Code, use the command: - - /mcp - -Servers from claude.ai appear in the list with indicators showing they come from claude.ai. - -From v2.1.161, connectors you have never signed in to are collapsed behind a `Show unused connectors` row at the end of the claude.ai section, so an organization-provisioned list doesn’t fill the panel. Select the row to expand them. A connector you signed in to before stays visible even when it currently needs re-authentication. Connectors from claude.ai are fetched only when your active [authentication method](</docs/en/authentication#authentication-precedence>) is a claude.ai subscription login. They aren’t loaded, even if you previously ran `/login`, when: - - * `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or `apiKeyHelper` is active - * A third-party provider such as Amazon Bedrock or Google Cloud’s Agent Platform is active - * `CLAUDE_CODE_OAUTH_TOKEN` holds a token from [`claude setup-token`](</docs/en/authentication#generate-a-long-lived-token>), which can only make model requests - -If `/mcp` doesn’t list a connector you added, run `/status` to confirm which authentication method is active, unset that environment variable or remove the `apiKeyHelper` setting, then run `/login` to select your claude.ai account. If `/mcp` shows a connector as `connected · session token rejected`, or its detail view shows [`claude.ai rejected the session token`](</docs/en/errors#claude-ai-rejected-the-session-token>), claude.ai rejected the token from your Claude Code login, usually because the login expired and couldn’t be refreshed. Authorizing the connector again doesn’t clear this state, because the connector’s own authorization in claude.ai isn’t what was rejected. To clear it: - - 1. Run `/login` to sign in again. - 2. Reconnect the connector from `/mcp`. - -Before v2.1.222, Claude Code marked connectors as needing authentication instead, and authorizing them didn’t resolve it. A server you’ve added in Claude Code takes precedence over a claude.ai connector that points at the same URL. When this happens, `/mcp` lists the connector as hidden and shows how to remove the duplicate if you’d rather use the connector. Some Anthropic-hosted connectors, such as Microsoft 365, Gmail, and Google Calendar, don’t support local OAuth from Claude Code because the upstream identity provider only accepts the redirect URL that claude.ai registered. From v2.1.162, authenticating one of these hosts in `/mcp` shows a message directing you to connect it at Settings → Connectors on claude.ai instead. Once connected there, the connector appears in Claude Code automatically. - -### - -​ - -Organization controls on connector tools - -Your organization can set per-tool controls on [claude.ai connectors](<https://claude.com/docs/connectors>). Claude Code reads these settings at startup and enforces them locally. Run `/mcp` to see which setting applies to each tool on a connector. - - * **Tool set to`ask`**: Claude Code prompts on every call with the reason `Your organization requires approval for this tool`. The prompt appears even in `acceptEdits`, `auto`, and `bypassPermissions` [permission modes](</docs/en/permissions#permission-modes>), and never offers an option to remember your choice. [Allow rules](</docs/en/permissions>) that match the tool don’t skip the prompt either. In `dontAsk` mode, which never prompts, Claude Code denies the call instead. - * **Tool set to`blocked`**: Claude Code filters the tool out before Claude sees it, so it never appears in the tool list. - -### - -​ - -Disable claude.ai connectors - -To disable claude.ai MCP servers in Claude Code, set [`disableClaudeAiConnectors`](</docs/en/settings#available-settings>) to `true` in any settings scope: - - { - "disableClaudeAiConnectors": true - } - -This setting uses any-source-true semantics: `true` in any settings source takes precedence. A checked-in project `.claude/settings.json` can opt a repository out of cloud connectors, but a project-level `false` can’t re-enable connectors that a user- or policy-level `true` has disabled. Servers passed explicitly via `--mcp-config` are unaffected. You can also set the `ENABLE_CLAUDEAI_MCP_SERVERS` environment variable to `false`, which has the same effect for the current shell session: - - ENABLE_CLAUDEAI_MCP_SERVERS=false claude - -To block individual claude.ai connectors instead of all of them, add them to [`deniedMcpServers`](</docs/en/managed-mcp>) by name or by URL pattern. For example, a `serverName` entry of `"claude.ai Slack"` blocks the Slack connector. To toggle a connector on or off for the current project only, use the `/mcp` panel. - -These client-side settings govern local Claude Code sessions. In [Claude Code on the web](</docs/en/claude-code-on-the-web>) sessions, claude.ai connectors are provisioned by the remote host and arrive as explicit `--mcp-config` entries, so `disableClaudeAiConnectors` doesn’t apply there. Connector URLs are also rewritten through the session proxy, so a `deniedMcpServers` `serverUrl` pattern targeting the vendor URL won’t match. Manage which connectors a cloud session can use from your claude.ai organization settings. - -## - -​ - -Use Claude Code as an MCP server - -You can use Claude Code itself as an MCP server that other applications can connect to: - - # Start Claude as a stdio MCP server - claude mcp serve - -The command prints nothing when it starts. A stdio MCP server communicates over stdin and stdout, so a silent, blocked terminal means the server is running and waiting for a client to connect. You can use this in Claude Desktop by adding this configuration to claude_desktop_config.json: - - { - "mcpServers": { - "claude-code": { - "type": "stdio", - "command": "claude", - "args": ["mcp", "serve"], - "env": {} - } - } - } - -**Configuring the executable path** : the `command` field must reference the Claude Code executable. If the `claude` command is not in your system’s PATH, you’ll need to specify the full path to the executable.To find the full path: - - which claude - -Then use the full path in your configuration: - - { - "mcpServers": { - "claude-code": { - "type": "stdio", - "command": "/full/path/to/claude", - "args": ["mcp", "serve"], - "env": {} - } - } - } - -Without the correct executable path, you’ll encounter errors like `spawn claude ENOENT`. - -Tips: - - * In Claude Desktop, try asking Claude to read files in a directory, make edits, and more. - * This MCP server only exposes Claude Code’s tools to your MCP client, so your own client is responsible for implementing user confirmation for individual tool calls. - -## - -​ - -MCP output limits and warnings - -When MCP tools produce large outputs, Claude Code helps manage the token usage to prevent overwhelming your conversation context: - - * **Output warning threshold** : Claude Code displays a warning when any MCP tool output exceeds 10,000 tokens - * **Configurable limit** : you can adjust the maximum allowed MCP output tokens using the `MAX_MCP_OUTPUT_TOKENS` environment variable - * **Default limit** : the default maximum is 25,000 tokens - * **Scope** : the environment variable applies to tools that don’t declare their own limit. Tools that set `anthropic/maxResultSizeChars` use that value instead for text content, regardless of what `MAX_MCP_OUTPUT_TOKENS` is set to. Tools that return image data are still subject to `MAX_MCP_OUTPUT_TOKENS` - -To increase the limit for tools that produce large outputs: - - export MAX_MCP_OUTPUT_TOKENS=50000 - claude - -### - -​ - -Raise the limit for a specific tool - -If you’re building an MCP server, you can allow individual tools to return results larger than the default persist-to-disk threshold by setting `_meta["anthropic/maxResultSizeChars"]` in the tool’s `tools/list` response entry. Claude Code raises that tool’s threshold to the annotated value, up to a hard ceiling of 500,000 characters. This is useful for tools that return inherently large but necessary outputs, such as database schemas or full file trees. Without the annotation, results that exceed the default threshold are persisted to disk and replaced with a file reference in the conversation. - - { - "name": "get_schema", - "description": "Returns the full database schema", - "_meta": { - "anthropic/maxResultSizeChars": 200000 - } - } - -The annotation applies independently of `MAX_MCP_OUTPUT_TOKENS` for text content, so users don’t need to raise the environment variable for tools that declare it. Tools that return image data are still subject to the token limit. - -If you frequently encounter output warnings with specific MCP servers you don’t control, consider increasing the `MAX_MCP_OUTPUT_TOKENS` limit. You can also ask the server author to add the `anthropic/maxResultSizeChars` annotation or to paginate their responses. The annotation has no effect on tools that return image content; for those, raising `MAX_MCP_OUTPUT_TOKENS` is the only option. - -## - -​ - -Tool input schemas with a root-level combinator - -Some MCP servers declare a tool’s input schema as a JSON Schema union, with `anyOf`, `oneOf`, or `allOf` at the top level of the schema. The Claude API doesn’t accept those keywords at the schema root. It does accept combinators nested inside `properties`, which Claude Code sends unchanged. As of Claude Code v2.1.195, tools with a root-level combinator stay available. Before sending the tool to the API, Claude Code flattens the schema into a single object and prepends a sentence to the tool’s description that tells Claude which parameter groups belong together: - - * `allOf`: properties from every branch are merged, and each branch’s `required` list still applies - * `anyOf` and `oneOf`: properties from every branch are merged, and each branch’s `required` list is described in the tool description instead of enforced by the schema - -Your server receives whichever arguments Claude chose, so keep validating the combination server-side. When Claude Code can’t produce a schema the API accepts, or on a deployment that doesn’t receive the remote configuration that enables the rewrite, such as an offline machine, it skips that one tool, records the reason in the server’s log, and leaves the server’s other tools available. Versions earlier than v2.1.195 skip every tool whose input schema has a root-level `anyOf`, `oneOf`, or `allOf`. - -## - -​ - -Require approval for a specific tool - -If you’re building an MCP server, you can mark a tool as requiring explicit approval on every call by setting `_meta["anthropic/requiresUserInteraction"]` to `true` in the tool’s `tools/list` response entry. The value must be the JSON boolean `true`; any other value is ignored. Claude Code shows that tool’s permission prompt on every call, even in `acceptEdits`, `auto`, and `bypassPermissions` [permission modes](</docs/en/permissions#permission-modes>), and doesn’t offer a “don’t ask again” option for it. [Allow rules](</docs/en/permissions#permission-rule-syntax>) that match the tool don’t skip the prompt either. In `dontAsk` mode, which never prompts, Claude Code denies the call instead. The prompt has to reach a person. In non-interactive mode with [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>), an `allow` result from the prompt tool for a flagged tool is converted to a deny with the message `MCP tool requires user interaction; not supported via --permission-prompt-tool`. The Agent SDK’s [`canUseTool` callback](</docs/en/agent-sdk/permissions>) does receive these calls and can approve them, because your SDK application is expected to show them to a user. Use this for tools whose permission prompt is itself the point, such as a consent or access-grant step where auto-approval would mean no human ever agreed. Other tools from the same server keep their normal permission behavior. The following `tools/list` entry marks one tool as always requiring approval. - - { - "name": "grant_access", - "description": "Requests access to a protected resource", - "_meta": { - "anthropic/requiresUserInteraction": true - } - } - -The `anthropic/requiresUserInteraction` annotation requires Claude Code v2.1.199 or later. Earlier versions ignore it and apply the standard permission flow. Some surfaces, such as [Remote Control](</docs/en/remote-control>) and applications built on the [Agent SDK](</docs/en/agent-sdk/overview>), normally let you approve tool calls with one tap. For a tool marked with this annotation, Claude Code withholds the one-tap action and shows the tool’s full permission prompt instead, so approval still comes from a person answering the prompt rather than a tap. Claude Code withholds one-tap approval the same way for any permission request that only the terminal dialog can render in full, such as one that carries a safety warning or an always-allow option the remote surface can’t show. You answer that request in the terminal dialog rather than from Remote Control. Requires Claude Code v2.1.214 or later. - -## - -​ - -Respond to MCP elicitation requests - -MCP servers can request structured input from you mid-task using elicitation. When a server needs information it can’t get on its own, Claude Code displays an interactive dialog and passes your response back to the server. No configuration is required on your side: elicitation dialogs appear automatically when a server requests them. Servers can request input in two ways: - - * **Form mode** : Claude Code shows a dialog with form fields defined by the server (for example, a username and password prompt). Fill in the fields and submit. - * **URL mode** : Claude Code opens a browser URL for authentication or approval. Complete the flow in the browser, then confirm in the CLI. - -To auto-respond to elicitation requests without showing a dialog, use the [`Elicitation` hook](</docs/en/hooks#elicitation>). If you’re building an MCP server that uses elicitation, see the [MCP elicitation specification](<https://modelcontextprotocol.io/docs/learn/client-concepts#elicitation>) for protocol details and schema examples. - -## - -​ - -Use MCP resources - -MCP servers can expose resources that you can reference using @ mentions, similar to how you reference files. - -### - -​ - -Reference MCP resources - -1 - -List available resources - -Type `@` in your prompt to see available resources from all connected MCP servers. Resources appear alongside files in the autocomplete menu. - -2 - -Reference a specific resource - -Use the format `@server:protocol://resource/path` to reference a resource: - - Can you analyze @github:issue://123 and suggest a fix? - - Please review the API documentation at @docs:file://api/authentication - -3 - -Multiple resource references - -You can reference multiple resources in a single prompt: - - Compare @postgres:schema://users with @docs:file://database/user-model - -Tips: - - * Resources are automatically fetched and included as attachments when referenced - * Resource paths are fuzzy-searchable in the @ mention autocomplete - * Claude Code automatically provides tools to list and read MCP resources when servers support them - * Resources can contain any type of content that the MCP server provides (text, JSON, structured data, etc.) - -## - -​ - -Scale with MCP tool search - -Tool search keeps MCP context usage low by deferring tool definitions until Claude needs them. Only tool names and server instructions load at session start, so adding more MCP servers has minimal impact on your context window. Claude Code doesn’t impose a fixed per-server tool cap; the practical limit is your context window budget. - -Tool search isn’t supported on Microsoft Foundry [deployments hosted on Azure](<https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry#hosting-options>), which reject it server-side: Claude Code detects the rejection and loads MCP tools upfront for that deployment instead. `ENABLE_TOOL_SEARCH` can’t override this, since the rejection comes from the deployment itself. - -### - -​ - -How it works - -Tool search is enabled by default. MCP tools are deferred rather than loaded into context upfront, and Claude uses a search tool to discover relevant ones when a task needs them. Only the tools Claude actually uses enter context. From your perspective, MCP tools work exactly as before. If you prefer threshold-based loading, set `ENABLE_TOOL_SEARCH=auto` to load schemas upfront when they fit within 10% of the context window and defer only the overflow. See Configure tool search for all options. - -### - -​ - -For MCP server authors - -If you’re building an MCP server, the server instructions field becomes more useful with tool search enabled. Server instructions help Claude understand when to search for your tools, similar to how [skills](</docs/en/skills>) work. Add clear, descriptive server instructions that explain: - - * What category of tasks your tools handle - * When Claude should search for your tools - * Key capabilities your server provides - -Claude Code truncates tool descriptions and server instructions at 2KB each. Keep them concise to avoid truncation, and put critical details near the start. - -### - -​ - -Configure tool search - -Tool search is enabled by default: MCP tools are deferred and discovered on demand. Claude Code disables it when `ANTHROPIC_BASE_URL` points to a non-first-party host, since most proxies don’t forward `tool_reference` blocks. Set `ENABLE_TOOL_SEARCH` explicitly to override that fallback. Setting [`CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS`](</docs/en/env-vars>) keeps tool search off, and `ENABLE_TOOL_SEARCH` can’t override it. The variable strips the beta header that `defer_loading` tool definitions and `tool_reference` content blocks require. Tool search requires a model that supports `tool_reference` blocks: Claude Sonnet 4.5, Claude Haiku 4.5, Claude Opus 4.5, and later models. See [model compatibility in the API docs](<https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool#model-compatibility>) for the current list. On Google Cloud’s Agent Platform, Claude Code decides by model generation: - - * **Claude Opus 4.5, Sonnet 4.5, Haiku 4.5, and later** : tool search is on by default, the same as on the Anthropic API. - * **Earlier Agent Platform models** : Claude Code loads all MCP tools upfront, because their serving stacks reject the required beta header. `ENABLE_TOOL_SEARCH=true` doesn’t override this. - -Before v2.1.221, Claude Code disabled tool search for all models on Google Cloud’s Agent Platform unless you set `ENABLE_TOOL_SEARCH=true`. Control tool search behavior with the `ENABLE_TOOL_SEARCH` environment variable: - -Value| Behavior ----|--- -(unset)| All MCP tools deferred and loaded on demand. Falls back to loading upfront on Google Cloud’s Agent Platform models earlier than the Claude 4.5 generation, when `ANTHROPIC_BASE_URL` is a non-first-party host, or on a Microsoft Foundry deployment hosted on Azure -`true`| All MCP tools deferred, except on a Microsoft Foundry deployment hosted on Azure, where the server-side rejection still forces upfront loading, and on Google Cloud’s Agent Platform models earlier than the Claude 4.5 generation, where Claude Code keeps loading tools upfront. Claude Code sends the beta header through proxies, and requests fail on proxies that don’t support `tool_reference` blocks -`auto`| Threshold mode: tools load upfront if they fit within 10% of the context window, deferred otherwise -`auto:N`| Threshold mode with a custom percentage, where `N` is 0-100. For example, `auto:5` for 5% -`false`| All MCP tools loaded upfront, no deferral - - # Use a custom 5% threshold - ENABLE_TOOL_SEARCH=auto:5 claude - - # Disable tool search entirely - ENABLE_TOOL_SEARCH=false claude - -Or set the value in your [settings.json `env` field](</docs/en/settings#available-settings>). You can also disable the `ToolSearch` tool specifically: - - { - "permissions": { - "deny": ["ToolSearch"] - } - } - -### - -​ - -Exempt a server from deferral - -If a server’s tools should always be visible to Claude without a search step, set `alwaysLoad` to `true` in that server’s configuration. Every tool from that server then loads into context at session start regardless of the `ENABLE_TOOL_SEARCH` setting. Use this for a small number of tools that Claude needs on every turn, since each upfront tool consumes context that would otherwise be available for your conversation. The following `.mcp.json` entry exempts one HTTP server while leaving other servers deferred: - - { - "mcpServers": { - "core-tools": { - "type": "http", - "url": "https://mcp.example.com/mcp", - "alwaysLoad": true - } - } - } - -The `alwaysLoad` field is available on all server types. An MCP server can also mark individual tools as always-loaded by including `"anthropic/alwaysLoad": true` in the tool’s `_meta` object, which has the same effect for that tool only. Setting `alwaysLoad: true` also makes startup wait for the server’s tools, capped at the standard 5-second connect timeout, since they must be present when the first prompt is built. A remote server with a valid `cached` entry supplies its tools from the cache without connecting, so it doesn’t hold startup. Other servers connect in the background by default; set [`MCP_CONNECTION_NONBLOCKING=0`](</docs/en/env-vars>) to make startup wait for them too. - -## - -​ - -Use MCP prompts as commands - -MCP servers can expose prompts that become available as commands in Claude Code. - -### - -​ - -Execute MCP prompts - -1 - -Discover available prompts - -Type `/` to see all available commands, including those from MCP servers. MCP prompts appear with the format `/mcp__servername__promptname`. - -2 - -Execute a prompt without arguments - - /mcp__github__list_prs - -3 - -Execute a prompt with arguments - -Many prompts accept arguments. Pass them space-separated after the command: - - /mcp__github__pr_review 456 - - /mcp__jira__create_issue "Bug in login flow" high - -Tips: - - * MCP prompts are dynamically discovered from connected servers - * Arguments are parsed based on the prompt’s defined parameters - * Prompt results are injected directly into the conversation - * Server and prompt names are normalized, with spaces converted to underscores - -## - -​ - -Managed MCP configuration - -For organizations that need centralized control over which MCP servers users can connect to, see [Managed MCP configuration](</docs/en/managed-mcp>). It covers deploying a fixed server set with `managed-mcp.json`, restricting servers with `allowedMcpServers` and `deniedMcpServers`, and what users see when a server is blocked. + "url": "https://api.example.com/mcp", + "headers": { + "Authorization": "Bearer ${API_TOKEN}" + } + } + } + } + +The `${API_TOKEN}` syntax expands environment variables at runtime. + +For a complete working example of a remote server authenticated with headers, see List issues from a repository. + +### + +​ + +OAuth2 authentication + +The [MCP specification supports OAuth 2.1](<https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization>) for authorization. The SDK doesn’t open a browser or run an interactive OAuth flow. When a configured server returns an authorization challenge and no stored token is available, the agent run continues without that server’s tools, and the server reports status `needs-auth`. The `mcp_servers` array of the [system init message](</docs/en/agent-sdk/typescript#sdksystemmessage>) may still show `pending` for that server when it’s emitted. To confirm whether a server needs credentials, poll `mcpServerStatus()` in the TypeScript SDK or [`get_mcp_status()`](</docs/en/agent-sdk/python#methods>) in Python. To supply credentials, complete the OAuth flow in your own application and pass the resulting access token in the server’s `headers`: + +TypeScript + +Python + + // After completing OAuth flow in your app. + // Implement getAccessTokenFromOAuthFlow for your OAuth provider. + const accessToken = await getAccessTokenFromOAuthFlow(); + + const options = { + mcpServers: { + "oauth-api": { + type: "http", + url: "https://api.example.com/mcp", + headers: { + Authorization: `Bearer ${accessToken}` + } + } + }, + allowedTools: ["mcp__oauth-api__*"] + }; + + # After completing OAuth flow in your app. + # Implement get_access_token_from_oauth_flow for your OAuth provider. + access_token = await get_access_token_from_oauth_flow() + + options = ClaudeAgentOptions( + mcp_servers={ + "oauth-api": { + "type": "http", + "url": "https://api.example.com/mcp", + "headers": {"Authorization": f"Bearer {access_token}"}, + } + }, + allowed_tools=["mcp__oauth-api__*"], + ) + +## + +​ + +Examples + +### + +​ + +List issues from a repository + +This example connects to the remote [GitHub MCP server](<https://github.com/github/github-mcp-server>) to list recent issues. The example includes debug logging to verify the MCP connection and tool calls. Before running, create a [GitHub personal access token](<https://github.com/settings/personal-access-tokens>) with read access to the repositories you want to query and set it as an environment variable: + + export GITHUB_TOKEN=YOUR_GITHUB_PAT + +TypeScript + +Python + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + for await (const message of query({ + prompt: "List the 3 most recent issues in anthropics/claude-code", + options: { + mcpServers: { + github: { + type: "http", + url: "https://api.githubcopilot.com/mcp/", + headers: { + Authorization: `Bearer ${process.env.GITHUB_TOKEN}` + } + } + }, + allowedTools: ["mcp__github__list_issues"] + } + })) { + // Verify MCP server connected successfully + if (message.type === "system" && message.subtype === "init") { + console.log("MCP servers:", message.mcp_servers); + } + + // Log when Claude calls an MCP tool + if (message.type === "assistant") { + for (const block of message.message.content) { + if (block.type === "tool_use" && block.name.startsWith("mcp__")) { + console.log("MCP tool called:", block.name); + } + } + } + + // Print the final result + if (message.type === "result" && message.subtype === "success") { + console.log(message.result); + } + } + + import asyncio + import os + from claude_agent_sdk import ( + query, + ClaudeAgentOptions, + ResultMessage, + SystemMessage, + AssistantMessage, + ) + + async def main(): + options = ClaudeAgentOptions( + mcp_servers={ + "github": { + "type": "http", + "url": "https://api.githubcopilot.com/mcp/", + "headers": {"Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}"}, + } + }, + allowed_tools=["mcp__github__list_issues"], + ) + + async for message in query( + prompt="List the 3 most recent issues in anthropics/claude-code", + options=options, + ): + # Verify MCP server connected successfully + if isinstance(message, SystemMessage) and message.subtype == "init": + print("MCP servers:", message.data.get("mcp_servers")) + + # Log when Claude calls an MCP tool + if isinstance(message, AssistantMessage): + for block in message.content: + if hasattr(block, "name") and block.name.startswith("mcp__"): + print("MCP tool called:", block.name) + + # Print the final result + if isinstance(message, ResultMessage) and message.subtype == "success": + print(message.result) + + asyncio.run(main()) + +### + +​ + +Query a database + +This example uses [DBHub](<https://github.com/bytebase/dbhub>) to query a Postgres database. The agent automatically discovers the database schema, writes the SQL query, and returns the results. DBHub’s `execute_sql` tool runs whatever SQL the agent emits, including writes, unless you restrict it. Setting `readonly = true` in the [DBHub configuration file](<https://dbhub.ai/config/toml>) makes DBHub reject `INSERT`, `UPDATE`, `DELETE`, and DDL statements, so the example cannot modify your data even if the agent emits a write. DBHub resolves `${DATABASE_URL}` from the process environment when it loads the config, so the connection string stays out of the file. Create this `dbhub.toml` next to your script: + +dbhub.toml + + [[sources]] + id = "production" + dsn = "${DATABASE_URL}" + + [[tools]] + name = "execute_sql" + source = "production" + readonly = true + +The script then points DBHub at the config file instead of passing a connection string directly. Before running, set the `DATABASE_URL` environment variable to your connection string. Replace the placeholder values with your own database details: + + export DATABASE_URL=postgresql://user:password@localhost:5432/mydb + +TypeScript + +Python + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + for await (const message of query({ + // Natural language query - Claude writes the SQL + prompt: "How many users signed up last week? Break it down by day.", + options: { + mcpServers: { + postgres: { + command: "npx", + // dbhub.toml sets readonly = true, so execute_sql rejects writes + args: ["-y", "@bytebase/dbhub", "--config", "dbhub.toml"] + } + }, + allowedTools: ["mcp__postgres__execute_sql"] + } + })) { + if (message.type === "result" && message.subtype === "success") { + console.log(message.result); + } + } + + import asyncio + from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage + + async def main(): + options = ClaudeAgentOptions( + mcp_servers={ + "postgres": { + "command": "npx", + # dbhub.toml sets readonly = true, so execute_sql rejects writes + "args": [ + "-y", + "@bytebase/dbhub", + "--config", + "dbhub.toml", + ], + } + }, + allowed_tools=["mcp__postgres__execute_sql"], + ) + + # Natural language query - Claude writes the SQL + async for message in query( + prompt="How many users signed up last week? Break it down by day.", + options=options, + ): + if isinstance(message, ResultMessage) and message.subtype == "success": + print(message.result) + + asyncio.run(main()) + +## + +​ + +Error handling + +MCP servers can fail to connect for various reasons: the server process might not be installed, credentials might be invalid, or a remote server might be unreachable. Claude Code emits a `system` message with subtype `init` at the start of each query. This message includes the connection status for each MCP server. The `status` field can be `"pending"`, `"connected"`, `"failed"`, `"needs-auth"`, or `"disabled"`. Claude Code emits the init message after the first-turn connection wait for servers passed in `options.mcpServers`, so such a server that connected within the wait shows `"connected"`. A `"pending"` status means the server hasn’t connected yet, which is common for settings-file servers that don’t get the full wait, or that its tool list was served from the cache with a connection made on first use; the reported status for a deadline-expired server can be `"pending"` or `"failed"` depending on timing. Don’t treat `"pending"` as a failure. Check for `"failed"` or `"needs-auth"` to detect servers that won’t be usable: + +TypeScript + +Python + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + try { + for await (const message of query({ + prompt: "Process data", + options: { + mcpServers: { + // Replace dataServer with your server configuration + "data-processor": dataServer + } + } + })) { + if (message.type === "system" && message.subtype === "init") { + const unavailableServers = message.mcp_servers.filter( + (s) => s.status === "failed" || s.status === "needs-auth" + ); + + if (unavailableServers.length > 0) { + console.warn("Unavailable MCP servers:", unavailableServers); + } + } + + if (message.type === "result" && message.subtype === "error_during_execution") { + console.error("Execution failed"); + } + } + } catch (error) { + // A single-shot query() throws after yielding an error result. If the + // failure was an error result, the error subtype branch above has + // already run; a failure to start or reach the Claude Code process + // yields no result message. MCP servers that fail to connect don't + // throw: use the status check above, and note that servers still + // "pending" at init need a later status check. + console.log(`Session ended with an error: ${error}`); + } + + import asyncio + from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage, ResultMessage + + async def main(): + # Replace data_server with your server configuration + options = ClaudeAgentOptions(mcp_servers={"data-processor": data_server}) + + try: + async for message in query(prompt="Process data", options=options): + if isinstance(message, SystemMessage) and message.subtype == "init": + unavailable_servers = [ + s + for s in message.data.get("mcp_servers", []) + if s.get("status") in ("failed", "needs-auth") + ] + + if unavailable_servers: + print(f"Unavailable MCP servers: {unavailable_servers}") + + if ( + isinstance(message, ResultMessage) + and message.subtype == "error_during_execution" + ): + print("Execution failed") + except Exception as error: + # A single-shot query() raises after yielding an error result. If the + # failure was an error result, the error subtype branch above has + # already run; a failure to start or reach the Claude Code process + # yields no result message. MCP servers that fail to connect don't + # raise: use the status check above, and note that servers still + # "pending" at init need a later status check. + print(f"Session ended with an error: {error}") + + asyncio.run(main()) + +## + +​ + +Troubleshooting + +### + +​ + +Server shows “failed” status + +Check the `init` message to see which servers failed to connect: + +TypeScript + +Python + + if (message.type === "system" && message.subtype === "init") { + for (const server of message.mcp_servers) { + if (server.status === "failed") { + console.error(`Server ${server.name} failed to connect`); + } + } + } + + if isinstance(message, SystemMessage) and message.subtype == "init": + for server in message.data.get("mcp_servers", []): + if server.get("status") == "failed": + print(f"Server {server['name']} failed to connect") + +A `"pending"` status doesn’t mean the server failed; see Error handling for the two cases it covers at init. To get updated statuses later in the session, call the query’s `mcpServerStatus()` method in the TypeScript SDK, or [`ClaudeSDKClient.get_mcp_status()`](</docs/en/agent-sdk/python#methods>) in Python. Common causes: + + * **Missing environment variables** : Ensure required tokens and credentials are set. For stdio servers, check the `env` field matches what the server expects. + * **Server not installed** : For `npx` commands, verify the package exists and Node.js is in your PATH. + * **Invalid connection string** : For database servers, verify the connection string format and that the database is accessible. + * **Network issues** : For remote HTTP/SSE servers, check the URL is reachable and any firewalls allow the connection. + +### + +​ + +Tools not being called + +If Claude sees tools but doesn’t use them, check that you’ve granted permission with `allowedTools`: + +TypeScript + +Python + + const _ = { + options: { + mcpServers: { + // your servers + }, + allowedTools: ["mcp__servername__*"] // Auto-approve calls from this server + } + }; + + options = ClaudeAgentOptions( + mcp_servers={ + # your servers + }, + allowed_tools=["mcp__servername__*"], # Auto-approve calls from this server + ) + +### + +​ + +Connection timeouts + +MCP server connections time out after 30 seconds by default. If your server takes longer to start, the connection fails. Raise the limit with the [`MCP_TIMEOUT`](</docs/en/env-vars>) environment variable, in milliseconds. For servers that need more startup time, also consider: + + * Using a lighter-weight server if available + * Pre-warming the server before starting your agent + * Checking server logs for slow initialization causes + +### + +​ + +Tool output exceeds maximum allowed tokens + +The SDK applies the same MCP output limit as Claude Code. When a tool result is larger than 25,000 tokens, the full output is saved to a file and the tool result is replaced with an error message that names the file path, so the agent can read the output back in portions. Raise the limit with the [`MAX_MCP_OUTPUT_TOKENS`](</docs/en/env-vars>) environment variable. See [MCP output limits and warnings](</docs/en/mcp#mcp-output-limits-and-warnings>) for the full behavior, including how a server can declare a higher per-tool limit. + +## + +​ + +Related resources + + * **[Custom tools guide](</docs/en/agent-sdk/custom-tools>)** : Build your own MCP server that runs in-process with your SDK application + * **[Permissions](</docs/en/agent-sdk/permissions>)** : Control which MCP tools your agent can use with `allowedTools` and `disallowedTools` + * **[MCP output limits and warnings](</docs/en/mcp#mcp-output-limits-and-warnings>)** : How the SDK handles tool results that exceed `MAX_MCP_OUTPUT_TOKENS`, including the persist-to-disk fallback and the `anthropic/maxResultSizeChars` per-tool annotation + * **[TypeScript SDK reference](</docs/en/agent-sdk/typescript>)** : Full API reference including MCP configuration options + * **[Python SDK reference](</docs/en/agent-sdk/python>)** : Full API reference including MCP configuration options + * **[MCP server directory](<https://github.com/modelcontextprotocol/servers>)** : Browse available MCP servers for databases, APIs, and more
modified Migrate to Claude Agent SDK View current →
--- a/migration-guide.md +++ b/migration-guide.md @@ -78,7 +78,7 @@ pip install claude-agent-sdk -**3\. Update your imports:** Change all imports from `claude_code_sdk` to `claude_agent_sdk`: +If `claude-code-sdk` is listed in your `requirements.txt` or `pyproject.toml`, replace it with `claude-agent-sdk`. **3\. Update your imports:** Change all imports from `claude_code_sdk` to `claude_agent_sdk`: # Before from claude_code_sdk import query, ClaudeCodeOptions @@ -125,8 +125,6 @@ from claude_agent_sdk import query, ClaudeAgentOptions options = ClaudeAgentOptions(model="claude-opus-4-7", permission_mode="acceptEdits") - -**Why this changed:** The type name now matches the “Claude Agent SDK” branding and provides consistency across the SDK’s naming conventions. ### @@ -197,7 +195,7 @@ Settings sources default -This default was briefly changed in v0.1.0 and then reverted, so no migration action is needed. **Current behavior:** Omitting `settingSources` on `query()` loads user, project, and local filesystem settings, matching the CLI. This includes `~/.claude/settings.json`, `.claude/settings.json`, `.claude/settings.local.json`, CLAUDE.md files, and custom commands. To run isolated from filesystem settings, pass an empty array: +This default was briefly changed in v0.1.0 to load no filesystem settings and then reverted, so no migration action is needed. **Current behavior:** Omitting `settingSources` on `query()` loads user, project, and local filesystem settings, matching the CLI. This includes `~/.claude/settings.json`, `.claude/settings.json`, `.claude/settings.local.json`, CLAUDE.md files, and custom commands. To run isolated from filesystem settings, pass an empty array: TypeScript @@ -243,37 +241,7 @@ Isolation is especially important for CI/CD pipelines, deployed applications, test environments, and multi-tenant systems where local customizations should not leak in. -SDK v0.1.0 briefly defaulted to no settings loaded; this was reverted in subsequent releases. Python SDK 0.1.59 and earlier treated an empty list the same as omitting the option, so upgrade before relying on `setting_sources=[]`. See [What settingSources does not control](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>) for inputs that are read even when `settingSources` is `[]`. - -## - -​ - -Why the Rename? - -The Claude Code SDK was originally designed for coding tasks, but it has evolved into a powerful framework for building all types of AI agents. The new name “Claude Agent SDK” better reflects its capabilities: - - * Building business agents (legal assistants, finance advisors, customer support) - * Creating specialized coding agents (SRE bots, security reviewers, code review agents) - * Developing custom agents for any domain with tool use, MCP integration, and more - -## - -​ - -Getting Help - -If you encounter any issues during migration: **For TypeScript/JavaScript:** - - 1. Check that all imports are updated to use `@anthropic-ai/claude-agent-sdk` - 2. Verify your package.json has the new package name - 3. Run `npm install` to ensure dependencies are updated - -**For Python:** - - 1. Check that all imports are updated to use `claude_agent_sdk` - 2. Verify your requirements.txt or pyproject.toml has the new package name - 3. Run `pip install claude-agent-sdk` to ensure the package is installed +Python SDK 0.1.59 and earlier treated an empty list the same as omitting the option, so upgrade before relying on `setting_sources=[]`. See [What settingSources does not control](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>) for inputs that are read even when `settingSources` is `[]`. ##
modified Modifying system prompts View current →
--- a/modifying-system-prompts.md +++ b/modifying-system-prompts.md @@ -1,9 +1,4 @@ -System prompts define Claude’s behavior, capabilities, and response style. Start from the `claude_code` preset for CLI or IDE-like coding tools where a human watches and steers the work. Write your own prompt for agents with a different surface, identity, or permission model. This page covers: - - * How system prompts work, with a decision table for choosing between the preset, the preset with `append`, and a custom prompt - * Customize agent behavior with CLAUDE.md files, output styles, `append`, or a custom string - * Compare the four approaches by persistence, scope, and what they preserve - * Combine approaches to layer customization methods together +System prompts define Claude’s behavior, capabilities, and response style. Start from the `claude_code` preset for CLI or IDE-like coding tools where a human watches and steers the work. Write your own prompt for agents with a different surface, identity, or permission model. ## @@ -367,7 +362,7 @@ When to use CLAUDE.md -Use CLAUDE.md for instructions that should apply to every session in a project, regardless of which system prompt the session uses: coding standards, common commands, architecture context, and team conventions. CLAUDE.md is committed to your repository, so it stays in sync with the code it describes. See [When to add to CLAUDE.md](</docs/en/memory#when-to-add-to-claude-md>) for full guidance. CLAUDE.md files load when the `project` setting source is enabled, which it is for default `query()` options. If you set `settingSources` in TypeScript or `setting_sources` in Python explicitly, include `'project'` to keep loading project-level CLAUDE.md. +Use CLAUDE.md for instructions that should apply to every session in a project, regardless of which system prompt the session uses: coding standards, common commands, architecture context, and team conventions. CLAUDE.md is committed to your repository, so it stays in sync with the code it describes. See [When to add to CLAUDE.md](</docs/en/memory#when-to-add-to-claude-md>) for full guidance. ###
modified Agent SDK overview View current →
Show diff (272 lines)
--- a/overview.md +++ b/overview.md @@ -1,4 +1,40 @@ -Claude Code is an AI-powered coding assistant that helps you build features, fix bugs, and automate development tasks. It understands your entire codebase and can work across multiple files and tools to get things done. +An agent is an application that completes a task by planning its own steps and calling tools that read files, run commands, or edit code. The Agent SDK gives you the same tools, [agent loop](</docs/en/agent-sdk/agent-loop>), and context management that power Claude Code, programmable in Python and TypeScript. + +## + +​ + +Compare the Agent SDK to other Claude tools + +The Agent SDK, the CLI, the Client SDK, and Managed Agents each fit different needs. Use the table to find the one that matches what you’re building. + +If you’re…| Use| Why +---|---|--- +Building an agent without implementing the tool loop yourself| **Agent SDK**| A library that runs the agent loop in your own process, in Python or TypeScript. +Doing interactive development or running one-off tasks from a terminal| [**Claude Code CLI**](</docs/en/overview>)| The terminal interface, built for daily interactive use. +Calling the API directly and implementing the tool loop yourself| [**Client SDK**](<https://platform.claude.com/docs/en/api/client-sdks>)| Direct access to the Anthropic API rather than to Claude Code. You implement the tool loop yourself. +Running long-running or asynchronous agents without managing your own sandbox or session infrastructure| [**Managed Agents**](<https://platform.claude.com/docs/en/managed-agents/overview>)| Hosted REST API, a separate product from the Agent SDK. Anthropic runs the agent and the sandbox. + +The SDK is available as a library for Python and TypeScript only. To drive the same agent loop from another language, [run the CLI as a subprocess](</docs/en/headless>) with the `-p` flag and `--output-format json`. + +## + +​ + +Capabilities + +Everything that makes Claude Code powerful is available in the SDK. + +Capability| What it does| Learn more +---|---|--- +Built-in tools| Read, write, edit files, run commands, and search the web| [Tools reference](</docs/en/tools-reference>) +Hooks| Run custom code at key points in the agent lifecycle| [Hooks](</docs/en/agent-sdk/hooks>) +Subagents| Spawn specialized agents for focused subtasks| [Subagents](</docs/en/agent-sdk/subagents>) +MCP| Connect external tools and data sources via the Model Context Protocol| [MCP](</docs/en/agent-sdk/mcp>) +Permissions| Control which tools run automatically, which need approval| [Permissions](</docs/en/agent-sdk/permissions>) +Sessions| Maintain context across exchanges, resume or fork later| [Sessions](</docs/en/agent-sdk/sessions>) +Skills, commands, and memory| Load automatically from your project’s `.claude/` and from `~/.claude/`, same as Claude Code| [Skills](</docs/en/agent-sdk/skills>), [Commands](</docs/en/agent-sdk/slash-commands>), [Memory](</docs/en/agent-sdk/modifying-system-prompts>), [Configuration loading](</docs/en/agent-sdk/claude-code-features>) +Plugins| Package skills, agents, hooks, and MCP servers, and load them by local path| [Plugins](</docs/en/agent-sdk/plugins>) ## @@ -6,170 +42,58 @@ Get started -Claude Code runs on several surfaces: the terminal, IDE extensions, a desktop app, and the web. Choose one from the tabs below to get started. Most surfaces require a [Claude subscription](<https://claude.com/pricing?utm_source=claude_code&utm_medium=docs&utm_content=overview_pricing>) or [Anthropic Console](<https://console.anthropic.com/>) account. The Terminal CLI and VS Code also support [third-party providers](</docs/en/third-party-integrations>). +Follow the [Quickstart](</docs/en/agent-sdk/quickstart>) to install the SDK, set your API key, and build your first agent, one that finds and fixes bugs in existing code. - * Terminal - - * VS Code - - * Desktop app - - * Web - - * JetBrains - -The full-featured CLI for working with Claude Code directly in your terminal. Edit files, run commands, and manage your entire project from the command line.To install Claude Code, use one of the following methods: - - * Native Install (Recommended) - - * Homebrew - - * WinGet - -**macOS, Linux, WSL:** - - curl -fsSL https://claude.ai/install.sh | bash - -**Windows PowerShell:** - - irm https://claude.ai/install.ps1 | iex - -**Windows CMD:** - - curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd - -If you see `The token '&&' is not a valid statement separator`, you’re in PowerShell, not CMD. If you see `'irm' is not recognized as an internal or external command`, you’re in CMD, not PowerShell. Your prompt shows `PS C:\` when you’re in PowerShell and `C:\` without the `PS` when you’re in CMD.If the install command fails with `syntax error near unexpected token '<'`, a `403`, or another curl error, see [Troubleshoot installation](</docs/en/troubleshoot-install#find-your-error>) to match the error to a fix and for alternative install methods.[Git for Windows](<https://git-scm.com/downloads/win>) is recommended on native Windows so Claude Code can use the Bash tool. If Git for Windows is not installed, Claude Code uses PowerShell as the shell tool instead. WSL setups do not need Git for Windows. - -Native installations automatically update in the background to keep you on the latest version. - - brew install --cask claude-code - -Homebrew offers two casks. `claude-code` tracks the stable release channel, which is typically about a week behind and skips releases with major regressions. `claude-code@latest` tracks the latest channel and receives new versions as soon as they ship. - -Homebrew installations do not auto-update. Run `brew upgrade claude-code` or `brew upgrade claude-code@latest`, depending on which cask you installed, to get the latest features and security fixes. - - winget install Anthropic.ClaudeCode - -WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes. - -You can also install with [apt, dnf, or apk](</docs/en/setup#install-with-linux-package-managers>) on Debian, Fedora, RHEL, and Alpine.Then start Claude Code in any project. Replace `your-project` with the path to a project directory on your machine: - - cd your-project - claude - -You’ll be prompted to log in on first use. If you’ve set the `ANTHROPIC_API_KEY` environment variable, Claude Code skips the login prompt and asks you to approve the key instead. That’s it! [Continue with the Quickstart →](</docs/en/quickstart>) - -See [advanced setup](</docs/en/setup>) for installation options, manual updates, or uninstallation instructions. Visit [installation troubleshooting](</docs/en/troubleshoot-install>) if you hit issues. - -The VS Code extension provides inline diffs, @-mentions, plan review, and conversation history directly in your editor. - - * [Install for VS Code](<vscode:extension/anthropic.claude-code>) - * [Install for Cursor](<cursor:extension/anthropic.claude-code>) - -Or search for “Claude Code” in the Extensions view (`Cmd+Shift+X` on Mac, `Ctrl+Shift+X` on Windows/Linux). After installing, open the Command Palette (`Cmd+Shift+P` / `Ctrl+Shift+P`), type “Claude Code”, and select **Open in New Tab**.[Get started with VS Code →](</docs/en/vs-code#get-started>) - -A standalone app for running Claude Code outside your IDE or terminal. Review diffs visually, run multiple sessions side by side, schedule recurring tasks, and kick off cloud sessions.Download and install: - - * [macOS](<https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code&utm_medium=docs>) (Intel and Apple Silicon) - * [Windows](<https://claude.ai/api/desktop/win32/x64/setup/latest/redirect?utm_source=claude_code&utm_medium=docs>) (x64) - * [Windows ARM64](<https://claude.ai/api/desktop/win32/arm64/setup/latest/redirect?utm_source=claude_code&utm_medium=docs>) - -After installing, launch Claude, sign in, and click the **Code** tab to start coding. A [paid subscription](<https://claude.com/pricing?utm_source=claude_code&utm_medium=docs&utm_content=overview_desktop_pricing>) is required.[Learn more about the desktop app →](</docs/en/desktop-quickstart>) - -Run Claude Code in your browser with no local setup. Kick off long-running tasks and check back when they’re done, work on repos you don’t have locally, or run multiple tasks in parallel. Available on desktop browsers and [the Claude app for iOS and Android](</docs/en/mobile>).Start coding at [claude.ai/code](<https://claude.ai/code>).[Get started on the web →](</docs/en/web-quickstart>) - -A plugin for IntelliJ IDEA, PyCharm, WebStorm, and other JetBrains IDEs with interactive diff viewing and selection context sharing.Install the [Claude Code plugin](<https://plugins.jetbrains.com/plugin/27310-claude-code-beta->) from the JetBrains Marketplace and restart your IDE. The plugin requires the Claude Code CLI, installed separately; see the [JetBrains setup steps](</docs/en/jetbrains#installation>).[Get started with JetBrains →](</docs/en/jetbrains>) +Unless previously approved, Anthropic does not allow third party developers to offer claude.ai login or rate limits for their products, including agents built on the Claude Agent SDK. Use the API key authentication methods described in the [Quickstart](</docs/en/agent-sdk/quickstart>) instead. ## ​ -What you can do +Changelog -Here are some of the ways you can use Claude Code: +View the full changelog for SDK updates, bug fixes, and new features: -Automate the work you keep putting off - -Claude Code handles the tedious tasks that eat up your day: writing tests for untested code, fixing lint errors across a project, resolving merge conflicts, updating dependencies, and writing release notes. - - claude "write tests for the auth module, run them, and fix any failures" - -Build features and fix bugs - -Describe what you want in plain language. Claude Code plans the approach, writes the code across multiple files, and verifies it works.For bugs, paste an error message or describe the symptom. Claude Code traces the issue through your codebase, identifies the root cause, and implements a fix. See [common workflows](</docs/en/common-workflows>) for more examples. - -Create commits and pull requests - -Claude Code works directly with git. It stages changes, writes commit messages, creates branches, and opens pull requests. - - claude "commit my changes with a descriptive message" - -In CI, you can automate code review and issue triage with [GitHub Actions](</docs/en/github-actions>) or [GitLab CI/CD](</docs/en/gitlab-ci-cd>). - -Connect your tools with MCP - -The [Model Context Protocol (MCP)](</docs/en/mcp>) is an open standard for connecting AI tools to external data sources. With MCP, Claude Code can read your design docs in Google Drive, update tickets in Jira, pull data from Slack, or use your own custom tooling. The [MCP quickstart](</docs/en/mcp-quickstart>) connects your first server end to end. - -Customize with instructions, skills, and hooks - -[`CLAUDE.md`](</docs/en/memory>) is a markdown file you add to your project root that Claude Code reads at the start of every session. Use it to set coding standards, architecture decisions, preferred libraries, and review checklists. Claude also builds [auto memory](</docs/en/memory#auto-memory>) as it works, saving learnings like build commands and debugging insights across sessions without you writing anything.Create [skills](</docs/en/skills>) to package repeatable workflows your team can share, like `/review-pr` or `/deploy-staging`.[Hooks](</docs/en/hooks>) let you run shell commands before or after Claude Code actions, like auto-formatting after every file edit or running lint before a commit. - -Run agent teams and build custom agents - -Spawn [multiple Claude Code agents](</docs/en/sub-agents>) that work on different parts of a task simultaneously. A lead agent coordinates the work, assigns subtasks, and merges results.To run several full sessions in parallel and watch them from one screen, use [background agents](</docs/en/agent-view>). For fully custom workflows, the [Agent SDK](</docs/en/agent-sdk/overview>) lets you build your own agents powered by Claude Code’s tools and capabilities, with full control over orchestration, tool access, and permissions. - -Pipe, script, and automate with the CLI - -Claude Code is composable and follows the Unix philosophy. Pipe logs into it, run it in CI, or chain it with other tools: - - # Analyze recent log output - tail -200 app.log | claude -p "Slack me if you see any anomalies" - - # Automate translations in CI - claude -p "translate new strings into French and raise a PR for review" - - # Bulk operations across files - git diff main --name-only | claude -p "review these changed files for security issues" - -See the [CLI reference](</docs/en/cli-reference>) for the full set of commands and flags. - -Schedule recurring tasks - -Run Claude on a schedule to automate work that repeats: morning PR reviews, overnight CI failure analysis, weekly dependency audits, or syncing docs after PRs merge. - - * [Routines](</docs/en/routines>) run in the cloud, so they keep running even when your computer is off. They can also trigger on API calls or GitHub events. Create them from the web, the Desktop app, or by running `/schedule` in the CLI. - * [Desktop scheduled tasks](</docs/en/desktop-scheduled-tasks>) run on your machine, with direct access to your local files and tools - * [`/loop`](</docs/en/scheduled-tasks>) repeats a prompt within a CLI session for quick polling - -Work from anywhere - -Sessions aren’t tied to a single surface. Move work between them as your context changes: - - * Step away from your desk and keep working from your phone or any browser with [Remote Control](</docs/en/remote-control>) - * Message [Dispatch](</docs/en/desktop#sessions-from-dispatch>) a task from your phone and open the Desktop session it creates - * Kick off a long-running task on the [web](</docs/en/claude-code-on-the-web>) or the [Claude mobile app](</docs/en/mobile>), then pull it into your terminal with `claude --teleport`. Teleport requires a claude.ai subscription. - * Run `/desktop` to continue your current terminal session in the [Desktop app](</docs/en/desktop>), where you can review diffs visually. The `/desktop` handoff requires a claude.ai subscription. Available on macOS and x64 Windows. - * Route tasks from team chat: mention `@Claude` in [Slack](</docs/en/slack>) with a bug report and get a pull request back + * **TypeScript SDK** : [view CHANGELOG.md](<https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/CHANGELOG.md>) + * **Python SDK** : [view CHANGELOG.md](<https://github.com/anthropics/claude-agent-sdk-python/blob/main/CHANGELOG.md>) ## ​ -Use Claude Code everywhere +Report bugs -Each [surface](</docs/en/glossary#surface>) connects to the same underlying Claude Code engine, so your CLAUDE.md files, settings, and MCP servers work across all of them. Beyond the [Terminal](</docs/en/quickstart>), [VS Code](</docs/en/vs-code>), [JetBrains](</docs/en/jetbrains>), [Desktop](</docs/en/desktop>), and [Web](</docs/en/claude-code-on-the-web>) surfaces above, Claude Code integrates with CI/CD, chat, and browser workflows: +If you encounter bugs or issues with the Agent SDK: -I want to…| Best option ----|--- -Continue a local session from my phone or another device| [Remote Control](</docs/en/remote-control>) -Push events from Telegram, Discord, iMessage, or my own webhooks into a session| [Channels](</docs/en/channels>) -Start a task locally, continue on mobile| [`claude --cloud`](</docs/en/claude-code-on-the-web#from-terminal-to-web>), then the [Claude mobile app](</docs/en/mobile>) -Run Claude on a recurring schedule| [Routines](</docs/en/routines>) or [Desktop scheduled tasks](</docs/en/desktop-scheduled-tasks>) -Automate PR reviews and issue triage| [GitHub Actions](</docs/en/github-actions>) or [GitLab CI/CD](</docs/en/gitlab-ci-cd>) -Get automatic code review on every PR| [GitHub Code Review](</docs/en/code-review>) -Route bug reports from Slack to pull requests| [Slack](</docs/en/slack>) -Debug live web applications| [Chrome](</docs/en/chrome>) -Build custom agents for your own workflows| [Agent SDK](</docs/en/agent-sdk/overview>) + * **TypeScript SDK** : [report issues on GitHub](<https://github.com/anthropics/claude-agent-sdk-typescript/issues>) + * **Python SDK** : [report issues on GitHub](<https://github.com/anthropics/claude-agent-sdk-python/issues>) + +## + +​ + +Branding guidelines + +For partners integrating the Claude Agent SDK, use of Claude branding is optional. When referencing Claude in your product: **Allowed:** + + * “Claude Agent”, preferred for dropdown menus + * “Claude”, when within a menu already labeled “Agents” + * “{YourAgentName} Powered by Claude”, if you have an existing agent name + +**Not permitted:** + + * “Claude Code” or “Claude Code Agent” + * Claude Code-branded ASCII art or visual elements that mimic Claude Code + +Your product should maintain its own branding and not appear to be Claude Code or any Anthropic product. For questions about branding compliance, contact the Anthropic [sales team](<https://www.anthropic.com/contact-sales>). + +## + +​ + +License and terms + +Use of the Claude Agent SDK is governed by [Anthropic’s Commercial Terms of Service](<https://www.anthropic.com/legal/commercial-terms>), including when you use it to power products and services that you make available to your own customers and end users, except to the extent a specific component or dependency is covered by a different license as indicated in that component’s LICENSE file. ## @@ -177,12 +101,11 @@ Next steps -Once you’ve installed Claude Code, these guides help you go deeper. +These resources cover deeper technical detail and example projects for building with the Agent SDK. - * [Quickstart](</docs/en/quickstart>): walk through your first real task, from exploring a codebase to committing a fix - * [Store instructions and memories](</docs/en/memory>): give Claude persistent instructions with CLAUDE.md files and auto memory - * [Common workflows](</docs/en/common-workflows>) and [best practices](</docs/en/best-practices>): patterns for getting the most out of Claude Code - * [A harness for every task](<https://claude.com/blog/a-harness-for-every-task-dynamic-workflows-in-claude-code>): how the Claude Code team uses [dynamic workflows](</docs/en/workflows>) to orchestrate subagents at scale - * [Settings](</docs/en/settings>): customize Claude Code for your workflow - * [Troubleshooting](</docs/en/troubleshooting>): solutions for common issues - * [code.claude.com](<https://code.claude.com/>): demos, pricing, and product details + * [Quickstart](</docs/en/agent-sdk/quickstart>): build your first agent that finds and fixes bugs + * [Agent loop](</docs/en/agent-sdk/agent-loop>): how Claude plans, calls tools, and decides when a task is done + * [Example agents](<https://github.com/anthropics/claude-agent-sdk-demos>): demo apps for local development + * [TypeScript SDK](</docs/en/agent-sdk/typescript>): full TypeScript API reference and examples + * [Python SDK](</docs/en/agent-sdk/python>): full Python API reference and examples + * [Agent harness design](<https://claude.com/blog/a-harness-for-every-task-dynamic-workflows-in-claude-code>): how the Claude Code team uses dynamic workflows to orchestrate subagents at scale
modified Choose a permission mode View current →
--- a/permission-modes.md +++ b/permission-modes.md @@ -157,7 +157,7 @@ Starting August 14, 2026, auto mode becomes the default permission mode for new sessions on Pro, Max, and Team plans. You can switch modes at any time. A default you set yourself stays in place unless you accept the one-time switch prompt, and a default your organization manages is unchanged. For details, see [the announcement](<https://claude.com/blog/auto-mode-default-in-claude-code>) on the blog. -Auto mode lets Claude execute without routine permission prompts. A separate classifier model reviews actions before they run, blocking anything that escalates beyond your request, targets unrecognized infrastructure, or appears driven by hostile content Claude read. Explicit [ask rules](</docs/en/permissions#manage-permissions>) still force a prompt. The classifier also decides removals targeting the filesystem root or home directory, such as `rm -rf /` and `rm -rf ~`, including when the removal sits inside command or process substitution. Before v2.1.218, the plain forms prompted for approval instead, and the substitution forms prompted in v2.1.208 through v2.1.217. Auto mode also nudges Claude to keep working without stopping for clarifying questions, though Claude still asks when your prompt or a skill explicitly relies on it. For stronger autonomous behavior while keeping permission prompts, set the [Proactive output style](</docs/en/output-styles>) instead. +Auto mode lets Claude execute without routine permission prompts. A separate classifier model reviews actions before they run, blocking anything that escalates beyond your request, targets unrecognized infrastructure, or appears driven by hostile content Claude read. Explicit [ask rules](</docs/en/permissions#manage-permissions>) still force a prompt. The classifier also reviews each message Claude sends to another agent with [`SendMessage`](</docs/en/tools-reference>), plain or structured, before Claude Code delivers it, both in auto mode and in plan mode while the classifier reviews commands; the send review requires Claude Code v2.1.222 or later. The classifier also decides removals targeting the filesystem root or home directory, such as `rm -rf /` and `rm -rf ~`, including when the removal sits inside command or process substitution. Before v2.1.218, the plain forms prompted for approval instead, and the substitution forms prompted in v2.1.208 through v2.1.217. Auto mode also nudges Claude to keep working without stopping for clarifying questions, though Claude still asks when your prompt or a skill explicitly relies on it. For stronger autonomous behavior while keeping permission prompts, set the [Proactive output style](</docs/en/output-styles>) instead. Auto mode reduces permission prompts but does not guarantee safety. Use it for tasks where you trust the general direction, not as a replacement for review on sensitive operations.
modified Configure permissions View current →
Show diff (799 lines)
--- a/permissions.md +++ b/permissions.md @@ -1,36 +1,88 @@ -Claude Code supports fine-grained permissions so that you can specify exactly what the agent is allowed to do and what it can’t. You can check permission settings into version control to share them with every developer in your organization, and each developer can customize their own. - -## - -​ - -Permission system - -Claude Code uses a tiered permission system to balance power and safety: - -Tool type| Example| Approval required| ”Yes, don’t ask again” behavior ----|---|---|--- -Read-only| File reads, Grep| No, within the working directory and additional directories| N/A -Bash commands| Shell execution| Yes, except a built-in set of read-only commands| Permanently per repository and command -File modification| Edit/write files| Yes| Until session end - -When you choose “Yes, don’t ask again” and the approval saves permanently, such as for a Bash command, Claude Code saves the rule to `.claude/settings.local.json` at the root of the git repository, resolved through [worktrees](</docs/en/worktrees>) to the main checkout. The rule applies to future sessions anywhere in that repository, including sessions started in subdirectories and in worktrees. A file-modification approval isn’t saved to the file: as the table shows, it lasts until the session ends. Outside a git repository, and when the repository root is your home directory, Claude Code saves the rule in the directory you started it from. Before v2.1.211, Claude Code always saved the rule in the starting directory, so an approval granted in a worktree or subdirectory didn’t apply to the rest of the repository. Rules that earlier versions saved in a subdirectory or worktree still apply to sessions started there. On a Bash or PowerShell permission prompt, press `Ctrl+E` to show an explanation of the command: what it does, why Claude is running it, and what could go wrong, labeled **Low risk** , **Med risk** , or **High risk**. Claude Code sends the command and Claude’s own description of the call to the model to generate the explanation only when you press `Ctrl+E`, not on every prompt. Showing the explanation doesn’t run the command; press `Ctrl+E` again to hide it. To turn the shortcut off, set [`permissionExplainerEnabled`](</docs/en/settings#global-config-settings>) to `false` in `~/.claude.json`. - -## - -​ - -Manage permissions - -You can view and manage Claude Code’s tool permissions with `/permissions`. This UI lists all permission rules and the `settings.json` file each rule comes from. - - * **Allow** rules let Claude Code use the specified tool without manual approval. - * **Ask** rules prompt for confirmation whenever Claude Code tries to use the specified tool. - * **Deny** rules prevent Claude Code from using the specified tool. - -Rules are evaluated in order: deny, then ask, then allow. The first match in that order determines the outcome, and rule specificity doesn’t change the order. A broad deny rule like `Bash(aws *)` blocks every matching call, including calls that also match a narrower allow rule like `Bash(aws s3 ls)`, so a deny rule can’t carry allowlist exceptions. The same precedence applies between ask and allow: a matching ask rule prompts even when a more specific allow rule also matches the same call. Deny rules behave differently depending on whether they name a tool or scope a pattern within one. A bare tool name like `Bash` removes the tool from Claude’s context entirely, so Claude never sees it. Bare-name removal applies to every tool except [`EndConversation`](</docs/en/tools-reference#endconversation-tool-behavior>): a deny rule can’t remove it while any other tool remains, and an ask rule never prompts for it. A scoped rule like `Bash(rm *)` leaves the tool available and blocks matching calls when Claude attempts them. - -Permission rules are enforced by Claude Code, not by the model. Instructions in your prompt or `CLAUDE.md` shape what Claude tries to do, but they don’t change what Claude Code allows. To grant or revoke access, use `/permissions`, the rules described here, a [permission mode](</docs/en/permission-modes>), or a PreToolUse hook. +The Claude Agent SDK provides permission controls to manage how Claude uses tools. Use permission modes and rules to define what’s allowed automatically, and the [`canUseTool` callback](</docs/en/agent-sdk/user-input>) to handle everything else at runtime. + +## + +​ + +How permissions are evaluated + +When Claude requests a tool, the SDK checks permissions in this order: + +1 + +Hooks + +Run [hooks](</docs/en/agent-sdk/hooks>) first. A hook can deny the call outright or pass it on. A hook that returns `allow` does not skip the deny and ask rules below; those are evaluated regardless of the hook result. + +2 + +Deny rules + +Check `deny` rules (from `disallowed_tools` and [settings.json](</docs/en/settings#permission-settings>)). If a deny rule matches, the tool is blocked, even in `bypassPermissions` mode. Bare-name deny rules like `Bash` remove the tool from Claude’s context before this evaluation begins, so only scoped rules like `Bash(rm *)` are checked at this step. + +3 + +Ask rules + +Check `ask` rules from [settings.json](</docs/en/settings#permission-settings>). If an ask rule matches, the call falls through to your [`canUseTool` callback](</docs/en/agent-sdk/user-input>) for confirmation, even in `bypassPermissions` mode.Tools that require user interaction behave the same way: `AskUserQuestion` and MCP tools whose server sets [`_meta["anthropic/requiresUserInteraction"]`](</docs/en/mcp#require-approval-for-a-specific-tool>) always fall through to the callback, even when an allow rule matches. In `dontAsk` mode both cases are denied instead, because that mode never prompts. The MCP annotation requires Claude Code v2.1.199 or later.[claude.ai connector](</docs/en/mcp#organization-controls-on-connector-tools>) tools your organization has set to `ask` also leave the flow at this step. Every call falls through to the callback, even in `bypassPermissions` mode and even when an allow rule matches. The callback receives the reason `Your organization requires approval for this tool`. In `dontAsk` mode the call is denied instead, because that mode never prompts. + +4 + +Permission mode + +Apply the active permission mode. `bypassPermissions` approves everything that reaches this step. `acceptEdits` approves file operations. `plan` routes file-edit and shell-write tools to your `canUseTool` callback regardless of allow rules, so write operations cannot be auto-approved while planning. Other modes fall through. + +5 + +Allow rules + +Check `allow` rules (from `allowed_tools` and settings.json). If a rule matches, the tool is approved. + +6 + +canUseTool callback + +If not resolved by any of the above, call your [`canUseTool` callback](</docs/en/agent-sdk/user-input>) for a decision. In `dontAsk` mode, this step is skipped and the tool is denied. + +If you pass a `canUseTool` callback that this evaluation order can never reach, the TypeScript SDK emits a Node.js process warning once when the query is constructed. The warning’s code is `CLAUDE_SDK_CAN_USE_TOOL_SHADOWED`. Two configurations trigger it: + + * `permissionMode: 'bypassPermissions'`, which auto-approves every call that reaches the permission mode step + * Each bare `allowedTools` entry such as `"Read"`, which auto-approves that whole tool before the callback is consulted + +Entries with a specifier such as `Bash(ls *)` and the `acceptEdits` mode don’t trigger it, and allow rules coming from settings files aren’t visible to the check. Listen with `process.on('warning', ...)` and match the code to log or suppress it. To gate every tool call regardless of mode and rules, use a [`PreToolUse` hook](</docs/en/agent-sdk/hooks>) instead. This page focuses on **allow and deny rules** and **permission modes**. For the other steps: + + * **Hooks:** run custom code to allow, deny, or modify tool requests. See [Control execution with hooks](</docs/en/agent-sdk/hooks>). + * **canUseTool callback:** prompt users for approval at runtime, when no earlier step resolves the call. See [Handle approvals and user input](</docs/en/agent-sdk/user-input>). + +## + +​ + +Allow and deny rules + +`allowed_tools` and `disallowed_tools` (TypeScript: `allowedTools` / `disallowedTools`) add entries to the allow and deny rule lists in the evaluation flow above. Allow rules only affect approval: a tool not listed in `allowed_tools` is still available to Claude and falls through to the permission mode. Deny rules behave differently depending on whether they name a tool or scope a pattern within one. + +Option| Effect +---|--- +`allowed_tools=["Read", "Grep"]`| `Read` and `Grep` are auto-approved. Tools not listed here still exist and fall through to the permission mode and `canUseTool`. +`disallowed_tools=["Bash"]`| The `Bash` tool definition is removed from the request. Claude does not see the tool and cannot attempt it. +`disallowed_tools=["Bash(rm *)"]`| `Bash` stays available. Calls matching `rm *` are denied in every permission mode, including `bypassPermissions`. Other `Bash` calls fall through to the permission mode. +`disallowed_tools=["*"]`| Every tool definition is removed from the request. Tool-name globs are supported in deny rules: `"*"` matches every tool and `"mcp__*"` matches every MCP tool across all servers. + +Allow rules accept tool-name globs only after a literal `mcp__<server>__` prefix. The server segment must be glob-free so the rule names a specific server you configured: `mcp__puppeteer__*` matches every tool from the `puppeteer` server, and `mcp__github__get_*` matches its `get_` tools. An unanchored entry like `allowed_tools=["*"]` or `allowed_tools=["mcp__*"]` is ignored with a startup warning and does not auto-approve anything. Scoped rules for `Read` and `Edit` take a path pattern. `Edit(path)` rules govern all built-in tools that write files, including `Write` and `NotebookEdit`; a `Write(path)` rule is never matched by the file permission checks. Use `//path` for an absolute filesystem path: a deny rule of `Edit(//secrets/**)` blocks writes anywhere under `/secrets` on disk. With a single leading slash, `Edit(/secrets/**)` anchors at the rule’s source instead. For rules passed through `allowed_tools` or `disallowed_tools`, that means the session’s working directory, so the rule doesn’t block `/secrets` on disk. See [Read and Edit rules](</docs/en/permissions#read-and-edit>) for the four anchor forms and how rules from settings files resolve. + +**Auto-approved tools never reach`canUseTool`.** A tool call approved at any earlier step, by `acceptEdits` or `bypassPermissions`, or by an allow rule, skips your `canUseTool` callback, so permission checks you put there are silently bypassed for that tool. `AskUserQuestion`, MCP tools marked [`_meta["anthropic/requiresUserInteraction"]`](</docs/en/mcp#require-approval-for-a-specific-tool>), and connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) still reach the callback, even when an allow rule matches.Coverage depends on the entry’s form: a bare name like `Read` or `mcp__github__get_issue` auto-approves every call to that tool, while a scoped rule like `Bash(ls *)` auto-approves only matching calls and other `Bash` calls still fall through to the callback. For checks that must run on every tool call, use a [`PreToolUse` hook](</docs/en/agent-sdk/hooks>): hooks run before every other step, and a hook deny applies even in `bypassPermissions` mode. + +For a locked-down agent, pair `allowedTools` with `permissionMode: "dontAsk"`. Listed tools are approved, apart from the always-prompt tools in the Warning above; anything else is denied outright instead of prompting: + + const options = { + allowedTools: ["Read", "Glob", "Grep"], + permissionMode: "dontAsk" + }; + +**`allowed_tools` does not constrain `bypassPermissions`.** `allowed_tools` only pre-approves the tools you list. Unlisted tools are not matched by any allow rule and fall through to the permission mode, where `bypassPermissions` approves them. Setting `allowed_tools=["Read"]` alongside `permission_mode="bypassPermissions"` still approves every tool, including `Bash`, `Write`, and `Edit`. If you need `bypassPermissions` but want specific tools blocked, use `disallowed_tools`. + +You can also configure allow, deny, and ask rules declaratively in `.claude/settings.json`. These rules are read when the `project` setting source is enabled, which it is for default `query()` options. If you set `setting_sources` (TypeScript: `settingSources`) explicitly, include `"project"` for them to apply. See [Permission settings](</docs/en/settings#permission-settings>) for the rule syntax. ## @@ -38,514 +90,184 @@ Permission modes -Claude Code supports several permission modes that control how it approves tool calls. See [Permission modes](</docs/en/permission-modes>) for when to use each one. Set the `defaultMode` in your [settings files](</docs/en/settings#settings-files>): - -Mode| Description ----|--- -`default`| Standard behavior: prompts for permission on first use of each tool. Labeled Manual in the CLI, the VS Code and JetBrains extensions, and the desktop app, and Claude Code accepts `manual` as an alias. The label and alias require Claude Code v2.1.200 or later. The desktop app’s label doesn’t depend on your CLI version -`acceptEdits`| Automatically accepts file edits and common filesystem commands such as `mkdir`, `touch`, `mv`, and `cp` for paths in the working directory or `additionalDirectories` -`plan`| Claude reads files and runs read-only shell commands to explore but doesn’t edit your source files; with [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) available, classifier-approved commands also run. Labeled Plan in the CLI and the VS Code extension -`auto`| Auto-approves tool calls with background safety checks that verify actions align with your request -`dontAsk`| Auto-denies tools unless pre-approved via `/permissions` or `permissions.allow` rules. `AskUserQuestion`, connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) are denied even if you’ve allowed them -`bypassPermissions`| Skips permission prompts, except those forced by explicit `ask` rules, connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>). Root and home directory removals such as `rm -rf /` also still prompt as a circuit breaker, and the [cross-session messaging safeguards](</docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode>) still apply - -`bypassPermissions` mode skips permission prompts, including for writes to [protected paths](</docs/en/permission-modes#protected-paths>) such as `.git` and `.claude`. The [cross-session messaging safeguards](</docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode>) still apply. Only use this mode in isolated environments like containers or VMs where Claude Code can’t cause damage.A few prompts still fire in this mode. Explicit `ask` rules, connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) still prompt. Removals targeting the filesystem root or home directory, such as `rm -rf /` and `rm -rf ~`, also prompt as a circuit breaker against model error, including when the command contains command substitution with `$(...)` or backticks, or process substitution with `<(...)`. - -To prevent `bypassPermissions` or `auto` mode from being used, set `permissions.disableBypassPermissionsMode` or `permissions.disableAutoMode` to `"disable"` in any [settings file](</docs/en/settings#settings-files>). These are most useful in managed settings where they can’t be overridden. - -## - -​ - -Permission rule syntax - -Permission rules follow the format `Tool` or `Tool(specifier)`. +Permission modes provide global control over how Claude uses tools. You can set the permission mode when calling `query()` or change it dynamically during streaming sessions. ### ​ -Match all uses of a tool - -To match all uses of a tool, use only the tool name without parentheses: - -Rule| Effect ----|--- -`Bash`| Matches all Bash commands -`WebFetch`| Matches all web fetch requests -`Read`| Matches all file reads - -`Bash(*)` is equivalent to `Bash` and matches all Bash commands. As a deny rule, both forms remove the tool from Claude’s context. +Available modes + +The SDK supports these permission modes: + +Mode| Description| Tool behavior +---|---|--- +`default`| Standard permission behavior| No auto-approvals; unmatched tools trigger your `canUseTool` callback +`dontAsk`| Deny instead of prompting| Anything not pre-approved by `allowed_tools` or rules is denied; connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) and tools that require user interaction are denied even if you’ve pre-approved them. `canUseTool` is never called +`acceptEdits`| Auto-accept file edits| File edits and filesystem operations (`mkdir`, `rm`, `mv`, etc.) are automatically approved +`bypassPermissions`| Bypass permission checks| Tools run without permission prompts, except tools matched by an explicit `ask` rule, connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), and tools that require user interaction. The [cross-session messaging safeguards](</docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode>) still apply. Use with caution +`plan`| Planning mode| Claude explores and plans without editing your source files; file edits are never auto-approved and prompt through your `canUseTool` callback +`auto`| Model-classified approvals| A model classifier approves or denies permission prompts. See [Auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) for availability + +**Subagent inheritance:** Subagents inherit the parent session’s permission mode. An [`AgentDefinition`’s `permissionMode`](</docs/en/agent-sdk/typescript#agentdefinition>) can override it, except when the parent uses `bypassPermissions`, `acceptEdits`, or `auto`: those modes apply to every subagent and can’t be overridden per subagent.Subagents may have different system prompts and less constrained behavior than your main agent, so inheriting `bypassPermissions` grants them full, autonomous system access. Explicit `ask` rules, connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), and tools that require user interaction still force a prompt, as does the [`isolatePeerMachines`](</docs/en/settings#available-settings>) approval for cross-machine messages. ### ​ -Use specifiers for fine-grained control - -Add a specifier in parentheses to match specific tool uses: - -Rule| Effect ----|--- -`Bash(npm run build)`| Matches the exact command `npm run build` -`Read(./.env)`| Matches reading the `.env` file in the current directory -`WebFetch(domain:example.com)`| Matches fetch requests to example.com - -### - -​ - -Match by input parameter - -Deny and ask rules can match a top-level input parameter on any tool with `Tool(param:value)`. The rule matches when Claude calls the tool with that parameter set to that exact value. An allow rule for one parameter value wouldn’t establish that the call is safe overall, so allow rules continue to use each tool’s own specifier syntax. This works for any scalar parameter the tool accepts: - -Rule| Matches ----|--- -`Agent(model:opus)`| Agent calls that request the Opus model tier -`Agent(isolation:worktree)`| Agent calls that request a git worktree -`Bash(run_in_background:true)`| Bash calls that run in the background - -Parameter matching follows these rules: - - * The parameter name must be a direct field of the tool’s input, such as `model` on the Agent tool. Fields nested inside an object or array are not matchable - * Each rule names one parameter. To gate on both `model` and `isolation`, write two rules, `Agent(model:opus)` and `Agent(isolation:worktree)`, rather than combining them in one rule - * The value supports `*` as a wildcard that matches any sequence of characters, so `Agent(isolation:*)` matches any explicit isolation value. Without `*` the match is exact - * A parameter the model omits is never matched, so `Agent(model:*)` doesn’t match a call that leaves `model` unset - * The value is compared against the literal input Claude sends, before any normalization. `Agent(model:opus)` matches the alias `opus` but not a full model ID. Run with [`--verbose`](</docs/en/cli-reference>) to see the exact parameter names and values in each tool call - * Whitespace around the colon is ignored - -You can’t match a tool’s primary content field this way: `command` for Bash and PowerShell, `file_path` for Read, Edit, and Write, `path` for Grep and Glob, `notebook_path` for NotebookEdit, and `url` for WebFetch. A rule like `Bash(command:rm *)` would be bypassable by a compound command, so Claude Code ignores it and emits a startup warning. Use `Bash(rm *)`, `Read(./path)`, or `WebFetch(domain:host)` instead. - -### - -​ - -Wildcard patterns - -Bash rules support glob patterns with `*`. This configuration allows npm and git commit commands while blocking git push: - - { - "permissions": { - "allow": [ - "Bash(npm run *)", - "Bash(git commit *)", - "Bash(git * main)", - "Bash(* --version)", - "Bash(* --help *)" - ], - "deny": [ - "Bash(git push *)" - ] +Set permission mode + +You can set the permission mode once when starting a query, or change it dynamically while the session is active. + + * At query time + + * During streaming + +Pass `permission_mode` (Python) or `permissionMode` (TypeScript) when creating a query. This mode applies for the entire session unless changed dynamically. + +Python + +TypeScript + + import asyncio + from claude_agent_sdk import query, ClaudeAgentOptions + + async def main(): + async for message in query( + prompt="Help me refactor this code", + options=ClaudeAgentOptions( + permission_mode="default", # Set the mode here + ), + ): + if hasattr(message, "result"): + print(message.result) + + asyncio.run(main()) + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + async function main() { + for await (const message of query({ + prompt: "Help me refactor this code", + options: { + permissionMode: "default" // Set the mode here + } + })) { + if ("result" in message) { + console.log(message.result); + } } } -The `:*` suffix is an equivalent way to write a trailing wildcard, so `Bash(ls:*)` matches the same commands as `Bash(ls *)`. The permission dialog writes the space-separated form when you select “Yes, don’t ask again” for a command prefix. The `:*` form is only recognized at the end of a pattern. In a pattern like `Bash(git:* push)`, the colon is treated as a literal character and won’t match git commands. - -### - -​ - -Tool name wildcards - -Deny and ask rules also accept glob patterns in the tool-name position. The pattern must match the full tool name: `"*"` matches every tool, and `"mcp__*"` matches every MCP tool across all servers. A tool matched by a bare-name glob deny rule is removed from Claude’s context, the same as a bare tool name, including the [`EndConversation`](</docs/en/tools-reference#endconversation-tool-behavior>) exception: a glob deny can’t remove it while any other tool remains, and a glob ask never prompts for it. This configuration denies every MCP tool: - - { - "permissions": { - "deny": [ - "mcp__*" - ] + main(); + +Call `set_permission_mode()` (Python) or `setPermissionMode()` (TypeScript) to change the mode mid-session. The new mode takes effect immediately for all subsequent tool requests. This lets you start restrictive and loosen permissions as trust builds, for example switching to `acceptEdits` after reviewing Claude’s initial approach. + +Python + +TypeScript + + import asyncio + from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions + + async def main(): + async with ClaudeSDKClient( + options=ClaudeAgentOptions( + permission_mode="default", # Start in default mode + ) + ) as client: + await client.query("Help me refactor this code") + + # Change mode dynamically mid-session + await client.set_permission_mode("acceptEdits") + + # Process messages with the new permission mode + async for message in client.receive_response(): + if hasattr(message, "result"): + print(message.result) + + asyncio.run(main()) + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + async function main() { + const q = query({ + prompt: "Help me refactor this code", + options: { + permissionMode: "default" // Start in default mode + } + }); + + // Change mode dynamically mid-session + await q.setPermissionMode("acceptEdits"); + + // Process messages with the new permission mode + for await (const message of q) { + if ("result" in message) { + console.log(message.result); + } } } -Allow rules accept tool-name globs only after a literal `mcp__<server>__` prefix. The server segment must be glob-free so the rule names a specific server you configured. `mcp__puppeteer__*` matches every tool from the `puppeteer` server, and `mcp__github__get_*` matches its `get_` tools. An unanchored allow glob such as `"*"`, `"B*"`, or `"mcp__*"` is skipped with a warning and doesn’t auto-approve anything. A deny or ask rule whose tool name matches no known tool produces a startup warning to catch typos. Tool names containing `_` or `*` are exempt from the check. The label shown for a tool in the transcript and permission dialog can differ from its canonical name. For example, the tool labeled `Stop Task` in the transcript has the canonical name `TaskStop`. Permission rules and [hook matchers](</docs/en/hooks>) match the canonical name only, so a rule written as `Stop Task` doesn’t match. For deny and ask rules, the startup warning above catches the mismatch. Use the canonical names listed in the [tools reference](</docs/en/tools-reference>). - -## - -​ - -Tool-specific permission rules + main(); ### ​ -Bash - -Bash permission rules support wildcard matching with `*`. Wildcards can appear at any position in the command, including at the beginning, middle, or end: - - * `Bash(npm run build)` matches the exact Bash command `npm run build` - * `Bash(npm run test *)` matches Bash commands starting with `npm run test` - * `Bash(npm *)` matches any command starting with `npm ` - * `Bash(* install)` matches any command ending with ` install` - * `Bash(git * main)` matches commands like `git checkout main` and `git log --oneline main` - -A single `*` matches any sequence of characters including spaces, so one wildcard can span multiple arguments. `Bash(git *)` matches `git log --oneline --all`, and `Bash(git * main)` matches `git push origin main` as well as `git merge main`. When `*` appears at the end with a space before it (like `Bash(ls *)`), it enforces a word boundary, requiring the prefix to be followed by a space or end-of-string. For example, `Bash(ls *)` matches `ls -la` but not `lsof`. In contrast, `Bash(ls*)` without a space matches both `ls -la` and `lsof` because there’s no word boundary constraint. - -#### - -​ - -Compound commands - -Claude Code is aware of shell operators, so a rule like `Bash(safe-cmd *)` won’t give it permission to run the command `safe-cmd && other-cmd`. The recognized command separators are `&&`, `||`, `;`, `|`, `|&`, `&`, and newlines. A rule must match each subcommand independently. - -When you approve a compound command with “Yes, don’t ask again”, Claude Code saves a separate rule for each subcommand that requires approval, rather than a single rule for the full compound string. For example, approving `git status && npm test` saves a rule for `npm test`, so future `npm test` invocations are recognized regardless of what precedes the `&&`. Subcommands like `cd` into a subdirectory generate their own Read rule for that path. Up to 5 rules may be saved for a single compound command. - -#### - -​ - -Wrappers - -Before matching Bash rules, Claude Code strips a fixed set of wrappers, so a rule like `Bash(npm test *)` also matches `timeout 30 npm test`. The stripped wrappers are `timeout`, `time`, `nice`, `nohup`, and `stdbuf`, plus the shell builtins `command` and `builtin`, and zsh’s `noglob`. Each runs its argument as the actual command. Two related forms aren’t stripped: the query form `command -v`, which looks up a command rather than running one, and zsh’s `nocorrect`. Claude Code also strips a leading assignment of certain known-safe environment variables, so `Bash(npm test *)` matches `NODE_ENV=test npm test`. An allow rule won’t match past an assignment of any other variable. A deny or ask rule matches past any leading assignment, so `Bash(rm *)` in deny still matches `FOO=bar rm -rf tmp/`. Bare `xargs` is also stripped, so `Bash(grep *)` matches `xargs grep pattern`. Stripping applies only when `xargs` has no flags: an invocation like `xargs -n1 grep pattern` is matched as an `xargs` command, so rules written for the inner command do not cover it. This wrapper list is built in and is not configurable. Development environment runners such as `direnv exec`, `devbox run`, `mise exec`, `npx`, and `docker exec` are not in the list. Because these tools execute their arguments as a command, a rule like `Bash(devbox run *)` matches whatever comes after `run`, including `devbox run rm -rf .`. To approve work inside an environment runner, write a specific rule that includes both the runner and the inner command, such as `Bash(devbox run npm test)`. Add one rule per inner command you want to allow. Exec wrappers such as `watch`, `setsid`, `ionice`, and `flock` always prompt and can’t be auto-approved by a prefix rule like `Bash(watch *)`. The same applies to `find` with `-exec` or `-delete`: a `Bash(find *)` rule doesn’t cover these forms. To approve a specific invocation, write an exact-match rule for the full command string. - -#### - -​ - -Read-only commands - -Claude Code recognizes a built-in set of Bash commands as read-only and runs them without a permission prompt in every mode. These include `ls`, `cat`, `echo`, `pwd`, `head`, `tail`, `grep`, `find`, `wc`, `which`, `diff`, `stat`, `du`, `cd`, and read-only forms of `git`. The set is not configurable; to require a prompt for one of these commands, add an `ask` or `deny` rule for it. Unquoted glob patterns are permitted for commands whose every flag is read-only, so `ls *.ts` and `wc -l src/*.py` run without a prompt. Commands from this set still prompt in these cases: - - * **Unquoted globs for commands with write-capable flags** : commands with write-capable or exec-capable flags, such as `find`, `sort`, `sed`, and `git`, prompt when an unquoted glob is present, because the glob could expand to a flag like `-delete`. - * **`docker` pointed at another daemon**: read-only forms of `docker` prompt when the command carries a flag that selects a different daemon, such as `-H`, `--context`, or Podman’s `--url` and `--connection`. - * **`file` with path-opening flags**: `file` prompts when it passes `-m`/`--magic-file` or `-f`/`--files-from`, because those flags make `file` open the paths named in the flag’s value. - * **Network paths on Windows** : a command whose arguments include a network (UNC) path, such as `\\server\share\file`, prompts because accessing a network path can send your Windows credentials to the host it names. The same check applies to [PowerShell tool](</docs/en/tools-reference#powershell-tool>) commands. - * **Commands the analysis can’t parse** : when Claude Code can’t fully parse a command, it asks for approval instead of treating the command as read-only. Commands longer than 10,000 characters always prompt because they exceed what the analysis parses. - -A `cd` into a path inside your working directory or an additional directory is also read-only, and a compound command like `cd packages/api && ls` runs without a prompt when each part qualifies on its own. Two combinations prompt even when each part is read-only: - - * **`cd` with `git`**: prompts when the `cd` changes into a different directory, since running `git` in a new directory can execute that directory’s hooks. A `cd` whose target resolves to the current working directory is a no-op and doesn’t trigger the prompt. - * **`cd` with an output redirect**: prompts when Claude Code can’t determine which directory the redirect target resolves against after the `cd` runs. A command whose only redirect target is `/dev/null`, such as `cd app; grep -r pattern . 2>/dev/null`, doesn’t prompt, because `/dev/null` doesn’t depend on the working directory. - -Bash permission patterns that try to constrain command arguments are fragile. For example, `Bash(curl http://github.com/ *)` intends to restrict curl to GitHub URLs, but won’t match variations like: - - * Options before URL: `curl -X GET http://github.com/...` - * Different protocol: `curl https://github.com/...` - * Redirects: `curl -L http://short.example.com/xyz`, which redirects to GitHub - * Variables: `URL=http://github.com && curl $URL` - * Extra spaces: `curl http://github.com` - -For more reliable URL filtering, consider: - - * **Restrict Bash network tools** : use deny rules to block `curl`, `wget`, and similar commands, then use the WebFetch tool with `WebFetch(domain:github.com)` permission for allowed domains - * **Use PreToolUse hooks** : implement a hook that validates URLs in Bash commands and blocks disallowed domains - * **Add CLAUDE.md guidance** : describe your allowed curl patterns in `CLAUDE.md`. This shapes what Claude tries but doesn’t enforce a boundary, so pair it with one of the options above - -Note that using WebFetch alone doesn’t prevent network access. If Bash is allowed, Claude can still use `curl`, `wget`, or other tools to reach any URL. - -### - -​ - -PowerShell - -PowerShell permission rules use the same shape as Bash rules. Wildcards with `*` match at any position, the `:*` suffix is equivalent to a trailing ` *`, and a bare `PowerShell` or `PowerShell(*)` matches every command. This configuration allows `Get-ChildItem` and `git commit` commands while blocking `Remove-Item`: - - { - "permissions": { - "allow": [ - "PowerShell(Get-ChildItem *)", - "PowerShell(git commit *)" - ], - "deny": [ - "PowerShell(Remove-Item *)" - ] - } - } - -Common aliases are canonicalized before matching. A rule written for the cmdlet name also matches its aliases, so `PowerShell(Get-ChildItem *)` matches `gci`, `ls`, and `dir` as well. Matching is case-insensitive. Claude Code parses the PowerShell AST and checks each command in a compound command independently. Pipeline operators `|`, statement separators `;`, and on PowerShell 7+ the chain operators `&&` and `||` split a compound command into subcommands. A rule must match every subcommand for the compound command to be allowed. - -### - -​ - -Read and Edit - -`Edit` rules apply to all built-in tools that edit files. Claude makes a best-effort attempt to apply `Read` rules to all built-in tools that read files like Grep and Glob, to `@file` mentions in your prompts, and to the selection and open-file context that a connected [IDE](</docs/en/vs-code#the-built-in-ide-mcp-server>) shares with Claude. A `Read` deny rule also blocks the [Edit tool](</docs/en/errors#file-is-covered-by-a-read-deny-rule>) on the same path, including creating a new file there. Write and NotebookEdit aren’t covered, so add an `Edit` deny rule for paths no tool may change. Requires Claude Code v2.1.208 or later. Claude Code checks file permissions against `Edit(path)` and `Read(path)` rules only. If you write a path rule for `Write`, `NotebookEdit`, `Glob`, or the legacy `MultiEdit` tool instead, Claude Code accepts the rule but never consults it, and [warns at startup](</docs/en/errors#is-not-matched-by-file-permission-checks>), except for a `Glob` rule passed in `--allowedTools`. Use `Edit(docs/**)` in place of `Write(docs/**)`, `NotebookEdit(docs/**)`, or `MultiEdit(docs/**)`, and `Read(docs/**)` in place of `Glob(docs/**)`. Claude Code doesn’t warn about a tool-name rule with no path, such as a deny rule for `Write`; it matches that rule at the tool level everywhere. Requires Claude Code v2.1.210 or later. If you put a deny rule `Write(docs/**)` in project settings, Claude Code prints this startup warning: - - Permission deny rule (.claude/settings.json): Write(docs/**) is not matched by file permission checks — only Edit(path) rules are. Use Edit(docs/**) instead (Edit rules cover all file-editing tools). - -Read and Edit deny rules apply to Claude’s built-in file tools and to file commands Claude Code recognizes in Bash, such as `cat`, `head`, `tail`, and `sed`. They don’t apply to arbitrary subprocesses that read or write files indirectly, like a Python or Node script that opens files itself. For OS-level enforcement that blocks all processes from accessing a path, [enable the sandbox](</docs/en/sandboxing>). - -Read and Edit rules both use [gitignore](<https://git-scm.com/docs/gitignore>) pattern syntax with four distinct pattern types; for single-segment directory patterns, the matching depth also depends on the rule type, described later in this section: - -Pattern| Meaning| Example| Matches ----|---|---|--- -`//path`| Absolute path from filesystem root| `Read(//Users/alice/secrets/**)`| `/Users/alice/secrets/**` -`~/path`| Path from home directory| `Read(~/Documents/*.pdf)`| `/Users/alice/Documents/*.pdf` -`/path`| Path relative to the settings source| `Edit(/src/**/*.ts)`| `<project root>/src/**/*.ts` in project settings -`path` or `./path`| Path relative to current directory| `Read(*.env)`| `<cwd>/*.env` - -A pattern like `/Users/alice/file` isn’t an absolute path. The single leading slash anchors at the settings source, not the filesystem root. Use `//Users/alice/file` for absolute paths. - -A `/path` pattern anchors at a directory associated with the settings source that defines it, so the same rule matches different locations depending on where you put it: - -Rule defined in| `/path` resolves to ----|--- -Project settings at `.claude/settings.json`| `<project root>/path` -Local settings at `.claude/settings.local.json`| `<original cwd>/path` -User settings at `~/.claude/settings.json`| `~/.claude/path` -A file passed with `--settings <file>`| `<directory of file>/path` -CLI flags, `/permissions`, or session rules| `<original cwd>/path` - -Local settings rules anchor at the directory you started Claude Code from, not at the repository root where Claude Code stores the file in v2.1.211 and later. In a session started at the repository root, the two directories are the same; in a [worktree](</docs/en/worktrees>) session, a shared rule such as `Edit(/src/**)` matches that worktree’s own `src/` directory. A deny rule such as `Read(/secrets/**)` in user settings blocks `~/.claude/secrets/**`, not a `secrets` directory in your project. To write a rule in user settings that applies inside every project, use a `//` absolute path or a `~/` home-relative path instead. On Windows, paths are normalized to POSIX form before matching. `C:\Users\alice` becomes `/c/Users/alice`, so use `//c/**/.env` to match `.env` files anywhere on that drive. To match across all drives, use `//**/.env`. Examples: - - * `Edit(/docs/**)`: edits in `<project>/docs/`, not `/docs/` or `<project>/.claude/docs/` - * `Read(~/.zshrc)`: reads your home directory’s `.zshrc` - * `Edit(//tmp/scratch.txt)`: edits the absolute path `/tmp/scratch.txt` - * `Read(src/**)`: as an allow rule, reads from `<current-directory>/src/` only; as a deny or ask rule, matches a `src` directory at any depth under the current directory - -A rule only matches files under its anchor; within that bound, matching depth depends on the pattern shape and, for single-segment directory patterns, the rule type, described below. Bare filenames follow gitignore semantics and match at any depth, so `Read(.env)` and `Read(**/.env)` are equivalent: - -Deny rule| Blocks| Does not block ----|---|--- -`Read(.env)` or `Read(**/.env)`| any `.env` at or under the current directory| `.env` in a parent directory or another project -`Read(//**/.env)`| any `.env` anywhere on the filesystem| nothing; the rule is anchored at the filesystem root - -A relative pattern with a single directory segment, such as `src/**`, matches at different depths depending on the rule type: - - * **Allow rules** : `Edit(src/**)` matches only `<cwd>/src` and the files under it. To allow a directory name at any depth, write `Edit(**/src/**)`. - * **Deny and ask rules** : `Read(secrets/**)` matches a directory named `secrets` at any depth under the current directory, so the rule also applies to nested copies. - -Every other pattern shape matches at the same depth in every rule type: `Edit(/src/**)` and `Edit(src/components/**)` match only at their anchored location, while `Edit(**/src/**)` matches at any depth. The following example shows each pattern shape against a project with a top-level `src/` directory and a nested copy under `vendor/`: - - <current-directory>/ - ├── src/ - │ └── app.ts - └── vendor/ - └── pkg/ - └── src/ - └── lib.js - -Rule| Matches `src/app.ts`| Matches `vendor/pkg/src/lib.js` ----|---|--- -`Edit(src/**)` as an allow rule| Yes| No -`Edit(src/**)` as a deny or ask rule| Yes| Yes -`Edit(/src/**)` in any rule type| Yes| No -`Edit(**/src/**)` in any rule type| Yes| Yes - -In gitignore patterns, `*` matches within a single path segment and can appear at any position in the pattern, while `**` matches across directories. To allow all file access, use only the tool name without parentheses: `Read`, `Edit`, or `Write`. - -When you approve a file path with “Yes, don’t ask again”, Claude Code escapes gitignore pattern characters in that path, such as `[`, `]`, and `*`, so the generated rule matches only the literal path you approved. Rules you write yourself aren’t escaped. Before v2.1.202, Claude Code saved the path unescaped, so a generated rule for a directory named `[2024-06] Reports` could fail to match its own path or match unintended sibling directories. When Claude accesses a symlink, permission rules check two paths: the symlink itself and the file it resolves to. Allow and deny rules treat that pair differently: allow rules fall back to prompting you, while deny rules block outright. - - * **Allow rules** : apply only when both the symlink path and its target match. A symlink inside an allowed directory that points outside it still prompts you. - * **Deny rules** : apply when either the symlink path or its target matches. A symlink that points to a denied file is itself denied. - -For example, with `Read(./project/**)` allowed and `Read(~/.ssh/**)` denied, a symlink at `./project/key` pointing to `~/.ssh/id_rsa` is blocked: the target fails the allow rule and matches the deny rule. - -### - -​ - -WebFetch - -WebFetch rules use a `domain:` prefix and match against the hostname of the requested URL. Matching is case-insensitive, supports `*` wildcards, and strips a trailing `.` from both the rule and the hostname so `example.com.` and `example.com` are treated the same. - - * `WebFetch(domain:example.com)` matches requests to `example.com` - * `WebFetch(domain:*.example.com)` matches any subdomain at any depth, such as `api.example.com` or `a.b.example.com`, but not `example.com` itself - * `WebFetch(domain:*)` matches every domain and is equivalent to a bare `WebFetch` rule - -In any position other than a leading `*.` or a bare `*`, the wildcard matches only the text between two dots. `WebFetch(domain:example.*)` matches `example.org`, where `*` becomes `org`, but not `example.evil.com`, where `*` would have to become `evil.com` and cross a dot. This keeps a trailing wildcard from matching domains an attacker could register. - -### - -​ - -MCP - -MCP rules use the server name as configured in Claude Code, optionally followed by the name of a tool from that server. - - * `mcp__puppeteer` matches any tool provided by the `puppeteer` server - * `mcp__puppeteer__*` uses wildcard syntax and also matches all tools from the `puppeteer` server - * `mcp__puppeteer__puppeteer_navigate` matches the `puppeteer_navigate` tool provided by the `puppeteer` server - -If your organization has set a [claude.ai connector](</docs/en/mcp#organization-controls-on-connector-tools>) tool to `ask`, allow rules for that tool don’t take effect: Claude Code prompts on every call, even in `auto` and `bypassPermissions` modes. In `dontAsk` mode, which never prompts, Claude Code denies the call instead. Connector tools appear as `mcp__claude_ai_<server>__<tool>`. - -### - -​ - -Agent (subagents) - -Use `Agent(AgentName)` rules to control which [subagents](</docs/en/sub-agents>) Claude can use: - - * `Agent(Explore)` matches the Explore subagent - * `Agent(Plan)` matches the Plan subagent - * `Agent(my-custom-agent)` matches a custom subagent named `my-custom-agent` - -Add these rules to the `deny` array in your settings or use the `--disallowedTools` CLI flag to disable specific agents. To disable the Explore agent: - - { - "permissions": { - "deny": ["Agent(Explore)"] - } - } - -### - -​ - -Cd - -`Cd` rules control which directories the [`/cd` command](</docs/en/commands>) can move the session to. `Cd` is not a model-invocable tool: Claude can’t call it, and the rules apply only when you run `/cd` yourself. A bare `Cd` deny rule disables `/cd` entirely. A `Cd(<path-pattern>)` deny rule blocks matching targets. Deny rules check every spelling of the target, including each symlink hop it resolves through, so a rule written for one path also blocks targets that resolve to it. Adding any `Cd` allow rule switches `/cd` to allowlist mode: the resolved target directory must match one of your allow rules, or `/cd` refuses. With no `Cd` rules configured, `/cd` keeps its default behavior and prompts you to trust an unfamiliar directory. Path patterns share the `//`, `~/`, and `/` anchors from Read and Edit rules, but matching is anchored to the whole directory path rather than gitignore-style. `*` matches exactly one path segment and `**` matches across segments. A trailing `/**` also matches its named root. - -Rule| Matches| Does not match ----|---|--- -`Cd(~/code/*)`| `~/code/app`| `~/code/app/src`, `~/code` -`Cd(~/code/**)`| `~/code` and any directory under it| directories outside `~/code` -`Cd(**/node_modules)`| any `node_modules` directory at any depth| `node_modules/pkg` - -## - -​ - -Extend permissions with hooks - -[Claude Code hooks](</docs/en/hooks-guide>) let you register custom shell commands that evaluate permissions at runtime. When Claude Code makes a tool call, PreToolUse hooks run before the permission prompt, for every tool except [`EndConversation`](</docs/en/tools-reference#endconversation-tool-behavior>). The hook output can deny the tool call, force a prompt, or skip the prompt to let the call proceed. Hook decisions don’t bypass permission rules. Claude Code evaluates deny and ask rules regardless of what a PreToolUse hook returns: a matching deny rule blocks the call, and a matching ask rule still prompts even when the hook returned `"allow"` or `"ask"`. This preserves the deny-first precedence described in Manage permissions, including deny rules set in managed settings. Connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) also still prompt when a hook returns `"allow"`. A blocking hook also takes precedence over allow rules. A hook that exits with code 2 stops the tool call before permission rules are evaluated, so the block applies even when an allow rule would otherwise let the call proceed. To run all Bash commands without prompts except for a few you want blocked, add `"Bash"` to your allow list and register a PreToolUse hook that rejects those specific commands. See [Block edits to protected files](</docs/en/hooks-guide#block-edits-to-protected-files>) for a hook script you can adapt. - -## - -​ - -Working directories - -By default, Claude has access to files in the directory where you launched it. You can extend this access: - - * **During startup** : use `--add-dir <path>` CLI argument - * **During session** : use `/add-dir` command - * **Persistent configuration** : add to `additionalDirectories` in [settings files](</docs/en/settings#settings-files>) - -Files in additional directories follow the same permission rules as the original working directory: they become readable without prompts, and file editing permissions follow the current permission mode. In background sessions on macOS, the session host requests access to protected folders such as `~/Desktop`, `~/Documents`, and `~/Downloads` separately from your terminal when Claude needs to read or write files there; if reads there fail with `Operation not permitted`, see [how to grant folder access to background sessions](</docs/en/agent-view#background-sessions-can%E2%80%99t-read-desktop-documents-or-downloads-on-macos>). To change the session’s primary working directory instead of adding another, use [`/cd`](</docs/en/commands>). The `/cd` command requires Claude Code v2.1.169 or later. Unlike `/add-dir`, it relocates the session: the new directory’s `CLAUDE.md` is loaded and `--resume` finds the session from there. - -### - -​ - -Additional directories grant file access, not configuration - -Adding a directory extends where Claude can read and edit files. It doesn’t make that directory a full configuration root: most `.claude/` configuration is not discovered from additional directories, though a few types are loaded as exceptions. These exceptions apply only to directories added with the `--add-dir` flag or the `/add-dir` command. Directories listed in `permissions.additionalDirectories` in a settings file grant file access only and don’t load any of the configuration below. The following configuration types are loaded from `--add-dir` directories: - -Configuration| Loaded from `--add-dir` ----|--- -[Skills](</docs/en/skills>) in `.claude/skills/`| Yes, with live reload -[Subagents](</docs/en/sub-agents>) in `.claude/agents/`| Yes -[Settings](</docs/en/settings>) in `.claude/settings.json` and `.claude/settings.local.json`| `enabledPlugins` and `extraKnownMarketplaces` keys only -[CLAUDE.md](</docs/en/memory>) files, `.claude/rules/`, and `CLAUDE.local.md`| Only when `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1` is set. `CLAUDE.local.md` additionally requires the `local` setting source, which is enabled by default - -Claude Code discovers commands and output styles from the current working directory and its parents, your user directory at `~/.claude/`, and managed settings. Hooks and other `.claude/settings.json` keys load from the current working directory’s `.claude/` folder with no parent-directory fallback, alongside your user `~/.claude/settings.json` and managed settings. `.claude/settings.local.json` loads from the git repository root instead, even when you start Claude Code in a subdirectory; before v2.1.211, it too loaded only from the current working directory. [Agent SDK](</docs/en/agent-sdk/claude-code-features#control-filesystem-settings-with-settingsources>) sessions load it from the working directory in all versions. To share that configuration across projects, use one of these approaches: - - * **User-level configuration** : place files in `~/.claude/agents/`, `~/.claude/output-styles/`, or `~/.claude/settings.json` to make them available in every project - * **Plugins** : package and distribute configuration as a [plugin](</docs/en/plugins>) that teams can install - * **Launch from the config directory** : run Claude Code from the directory containing the `.claude/` configuration you want - -## - -​ - -How permissions interact with sandboxing - -Permissions and [sandboxing](</docs/en/sandboxing>) are complementary security layers: - - * **Permissions** control which tools Claude Code can use and which files or domains it can access. They apply to Bash, Read, Edit, WebFetch, MCP, and every other tool, except that a deny or ask rule can’t block [`EndConversation`](</docs/en/tools-reference#endconversation-tool-behavior>) while any other tool remains. - * **Sandboxing** provides OS-level enforcement that restricts the Bash tool’s filesystem and network access. It applies only to Bash commands and their child processes. - -Use both for defense-in-depth: - - * Permission deny rules block Claude from even attempting to access restricted resources - * Sandbox restrictions prevent Bash commands from reaching resources outside defined boundaries, even if a prompt injection bypasses Claude’s decision-making - * Filesystem restrictions in the sandbox combine the [`sandbox.filesystem`](</docs/en/sandboxing>) settings with Read and Edit deny rules; both are merged into the final sandbox boundary - * Network restrictions combine WebFetch permission rules with the sandbox’s `allowedDomains` and `deniedDomains` lists - -When you enable sandboxing and leave `autoAllowBashIfSandboxed` at its default of `true`, sandboxed Bash commands run without prompting even if your permissions include a bare `Bash` ask rule, or the equivalent `Bash(*)` form: the sandbox boundary substitutes for that whole-tool prompt. In [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>), Claude Code skips this substitution. Without an ask rule, the built-in read-only commands still run without prompting, and any other shell command prompts for approval while you are still planning, or goes to the classifier when [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) is available and `useAutoModeDuringPlan` is on. With a bare `Bash` ask rule, every Bash command prompts, including sandboxed read-only commands, the same as outside sandboxing. Before v2.1.212, the substitution applied in plan mode as well. In v2.1.212 through v2.1.217, those commands prompted even when auto mode was available. These checks still apply: - - * Content-scoped ask rules like `Bash(git push *)` still force a prompt - * Explicit deny rules still apply - * `rm` or `rmdir` commands that target `/`, your home directory, or other critical system paths still trigger a prompt, or a classifier check in [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>); the classifier routing requires Claude Code v2.1.218 or later - -Commands that won’t run sandboxed, such as excluded commands, respect the bare `Bash` ask rule as usual. See [sandbox modes](</docs/en/sandboxing#sandbox-modes>) to change this behavior. - -## - -​ - -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, apart from the exceptions listed in the [settings reference’s precedence section](</docs/en/settings#settings-precedence>). 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. - -### - -​ - -Managed-only settings - -The following settings are only read from managed settings. Placing them in user or project settings files has no effect. - -Setting| Description ----|--- -`allowAllClaudeAiMcps`| When `true`, claude.ai connectors load alongside a deployed `managed-mcp.json` instead of being suppressed by its exclusive control. See [Managed MCP configuration](</docs/en/managed-mcp>) -`allowedChannelPlugins`| Allowlist of channel plugins that may push messages. Replaces the default Anthropic allowlist when set. Requires `channelsEnabled: true`. See [Restrict which channel plugins can run](</docs/en/channels#restrict-which-channel-plugins-can-run>) -`allowManagedHooksOnly`| When `true`, only managed hooks, SDK hooks, and hooks from plugins force-enabled in managed settings `enabledPlugins` are loaded. User, project, and all other plugin hooks are blocked -`allowManagedMcpServersOnly`| When `true`, only `allowedMcpServers` from managed settings are respected. `deniedMcpServers` still merges from all sources. See [Managed MCP configuration](</docs/en/managed-mcp>) -`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 -`sandbox.network.allowManagedDomainsOnly`| When `true`, only `allowedDomains` and `WebFetch(domain:...)` allow rules from managed settings are respected. Non-allowed domains are blocked automatically without prompting the user. Denied domains still merge from all sources -`strictKnownMarketplaces`| Controls which plugin marketplace sources users can add and install plugins from. See [managed marketplace restrictions](</docs/en/plugin-marketplaces#managed-marketplace-restrictions>) -`strictPluginOnlyCustomization`| 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 such as `["skills", "hooks"]` locks only the named ones. See [`strictPluginOnlyCustomization`](</docs/en/settings#strictpluginonlycustomization>) -`wslInheritsWindowsSettings`| When `true` in the Windows HKLM registry key or `C:\Program Files\ClaudeCode\managed-settings.json`, WSL reads managed settings from the Windows policy chain in addition to `/etc/claude-code`. See [Settings files](</docs/en/settings#settings-files>) - -`disableBypassPermissionsMode` is typically placed in managed settings to enforce organizational policy, but it works from any scope. A user can set it in their own settings to lock themselves out of bypass mode. - -On Team and Enterprise plans, an Owner enables or disables [Remote Control](</docs/en/remote-control>) and [web sessions](</docs/en/claude-code-on-the-web>) organization-wide in [Claude Code admin settings](<https://claude.ai/admin-settings/claude-code>). Remote Control can additionally be disabled per device with the [`disableRemoteControl`](</docs/en/settings#available-settings>) setting. Web sessions have no per-device managed settings key. - -## - -​ - -Settings precedence - -Permission rules follow the same [settings precedence](</docs/en/settings#settings-precedence>) as all other Claude Code settings, with managed settings highest: no other level, including command line arguments, can override a managed permission rule. If a tool is denied at any level, no other level can allow it. For example, a managed settings deny can’t be overridden by `--allowedTools`, and `--disallowedTools` can add restrictions beyond what managed settings define. The same holds across settings scopes: if user settings allow a permission and project settings deny it, the deny rule blocks it. The reverse is also true: a user-level deny blocks a project-level allow, because deny rules from any scope are evaluated before allow rules. Embedding hosts can supply additional managed policy via the SDK `managedSettings` option, including permission allow rules unless the admin sets the `allowManaged*Only` locks; [Deliver policy to Claude Desktop sessions](</docs/en/claude-apps-gateway#deliver-policy-to-claude-desktop-sessions>) covers when embedder policy applies at all. - -## - -​ - -Project allow rules and workspace trust - -`permissions.allow` rules and `permissions.additionalDirectories` entries in a project’s `.claude/settings.json` grant capability, so Claude Code applies them only after you accept the [workspace trust dialog](</docs/en/security#additional-safeguards>) for that workspace. Until then, Claude Code reads the rules but doesn’t apply them. The trust dialog lists the allow rules and additional directories the folder would grant so you can review them before accepting. `deny` and `ask` rules aren’t affected, since they only restrict. Claude Code saves trust per workspace, keyed on the git repository root or, outside a repository, the directory you started Claude Code from. When you start in your home directory, trust is held for the current session only and isn’t written to disk; see the [additional safeguards](</docs/en/security#additional-safeguards>) note. Trusting a parent directory doesn’t apply a nested project’s allow rules. `.claude/settings.local.json` is your own file, so the workspace trust check usually doesn’t apply to it. When a repository could have supplied the file, such as when it is committed to git or `.claude` is a symlink, its allow rules and additional directories go through the trust check like project settings. Claude Code runs git to check whether the repository supplied the file, and it runs that check only in a folder covered by an accepted trust dialog, for that folder or for one of its parent directories. In an interactive session in a folder you haven’t trusted yet, allow rules and additional directories in `.claude/settings.local.json` go through the trust check like project settings until you accept the dialog, unless the session runs in your own configuration home as described below. Of the two exceptions below, only the configuration-home exception applies before the dialog, because it doesn’t need to run git. Determining that a directory isn’t inside a git repository uses the same git check, so the not-inside-a-repository exception takes effect once a trust dialog covering the folder is accepted. Before v2.1.207, an untracked `.claude/settings.local.json` applied its allow rules in that folder before you accepted the dialog. Allow rules and additional directories in `.claude/settings.local.json` also apply without workspace trust in two cases: - - * The directory you started Claude Code from isn’t inside a git repository. - * The session runs in your own configuration home: your home directory or any directory whose `.claude` subdirectory you’ve set as [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars>). - -In both cases the file is one you created rather than one a repository could have supplied, and a repository-committed `.claude/settings.local.json` still requires workspace trust. Versions 2.1.196 through 2.1.199 treated the file as repository-supplied in those workspaces, ignored its allow rules, and printed a [`this workspace has not been trusted`](</docs/en/errors#workspace-has-not-been-trusted>) warning to stderr. The two exceptions above match v2.1.195 and earlier and were restored in v2.1.200. Also as of v2.1.200, a workspace whose allow rules or additional directories still aren’t applied, but that never showed the trust dialog because a parent directory was already trusted, shows the dialog the next time you start Claude Code there interactively. The dialog offers two choices: - - * **Yes, I trust this folder** : saves trust for that workspace and applies the rules in the same session. - * **No, continue without these permissions** : keeps working with those rules ignored. The dialog appears again in the next session. - -In [non-interactive mode](</docs/en/headless>) with `-p`, no dialog appears and the rules stay ignored. - -## - -​ - -Example configurations - -This [repository](<https://github.com/anthropics/claude-code/tree/main/examples/settings>) includes starter settings configurations for common deployment scenarios. Use these as starting points and adjust them to fit your needs. - -## - -​ - -See also - - * [Settings](</docs/en/settings>): complete configuration reference including the permission settings table - * [Configure auto mode](</docs/en/auto-mode-config>): tell the auto mode classifier which infrastructure your organization trusts - * [Sandboxing](</docs/en/sandboxing>): OS-level filesystem and network isolation for Bash commands - * [Authentication](</docs/en/authentication>): set up user access to Claude Code - * [Security](</docs/en/security>): security safeguards and best practices - * [Hooks](</docs/en/hooks-guide>): automate workflows and extend permission evaluation +Mode details + +#### + +​ + +Accept edits mode (`acceptEdits`) + +Auto-approves file operations so Claude can edit code without prompting. Other tools (like Bash commands that aren’t filesystem operations) still require normal permissions. **Auto-approved operations:** + + * File edits (Edit, Write tools) + * Filesystem commands: `mkdir`, `touch`, `rm`, `rmdir`, `mv`, `cp`, `sed` + +Both apply only to paths inside the working directory or `additionalDirectories`. Paths outside that scope and writes to protected paths still prompt. **Use when:** you trust Claude’s edits and want faster iteration, such as during prototyping or when working in an isolated directory. + +#### + +​ + +Don’t ask mode (`dontAsk`) + +Converts any permission prompt into a denial. Tools pre-approved by `allowed_tools`, `settings.json` allow rules, or a hook run as normal. Connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) and tools that require user interaction are denied even when an allow rule matches. Everything else is denied without calling `canUseTool`. **Use when:** you want a fixed, explicit tool surface for a headless agent and prefer a hard deny over silent reliance on `canUseTool` being absent. + +#### + +​ + +Bypass permissions mode (`bypassPermissions`) + +Auto-approves tool uses without prompting, except the cases listed in the warning below. Hooks still execute and can block operations if needed. + +Use with extreme caution. Claude has full system access in this mode. Only use in controlled environments where you trust all possible operations.`allowed_tools` does not constrain this mode. Every tool is approved, not just the ones you listed. These controls still apply: + + * Deny rules, explicit `ask` rules, and hooks are evaluated before the mode check and can still block a tool. + * Connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) and tools that require user interaction still fall through to your `canUseTool` callback. + * The [cross-session messaging safeguards](</docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode>) still apply. + +#### + +​ + +Plan mode (`plan`) + +Claude explores the codebase and produces a plan without editing your source files. Read-only tools run as in default mode. File edits are never auto-approved in plan mode, even when an allow rule matches. They prompt through your `canUseTool` callback instead. On Claude Code v2.1.212 or later, shell commands that modify files, such as `touch` and `rm`, reach your `canUseTool` callback the same way. Claude may use `AskUserQuestion` to clarify requirements before finalizing the plan. See [Handle approvals and user input](</docs/en/agent-sdk/user-input#handle-clarifying-questions>) for handling these prompts. **Use when:** you want Claude to propose changes without executing them, such as during code review or when you need to approve changes before they’re made. + +## + +​ + +Related resources + +For the other steps in the permission evaluation flow: + + * [Handle approvals and user input](</docs/en/agent-sdk/user-input>): interactive approval prompts and clarifying questions + * [Hooks guide](</docs/en/agent-sdk/hooks>): run custom code at key points in the agent lifecycle + * [Permission rules](</docs/en/settings#permission-settings>): declarative allow/deny rules in `settings.json`
modified Constrain plugin dependency versions View current →
--- a/plugin-dependencies.md +++ b/plugin-dependencies.md @@ -99,7 +99,7 @@ Tag plugin releases for version resolution -Version constraints resolve against git tags on the marketplace repository. For Claude Code to find a dependency’s available versions, the upstream plugin’s releases must be tagged using a specific naming convention. Tag each release as `{plugin-name}--v{version}`, where `{version}` matches the `version` field in that commit’s `plugin.json`. From the plugin directory, run: +Claude Code resolves version constraints against git tags on the repository that hosts the dependency: the plugin’s own repository for `github`, `url`, and `git-subdir` [plugin sources](</docs/en/plugin-marketplaces#plugin-sources>), or the marketplace repository for a plugin the marketplace references by a relative path. For Claude Code to find a dependency’s available versions, the upstream plugin’s releases must be tagged using a specific naming convention. Tag each release as `{plugin-name}--v{version}`, where `{version}` matches the `version` field in that commit’s `plugin.json`. From the plugin directory, run: claude plugin tag --push @@ -110,14 +110,14 @@ * With `--push`, a successful run ends with `Created tag secrets-vault--v2.1.0` and `Pushed to origin`, where the last line names the remote it pushed to. Without `--push`, the command prints the `git push` command to run instead. * `--dry-run` prints 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: +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 tags on the repository that hosts `secrets-vault`, filters to those starting with `secrets-vault--v`, and fetches the highest version satisfying `~2.1.0`. If no tag on the plugin’s own repository satisfies the range, the install fails with `Dependency "secrets-vault" has no git tag satisfying ~2.1.0`. For a relative-path plugin with no matching tag, Claude Code installs the marketplace’s current copy instead and checks the constraint when the plugin loads. For a plugin the marketplace references by a relative path, 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 dependencies with an `npm` [plugin source](</docs/en/plugin-marketplaces#plugin-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. +For dependencies with an `npm` or `archive` [plugin source](</docs/en/plugin-marketplaces#plugin-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 Plugins in the SDK View current →
Show diff (816 lines)
--- a/plugins.md +++ b/plugins.md @@ -1,483 +1,351 @@ -Plugins let you extend Claude Code with custom functionality that can be shared across projects and teams. This guide covers creating your own plugins with skills, agents, hooks, and MCP servers. Looking to install existing plugins? See [Discover and install plugins](</docs/en/discover-plugins>). For complete technical specifications, see [Plugins reference](</docs/en/plugins-reference>). - -## - -​ - -When to use plugins vs standalone configuration - -Claude Code supports two ways to add custom skills, agents, and hooks: - -Approach| Skill names| Best for ----|---|--- -**Standalone** (`.claude/` directory)| `/hello`| Personal workflows, project-specific customizations, quick experiments -**Plugins** (self-contained directories with skills, agents, hooks, or a `.claude-plugin/plugin.json` manifest)| `/plugin-name:hello`| Sharing with teammates, distributing to community, versioned releases, reusable across projects - -Start with standalone configuration in `.claude/` for quick iteration, then convert to a plugin when you’re ready to share. - -## - -​ - -Quickstart - -This quickstart walks you through creating a plugin with a custom skill. You’ll create a manifest (the configuration file that defines your plugin), add a skill, and test it locally using the `--plugin-dir` flag. +Plugins allow you to extend Claude Code with custom functionality that can be shared across projects. Through the Agent SDK, you can programmatically load plugins from local directories to add skills, agents, hooks, and MCP servers to your agent sessions. + +## + +​ + +What are plugins? + +Plugins are packages of Claude Code extensions that can include: + + * **Skills** : Model-invoked capabilities that Claude uses autonomously (can also be invoked with `/skill-name`) + * **Agents** : Specialized subagents for specific tasks + * **Hooks** : Event handlers that respond to tool use and other events + * **MCP servers** : External tool integrations via Model Context Protocol + +The `commands/` directory is a legacy format. Use `skills/` for new plugins. Claude Code continues to support both formats for backward compatibility. + +For complete information on plugin structure and how to create plugins, see [Plugins](</docs/en/plugins>). + +## + +​ + +Loading plugins + +Load plugins by providing their local file system paths in your options configuration. The `type` field must be `"local"`, the only value the SDK accepts. The SDK supports loading multiple plugins from different locations. To use a plugin distributed through a [marketplace](</docs/en/plugin-marketplaces>) or remote repository, download it first and provide the local directory path. For the directory layout a plugin needs, see the Plugin structure reference below. + +TypeScript + +Python + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + for await (const message of query({ + prompt: "Hello", + options: { + plugins: [ + { type: "local", path: "./my-plugin" }, + { type: "local", path: "/absolute/path/to/another-plugin" } + ] + } + })) { + // Plugin commands, agents, and other features are now available + } + + import asyncio + from claude_agent_sdk import query, ClaudeAgentOptions + + async def main(): + async for message in query( + prompt="Hello", + options=ClaudeAgentOptions( + plugins=[ + {"type": "local", "path": "./my-plugin"}, + {"type": "local", "path": "/absolute/path/to/another-plugin"}, + ] + ), + ): + # Plugin commands, agents, and other features are now available + pass + + asyncio.run(main()) ### ​ -Prerequisites - - * Claude Code [installed and authenticated](</docs/en/quickstart#step-1-install-claude-code>) - -### - -​ - -Create your first plugin - -1 - -Create the plugin directory - -Every plugin lives in its own directory containing your skills, agents, or hooks, optionally alongside a `.claude-plugin/plugin.json` manifest. The location doesn’t matter for this quickstart because you’ll point Claude Code at the directory with `--plugin-dir` in the test step. Create it anywhere convenient, such as a scratch folder or a projects directory: - - mkdir my-first-plugin - -The remaining steps run from the parent directory and reference paths like `my-first-plugin/...` relative to it. - -2 - -Create the plugin manifest - -The manifest file at `.claude-plugin/plugin.json` defines your plugin’s identity: its name, description, and version. Claude Code uses this metadata to display your plugin in the plugin manager.Create the `.claude-plugin` directory inside your plugin folder: - - mkdir my-first-plugin/.claude-plugin - -Then create `my-first-plugin/.claude-plugin/plugin.json` with this content: - -my-first-plugin/.claude-plugin/plugin.json - - { - "name": "my-first-plugin", - "description": "A greeting plugin to learn the basics", - "version": "1.0.0", - "author": { - "name": "Your Name" +Path specifications + +Plugin paths can be: + + * **Relative paths** : Resolved relative to your current working directory (for example, `"./plugins/my-plugin"`) + * **Absolute paths** : Full file system paths (for example, `"/home/user/plugins/my-plugin"`) + +The path should point to the plugin’s root directory: the parent of `skills/`, `agents/`, `hooks/`, `commands/` (legacy), or `.claude-plugin/`, not a subdirectory. + +## + +​ + +Verifying plugin installation + +When plugins load successfully, they appear in the system initialization message. You can verify that your plugins are available: + +TypeScript + +Python + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + for await (const message of query({ + prompt: "Hello", + options: { + plugins: [{ type: "local", path: "./my-plugin" }] + } + })) { + if (message.type === "system" && message.subtype === "init") { + // Check loaded plugins + console.log("Plugins:", message.plugins); + // Example: [{ name: "my-plugin", path: "/absolute/path/to/my-plugin" }] + + // Plugin skills appear with the plugin name as a prefix + console.log("Skills:", message.skills); + // Example: ["my-plugin:greet"] + + // Plugin commands use the same prefix, and skills appear here too + console.log("Commands:", message.slash_commands); + // Example: ["compact", "context", "my-plugin:custom-command", "my-plugin:greet"] } } -Field| Purpose ----|--- -`name`| Unique identifier and skill namespace. Skills are prefixed with this (e.g., `/my-first-plugin:hello`). -`description`| Shown in the plugin manager when browsing or installing plugins. -`version`| Optional. If set, users only receive updates when you bump this field. If omitted, the version comes from the next source in [version management](</docs/en/plugins-reference#version-management>). -`author`| Optional. Helpful for attribution. - -For additional fields like `homepage`, `repository`, and `license`, see the [full manifest schema](</docs/en/plugins-reference#plugin-manifest-schema>). - -3 - -Add a skill - -Skills live in the `skills/` directory. Each skill is a folder containing a `SKILL.md` file. The folder name becomes the skill name, prefixed with the plugin’s namespace (`hello/` in a plugin named `my-first-plugin` creates `/my-first-plugin:hello`).Create a skill directory in your plugin folder: - - mkdir -p my-first-plugin/skills/hello - -Then create `my-first-plugin/skills/hello/SKILL.md` with this content: - -my-first-plugin/skills/hello/SKILL.md - - --- - description: Greet the user with a friendly message - disable-model-invocation: true - --- - - Greet the user warmly and ask how you can help them today. - -4 - -Test your plugin - -Run Claude Code with the `--plugin-dir` flag to load your plugin: - - claude --plugin-dir ./my-first-plugin - -Once Claude Code starts, try your new skill: - - /my-first-plugin:hello - -You’ll see Claude respond with a greeting. Run `/help` and open the **Custom commands** tab to see your skill listed under the plugin namespace. - -**Why namespacing?** Plugin skills are always namespaced (like `/my-first-plugin:hello`) to prevent conflicts when multiple plugins have skills with the same name.To change the namespace prefix, update the `name` field in `plugin.json`. - -5 - -Add skill arguments - -Make your skill dynamic by accepting user input. The `$ARGUMENTS` placeholder captures any text the user provides after the skill name.Update your `SKILL.md` file: - -my-first-plugin/skills/hello/SKILL.md - - --- - description: Greet the user with a personalized message - --- - - # Hello Skill - - Greet the user named "$ARGUMENTS" warmly and ask how you can help them today. Make the greeting personal and encouraging. - -Run `/reload-plugins` to pick up the changes. The skills count in the summary covers only `commands/` directories, so it can report `0 skills` even though the skill you just edited reloaded. Then try the skill with your name: - - /my-first-plugin:hello Alex - -Claude will greet you by name. For more on passing arguments to skills, see [Skills](</docs/en/skills#pass-arguments-to-skills>). - -The `--plugin-dir` flag is useful for development and testing. When you’re ready to share your plugin with others, see [Create and distribute a plugin marketplace](</docs/en/plugin-marketplaces>). - -## - -​ - -Develop a plugin in your skills directory - -Instead of passing `--plugin-dir` on every launch, you can keep a plugin in your skills directory and have Claude Code load it automatically. `claude plugin init` scaffolds one: - - claude plugin init my-tool - -This creates `~/.claude/skills/my-tool/` with a `.claude-plugin/plugin.json` manifest and a starter `SKILL.md`. On the next session it loads as `my-tool@skills-dir` with no marketplace or install step. For the auto-load rules, personal vs. project scope, the workspace-trust requirement, and how to update or remove one, see [Skills-directory plugins](</docs/en/plugins-reference#skills-directory-plugins>). - -## - -​ - -Plugin structure overview - -You’ve created a plugin with a skill, but plugins can include much more: custom agents, hooks, MCP servers, LSP servers, and background monitors. - -**Common mistake** : Don’t put `commands/`, `agents/`, `skills/`, or `hooks/` inside the `.claude-plugin/` directory. Only `plugin.json` goes inside `.claude-plugin/`. All other directories must be at the plugin root level.The plugin root is the individual plugin’s own directory: the one you pass to `--plugin-dir` or that contains `.claude-plugin/plugin.json`. It is never `~/.claude/`. For example, Claude Code doesn’t read a `.mcp.json` placed at `~/.claude/.mcp.json`. - -Directory| Location| Purpose ----|---|--- -`.claude-plugin/`| Plugin root| Contains `plugin.json` manifest (optional if components use default locations) -`skills/`| Plugin root| Skills as `<name>/SKILL.md` directories -`commands/`| Plugin root| Skills as flat Markdown files. Use `skills/` for new plugins -`agents/`| Plugin root| Custom agent definitions -`hooks/`| Plugin root| Event handlers in `hooks.json` -`.mcp.json`| Plugin root| MCP server configurations -`.lsp.json`| Plugin root| LSP server configurations for code intelligence -`monitors/`| Plugin root| Background monitor configurations in `monitors.json` -`bin/`| Plugin root| Executables added to the Bash tool’s `PATH` while the plugin is enabled -`settings.json`| Plugin root| Default [settings](</docs/en/settings>) applied when the plugin is enabled - -A plugin that ships exactly one skill can place `SKILL.md` directly at the plugin root instead of creating a `skills/` directory. Claude Code loads it as a single skill and uses the frontmatter `name` field for the invocation name. Use the `skills/` layout for plugins that may grow to more than one skill. - -**Next steps** : Ready to add more features? Jump to Develop more complex plugins to add agents, hooks, MCP servers, and LSP servers. For complete technical specifications of all plugin components, see [Plugins reference](</docs/en/plugins-reference>). - -## - -​ - -Develop more complex plugins - -Once you’re comfortable with basic plugins, you can create more sophisticated extensions. - -### - -​ - -Add Skills to your plugin - -Plugins can include [Agent Skills](</docs/en/skills>) to extend Claude’s capabilities. Skills are model-invoked: Claude automatically uses them based on the task context. Add a `skills/` directory at your plugin root with Skill folders containing `SKILL.md` files: + import asyncio + from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage + + async def main(): + async for message in query( + prompt="Hello", + options=ClaudeAgentOptions( + plugins=[{"type": "local", "path": "./my-plugin"}] + ), + ): + if isinstance(message, SystemMessage) and message.subtype == "init": + # Check loaded plugins + print("Plugins:", message.data.get("plugins")) + # Example: [{"name": "my-plugin", "path": "/absolute/path/to/my-plugin"}] + + # Plugin skills appear with the plugin name as a prefix + print("Skills:", message.data.get("skills")) + # Example: ["my-plugin:greet"] + + # Plugin commands use the same prefix, and skills appear here too + print("Commands:", message.data.get("slash_commands")) + # Example: ["compact", "context", "my-plugin:custom-command", "my-plugin:greet"] + + asyncio.run(main()) + +## + +​ + +Using plugin skills + +Skills from plugins are automatically namespaced with the plugin name to avoid conflicts. To invoke one directly, send `/plugin-name:skill-name` as the prompt. + +TypeScript + +Python + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + // Load a plugin with a custom /greet skill + for await (const message of query({ + prompt: "/my-plugin:greet", // Use plugin skill with namespace + options: { + plugins: [{ type: "local", path: "./my-plugin" }] + } + })) { + // Claude executes the custom greeting skill from the plugin + if (message.type === "assistant") { + console.log(message.message.content); + } + } + + import asyncio + from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, TextBlock + + async def main(): + # Load a plugin with a custom /greet skill + async for message in query( + prompt="/my-plugin:greet", # Use plugin skill with namespace + options=ClaudeAgentOptions( + plugins=[{"type": "local", "path": "./my-plugin"}] + ), + ): + # Claude executes the custom greeting skill from the plugin + if isinstance(message, AssistantMessage): + for block in message.content: + if isinstance(block, TextBlock): + print(f"Claude: {block.text}") + + asyncio.run(main()) + +If you installed a plugin via the CLI (for example, `/plugin install my-plugin@marketplace`), you can still use it in the SDK by providing its installation path. Check `~/.claude/plugins/` for CLI-installed plugins. + +## + +​ + +Complete example + +Here’s a full example demonstrating plugin loading and usage: + +TypeScript + +Python + + import { query } from "@anthropic-ai/claude-agent-sdk"; + import { fileURLToPath } from "node:url"; + + async function runWithPlugin() { + const pluginPath = fileURLToPath(new URL("./plugins/my-plugin", import.meta.url)); + + console.log("Loading plugin from:", pluginPath); + + for await (const message of query({ + prompt: "What custom commands do you have available?", + options: { + plugins: [{ type: "local", path: pluginPath }], + maxTurns: 3 + } + })) { + if (message.type === "system" && message.subtype === "init") { + console.log("Loaded plugins:", message.plugins); + console.log("Available skills:", message.skills); + console.log("Available commands:", message.slash_commands); + } + + if (message.type === "assistant") { + console.log("Assistant:", message.message.content); + } + } + } + + runWithPlugin().catch(console.error); + + #!/usr/bin/env python3 + """Example demonstrating how to use plugins with the Agent SDK.""" + + import asyncio + from pathlib import Path + + from claude_agent_sdk import ( + AssistantMessage, + ClaudeAgentOptions, + SystemMessage, + TextBlock, + query, + ) + + async def run_with_plugin(): + """Example using a custom plugin.""" + plugin_path = Path(__file__).parent / "plugins" / "my-plugin" + + print(f"Loading plugin from: {plugin_path}") + + options = ClaudeAgentOptions( + plugins=[{"type": "local", "path": str(plugin_path)}], + max_turns=3, + ) + + async for message in query( + prompt="What custom commands do you have available?", options=options + ): + if isinstance(message, SystemMessage) and message.subtype == "init": + print(f"Loaded plugins: {message.data.get('plugins')}") + print(f"Available skills: {message.data.get('skills')}") + print(f"Available commands: {message.data.get('slash_commands')}") + + if isinstance(message, AssistantMessage): + for block in message.content: + if isinstance(block, TextBlock): + print(f"Assistant: {block.text}") + + if __name__ == "__main__": + asyncio.run(run_with_plugin()) + +## + +​ + +Plugin structure reference + +A plugin directory typically contains a `.claude-plugin/plugin.json` manifest file. The manifest is optional. When omitted, Claude Code auto-discovers components from the directory layout. The directory can include: my-plugin/ ├── .claude-plugin/ - │ └── plugin.json - └── skills/ - └── code-review/ - └── SKILL.md - -Each `SKILL.md` contains YAML frontmatter and instructions. Include a `description` so Claude knows when to use the skill: - - --- - description: Reviews code for best practices and potential issues. Use when reviewing code, checking PRs, or analyzing code quality. - --- - - When reviewing code, check for: - 1. Code organization and structure - 2. Error handling - 3. Security concerns - 4. Test coverage - -After you install the plugin, check the install summary: if it reports `Run /reload-plugins to activate.`, run that command to load the Skills. For complete Skill authoring guidance including progressive disclosure and tool restrictions, see [Agent Skills](</docs/en/skills>). + │ └── plugin.json # Plugin manifest (optional, components auto-discovered without it) + ├── skills/ # Agent Skills (invoked autonomously or via /skill-name) + │ └── my-skill/ + │ └── SKILL.md + ├── commands/ # Legacy: use skills/ instead + │ └── custom-cmd.md + ├── agents/ # Custom agents + │ └── specialist.md + ├── hooks/ # Event handlers + │ └── hooks.json + └── .mcp.json # MCP server definitions + +## + +​ + +Multiple plugin sources + +Combine plugins from different locations: + + import * as os from "node:os"; + import * as path from "node:path"; + + plugins: [ + { type: "local", path: "./local-plugin" }, + { + type: "local", + path: path.join(os.homedir(), ".claude", "custom-plugins", "shared-plugin") + } + ]; + +The SDK doesn’t expand tilde paths like `~/plugins`. If a plugin path doesn’t exist, the SDK skips that plugin and the session continues, so check the `plugins` list in the init message to confirm each plugin loaded. + +## + +​ + +Troubleshooting ### ​ -Add LSP servers to your plugin - -For common languages like TypeScript, Python, and Rust, install the pre-built LSP plugins from the official marketplace. Create custom LSP plugins only when you need support for languages not already covered. - -LSP (Language Server Protocol) plugins give Claude real-time code intelligence. If you need to support a language that doesn’t have an official LSP plugin, you can create your own by adding an `.lsp.json` file to your plugin: - -.lsp.json - - { - "go": { - "command": "gopls", - "args": ["serve"], - "extensionToLanguage": { - ".go": "go" - } - } - } - -Users installing your plugin must have the language server binary installed on their machine. To confirm the server starts, launch Claude Code with the plugin enabled and check the `/plugin` Errors tab: a language server that fails to start appears there, for example with `Executable not found in $PATH` when the binary isn’t installed. An entry with an invalid configuration is skipped instead; run `claude --debug` to see why. For complete LSP configuration options, see [LSP servers](</docs/en/plugins-reference#lsp-servers>). +Plugin not loading + +If your plugin doesn’t appear in the init message: + + 1. **Check the path** : ensure the path points to the plugin root directory, the parent of `skills/`, `agents/`, `hooks/`, `commands/` (legacy), or `.claude-plugin/` + 2. **Validate plugin.json** : if your plugin includes a manifest, ensure it has valid JSON syntax + 3. **Check file permissions** : ensure the plugin directory is readable + 4. **Confirm the directory exists** : the SDK skips a nonexistent path, and the plugin doesn’t appear in the init message’s `plugins` list ### ​ -Add background monitors to your plugin - -Background monitors let your plugin watch logs, files, or external status in the background and notify Claude as events arrive. Claude Code starts each monitor automatically when the plugin is active, so you don’t need to instruct Claude to start the watch. Add a `monitors/monitors.json` file at the plugin root with an array of monitor entries: - -monitors/monitors.json - - [ - { - "name": "error-log", - "command": "tail -F ./logs/error.log", - "description": "Application error log" - } - ] - -Each stdout line from `command` is delivered to Claude as a notification during the session. For the full schema, including the `when` trigger and variable substitution, see [Monitors](</docs/en/plugins-reference#monitors>). - -### - -​ - -Ship default settings with your plugin - -Plugins can include a `settings.json` file at the plugin root to apply default configuration when the plugin is enabled. Currently, only the `agent` and `subagentStatusLine` keys are supported. Setting `agent` activates one of the plugin’s [custom agents](</docs/en/sub-agents>) as the main thread, applying its system prompt, tool restrictions, and model. This lets a plugin change how Claude Code behaves by default when enabled. - -settings.json - - { - "agent": "security-reviewer" - } - -This example activates the `security-reviewer` agent defined in the plugin’s `agents/` directory. Settings from `settings.json` take priority over `settings` declared in `plugin.json`. Unknown keys are silently ignored. - -### - -​ - -Organize complex plugins - -For plugins with many components, organize your directory structure by functionality. For complete directory layouts and organization patterns, see [Plugin directory structure](</docs/en/plugins-reference#plugin-directory-structure>). - -### - -​ - -Test your plugins locally - -Use the `--plugin-dir` flag to test plugins during development. This loads your plugin directly without requiring installation. - - claude --plugin-dir ./my-plugin - -The flag also accepts a `.zip` archive of the plugin directory. - - claude --plugin-dir ./my-plugin.zip - -When a `--plugin-dir` plugin has the same name as an installed marketplace plugin, the local copy takes precedence for that session. This lets you test changes to a plugin you already have installed without uninstalling it first. The exception is plugins that managed settings force-enable or force-disable: `--plugin-dir` cannot override those. As you make changes to your plugin, run `/reload-plugins` to pick up the updates without restarting. This reloads plugins, skills, agents, hooks, plugin MCP servers, and plugin LSP servers. Test your plugin components: - - * Try your skills with `/plugin-name:skill-name` - * Check that agents appear in `/context` under Custom Agents, or @-mention one by its scoped name - * Trigger the event each hook matches, such as asking Claude to edit a file for a `PostToolUse` hook, and confirm its effect. Claude Code records which hooks matched, their exit codes, and their output in the [debug log](</docs/en/hooks#debug-hooks>) - -You can load multiple plugins at once by specifying the flag multiple times: - - claude --plugin-dir ./plugin-one --plugin-dir ./plugin-two - -To test a plugin that is already packaged as a `.zip` archive and hosted at a URL, such as a CI build artifact, use `--plugin-url` instead. Claude Code fetches the archive at startup and loads it for that session only. If Claude Code can’t fetch the archive, or the archive is invalid, it starts without the plugin and records a plugin load error that you can review in the `/plugin` manager’s **Errors** tab. The same [trust considerations](</docs/en/discover-plugins#security>) apply as for any plugin source: only point this flag at archives you control or trust. To load multiple plugins, repeat the flag for each URL: - - claude --plugin-url https://example.com/my-plugin.zip --plugin-url https://example.com/other.zip - -Or pass space-separated URLs as one quoted argument: - - claude --plugin-url "https://example.com/my-plugin.zip https://example.com/other.zip" - -### - -​ - -Debug plugin issues - -If your plugin isn’t working as expected: - - 1. **Check the structure** : Ensure your directories are at the plugin root, not inside `.claude-plugin/` - 2. **Test components individually** : Check each skill, agent, and hook separately - 3. **Use validation and debugging tools** : See [Debugging and development tools](</docs/en/plugins-reference#debugging-and-development-tools>) for CLI commands and troubleshooting techniques - -### - -​ - -Share your plugins - -When your plugin is ready to share: - - 1. **Add documentation** : Include a `README.md` with installation and usage instructions - 2. **Choose a versioning strategy** : Decide whether to set an explicit `version` or rely on the fallback described in [version management](</docs/en/plugins-reference#version-management>). - 3. **Create or use a marketplace** : Distribute through [plugin marketplaces](</docs/en/plugin-marketplaces>) for installation - 4. **Test with others** : Have team members test the plugin before wider distribution - -Once your plugin is in a marketplace, others can install it using the instructions in [Discover and install plugins](</docs/en/discover-plugins>). To keep a plugin internal to your team, host the marketplace in a [private repository](</docs/en/plugin-marketplaces#private-repositories>). - -### - -​ - -Submit your plugin to the community marketplace - -Anthropic maintains two public marketplaces for Claude Code plugins: - - * **`claude-plugins-official`** : a curated set of plugins maintained by Anthropic. Claude Code registers it automatically the first time you start Claude Code interactively. If you run Claude Code non-interactively before that first interactive launch, or a [marketplace policy](</docs/en/plugin-marketplaces#managed-marketplace-restrictions>) blocked an earlier attempt, register it yourself with `claude plugin marketplace add anthropics/claude-plugins-official`. - * **`claude-community`** : the public community marketplace where third-party submissions land after review. Users add it with `/plugin marketplace add anthropics/claude-plugins-community` and install from it as `@claude-community`. - -To submit your plugin for community-marketplace review, use one of the in-app forms: - - * **claude.ai** : [claude.ai/admin-settings/directory/submissions/plugins/new](<https://claude.ai/admin-settings/directory/submissions/plugins/new>) - * **Console** : [platform.claude.com/plugins/submit](<https://platform.claude.com/plugins/submit>) - -The claude.ai form requires a Team or Enterprise organization and directory management access; organization Owners have this access by default. Individual authors who aren’t part of a Team or Enterprise organization can use the Console form instead. Run `claude plugin validate ./your-plugin` locally before you submit, replacing `./your-plugin` with the path to your plugin directory. The review pipeline runs the same check on every submission, along with automated safety screening. When validation passes, Claude Code prints `✔ Validation passed`, or `✔ Validation passed with warnings` if there are warnings. Warnings don’t fail validation; add `--strict` to treat them as errors. Approved plugins are pinned to a specific commit SHA in the [`anthropics/claude-plugins-community`](<https://github.com/anthropics/claude-plugins-community>) catalog, and CI bumps the pin automatically as you push new commits to your repository. The public catalog syncs nightly from the review pipeline, so there can be a delay between approval and your plugin appearing in `marketplace.json`. To check whether your plugin is installable yet, search for its name in the [community catalog](<https://github.com/anthropics/claude-plugins-community/blob/main/.claude-plugin/marketplace.json>). The official marketplace, `claude-plugins-official`, is curated separately. Anthropic decides which plugins to include at its discretion. There is no application process, and the submission form does not add plugins to the official marketplace. If Anthropic lists your plugin in the official marketplace, your CLI can prompt Claude Code users to install it. See [Recommend your plugin from your CLI](</docs/en/plugin-hints>). - -## - -​ - -Convert existing configurations to plugins - -If you already have skills or hooks in your `.claude/` directory, you can convert them into a plugin for easier sharing and distribution. - -### - -​ - -Migration steps - -1 - -Create the plugin structure - -Create a new plugin directory in your project root, alongside the existing `.claude/` folder, so the relative `cp` paths in the next step resolve: - - mkdir -p my-plugin/.claude-plugin - -Create the manifest file at `my-plugin/.claude-plugin/plugin.json`: - -my-plugin/.claude-plugin/plugin.json - - { - "name": "my-plugin", - "description": "Migrated from standalone configuration", - "version": "1.0.0" - } - -2 - -Copy your existing files - -Copy each configuration directory you have to the plugin root. You might not have all three: if a directory doesn’t exist, `cp` prints `No such file or directory` and copies nothing, so skip that command or ignore the error. - - cp -r .claude/commands my-plugin/ - - cp -r .claude/agents my-plugin/ - - cp -r .claude/skills my-plugin/ - -Your plugin now contains copies of the directories you had under `.claude/`. Run `ls my-plugin` to confirm: you should see each directory you copied. - -3 - -Migrate hooks - -If you have hooks in your settings, create a hooks directory: - - mkdir my-plugin/hooks - -Create `my-plugin/hooks/hooks.json` with your hooks configuration. Copy the `hooks` object from your `.claude/settings.json` or `settings.local.json`, since the format is the same. The command receives hook input as JSON on stdin, so use `jq` to extract the file path: - -my-plugin/hooks/hooks.json - - { - "hooks": { - "PostToolUse": [ - { - "matcher": "Write|Edit", - "hooks": [{ "type": "command", "command": "jq -r '.tool_input.file_path' | xargs npm run lint:fix" }] - } - ] - } - } - -4 - -Test your migrated plugin - -Load your plugin to verify everything works: - - claude --plugin-dir ./my-plugin - -Test each component: run your commands, check that agents appear in `/context`, and trigger the event each hook matches to confirm its effect. Claude Code records which hooks matched and how they exited in the [debug log](</docs/en/hooks#debug-hooks>). - -### - -​ - -What changes when migrating - -Standalone (`.claude/`)| Plugin ----|--- -Only available in one project| Can be shared via marketplaces -Files in `.claude/commands/`| Files in `plugin-name/commands/` -Hooks in `settings.json`| Hooks in `hooks/hooks.json` -Must manually copy to share| Install with `/plugin install` - -After migrating, remove the original files from `.claude/` to avoid duplicates. Project and user `.claude/agents/` definitions override same-named plugin agents, so the plugin version only takes effect once the originals are removed. Plugin skills are namespaced as `/plugin-name:skill-name`, so the original `/skill-name` and the plugin copy both remain available rather than one overriding the other. - -## - -​ - -Next steps - -Now that you understand Claude Code’s plugin system, here are suggested paths for different goals: - -### - -​ - -For plugin users - - * [Discover and install plugins](</docs/en/discover-plugins>): browse marketplaces and install plugins - * [Configure team marketplaces](</docs/en/discover-plugins#configure-team-marketplaces>): set up repository-level plugins for your team - -### - -​ - -For plugin developers - - * [Create and distribute a marketplace](</docs/en/plugin-marketplaces>): package and share your plugins - * [Plugins reference](</docs/en/plugins-reference>): complete technical specifications - * Dive deeper into specific plugin components: - * [Skills](</docs/en/skills>): skill development details - * [Subagents](</docs/en/sub-agents>): agent configuration and capabilities - * [Hooks](</docs/en/hooks>): event handling and automation - * [MCP](</docs/en/mcp>): external tool integration +Skills not appearing + +If plugin skills don’t work: + + 1. **Use the namespace** : invoke plugin skills as `/plugin-name:skill-name` + 2. **Check init message** : verify the skill appears in the `skills` list with the correct namespace + 3. **Validate skill files** : ensure each skill has a `SKILL.md` file in its own subdirectory under `skills/`, for example `skills/my-skill/SKILL.md` + +## + +​ + +See also + + * [Plugins](</docs/en/plugins>) \- Complete plugin development guide + * [Plugins reference](</docs/en/plugins-reference>) \- Technical specifications + * [Commands](</docs/en/agent-sdk/slash-commands>) \- Using commands in the SDK + * [Subagents](</docs/en/agent-sdk/subagents>) \- Working with specialized agents + * [Skills](</docs/en/agent-sdk/skills>) \- Using Agent Skills
modified Agent SDK reference - Python View current →
Show diff (218 lines)
--- a/python.md +++ b/python.md @@ -19,12 +19,6 @@ Choosing between `query()` and `ClaudeSDKClient` The Python SDK provides two ways to interact with Claude Code: - -### - -​ - -Quick comparison Feature| `query()`| `ClaudeSDKClient` ---|---|--- @@ -38,32 +32,7 @@ **Continue Chat**| Manual via `continue_conversation` or `resume`| ✅ Automatic **Use Case**| One-off tasks| Continuous conversations -### - -​ - -When to use `query()` (one-off tasks) - -**Best for:** - - * One-off questions where you don’t need conversation history - * Independent tasks that don’t require context from previous exchanges - * Simple automation scripts - * When you want a fresh start each time - -### - -​ - -When to use `ClaudeSDKClient` (continuous conversation) - -**Best for:** - - * **Continuing conversations** \- When you need Claude to remember context - * **Follow-up questions** \- Building on previous responses - * **Interactive applications** \- Chat interfaces, REPLs - * **Response-driven logic** \- When next action depends on Claude’s response - * **Session control** \- Managing conversation lifecycle explicitly +Use `ClaudeSDKClient` for interactive applications such as chat interfaces, or when the next action depends on Claude’s response. ## @@ -546,20 +515,7 @@ `ClaudeSDKClient` -**Maintains a conversation session across multiple exchanges.** This is the Python equivalent of how the TypeScript SDK’s `query()` function works internally - it creates a client object that can continue conversations. - -#### - -​ - -Key Features - - * **Session continuity** : Maintains conversation context across multiple `query()` calls - * **Same conversation** : The session retains previous messages - * **Interrupt support** : Can stop execution mid-task - * **Explicit lifecycle** : You control when the session starts and ends - * **Response-driven flow** : Can react to responses and send follow-ups - * **Custom tools and hooks** : Supports custom tools (created with `@tool` decorator) and hooks +**Maintains a conversation session across multiple exchanges.** This is the Python equivalent of how the TypeScript SDK’s `query()` function works internally - it creates a client object that can continue conversations. See the comparison with `query()`. class ClaudeSDKClient: def __init__(self, options: ClaudeAgentOptions | None = None, transport: Transport | None = None) @@ -1106,22 +1062,6 @@ In Python SDK 0.1.59 and earlier, an empty list was treated the same as omitting the option, so `setting_sources=[]` did not disable filesystem settings. Upgrade to a newer release if you need an empty list to take effect. The TypeScript SDK is not affected. -**Load all filesystem settings explicitly:** - - import asyncio - from claude_agent_sdk import query, ClaudeAgentOptions - - async def main(): - async for message in query( - prompt="Analyze this code", - options=ClaudeAgentOptions( - setting_sources=["user", "project", "local"] - ), - ): - print(message) - - asyncio.run(main()) - **Load only specific setting sources:** # Load only project settings, ignore user and local @@ -1133,24 +1073,6 @@ prompt="Run CI checks", options=ClaudeAgentOptions( setting_sources=["project"] # Only .claude/settings.json - ), - ): - print(message) - - asyncio.run(main()) - -**Testing and CI environments:** - - # Ensure consistent behavior in CI by excluding local settings - import asyncio - from claude_agent_sdk import query, ClaudeAgentOptions - - async def main(): - async for message in query( - prompt="Run tests", - options=ClaudeAgentOptions( - setting_sources=["project"], # Only team-shared settings - permission_mode="bypassPermissions", ), ): print(message) @@ -1182,27 +1104,7 @@ asyncio.run(main()) -**Loading CLAUDE.md project instructions:** - - # Load project settings to include CLAUDE.md files - import asyncio - from claude_agent_sdk import query, ClaudeAgentOptions - - async def main(): - async for message in query( - prompt="Add a new feature following project conventions", - options=ClaudeAgentOptions( - system_prompt={ - "type": "preset", - "preset": "claude_code", # Use Claude Code's system prompt - }, - setting_sources=["project"], # Loads CLAUDE.md from project - allowed_tools=["Read", "Write", "Edit"], - ), - ): - print(message) - - asyncio.run(main()) +To load CLAUDE.md project instructions, include `"project"` in `setting_sources`. See [Modify system prompts](</docs/en/agent-sdk/modifying-system-prompts#claude-md-files-for-project-level-instructions>) for how CLAUDE.md loading interacts with the system prompt options. #### @@ -2552,7 +2454,7 @@ `HookSpecificOutput` -A `TypedDict` containing the hook event name and event-specific fields. The shape depends on the `hookEventName` value. For full details on available fields per hook event, see [Control execution with hooks](</docs/en/agent-sdk/hooks#outputs>). A discriminated union of event-specific output types. The `hookEventName` field determines which fields are valid. +A discriminated union of event-specific `TypedDict` output types. The `hookEventName` field determines which fields are valid. For full details on available fields per hook event, see [Control execution with hooks](</docs/en/agent-sdk/hooks#outputs>). class PreToolUseHookSpecificOutput(TypedDict): hookEventName: Literal["PreToolUse"] @@ -3593,33 +3495,6 @@ ​ -Streaming mode with client - - from claude_agent_sdk import ClaudeSDKClient - import asyncio - - async def interactive_session(): - async with ClaudeSDKClient() as client: - # Send initial message - await client.query("What's the weather like?") - - # Process responses - async for msg in client.receive_response(): - print(msg) - - # Send follow-up - await client.query("Tell me more about that") - - # Process follow-up response - async for msg in client.receive_response(): - print(msg) - - asyncio.run(interactive_session()) - -### - -​ - Using custom tools with ClaudeSDKClient from claude_agent_sdk import ( @@ -3810,12 +3685,7 @@ Permissions Fallback for Unsandboxed Commands -When `allowUnsandboxedCommands` is enabled, the model can request to run commands outside the sandbox by setting `dangerouslyDisableSandbox: True` in the tool input. These requests fall back to the existing permissions system, meaning your `can_use_tool` handler will be invoked, allowing you to implement custom authorization logic. - -**`excludedCommands` vs `allowUnsandboxedCommands`:** - - * `excludedCommands`: A static list of commands that always bypass the sandbox automatically (e.g., `["docker"]`). The model has no control over this. - * `allowUnsandboxedCommands`: Lets the model decide at runtime whether to request unsandboxed execution by setting `dangerouslyDisableSandbox: True` in the tool input. +When `allowUnsandboxedCommands` is enabled, the model can request to run commands outside the sandbox by setting `dangerouslyDisableSandbox: True` in the tool input. These requests fall back to the existing permissions system, meaning your `can_use_tool` handler will be invoked, allowing you to implement custom authorization logic. Commands listed in `excludedCommands` instead bypass the sandbox automatically, with no model involvement; see `SandboxSettings`. The following example logs each unsandboxed request and denies it unless your own authorization logic allows it: import asyncio from claude_agent_sdk import ( @@ -3873,12 +3743,6 @@ asyncio.run(main()) -This pattern enables you to: - - * **Audit model requests** : Log when the model requests unsandboxed execution - * **Implement allowlists** : Only permit specific commands to run unsandboxed - * **Add approval workflows** : Require explicit authorization for privileged operations - Commands running with `dangerouslyDisableSandbox: True` have full system access. Ensure your `can_use_tool` handler validates these requests carefully.If `permission_mode` is set to `bypassPermissions` and `allow_unsandboxed_commands` is enabled, the model can autonomously execute commands outside the sandbox without approval prompts (an explicit [`ask` rule](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) still forces one). This combination effectively allows the model to escape sandbox isolation silently. ##
modified Quickstart View current →
Show diff (647 lines)
--- a/quickstart.md +++ b/quickstart.md @@ -1,307 +1,337 @@ -This quickstart guide will have you using AI-powered coding assistance in a few minutes. By the end, you’ll understand how to use Claude Code for common development tasks. - -## - -​ - -Before you begin - -Make sure you have: - - * A terminal or command prompt open - * If you’ve never used the terminal before, check out the [terminal guide](</docs/en/terminal-guide>) - * A code project to work with - * A [Claude subscription](<https://claude.com/pricing?utm_source=claude_code&utm_medium=docs&utm_content=quickstart_prereq>) (Pro, Max, Team, or Enterprise), [Claude Console](<https://console.anthropic.com/>) account, or access through a [supported cloud provider](</docs/en/third-party-integrations>) - -This guide covers the terminal CLI. Claude Code is also available on the [web](<https://claude.ai/code>), as a [desktop app](</docs/en/desktop>), in [VS Code](</docs/en/vs-code>) and [JetBrains IDEs](</docs/en/jetbrains>), in [Slack](</docs/en/slack>), and in CI/CD with [GitHub Actions](</docs/en/github-actions>) and [GitLab](</docs/en/gitlab-ci-cd>). See [all interfaces](</docs/en/overview#use-claude-code-everywhere>). - -## - -​ - -Step 1: Install Claude Code - -To install Claude Code, use one of the following methods: - - * Native Install (Recommended) - - * Homebrew - - * WinGet - -**macOS, Linux, WSL:** - - curl -fsSL https://claude.ai/install.sh | bash - -**Windows PowerShell:** - - irm https://claude.ai/install.ps1 | iex - -**Windows CMD:** - - curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd - -If you see `The token '&&' is not a valid statement separator`, you’re in PowerShell, not CMD. If you see `'irm' is not recognized as an internal or external command`, you’re in CMD, not PowerShell. Your prompt shows `PS C:\` when you’re in PowerShell and `C:\` without the `PS` when you’re in CMD.If the install command fails with `syntax error near unexpected token '<'`, a `403`, or another curl error, see [Troubleshoot installation](</docs/en/troubleshoot-install#find-your-error>) to match the error to a fix and for alternative install methods.[Git for Windows](<https://git-scm.com/downloads/win>) is recommended on native Windows so Claude Code can use the Bash tool. If Git for Windows is not installed, Claude Code uses PowerShell as the shell tool instead. WSL setups do not need Git for Windows. - -Native installations automatically update in the background to keep you on the latest version. - - brew install --cask claude-code - -Homebrew offers two casks. `claude-code` tracks the stable release channel, which is typically about a week behind and skips releases with major regressions. `claude-code@latest` tracks the latest channel and receives new versions as soon as they ship. - -Homebrew installations do not auto-update. Run `brew upgrade claude-code` or `brew upgrade claude-code@latest`, depending on which cask you installed, to get the latest features and security fixes. - - winget install Anthropic.ClaudeCode - -WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes. - -You can also install with [apt, dnf, or apk](</docs/en/setup#install-with-linux-package-managers>) on Debian, Fedora, RHEL, and Alpine. To confirm the installation worked, run: - - claude --version - -The command prints a version number followed by `(Claude Code)`. - -## - -​ - -Step 2: Log in to your account - -Claude Code requires an account to use. Start an interactive session with the `claude` command and you’ll be prompted to log in on first use: - - claude - -For Claude subscription or Console accounts, follow the prompts to complete authentication in your browser. If you’ve set the `ANTHROPIC_API_KEY` environment variable, Claude Code skips the login prompt and asks you to approve the key instead. To switch accounts later or re-authenticate, type `/login` inside the running session: - - /login - -You can log in using any of these account types: - - * [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 Cloud’s Agent Platform, 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. - -## - -​ - -Step 3: Start your first session - -Open your terminal in any project directory and start Claude Code: - - cd /path/to/your/project - claude - -Replace `/path/to/your/project` with the path to the project you want to work on. You’ll see the Claude Code prompt with the version, current model, and working directory shown above it. Type `/help` for available commands or `/resume` to continue a previous conversation. - -After logging in (Step 2), your credentials are stored on your system. Learn more in [Credential Management](</docs/en/authentication#credential-management>). - -## - -​ - -Step 4: Ask your first question - -Let’s start with understanding your codebase. Try one of these commands: - - what does this project do? - -Claude will analyze your files and provide a summary. You can also ask more specific questions: - - what technologies does this project use? - - where is the main entry point? - - explain the folder structure - -You can also ask Claude about its own capabilities: - - what can Claude Code do? - - how do I create custom skills in Claude Code? - - can Claude Code work with Docker? - -Claude Code reads your project files as needed. You don’t have to manually add context. - -## - -​ - -Step 5: Make your first code change - -Now let’s make Claude Code do some actual coding. Try a simple task: - - add a hello world function to the main file - -Claude Code will: - - 1. Find the appropriate file - 2. Show you the proposed changes - 3. Ask for your approval before changing files, depending on your permission mode - 4. Make the edit - -Whether Claude Code asks before changing files depends on your [permission mode](</docs/en/permission-modes>). In default mode, Claude asks for approval before each change. Press `Shift+Tab` to cycle through modes: `acceptEdits` auto-approves file edits, and `plan` lets Claude propose changes without editing. Some accounts also have an `auto` mode that runs a background safety check and blocks risky actions, returning to prompts only after repeated blocks. - -## - -​ - -Step 6: Use Git with Claude Code - -Claude Code makes Git operations conversational: - - what files have I changed? - - commit my changes with a descriptive message - -You can also prompt for more complex Git operations: - - create a new branch called feature/quickstart - - show me the last 5 commits - - help me resolve merge conflicts - -## - -​ - -Step 7: Fix a bug or add a feature - -Claude is proficient at debugging and feature implementation. Describe what you want in natural language: - - add input validation to the user registration form - -Or fix existing issues: - - there's a bug where users can submit empty forms - fix it - -Claude Code will: - - * Locate the relevant code - * Understand the context - * Implement a solution - * Run tests if available - -## - -​ - -Step 8: Test out other common workflows - -There are a number of ways to work with Claude: **Refactor code** - - refactor the authentication module to use async/await instead of callbacks - -**Write tests** - - write unit tests for the calculator functions - -**Update documentation** - - update the README with installation instructions - -**Code review** - - review my changes and suggest improvements - -Talk to Claude like you would a helpful colleague. Describe what you want to achieve, and it will help you get there. - -## - -​ - -Essential commands - -Here are the most important commands for daily use. Shell commands run from your terminal to start or resume Claude Code. Session commands run inside Claude Code after it starts. **Shell commands** - -Command| What it does| Example ----|---|--- -`claude`| Start interactive mode| `claude` -`claude "task"`| Run a one-time task| `claude "fix the build error"` -`claude -p "query"`| Run one-off query, then exit| `claude -p "explain this function"` -`claude -c`| Continue most recent conversation in current directory| `claude -c` -`claude -r`| Resume a previous conversation| `claude -r` - -**Session commands** - -Command| What it does| Example ----|---|--- -`/clear`| Clear conversation history| `/clear` -`/help`| Show available commands| `/help` -`/exit` or Ctrl+D twice| Exit Claude Code| `/exit` - -See the [CLI reference](</docs/en/cli-reference>) for the complete list of shell commands and the [commands reference](</docs/en/commands>) for the complete list of session commands. - -## - -​ - -Pro tips for beginners - -For more, see [best practices](</docs/en/best-practices>) and [common workflows](</docs/en/common-workflows>). - -Be specific with your requests - -Instead of: “fix the bug”Try: “fix the login bug where users see a blank screen after entering wrong credentials” - -Use step-by-step instructions - -Break complex tasks into steps: - - 1. create a new database table for user profiles - 2. create an API endpoint to get and update user profiles - 3. build a webpage that allows users to see and edit their information - -Let Claude explore first - -Before making changes, let Claude understand your code: - - analyze the database schema - - build a dashboard showing products that are most frequently returned by our UK customers - -Save time with shortcuts - - * Type `/` to see all commands and skills - * Use Tab for command completion - * Press ↑ for command history - * Press `Shift+Tab` to cycle permission modes - -## - -​ - -What’s next? - -Now that you’ve learned the basics, explore more advanced features: - -## How Claude Code works - -Understand the agentic loop, built-in tools, and how Claude Code interacts with your project - -## Best practices - -Get better results with effective prompting and project setup - -## Common workflows - -Step-by-step guides for common tasks - -## Extend Claude Code - -Customize with CLAUDE.md, skills, hooks, MCP, and more - -## - -​ - -Getting help - - * **In Claude Code** : Type `/help` or ask “how do I…” - * **Documentation** : You’re here! Browse other guides - * **Community** : Join our [Discord](<https://www.anthropic.com/discord>) for tips and support +Use the Agent SDK to build an AI agent that reads your code, finds bugs, and fixes them, all without manual intervention. **What you’ll do:** + + 1. Set up a project with the Agent SDK + 2. Create a file with some buggy code + 3. Run an agent that finds and fixes the bugs automatically + +## + +​ + +Prerequisites + + * **Node.js 18+** or **Python 3.10+** + * An **Anthropic account**. If you don’t have one, [sign up here](<https://platform.claude.com/>). + +## + +​ + +Setup + +1 + +Create a project folder + +Create a new directory for this quickstart: + + mkdir my-agent + cd my-agent + +For your own projects, you can run the SDK from any folder; it will have access to files in that directory and its subdirectories by default. + +2 + +Install the SDK + +Install the Agent SDK package for your language: + + * TypeScript (new project) + + * TypeScript (existing project) + + * Python (uv) + + * Python (pip) + + npm init -y + npm pkg set type=module + npm install @anthropic-ai/claude-agent-sdk + npm install --save-dev tsx + +Setting `"type": "module"` in `package.json` lets your agent script use top-level `await`, and [tsx](<https://tsx.hirok.io>) runs TypeScript files directly. npm prints `added N packages` when the install succeeds. + + npm install @anthropic-ai/claude-agent-sdk + npm install --save-dev tsx + +[tsx](<https://tsx.hirok.io>) runs TypeScript files directly. If your project uses CommonJS, name your agent script `agent.mts` instead of `agent.ts`. The `.mts` extension makes tsx treat the file as an ES module, so top-level `await` works without converting your whole project to ES modules. Use `agent.mts` in place of `agent.ts` in the create and run steps later in this quickstart. + +[uv](<https://docs.astral.sh/uv/>) is a fast Python package manager that handles virtual environments automatically: + + uv init + uv add claude-agent-sdk + +Create and activate a virtual environment, then install the package.On macOS or Linux: + + python3 -m venv .venv + source .venv/bin/activate + pip install claude-agent-sdk + +On Windows: + + py -m venv .venv + .venv\Scripts\Activate.ps1 + pip install claude-agent-sdk + +If PowerShell blocks `Activate.ps1` with an execution policy error, run `Set-ExecutionPolicy -Scope Process RemoteSigned` first. + +Both the TypeScript and Python SDKs bundle a native Claude Code binary, so most installs need no separate Claude Code install. Some installs have no bundled binary: + + * If pip installs the Python SDK’s source distribution instead of a platform wheel, for example on ARM64 Windows, no binary is bundled. [Install Claude Code natively](</docs/en/setup#install-claude-code>). The Python SDK finds it on your `PATH`. + * The TypeScript SDK installs its binary through npm optional dependencies, so an install that skips them, for example `npm ci --omit=optional`, gets no binary even on a supported platform. Reinstall without skipping optional dependencies, or [install Claude Code natively](</docs/en/setup#install-claude-code>) and set `pathToClaudeCodeExecutable` to its path. + +3 + +Set your API key + +Get an API key from the [Claude Console](<https://platform.claude.com/>), then set it as an environment variable in the shell where you’ll run your agent: + + * macOS / Linux + + * Windows (PowerShell) + + export ANTHROPIC_API_KEY=your-api-key + + $env:ANTHROPIC_API_KEY = "your-api-key" + +The SDK reads the key from the environment of the process that runs your agent; it doesn’t load `.env` files automatically. If you keep the key in a `.env` file, load it yourself, for example with the `dotenv` package, before calling the SDK.The SDK also supports authentication via third-party API providers: + + * **Amazon Bedrock** : set `CLAUDE_CODE_USE_BEDROCK=1` environment variable and configure AWS credentials + * **Claude Platform on AWS** : set `CLAUDE_CODE_USE_ANTHROPIC_AWS=1` and `ANTHROPIC_AWS_WORKSPACE_ID`, then configure AWS credentials + * **Google Cloud’s Agent Platform** : set `CLAUDE_CODE_USE_VERTEX=1` environment variable and configure Google Cloud credentials + * **Microsoft Foundry** : set `CLAUDE_CODE_USE_FOUNDRY=1` environment variable and configure Azure credentials + +See the setup guides for [Amazon Bedrock](</docs/en/amazon-bedrock>), [Claude Platform on AWS](</docs/en/claude-platform-on-aws>), [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>), or [Microsoft Foundry](</docs/en/microsoft-foundry>) for details. + +Unless previously approved, Anthropic does not allow third party developers to offer claude.ai login or rate limits for their products, including agents built on the Claude Agent SDK. Please use the API key authentication methods described in this document instead. + +## + +​ + +Create a buggy file + +This quickstart walks you through building an agent that can find and fix bugs in code. First, you need a file with some intentional bugs for the agent to fix. Create `utils.py` in the `my-agent` directory and paste the following code: + + def calculate_average(numbers): + total = 0 + for num in numbers: + total += num + return total / len(numbers) + + def get_user_name(user): + return user["name"].upper() + +This code has two bugs: + + 1. `calculate_average([])` crashes with division by zero + 2. `get_user_name(None)` crashes with a TypeError + +## + +​ + +Build an agent that finds and fixes bugs + +Create `agent.py` if you’re using the Python SDK, or `agent.ts` for TypeScript. Use `agent.mts` instead if your existing project uses CommonJS: + +Python + +TypeScript + + import asyncio + from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ResultMessage + + async def main(): + # Agentic loop: streams messages as Claude works + async for message in query( + prompt="Review utils.py for bugs that would cause crashes. Fix any issues you find.", + options=ClaudeAgentOptions( + allowed_tools=["Read", "Edit", "Glob"], # Auto-approve these tools + permission_mode="acceptEdits", # Auto-approve file edits + ), + ): + # Print human-readable output + if isinstance(message, AssistantMessage): + for block in message.content: + if hasattr(block, "text"): + print(block.text) # Claude's reasoning + elif hasattr(block, "name"): + print(f"Tool: {block.name}") # Tool being called + elif isinstance(message, ResultMessage): + print(f"Done: {message.subtype}") # Final result + + asyncio.run(main()) + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + // Agentic loop: streams messages as Claude works + for await (const message of query({ + prompt: "Review utils.py for bugs that would cause crashes. Fix any issues you find.", + options: { + allowedTools: ["Read", "Edit", "Glob"], // Auto-approve these tools + permissionMode: "acceptEdits" // Auto-approve file edits + } + })) { + // Print human-readable output + if (message.type === "assistant" && message.message?.content) { + for (const block of message.message.content) { + if ("text" in block) { + console.log(block.text); // Claude's reasoning + } else if ("name" in block) { + console.log(`Tool: ${block.name}`); // Tool being called + } + } + } else if (message.type === "result") { + console.log(`Done: ${message.subtype}`); // Final result + } + } + +This code has three main parts: + + 1. **`query`** : the main entry point that creates the agentic loop. It returns an async iterator, so you use `async for` to stream messages as Claude works. See the full API in the [Python](</docs/en/agent-sdk/python#query>) or [TypeScript](</docs/en/agent-sdk/typescript#query>) SDK reference. + 2. **`prompt`** : what you want Claude to do. Claude figures out which tools to use based on the task. + 3. **`options`** : configuration for the agent. This example uses `allowedTools` to pre-approve `Read`, `Edit`, and `Glob`, and `permissionMode: "acceptEdits"` to auto-approve file changes. Other options include `systemPrompt`, `mcpServers`, and more. See all options for [Python](</docs/en/agent-sdk/python#claudeagentoptions>) or [TypeScript](</docs/en/agent-sdk/typescript#options>). + +The `async for` loop keeps running as Claude thinks, calls tools, observes results, and decides what to do next. Each iteration yields a message: Claude’s reasoning, a tool call, a tool result, or the final outcome. The SDK handles the orchestration, tool execution, context management, and retries, so you consume the stream. The loop ends when Claude finishes the task or hits an error. The message handling inside the loop filters for human-readable output. Without filtering, you’d see raw message objects including system initialization and internal state, which is useful for debugging but noisy otherwise. + +This example uses streaming to show progress in real-time. If you don’t need live output (e.g., for background jobs or CI pipelines), you can collect all messages at once. See [Streaming vs. single-turn mode](</docs/en/agent-sdk/streaming-vs-single-mode>) for details. + +### + +​ + +Run your agent + +Your agent is ready. Run it with the following command: + + * TypeScript + + * Python (uv) + + * Python (pip) + + npx tsx agent.ts + +If you named your script `agent.mts`, run `npx tsx agent.mts` instead. + + uv run agent.py + +With your virtual environment still activated: + + python agent.py + +As it works, the agent prints its reasoning and each tool it calls, ending with `Done: success`. After running, check `utils.py`. You’ll see defensive code handling empty lists and null users. Your agent autonomously: + + 1. **Read** `utils.py` to understand the code + 2. **Analyzed** the logic and identified edge cases that would crash + 3. **Edited** the file to add proper error handling + +This is what makes the Agent SDK different: Claude executes tools directly instead of asking you to implement them. + +If you see “API key not found”, make sure you’ve set the `ANTHROPIC_API_KEY` environment variable in the shell where you run your agent. The SDK doesn’t load `.env` files automatically. See the [full troubleshooting guide](</docs/en/troubleshooting>) for more help. + +### + +​ + +Try other prompts + +Now that your agent is set up, try some different prompts: + + * `"Add docstrings to all functions in utils.py"` + * `"Add type hints to all functions in utils.py"` + * `"Create a README.md documenting the functions in utils.py"` + +### + +​ + +Customize your agent + +You can modify your agent’s behavior by changing the options. Here are a few examples: **Add web search capability:** + +Python + +TypeScript + + options = ClaudeAgentOptions( + allowed_tools=["Read", "Edit", "Glob", "WebSearch"], permission_mode="acceptEdits" + ) + + const _ = { + options: { + allowedTools: ["Read", "Edit", "Glob", "WebSearch"], + permissionMode: "acceptEdits" + } + }; + +**Give Claude a custom system prompt:** + +Python + +TypeScript + + options = ClaudeAgentOptions( + allowed_tools=["Read", "Edit", "Glob"], + permission_mode="acceptEdits", + system_prompt="You are a senior Python developer. Always follow PEP 8 style guidelines.", + ) + + const _ = { + options: { + allowedTools: ["Read", "Edit", "Glob"], + permissionMode: "acceptEdits", + systemPrompt: "You are a senior Python developer. Always follow PEP 8 style guidelines." + } + }; + +**Run commands in the terminal:** + +Python + +TypeScript + + options = ClaudeAgentOptions( + allowed_tools=["Read", "Edit", "Glob", "Bash"], permission_mode="acceptEdits" + ) + + const _ = { + options: { + allowedTools: ["Read", "Edit", "Glob", "Bash"], + permissionMode: "acceptEdits" + } + }; + +With `Bash` enabled, try: `"Write unit tests for utils.py, run them, and fix any failures"` + +## + +​ + +Key concepts + +**Tools** control what your agent can do: + +Tools| What the agent can do +---|--- +`Read`, `Glob`, `Grep`| Read-only analysis +`Read`, `Edit`, `Glob`| Analyze and modify code +`Read`, `Edit`, `Bash`, `Glob`, `Grep`| Full automation + +**Permission modes** control how much human oversight you want. The SDK evaluates the active mode together with your allow and deny rules in a fixed order, described in [How permissions are evaluated](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>). For the full list of modes, their behavior, and when to use each, see [Permission mode in How the agent loop works](</docs/en/agent-sdk/agent-loop#permission-mode>). + +## + +​ + +Next steps + +Now that you’ve created your first agent, learn how to extend its capabilities and tailor it to your use case: + + * **[Permissions](</docs/en/agent-sdk/permissions>)** : control what your agent can do and when it needs approval + * **[Hooks](</docs/en/agent-sdk/hooks>)** : run custom code before or after tool calls + * **[Sessions](</docs/en/agent-sdk/sessions>)** : build multi-turn agents that maintain context + * **[MCP servers](</docs/en/agent-sdk/mcp>)** : connect to databases, browsers, APIs, and other external systems + * **[Hosting](</docs/en/agent-sdk/hosting>)** : deploy agents to Docker, cloud, and CI/CD + * **[Example agents](<https://github.com/anthropics/claude-agent-sdk-demos>)** : see complete examples: email assistant, research agent, and more
modified Continue local sessions from any device with Remote Control View current →
--- a/remote-control.md +++ b/remote-control.md @@ -156,7 +156,7 @@ Connection and security -Your local Claude Code session makes outbound HTTPS requests only and never opens inbound ports on your machine. When you start Remote Control, it registers with the Anthropic API and polls for work. When you connect from another device, the server routes messages between the web or mobile client and your local session over a streaming connection. All traffic travels through the Anthropic API over TLS, the same transport security as any Claude Code session. The connection uses multiple short-lived credentials, each scoped to a single purpose and expiring independently. While Remote Control is connected, the session transcript, including your messages, Claude’s responses, and tool activity, is stored on Anthropic servers. The stored transcript keeps the conversation in sync across your devices and lets the session reconnect after a network drop. Execution and filesystem access stay on your machine, and stored transcripts are retained under the [Data usage](</docs/en/data-usage>) policy. With [cross-session messaging](</docs/en/cross-session-messaging>), the Remote Control connection also carries messages between your own Claude Code sessions on different machines, and messages arriving from your [Claude Code on the web](</docs/en/claude-code-on-the-web>) sessions, traveling through Anthropic servers like the rest of Remote Control traffic. [Message sessions on other machines](</docs/en/cross-session-messaging#message-sessions-on-other-machines>) covers the reply-only delivery rules and the `isolatePeerMachines` approval requirement. [Control inbound messages](</docs/en/cross-session-messaging#control-inbound-messages>) covers the inbound controls. Cross-session messaging requires Claude Code v2.1.224 or later. To turn Remote Control off entirely, use the [`disableRemoteControl`](</docs/en/settings#available-settings>) setting. Organizations with compliance requirements such as Zero Data Retention can’t enable Remote Control. +Your local Claude Code session makes outbound HTTPS requests only and never opens inbound ports on your machine. When you start Remote Control, it registers with the Anthropic API and polls for work. When you connect from another device, the server routes messages between the web or mobile client and your local session over a streaming connection. All traffic travels through the Anthropic API over TLS, the same transport security as any Claude Code session. The connection uses multiple short-lived credentials, each scoped to a single purpose and expiring independently. While Remote Control is connected, the session transcript, including your messages, Claude’s responses, and tool activity, is stored on Anthropic servers. The stored transcript keeps the conversation in sync across your devices and lets the session reconnect after a network drop. Execution and filesystem access stay on your machine, and stored transcripts are retained under the [Data usage](</docs/en/data-usage>) policy. With [cross-session messaging](</docs/en/cross-session-messaging>), the Remote Control connection also carries messages between your own Claude Code sessions on different machines, and messages arriving from your [Claude Code on the web](</docs/en/claude-code-on-the-web>) sessions, traveling through Anthropic servers like the rest of Remote Control traffic. [Message sessions on other machines](</docs/en/cross-session-messaging#message-sessions-on-other-machines>) covers the cross-machine delivery rules and the `isolatePeerMachines` approval requirement. [Control inbound messages](</docs/en/cross-session-messaging#control-inbound-messages>) covers the inbound controls. Cross-session messaging requires Claude Code v2.1.224 or later. To turn Remote Control off entirely, use the [`disableRemoteControl`](</docs/en/settings#available-settings>) setting. Organizations with compliance requirements such as Zero Data Retention can’t enable Remote Control. ## @@ -432,7 +432,7 @@ Related resources * [Claude Code on the web](</docs/en/claude-code-on-the-web>): run sessions in the cloud instead of your machine, configured through [cloud environments](</docs/en/cloud-environments>) - * [Cross-session messaging](</docs/en/cross-session-messaging>): let Claude reply to messages from your sessions on other machines or on [Claude Code on the web](</docs/en/claude-code-on-the-web>) over the Remote Control connection + * [Cross-session messaging](</docs/en/cross-session-messaging>): let Claude message your sessions on other machines or on [Claude Code on the web](</docs/en/claude-code-on-the-web>) * [Channels](</docs/en/channels>): forward Telegram, Discord, or iMessage into a session so Claude reacts to messages while you’re away * [Dispatch](</docs/en/desktop#sessions-from-dispatch>): message a task from your phone and it can spawn a Desktop session to handle it * [Authentication](</docs/en/authentication>): set up `/login` and manage credentials for claude.ai
modified Securely deploying AI agents View current →
--- a/secure-deployment.md +++ b/secure-deployment.md @@ -1,4 +1,4 @@ -Claude Code and the Agent SDK are powerful tools that can execute code, access files, and interact with external services on your behalf. Like any tool with these capabilities, deploying them thoughtfully ensures you get the benefits while maintaining appropriate controls. Unlike traditional software that follows predetermined code paths, these tools generate their actions dynamically based on context and goals. This flexibility is what makes them useful, but it also means their behavior can be influenced by the content they process: files, webpages, or user input. This is sometimes called prompt injection. For example, if a repository’s README contains unusual instructions, Claude Code might incorporate those into its actions in ways the operator didn’t anticipate. This guide covers practical ways to reduce this risk. The good news is that securing an agent deployment doesn’t require exotic infrastructure. The same principles that apply to running any semi-trusted code apply here: isolation, least privilege, and defense in depth. Claude Code includes several security features that help with common concerns, and this guide walks through these along with additional hardening options for those who need them. Not every deployment needs maximum security. A developer running Claude Code on their laptop has different requirements than a company processing customer data in a multi-tenant environment. This guide presents options ranging from Claude Code’s built-in security features to hardened production architectures, so you can choose what fits your situation. +Claude Code and the Agent SDK are powerful tools that can execute code, access files, and interact with external services on your behalf. Unlike traditional software that follows predetermined code paths, these tools generate their actions dynamically based on context and goals. This flexibility is what makes them useful, but it also means their behavior can be influenced by the content they process: files, webpages, or user input. This is sometimes called prompt injection. For example, if a repository’s README contains unusual instructions, Claude Code might incorporate those into its actions in ways the operator didn’t anticipate. This guide covers practical ways to reduce this risk. Not every deployment needs maximum security. A developer running Claude Code on their laptop has different requirements than a company processing customer data in a multi-tenant environment. This guide presents options ranging from Claude Code’s built-in security features to hardened production architectures, so you can choose what fits your situation. ## @@ -90,7 +90,7 @@ Sandbox runtime -For lightweight isolation without containers, [sandbox-runtime](<https://github.com/anthropic-experimental/sandbox-runtime>) enforces filesystem and network restrictions at the OS level. The main advantage is simplicity: no Docker configuration, container images, or networking setup required. The proxy and filesystem restrictions are built in. You provide a settings file specifying allowed domains and paths. **How it works:** +For lightweight isolation without containers, [sandbox-runtime](<https://github.com/anthropic-experimental/sandbox-runtime>) enforces filesystem and network restrictions at the OS level. The main advantage is simplicity: no Docker configuration, container images, or networking setup required. The proxy and filesystem restrictions are built in. **How it works:** * **Filesystem** : Uses OS primitives (`bubblewrap` on Linux, `sandbox-exec` on macOS) to restrict read/write access to configured paths * **Network** : Removes network namespace (Linux) or uses Seatbelt profiles (macOS) to route network traffic through a built-in proxy
modified Work with sessions View current →
Show diff (587 lines)
--- a/sessions.md +++ b/sessions.md @@ -1,201 +1,409 @@ -A session is a saved conversation tied to a project directory. Claude Code stores it locally as you work, so you can resume where you left off, branch to try a different approach, or switch between tasks. The [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>), [Claude Code on the web](</docs/en/claude-code-on-the-web>), and the [VS Code extension](</docs/en/vs-code#resume-past-conversations>) each maintain their own session history. This page covers the CLI. +A session is the conversation history the SDK accumulates while your agent works. It contains your prompt, every tool call the agent made, every tool result, and every response. The SDK writes it to disk automatically so you can return to it later. Returning to a session means the agent has full context from before: files it already read, analysis it already performed, decisions it already made. You can ask a follow-up question, recover from an interruption, or branch off to try a different approach. + +Sessions persist the **conversation** , not the filesystem. To snapshot and revert file changes the agent made, use [file checkpointing](</docs/en/agent-sdk/file-checkpointing>). + +This guide covers how to pick the right approach for your app, the SDK interfaces that track sessions automatically, how to capture session IDs and use `resume` and `fork` manually, and what to know about resuming sessions across hosts. ## ​ -Resume a session - -Sessions are saved continuously to local transcript files as you work, so you can return to one after exiting or running `/clear`. Use these entry points: - -Command| What it does +Choose an approach + +How much session handling you need depends on your application’s shape. Session management comes into play when you send multiple prompts that should share context. Within a single `query()` call, the agent already takes as many turns as it needs, and permission prompts and `AskUserQuestion` are [handled in-loop](</docs/en/agent-sdk/user-input>) (they don’t end the call). + +What you’re building| What to use ---|--- -`claude --continue`| Resumes the most recent session in the current directory -`claude --resume`| Opens the session picker -`claude --resume <name>`| Resumes the named session directly -`claude --from-pr <number>`| Opens the session picker filtered to sessions linked to that pull request -`/resume`| Switches to a different conversation from inside an active session - -Sessions created with [`claude -p`](</docs/en/headless>) or the [Agent SDK](</docs/en/agent-sdk/overview>) don’t appear in the session picker, but you can still resume one by passing its session ID to `claude --resume <session-id>`. You can run `claude --resume <session-id>` from any directory: Claude Code looks for the ID in the current project directory and its git worktrees first, then in every other project on this machine, so it finds a session that started elsewhere or moved with [`/cd`](</docs/en/commands>). The cross-project search resolves the ID only when exactly one other project holds a transcript with messages for it, so a hand-copied duplicate makes Claude Code report not-found rather than resume an arbitrary copy. If no stored session matches the ID, Claude Code reports `No conversation found with session ID: <session-id>`. Before v2.1.223, the lookup stopped at the current project directory and its git worktrees, so you had to resume from the directory the session last worked in. - -### - -​ - -What a resumed session restores - -A resumed session restores the conversation along with the state saved in it: - - * Conversation history: the full history, including tool calls and results. - * Model: the session continues on the model it was using. The model isn’t restored when it has been retired or isn’t allowed by `availableModels`, when a `--model` flag or `ANTHROPIC_MODEL`-family environment variable picks one at launch, or on providers that use provider-specific deployment IDs, such as [Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry](</docs/en/third-party-integrations>); see [model configuration](</docs/en/model-config#setting-your-model>) for the resolution order. - * Agent: a session started with [`--agent`](</docs/en/sub-agents#invoke-subagents-explicitly>) or the `agent` setting continues as that agent, keeping its system prompt, tool restrictions, and model. Pass `--agent` when resuming to pick a different one. Claude Code looks for the agent in two places: the session’s original directory, provided you have [trusted that workspace](</docs/en/permissions#project-allow-rules-and-workspace-trust>), and then the directory you resume from, so a project-scoped agent still loads when you resume from another directory. If Claude Code doesn’t find the agent in either place, the session resumes with the default tools and system prompt and shows a [warning naming the agent](</docs/en/errors#session-agent-no-longer-available>). - * Permission mode: the mode the session was in. `plan` and `bypassPermissions` are never restored; [bypassing permissions](</docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode>) must be enabled again at launch, with one of its launch flags or `permissions.defaultMode: "bypassPermissions"` in [settings](</docs/en/settings#permission-settings>). `auto` is restored only when your account still meets the [auto mode requirements](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>). Pass `--permission-mode` to override the restored mode. - * Active goal: a [goal](</docs/en/goal#resume-with-an-active-goal>) that was still active when the session ended carries over; its turn count, timer, and token-spend baseline reset. - * Scheduled tasks: [tasks that haven’t expired](</docs/en/scheduled-tasks#limitations>) are restored. Background Bash and monitor tasks aren’t. - -Not every configuration flag from the original launch is restored. If the session depended on `--mcp-config`, `--settings`, `--plugin-dir`, `--fallback-model`, or directories added with `--add-dir`, pass them again when you resume; directories added mid-session with `/add-dir` aren’t restored either, though the session picker still uses them to locate the session. The standard settings files, such as `settings.json` and `settings.local.json`, are re-read at launch, so configuration that lives in them doesn’t need to be passed again. - -### - -​ - -Resume from a summary - -On a Pro or Max plan, when you resume a session that has been inactive for more than about an hour and is over 100,000 tokens, Claude Code restores the conversation and then opens a dialog before you send your first message. The session’s [prompt cache](</docs/en/prompt-caching#cache-lifetime>) has expired by then, so the next request processes the full history once no matter which of the dialog’s options you pick. The dialog offers three ways to continue the session. They differ in how much of the conversation each one carries forward into later requests, which is a tradeoff between keeping every detail and sending fewer tokens per request: - - * **Resume from summary** : runs [`/compact`](</docs/en/context-window#what-survives-compaction>) immediately. Claude Code sends one summarization request over the full history, then replaces the history with the summary, your most recent exchanges, and up to five recently read files. Later requests carry the summary instead of the full history. - * **Resume full session as-is** : loads the conversation unchanged. After you send your first message, Claude Code reprocesses and re-caches the full history, then re-reads it from the cache on later requests while the cache stays warm. - * **Don’t ask me again** : resumes the full session and stops showing the dialog on all future resumes. - -Resuming as-is keeps every detail of the conversation available, at a per-request cost that scales with the conversation’s size. Resuming from the summary costs less on each later request because it carries the summary instead of the full history, but whatever the summary leaves out is no longer in Claude’s context. See [why usage climbs in a long session](</docs/en/costs#why-usage-climbs-in-a-long-session>) for where that per-request cost comes from. - -### - -​ - -Where the session picker looks - -Claude Code stores sessions per project directory. By default the session picker shows: - - * Sessions from the current worktree, including [background sessions](</docs/en/agent-view>), which are marked `bg` in the list - * 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. Sessions whose first prompt was a [`/loop`](</docs/en/scheduled-tasks#run-a-prompt-repeatedly-with-%2Floop>) command don’t appear in the picker; running `/loop` later in a conversation doesn’t hide the session. Before v2.1.211, a `/loop` run early in a conversation hid the session from the picker permanently. 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. When you select a session from another worktree of the same repository, Claude Code resumes it in place. When you select a session from an unrelated project, Claude Code 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 ----|---|--- -`claude --resume <name>`| Resumes directly| Opens the session picker with the name pre-filled as a search term -`/resume <name>`| Resumes directly| Reports an error; run `/resume` with no argument to open the session picker +One-shot task: single prompt, no follow-up| Nothing extra. One `query()` call handles it. +Multi-turn chat in one process| `ClaudeSDKClient` (Python) or `continue: true` (TypeScript). The SDK tracks the session for you with no ID handling. +Pick up where you left off after a process restart| `continue_conversation=True` (Python) / `continue: true` (TypeScript). Resumes the most recent session in the directory, no ID needed. +Resume a specific past session (not the most recent)| Capture the session ID and pass it to `resume`. +Try an alternative approach without losing the original| Fork the session. +Stateless task, don’t want anything written to disk| Set [`persistSession: false`](</docs/en/agent-sdk/typescript#options>) (TypeScript only). The session exists only in memory for the duration of the call. In Python, set [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](</docs/en/env-vars>) in the `env` option to suppress transcript writes instead. + +### + +​ + +Continue, resume, and fork + +Continue, resume, and fork are option fields you set on `query()` ([`ClaudeAgentOptions`](</docs/en/agent-sdk/python#claudeagentoptions>) in Python, [`Options`](</docs/en/agent-sdk/typescript#options>) in TypeScript). **Continue** and **resume** both pick up an existing session and add to it. The difference is how they find that session: + + * **Continue** finds the most recent session in the current directory. You don’t track anything. Works well when your app runs one conversation at a time. + * **Resume** takes a specific session ID. You track the ID. Required when you have multiple sessions (for example, one per user in a multi-user app) or want to return to one that isn’t the most recent. + +**Fork** is different: it creates a new session that starts with a copy of the original’s history. The original stays unchanged. Use fork to try a different direction while keeping the option to go back. ## ​ -Name your sessions - -Give sessions descriptive names so they’re findable in the session picker and resumable by name. This matters most when you’re working on several tasks in parallel. - -When| How to set the name ----|--- -At startup| `claude -n auth-refactor` -During a session| `/rename auth-refactor`. The name also appears on the prompt bar -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 -From claude.ai or the Claude app| Rename a [Remote Control session](</docs/en/remote-control#connect-from-another-device>); Claude Code applies the same name in the CLI. Requires Claude Code v2.1.221 or later -From the desktop app| Rename a session in the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>) - -Once you name a session through a CLI route or from claude.ai, return to it with `claude --resume <name>` or `/resume <name>`; a desktop-app session resumes in the app, which keeps its own session history. 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. If you don’t name a session, Claude Code generates a session title for it: a short summary of your first prompt, written by a background request to the small/fast model, normally a Haiku-class model. Naming the session with `--name` or `/rename` replaces the generated title. You see the generated title in the session picker and in the statusline [`session_name`](</docs/en/statusline>) field when no name is set; like the default display name, it isn’t a resume handle. +Automatic session management + +Both SDKs offer an interface that tracks session state for you across calls, so you don’t pass IDs around manually. Use these for multi-turn conversations within a single process. + +### + +​ + +Python: `ClaudeSDKClient` + +[`ClaudeSDKClient`](</docs/en/agent-sdk/python#claudesdkclient>) handles session IDs internally. Each call to `client.query()` automatically continues the same session. Call [`client.receive_response()`](</docs/en/agent-sdk/python#claudesdkclient>) to iterate over the messages for the current query. Use the client as an async context manager so connection setup and teardown are handled for you, or call `connect()` and `disconnect()` manually. This example runs two queries against the same `client`. The first asks the agent to analyze a module; the second asks it to refactor that module. Because both calls go through the same client instance, the second query has full context from the first without any explicit `resume` or session ID: + +Python + + import asyncio + from claude_agent_sdk import ( + ClaudeSDKClient, + ClaudeAgentOptions, + AssistantMessage, + ResultMessage, + TextBlock, + ) + + def print_response(message): + """Print only the human-readable parts of a message.""" + if isinstance(message, AssistantMessage): + for block in message.content: + if isinstance(block, TextBlock): + print(block.text) + elif isinstance(message, ResultMessage): + cost = ( + f"${message.total_cost_usd:.4f}" + if message.total_cost_usd is not None + else "N/A" + ) + print(f"[done: {message.subtype}, cost: {cost}]") + + async def main(): + options = ClaudeAgentOptions( + allowed_tools=["Read", "Edit", "Glob", "Grep"], + ) + + async with ClaudeSDKClient(options=options) as client: + # First query: client captures the session ID internally + await client.query("Analyze the auth module") + async for message in client.receive_response(): + print_response(message) + + # Second query: automatically continues the same session + await client.query("Now refactor it to use JWT") + async for message in client.receive_response(): + print_response(message) + + asyncio.run(main()) + +Each query prints the agent’s text response followed by a status line from the result message, such as `[done: success, cost: $0.0042]`. See the [Python SDK reference](</docs/en/agent-sdk/python#choosing-between-query-and-claudesdkclient>) for details on when to use `ClaudeSDKClient` vs the standalone `query()` function. + +### + +​ + +TypeScript: `continue: true` + +The TypeScript SDK doesn’t have a session-holding client object like Python’s `ClaudeSDKClient`. Instead, pass `continue: true` on each subsequent `query()` call and the SDK picks up the most recent session in the current directory. No ID tracking required. This example makes two separate `query()` calls. The first creates a fresh session; the second sets `continue: true`, which tells the SDK to find and resume the most recent session on disk. The agent has full context from the first call: + +TypeScript + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + // First query: creates a new session + try { + for await (const message of query({ + prompt: "Analyze the auth module", + options: { allowedTools: ["Read", "Glob", "Grep"] } + })) { + if (message.type === "result" && message.subtype === "success") { + console.log(message.result); + } + } + } catch (error) { + // A single-shot query() throws after yielding an error result, + // so the follow-up query below still runs. + console.error(`Session ended with an error: ${error}`); + } + + // Second query: continue: true resumes the most recent session + for await (const message of query({ + prompt: "Now refactor it to use JWT", + options: { + continue: true, + allowedTools: ["Read", "Edit", "Write", "Glob", "Grep"] + } + })) { + if (message.type === "result" && message.subtype === "success") { + console.log(message.result); + } + } + +The experimental [V2 session API](</docs/en/agent-sdk/typescript-v2-preview>), which provided `createSession()` with a `send` / `stream` pattern, was removed in TypeScript Agent SDK 0.3.142. Use the `query()` function and the session options described on this page instead. ## ​ -Use the session picker - -Run `/resume` inside a session, or `claude --resume` with no arguments, to open the interactive session picker. Use these keyboard shortcuts to navigate, search, and widen the list: - -Shortcut| Action ----|--- -`↑` / `↓`| Navigate between sessions -`→` / `←`| Expand or collapse grouped sessions -`Enter`| Resume the highlighted session -`Space`| Preview the session content. `Ctrl+V` also works on terminals that don’t capture it as paste -`Ctrl+R`| Rename the highlighted session -`/` or any printable character other than `Space`| Enter search mode and filter sessions. Paste a GitHub, GitHub Enterprise, GitLab, or Bitbucket pull or merge request URL to find the session that created it -`Ctrl+A`| Show sessions from all projects on this machine. Press again to return to the current repository -`Ctrl+W`| Show sessions from all worktrees of the current repository. Press again to return to the current worktree. Only shown in multi-worktree repositories -`Ctrl+B`| Filter to sessions from the current git branch. Press again to show all branches -`Esc`| Exit the session picker or search mode - -Each row shows the session name if you set one, otherwise the AI-generated session title, conversation summary, or first prompt, along with time since last activity, git branch, and file size. Widen to all projects with `Ctrl+A` to also see each session’s project path. Sessions created with `/branch` or `--fork-session` get their own session IDs and appear as separate rows. When the picker finds more than one entry for the same session, it groups them under a single row. Press `→` to expand a group. If Claude Code can’t load the session you select from the `claude --resume` picker, it prints [`Failed to resume the conversation`](</docs/en/errors#failed-to-resume-the-conversation>) with a command to retry, then exits with code 1. From the `/resume` picker inside a session, Claude Code reports the failure and your current conversation keeps running. +Use session options with `query()` + +### + +​ + +Capture the session ID + +Resume and fork require a session ID. Read it from the `session_id` field on the result message ([`ResultMessage`](</docs/en/agent-sdk/python#resultmessage>) in Python, [`SDKResultMessage`](</docs/en/agent-sdk/typescript#sdkresultmessage>) in TypeScript), which is present on every result regardless of success or error. In TypeScript the ID is also available earlier as a direct field on the init `SystemMessage`; in Python it’s nested inside `SystemMessage.data`. + +Python + +TypeScript + + import asyncio + from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage + + async def main(): + session_id = None + + try: + async for message in query( + prompt="Analyze the auth module and suggest improvements", + options=ClaudeAgentOptions( + allowed_tools=["Read", "Glob", "Grep"], + ), + ): + if isinstance(message, ResultMessage): + session_id = message.session_id + if message.subtype == "success": + print(message.result) + except Exception as error: + # A single-shot query() raises after yielding an error result. If the + # failure was an error result, the loop above already captured session_id; + # connection or process failures yield no result message, so session_id stays None. + print(f"Session ended with an error: {error}") + + print(f"Session ID: {session_id}") + return session_id + + session_id = asyncio.run(main()) + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + let sessionId: string | undefined; + + try { + for await (const message of query({ + prompt: "Analyze the auth module and suggest improvements", + options: { allowedTools: ["Read", "Glob", "Grep"] } + })) { + if (message.type === "result") { + sessionId = message.session_id; + if (message.subtype === "success") { + console.log(message.result); + } + } + } + } catch (error) { + // A single-shot query() throws after yielding an error result. If the + // failure was an error result, the loop above already captured sessionId; + // connection or process failures yield no result message, so sessionId stays undefined. + console.error(`Session ended with an error: ${error}`); + } + + console.log(`Session ID: ${sessionId}`); + +When the query completes, the script prints the agent’s response followed by a line such as `Session ID: 5b3f2c1a-8d4e-4f6b-9a7c-2e1d0f9b8a6c`. In the next sections, you pass this ID to `resume`. + +### + +​ + +Resume by ID + +Pass a session ID to `resume` to return to that specific session. The agent picks up with full context from wherever the session left off. Common reasons to resume: + + * **Follow up on a completed task.** The agent already analyzed something; now you want it to act on that analysis without re-reading files. + * **Recover from a limit.** The first run ended with `error_max_turns` or `error_max_budget_usd` (see [Handle the result](</docs/en/agent-sdk/agent-loop#handle-the-result>)); resume with a higher limit. In a single-shot `query()` call the SDK raises after yielding that error result, so catch the error before resuming. + * **Restart your process.** You captured the ID before shutdown and want to restore the conversation. + +This example resumes the session from Capture the session ID with a follow-up prompt. Because you’re resuming, the agent already has the prior analysis in context: + +Python + +TypeScript + + import asyncio + from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage + + session_id = "..." # The ID you captured in the previous example + + async def main(): + # Earlier session analyzed the code; now build on that analysis + async for message in query( + prompt="Now implement the refactoring you suggested", + options=ClaudeAgentOptions( + resume=session_id, + allowed_tools=["Read", "Edit", "Write", "Glob", "Grep"], + ), + ): + if isinstance(message, ResultMessage) and message.subtype == "success": + print(message.result) + + asyncio.run(main()) + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + const sessionId = "..."; // The ID you captured in the previous example + + // Earlier session analyzed the code; now build on that analysis + for await (const message of query({ + prompt: "Now implement the refactoring you suggested", + options: { + resume: sessionId, + allowedTools: ["Read", "Edit", "Write", "Glob", "Grep"] + } + })) { + if (message.type === "result" && message.subtype === "success") { + console.log(message.result); + } + } + +You should see a response that builds on the earlier analysis instead of starting fresh. That confirms the agent resumed the session with its prior context intact. + +Sessions are stored under `~/.claude/projects/<encoded-cwd>/*.jsonl`, or under `$CLAUDE_CONFIG_DIR/projects/<encoded-cwd>/*.jsonl` if you set the `CLAUDE_CONFIG_DIR` environment variable. `<encoded-cwd>` is the absolute working directory with every non-alphanumeric character replaced by `-`, so `/Users/me/proj` becomes `-Users-me-proj`.You can resume from any working directory: + + * **Cross-directory lookup** : Claude Code searches beyond the current project directory to find the ID; see [Resume a session](</docs/en/sessions#resume-a-session>) for the exact lookup order and how duplicate copies are handled. + * **Same machine only** : the session file still needs to exist on the current machine. + +Before v2.1.223, the lookup was scoped to the current project directory and its git worktrees; SDK versions that bundle an older CLI still behave this way. + +To resume sessions across machines or in serverless environments, mirror transcripts to shared storage with a [`SessionStore` adapter](</docs/en/agent-sdk/session-storage>). + +### + +​ + +Fork to explore alternatives + +Forking creates a new session that starts with a copy of the original’s history but diverges from that point. The fork gets its own session ID; the original’s ID and history stay unchanged. You end up with two independent sessions you can resume separately. + +Forking branches the conversation history, not the filesystem. If a forked agent edits files, those changes are real and visible to any session working in the same directory. To branch and revert file changes, use [file checkpointing](</docs/en/agent-sdk/file-checkpointing>). + +This example builds on Capture the session ID: you’ve already analyzed an auth module in `session_id` and want to explore OAuth2 without losing the JWT-focused thread. The first block forks the session and captures the fork’s ID (`forked_id`); the second block resumes the original `session_id` to continue down the JWT path. You now have two session IDs pointing at two separate histories: + +Python + +TypeScript + + import asyncio + from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage + + session_id = "..." # The ID you captured in the previous example + + async def main(): + # Fork: branch from session_id into a new session + forked_id = None + try: + async for message in query( + prompt="Instead of JWT, outline how OAuth2 would work for the auth module", + options=ClaudeAgentOptions( + resume=session_id, + fork_session=True, + max_turns=5, + ), + ): + if isinstance(message, ResultMessage): + forked_id = message.session_id # The fork's ID, distinct from session_id + if message.subtype == "success": + print(message.result) + except Exception as error: + # A single-shot query() raises after yielding an error result. If the + # failure was an error result, forked_id was already captured by the + # loop above; connection or process failures yield no result message. + print(f"Session ended with an error: {error}") + + print(f"Forked session: {forked_id}") + + # Original session is untouched; resuming it continues the JWT thread + try: + async for message in query( + prompt="Continue with the JWT approach", + options=ClaudeAgentOptions(resume=session_id), + ): + if isinstance(message, ResultMessage) and message.subtype == "success": + print(message.result) + except Exception as error: + # A single-shot query() raises after yielding an error result. + print(f"Session ended with an error: {error}") + + asyncio.run(main()) + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + const sessionId = "..."; // The ID you captured in the previous example + + // Fork: branch from sessionId into a new session + let forkedId: string | undefined; + + try { + for await (const message of query({ + prompt: "Instead of JWT, outline how OAuth2 would work for the auth module", + options: { + resume: sessionId, + forkSession: true, + maxTurns: 5 + } + })) { + if (message.type === "system" && message.subtype === "init") { + forkedId = message.session_id; // The fork's ID, distinct from sessionId + } + if (message.type === "result" && message.subtype === "success") { + console.log(message.result); + } + } + } catch (error) { + // A single-shot query() throws after yielding an error result. If the + // failure was an error result, forkedId was already captured by the loop + // above; connection or process failures yield no result message. + console.error(`Session ended with an error: ${error}`); + } + + console.log(`Forked session: ${forkedId}`); + + // Original session is untouched; resuming it continues the JWT thread + try { + for await (const message of query({ + prompt: "Continue with the JWT approach", + options: { resume: sessionId } + })) { + if (message.type === "result" && message.subtype === "success") { + console.log(message.result); + } + } + } catch (error) { + // A single-shot query() throws after yielding an error result. + console.error(`Session ended with an error: ${error}`); + } + +You should see that `forkedId` differs from the original session ID. Resuming the original session still continues the JWT thread, which confirms the fork did not modify the original history. ## ​ -Branch a session - -Branching creates a copy of the conversation so far and switches you into it, leaving the original intact. Use it to try a different approach without losing the path you were on. From inside a session, run `/branch` with an optional name: - - /branch try-streaming-approach - -If you omit the name, Claude Code names the new branch after the first prompt in the conversation. As of v2.1.198 this also applies after [compaction](</docs/en/how-claude-code-works#when-context-fills-up>); earlier versions fell back to the literal name `Branched conversation` instead of looking past the compaction summary to the original first prompt. From the command line, combine `--continue` or `--resume` with `--fork-session`: - - claude --continue --fork-session - -The `/branch` confirmation prints two session IDs: the new branch you are now in and the original. The original is unchanged on disk and remains in the session picker; return to it with `/resume <original-name>` or by passing its ID to `/resume`. `/branch` copies the transcript and switches the running Claude Code process to write to it. That distinction determines what the branch inherits: - -State| After `/branch` ----|--- -Conversation history| Copied into the branch up to the point you ran `/branch` -”Allow for this session” permission grants| Carried over; the branch runs in the same process, so your existing grants still apply. If you fork into a separate process with `--fork-session`, the new process starts without them and you re-approve there -In-flight [background subagents](</docs/en/sub-agents#run-subagents-in-foreground-or-background>) and [background Bash commands](</docs/en/interactive-mode#background-bash-commands>)| Keep running. Their output appears in the new branch you switched into, not in the original session - -If you resume the same session in two terminals without forking, messages from both interleave into one transcript. For checkpoint-based rewind within a single session, see [Checkpointing](</docs/en/checkpointing>). +Resume across hosts + +Session files are local to the machine that created them. To resume a session on a different host (CI workers, ephemeral containers, serverless), you have two options: + + * **Move the session file.** Persist `~/.claude/projects/<encoded-cwd>/<session-id>.jsonl` from the first run and restore it inside any directory under `~/.claude/projects/` on the new host before calling `resume`. Claude Code searches beyond the current project directory to find the ID; see [Resume a session](</docs/en/sessions#resume-a-session>) for the exact lookup order and how duplicate copies are handled. Before v2.1.223, the lookup was scoped to the current project directory and its git worktrees; SDK versions that bundle an older CLI still behave this way. + * **Don’t rely on session resume.** Capture the results you need (analysis output, decisions, file diffs) as application state and pass them into a fresh session’s prompt. This is often more robust than shipping transcript files around. + +Both SDKs expose functions for enumerating sessions on disk and reading their messages: [`listSessions()`](</docs/en/agent-sdk/typescript#listsessions>) and [`getSessionMessages()`](</docs/en/agent-sdk/typescript#getsessionmessages>) in TypeScript, [`list_sessions()`](</docs/en/agent-sdk/python#list_sessions>) and [`get_session_messages()`](</docs/en/agent-sdk/python#get_session_messages>) in Python. Use them to build custom session pickers, cleanup logic, or transcript viewers. Both SDKs also expose functions for looking up and mutating individual sessions: [`get_session_info()`](</docs/en/agent-sdk/python#get_session_info>), [`rename_session()`](</docs/en/agent-sdk/python#rename_session>), and [`tag_session()`](</docs/en/agent-sdk/python#tag_session>) in Python, and [`getSessionInfo()`](</docs/en/agent-sdk/typescript#getsessioninfo>), [`renameSession()`](</docs/en/agent-sdk/typescript#renamesession>), and [`tagSession()`](</docs/en/agent-sdk/typescript#tagsession>) in TypeScript. Use them to organize sessions by tag or give them human-readable titles. ## ​ -Manage context within a session - -These commands control what’s in the context window without leaving the session: - - * **`/clear`** : start fresh with an empty context. Claude Code saves the previous conversation; resume it with `/resume`, or, in the same Claude Code process, from [the rewind menu’s previous-session entry](</docs/en/checkpointing#rewind-past-a-cleared-conversation>). You keep a name you set with `--name` or `/rename` in the new conversation, but not an AI-generated session title - * **`/compact [instructions]`** : replace history with a summary, optionally focused on what you specify - * **`/context`** : show what is currently consuming context - -For how compaction interacts with CLAUDE.md, skills, and rules, see the [context window guide](</docs/en/context-window>). For strategies on when to clear versus compact, see [Best practices](</docs/en/best-practices#manage-your-session>). - -## - -​ - -Export and locate session data - -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. - -### - -​ - -Access conversations from scripts - -`/export` produces a rendered transcript for a person to read. The interfaces below produce structured data for a script to parse: a JSON result from a run, the path to a session’s transcript file, or a live stream of events. Pick by what triggers the script: - - * **Run Claude once and capture the result** : invoke `claude -p` with [`--output-format json` or `stream-json`](</docs/en/headless#get-structured-output>) to capture the result, session ID, usage, and cost of a non-interactive run as structured JSON. - * **Ask an existing session a question** : pass a session ID to [`claude -p --resume`](</docs/en/headless#continue-conversations>) to send a follow-up prompt, such as a summary request, and capture the structured response. - * **React to session events** : read the `transcript_path` field that [hooks](</docs/en/hooks#common-input-fields>) and [status line commands](</docs/en/statusline#available-data>) receive as input. A `SessionEnd` hook can archive the transcript when a session ends. - * **Embed Claude in a TypeScript or Python app** : use the [Agent SDK](</docs/en/agent-sdk/overview>) to receive each message programmatically. - -The example below uses the second interface. It sends a follow-up prompt to an existing session and reads the answer with `jq`: - - claude -p --resume <session-id> --output-format json "summarize what we changed" | jq -r '.result' - -### - -​ - -Where transcripts are stored - -By default, transcripts are stored as JSONL at `~/.claude/projects/<project>/<session-id>.jsonl`, where `<project>` is your working directory path with non-alphanumeric characters replaced by `-`. Each line is a JSON object for a message, tool use, or metadata entry. The entry format is internal to Claude Code and changes between versions, so scripts that parse these files directly can break on any release. To build on session data, use `/export` or the script interfaces instead. The location, retention, and write behavior are configurable: - -To| Set| Where ----|---|--- -Move storage off `~/.claude`| [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars>)| Environment variable -Change the 30-day retention| [`cleanupPeriodDays`](</docs/en/settings#available-settings>)| `settings.json` -Suppress transcript writes in all modes| [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](</docs/en/env-vars>)| Environment variable -Suppress writes for one non-interactive run| [`--no-session-persistence`](</docs/en/cli-reference>)| CLI flag with `claude -p` - -## - -​ - -See also - -These pages cover related session and parallelism mechanics: - - * [Worktrees](</docs/en/worktrees>): run isolated parallel sessions on separate branches - * [Checkpointing](</docs/en/checkpointing>): rewind code and conversation to an earlier point - * [Context window](</docs/en/context-window>): what fills context and what survives compaction - * [Non-interactive mode](</docs/en/headless>): session behavior under `claude -p` +Related resources + + * [How the agent loop works](</docs/en/agent-sdk/agent-loop>): Understand turns, messages, and context accumulation within a session + * [File checkpointing](</docs/en/agent-sdk/file-checkpointing>): Snapshot and revert file changes the agent made within a session + * [Python `ClaudeAgentOptions`](</docs/en/agent-sdk/python#claudeagentoptions>): Full session option reference for Python + * [TypeScript `Options`](</docs/en/agent-sdk/typescript#options>): Full session option reference for TypeScript
modified Claude Code settings View current →
--- a/settings.md +++ b/settings.md @@ -247,7 +247,7 @@ `crossSessionInbound`| How this session treats inbound [cross-session messages](</docs/en/cross-session-messaging#control-inbound-messages>) from your other Claude Code sessions: `"accept"` delivers them to Claude, `"hold"` shows a notice for each message without delivering it, and `"refuse"` drops them. When no value applies, Claude Code decides per message from the two sessions’ permission-mode classes; see [Control inbound messages](</docs/en/cross-session-messaging#control-inbound-messages>) for the rules. Claude Code reads managed settings first, then the `--settings` flag, then user settings, and applies the first value found; a value in project or local settings applies only when it’s stricter, on the `accept` < `hold` < `refuse` ladder, than the value those trusted sources give. When none of the trusted sources sets a value, a project or local `hold` or `refuse` still applies, replacing the per-message default. Requires Claude Code v2.1.224 or later| `"hold"` `defaultShell`| **Default** : `"bash"`, or `"powershell"` on Windows when Bash isn’t available. Default shell for input-box `!` commands. Accepts `"bash"` or `"powershell"`. Setting `"powershell"` routes interactive `!` commands through PowerShell when the [PowerShell tool](</docs/en/tools-reference#powershell-tool>) is enabled: it’s on by default on Windows without Git Bash, and `CLAUDE_CODE_USE_POWERSHELL_TOOL=1` enables it elsewhere| `"powershell"` `deniedMcpServers`| When set in managed-settings.json, denylist of MCP servers that are explicitly blocked. Applies to all scopes including managed servers. Denylist takes precedence over allowlist. See [Managed MCP configuration](</docs/en/managed-mcp>)| `[{ "serverName": "filesystem" }]` -`dialogExpiry`| **Default** : `"5m"`. Deadline for dialogs Claude Code forwards to a remote client, such as a [Remote Control](</docs/en/remote-control>) or SDK host, for example the model-choice prompt shown after a safety refusal, and for the approval dialog for a [held cross-session message](</docs/en/cross-session-messaging#control-inbound-messages>). When no answer arrives before the deadline, Claude Code cancels the dialog and continues with its no-action default. For a held message, that drops the message. Permission prompts and [`AskUserQuestion`](</docs/en/tools-reference#askuserquestion-tool-behavior>) questions use their own flows and aren’t governed by this deadline. Accepts `"60s"`, `"5m"`, `"10m"`, or `"never"`, which disables the deadline. The [`CLAUDE_CODE_USER_DIALOG_TIMEOUT_MS`](</docs/en/env-vars>) environment variable overrides this setting. Read from user, managed, and `--settings` sources only. Requires Claude Code v2.1.224 or later| `"10m"` +`dialogExpiry`| **Default** : `"5m"`. Deadline for dialogs Claude Code forwards to a remote client, such as a [Remote Control](</docs/en/remote-control>) or SDK host, for example the model-choice prompt shown after a safety refusal, and for a [held cross-session message](</docs/en/cross-session-messaging#control-inbound-messages>) awaiting approval. When no answer arrives before the deadline, Claude Code cancels the dialog and continues with its no-action default; when the deadline passes on a message the [inbound default](</docs/en/cross-session-messaging#control-inbound-messages>) holds, Claude Code drops it. Permission prompts and [`AskUserQuestion`](</docs/en/tools-reference#askuserquestion-tool-behavior>) questions use their own flows and aren’t governed by this deadline. Accepts `"60s"`, `"5m"`, `"10m"`, or `"never"`, which disables the deadline. The [`CLAUDE_CODE_USER_DIALOG_TIMEOUT_MS`](</docs/en/env-vars>) environment variable overrides this setting. Read from user, managed, and `--settings` sources only. Requires Claude Code v2.1.224 or later| `"10m"` `disableAgentView`| Set to `true` to turn off [background agents and agent view](</docs/en/agent-view>): `claude agents`, `--bg`, `/background`, and the on-demand supervisor. Typically set in [managed settings](</docs/en/permissions#managed-settings>). Equivalent to setting `CLAUDE_CODE_DISABLE_AGENT_VIEW` to `1`| `true` `disableAllHooks`| Disable all [hooks](</docs/en/hooks>) and any custom [status line](</docs/en/statusline>)| `true` `disableArtifact`| Set to `true` to disable the [Artifact](</docs/en/artifacts>) tool, which publishes session output as a private web page on claude.ai. Equivalent to setting `CLAUDE_CODE_DISABLE_ARTIFACT` to `1`| `true` @@ -286,19 +286,19 @@ `httpHookAllowedEnvVars`| Allowlist of environment variable names HTTP hooks may interpolate into headers. When set, each hook’s effective `allowedEnvVars` is the intersection with this list. Undefined = no restriction. Arrays merge across settings sources. See Hook configuration| `["MY_TOKEN", "HOOK_SECRET"]` `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>)| `true` -`isolatePeerMachines`| Require your explicit approval before Claude’s `SendMessage` reply reaches one of your sessions beyond this machine; see [cross-session messaging](</docs/en/cross-session-messaging#require-approval-for-cross-machine-messages>). The approval prompt appears even in [`bypassPermissions` mode](</docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode>). A `true` from any settings scope applies, so a checked-in project file can turn the requirement on but not off. The cross-machine `SendMessage` approval requires Claude Code v2.1.224 or later| `true` +`isolatePeerMachines`| Require your explicit approval before Claude’s `SendMessage` reaches one of your sessions beyond this machine; see [cross-session messaging](</docs/en/cross-session-messaging#require-approval-for-cross-machine-messages>). The approval prompt appears even in [`bypassPermissions` mode](</docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode>). A `true` from any settings scope applies, so a checked-in project file can turn the requirement on but not off. The cross-machine `SendMessage` approval requires Claude Code v2.1.224 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"` `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-5"` `modelOverrides`| Map Anthropic model IDs to provider-specific model IDs such as Amazon 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:..."}` `otelHeadersHelper`| Script to generate dynamic OpenTelemetry headers. Runs at startup and periodically. Set the refresh interval with [`CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS`](</docs/en/env-vars>). See [Dynamic headers](</docs/en/monitoring-usage#dynamic-headers>)| `/bin/generate_otel_headers.sh` `outputStyle`| Configure an output style to adjust the system prompt. See [output styles documentation](</docs/en/output-styles>)| `"Explanatory"` -`parentSettingsBehavior`| (Managed settings only) **Default** : `"first-wins"`. Controls whether managed settings supplied programmatically by an embedding host process, such as the Agent SDK or an IDE extension, apply when an admin-deployed managed tier is also present. `"first-wins"`: the parent-supplied settings are dropped and only the admin tier applies. `"merge"`: the parent-supplied settings apply under the admin tier through a restrictive-only filter. Only the highest-priority managed source’s value of this key is read. Unless the `allowManaged*Only` locks are set, allow-direction entries such as permission allow rules and sandbox allowlists still apply; see [Restrict parent settings](</docs/en/claude-apps-gateway#restrict-parent-settings>). Has no effect when no admin tier is deployed, or when a `policyHelper` is configured: the helper’s output replaces every other managed source and parent settings are never merged. Requires Claude Code v2.1.133 or later| `"merge"` +`parentSettingsBehavior`| (Managed settings only) **Default** : `"first-wins"`. Controls whether Claude Code applies managed settings supplied by an embedding host process, such as the Agent SDK or an IDE extension, when an admin-deployed managed tier is also present. With `"first-wins"`, Claude Code drops the parent-supplied settings. With `"merge"`, Claude Code applies them under the admin tier through a restrictive-only filter. For the filter’s limits and how the managed sources interact, see Settings precedence and [Restrict parent settings](</docs/en/claude-apps-gateway#restrict-parent-settings>)| `"merge"` `permissions`| See table below for structure of permissions.| `plansDirectory`| **Default** : `~/.claude/plans`. Customize where plan files are stored. Path is relative to project root.| `"./plans"` `pluginSuggestionMarketplaces`| (Managed settings only) Marketplace names whose plugins can appear as contextual install suggestions. No marketplace-declared suggestions surface without this allowlist; the built-in first-party frontend-design tip is unaffected. Suggestions come from each plugin’s `relevance` declaration in its marketplace entry. A name only takes effect when the marketplace is registered on the machine and its registered source is also declared in managed settings, either as the `extraKnownMarketplaces` entry for that name or as an entry of `strictKnownMarketplaces`. A marketplace registered from a different source under an allowlisted name is ignored. The official marketplace is exempt from the source requirement: allowlisting its name alone suffices, since that name can only register from the official Anthropic source.| `["acme-corp-plugins"]` `pluginTrustMessage`| (Managed settings only) Custom message appended to the plugin trust warning shown before installation. Use this to add organization-specific context, for example to confirm that plugins from your internal marketplace are vetted.| `"All plugins from our marketplace are approved by IT"` -`policyHelper`| Admin-deployed executable that computes managed settings dynamically at startup. Only honored from MDM or a system `managed-settings.json` file. See Compute managed settings with a policy helper. Requires Claude Code v2.1.136 or later| `{"path": "/usr/local/bin/claude-policy"}` +`policyHelper`| Admin-deployed executable that computes managed settings dynamically at startup. Only honored from MDM or a system `managed-settings.json` file. See Compute managed settings with a policy helper| `{"path": "/usr/local/bin/claude-policy"}` `preferredNotifChannel`| **Default** : `"auto"`. Method for task-complete and permission-prompt notifications: `"auto"`, `"terminal_bell"`, `"iterm2"`, `"iterm2_with_bell"`, `"kitty"`, `"ghostty"`, or `"notifications_disabled"`. `"auto"` sends a desktop notification in iTerm2, Ghostty, and Kitty and does nothing in other terminals. Set `"terminal_bell"` to ring the bell character in any terminal. Appears in `/config` as **Notifications**. See [Get a terminal bell or notification](</docs/en/terminal-config#get-a-terminal-bell-or-notification>)| `"terminal_bell"` `prefersReducedMotion`| Reduce or disable UI animations (spinners, shimmer, flash effects) for accessibility| `true` `processWrapper`| Corporate launcher command placed in front of the [background processes Claude Code starts](</docs/en/corporate-launcher#what-the-launcher-covers>). Honored from managed settings, a `--settings` file, and user settings only; the [`CLAUDE_CODE_PROCESS_WRAPPER`](</docs/en/env-vars>) environment variable takes precedence when both are set. See [Run Claude Code behind a corporate launcher](</docs/en/corporate-launcher>) for the launcher contract. Requires Claude Code v2.1.210 or later| `"/opt/corp/launcher --profile claude"`
modified Agent Skills in the SDK View current →
Show diff (1213 lines)
--- a/skills.md +++ b/skills.md @@ -1,845 +1,220 @@ -Skills extend what Claude can do. Create a `SKILL.md` file with instructions, and Claude adds it to its toolkit. Claude uses skills when relevant, or you can invoke one directly with `/skill-name`. Create a skill when you keep pasting the same instructions, checklist, or multi-step procedure into chat, or when a section of CLAUDE.md has grown into a procedure rather than a fact. Unlike CLAUDE.md content, a skill’s body loads only when it’s used, so long reference material costs almost nothing until you need it. - -For built-in commands like `/help` and `/compact`, and bundled skills like `/debug` and `/code-review`, see the [commands reference](</docs/en/commands>).**Custom commands have been merged into skills.** A file at `.claude/commands/deploy.md` and a skill at `.claude/skills/deploy/SKILL.md` both create `/deploy` and work the same way. Your existing `.claude/commands/` files keep working. Skills add optional features: a directory for supporting files, frontmatter to control whether you or Claude invokes them, and the ability for Claude to load them automatically when relevant. - -Claude Code skills follow the [Agent Skills](<https://agentskills.io>) open standard, which works across multiple AI tools. Claude Code extends the standard with additional features like invocation control, subagent execution, and dynamic context injection. See Using skill frontmatter outside Claude Code for which frontmatter fields are part of the standard and which are Claude Code extensions. - -## - -​ - -Bundled skills - -Claude Code includes a set of bundled skills, such as `/doctor`, `/code-review`, `/batch`, `/debug`, `/loop`, and `/claude-api`. Bundled skills are prompt-based: they give Claude detailed instructions and let it orchestrate the work using its tools. Most built-in commands instead execute fixed logic directly. You invoke a bundled skill the same way as any other skill, by typing `/` followed by the skill name. Claude invokes some bundled skills automatically when relevant; others, including `/verify` and `/code-review`, run only when you invoke them, which keeps you in control of when these longer-running checks spend time and tokens. Before v2.1.215, Claude could also run `/verify` and `/code-review` on its own. Bundled skills are available in every session. To turn them off, use the [`disableBundledSkills`](</docs/en/settings#available-settings>) setting, which disables every bundled skill except `/doctor`. - -The [`/doctor`](</docs/en/commands#all-commands>) setup checkup stays typable when `disableBundledSkills` is on, in Claude Code v2.1.205 and later. To hide it, set the `DISABLE_DOCTOR_COMMAND` environment variable or a `skillOverrides` entry of `"doctor": "off"`. Before v2.1.205, `/doctor` was a built-in command rather than a bundled skill. - -Bundled skills are listed alongside built-in commands in the [commands reference](</docs/en/commands>), marked **Skill** in the Purpose column. - -### - -​ - -Run and verify your app - -Three bundled skills work together to launch your app and confirm changes against the running app instead of just tests: - -Skill| Purpose ----|--- -`/run`| Launch and drive your app to see a change working -`/verify`| Build and run your app to confirm a code change does what it should, without falling back to tests or type checks -`/run-skill-generator`| Teach `/run` and `/verify` how to build and launch your project - -All three skills require Claude Code v2.1.145 or later. Check your version with `claude --version` or the `/status` command. `/run` and `/verify` work without setup. They infer the launch from your project type (CLI, server, TUI, browser-driven) and from what’s in your README, `package.json`, or `Makefile`. That inference gets unreliable for projects that need anything beyond a standard launch: a database, an env file, a graphical session, a multi-step build. `/run-skill-generator` records the recipe instead. It gets your app running from a clean environment, captures what worked (the install commands, the env vars, the launch script), and commits it as a per-project skill at `.claude/skills/run-<name>/`. After that, `/run`, `/verify`, and any other agent in the repo follow the recorded recipe instead of rediscovering it. Run `/run-skill-generator` once per project, and again if the build or launch process changes. `/verify` can also record its own recipe. When it has to build and drive your app without a recorded recipe, it writes what worked to `.claude/skills/verify/SKILL.md` at the repo root, or in the touched package directory in a monorepo, so later runs and other agents follow the same steps. At the repo root, the recorded skill replaces the bundled `/verify`. This requires Claude Code v2.1.200 or later. Claude edits the recorded file only when it steered a run wrong, such as a command that failed or a missing step, so you can commit the file without per-session diffs. Before v2.1.205, the bundled skill told Claude to fold in anything a run learned, which caused frequent merge conflicts. - -## - -​ - -Getting started - -### - -​ - -Create your first skill - -This example creates a skill that summarizes the uncommitted changes in your git repository and flags anything risky. It pulls the live diff into the prompt before Claude reads it, so the response is grounded in your actual working tree rather than what Claude can guess from open files. Claude loads the skill automatically when you ask about your changes, or you can invoke it directly with `/summarize-changes`. - -1 - -Create the skill directory - -Create a directory for the skill in your personal skills folder. Personal skills are available across all your projects. - - mkdir -p ~/.claude/skills/summarize-changes - -2 - -Write SKILL.md - -Every skill needs a `SKILL.md` file with two parts: YAML frontmatter between `---` markers that tells Claude when to use the skill, and markdown content with the instructions Claude follows when the skill runs. The directory name becomes the command you type, and the `description` helps Claude decide when to load the skill automatically.Save this to `~/.claude/skills/summarize-changes/SKILL.md`: - - --- - description: Summarizes uncommitted changes and flags anything risky. Use when the user asks what changed, wants a commit message, or asks to review their diff. - --- - - ## Current changes - - !`git diff HEAD` - - ## Instructions - - Summarize the changes above in two or three bullet points, then list any risks you notice such as missing error handling, hardcoded values, or tests that need updating. If the diff is empty, say there are no uncommitted changes. - -The `!`git diff HEAD`` line uses dynamic context injection: Claude Code runs the command and replaces the line with its output before Claude sees the skill content, so the instructions arrive with the current diff already inlined. - -3 - -Test the skill - -Open a git project, make a small edit to any file, and start Claude Code by running `claude`. You can test the skill two ways.**Let Claude invoke it automatically** by asking something that matches the description: - - What did I change? - -**Or invoke it directly** with the skill name: - - /summarize-changes - -Either way, Claude should respond with a short summary of your edit and a list of risks. - -### - -​ - -Where skills live - -Where you store a skill determines who can use it: - -Location| Path| Applies to ----|---|--- -Enterprise| See [managed settings](</docs/en/settings#settings-files>)| All users in your organization -Personal| `~/.claude/skills/<skill-name>/SKILL.md`| All your projects -Project| `.claude/skills/<skill-name>/SKILL.md`| This project only -Plugin| `<plugin>/skills/<skill-name>/SKILL.md`| Where plugin is enabled - -When skills share the same name across levels, enterprise overrides personal, and personal overrides project. A skill at any of these levels also overrides a bundled skill with the same name. For example, a `code-review` skill in your project’s `.claude/skills/` replaces the bundled `/code-review`. Plugin skills use a `plugin-name:skill-name` namespace, so they cannot conflict with other levels. If you have files in `.claude/commands/`, those work the same way, but if a skill and a command share the same name, the skill takes precedence. Skills also load from nested `.claude/skills/` directories below your working directory. When Claude reads or edits a file in a subdirectory, skills from that subdirectory’s `.claude/skills/` become available. This lets a monorepo package provide its own skills that apply when working on that package, even if the session started at the repo root. If a nested skill shares a name with another skill, both stay available. For example, with a `deploy` skill at the project root and another in `apps/web/.claude/skills/`: - - * The nested one appears under a directory-qualified name, `apps/web:deploy`. - * Its description says which directory it applies to. - * Claude picks the variant that matches the files it is working on. - -Typing `/deploy` runs the project-root skill. Type the qualified name `/apps/web:deploy` to run the nested variant explicitly. When you or Claude invoke the unqualified name, the project-root skill loads, and Claude Code appends a list of the directory-qualified variants to its content with an instruction to also invoke any variant whose directory holds the files Claude is working on. A nested skill therefore still applies to work in its directory when only the unqualified name is invoked. Requires Claude Code v2.1.203 or later. A `<skill-name>` entry in the enterprise, personal, or project locations can be a symlink to a directory elsewhere on disk. Claude Code follows the symlink and reads `SKILL.md` from the target directory, and if the same target is reachable from more than one location, Claude Code loads the skill once. Plugin skills handle symlinks differently; see [Share files within a marketplace with symlinks](</docs/en/plugins-reference#share-files-within-a-marketplace-with-symlinks>). - -Add a `.claude-plugin/plugin.json` to a skill folder and it loads as a [plugin](</docs/en/plugins-reference#skills-directory-plugins>) named `<name>@skills-dir`, so it can bundle agents, hooks, and MCP servers. In a project’s `.claude/skills/`, this requires accepting the workspace trust dialog first. - -#### - -​ - -Live change detection - -Claude Code watches skill directories for file changes. When you add, edit, or remove a skill under `~/.claude/skills/`, the project `.claude/skills/`, or a `.claude/skills/` inside an `--add-dir` directory, Claude Code picks up the change within the current session, without a restart. If you create a top-level skills directory that didn’t exist when the session started, restart Claude Code so it can watch the new directory. - -Live change detection covers `SKILL.md` text only. For a skill folder that is also a [plugin](</docs/en/plugins-reference#skills-directory-plugins>), changes to `hooks/`, `.mcp.json`, `agents/`, and `output-styles/` need `/reload-plugins` to take effect. - -#### - -​ - -Discovery from parent and nested directories - -Project skills load from `.claude/skills/` in the directory where you start Claude Code and in every parent directory up to the repository root. Starting Claude in a subdirectory still picks up skills defined at the root. To load skills from a directory outside that path at startup, pass it with [`--add-dir`](</docs/en/cli-reference>). Claude Code reads `.claude/skills/` inside each added directory alongside the project skills. Skills in nested `.claude/skills/` directories below your starting directory aren’t loaded at startup. They load the first time Claude reads or edits a file inside that subdirectory, and stay available for the rest of the session. For example, after Claude edits a file under `packages/frontend/`, skills in `packages/frontend/.claude/skills/` become available. Until then, those skills don’t appear in autocomplete and can’t be invoked by name. Each skill is a directory with `SKILL.md` as the entrypoint: - - my-skill/ - ├── SKILL.md # Main instructions (required) - ├── template.md # Template for Claude to fill in - ├── examples/ - │ └── sample.md # Example output showing expected format - └── scripts/ - └── validate.sh # Script Claude can execute - -The `SKILL.md` contains the main instructions and is required. Other files are optional and let you build more powerful skills: templates for Claude to fill in, example outputs showing the expected format, scripts Claude can execute, or detailed reference documentation. Reference these files from your `SKILL.md` so Claude knows what they contain and when to load them. See Add supporting files for more details. - -Files in `.claude/commands/` support the same frontmatter. Skills are recommended since they support additional features like supporting files. - -#### - -​ - -Skills from additional directories - -The `--add-dir` flag and `/add-dir` command [grant file access](</docs/en/permissions#additional-directories-grant-file-access-not-configuration>) rather than configuration discovery, but skills are an exception: `.claude/skills/` within an added directory is loaded automatically. This exception applies only to `--add-dir` and `/add-dir`. The `permissions.additionalDirectories` setting in `settings.json` grants file access only and does not load skills. See Live change detection for how edits are picked up during a session. Other `.claude/` configuration such as commands and output styles is not loaded from additional directories. See the [exceptions table](</docs/en/permissions#additional-directories-grant-file-access-not-configuration>) for the complete list of what is and isn’t loaded, and the recommended ways to share configuration across projects. - -CLAUDE.md files from `--add-dir` directories are not loaded by default. To load them, set `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1`. See [Load from additional directories](</docs/en/memory#load-from-additional-directories>). - -#### - -​ - -Skills in Cowork and cloud sessions - -[Cowork](<https://claude.com/product/cowork>) sessions and [cloud sessions](</docs/en/cloud-environments#what-carries-over-from-your-setup>), including [routines](</docs/en/routines>), don’t read `~/.claude/skills/` on your machine. Both interactive and scheduled Cowork sessions load the skills enabled for your claude.ai account, synced at session start; manage them from **Customize** in the Desktop app sidebar or from the skills settings on claude.ai. Cloud sessions additionally load project skills committed to the cloned repository’s `.claude/skills/`. If a skill exists only in `~/.claude/skills/` on your machine, Claude Code reports that the skill was not found when a [routine](</docs/en/routines>) invokes it, because each routine run starts as a fresh remote session. To make a personal skill available in these sessions: - - * For Cowork and cloud sessions, enable the skill for your claude.ai account. - * For cloud sessions, you can instead commit the skill to the repository’s `.claude/skills/`, or ship it in a plugin declared in the repository’s `.claude/settings.json`. Repo-declared plugins [install at session start](</docs/en/cloud-environments#what-carries-over-from-your-setup>); plugins enabled only in your user settings don’t transfer. - -[Desktop scheduled tasks](</docs/en/desktop-scheduled-tasks>) are different: they run locally on your machine and load skills from the same locations as any other local session. - -## - -​ - -Configure skills - -Skills are configured through YAML frontmatter at the top of `SKILL.md` and the markdown content that follows. - -### - -​ - -Types of skill content - -Skill files can contain any instructions, but thinking about how you want to invoke them helps guide what to include: **Reference content** adds knowledge Claude applies to your current work. Conventions, patterns, style guides, domain knowledge. This content runs inline so Claude can use it alongside your conversation context. - - --- - name: api-conventions - description: API design patterns for this codebase - --- - - When writing API endpoints: - - Use RESTful naming conventions - - Return consistent error formats - - Include request validation - -**Task content** gives Claude step-by-step instructions for a specific action, like deployments, commits, or code generation. These are often actions you want to invoke directly with `/skill-name` rather than letting Claude decide when to run them. Add `disable-model-invocation: true` to prevent Claude from triggering it automatically. The example below adds `context: fork`, which runs the skill in its own subagent context; see Run skills in a subagent. - - --- - name: deploy - description: Deploy the application to production - context: fork - disable-model-invocation: true - --- - - Deploy the application: - 1. Run the test suite - 2. Build the application - 3. Push to the deployment target - -Keep the body itself concise. Once a skill loads, its content stays in context across turns, so every line is a recurring token cost. State what to do rather than narrating how or why, and apply the same conciseness test you would for [CLAUDE.md content](</docs/en/best-practices#write-an-effective-claude-md>). - -### - -​ - -Frontmatter reference - -Beyond the markdown content, you can configure skill behavior using YAML frontmatter fields between `---` markers at the top of your `SKILL.md` file: - - --- - name: my-skill - description: What this skill does - disable-model-invocation: true - allowed-tools: Read Grep - --- - - Your skill instructions here... - -All fields are optional. Only `description` is recommended so Claude knows when to use the skill. Boolean fields accept `yes`, `no`, `on`, `off`, `1`, and `0` in any letter case, in addition to `true` and `false`. Before v2.1.218, Claude Code recognized only `true` and `false`. - -Field| Required| Description ----|---|--- -`name`| No| Display name shown in skill listings. Defaults to the directory name. See How a skill gets its command name for how the field interacts with the name you type to invoke the skill. -`description`| Recommended| What the skill does and when to use it. Claude uses this to decide when to apply the skill. If omitted, uses the first paragraph of markdown content. Put the key use case first: the combined `description` and `when_to_use` text is truncated at 1,536 characters in the skill listing to reduce context usage. -`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>). 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 during the turn that invokes this skill. The grant clears when you send your next message. Accepts a space- or comma-separated string, or a YAML list. See Pre-approve tools for a skill. -`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. Like deny rules, the field can’t remove [`EndConversation`](</docs/en/tools-reference#endconversation-tool-behavior>) while any other tool remains. -`model`| No| Model to use when this skill is active. The override applies for the rest of the current turn and is not saved to settings; the session model resumes on your next prompt. Accepts the same values as [`/model`](</docs/en/model-config>), or `inherit` to keep the active model. A value excluded by your organization’s [`availableModels`](</docs/en/model-config#restrict-model-selection>) allowlist is not used and the session keeps its current model. With `context: fork`, the value sets the forked subagent’s model instead, and an excluded value follows the [same rules as a subagent model override](</docs/en/model-config#restrict-model-selection>). -`effort`| No| [Effort level](</docs/en/model-config#adjust-effort-level>) when this skill is active. Overrides the session effort level. Default: inherits from session. Options: `low`, `medium`, `high`, `xhigh`, `max`; available levels depend on the model. -`context`| No| Set to `fork` to run in a forked subagent context. See Run skills in a subagent. -`agent`| No| Which subagent type to use when `context: fork` is set. -`background`| No| Only applies with `context: fork`. Set to `false` to wait for the forked subagent’s result in the turn that invoked the skill, instead of running it in the background. Default: `true`. Requires Claude Code v2.1.218 or later. -`hooks`| No| Hooks scoped to this skill’s lifecycle. See [Hooks in skills and agents](</docs/en/hooks#hooks-in-skills-and-agents>) for configuration format. -`paths`| No| Glob patterns that limit when this skill is activated. Accepts a comma-separated string or a YAML list. When set, Claude loads the skill automatically only when working with files matching the patterns. Uses the same format as [path-specific rules](</docs/en/memory#path-specific-rules>). -`shell`| No| Shell to use for `!`command`` and ````!` blocks in this skill. Accepts `bash` (default) or `powershell`. Setting `powershell` runs inline shell commands via PowerShell when the [PowerShell tool](</docs/en/tools-reference#powershell-tool>) is enabled: it’s on by default on Windows without Git Bash, and `CLAUDE_CODE_USE_POWERSHELL_TOOL=1` enables it elsewhere. -`metadata`| No| Free-form YAML map for your own key-value data, such as entitlement or catalog fields, read by your own tooling from `SKILL.md`. Claude Code doesn’t act on its contents, and drops a value that isn’t a map. Don’t reuse frontmatter field names such as `paths` as keys. -`license`| No| License covering the skill. Part of the [Agent Skills](<https://agentskills.io>) spec; see Using skill frontmatter outside Claude Code. Claude Code accepts the field but doesn’t act on it. -`compatibility`| No| Environment requirements for the skill, such as intended products or system prerequisites, as defined by the [Agent Skills](<https://agentskills.io>) spec; see Using skill frontmatter outside Claude Code. Accepts a string of up to 500 characters. Claude Code accepts the field but doesn’t act on it. - -#### - -​ - -Using skill frontmatter outside Claude Code - -Claude Code accepts every field in the table above. Outside Claude Code, you can use only the fields in the [Agent Skills](<https://agentskills.io>) spec: - -Distribution path| Frontmatter fields you can use ----|--- -Claude Code skills at any level, including [plugin](</docs/en/plugins>) skills| Every field in the table above -claude.ai skill uploads, the Skills API, and packaging with `package_skill.py` from [anthropics/skills](<https://github.com/anthropics/skills>)| `name`, `description`, `license`, `compatibility`, `metadata`, `allowed-tools` - -When you enable a personal skill for Cowork and cloud sessions, including routines, you upload it to claude.ai, so the same rules apply. If you include any field the spec doesn’t allow, packaging or upload fails with a hard error instead of ignoring the field: - - Unexpected key(s) in SKILL.md frontmatter: argument-hint. Allowed properties are: allowed-tools, compatibility, description, license, metadata, name - -Restricting frontmatter to the spec’s six fields avoids the unexpected-key error above. The [Agent Skills spec](<https://agentskills.io>) and the [Skills API requirements](<https://docs.claude.com/en/api/skills-guide>) define everything else those paths validate. Claude Code-only body features, such as dynamic context injection, don’t function in claude.ai chat or through the API. Claude Code accepts all six fields, so frontmatter that follows the spec loads in Claude Code without changes. - -#### - -​ - -How a skill gets its command name - -The command you type to invoke a skill comes from where the skill file lives and, for plugin skills, also from the frontmatter `name` field. In a personal or project skill, `name` sets only the display label shown in skill listings, and the command still comes from the directory or file name. In a plugin skill, `name` sets the last segment of the command and the plugin prefix stays in place. The table below shows where the command name comes from for each layout: - -Skill location| Command name source| Example ----|---|--- -Skill directory under `~/.claude/skills/` or `.claude/skills/`| Directory name| `.claude/skills/deploy-staging/SKILL.md` → `/deploy-staging` -Nested `.claude/skills/` directory, when the name clashes with another skill| Subdirectory path relative to the working directory, then the skill directory name| `apps/web/.claude/skills/deploy/SKILL.md` → `/apps/web:deploy` -File under `.claude/commands/`| File name without extension| `.claude/commands/deploy.md` → `/deploy` -Plugin `skills/` subdirectory| Frontmatter `name` or the directory name, namespaced by plugin| `my-plugin/skills/review/SKILL.md` → `/my-plugin:review`, or `/my-plugin:fancy` with `name: fancy` -Plugin root `SKILL.md`| Frontmatter `name`, with the plugin directory name as a fallback| `my-plugin/SKILL.md` with `name: review` → `/my-plugin:review`. See [Path behavior rules](</docs/en/plugins-reference#path-behavior-rules>) - -In a plugin skill, the frontmatter `name` replaces the directory name in the last segment of the command, so `my-plugin/skills/review/SKILL.md` with `name: fancy` becomes `/my-plugin:fancy`. The bare `/fancy` also invokes the skill unless another command already uses that name. Before v2.1.216, the frontmatter name replaced the whole command name, so the menu showed `/fancy` without the plugin prefix and `/my-plugin:fancy` didn’t autocomplete. In [non-interactive sessions](</docs/en/headless>), Claude Code doesn’t reserve the names `help` and `feedback` for their terminal-only built-in commands, so a plugin skill with one of those names keeps its bare command there. Claude Code still reserves the name of every other terminal-only built-in, such as `/login`, even though the command can’t run in those sessions. From v2.1.216 through v2.1.220, `help` and `feedback` were reserved too, so a plugin skill with one of those names was invocable only by its namespaced command in non-interactive sessions. For a plugin-root `SKILL.md`, there is no skill directory to take the name from, so `name` supplies the whole final segment. Without a `name` field, Claude Code falls back to the plugin’s directory name. - -#### - -​ - -Available string substitutions - -Skills support string substitution for dynamic values in the skill content: - -Variable| Description ----|--- -`$ARGUMENTS`| All arguments passed when invoking the skill. If `$ARGUMENTS` is not present in the content, arguments are appended as `ARGUMENTS: <value>`. -`$ARGUMENTS[N]`| Access a specific argument by 0-based index, such as `$ARGUMENTS[0]` for the first argument. -`$N`| Shorthand for `$ARGUMENTS[N]`, such as `$0` for the first argument or `$1` for the second. -`$name`| Named argument declared in the `arguments` frontmatter list. Names map to positions in order, so with `arguments: [issue, branch]` the placeholder `$issue` expands to the first argument and `$branch` to the second. -`${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. -`${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. - -Claude Code substitutes `${CLAUDE_SKILL_DIR}` and `${CLAUDE_PROJECT_DIR}` in two places: the skill’s markdown content, and Bash rules in the `allowed-tools` frontmatter. Using the same variable in both places lets a skill run a bundled script without a permission prompt. The following skill shows the pattern: - - --- - name: render-chart - description: Render a chart from a CSV file - allowed-tools: Bash(${CLAUDE_SKILL_DIR}/scripts/render.sh *) - --- - - Run `${CLAUDE_SKILL_DIR}/scripts/render.sh <csv-file>` to render the chart. - -If this skill is installed at `~/.claude/skills/render-chart/`, both occurrences of `${CLAUDE_SKILL_DIR}` expand to that directory. The `allowed-tools` rule then matches the exact command the skill body tells Claude to run, so the script runs without prompting. The `${CLAUDE_PROJECT_DIR}` substitution requires Claude Code v2.1.196 or later. 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. An indexed placeholder with no corresponding argument, such as `$2` when only one argument was passed, stays in the content unchanged. A named placeholder from the `arguments` frontmatter with no matching argument expands to an empty string. 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 - description: Log activity for this session - --- - - Log the following to logs/${CLAUDE_SESSION_ID}.log: - - $ARGUMENTS - -### - -​ - -Add supporting files - -Skills can include multiple files in their directory. This keeps `SKILL.md` focused on the essentials while letting Claude access detailed reference material only when needed. Large reference docs, API specifications, or example collections don’t need to load into context every time the skill runs. - - my-skill/ - ├── SKILL.md (required - overview and navigation) - ├── reference.md (detailed API docs - loaded when needed) - ├── examples.md (usage examples - loaded when needed) - └── scripts/ - └── helper.py (utility script - executed, not loaded) - -Reference supporting files from `SKILL.md` so Claude knows what each file contains and when to load it: - - ## Additional resources - - - For complete API details, see [reference.md](reference.md) - - For usage examples, see [examples.md](examples.md) - -Keep `SKILL.md` under 500 lines. Move detailed reference material to separate files. - -### - -​ - -Control who invokes a skill - -By default, both you and Claude can invoke any skill. You can type `/skill-name` to invoke it directly, and Claude can load it automatically when relevant to your conversation. Two frontmatter fields let you restrict this: - - * **`disable-model-invocation: true`** : Only you can invoke the skill. Use this for workflows with side effects or that you want to control timing, like `/commit`, `/deploy`, or `/send-slack-message`. You don’t want Claude deciding to deploy because your code looks ready. - * **`user-invocable: false`** : Only Claude can invoke the skill. Use this for background knowledge that isn’t actionable as a command. A `legacy-system-context` skill explains how an old system works. Claude should know this when relevant, but `/legacy-system-context` isn’t a meaningful action for users to take. - -This example creates a deploy skill that only you can trigger. If you set `disable-model-invocation: true`, Claude can’t run the skill automatically: - - --- - name: deploy - description: Deploy the application to production - disable-model-invocation: true - --- - - Deploy $ARGUMENTS to production: - - 1. Run the test suite - 2. Build the application - 3. Push to the deployment target - 4. Verify the deployment succeeded - -If Claude tries anyway, Claude Code blocks the call and instructs it not to reproduce the deploy steps another way, so expect Claude to suggest running `/deploy` yourself. Here’s how the two fields affect invocation and context loading: - -Frontmatter| You can invoke| Claude can invoke| When loaded into context ----|---|---|--- -(default)| Yes| Yes| Description always in context, full skill loads when invoked -`disable-model-invocation: true`| Yes| No| Description not in context, full skill loads when you invoke -`user-invocable: false`| No| Yes| Description always in context, full skill loads when invoked - -In a regular session, skill descriptions are loaded into context so Claude knows what’s available, but full skill content only loads when invoked. [Subagents with preloaded skills](</docs/en/sub-agents#preload-skills-into-subagents>) work differently: the full skill content is injected at startup. - -### - -​ - -Skill content lifecycle - -When you or Claude invoke a skill, the rendered `SKILL.md` content enters the conversation as a single message and stays there for the rest of the session. This persistence applies to the skill’s instructions, not its permissions: an `allowed-tools` grant clears when you send your next message. Claude Code does not re-read the skill file on later turns, so write guidance that should apply throughout a task as standing instructions rather than one-time steps. When Claude re-invokes a skill whose rendered content is identical to the copy already in context, Claude Code adds a short note that the skill is already loaded rather than a second copy of the content. When the rendered content differs, because the arguments changed or a dynamic context command produced new output, Claude Code appends the full content again. Before v2.1.202, every re-invocation appended another full copy of the skill’s instructions. [Auto-compaction](</docs/en/how-claude-code-works#when-context-fills-up>) carries invoked skills forward within a token budget. When the conversation is summarized to free context, Claude Code re-attaches the most recent invocation of each skill after the summary, keeping the first 5,000 tokens of each. Re-attached skills share a combined budget of 25,000 tokens. Claude Code fills this budget starting from the most recently invoked skill, so older skills can be dropped entirely after compaction if you have invoked many in one session. If a skill seems to stop influencing behavior after the first response, the content is usually still present and the model is choosing other tools or approaches. Strengthen the skill’s `description` and instructions so the model keeps preferring it, or use [hooks](</docs/en/hooks>) to enforce behavior deterministically. If the skill is large or you invoked several others after it, re-invoke it after compaction to restore the full content. - -### - -​ - -Pre-approve tools for a skill - -The `allowed-tools` field grants permission for the listed tools during the turn that invokes the skill, so Claude can use them without prompting you for approval. The grant clears when you send your next message, even though the skill content stays in context; invoking the skill again re-applies it for that turn. It does not restrict which tools are available: every tool remains callable, and your [permission settings](</docs/en/permissions>) still govern tools that are not listed. To pre-approve tools for the whole session rather than a single turn, add allow rules to those permission settings instead. For skills checked into a project’s `.claude/skills/` directory, `allowed-tools` takes effect after you accept the workspace trust dialog for that folder, the same as permission rules in `.claude/settings.json`. Review project skills before trusting a repository, since a skill can grant itself broad tool access. This skill lets Claude run git commands without per-use approval whenever you invoke it: - - --- - name: commit - description: Stage and commit the current changes - disable-model-invocation: true - allowed-tools: Bash(git add *) Bash(git commit *) Bash(git status *) - --- - -To remove tools from Claude’s available pool while a skill is active, list them in `disallowed-tools` in the skill’s frontmatter. The restriction clears when you send your next message. Like deny rules, the field can’t remove [`EndConversation`](</docs/en/tools-reference#endconversation-tool-behavior>) while any other tool remains. To block tools across all skills and prompts, add deny rules in your [permission settings](</docs/en/permissions>). - -### - -​ - -Pass arguments to skills - -Both you and Claude can pass arguments when invoking a skill. Arguments are available via the `$ARGUMENTS` placeholder. This skill fixes a GitHub issue by number. The `$ARGUMENTS` placeholder gets replaced with whatever follows the skill name: - - --- - name: fix-issue - description: Fix a GitHub issue - disable-model-invocation: true - --- - - Fix GitHub issue $ARGUMENTS following our coding standards. - - 1. Read the issue description - 2. Understand the requirements - 3. Implement the fix - 4. Write tests - 5. Create a commit - -When you run `/fix-issue 123`, Claude receives “Fix GitHub issue 123 following our coding standards…” If you invoke a skill with arguments but the skill doesn’t include `$ARGUMENTS`, Claude Code appends `ARGUMENTS: <your input>` to the end of the skill content so Claude still sees what you typed. You can also stack several skills at the start of one message. Typing `/write-tests /fix-issue 123` loads both skills and passes the trailing text `123` as `$ARGUMENTS` to each of them. Before v2.1.199, only the first skill loaded and received `/fix-issue 123` as literal argument text. Claude Code expands the first skill plus up to five more stacked after it. Expansion stops at the first token that isn’t an inline user-invocable skill, so a skill that runs as a forked subagent, such as [`/code-review`](</docs/en/code-review#review-a-diff-locally>), or one whose arguments may themselves start with a slash command, such as `/loop`, also ends the run there. That token and everything after it become the argument text for every expanded skill. `/code-review` runs as a forked subagent from v2.1.218; on earlier versions it ran inline and stacked. To access individual arguments by position, use `$ARGUMENTS[N]` or the shorter `$N`: - - --- - name: migrate-component - description: Migrate a component from one framework to another - --- - - Migrate the $ARGUMENTS[0] component from $ARGUMENTS[1] to $ARGUMENTS[2]. - Preserve all existing behavior and tests. - -Running `/migrate-component SearchBar React Vue` replaces `$ARGUMENTS[0]` with `SearchBar`, `$ARGUMENTS[1]` with `React`, and `$ARGUMENTS[2]` with `Vue`. The same skill using the `$N` shorthand: - - --- - name: migrate-component - description: Migrate a component from one framework to another - --- - - Migrate the $0 component from $1 to $2. - Preserve all existing behavior and tests. - -## - -​ - -Advanced patterns - -### - -​ - -Inject dynamic context - -The `!`<command>`` syntax runs shell commands before the skill content is sent to Claude. The command output replaces the placeholder, so Claude receives actual data, not the command itself. This skill summarizes a pull request by fetching live PR data with the GitHub CLI. The `!`gh pr diff`` and other commands run first, and their output gets inserted into the prompt: - - --- - name: pr-summary - description: Summarize changes in a pull request - context: fork - agent: Explore - allowed-tools: Bash(gh *) - --- - - ## Pull request context - - PR diff: !`gh pr diff` - - PR comments: !`gh pr view --comments` - - Changed files: !`gh pr diff --name-only` - - ## Your task - Summarize this pull request... - -When this skill runs: - - 1. Each `!`<command>`` executes immediately (before Claude sees anything) - 2. The output replaces the placeholder in the skill content - 3. Claude receives the fully-rendered prompt with actual PR data - -This is preprocessing, not something Claude executes. Claude only sees the final result. Substitution runs once over the original file. Command output is inserted as plain text and is not re-scanned for further `!`<command>`` placeholders, so a command cannot emit a placeholder for a later pass to expand. The inline form is only recognized when `!` appears at the start of a line or immediately after whitespace. If `!` follows another character, as in `KEY=!`cmd``, the placeholder is left as literal text and the command does not run. For multi-line commands, use a fenced code block opened with ````!` instead of the inline form: - - ## Environment - ```! - node --version - npm --version - git status --short - ``` - -To disable this behavior for skills and custom commands from user, project, plugin, or additional-directory sources, set `"disableSkillShellExecution": true` in [settings](</docs/en/settings>). Each command is replaced with `[shell command execution disabled by policy]` instead of being run. Bundled and managed skills are not affected. This setting is most useful in [managed settings](</docs/en/permissions#managed-settings>), where users cannot override it. - -To request deeper reasoning when a skill runs, include `ultrathink` anywhere in the skill content. See [Use ultrathink for one-off deep reasoning](</docs/en/model-config#use-ultrathink-for-one-off-deep-reasoning>). - -### - -​ - -Run skills in a subagent - -Add `context: fork` to your frontmatter when you want a skill to run in isolation. The skill content becomes the prompt that drives the subagent. It won’t have access to your conversation history. The forked subagent runs in the [background](</docs/en/sub-agents#run-subagents-in-foreground-or-background>): you keep working while it runs, and its result arrives in your conversation when it completes. Set `background: false` in the frontmatter to instead wait for the result in the turn that invoked the skill. Before v2.1.218, forked skills always blocked the turn until they finished. Claude Code also waits for the result, even when the skill doesn’t set `background: false`, in cases like these: - - * In non-interactive mode, with the `-p` flag or the Agent SDK - * When you set [`CLAUDE_CODE_DISABLE_BACKGROUND_TASKS`](</docs/en/env-vars>) to `1`, which also turns off all other background task features - * When you invoke a forked skill while an earlier invocation of the same skill is still running - * When a [scheduled task](</docs/en/scheduled-tasks>) fires with the skill as its prompt - -A backgrounded fork also runs with the [narrower tool set that applies to background subagents](</docs/en/sub-agents#run-subagents-in-foreground-or-background>): the skill’s subagent is a regular agent type, so the exemption for subagents that fork the conversation doesn’t cover it. If your skill’s steps depend on a tool outside that set, set `background: false` to keep the full tool set. A forked skill that runs in the background applies its edits outside your session’s [checkpoints](</docs/en/checkpointing>), so `/rewind` doesn’t undo them; use git to revert them. - -`context: fork` only makes sense for skills with explicit instructions. If your skill contains guidelines like “use these API conventions” without a task, the subagent receives the guidelines but no actionable prompt, and returns without meaningful output. - -Skills and [subagents](</docs/en/sub-agents>) work together in two directions: - -Approach| System prompt| Task| Also loads ----|---|---|--- -Skill with `context: fork`| From agent type| SKILL.md content| CLAUDE.md, except when the agent is Explore or Plan -Subagent with `skills` field| Subagent’s markdown body| Claude’s delegation message| Preloaded skills + CLAUDE.md - -With `context: fork`, you write the task in your skill and pick an agent type to execute it. The built-in Explore and Plan agents [skip CLAUDE.md and git status](</docs/en/sub-agents#what-loads-at-startup>) to keep their context small, so a forked skill using `agent: Explore` sees only the SKILL.md content and the agent’s own system prompt. For the inverse, where you define a custom subagent that uses skills as reference material, see [Subagents](</docs/en/sub-agents#preload-skills-into-subagents>). - -#### - -​ - -Example: Research skill using Explore agent - -This skill runs research in a forked Explore agent. The skill content becomes the task, and the agent provides read-only tools optimized for codebase exploration: - - --- - name: deep-research - description: Research a topic thoroughly - context: fork - agent: Explore - --- - - Research $ARGUMENTS thoroughly: - - 1. Find relevant files using Glob and Grep - 2. Read and analyze the code - 3. Summarize findings with specific file references - -When this skill runs: - - 1. A new isolated context is created - 2. The subagent receives the skill content as its prompt (“Research $ARGUMENTS thoroughly…”) - 3. The `agent` field determines the execution environment (model, tools, and permissions) - 4. The subagent summarizes its results and returns them to your main conversation when it finishes - -The `agent` field specifies which subagent configuration to use. Options include built-in agents (`Explore`, `Plan`, `general-purpose`) or any custom subagent from `.claude/agents/`. If omitted, uses `general-purpose`. - -### - -​ - -Restrict Claude’s skill access - -By default, Claude can invoke any skill that doesn’t have `disable-model-invocation: true` set. Skills that define `allowed-tools` grant Claude access to those tools without per-use approval during the turn that invokes the skill; the grant clears when you send your next message. Your [permission settings](</docs/en/permissions>) still govern baseline approval behavior for all other tools. A few built-in commands are also available through the Skill tool, including `/init` and `/security-review`. Other built-in commands such as `/compact` are not. Three ways to control which skills Claude can invoke: **Disable all skills** by denying the Skill tool in `/permissions`: - - # Add to deny rules: - Skill - -**Allow or deny specific skills** using [permission rules](</docs/en/permissions>): - - # Allow only specific skills - Skill(commit) - Skill(review-pr *) - - # Deny specific skills - Skill(deploy *) - -Permission syntax: `Skill(name)` for exact match, `Skill(name *)` for prefix match with any arguments. **Hide individual skills** by adding `disable-model-invocation: true` to their frontmatter. This removes the skill from Claude’s context entirely. - -The `user-invocable` field only controls menu visibility, not Skill tool access. Use `disable-model-invocation: true` to block programmatic invocation. - -### - -​ - -Override skill visibility from settings - -The `skillOverrides` setting controls skill visibility from your [settings](</docs/en/settings>) instead of the skill’s own frontmatter. Use it for skills whose SKILL.md you don’t want to edit, such as ones checked into a shared project repo. The `/skills` menu writes it for you: highlight a skill and press `Space` to cycle states, then `Enter` to save to `.claude/settings.local.json`. Each key is a skill name and each value is one of four states: - -Value| Listed to Claude| In `/` menu ----|---|--- -`"on"`| Name and description| Yes -`"name-only"`| Name only| Yes -`"user-invocable-only"`| Hidden| Yes -`"off"`| Hidden| Hidden - -The `/skills` menu labels the `"user-invocable-only"` state `user-only`. As of v2.1.199, `"off"` also hides the skill from the command lists advertised to [Remote Control](</docs/en/remote-control>) clients and to [Agent SDK](</docs/en/agent-sdk/slash-commands>) callers, not only the terminal `/` menu. Invoking a hidden skill by its full name still returns the `skillOverrides` error instead of running it. A skill that is absent from `skillOverrides` is treated as `"on"`. The example below collapses one skill to its name and turns another off entirely: - - { - "skillOverrides": { - "legacy-context": "name-only", - "deploy": "off" +## + +​ + +Overview + +Agent Skills extend Claude with specialized capabilities that Claude autonomously invokes when relevant. Skills are packaged as `SKILL.md` files containing instructions, descriptions, and optional supporting resources. For comprehensive information about Skills, including benefits, architecture, and authoring guidelines, see the [Agent Skills overview](<https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview>). + +## + +​ + +How Skills Work with the SDK + +When using the Claude Agent SDK, Skills are: + + 1. **Defined as filesystem artifacts** : you create each Skill as a `SKILL.md` file in its own directory, such as `.claude/skills/<name>/SKILL.md` + 2. **Loaded from filesystem** : the SDK loads Skills from the filesystem locations governed by `settingSources` (TypeScript) or `setting_sources` (Python) + 3. **Automatically discovered** : once filesystem settings load, the SDK discovers Skill metadata at startup from user and project directories, and loads the full content when Claude invokes the Skill + 4. **Model-invoked** : Claude autonomously chooses when to use them based on context + 5. **Filtered via the`skills` option**: discovered skills are enabled by default. Pass a list of skill names, `"all"`, or `[]` to control which are available in the session + +Unlike subagents (which can be defined programmatically), Skills must be created as filesystem artifacts. The SDK does not provide a programmatic API for registering Skills. + +Skills are discovered through the filesystem setting sources. With default `query()` options, the SDK loads user and project sources, so skills in `~/.claude/skills/`, `<cwd>/.claude/skills/`, and `.claude/skills/` in any parent directory of `<cwd>` up to the repository root are available. If you set `settingSources` explicitly, include `'user'` or `'project'` to keep skill discovery, or use the [`plugins` option](</docs/en/agent-sdk/plugins>) to load skills from a specific path. + +## + +​ + +Using Skills with the SDK + +Set the `skills` option on `query()` to control which Skills are available to the session. When omitted, discovered Skills are enabled and the Skill tool is available, matching CLI behavior. Pass `"all"` to enable every discovered Skill, a list of Skill names to enable only those, or `[]` to disable all. When you set `skills`, the SDK adds the Skill tool to `allowedTools` automatically. If you also pass an explicit `tools` list, include `"Skill"` in that list so Claude can invoke skills. Once configured, Claude automatically discovers Skills from the filesystem and invokes them when relevant to the user’s request. The following example sets `cwd` to the process’s current working directory, so run it from inside a project that has a `.claude/skills/` directory in the current directory or any parent up to the repository root: + +Python + +TypeScript + + import asyncio + import os + + from claude_agent_sdk import query, ClaudeAgentOptions + + async def main(): + options = ClaudeAgentOptions( + cwd=os.getcwd(), # .claude/skills/ here or in a parent directory + setting_sources=["user", "project"], # Load Skills from filesystem + skills="all", # Enable every discovered Skill + allowed_tools=["Read", "Write", "Bash"], + ) + + async for message in query( + prompt="Help me process this PDF document", options=options + ): + print(message) + + asyncio.run(main()) + + import { query } from "@anthropic-ai/claude-agent-sdk"; + + for await (const message of query({ + prompt: "Help me process this PDF document", + options: { + cwd: process.cwd(), // .claude/skills/ here or in a parent directory + settingSources: ["user", "project"], // Load Skills from filesystem + skills: "all", // Enable every discovered Skill + allowedTools: ["Read", "Write", "Bash"] } + })) { + console.log(message); } -Plugin skills are not affected by `skillOverrides`. Manage those through `/plugin` instead. - -## - -​ - -Evaluate and iterate on a skill - -Seeing a skill trigger tells you Claude found it, not that it did what you intended. To know a skill is working, measure two things separately: whether Claude invokes it on the prompts it should, and whether the output matches what you expect when it does. The check for both is a baseline comparison. Collect a few realistic prompts, run each one in a fresh session with the skill available and again with it disabled, and compare the results. A fresh session matters because leftover context from authoring the skill will mask gaps in the written instructions. - -### - -​ - -Run evals with skill-creator - -The [`skill-creator` plugin](<https://github.com/anthropics/claude-plugins-official/tree/main/plugins/skill-creator>) automates the comparison loop inside Claude Code. Install it from the official marketplace: - - /plugin install skill-creator@claude-plugins-official - -If the install fails, match the message Claude Code reports: - - * `Marketplace "claude-plugins-official" not found`: add the marketplace with `/plugin marketplace add anthropics/claude-plugins-official`, then retry the install. - * The plugin is not found in the marketplace: check the plugin name. Claude Code [refreshes a stale marketplace catalog and retries](</docs/en/discover-plugins#install-plugins>) before reporting this, so if you turned off [marketplace auto-update](</docs/en/discover-plugins#configure-auto-updates>), refresh manually with `/plugin marketplace update claude-plugins-official` and retry the install. - -If the install summary reports `Run /reload-plugins to activate.`, run that command to make the plugin’s skills available in the current session. Then ask Claude to evaluate an existing skill, for example `evaluate my summarize-changes skill with skill-creator`. The plugin walks you through writing test cases and runs the loop: - - * **Test cases** : stores prompts, input files, and expected behavior in `evals/evals.json` inside the skill directory - * **Isolated runs** : spawns a [subagent](</docs/en/sub-agents>) per test case so each run starts with a clean context, and records token count and duration - * **Grading** : checks each assertion against the output and writes pass or fail with evidence to `grading.json` - * **Benchmark** : aggregates pass rate, time, and tokens for with-skill versus without-skill into `benchmark.json` so you can compare the pass-rate improvement against the token and time overhead - * **Version comparison** : runs a blind A/B between two versions of the skill so you can confirm an edit is an improvement before committing it - * **Description tuning** : generates should-trigger and should-not-trigger prompts, measures the hit rate, and proposes description edits when the skill activates on the wrong requests - * **Review viewer** : opens an HTML report where you inspect each output and record qualitative feedback that the next iteration reads - -For the eval file format and the full iteration workflow, see [Evaluating skill output quality](<https://agentskills.io/skill-creation/evaluating-skills>) on agentskills.io. For background on the benchmark and comparison modes, see the [skill-creator announcement](<https://claude.com/blog/improving-skill-creator-test-measure-and-refine-agent-skills>). - -## - -​ - -Share skills - -Skills can be distributed at different scopes depending on your audience: - - * **Project skills** : Commit `.claude/skills/` to version control - * **Plugins** : Create a `skills/` directory in your [plugin](</docs/en/plugins>) - * **Managed** : Deploy organization-wide through [managed settings](</docs/en/settings#settings-files>) - -### - -​ - -Generate visual output - -Skills can bundle and run scripts in any language, giving Claude capabilities beyond what’s possible in a single prompt. One powerful pattern is generating visual output: interactive HTML files that open in your browser for exploring data, debugging, or creating reports. This example creates a codebase explorer: an interactive tree view where you can expand and collapse directories, see file sizes at a glance, and identify file types by color. Create the Skill directory: - - mkdir -p ~/.claude/skills/codebase-visualizer/scripts - -Save this to `~/.claude/skills/codebase-visualizer/SKILL.md`. The description tells Claude when to activate this Skill, and the instructions tell Claude to run the bundled script. The script path uses `${CLAUDE_SKILL_DIR}` so it resolves correctly whether the skill is installed at the personal, project, or plugin level: - - --- - name: codebase-visualizer - description: Generate an interactive collapsible tree visualization of your codebase. Use when exploring a new repo, understanding project structure, or identifying large files. - allowed-tools: Bash(python3 *) - --- - - # Codebase Visualizer - - Generate an interactive HTML tree view that shows your project's file structure with collapsible directories. - - ## Usage - - Run the visualization script from your project root: - - ```bash - python3 ${CLAUDE_SKILL_DIR}/scripts/visualize.py . - ``` - - This creates `codebase-map.html` in the current directory and opens it in your default browser. - - ## What the visualization shows - - - **Collapsible directories**: Click folders to expand/collapse - - **File sizes**: Displayed next to each file - - **Colors**: Different colors for different file types - - **Directory totals**: Shows aggregate size of each folder - -Save this to `~/.claude/skills/codebase-visualizer/scripts/visualize.py`. This script scans a directory tree and generates a self-contained HTML file with: - - * A **summary sidebar** showing file count, directory count, total size, and number of file types - * A **bar chart** breaking down the codebase by file type (top 8 by size) - * A **collapsible tree** where you can expand and collapse directories, with color-coded file type indicators - -The script requires Python 3 but uses only built-in libraries, so there are no packages to install: - - #!/usr/bin/env python3 - """Generate an interactive collapsible tree visualization of a codebase.""" - - import json - import sys - import webbrowser - from html import escape - from pathlib import Path - from collections import Counter - - IGNORE = {'.git', 'node_modules', '__pycache__', '.venv', 'venv', 'dist', 'build'} - - def scan(path: Path, stats: dict) -> dict: - result = {"name": path.name, "children": [], "size": 0} - try: - for item in sorted(path.iterdir()): - if item.name in IGNORE or item.name.startswith('.'): - continue - if item.is_file(): - size = item.stat().st_size - ext = item.suffix.lower() or '(no ext)' - result["children"].append({"name": item.name, "size": size, "ext": ext}) - result["size"] += size - stats["files"] += 1 - stats["extensions"][ext] += 1 - stats["ext_sizes"][ext] += size - elif item.is_dir(): - stats["dirs"] += 1 - child = scan(item, stats) - if child["children"]: - result["children"].append(child) - result["size"] += child["size"] - except PermissionError: - pass - return result - - def generate_html(data: dict, stats: dict, output: Path) -> None: - ext_sizes = stats["ext_sizes"] - total_size = sum(ext_sizes.values()) or 1 - sorted_exts = sorted(ext_sizes.items(), key=lambda x: -x[1])[:8] - colors = { - '.js': '#f7df1e', '.ts': '#3178c6', '.py': '#3776ab', '.go': '#00add8', - '.rs': '#dea584', '.rb': '#cc342d', '.css': '#264de4', '.html': '#e34c26', - '.json': '#6b7280', '.md': '#083fa1', '.yaml': '#cb171e', '.yml': '#cb171e', - '.mdx': '#083fa1', '.tsx': '#3178c6', '.jsx': '#61dafb', '.sh': '#4eaa25', - } - lang_bars = "".join( - f'<div class="bar-row"><span class="bar-label">{ext}</span>' - f'<div class="bar" style="width:{(size/total_size)*100}%;background:{colors.get(ext,"#6b7280")}"></div>' - f'<span class="bar-pct">{(size/total_size)*100:.1f}%</span></div>' - for ext, size in sorted_exts - ) - def fmt(b): - if b < 1024: return f"{b} B" - if b < 1048576: return f"{b/1024:.1f} KB" - return f"{b/1048576:.1f} MB" - - html = f'''<!DOCTYPE html> - <html><head> - <meta charset="utf-8"><title>Codebase Explorer</title> - <style> - body {{ font: 14px/1.5 system-ui, sans-serif; margin: 0; background: #1a1a2e; color: #eee; }} - .container {{ display: flex; height: 100vh; }} - .sidebar {{ width: 280px; background: #252542; padding: 20px; border-right: 1px solid #3d3d5c; overflow-y: auto; flex-shrink: 0; }} - .main {{ flex: 1; padding: 20px; overflow-y: auto; }} - h1 {{ margin: 0 0 10px 0; font-size: 18px; }} - h2 {{ margin: 20px 0 10px 0; font-size: 14px; color: #888; text-transform: uppercase; }} - .stat {{ display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #3d3d5c; }} - .stat-value {{ font-weight: bold; }} - .bar-row {{ display: flex; align-items: center; margin: 6px 0; }} - .bar-label {{ width: 55px; font-size: 12px; color: #aaa; }} - .bar {{ height: 18px; border-radius: 3px; }} - .bar-pct {{ margin-left: 8px; font-size: 12px; color: #666; }} - .tree {{ list-style: none; padding-left: 20px; }} - details {{ cursor: pointer; }} - summary {{ padding: 4px 8px; border-radius: 4px; }} - summary:hover {{ background: #2d2d44; }} - .folder {{ color: #ffd700; }} - .file {{ display: flex; align-items: center; padding: 4px 8px; border-radius: 4px; }} - .file:hover {{ background: #2d2d44; }} - .size {{ color: #888; margin-left: auto; font-size: 12px; }} - .dot {{ width: 8px; height: 8px; border-radius: 50%; margin-right: 8px; }} - </style> - </head><body> - <div class="container"> - <div class="sidebar"> - <h1>📊 Summary</h1> - <div class="stat"><span>Files</span><span class="stat-value">{stats["files"]:,}</span></div> - <div class="stat"><span>Directories</span><span class="stat-value">{stats["dirs"]:,}</span></div> - <div class="stat"><span>Total size</span><span class="stat-value">{fmt(data["size"])}</span></div> - <div class="stat"><span>File types</span><span class="stat-value">{len(stats["extensions"])}</span></div> - <h2>By file type</h2> - {lang_bars} - </div> - <div class="main"> - <h1>📁 {escape(data["name"])}</h1> - <ul class="tree" id="root"></ul> - </div> - </div> - <script> - const data = {json.dumps(data)}; - const colors = {json.dumps(colors)}; - function fmt(b) {{ if (b < 1024) return b + ' B'; if (b < 1048576) return (b/1024).toFixed(1) + ' KB'; return (b/1048576).toFixed(1) + ' MB'; }} - function esc(s) {{ return s.replace(/[&<>"']/g, c => ({{"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}}[c])); }} - function render(node, parent) {{ - if (node.children) {{ - const det = document.createElement('details'); - det.open = parent === document.getElementById('root'); - det.innerHTML = `<summary><span class="folder">📁 ${{esc(node.name)}}</span><span class="size">${{fmt(node.size)}}</span></summary>`; - const ul = document.createElement('ul'); ul.className = 'tree'; - node.children.sort((a,b) => (b.children?1:0)-(a.children?1:0) || a.name.localeCompare(b.name)); - node.children.forEach(c => render(c, ul)); - det.appendChild(ul); - const li = document.createElement('li'); li.appendChild(det); parent.appendChild(li); - }} else {{ - const li = document.createElement('li'); li.className = 'file'; - li.innerHTML = `<span class="dot" style="background:${{colors[node.ext]||'#6b7280'}}"></span>${{esc(node.name)}}<span class="size">${{fmt(node.size)}}</span>`; - parent.appendChild(li); - }} - }} - data.children.forEach(c => render(c, document.getElementById('root'))); - </script> - </body></html>''' - output.write_text(html) - - if __name__ == '__main__': - target = Path(sys.argv[1] if len(sys.argv) > 1 else '.').resolve() - stats = {"files": 0, "dirs": 0, "extensions": Counter(), "ext_sizes": Counter()} - data = scan(target, stats) - out = Path('codebase-map.html') - generate_html(data, stats, out) - print(f'Generated {out.absolute()}') - webbrowser.open(f'file://{out.absolute()}') - -See all 133 lines - -To test, open Claude Code in any project and ask “Visualize this codebase.” Claude runs the script, which prints the generated file’s path, such as `Generated /path/to/codebase-map.html`, and opens it in your browser. If you work in a headless environment where no browser opens, the printed path confirms the script succeeded. This pattern works for any visual output: dependency graphs, test coverage reports, API documentation, or database schema visualizations. The bundled script does the work while Claude handles orchestration. +Near the start of the stream, the SDK yields a system message with subtype `init`. Check its `skills` array to confirm your Skills loaded before Claude starts working. The array lists user-invocable Skills only. A Skill with [`user-invocable: false`](</docs/en/skills#control-who-invokes-a-skill>) in its frontmatter loads and remains available to Claude but doesn’t appear in the array. To enable only specific Skills, pass their names. Names match the `name` field in `SKILL.md` or the Skill’s directory name. Use `plugin:skill` for plugin-provided Skills. + +Import statements from the first example are assumed in the following code snippets. + +Python + +TypeScript + + options = ClaudeAgentOptions(skills=["pdf", "docx"]) + + const options = { skills: ["pdf", "docx"] }; + +The list takes exact Skill names only. In the TypeScript SDK, `query()` throws before starting the Claude Code process when a name can’t work as an exact Skill name. In the Python SDK, `query()` raises `ValueError` in the same cases, for example: + + * An empty name + * A name containing parentheses, commas, or control characters + * A name padded with whitespace + * A wildcard form such as a bare `*` or a `:*` suffix + +To enable every discovered Skill, pass `skills: "all"` rather than a wildcard. The `skills` option is a context filter, not a sandbox. Unlisted Skills are hidden from the model and rejected by the Skill tool, but their files remain on disk and are reachable through Read and Bash. + +## + +​ + +Creating Skills + +Create each Skill as a directory containing a `SKILL.md` file with YAML frontmatter and Markdown content. The `description` field determines when Claude invokes your Skill. **Example directory structure** : + + .claude/skills/processing-pdfs/ + └── SKILL.md + +For complete guidance on creating Skills, including SKILL.md structure, multi-file Skills, and examples, see: + + * [Agent Skills in Claude Code](</docs/en/skills>): Complete guide with examples + * [Agent Skills Best Practices](<https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices>): Authoring guidelines and naming conventions + +## + +​ + +Tool Restrictions + +The `allowed-tools` frontmatter field in SKILL.md is only supported when using Claude Code CLI directly. **It does not apply when using Skills through the SDK**.When using the SDK, control tool access through the main `allowedTools` option in your query configuration. + +To control tool access for Skills in SDK applications, use `allowedTools` to pre-approve specific tools. Without a `canUseTool` callback, anything not in the list is denied: + +Python + +TypeScript + + options = ClaudeAgentOptions( + setting_sources=["user", "project"], # Load Skills from filesystem + skills="all", + allowed_tools=["Read", "Grep", "Glob"], + permission_mode="dontAsk", # Deny anything not pre-approved instead of prompting + ) + + async def main(): + async for message in query(prompt="Analyze the codebase structure", options=options): + print(message) + + asyncio.run(main()) + + for await (const message of query({ + prompt: "Analyze the codebase structure", + options: { + settingSources: ["user", "project"], // Load Skills from filesystem + skills: "all", + allowedTools: ["Read", "Grep", "Glob"], + permissionMode: "dontAsk" // Deny anything not pre-approved instead of prompting + } + })) { + console.log(message); + } + +## + +​ + +Discovering Available Skills + +To see which Skills are available in your SDK application, ask Claude. The example below sets only the `skills` option and omits `settingSources`/`setting_sources`. When you leave `settingSources`/`setting_sources` unset, the SDK still loads Skills from the user and project sources, so the `skills` option set to `"all"` on its own makes them available to list. + +Python + +TypeScript + + options = ClaudeAgentOptions(skills="all") + + async def main(): + async for message in query(prompt="What Skills are available?", options=options): + print(message) + + asyncio.run(main()) + + for await (const message of query({ + prompt: "What Skills are available?", + options: { + skills: "all" + } + })) { + console.log(message); + } + +Claude will list the available Skills based on your current working directory and installed plugins. + +## + +​ + +Testing Skills + +Test Skills by asking questions that match their descriptions: + +Python + +TypeScript + + options = ClaudeAgentOptions( + cwd=os.getcwd(), + setting_sources=["user", "project"], # Load Skills from filesystem + skills="all", + allowed_tools=["Read", "Bash"], + ) + + async def main(): + async for message in query(prompt="Extract text from invoice.pdf", options=options): + print(message) + + asyncio.run(main()) + + for await (const message of query({ + prompt: "Extract text from invoice.pdf", + options: { + cwd: process.cwd(), + settingSources: ["user", "project"], // Load Skills from filesystem + skills: "all", + allowedTools: ["Read", "Bash"] + } + })) { + console.log(message); + } + +Claude automatically invokes the relevant Skill if the description matches your request. ## @@ -851,49 +226,104 @@ ​ -Skill not triggering - -If Claude doesn’t use your skill when expected: - - 1. Check the description includes keywords users would naturally say - 2. Verify the skill appears in `What skills are available?` - 3. Try rephrasing your request to match the description more closely - 4. Invoke it directly with `/skill-name` if the skill is user-invocable - -If the frontmatter YAML is malformed, Claude Code loads the skill body with empty metadata, so `/skill-name` still works but Claude has no `description` to match against. Run with `--debug` to see the parse error. - -### - -​ - -Skill triggers too often - -If Claude uses your skill when you don’t want it: - - 1. Make the description more specific - 2. Add `disable-model-invocation: true` if you only want manual invocation - -### - -​ - -Skill descriptions are cut short - -Claude Code loads a listing of skill names and descriptions into context so Claude knows what’s available. The listing always contains every skill name, but if you have many skills, Claude Code shortens descriptions to fit the listing’s 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 the listing overflows, Claude Code drops descriptions starting with the skills you invoke least, so the skills you use most keep their full text. Run `/doctor` for an estimate of the listing’s context cost and its biggest contributors. When the listing exceeds its budget, Claude Code also writes a warning to the debug log, visible with [`--debug`](</docs/en/cli-reference#cli-flags>). The Skills row in `/context` reports the size of the listing after the budget is applied, so it matches what the model receives. Before v2.1.196, the row counted the full text of every description and could show a value several times larger than the configured budget. 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>). - -## - -​ - -Related resources - - * **[Debug your configuration](</docs/en/debug-your-config>)** : diagnose why a skill isn’t appearing or triggering - * **[Evaluating skill output quality](<https://agentskills.io/skill-creation/evaluating-skills>)** : the eval file format and iteration workflow on agentskills.io - * **[Skill authoring best practices](<https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices>)** : writing guidance that applies across Claude products - * **[Subagents](</docs/en/sub-agents>)** : delegate tasks to specialized agents - * **[Plugins](</docs/en/plugins>)** : package and distribute skills with other extensions - * **[Hooks](</docs/en/hooks>)** : automate workflows around tool events - * **[Memory](</docs/en/memory>)** : manage CLAUDE.md files for persistent context - * **[Commands](</docs/en/commands>)** : reference for built-in commands and bundled skills - * **[Permissions](</docs/en/permissions>)** : control tool and skill access - * **[Claude Tag skills](<https://claude.com/docs/claude-tag/admins/skills-repo>)** : project skills committed to a repo also load when that repo is used in a Claude Tag channel +Skills Not Found + +**Check settingSources configuration** : Skills are discovered through the `user` and `project` setting sources. If you set `settingSources`/`setting_sources` explicitly and omit those sources, skills are not loaded: + +Python + +TypeScript + + # Skills not loaded: setting_sources excludes user and project + options = ClaudeAgentOptions(setting_sources=[], skills="all") + + # Skills loaded: user and project sources included + options = ClaudeAgentOptions( + setting_sources=["user", "project"], + skills="all", + ) + + // Skills not loaded: settingSources excludes user and project + const optionsWithoutSkills = { + settingSources: [], + skills: "all" + }; + + // Skills loaded: user and project sources included + const optionsWithSkills = { + settingSources: ["user", "project"], + skills: "all" + }; + +For which skill directories each source loads, see the [filesystem sources table](</docs/en/agent-sdk/claude-code-features#control-filesystem-settings-with-settingsources>). For more details on `settingSources`/`setting_sources`, see the [TypeScript SDK reference](</docs/en/agent-sdk/typescript#settingsource>) or [Python SDK reference](</docs/en/agent-sdk/python#settingsource>). **Check working directory** : The SDK loads Skills from `.claude/skills/` in the `cwd` option and in every parent directory up to the repository root. Ensure `cwd` points at or below the directory containing `.claude/skills/`, within the same repository: + +Python + +TypeScript + + # Ensure your cwd points to the directory containing .claude/skills/ + options = ClaudeAgentOptions( + cwd="/path/to/project", # .claude/skills/ here or in a parent directory + setting_sources=["user", "project"], # Loads skills from these sources + skills="all", + ) + + // Ensure your cwd points to the directory containing .claude/skills/ + const options = { + cwd: "/path/to/project", // .claude/skills/ here or in a parent directory + settingSources: ["user", "project"], // Loads skills from these sources + skills: "all" + }; + +See the “Using Skills with the SDK” section above for the complete pattern. **Verify filesystem location** : + + # Check project Skills + ls .claude/skills/*/SKILL.md + + # Check personal Skills + ls ~/.claude/skills/*/SKILL.md + +### + +​ + +Skill Not Being Used + +**Check the`skills` option**: If you passed a `skills` list, confirm the skill’s name is included. Passing `[]` disables all skills. **Check the description** : Ensure it’s specific and includes relevant keywords. See [Agent Skills Best Practices](<https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices#writing-effective-descriptions>) for guidance on writing effective descriptions. + +### + +​ + +Additional Troubleshooting + +For general Skills troubleshooting (YAML syntax, debugging, etc.), see the [Claude Code Skills troubleshooting section](</docs/en/skills#troubleshooting>). + +## + +​ + +Related Documentation + +### + +​ + +Skills Guides + + * [Agent Skills in Claude Code](</docs/en/skills>): Complete Skills guide with creation, examples, and troubleshooting + * [Agent Skills Overview](<https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview>): Conceptual overview, benefits, and architecture + * [Agent Skills Best Practices](<https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices>): Authoring guidelines for effective Skills + * [Agent Skills Cookbook](<https://platform.claude.com/cookbook/skills-notebooks-01-skills-introduction>): Example Skills and templates + +### + +​ + +SDK Resources + + * [Subagents in the SDK](</docs/en/agent-sdk/subagents>): Similar filesystem-based agents with programmatic options + * [Slash Commands in the SDK](</docs/en/agent-sdk/slash-commands>): User-invoked commands + * [SDK Overview](</docs/en/agent-sdk/overview>): General SDK concepts + * [TypeScript SDK Reference](</docs/en/agent-sdk/typescript>): Complete API documentation + * [Python SDK Reference](</docs/en/agent-sdk/python>): Complete API documentation
modified Claude Code in Slack View current →
--- a/slack.md +++ b/slack.md @@ -1,6 +1,6 @@ This page documents the earlier Claude Code in Slack, which runs each session under an individual user’s account. - * **Team and Enterprise plans:** Anthropic is retiring this version in favor of [Claude Tag](<https://claude.com/docs/claude-tag/overview>), which runs @Claude as your organization’s shared identity with admin-configured access. Your existing Slack app and @Claude handle stay, and your Anthropic account team can tell you the cutover date. Set up Claude Tag for a new workspace; to move one that already uses this version, see [Migrate from the earlier Claude in Slack](<https://claude.com/docs/claude-tag/admins/migrate-from-earlier>). + * **Team and Enterprise plans:** Anthropic is retiring this version in favor of [Claude Tag](<https://claude.com/product/tag>), which runs @Claude as your organization’s shared identity with admin-configured access. Your existing Slack app and @Claude handle stay, and your Anthropic account team can tell you the cutover date. [Set up Claude Tag](<https://claude.com/docs/claude-tag/overview>) for a new workspace; to move one that already uses this version, see [Migrate from the earlier Claude in Slack](<https://claude.com/docs/claude-tag/admins/migrate-from-earlier>). * **Pro and Max plans:** Claude Tag isn’t available on individual plans, so this page remains the setup path. Claude Code in Slack brings the power of Claude Code directly into your Slack workspace. When you mention `@Claude` with a coding task, Claude automatically detects the intent and creates a Claude Code session on the web, allowing you to delegate development work without leaving your team conversations. This integration is built on the existing Claude for Slack app but adds intelligent routing to Claude Code on the web for coding-related requests. Each session runs under your own Claude account, using your connected repositories and your plan limits.
modified Slash Commands in the SDK View current →
--- a/slash-commands.md +++ b/slash-commands.md @@ -521,57 +521,6 @@ 3. If tests fail, analyze and fix them 4. Re-run to verify fixes -Use these commands through the SDK: - -TypeScript - -Python - - import { query } from "@anthropic-ai/claude-agent-sdk"; - - // Run code review - try { - for await (const message of query({ - prompt: "/review-pr", - options: { maxTurns: 3 } - })) { - // Process review feedback - } - } catch (error) { - // A single-shot query() throws after yielding an error result, - // so the second query below still runs. - console.error(`Session ended with an error: ${error}`); - } - - // Run specific tests - for await (const message of query({ - prompt: "/test auth", - options: { maxTurns: 5 } - })) { - // Handle test results - } - - import asyncio - from claude_agent_sdk import query, ClaudeAgentOptions - - async def main(): - # Run code review - try: - async for message in query(prompt="/review-pr", options=ClaudeAgentOptions(max_turns=3)): - # Process review feedback - pass - except Exception as error: - # A single-shot query() raises after yielding an error result, - # so the second query below still runs. - print(f"Session ended with an error: {error}") - - # Run specific tests - async for message in query(prompt="/test auth", options=ClaudeAgentOptions(max_turns=5)): - # Handle test results - pass - - asyncio.run(main()) - ## ​
modified Stream responses in real-time View current →
--- a/streaming-output.md +++ b/streaming-output.md @@ -1,4 +1,4 @@ -By default, the Agent SDK yields complete `AssistantMessage` objects after Claude finishes generating each response. To receive incremental updates as text and tool calls are generated, enable partial message streaming by setting `include_partial_messages` (Python) or `includePartialMessages` (TypeScript) to `true` in your options. +By default, the Agent SDK yields complete `AssistantMessage` objects after Claude finishes generating each response. To receive incremental updates as text and tool calls are generated, enable partial message streaming. This page covers output streaming (receiving tokens in real-time). For input modes (how you send messages), see [Send messages to agents](</docs/en/agent-sdk/streaming-vs-single-mode>). You can also [stream responses using the Agent SDK via the CLI](</docs/en/headless>). @@ -125,55 +125,7 @@ ... more streaming events for next turn ... ResultMessage - final result -Without partial messages enabled (`include_partial_messages` in Python, `includePartialMessages` in TypeScript), you receive all message types except `StreamEvent`. Common types include `SystemMessage` (session initialization), `AssistantMessage` (complete responses), `ResultMessage` (final result), and a compact boundary message indicating when conversation history was compacted (`SDKCompactBoundaryMessage` in TypeScript; `SystemMessage` with subtype `"compact_boundary"` in Python). - -## - -​ - -Stream text responses - -To display text as it’s generated, look for `content_block_delta` events where `delta.type` is `text_delta`. These contain the incremental text chunks. The example below prints each chunk as it arrives: - -Python - -TypeScript - - from claude_agent_sdk import query, ClaudeAgentOptions - from claude_agent_sdk.types import StreamEvent - import asyncio - - async def stream_text(): - options = ClaudeAgentOptions(include_partial_messages=True) - - async for message in query(prompt="Explain how databases work", options=options): - if isinstance(message, StreamEvent): - event = message.event - if event.get("type") == "content_block_delta": - delta = event.get("delta", {}) - if delta.get("type") == "text_delta": - # Print each text chunk as it arrives - print(delta.get("text", ""), end="", flush=True) - - print() # Final newline - - asyncio.run(stream_text()) - - import { query } from "@anthropic-ai/claude-agent-sdk"; - - for await (const message of query({ - prompt: "Explain how databases work", - options: { includePartialMessages: true } - })) { - if (message.type === "stream_event") { - const event = message.event; - if (event.type === "content_block_delta" && event.delta.type === "text_delta") { - process.stdout.write(event.delta.text); - } - } - } - - console.log(); // Final newline +Without partial messages enabled, you receive all message types except `StreamEvent`. Common types include `SystemMessage` (session initialization), `AssistantMessage` (complete responses), `ResultMessage` (final result), and a compact boundary message indicating when conversation history was compacted (`SDKCompactBoundaryMessage` in TypeScript; `SystemMessage` with subtype `"compact_boundary"` in Python). ##
modified Streaming Input View current →
--- a/streaming-vs-single-mode.md +++ b/streaming-vs-single-mode.md @@ -9,8 +9,6 @@ * **Streaming Input Mode** : a persistent, interactive session * **Single Message Input** : one-shot queries that use session state and resuming -This guide explains the differences, benefits, and use cases for each mode to help you choose the right approach for your application. - ## ​ @@ -31,25 +29,13 @@ Benefits -## Image Uploads - -Attach images directly to messages for visual analysis and understanding - -## Queued Messages - -Send multiple messages that process sequentially, with ability to interrupt - -## Tool Integration - -Full access to all tools and custom MCP servers during the session - -## Real-time Feedback - -See responses as they’re generated, not just final results - -## Context Persistence - -Maintain conversation context across multiple turns naturally +In streaming input mode, you work in a persistent session with these capabilities: + + * **Image uploads** : attach images directly to messages for visual analysis and understanding + * **Queued messages** : send multiple messages that process sequentially, with ability to interrupt + * **Tool integration** : full access to all tools and custom MCP servers during the session + * **Real-time feedback** : see responses as they’re generated, not just final results + * **Context persistence** : maintain conversation context across multiple turns naturally ###
modified Create custom subagents View current →
--- a/sub-agents.md +++ b/sub-agents.md @@ -849,7 +849,7 @@ Resume subagents -Each subagent invocation creates a new instance with fresh context. To continue an existing subagent’s work instead of starting over, ask Claude to resume it. Resumed subagents retain their full conversation history, including all previous tool calls, results, and reasoning. The subagent picks up exactly where it stopped rather than starting fresh. When a subagent completes, Claude receives its agent ID. The built-in Explore and Plan agents are one-shot and return no agent ID, so they can’t be resumed; use `general-purpose` or a custom subagent when you need to continue the work. Claude uses the `SendMessage` tool with the agent’s ID or name as the `to` field to resume it. `SendMessage` doesn’t require [agent teams](</docs/en/agent-teams>) to be enabled; only structured team-protocol messages such as `shutdown_request` and `plan_approval_response` do. Beyond subagents and teammates, in sessions where cross-session messaging is enabled, the same tool can message [your other Claude Code sessions](</docs/en/cross-session-messaging>) on this machine, or reply to your sessions [beyond it](</docs/en/cross-session-messaging#message-sessions-on-other-machines>). To resume a subagent, ask Claude to continue the previous work: +Each subagent invocation creates a new instance with fresh context. To continue an existing subagent’s work instead of starting over, ask Claude to resume it. Resumed subagents retain their full conversation history, including all previous tool calls, results, and reasoning. The subagent picks up exactly where it stopped rather than starting fresh. When a subagent completes, Claude receives its agent ID. The built-in Explore and Plan agents are one-shot and return no agent ID, so they can’t be resumed; use `general-purpose` or a custom subagent when you need to continue the work. Claude uses the `SendMessage` tool with the agent’s ID or name as the `to` field to resume it. `SendMessage` doesn’t require [agent teams](</docs/en/agent-teams>) to be enabled; only structured team-protocol messages such as `shutdown_request` and `plan_approval_response` do. Beyond subagents and teammates, in sessions where cross-session messaging is enabled, the same tool can message [your other Claude Code sessions](</docs/en/cross-session-messaging>), on this machine or [beyond it](</docs/en/cross-session-messaging#message-sessions-on-other-machines>). To resume a subagent, ask Claude to continue the previous work: Use the code-reviewer subagent to review the authentication module [Agent completes]
modified Subagents in the SDK View current →
--- a/subagents.md +++ b/subagents.md @@ -12,7 +12,7 @@ * **Filesystem-based** : define agents as markdown files in `.claude/agents/` directories. See [defining subagents as files](</docs/en/sub-agents>) * **Built-in general-purpose** : Claude can invoke the built-in `general-purpose` subagent at any time via the Agent tool without you defining anything -This guide focuses on the programmatic approach, which is recommended for SDK applications. When you define subagents, Claude determines whether to invoke them based on each subagent’s `description` field. Write clear descriptions that explain when to use the subagent, and Claude automatically delegates appropriate tasks. You can also explicitly request a subagent by name in your prompt, for example “Use the code-reviewer agent to…”. +This guide focuses on the programmatic approach, which is recommended for SDK applications. ## @@ -189,12 +189,9 @@ In the Python SDK, multi-word field names such as `disallowedTools` and `mcpServers` keep their camelCase spelling to match the wire format rather than following Python’s snake_case convention. See the [`AgentDefinition` reference](</docs/en/agent-sdk/python#agentdefinition>) for details. Two subagent behaviors changed in Claude Code v2.1.198: * Subagents run in the background by default. An Agent tool call that omits the [`run_in_background`](</docs/en/agent-sdk/typescript>) input launches a background subagent, and Claude sets `run_in_background: false` when it needs the result before continuing. Before v2.1.198, omitting `run_in_background` ran the subagent synchronously. Set the `background` field to `true` to force background execution for a specific agent regardless of what Claude requests. - * A subagent inherits the main session’s extended thinking configuration. On earlier versions, extended thinking is disabled inside subagents regardless of the main session’s setting. - -By default, subagents can spawn subagents of their own, up to three layers below the main conversation. To change the limit, set [`CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH`](</docs/en/env-vars>) to the number of subagent layers you want below your main conversation, or `1` to turn nesting off; see [nested subagents](</docs/en/sub-agents#let-subagents-spawn-their-own-subagents>).Earlier versions used different defaults: - - * **v2.1.172 through v2.1.216** : subagents could nest by default, up to five layers deep, and the limit couldn’t be changed. - * **v2.1.217 through v2.1.218** : the limit defaulted to one, so a subagent couldn’t spawn its own unless you raised it; v2.1.219 raised the default to three. + * A subagent inherits the main session’s extended thinking configuration. + +By default, subagents can spawn subagents of their own, up to three layers below the main conversation. To change the limit, set [`CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH`](</docs/en/env-vars>) to the number of subagent layers you want below your main conversation, or `1` to turn nesting off; see [nested subagents](</docs/en/sub-agents#let-subagents-spawn-their-own-subagents>). ### @@ -228,7 +225,7 @@ For a control-tag or permission-configuration match, Claude Code prepends a `[harness: ...]` marker line naming the matched patterns; a turn-marker match doesn’t add the marker line. Those are the only modifications the scan makes: it never removes or rewords the subagent’s text. -An API error that ends the subagent early, such as a rate limit, is never delivered as its result. If a rate limit, overload, or server error cuts off a foreground subagent that already produced text output, the Agent tool returns that partial output with a note that the subagent didn’t finish. A subagent that produced nothing, or whose only output was tool calls with no text, fails with an error message, `Agent terminated early due to an API error`, followed by the error detail. See [API errors in subagents](</docs/en/sub-agents#api-errors-in-subagents>) for the foreground and background behavior. This partial-output handling requires Claude Code v2.1.199 or later. In v2.1.199, a rate limit, overload, or server error left the tool-calls-only shape with an empty partial result containing only the cutoff note. +An API error that ends the subagent early, such as a rate limit, is never delivered as its result. See [API errors in subagents](</docs/en/sub-agents#api-errors-in-subagents>) for the foreground and background behavior. ## @@ -551,11 +548,7 @@ console.log("No agentId found in the first query, so there is no subagent to resume."); } -Subagent transcripts persist independently of the main conversation: - - * **Main conversation compaction** : when the main conversation compacts, subagent transcripts are unaffected. They’re stored in separate files. - * **Session persistence** : subagent transcripts persist within their session. You can resume a subagent after restarting Claude Code by resuming the same session. - * **Automatic cleanup** : Claude Code deletes subagent transcripts after the `cleanupPeriodDays` retention period, 30 days by default. +Subagent transcripts are stored in separate files and persist independently of the main conversation. See [resume subagents in Claude Code](</docs/en/sub-agents#resume-subagents>) for compaction behavior and the `cleanupPeriodDays` cleanup period. ##
modified Configure your terminal for Claude Code View current →
--- a/terminal-config.md +++ b/terminal-config.md @@ -53,7 +53,7 @@ Get a terminal bell or notification -When Claude finishes a task or pauses for a permission prompt, it fires a notification event. Surfacing this as a terminal bell or desktop notification lets you switch to other work while a long task runs. By default Claude Code sends a desktop notification only in Ghostty, Kitty, and iTerm2. In other terminals, set [`preferredNotifChannel`](</docs/en/settings#available-settings>) to `"terminal_bell"` to ring the terminal bell instead, or configure a Notification hook for a custom sound or command. The following settings entry turns on the terminal bell: +When Claude finishes a task or pauses for a permission prompt, and you appear to be away from the terminal, it fires a notification event. See [when each notification type fires](</docs/en/hooks#notification>) for the exact timing. Surfacing this as a terminal bell or desktop notification lets you switch to other work while a long task runs. By default Claude Code sends a desktop notification only in Ghostty, Kitty, and iTerm2. In other terminals, set [`preferredNotifChannel`](</docs/en/settings#available-settings>) to `"terminal_bell"` to ring the terminal bell instead, or configure a Notification hook for a custom sound or command. The following settings entry turns on the terminal bell: ~/.claude/settings.json
modified Todo Lists View current →
--- a/todo-tracking.md +++ b/todo-tracking.md @@ -1,4 +1,4 @@ -Todo tracking provides a structured way to manage tasks and display progress to users. The Claude Agent SDK includes built-in todo functionality that helps organize complex workflows and keep users informed about task progression. +The Claude Agent SDK includes built-in todo functionality that helps organize complex workflows and keep users informed about task progression. As of TypeScript Agent SDK 0.3.142 and Claude Code v2.1.142, sessions use the structured Task tools `TaskCreate`, `TaskUpdate`, `TaskGet`, and `TaskList` instead of `TodoWrite`. The Python SDK gets this change from the Claude Code CLI it launches, not from the Python package version: the switch applies once that CLI — the copy bundled inside the pip package, or one you point to with `cli_path` — is v2.1.142 or later. See Migrate to Task tools for how monitoring code changes. The examples on this page set `CLAUDE_CODE_ENABLE_TASKS=0` to keep showing `TodoWrite` for sessions that have not migrated yet.
modified Scale to many tools with tool search View current →
--- a/tool-search.md +++ b/tool-search.md @@ -13,7 +13,7 @@ When tool search is active, tool definitions are withheld from the context window. The agent receives a summary of available tools and searches for relevant ones when the task requires a capability not already loaded. Up to five of the most relevant tools are loaded into context by default, where they stay available for subsequent turns. If the conversation is long enough that the SDK compacts earlier messages to free space, previously discovered tools may be removed, and the agent searches again as needed. Tool search adds one extra round-trip the first time Claude discovers a tool (the search step), but for large tool sets this is offset by smaller context on every turn. With fewer than ~10 tools, loading everything upfront is typically faster. For details on the underlying API mechanism, see [Tool search in the API](<https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool>). -Tool search is supported on Claude Sonnet 4.5, Claude Haiku 4.5, Claude Opus 4.5, and later models; see [model compatibility in the API docs](<https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool#model-compatibility>) for the current list. The same minimums apply on Google Cloud’s Agent Platform, where the SDK loads tool definitions upfront for earlier models instead, because their serving stacks reject the required beta header.Tool search also isn’t supported on Microsoft Foundry [deployments hosted on Azure](<https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry#hosting-options>), which reject it server-side: the SDK detects the rejection and loads tool definitions upfront for that deployment instead. `ENABLE_TOOL_SEARCH` can’t override this, since the rejection comes from the deployment itself. +Tool search isn’t supported on Microsoft Foundry [deployments hosted on Azure](<https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry#hosting-options>), which reject it server-side: the SDK detects the rejection and loads tool definitions upfront for that deployment instead. `ENABLE_TOOL_SEARCH` can’t override this, since the rejection comes from the deployment itself. ## @@ -103,7 +103,7 @@ asyncio.run(main()) -To run this example, replace `https://tools.example.com/mcp` with the URL of your own MCP server. On success the result text prints to the console. Because this is a single-shot `query()` call, the SDK raises after yielding an error result, so the example wraps the loop in a try block. To see why a run failed, check the result message’s `subtype`, such as `error_during_execution`, inside the loop. For more on result messages, see [Handle the result](</docs/en/agent-sdk/agent-loop#handle-the-result>). Setting `ENABLE_TOOL_SEARCH` to `"false"` disables tool search and loads all tool definitions into context on every turn. This removes the search round-trip, which can be faster when the tool set is small (fewer than ~10 tools) and the definitions fit comfortably in the context window. +To run this example, replace `https://tools.example.com/mcp` with the URL of your own MCP server. On success the result text prints to the console. Because this is a single-shot `query()` call, the SDK raises after yielding an error result, so the example wraps the loop in a try block. To see why a run failed, check the result message’s `subtype`, such as `error_during_execution`, inside the loop. For more on result messages, see [Handle the result](</docs/en/agent-sdk/agent-loop#handle-the-result>). ##
modified Tools reference View current →
--- a/tools-reference.md +++ b/tools-reference.md @@ -19,7 +19,7 @@ `ExitWorktree`| Exits a worktree session and returns to the original directory. Not available to subagents that already run in their own working directory, such as with [`isolation: worktree`](</docs/en/sub-agents#supported-frontmatter-fields>)| No `Glob`| Finds files based on pattern matching. See Glob tool behavior| No `Grep`| Searches for patterns in file contents. See Grep tool behavior| No -`ListAgents`| Lists the agents Claude can message with `SendMessage`, apart from [agent team](</docs/en/agent-teams>) teammates, which Claude reaches through the team’s roster: subagents in the session, your other local Claude Code sessions, and reply-only [Remote Control](</docs/en/remote-control>) sessions, which cover your sessions on other machines and on [Claude Code on the web](</docs/en/claude-code-on-the-web>). Backs the `/list-agents` command. See [cross-session messaging](</docs/en/cross-session-messaging>). Requires Claude Code v2.1.224 or later, and appears only in sessions where [cross-session messaging is enabled](</docs/en/cross-session-messaging#availability>)| No +`ListAgents`| Lists the agents Claude can message with `SendMessage`, apart from [agent team](</docs/en/agent-teams>) teammates, which Claude reaches through the team’s roster: subagents in the session, your other local Claude Code sessions, your [Claude Code on the web](</docs/en/claude-code-on-the-web>) sessions when this session has cloud access, and your Remote Control sessions on other machines while this session is connected to [Remote Control](</docs/en/remote-control>). Backs the `/list-agents` command. See [cross-session messaging](</docs/en/cross-session-messaging>). Requires Claude Code v2.1.224 or later, and appears only in sessions where [cross-session messaging is enabled](</docs/en/cross-session-messaging#availability>)| 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. Can also open a WebSocket and treat each incoming message as an event. See Monitor tool| Yes @@ -31,7 +31,7 @@ `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 Cloud’s Agent Platform, 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. As of v2.1.199, a finding can also carry an optional `category` slug, such as `correctness` or `test-coverage`, shown next to the file location in the rendered list| 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. To end the loop instead, Claude calls it with `stop: true`, which cancels the pending wakeup. The `stop` field requires Claude Code v2.1.202 or later. The pending wakeup appears in `session_crons` in [Stop hook input](</docs/en/hooks#stop-input>). Not available on Amazon Bedrock, Claude Platform on AWS, Google Cloud’s Agent Platform, or Microsoft Foundry, where a `/loop` prompt with no interval runs on a fixed schedule instead| No -`SendMessage`| Sends a message to another agent: an [agent team](</docs/en/agent-teams>) teammate, a [subagent it resumes](</docs/en/sub-agents#resume-subagents>) by agent ID or name, or one of your other Claude Code sessions, on this machine or, in reply, beyond it through [Remote Control](</docs/en/remote-control>). Messaging other sessions requires Claude Code v2.1.224 or later and works only in sessions where [cross-session messaging is enabled](</docs/en/cross-session-messaging#availability>). A completed subagent auto-resumes in the background; a subagent you stopped from `/tasks` doesn’t and the call returns a refusal. Structured team-protocol messages require agent teams. A receiver never treats a message from another agent as your consent or approval. In [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>), and in [plan mode while the auto classifier reviews commands](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>), the classifier reviews each send, plain or structured, before Claude Code delivers it; the classifier review requires Claude Code v2.1.222 or later. A subagent treats a message from the agent that launched it as normal task direction rather than as a peer request; before v2.1.198, it treated such a message as a peer request. Claude Code refuses a send to a name that now resolves to a different agent than it did earlier in the conversation, where before v2.1.199 it delivered the message; see [Resume subagents](</docs/en/sub-agents#resume-subagents>)| No +`SendMessage`| Sends a message to another agent: an [agent team](</docs/en/agent-teams>) teammate, a [subagent it resumes](</docs/en/sub-agents#resume-subagents>) by agent ID or name, or one of your other Claude Code sessions, on this machine or beyond it. Messaging other sessions requires Claude Code v2.1.224 or later; [cross-session messaging](</docs/en/cross-session-messaging>) covers which sessions Claude can reach and each case’s requirements. A receiver never treats a message from another agent as your consent or approval| 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 Cloud’s Agent Platform, 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
modified Troubleshooting View current →
Show diff (200 lines)
--- a/troubleshooting.md +++ b/troubleshooting.md @@ -1,161 +1,68 @@ -This page covers performance, stability, and search problems once Claude Code is running. For other issues, start with the page that matches where you’re stuck: - -Symptom| Go to ----|--- -`command not found`, install fails, PATH issues, `EACCES`, TLS errors| [Troubleshoot installation and login](</docs/en/troubleshoot-install>) -Update or install download fails with `The connection dropped while downloading the update` or `aborted`| [Error reference](</docs/en/errors#the-connection-dropped-while-downloading-the-update>) -Login loops, OAuth errors, `403 Forbidden`, “organization disabled”, Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry credentials| [Troubleshoot installation and login](</docs/en/troubleshoot-install#login-and-authentication>) -Settings not applying, hooks not firing, MCP servers not loading| [Debug your configuration](</docs/en/debug-your-config>) -`API Error: 5xx`, `529 Overloaded`, `429`, request validation errors| [Error reference](</docs/en/errors>) -`model not found` or `you may not have access to it`| [Error reference](</docs/en/errors#theres-an-issue-with-the-selected-model>) -VS Code extension not connecting or detecting Claude| [VS Code integration](</docs/en/vs-code#fix-common-issues>) -`Claude Code process exited with code 1` in VS Code or an SDK app| [Error reference](</docs/en/errors#claude-code-process-exited-with-code-n>) -JetBrains plugin or IDE not detected| [JetBrains integration](</docs/en/jetbrains#troubleshooting>) -High CPU or memory, slow responses, hangs, search not finding files| Performance and stability below - -If you’re not sure which applies, run `/doctor` inside Claude Code for an automated check of your installation, settings, extensions, and context usage; it proposes fixes it can apply after you confirm. If `claude` won’t start at all, run `claude doctor` from your shell instead. Run `/mcp` to check MCP server status. +Entries on this page are keyed to the error you see. Each names the cause and what to do. ## ​ -Performance and stability - -These sections cover issues related to resource usage, responsiveness, and search behavior. +CLI startup ### ​ -High CPU or memory usage +CLINotFoundError: Claude Code not found -Claude Code is designed to work with most development environments, but may consume significant resources when processing large codebases. If you’re experiencing performance issues: +The Python SDK launches the Claude Code CLI as a subprocess. When it can’t find a `claude` executable, connecting fails with a `CLINotFoundError`: - 1. Use `/compact` regularly to reduce context size. If it returns `Not enough messages to compact.`, the conversation has too few turns to summarize; that can happen even with a full context when a single large paste filled it - 2. Close and restart Claude Code between major tasks - 3. Consider adding large build directories to your `.gitignore` file - 4. Restart with [`claude --safe-mode`](</docs/en/cli-reference#cli-flags>) to check whether a plugin, MCP server, or hook is the source. It disables all customizations for the session; if usage drops, see [Debug your configuration](</docs/en/debug-your-config#test-against-a-clean-configuration>) to find which one + Claude Code not found at: /your/configured/path -If memory usage stays high after these steps, run `/heapdump` to write two files to `~/Desktop`: a JavaScript heap snapshot named `<session-id>.heapsnapshot` and a memory breakdown named `<session-id>-diagnostics.json`. The command doesn’t appear in the command menu; type it in full. On Linux without a Desktop folder, the files are written to your home directory. +The message includes the configured path when you set `ClaudeAgentOptions(cli_path=...)` and it points at a missing file. Without `cli_path`, the SDK searches your `PATH` and common install locations, and the message includes install instructions for your platform. To fix it: -The `.heapsnapshot` file contains every string in the process, including your full conversation and credentials. Don’t attach it to a public issue or share it. - -The command also prints a summary in the conversation, showing resident set size, JS heap, array buffers, and unaccounted native memory, plus any leak indicators it detected, such as a high memory growth rate or an unusually high number of open handles. The summary says whether most memory is in the JS heap, which the snapshot captures, or in native memory, which it doesn’t. Do one of two things with the output: - - * **Report it** : open a [GitHub issue](<https://github.com/anthropics/claude-code/issues>) and attach only the `-diagnostics.json` file, which carries the statistics behind the printed summary and no conversation content or credentials - * **Investigate it yourself** : if the summary says most memory is JS heap, open the `.heapsnapshot` file in Chrome DevTools under Memory → Load and sort by retained size to see what’s holding the memory - -If the summary says most memory is native, the snapshot can’t show it; include the summary’s leak indicators in your report instead. + * Install Claude Code if it isn’t installed. See [Install Claude Code](</docs/en/setup#install-claude-code>) for the command on your platform. + * If you set `cli_path`, confirm the file exists and is the `claude` executable. + * If you rely on `PATH` resolution, confirm `claude --version` works in the same environment your application runs in. Processes you launch outside your shell, such as from an IDE or a service manager, often run with a different `PATH`. ### ​ -Large tables are cut off in the terminal +CLIConnectionError: Refusing to execute batch script -A Markdown table with more than 200 rows renders its first 200 rows followed by a `… N more rows not shown` line. Only the display is capped: the full table stays in the conversation, and [`/copy`](</docs/en/commands>) copies every row. For a table too large to read in the terminal, ask Claude to write it to a file instead. Before v2.1.208, Claude Code rendered every row, so resuming a session that contained a very large table could stall while it re-rendered. +On Windows, connecting fails with a `CLIConnectionError` when the CLI path the Python SDK uses is a `.bat` or `.cmd` batch script, including the `claude.cmd` shim that an npm install creates: + + Refusing to execute batch script 'C:\\Users\\you\\AppData\\Roaming\\npm\\claude.cmd': Windows runs .bat/.cmd files via cmd.exe, which can execute commands injected through CLI arguments, and no reliable escaping for cmd.exe exists. Use a native claude executable instead: install Claude Code natively (irm https://claude.ai/install.ps1 | iex), point ClaudeAgentOptions(cli_path=...) at a claude.exe, or install the claude-agent-sdk wheel for a platform that bundles claude.exe (e.g. Windows x64). + +The refusal is deliberate security hardening, not a broken install. Windows runs batch scripts by rewriting the spawn into a `cmd.exe /c` invocation, and `cmd.exe` re-parses the whole command line at execution time, so an argument value can execute injected commands. Most Windows installs never reach this error. The Windows x64 wheel of `claude-agent-sdk` bundles a `claude.exe`, and the SDK prefers the bundled CLI, then any native `claude.exe` it can discover, before falling back to a batch shim. You see the refusal in two cases: + + * You set `ClaudeAgentOptions(cli_path=...)` to a `.bat` or `.cmd` file, such as npm’s `claude.cmd` shim. + * Your install has no bundled or native `claude.exe`, for example a source install on ARM64 Windows where the only `claude` on your `PATH` is the npm shim. + +To fix it, give the SDK a native executable instead of a batch script: + + * If you set `ClaudeAgentOptions(cli_path=...)`, point it at a `claude.exe` or remove the option. The SDK skips discovery while `cli_path` is set, so a native install alone can’t take effect. + * Install Claude Code natively in PowerShell: `irm https://claude.ai/install.ps1 | iex` + * On x64 Windows, install the `claude-agent-sdk` wheel, which bundles `claude.exe`. + +Before `claude-agent-sdk` 0.2.124, the Python SDK spawned batch scripts through `cmd.exe` without this check. + +## + +​ + +Structured outputs ### ​ -Auto-compaction stops with a thrashing error +structured_output is None but the result says success -If you see `Autocompact is thrashing: the context refilled to the limit...`, automatic compaction succeeded but a file or tool output immediately refilled the context window several times in a row. Claude Code stops retrying to avoid wasting API calls on a loop that isn’t making progress. To recover: - - 1. Ask Claude to read the oversized file in smaller chunks, such as a specific line range or function, instead of the whole file - 2. Run `/compact` with a focus that drops the large output, for example `/compact keep only the plan and the diff` - 3. Move the large-file work to a [subagent](</docs/en/sub-agents>) so it runs in a separate context window - 4. Run `/clear` if the earlier conversation is no longer needed - -### - -​ - -Command hangs or freezes - -If Claude Code seems unresponsive: - - 1. Press Ctrl+C to attempt to cancel the current operation - 2. If unresponsive, you may need to close the terminal and restart - -Restarting doesn’t lose your conversation. Run `claude --resume` in the same directory to pick the session back up. - -### - -​ - -Garbled or corrupted text in an editor’s integrated terminal - -If characters render as boxes, smears, or the wrong glyphs when running Claude Code in the VS Code, Cursor, or Devin Desktop integrated terminal, the terminal’s GPU renderer is likely the cause. Run `/terminal-setup` inside Claude Code to set `terminal.integrated.gpuAcceleration` to `"off"`, or set it manually in your editor settings and reload the window. See [Terminal configuration](</docs/en/terminal-config>) for the other settings `/terminal-setup` writes. - -### - -​ - -Search and discovery issues - -If the Search tool, `@file` mentions, custom agents, or custom skills aren’t finding files, the bundled `ripgrep` binary may not run on your system. Install your platform’s `ripgrep` package and tell Claude Code to use it instead: - - * macOS - - * Ubuntu/Debian - - * Alpine - - * Arch - - * Windows - - brew install ripgrep - - sudo apt install ripgrep - - apk add ripgrep - -`ripgrep` is in Alpine’s community repository. If `apk` reports that the package is missing, see [Alpine Linux setup](</docs/en/setup#alpine-linux-and-musl-based-distributions>). - - pacman -S ripgrep - - winget install BurntSushi.ripgrep.MSVC - -Then set `USE_BUILTIN_RIPGREP` to `0`, either in your shell [environment](</docs/en/env-vars>) or in the `env` block of your [`settings.json`](</docs/en/settings#available-settings>): - - { - "env": { - "USE_BUILTIN_RIPGREP": "0" - } - } - -To confirm the switch took effect, run `claude doctor` in your terminal and check that the Search line shows the path of your system ripgrep instead of `OK (bundled)`. - -### - -​ - -Slow or incomplete search results on WSL - -Disk read performance penalties when [working across file systems on WSL](<https://learn.microsoft.com/en-us/windows/wsl/filesystems>) may result in fewer-than-expected matches when using Claude Code on WSL. Search still functions, but returns fewer results than on a native filesystem. - -`claude doctor` shows Search as OK in this case. - -**Solutions:** - - 1. **Submit more specific searches** : reduce the number of files searched by specifying directories or file types: “Search for JWT validation logic in the auth-service package” or “Find use of md5 hash in JS files”. - 2. **Move project to Linux filesystem** : if possible, ensure your project is located on the Linux filesystem (`/home/`) rather than the Windows filesystem (`/mnt/c/`). - 3. **Use native Windows instead** : consider running Claude Code natively on Windows instead of through WSL, for better file system performance. +A result message can end with `subtype: "success"` while `structured_output` is `None` in Python or `undefined` in TypeScript. The run completes, but no validated output exists. One way to hit this is a schema no output can satisfy, for example conflicting length constraints. The run ends without a validation error, and the only signal is the missing `structured_output`. Treat this result as a failure in application code. Check both that `subtype` is `success` and that `structured_output` is present before using it. The [Error handling](</docs/en/agent-sdk/structured-outputs#error-handling>) section shows this pattern for both SDKs. If it happens repeatedly with a schema you believe is correct, verify the schema is satisfiable, then simplify it until outputs validate, and reintroduce constraints one at a time. ## ​ -Get more help +Report a new issue -If you’re experiencing issues not covered here: - - 1. Run `/doctor` for a setup checkup and `/mcp` to check MCP server status - 2. Use the `/feedback` command within Claude Code to report problems directly to Anthropic - 3. Check the [GitHub repository](<https://github.com/anthropics/claude-code>) for known issues - 4. Ask Claude directly about its capabilities and features. Claude has built-in access to its documentation. - -For account, billing, or subscription problems, contact Anthropic support instead: sign in at [claude.ai](<https://claude.ai>) (Console users: [platform.claude.com](<https://platform.claude.com>)), click your initials in the lower left, and select **Get help**. See [How to get support](<https://support.claude.com/en/articles/9015913-how-to-get-support>) for the full flow, including who can reach a human agent on each plan. +If your error isn’t covered here, check the open issues or file a new one in the SDK repositories: [claude-agent-sdk-typescript](<https://github.com/anthropics/claude-agent-sdk-typescript/issues>) or [claude-agent-sdk-python](<https://github.com/anthropics/claude-agent-sdk-python/issues>). Include the full error text and your SDK version.
modified Agent SDK reference - TypeScript View current →
Show diff (128 lines)
--- a/typescript.md +++ b/typescript.md @@ -419,7 +419,7 @@ Resolves the effective Claude Code settings for a given directory using the same merge engine as the CLI, without spawning the Claude CLI. Use it to inspect what configuration a `query()` call would see before invoking one. -This function is alpha and its API may change before stabilization. It reads MDM sources, including macOS plist and Windows HKLM/HKCU, for parity with CLI startup, but does not execute the admin-configured `policyHelper` subprocess. The `permissions.defaultMode` field is returned as-is from all tiers including project settings. The trust filter the CLI applies before honoring escalating permission modes is not applied. +This function is alpha and its API may change before stabilization. It reads MDM sources, including macOS plist and Windows HKLM/HKCU, for parity with CLI startup, but does not execute the admin-configured `policyHelper` subprocess. The `permissions.defaultMode` field is returned as-is from all tiers including project settings. In a live session, the CLI [ignores `defaultMode: 'auto'` from project and local settings](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>); `resolveSettings()` skips that check, so an `auto` from those tiers appears here even though a session would ignore it. function resolveSettings( options?: ResolveSettingsOptions @@ -653,7 +653,7 @@ * **Applied during the current turn** : `model`. If you switch `model` while Claude is working on a turn, the response Claude is already generating finishes on the old model, and the rest of the turn, starting with the next call Claude Code makes to the model, uses the new one. Subagents keep their own model. Before v2.1.212, a mid-turn switch waited for the next turn. * **No effect mid-session** : the system prompt options. These are resolved once at startup, so the running session keeps the original value even though the call succeeds. To change them, start a new session. -`effortLevel` accepts an [effort level](</docs/en/model-config#adjust-effort-level>) name. It also accepts `"ultracode"`, which runs the session at `xhigh` effort and turns on [ultracode](</docs/en/workflows#let-claude-decide-with-ultracode>). The `Settings` type declares `effortLevel` without that value, so pass the equivalent `{ ultracode: true }` in TypeScript. The `ultracode` value requires Claude Code v2.1.203 or later and is accepted only by `applyFlagSettings()`, not by the `effortLevel` key in a settings file. The values are written to the flag-settings layer, the same layer the inline `settings` option of `query()` populates at startup. Flag settings sit near the top of the [settings precedence order](</docs/en/settings#settings-precedence>): they override user, project, and local settings, and only managed policy settings can override them. This is the same tier the on-page precedence section calls programmatic options. Successive calls shallow-merge top-level keys. A second call with `{ permissions: {...} }` replaces the entire `permissions` object from the prior call rather than deep-merging into it. To clear a key from the flag layer and fall back to lower-precedence sources, pass `null` for that key. Passing `undefined` has no effect because JSON serialization drops it. Only available in streaming input mode, the same constraint as `setModel()` and `setPermissionMode()`. The example below switches the active model mid-session, then clears the override so the model falls back to whatever the user or project settings specify. +`effortLevel` accepts an [effort level](</docs/en/model-config#adjust-effort-level>) name. It also accepts `"ultracode"`, which runs the session at `xhigh` effort and turns on [ultracode](</docs/en/workflows#let-claude-decide-with-ultracode>). The `Settings` type declares `effortLevel` without that value, so pass the equivalent `{ ultracode: true }` in TypeScript. The `ultracode` value requires Claude Code v2.1.203 or later and is accepted only by `applyFlagSettings()`, not by the `effortLevel` key in a settings file. The values are written to the flag-settings layer, the same layer the inline `settings` option of `query()` populates at startup. This is the same tier the on-page precedence section calls programmatic options. Successive calls shallow-merge top-level keys. A second call with `{ permissions: {...} }` replaces the entire `permissions` object from the prior call rather than deep-merging into it. To clear a key from the flag layer and fall back to lower-precedence sources, pass `null` for that key. Passing `undefined` has no effect because JSON serialization drops it. Only available in streaming input mode, the same constraint as `setModel()` and `setPermissionMode()`. The example below switches the active model mid-session, then clears the override so the model falls back to whatever the user or project settings specify. import { query } from "@anthropic-ai/claude-agent-sdk"; @@ -920,7 +920,7 @@ Default behavior -When `settingSources` is omitted or `undefined`, `query()` loads the same filesystem settings as the Claude Code CLI: user, project, and local. [Endpoint-managed policy](</docs/en/settings#settings-files>) is loaded in all cases; server-managed settings are fetched when the session authenticates with an organization credential on an [eligible configuration](</docs/en/server-managed-settings#platform-availability>). See [What settingSources does not control](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>) for inputs that are read regardless of this option, and how to disable them. +When `settingSources` is omitted or `undefined`, `query()` loads the same filesystem settings as the Claude Code CLI: user, project, and local. See [What settingSources does not control](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>) for inputs that are read regardless of this option, and how to disable them. #### @@ -938,17 +938,6 @@ options: { settingSources: [] } }); -**Load all filesystem settings explicitly:** - - import { query } from "@anthropic-ai/claude-agent-sdk"; - - const result = query({ - prompt: "Analyze this code", - options: { - settingSources: ["user", "project", "local"] // Load all settings - } - }); - **Load only specific setting sources:** import { query } from "@anthropic-ai/claude-agent-sdk"; @@ -958,40 +947,6 @@ prompt: "Run CI checks", options: { settingSources: ["project"] // Only .claude/settings.json - } - }); - -**Testing and CI environments:** - - import { query } from "@anthropic-ai/claude-agent-sdk"; - - // Ensure consistent behavior in CI by excluding local settings - const result = query({ - prompt: "Run tests", - options: { - settingSources: ["project"], // Only team-shared settings - permissionMode: "bypassPermissions", - allowDangerouslySkipPermissions: true - } - }); - -**SDK-only applications:** - - import { query } from "@anthropic-ai/claude-agent-sdk"; - - // Define everything programmatically. - // Pass [] to opt out of filesystem setting sources. - const result = query({ - prompt: "Review this PR", - options: { - settingSources: [], - agents: { - /* ... */ - }, - mcpServers: { - /* ... */ - }, - allowedTools: ["Read", "Grep", "Glob"] } }); @@ -1560,7 +1515,7 @@ `SDKPermissionDeniedMessage` -Stream event emitted when the permission system auto-denies a tool call without an interactive prompt. Use it to render the denial in your UI as it happens, rather than only observing the `is_error` tool result that follows. The interactive ask path reaches your application separately through the `canUseTool` callback. Denials issued by a `PreToolUse` hook are not reported through this event. This event requires Claude Code v2.1.136 or later. +Stream event emitted when the permission system auto-denies a tool call without an interactive prompt. Use it to render the denial in your UI as it happens, rather than only observing the `is_error` tool result that follows. The interactive ask path reaches your application separately through the `canUseTool` callback. Denials issued by a `PreToolUse` hook are not reported through this event. type SDKPermissionDeniedMessage = { type: "system"; @@ -1639,7 +1594,7 @@ A `peer` origin identifies which agent sent the message: an in-process [teammate](</docs/en/agent-teams>) sending to `main` with `SendMessage`, or a [cross-session peer](</docs/en/cross-session-messaging>), another of your Claude Code sessions. A cross-session peer can run on the same machine, or on [another of your machines](</docs/en/cross-session-messaging#message-sessions-on-other-machines>) or [Claude Code on the web](</docs/en/claude-code-on-the-web>) when its message arrives through Remote Control. The two kinds of sender fill the fields differently: - * `from`: the teammate’s name, or the sender address for a cross-session peer. For a [one-way cross-machine reply](</docs/en/cross-session-messaging#message-sessions-on-other-machines>), the sender has no reply address and `from` is `"unknown"`. The value is sender-authored; `verifiedPeerPid` is the verified identity. + * `from`: the teammate’s name, or the sender address for a cross-session peer. For a [one-way cross-machine message](</docs/en/cross-session-messaging#message-sessions-on-other-machines>), the sender has no reply address and `from` is `"unknown"`. The value is sender-authored; `verifiedPeerPid` is the verified identity. * `senderTaskId`: the teammate’s task ID. Absent for a cross-session peer. * `name`: the sender’s display name, normalized by Claude Code: it strips Unicode control, format, surrogate, and line or paragraph separator code points, then trims the result and caps it at 64 code points with an ellipsis. Requires Claude Code v2.1.205 or later. * `body`: the decoded message body with the peer envelope stripped, byte-exact with what the model sees. Always present for a teammate message; for a cross-session peer, present only when the turn is exactly one peer envelope formed by Claude Code. Render `name` and `body` instead of re-parsing the message text. Requires Claude Code v2.1.205 or later. @@ -2742,8 +2697,6 @@ `title`| `string`| Ignored; the script’s `meta` block sets the title `description`| `string`| Ignored; the script’s `meta` block sets the description -The schema accepts any JSON value for `args`; the exported type marks it `unknown`, but the published typings render the field as an object map. - ### ​ @@ -5224,12 +5177,6 @@ if ("result" in message) console.log(message.result); } -This pattern enables you to: - - * **Audit model requests:** Log when the model requests unsandboxed execution - * **Implement allowlists:** Only permit specific commands to run unsandboxed - * **Add approval workflows:** Require explicit authorization for privileged operations - Commands running with `dangerouslyDisableSandbox: true` have full system access. Ensure your `canUseTool` handler validates these requests carefully.If `permissionMode` is set to `bypassPermissions` and `allowUnsandboxedCommands` is enabled, the model can autonomously execute commands outside the sandbox without approval prompts (an explicit [`ask` rule](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) still forces one). This combination effectively allows the model to escape sandbox isolation silently. ##