Self-hosted environments are in public beta on Team and Enterprise plans; an Owner enables them by turning on Allow self-hosted environments on the Cloud environments admin page. This page assumes a working runner; see the quickstart for setup and Deploy to production for the fleet recipes.
pool, such as CLAUDE_RUNNER_POOL_ID; the CLI flag and env var names use environment, such as --environment-secret-file.
Wrapper scripts
Use a wrapper script when each session needs setup the runner can’t do on its own: provisioning short-lived credentials scoped to the session creator, exporting environment-specific secrets, preparing language toolchains, or applying resource limits around the child process. The runner starts your wrapper in place of the Claude Code binary, once per session. End the wrapper byexec-ing into $CLAUDE_RUNNER_CLAUDE_BIN, the runner’s own binary, so signals and exit codes propagate correctly.
Point --exec-path, or SELF_HOSTED_RUNNER_EXEC_PATH, at the wrapper when you start the runner:
The wrapper also inherits the rest of the child’s managed environment, including any server-provided environment variables.
exec propagates all of it automatically; if your wrapper spawns the child another way, forward the full environment.
CLAUDE_CODE_REMOTE_SLACK_THREAD_URL and CLAUDE_CODE_REMOTE_SLACK_THREAD_TS reach your wrapper or command hook. They also reach what the session runs, such as shell commands, git hooks, and Claude Code hooks. The checkout, post-session, and spawn-runner hooks don’t receive them.
Give a default to variables that can be unset
CCR_SESSION_ACCOUNT_EMAIL, CLAUDE_RUNNER_CLIENT_PLATFORM, CLAUDE_CODE_REMOTE_SLACK_THREAD_URL, and CLAUDE_CODE_REMOTE_SLACK_THREAD_TS can each be unset. If your script uses set -u, Bash stops with unbound variable when it expands one that’s unset, so expand them with a default, such as ${CCR_SESSION_ACCOUNT_EMAIL:-}.
Wherever a shell expands the Slack thread link, take these precautions:
- Quote it: the link can contain characters a shell acts on, such as
?and&, so quote the variable, as in"${CLAUDE_CODE_REMOTE_SLACK_THREAD_URL:-}". - Keep its value out of
evalandsh -cstrings: don’t substitute its value into a string thatevalorsh -cruns, even inside quotes. Have that string reference the variable instead.
Keep stdin and file descriptor 3 attached
The child’s stdin is the runner’s control channel. Token rotations and session-end signals arrive on it. The runner also opens a pipe on file descriptor 3 and reads the child’s activity signals from it to drive idle and startup timeouts. A plainexec "$CLAUDE_RUNNER_CLAUDE_BIN" "$@" preserves both automatically.
If your wrapper backgrounds the child with a bare &, it severs the child’s stdin. The session looks healthy until the initial OAuth token’s roughly 30-minute lifetime expires, and then every API call that uses the token fails with 401 authentication_error. If your wrapper must background the child, for example to keep a teardown trap alive, save stdin on file descriptor 4 or higher and re-attach it explicitly:
- File descriptor 3: carries the child’s activity signals to the runner. Don’t close it or reuse it in the wrapper.
- stderr: when the wrapper or the child exits non-zero, the runner posts the last lines of stderr to the session and prints them in its own log. The session’s user sees those lines, so don’t print secrets to stderr, and remove
set -xbefore you deploy the wrapper. If you redirect stderr, sessions still run, but the runner reports a failure with the exit code alone.
Pass the system prompt flags through
The system prompt and appended system prompt that Anthropic’s control plane sends for a session reach your wrapper as file paths, not as inline text. The runner writes each prompt to a file in the session’s config directory,CLAUDE_CONFIG_DIR, and passes its path in the arguments your wrapper receives, as --system-prompt-file <path> or --append-system-prompt-file <path>.
Runners on Claude Code v2.1.281 or later deliver the prompts as files. Before v2.1.281, the runner passed them as --system-prompt <text> and --append-system-prompt <text>.
In your wrapper script or command hook, handle these flags as follows:
- Pass them through: end the wrapper with
exec "$CLAUDE_RUNNER_CLAUDE_BIN" "$@", which forwards the file flags along with every other argument. Don’t drop or rewrite them. If a session loses a prompt file flag, it runs without the instructions the control plane sent for it. - On a runner at v2.1.281 or later, a file flag you append replaces the server’s, never adds to it: each prompt file flag takes a single value and Claude Code keeps the last occurrence, so if you append
--append-system-prompt-file <path>after"$@", your file’s contents replace the server’s appended instructions. To add instructions on top of the server’s, put them in the runner image’sCLAUDE.md, which the runner seeds into every session’s user-level config.
Provision credentials scoped to the session creator
Use thedecode-token subcommand to read claims from the session JWT. It reads the token from an argument, from CLAUDE_CODE_SESSION_ACCESS_TOKEN, or from stdin, in that order; see Verify the token inside the session for what it checks. The example below decodes the creator identity, exchanges it for short-lived AWS credentials, and execs into Claude Code:
jq -re rather than jq -r when the extracted claim gates an auth decision, so an absent claim exits non-zero instead of passing the literal string null downstream. Sessions created by an organization service identity, such as bot and agent sessions, carry an agent: subject rather than user:, so this example refuses them; if your environment serves those sessions, decide explicitly whether the wrapper falls back to a default credential for them instead of exiting. When your credential exchange needs the email instead, read .act.email and handle its absence: the token carries it only when the creating surface recorded it, and a CLI-dispatched session can lack it. For the full claim reference and verification from services outside the runner, see Verify session identity.
Lifecycle hooks
Lifecycle hooks replace stages of the runner’s per-session pipeline with your own scripts. Point the runner at a directory of hooks with--hooks-dir <path>, or SELF_HOSTED_RUNNER_HOOKS_DIR. The runner looks for executable files with well-known names; any hook that isn’t present falls through to the built-in behavior, so you only write the ones you need. Hooks run with the runner’s own privileges, and session children share that UID, so mount the hooks directory read-only, or bake it into the image, so session code can’t modify it; see the hardening section.
These hooks are distinct from Claude Code hooks, which run inside the session; lifecycle hooks run on the runner, around the session.
checkout
Runs once per repository, in place of the runner’s built-in clone and fetch. Use the hook to clone from a read-through mirror that you reach over HTTPS or SSH, seed a working tree from an archive, or apply per-session git auth. The runner sets these variables, and may set otherCLAUDE_RUNNER_ variables that the table doesn’t list:
The script must leave a working tree at
CLAUDE_RUNNER_CHECKOUT_PATH checked out at the requested revision. A detached HEAD works, because the runner creates the session’s working branch on top.
After your hook returns, the runner verifies that CLAUDE_RUNNER_CHECKOUT_PATH contains a .git. If your hook materializes a non-git source such as Perforce or an unpacked tarball, set CLAUDE_RUNNER_SKIP_GIT_VERIFY=1 in the runner’s environment to skip that check. Git-based flows such as working-branch creation and pushing results require a git checkout, so export outcomes from non-git trees with a post-session hook.
Get git credentials in the hook
The runner doesn’t pass a git credential to the hook. Thedecode-token subcommand isn’t available here either, because CLAUDE_RUNNER_CLAUDE_BIN isn’t set in the checkout-hook environment. Mint a per-session clone credential from the session’s identity instead, or fall back to the host’s own git authentication:
- Per-session clone credential: verify
CLAUDE_CODE_SESSION_ACCESS_TOKENwith a standard JWT library against the JWKS endpoint underCLAUDE_RUNNER_API_BASE_URL, as described in Verify the token from your service. Then have your credential service issue a short-lived clone credential for the identity in the token’sactclaim. Key that credential onact.sub, and don’t requireact.email. - Host git authentication: use whatever git authentication the host already has, such as an SSH agent, credential helper, or
.netrc.
When the hook fails
The hook fails when it exits non-zero, or exits 0 without leaving a usable checkout behind:- A repository the session pushes results to: the runner fails the session, and on a non-zero exit surfaces the tail of the script’s stderr to the user.
- A repository the session only reads from, such as a repository added to a running session: the runner logs a
[runner:warn]line with the failure detail, posts aSkippedstep to the session, removes whatever the hook left at the checkout path, and continues with the remaining repositories. If skipping leaves the session with no repository at all, the runner fails the session anyway.
post-session
Runs once per session, after the Claude Code child has exited and before the runner tears the workspace down. This hook is your only chance to save uncommitted work: at--capacity above one, the runner deletes per-session worktrees right after the hook returns, and at --capacity 1 the reused canonical clone is hard-reset when the next session starts, so uncommitted tracked changes don’t survive on either path. Typical uses are pushing a snapshot branch of uncommitted changes, archiving logs, or emitting a session-ended event to your own systems.
The hook fires on every session end where a child process was spawned, whatever the cause; the CLAUDE_RUNNER_EXIT_REASON values below enumerate the cases. It can’t fire when the runner terminates abruptly, such as a VM preemption or a power loss; if you need guarantees against abrupt termination, snapshot periodically from inside the session with a Claude Code PostToolUse hook instead. The runner sets:
CLAUDE_RUNNER_EXIT_REASON takes one of four values:
completed: the session ended cleanly. The Claude Code process exited normally, or exited by itself after the session was archived or deleted.failed: the Claude Code process crashed, or setup failed after it started.interrupted: the runner stopped the session, in one of these cases:- The runner released the session to free the slot.
- The session timed out at startup.
- The server moved the session off this runner.
- The runner’s poll noticed an archive or delete before the process exited.
- The runner was draining.
- The session outlasted its
--kill-session-after-minlimit.
abandoned: reserved for a session another runner claimed. The hook doesn’t currently fire in that case.
interrupted receipts to count as completed there. The counters count a release, a startup timeout, a server move, and an archive or delete that the runner’s poll noticed first as completed, because the runner handed the slot back cleanly.
The hook’s exit status never affects the session outcome; a failure is logged and ignored. The runner waits up to --post-session-hook-timeout-sec, 60 seconds by default, on every session end including runner shutdown. This example saves uncommitted work to a rescue branch:
GIT_ALLOW_PROTOCOL line in the script limits git to HTTPS, HTTP, and SSH remotes. If the runner’s environment already sets a non-empty GIT_ALLOW_PROTOCOL list of its own, the script keeps that list.
The hook pushes with whatever git credentials are available in its own environment on the runner host. Under the no-credentials-in-the-image posture, including when the built-in clone goes through the Anthropic git proxy, there are none, so mint a short-lived push credential inside the hook before pushing: exchange the session token the hook receives in CLAUDE_CODE_SESSION_ACCESS_TOKEN with your own token service, verifying it as Verify session identity describes.
Treat any credential your hook gives git as one a session can obtain, and mint it so that it can do no more than this push. Git in your hook reads configuration files that a session can write, and a credential helper or filter driver named in one of them runs with your hook’s privileges. Settings in those files can also change where a push goes, whatever remote you name. For the git settings the runner fixes in your hook and the ones it leaves to those files, see Git configuration inside lifecycle hooks.
Hook timing when the runner releases a session
A released session can resume on another runner. On a runner on v2.1.236 or later, what the session was doing at release decides whether it can resume before this hook finishes:- Idle after a turn, or timed out at startup: the runner stops the child and runs this hook to completion. Only then does it release the session. A user message sent while the hook runs can’t resume the session on another runner before the hook finishes.
- Waiting for the user to answer a prompt, such as a permission prompt: the runner releases the session first, then runs this hook. A user message sent while the hook runs can resume the session on another runner before the hook finishes.
--retire-at time, and, on a runner on v2.1.260 or later, at a session’s --kill-session-after-min limit. A session whose turn has ended and that holds only background tasks counts as idle here. Before v2.1.236, the runner released the session first and then ran this hook in both cases.
During a SIGTERM drain, the runner holds the session lease until the hook finishes; see Shutdown timing.
Git configuration inside lifecycle hooks
Thecheckout and post-session hooks run with the session’s access token in their environment, and the git they run reads configuration files that sessions can write, such as ~/.gitconfig and a checkout’s .git/config. Before either hook runs, the runner sets git settings in the hook’s environment, including the ones below, as GIT_CONFIG_COUNT/GIT_CONFIG_KEY_n/GIT_CONFIG_VALUE_n pairs and git environment variables. Git ranks those above every configuration file, and they apply only to the git your hooks run, not to the session’s own git. At startup, the runner prints a [runner:git] lifecycle hooks: line that shows the hooks path, allowed protocols, gpg programs, and signing mode in effect. Requires Claude Code v2.1.280 or later.
- Git hooks: unless you supply a value,
core.hooksPathis/dev/null, so git skips the hooks in a repository’s.git/hooksand any hooks directory that~/.gitconfignames. To supply one, exportcore.hooksPathas aGIT_CONFIG_KEY_n/GIT_CONFIG_VALUE_npair in the runner’s environment. The runner also readscore.hooksPathfrom the system git configuration, and uses it only when the runner’s user can’t write that file, the directory it names, or the hook files in it. When the runner ignores a value, a[runner:warn]line at startup names the value and the reason. - File system monitor:
core.fsmonitoris empty, so git in your hook doesn’t run a monitor program that a configuration file names. - Remote protocols:
GIT_ALLOW_PROTOCOLishttps:http:ssh. A clone, fetch, or push that uses a local path, afile://URL, or agit://URL fails withfatal: transport 'file' not allowedorfatal: transport 'git' not allowed. - SSH command and credential prompt: git in your hook ignores
core.sshCommandandcore.askPassfrom configuration files. To use your own SSH command, setGIT_SSH_COMMANDin the runner’s environment. To use a credential prompt program, setGIT_ASKPASSthere. Sessions inherit the runner’s environment, so both variables also reach the session’s own git. Don’t put a credential in either. - gpg programs:
gpg.program,gpg.openpgp.program,gpg.x509.program, andgpg.ssh.programare paths the runner sets, never values from a configuration file. - Commit signing: with
--configure-git, commits you make from a hook are signed as the session. Without the flag,commit.gpgsignandtag.gpgsignarefalse.
git -c option inside the hook:
- Configuration pairs: a
GIT_CONFIG_KEY_n/GIT_CONFIG_VALUE_npair you export in the runner’s environment replaces the runner’s value for the same key. Number your pairs from0and setGIT_CONFIG_COUNTto how many there are. When the last pair the count announces is missing, the runner ignores all of your pairs and logs a[runner:warn]line at startup. - Git environment variables: the runner leaves
GIT_ALLOW_PROTOCOL,GIT_SSH_COMMAND, andGIT_ASKPASSas you set them in its environment. git -coptions: agit -coption inside the hook overrides aGIT_CONFIG_KEY_npair, the runner’s or yours. It doesn’t changeGIT_ALLOW_PROTOCOL,GIT_SSH_COMMAND, orGIT_ASKPASS, which git reads ahead of any configuration.
url.*.insteadOf rewrites, and filter drivers, from every configuration file, including the ones sessions can write. A credential helper or filter driver named in one of those files runs as a program with your hook’s privileges, and configuration in those files can still change where a push from your hook goes, including a push to a URL you pass on the command line.
Before v2.1.280, the runner set none of these settings, and under --configure-git a commit made from a hook failed unless the hook passed -c commit.gpgsign=false.
command
Runs once per session after checkout, in place of the built-in child spawn. The hook receives the same environment as a wrapper script and shouldexec into "$CLAUDE_RUNNER_CLAUDE_BIN" the same way. Use the command hook to keep all customization in one hooks directory; use --exec-path when the wrapper lives elsewhere. If --exec-path is also set, the flag takes precedence and the command hook is ignored.
Always exec the runner’s own binary rather than a PATH-resolved claude; otherwise you defeat version pinning.
On-demand runners
Instead of running a fixed fleet, you can boot one runner per session. The orchestrator is a separate, stateless subcommand that polls Anthropic for spawn requests, one per session that’s queued with no runner available, and runs yourspawn-runner hook for each. Your hook submits a workload to your platform: a Kubernetes Job, an EC2 instance, a Nomad dispatch.
On-demand runners improve credential hygiene. On a fixed fleet, the environment secret lives on every runner host, which is the same host that runs user sessions. With the orchestrator, the environment secret stays only on the orchestrator host, which never runs user code; each spawned runner receives a single-use work order that registers exactly one runner and then expires.
To start the orchestrator, pass the environment secret and a hooks directory containing an executable spawn-runner script:
--expected-spawn-seconds value; see the hook contract.
The spawn-runner hook
The orchestrator runs${hooks-dir}/spawn-runner once per spawn request. The hook must submit work asynchronously, without waiting for the runner to boot, and return within --hook-timeout, 60 seconds by default. The hook receives:
The spawned runner registers with the work order in place of the environment secret:
- Start it with the work order: point
--environment-secret-fileat a file containing the work-order JWT, or setSELF_HOSTED_RUNNER_ENVIRONMENT_SECRETto the JWT value. - Copy the JWT before the hook exits: the orchestrator deletes the work-order file after the hook exits, so copy the JWT into the workload you submit, such as a Kubernetes Secret on the spawned Job, rather than passing the file path through.
- Use
--capacity 1on spawned runners: a session-bound work order registers exactly one runner bound to that session, so a higher capacity adds slots that never receive work, and the runner logs a warning at startup. - Pre-warming work orders register unbound: the standby runner isn’t bound to a session and claims queued work like a fixed-fleet runner.
-
Be idempotent on
CLAUDE_RUNNER_ORDER_ID. Redelivery of the same request must spawn at most one runner. Derive a deterministic resource name from the order ID and let your platform reject the duplicate. Don’t key onCLAUDE_RUNNER_SESSION_IDinstead. Every re-request for a session carries the same session ID with a new order ID, so a workload named or deduplicated by the session ID is created once and never again for that session. -
Don’t retry the workload. One order ID means at most one created workload. If the runner never registers, Anthropic re-requests with a fresh order ID after
--expected-spawn-seconds. -
Use the exit-code contract. Exit with the status that matches the outcome:
- Exit 0: submitted.
- Exit 1: retryable failure. The session backs off and is re-offered.
- Exit 2 or higher: non-retryable failure. The session is blocked from spawning again until a user sends it a new message or an Owner selects Retry on it in the environment’s Activity tab.
--expected-spawn-secondslease expires. -
Set
--expected-spawn-secondsto at least your p99 time from spawn request to runner registration. Measure from when the orchestrator receives the spawn request, and include any wait for capacity on your platform as well as boot time. This value is the server-side lease, and the work order expires with it, so a runner whose workload takes longer can’t register. All orchestrator replicas must use the same value.
/healthz body for queue counts, then open your environment’s Activity tab on the Cloud environments admin page: expand a failed session there for its spawn error, and select Retry to re-request it.
A session that stays queued with no spawn error in the Activity tab can mean the hook is keyed on the session ID. To confirm, check whether your platform has a workload for that session’s first spawn request and none for the re-requests. If so, key the workload on CLAUDE_RUNNER_ORDER_ID instead.
Keep transient failures retryable in a shell hook
In a shell hook that usesset -e, a failure that a retry could have cleared can block the session. The hook stops at the failing command and exits with that command’s own status, and the orchestrator applies the exit-code contract to that status. Many failures return a status of 2 or higher, such as 127 when a command isn’t installed and 22 from curl --fail on an HTTP error, so they block the session at its first failure.
A session the hook has already blocked stays blocked until a user sends it a new message or an Owner selects Retry on it in the environment’s Activity tab.
To turn such a failure into exit 1 instead, put these lines directly below the hook’s #! line, above anything that can fail:
-
Bare
exit 2or higher: with the trap set, it becomes exit 1. For an error that no retry can fix, callpermanentwith the reason instead, such aspermanent "namespace claude-runners does not exist". Call it in the main shell, not inside$( ),( ), or a pipe. -
exec: don’t start the hook’s last command withexec, becauseexecreplaces the shell and the trap doesn’t run. -
Second
EXITtrap: a secondtrap ... EXITreplaces the first, so merge the two into a single trap. Put your cleanup commands directly afterrc=$?;and end each with|| true;. Cleanup then runs on failure as well as on success, and a failing cleanup command doesn’t set the hook’s exit status. This merged trap shows the shape, withyour-cleanup-commandstanding in for your own: -
Commands that are allowed to fail: if the hook didn’t use
set -ebefore, it now stops at the first command that returns non-zero, such as a lookup that finds nothing or a duplicate submit that your platform rejects. If the hook acts on the result, make that command the condition of anif. If it ignores the result, follow the command with|| true.
trap line that calls a command that doesn’t exist, such as no-such-command. Run the hook file from your shell and check that echo $? prints 1, then remove the line.
Send model requests to Bedrock or Agent Platform
If your organization needs model requests to go through its own AWS or Google Cloud account, configure the runner for Amazon Bedrock or Google Cloud’s Agent Platform, formerly Vertex AI. Every session that runner starts then calls the model in your cloud account, with your cloud credentials. Without this configuration, sessions send model requests to the Anthropic API. The runner still polls Anthropic for sessions, and each session still sends its event stream toapi.anthropic.com. The event stream carries prompts, responses, and tool results. The plan requirement and the Zero Data Retention exclusion in Availability and limitations still apply.
Sessions are routed to an environment, not to a runner, and a requeued or resumed session can run on a different runner. Configure every runner in the environment the same way. Before you start, read what differs on these providers.
1
Prepare the cloud account and your egress rules
Set up model access, a narrowly scoped policy or role, and network access:
- Amazon Bedrock: submit use case details, then create the policy in IAM configuration, limiting
bedrock:InvokeModelandbedrock:InvokeModelWithResponseStreamto the inference profiles your sessions use and the foundation models behind them - Agent Platform: enable the API and request model access, then create the custom role that IAM configuration describes, with only
aiplatform.endpoints.predict - Egress: allow your provider’s endpoints through your egress rules. See Network requirements. If sessions can’t reach them, Claude Code can keep retrying for hours before the session shows an error.
2
Give sessions narrowly scoped credentials
Attach the policy or role from step 1 to an identity that can do nothing else. For the methods Claude Code accepts, see Configure AWS credentials and Configure GCP credentials.Check the method you choose against these runner behaviors:
- Metadata endpoint: if you deny sessions the cloud metadata endpoint outright, credentials served from it, such as an instance profile, don’t reach Claude Code either. A file-based web identity, such as IAM Roles for Service Accounts (IRSA) on Amazon EKS or a Workload Identity Federation credential file, doesn’t depend on it.
- Renewal: a session can outlive a credential, so use a method that renews itself, such as a file-based web identity
- Wrapper script: the runner starts your wrapper script once per session, so credentials it exports aren’t renewed. Claude Code reads AWS credentials from its environment, so if your wrapper already exports AWS credentials for other work, Claude Code can sign model requests with them.
3
Set one provider's variables in the runner's environment
Set exactly one provider’s variables where you set the runner’s other environment variables, such as the container spec or service unit, then restart the runner. The examples show them as shell exports. With on-demand runners, set them on the workload your
spawn-runner hook starts.Start these runners with --confine-repo-settings enforce. It refuses sessions on repositories whose committed settings it flags, so run in the default warn mode first and clear what it logs.- Amazon Bedrock
- Google Cloud's Agent Platform
Replace the region with your own:For how Claude Code resolves the region, see Configure Claude Code. For which inference profile prefix Claude Code uses for your region, see Cross-region inference profile prefixes.
4
Check that the variables reached a session
Your own shell on the host is a different process, so check from inside a session. Start one in the environment and ask Claude to run this command:A line that sets
CLAUDE_CODE_USE_BEDROCK or CLAUDE_CODE_USE_VERTEX to 1 means the variable reached the session. If both appear, Claude Code uses Amazon Bedrock. No output means neither reached it.The command shows configuration, not traffic. To confirm the requests themselves, look for them in your cloud account’s own metrics or request logs. If the first message fails instead, see troubleshooting for Amazon Bedrock or Agent Platform.What differs from sessions on the Anthropic API
A session that sends model requests to Amazon Bedrock or Google Cloud’s Agent Platform differs from a session on the Anthropic API in these ways:- Policy from claude.ai: server-managed settings don’t reach these sessions. Neither do the organization policies an Owner sets in Claude Code admin settings, so Claude Code doesn’t enforce them inside the session. Put the rules you rely on in the runner image’s managed settings file.
- Account skills: these sessions don’t download the skills enabled for a person’s claude.ai account. See How each session’s config is assembled.
- Files: files that people attach to a session in claude.ai or the mobile or desktop app don’t reach it, and Claude can’t send files back with the
SendUserFiletool. Put input files in the repository or on the runner instead. - Model selection: Anthropic’s control plane sends each session’s model, and when a session starts without one, Claude Code uses its default for the provider. You can’t choose the model with
ANTHROPIC_MODELorANTHROPIC_DEFAULT_MODELin the runner’s environment, but you can pin what an alias resolves to:ANTHROPIC_MODELandANTHROPIC_DEFAULT_MODEL: the runner removes them from the environment it passes to sessions, even though the provider pages’ examples setANTHROPIC_MODEL.- Per-family pinning variables: the variables in Pin model versions for Amazon Bedrock and Agent Platform do reach sessions. They decide what an alias such as
opusresolves to, not what a full model ID resolves to.
- Models your account doesn’t serve: a session can fail on a message with an error that names the model. Enable the models your developers can choose, the background model described in Pin model versions, and the classifier model that auto mode uses. On Amazon Bedrock, allow each of them in your policy.
- Web search and fast mode: web search isn’t available on Amazon Bedrock, and fast mode isn’t available on either provider. For other capabilities that differ by provider, see CLI capabilities that vary by provider.
MCP servers
To make MCP servers available in every session, add them at image build time with the sameclaude mcp add command used on a desktop install. If your runner is a bare process rather than a container, run the same command as the runner’s user on the host, then restart the runner: it reads host config once at startup. The --scope user flag is required; the default local scope writes under a per-directory key that the runner doesn’t seed into sessions. For example, in your Dockerfile:
mcpServers key from the host’s .claude.json, which lives next to rather than inside ~/.claude/, and the runner seeds only that key into each session’s isolated config; account state and project history are dropped. To confirm the servers reached sessions, start a session on the environment and ask Claude to list its MCP tools; the runner also logs a startup warning for any captured entry whose type it doesn’t recognize and drops the entry, so you can see why that server is missing from sessions. When SELF_HOSTED_RUNNER_HOST_CONFIG_DIR is set, the runner reads .claude.json from that directory instead, so pointing the variable at an empty directory disables MCP seeding too.
Claude Code also loads MCP servers from other sources:
- The enterprise-scope managed MCP file at its standard system path:
/etc/claude-code/managed-mcp.jsonon Linux runner hosts,/Library/Application Support/ClaudeCode/managed-mcp.jsonon macOS hosts. Use it for locked-down fleets where only administrator-listed servers may load. See exclusive control with managed-mcp.json for the precedence rules. When this file is on the runner host, Claude Code skips the MCP servers Anthropic’s control plane delivers to a session, including claude.ai connectors, and names them in a warning on the session child’s stderr, which the runner records at thedebuglog level. Before v2.1.229, those sessions exited at startup withYou cannot dynamically configure MCP servers when an enterprise MCP config is present. - The
managedMcpServerskey in managed settings on the runner host: provides HTTP and SSE servers without taking exclusive control, so servers from the other sources still load. Requires Claude Code v2.1.259 or later. <repo>/.mcp.json: project scope. Commit the file to the repository; its servers are auto-approved in cloud sessions. In a session with several repositories, at most one repository’s file loads.
api.anthropic.com. Sessions created programmatically, such as CLI dispatches, don’t receive connector delivery; give them MCP servers through any of the other sources this section lists instead. The child’s OAuth token doesn’t carry a scope for fetching connectors directly, so the child doesn’t attempt that fetch itself; delivery is server-driven.
settings.json doesn’t carry MCP server definitions, and there is no top-level mcpServers field in the settings schema. In managed settings, provide servers with the managedMcpServers key instead.
Sessions inherit the runner’s environment, so set ENABLE_TOOL_SEARCH there to control MCP tool search for every session a runner spawns; the MCP page covers the values.
Wait for MCP servers before the first turn
A self-hosted session waits briefly for MCP servers that are still connecting, at two separate points. A server that misses a wait has its tools missing when the first turn starts, and they become available later with no action on your part. The two waits are:- Session startup: before the tool list is first taken, the session waits up to 5 seconds by default for an HTTP or SSE server whose entry sets
alwaysLoad: true, or for all servers when you setMCP_CONNECTION_NONBLOCKING=0in the runner’s environment. HTTP and SSE servers otherwise connect in the background. While the session waits here, it’s slower to initialize.MCP_CONNECT_TIMEOUT_MSchanges the 5-second default. - First turn: after the message arrives, the first turn waits up to 2 seconds for stdio servers that are still connecting. While the session waits here, the first reply is slower. To change how long this wait lasts, set
CLAUDE_CODE_MCP_STARTUP_WAIT_MSin the runner’s environment. It doesn’t change which servers the wait covers. Requires Claude Code v2.1.274 or later.
claude mcp add has no alwaysLoad flag. To set the key, add the server with claude mcp add-json instead, which takes it in the server’s JSON and writes it to .claude.json. In your Dockerfile:
Turn off built-in session tools
Anthropic’s control plane attaches its own MCP server, named Claude Code Remote, to cloud sessions. Claude uses the server’s tools to schedule routines, start and steer other cloud sessions, attach more repositories, and follow pull request activity. To turn off the whole server, add a server-level deny rule to your settings. The control plane registers the server under one of three names, depending on how the session was created. Claude Code matches the name in a rule exactly, including case, so write the rule once per name as shown:mcp__Claude_Code_Remote__add_repo. To block the server from connecting at all rather than removing its tools, add the three names without the mcp__ prefix as serverName entries under deniedMcpServers instead.
Put the rules in server-managed settings to reach sessions with no change to the runner, or in ~/.claude/settings.json on the runner. On a runner that sends model requests to Bedrock or Agent Platform, use that file, because server-managed settings don’t reach those sessions. Permissions and tool approval explains how settings on the runner reach sessions.
To confirm the rules took effect, start a session on the environment and ask Claude to list its MCP tools. Claude Code removes a denied tool from Claude’s context, so the denied tools are absent from its answer.
Prompt sessions to push their work
Anthropic-hosted sessions run aStop hook, the Claude Code hook that runs when Claude finishes responding, that prompts Claude to commit and push its work. The runner doesn’t install one. Without it, a session that ends with uncommitted changes leaves that work only on the runner’s disk, and the Create PR button in claude.ai/code stays inactive until the branch exists on the remote.
The reference implementation below has two parts. Merge the settings block into ~/.claude/settings.json on the runner host, which the runner seeds into every session, and save the script as ~/.claude/hooks/stop-hook-nudge.sh on the runner host and make it executable:
$CLAUDE_PROJECT_DIR names.
Permissions and tool approval
A self-hosted session has no terminal attached, so an unanswered permission prompt stalls the turn until the user responds in the UI. Anthropic’s control plane sends each session’s tool list and permission rules with the work payload; the default configuration pre-approves routine tool calls, includingBash, and cloud sessions pre-approve file edits regardless of mode. A call that nothing pre-approves prompts through the session UI.
Only pin auto mode on an environment whose session containers run with default-deny network egress and the rest of the hardening section in place. Routine tool calls, including
Bash network requests, run without a human in the loop on both the default pre-approved tool set and in auto mode, so the network boundary is what limits where those calls can reach.command hook. Auto mode lets sessions run without routine permission prompts: a separate classifier model reviews actions before they run and blocks the ones it rejects, and explicit ask rules still force a prompt; the permission modes page covers what the classifier checks. The runner appends server-computed flags before invoking the wrapper, and for single-value flags such as --permission-mode the parser honors the last occurrence, so a flag you append after "$@" overrides the server-sent value:
--allowed-tools with your rules, for example --allowed-tools "Bash(bazel *) Bash(yarn *) mcp__internal__*". List flags such as --allowed-tools and --disallowed-tools accumulate across occurrences rather than overriding, so your rules apply on top of any rules the control plane sends. To narrow, append --disallowed-tools, which denies tools even if another rule allows them.
How each session’s config is assembled
The runner gives each session its own config directory, seeded from a snapshot of the host’s~/.claude/ that the runner captures once at startup: settings.json, CLAUDE.md, hooks, agents, commands, and skills in your runner image apply to every session as the user-level baseline. If you change config on a running host, the change takes effect only after you restart the runner.
Set SELF_HOSTED_RUNNER_HOST_CONFIG_DIR to seed from a different path, or point it at an empty directory to disable seeding.
Sessions also read these settings files:
- Project settings: a repository-committed
.claude/settings.jsonlayers on top of the user-level baseline. In a session with several repositories, at most one repository’s file takes effect. - Managed settings: sessions read
managed-settings.jsonfrom the standard system path in your runner image. For whether its keys apply alongside server-managed settings, see how Claude Code combines managed sources.
- Where they land: the runner writes each supplied hook script to a reserved
hooks/.ccr-launcher/subdirectory of the session’s config directory and registers the scripts in a separate settings file it passes to the session with--settings, leaving the seededsettings.jsonand your own scripts athooks/<name>untouched. The runner recreates the reserved subdirectory for each session and doesn’t seed host content at~/.claude/hooks/.ccr-launcher/into sessions. - Who authors them: the control plane populates the scripts from fixed constants in its own deployment, never from per-session or third-party input.
- What still governs them: hooks delivered through
--settingsenter the ordinary merged hook configuration, not the managed tier, so your managed settings still apply.disableAllHooksdisables them, and they are not among the categoriesallowManagedHooksOnlykeeps loaded.
.claude/skills/ or add it to your runner image.
Outside Claude Tag sessions, a session in a self-hosted environment runs with auto memory off by default. For instructions that should carry across sessions, use the CLAUDE.md in your runner image or in the repository.
The runner’s snapshot of the host’s ~/.claude/ leaves out the projects/ directory. Auto memory’s default storage location is under that directory. If you put memory files there, the runner doesn’t seed them into sessions, and they don’t turn auto memory on.
Repository settings in sessions with several repositories
In a session with several repositories, Claude Code reads project settings from the directory the session starts in, so at most one repository’s.claude/settings.json takes effect as project settings. A hook defined in another repository’s file doesn’t run, a deny rule in it doesn’t apply, and its env isn’t set.
--capacity 1, the default, with the built-in checkout: the session starts in the first repository in its list of repositories. That repository’s.claude/settings.jsontakes effect as project settings and its.mcp.jsonloads, and the other repositories’ don’t.- A
--capacityabove one, or acheckouthook: the session starts in a per-session directory that contains the checkouts. No repository’s.claude/settings.jsontakes effect as project settings, no repository’s.mcp.jsonloads, and$CLAUDE_PROJECT_DIRin a hook command is that directory, not a checkout.
CLAUDE.md and skills load wherever the session starts. The runner passes every repository to Claude Code as an additional directory, so Claude Code also reads the enabledPlugins and extraKnownMarketplaces keys from each repository’s .claude/settings.json.
To run a hook or apply a permission rule in every session, put it in ~/.claude/settings.json on the runner host. The runner seeds the host file into every session, wherever the session starts. Write a path in a Read or Edit rule as a // absolute or ~/ home-relative pattern, because other patterns anchor at the settings source or the current directory.
Repository-committed permission rules
Don’t put a bare"Edit", "Write", or "NotebookEdit" entry in a repository-committed permissions.allow. A bare file-tool rule matches the tool regardless of path, granting writes anywhere on the host rather than only the workspace, so the runner’s write-scope confine guard flags the session; with --confine-repo-settings enforce it refuses to spawn the session instead of logging and continuing. See the hardening section.
A repository needs no file-tool rule at all: cloud sessions pre-approve file edits regardless of mode. If you do commit a rule, scope it to the workspace, such as "Edit(/**)"; a single leading slash is relative to the project root, which is the session’s workspace. Bare file-tool rules are fine in the operator’s host-level settings.json, since that file isn’t repository-committed.
A defaultMode of auto is only honored from the image-wide or user-level settings file, so a checked-out repository can’t grant itself auto mode. For which modes cloud sessions accept and the full rule syntax, see permission modes.
What’s next
- Reference: every CLI flag, environment variable, and metric
- Verify session identity: validate the session token from services outside the runner