Claude Code through the gateway
Claude Code is Anthropic's coding agent. It runs in a terminal, inside VS Code and JetBrains IDEs, in CI jobs and inside programs built on the Agent SDK, and every one of those calls a model through the Anthropic Messages API. Pointing it at Spanway puts each of those calls behind the gateway, so the company's provider keys never sit on a laptop, every developer gets their own key with a budget and a rate limit, every prompt shows up on the Logs page under that developer's key, and the admin can move Claude Code from one provider to another without touching a single machine.
There are two ways to connect. The usual one is a virtual key in two settings, ANTHROPIC_BASE_URL and ANTHROPIC_AUTH_TOKEN, which this page walks through by hand. spanwayctl configure claude writes the same two settings for you, see coding agent setup. The other is gateway sign-in, where developers sign in with the company SSO through Claude Code's /login and never handle a key.
A real-world scenario
A team of twelve developers uses Claude Code every day on personal API keys, and the finance team cannot tell which project the spend belongs to. The admin registers claude-sonnet-5-5 and claude-haiku-5-5 on the gateway, creates one key per developer with a 300 USD monthly budget and a limit of 120 requests per minute, and sends each developer their key with the settings block from this page. Each developer pastes the block into ~/.claude/settings.json and runs /status to see the gateway address. From the next prompt on, the Logs page shows every turn under the developer's key alias with its cost, the Usage page shows spend per developer, and when one developer's agent gets stuck in a loop at night, the budget stops it at 300 USD instead of the invoice.
Before you start
- A gateway that serves the Anthropic Messages route
POST /v1/messages. Every Spanway gateway does, for any model behind a public name, see Anthropic Messages. - At least one model registered in Models + Endpoints. Claude Code works best with Claude models served under their Anthropic ids, such as
claude-sonnet-5-5,claude-opus-5-5andclaude-haiku-5-5, because Claude Code then knows each model's context window and features. - A recent Claude Code. Check with
claude --versionand update withclaude update. Several gateway features named on this page, such as model discovery with both key headers, need a recent release. - The gateway address reachable from the developer's machine over HTTPS. A gateway signed by a company certificate authority needs that certificate on the machine, see errors.
Make a key for Claude Code
Give every developer their own key, so spend, limits and logs are per person and one leaked key exposes only one person. The full recipe with every field is in make a key for a tool. For Claude Code:
- In the Admin UI open Virtual Keys (
/ui/api-keys) and click + Create New Key. - Under Key Ownership pick Another User and the developer, or You for your own key. Set Key Name to a name that says who and which tool, such as
jane-claude-code. Leave Key Type on AI APIs, so the key can call models but no management route. - In Models, pick the main model and every model Claude Code may ask for on its own. That means the model you set as the background tier with
ANTHROPIC_DEFAULT_HAIKU_MODEL, the models your subagents use, and the model a resumed session was started on. A model missing from the key fails only those calls, with 403, while the main chat keeps working, which is confusing to debug. Models in the picker explains the tiers. - Open Optional Settings. Set Max Budget (USD) to a monthly figure such as
300and Reset Budget to monthly, set Requests per minute Limit (RPM) to about120. Leave Tags empty unless the gateway has an Enterprise license, because key tags need one and without it the key is not created (Only premium users can add tags to keys). The key name already keeps this tool's spend apart in Usage. - Click Create Key and copy the key. It is shown once.
The same key from the API, with the master key or a proxy admin's key:
curl -X POST https://gateway.example.com/key/generate \
-H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
-d '{"key_alias": "jane-claude-code", "key_type": "llm_api", "models": ["claude-sonnet-5-5", "claude-haiku-5-5"], "max_budget": 300, "budget_duration": "30d", "rpm_limit": 120}'
The answer carries the new key in key, together with the alias, models and limits you set.
Steps
The base URL is the gateway root, https://gateway.example.com, with no /v1 at the end. Claude Code adds /v1/messages itself, so a base URL that ends in /v1 makes it call /v1/v1/messages and every request fails with 404. Do not point it at /anthropic either, that is the raw Anthropic pass-through, which skips the router, fallbacks and the model names on the key. A Spanway Cloud workspace uses its own address in the same root form. Connect any client explains the rule for every kind of client.
-
Set the two variables in a terminal, with your gateway address and the key from the admin.
export ANTHROPIC_BASE_URL=https://gateway.example.comexport ANTHROPIC_AUTH_TOKEN=sk-your-spanway-keyIn PowerShell, use
$env:ANTHROPIC_BASE_URL = "https://gateway.example.com"and$env:ANTHROPIC_AUTH_TOKEN = "sk-your-spanway-key". -
Check the address and the key before you open Claude Code. This sends a one token request the way Claude Code does.
curl -sS -w '\n%{http_code}\n' -X POST "$ANTHROPIC_BASE_URL/v1/messages" \-H "Authorization: Bearer $ANTHROPIC_AUTH_TOKEN" \-H "anthropic-version: 2023-06-01" -H "content-type: application/json" \-d '{"model": "claude-sonnet-5-5", "max_tokens": 1, "messages": [{"role": "user", "content": "."}]}'A JSON answer that starts with
{"id":"msg_and a final line200means the gateway, the key and the model all work. A400that names the model still proves the address and the key work, so only the model name is wrong. A401means the key is wrong. Look either up under errors. -
Start
claudefrom the same terminal, send a prompt, then run/status. The Status tab shows anAnthropic base URLline with your gateway address and anAuth tokenline that namesANTHROPIC_AUTH_TOKEN. ALogin methodline that names a claude.ai account instead means Claude Code is still on a personal login, so run/logoutand start again. -
Make the setup permanent. Shell exports only reach programs started from that terminal, so an IDE started from the dock and Claude Code's background agents do not see them. Put the same values in the
envblock of~/.claude/settings.json, which every Claude Code surface on the machine reads. On Windows the file is%USERPROFILE%\.claude\settings.json.{"env": {"ANTHROPIC_BASE_URL": "https://gateway.example.com","ANTHROPIC_AUTH_TOKEN": "sk-your-spanway-key","ANTHROPIC_DEFAULT_HAIKU_MODEL": "claude-haiku-5-5","CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY": "1"}}The two extra lines are optional.
ANTHROPIC_DEFAULT_HAIKU_MODELmoves Claude Code's background tasks to a cheaper model, andCLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERYfills the/modelpicker from the gateway, both explained under models in the picker. Never put the key in a project's.claude/settings.json, which is committed to the repository and shared with everyone who clones it. A value in a settings file wins over the same variable exported in the shell. -
Open Logs (
/ui/logs) in the Admin UI, filter Key Alias by the developer's key alias and check that the prompt is there.
Expected result
The curl check in step 2 answers like this, followed by the status line 200:
{"id": "msg_01Xf7c2d4e1f", "type": "message", "role": "assistant", "model": "claude-sonnet-5-5", "content": [{"type": "text", "text": "."}], "stop_reason": "max_tokens", "stop_sequence": null, "usage": {"input_tokens": 9, "output_tokens": 1}}
/status in Claude Code shows the two lines from step 3, and a prompt gets a normal answer with no error.
On the gateway, every Claude Code turn is one row on Logs under the key alias, with the public model name, the deployment that served it, tokens and cost. Claude Code sends a session id with every request, so the turns of one Claude Code session are folded into one row you can open, and the Session ID filter finds a session by id. The request carries the tag User-Agent: claude-cli, which is how Usage counts it under Top agents and User Agent Activity, see user agent analytics.
Every answer also carries response headers you can read with curl -i or in the detail drawer on Logs:
| Header | What it tells you |
|---|---|
x-spanway-call-id | The id of this request. Search for it on Logs, or send it to support. |
x-spanway-model-group, x-spanway-model-id | The public model name and the deployment that served the turn. |
x-spanway-routing-reason, x-spanway-attempts | Why the router picked that deployment and how many provider calls it took, see routing headers. |
x-spanway-attempted-fallbacks | How many fallback hops happened before the answer, sent after a fallback. |
x-spanway-response-cost | What the turn cost, in USD. |
How Claude Code sends the key
Claude Code has three ways to hold the key, and each sends it in a different header. The gateway reads all of them, so the choice is about convenience and rotation, not compatibility.
| Setting | Header Claude Code sends | When to use it |
|---|---|---|
ANTHROPIC_AUTH_TOKEN | Authorization: Bearer <key> | The default for a Spanway key. It takes over from a saved claude.ai login at once. This is what spanwayctl configure claude writes. |
ANTHROPIC_API_KEY | x-api-key: <key> | Works the same on the gateway. In an interactive session Claude Code asks once whether to use the key, and a key you declined earlier is ignored without asking again, so turn it on under /config with Use custom API key. |
apiKeyHelper | Both headers | When the key comes from a vault or a sign-in command and changes over time. Claude Code runs the command and caches its output for five minutes, or for CLAUDE_CODE_API_KEY_HELPER_TTL_MS milliseconds. |
An apiKeyHelper is a top level setting that names a command which prints only the key:
{
"env": {"ANTHROPIC_BASE_URL": "https://gateway.example.com"},
"apiKeyHelper": "~/bin/get-gateway-key.sh"
}
spanwayctl auth print-token can be that command, which gives Claude Code a short lived token from CLI sign-in that renews itself. A static key and a helper are two different setups. Running spanwayctl configure claude or spanwayctl reconfigure removes a helper you added by hand, so pick one setup per machine.
While any of the three is set, Claude Code sends the Spanway key instead of a developer's claude.ai subscription, so the subscription's usage limits do not apply and the spend lands on the gateway key. Setting only ANTHROPIC_BASE_URL without a key does not switch the credential. Claude Code then keeps sending the saved claude.ai login, which is not a Spanway key, so the gateway answers 401.
Models in the /model picker
The model Claude Code sends is a public model name on the gateway. Claude Code picks it in this order: the --model flag, ANTHROPIC_MODEL, the model setting, then its built-in default. The built-in aliases sonnet, opus, haiku and fable resolve to Anthropic ids such as claude-sonnet-5-5, so the simplest setup is to give the gateway's Claude models exactly those public names. Then the aliases, the picker and the background tier all work with no extra settings.
Filling the picker from the gateway. With CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1, Claude Code calls GET /v1/models on the gateway at startup with its own key and adds what it finds to /model. Claude Code keeps only ids that contain claude or anthropic and drops the rest. The gateway knows this. When the listing request comes from Claude Code, which it recognizes by the claude-cli/ or claude-code/ User-Agent or by the header x-gateway-client: claude-code, together with an anthropic-version header, it lists every other model under an id Claude Code keeps: claude-router- followed by the model name written as hexadecimal UTF-8 bytes. A model the gateway serves as gpt-coder appears as claude-router-6770742d636f646572, with display_name gpt-coder so the picker shows the real name. When Claude Code sends that id back, the gateway routes it to gpt-coder. A model whose max_input_tokens is one million or more also gets the suffix [1m], which tells Claude Code it may use the long context window. Every entry in this view carries source_model, the gateway name the id stands for. Only wildcard routes, names with *, are listed as they are and stay out of the picker.
To see exactly what the picker gets, run the listing the way Claude Code does:
curl https://gateway.example.com/v1/models \
-H "Authorization: Bearer $ANTHROPIC_AUTH_TOKEN" \
-H "anthropic-version: 2023-06-01" -H "x-gateway-client: claude-code"
{"data": [{"type": "model", "id": "claude-sonnet-5-5[1m]", "source_model": "claude-sonnet-5-5", "display_name": "claude-sonnet-5-5", "created_at": "2023-02-28T18:56:42Z", "max_input_tokens": 1000000, "max_tokens": 128000}, {"type": "model", "id": "claude-router-6770742d636f646572", "source_model": "gpt-coder", "display_name": "gpt-coder", "created_at": "2023-02-28T18:56:42Z", "max_input_tokens": 200000, "max_tokens": 32000}], "has_more": false, "first_id": "claude-sonnet-5-5[1m]", "last_id": "claude-router-6770742d636f646572"}
An admin can give a model a friendlier picker label with display_name in its model_info. Claude Code caches the discovered list in ~/.claude/cache/gateway-models.json and refreshes it on each start.
Background tasks and subagents. Claude Code also makes calls the developer does not choose, such as session titles and short summaries, and it starts subagents that may ask for another tier. With a Spanway key those background calls use the main model unless ANTHROPIC_DEFAULT_HAIKU_MODEL names a model, so setting it to claude-haiku-5-5 saves money on every session. ANTHROPIC_DEFAULT_SONNET_MODEL, ANTHROPIC_DEFAULT_OPUS_MODEL and ANTHROPIC_DEFAULT_FABLE_MODEL change what the other aliases resolve to, and CLAUDE_CODE_SUBAGENT_MODEL sets the default model for subagents. Every model those settings name must be served by the gateway and allowed on the key, or those calls fail with 403 while the main chat works. ANTHROPIC_SMALL_FAST_MODEL is the older name of ANTHROPIC_DEFAULT_HAIKU_MODEL.
Models that are not Claude. Claude Code treats a model id it does not recognize, such as a claude-router- id, as a current Claude model. It then assumes a one million token context window and sends adaptive thinking, effort and context management fields, which a provider that is not Anthropic can reject. Set CLAUDE_CODE_MAX_CONTEXT_TOKENS to the model's real window, such as 200000, so Claude Code compacts the conversation before it runs out, and see the next section for the request fields.
Streaming, tools, images, caching and reasoning
For deployments on Anthropic, the gateway forwards Claude Code's requests in their native form, including the anthropic-beta header, so streaming, tool use, images, prompt caching with cache_control, extended and adaptive thinking, effort levels, tool search and the long context window work as they do against Anthropic directly. The gateway also serves POST /v1/messages/count_tokens, so /context shows exact token counts instead of an estimate. For deployments on other providers, the gateway translates tools, tool results, images and documents between formats and streams the answer back as Anthropic events.
Claude Code sends every pre-release feature it knows to a gateway set with ANTHROPIC_BASE_URL, and some providers reject the ones they do not have. These are the known clashes and their switches, all documented by Claude Code as of 2026-11-22:
| What you see | Why | Switch on the developer's machine |
|---|---|---|
400 with Extra inputs are not permitted, or naming context_management, output_config or a tool field such as strict or defer_loading | The public name points at a provider, such as Bedrock or Vertex AI, that does not accept a pre-release field Claude Code sent. | CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1 stops most pre-release fields and their anthropic-beta values. Recent Claude Code releases also retry once without a rejected field on their own. |
400 naming thinking or adaptive, such as Input tag 'adaptive' found | The model behind the name does not accept adaptive thinking, which Claude Code sends to current Claude models and to names it does not recognize. | Point the name at a model build that accepts it. On Claude Opus 4.6 and Sonnet 4.6, CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1 works instead. |
400 with a context or token limit in the provider's words, such as ContextWindowExceededError | The model behind the name has a smaller window than Claude Code assumed, and Claude Code does not recognize the error as a prompt that is too long, so it does not compact on its own. | Run /compact to recover. Set CLAUDE_CODE_AUTO_COMPACT_WINDOW or CLAUDE_CODE_MAX_CONTEXT_TOKENS to the model's window to prevent it. |
| Every turn bills as uncached input | A provider without prompt caching sits behind the name. | Nothing to switch. Serve Claude Code from a provider with prompt caching to cut the cost of long sessions. |
When the gateway sits behind a strict firewall, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 stops Claude Code's own update checks, telemetry and release notes calls, which go to Anthropic and not to the gateway. It also turns off automatic updates, so plan another update path.
If a data policy restricts code traffic, the gateway recognizes Claude Code by its User-Agent and sends its turns only to deployments that meet the policy.
Other Claude Code surfaces
VS Code extension. The extension checks for a key before it starts, and it reads that check from VS Code's own settings, not from ~/.claude/settings.json. Run Preferences: Open User Settings (JSON) and add:
{
"claudeCode.environmentVariables": [
{"name": "ANTHROPIC_BASE_URL", "value": "https://gateway.example.com"},
{"name": "ANTHROPIC_AUTH_TOKEN", "value": "sk-your-spanway-key"}
]
}
Keep the same values in ~/.claude/settings.json as well, so the terminal and the extension agree. If the panel still asks you to sign in, tick Disable Login Prompt (claudeCode.disableLoginPrompt) in VS Code settings.
JetBrains IDEs. The Claude Code plugin runs the claude command in the IDE's terminal, so it uses ~/.claude/settings.json exactly like the terminal does, and the settings from step 4 are all it needs. If the IDE cannot find claude, set the full path under Settings, Tools, Claude Code [Beta], Claude command. A gateway signed by a company certificate authority needs NODE_EXTRA_CA_CERTS in the environment the IDE starts claude from.
GitHub Actions. The action reads ANTHROPIC_BASE_URL from the workflow's env block. It requires the anthropic_api_key input before it starts and sends that value as x-api-key, which the gateway accepts. Store the key as a repository secret and pass it once:
env:
ANTHROPIC_BASE_URL: https://gateway.example.com
steps:
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.SPANWAY_API_KEY }}
Give CI its own service account key with a tight budget and only the models the job needs, so a runaway job cannot spend a developer's budget. The runner must reach the gateway, so a gateway on a private network needs a self-hosted runner inside that network.
Agent SDK. The SDK starts Claude Code as a child process and has no gateway options of its own, so the gateway is set through the environment it passes on. In Python, ClaudeAgentOptions(env=...) adds to the inherited environment:
import os
from claude_agent_sdk import ClaudeAgentOptions
options = ClaudeAgentOptions(
env={
"ANTHROPIC_BASE_URL": "https://gateway.example.com",
"ANTHROPIC_AUTH_TOKEN": os.environ["SPANWAY_API_KEY"],
}
)
In TypeScript, setting options.env replaces the whole environment, so spread process.env into it:
const options = {
env: {
...process.env,
ANTHROPIC_BASE_URL: "https://gateway.example.com",
ANTHROPIC_AUTH_TOKEN: process.env.SPANWAY_API_KEY,
},
};
Claude Desktop. The desktop app does not read ANTHROPIC_BASE_URL. It has its own third-party inference setting, see Claude Desktop.
Claude Code in Slack and Claude Code cloud sessions run on Anthropic's side and do not use these settings, so their traffic does not go through the gateway.
Sign in through the gateway
Claude Code can also sign in to a gateway with /login, and from then on authenticate, run inference and fetch managed settings through it. Spanway implements that protocol under /claude_code_gateway, reusing the gateway's SSO for sign-in, so each developer gets a session bound to their own user and team, spend and logs are attributed to them, and the security team can push settings such as denied commands to every installation. This suits organisations that do not want to hand out keys at all. The gateway also hosts a Claude Code plugin marketplace, which has its own page.
Gateway sign-in and a gateway key cannot be combined on one machine. Claude Code refuses to start with forceLoginMethod in managed settings while ANTHROPIC_AUTH_TOKEN, ANTHROPIC_API_KEY or apiKeyHelper is set, so pick one per machine.
-
Turn the protocol on with the Claude Code gateway card on the Skills page, which needs no restart, see turn gateway sign-in on from the Admin UI. Or add the setting to
config.yamland restart. Managed settings are optional:general_settings:enable_claude_code_gateway: trueclaude_code_gateway_managed_settings:permissions:deny: ["Bash(rm -rf *)"]env:CLAUDE_CODE_ENABLE_TELEMETRY: "1" -
Point each developer machine at the gateway. Claude Code's terminal login picker has no gateway option, so the gateway URL is set in settings. In the developer's own
~/.claude/settings.json, on Claude Code v2.1.295 or later, two keys are enough:{"forceLoginMethod": "gateway","forceLoginGatewayUrl": "https://gateway.internal.example.com/claude_code_gateway"}In the managed settings file you push to developer machines, add a third key,
parentSettingsBehaviorset tomerge. It lets Claude Desktop pass the gateway's list of allowed outbound addresses on to the Claude Code sessions it starts, so those sessions can reach the gateway too:{"forceLoginMethod": "gateway","forceLoginGatewayUrl": "https://gateway.internal.example.com/claude_code_gateway","parentSettingsBehavior": "merge"}Claude Code checks the address before it signs in. The gateway host must resolve only to private addresses (RFC 1918, link-local, CGNAT
100.64.0.0/10, IPv6 ULA or loopback), and plainhttp://is accepted only forlocalhost,127.0.0.1and::1. An internal network numbered from public address space your company owns is declared with thegatewayInternalNetworksmanaged setting. The gateway sign-in needs Claude Code v2.1.195 or later. -
The developer runs
/loginin Claude Code. The Cloud gateway screen opens with the URL filled in, and the developer presses Enter. On the first connection Claude Code shows the first 16 characters of the gateway's TLS certificate fingerprint and asks the developer to trust it, so publish the expected fingerprint next to the URL. Print it from the certificate withopenssl x509 -noout -fingerprint -sha256 -in cert.pem | cut -d= -f2 | tr -d : | tr 'A-F' 'a-f'. Claude Code then starts a device flow, the browser opens the gateway's normal SSO sign-in, and the developer signs in. Claude Code receives a session token and starts talking to the gateway. -
The developer sends a prompt. In the Admin UI, open Logs. The request appears under the developer's user and team with the model and cost. Usage attributes the spend the same way.
-
Check the managed settings the way Claude Code does. The route accepts any credential the gateway accepts, so a virtual key works for the check:
curl -i https://gateway.internal.example.com/claude_code_gateway/managed/settings \-H "Authorization: Bearer $SPANWAY_API_KEY"Expected result:
{"uuid": "sha256:4b1f0c9e2a7d3b8f6e5c1a0d9b8e7f6a5c4d3b2a1f0e9d8c7b6a5f4e3d2c1b0a", "checksum": "sha256:4b1f0c9e2a7d3b8f6e5c1a0d9b8e7f6a5c4d3b2a1f0e9d8c7b6a5f4e3d2c1b0a", "settings": {"permissions": {"deny": ["Bash(rm -rf *)"]}, "env": {"CLAUDE_CODE_ENABLE_TELEMETRY": "1"}}}uuidandchecksumare the same value,sha256:followed by the SHA-256 of the settings, so they change only when the settings change. The response carries anETagwith that value in quotes, so Claude Code polls withIf-None-Matchand gets 304 when nothing changed.
The routes below are served with the /claude_code_gateway prefix and all answer 404 until the setting is on, except that the managed settings and telemetry routes first check the session and answer 401 to a caller without a valid one. Claude Code calls every one of them itself, so none of them is in the published API reference, and this table is their reference.
| Route | What happens |
|---|---|
GET /.well-known/oauth-authorization-server | Authorization server metadata for the device flow. |
POST /oauth/device_authorization | Starts an RFC 8628 device flow. The browser leg is the gateway's normal SSO sign-in, and allow_cli_sso_verification_uri_complete pre-fills the user code. |
POST /oauth/token | Exchanges the device code for a session token, the same JWT the CLI uses, accepted by every bearer authenticated route, with a rotating refresh token. |
POST /oauth/revoke | Signs out by revoking the refresh token. |
POST /v1/messages, POST /v1/messages/count_tokens | Inference through the Anthropic Messages API, identical to the top level routes. |
GET /managed/settings | The managed settings object with a uuid, a checksum and the settings. Answers 404 when no managed settings are configured. |
POST /v1/traces, POST /v1/logs, POST /v1/metrics | Accept Claude Code's OTLP telemetry from an authenticated session and discard it, so the client never fails on export. |
Turn gateway sign-in on from the Admin UI
The Skills page lists the registered plugins, adds new ones and deletes them. Enabling or disabling a plugin is done from the publish dialog on the AI hub page or with POST /claude-code/plugins/{plugin_name}/enable and /disable. The Claude Code gateway card at the top of the same page switches the gateway protocol on or off and edits the managed settings object as JSON, so neither needs a config file change or a restart. The card is read-only for view-only admins and when the config file sets the fields, and other gateway workers pick a change up on their next config reload.
To do the same from the API, update the two general settings fields directly.
curl -X POST https://gateway.example.com/config/field/update -H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
-d '{"config_type": "general_settings", "field_name": "enable_claude_code_gateway", "field_value": true}'
curl -X POST https://gateway.example.com/config/field/update -H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
-d '{"config_type": "general_settings", "field_name": "claude_code_gateway_managed_settings", "field_value": {"permissions": {"deny": ["Bash(rm -rf *)"]}}}'
Each answers with the stored field, for example {"config_type": "general_settings", "field_name": "enable_claude_code_gateway", "field_value": true, "message": "Field enable_claude_code_gateway updated"}, and GET /config/list?config_type=general_settings shows the stored values with source set to db.
Errors
Claude Code shows a gateway error as API Error: followed by the status and the gateway's own text. The gateway answers in the Anthropic error shape on both /v1/messages and the gateway sign-in path /claude_code_gateway/v1/messages, key check errors included, and running /login never fixes one, because the text comes from the gateway, not from Anthropic. Errors the gateway sends are also on Logs under the key alias. Rows marked "never reaches the gateway" leave no row there. The client error reference lists every gateway error with the exception each SDK raises.
| What Claude Code shows | Cause | Fix |
|---|---|---|
API Error: 401 with Authentication Error, Invalid proxy server token passed | The key is wrong, deleted or blocked, was copied with a missing character, or Claude Code sent a saved claude.ai login because no key is set. | Copy the key again and run the curl check from step 2, check the Auth token line in /status, or ask the admin for a new key. |
API Error: 401 with Authentication Error, No api key passed in. | The request carried no key at all. | Set ANTHROPIC_AUTH_TOKEN, and run /status to check the Auth token line. |
API Error: 403 with The requested model '<model>' is not available for this API key, or the model name is invalid. | The key may not use that model. Often it is the background tier, a subagent's model or the model a resumed session started on, while the main chat works. | Add the model to the key, or set ANTHROPIC_DEFAULT_HAIKU_MODEL and CLAUDE_CODE_SUBAGENT_MODEL to models the key has. |
API Error: 400 with Invalid model name passed in model=<name> | No deployment on the gateway carries that name. Names are case sensitive. | Pick a name from the /v1/models listing under models in the picker, or fix the model setting. |
API Error: 422 with Budget has been exceeded! Key=<key alias> Current cost: <spend>, Max budget: <max> | The key, its team or its user spent the budget. | Wait for the reset or ask the admin to raise Max Budget (USD). |
API Error: Request rejected (429) after a pause | The key or team is over its rate limit. The gateway text on Logs reads Rate limit exceeded for <scope>: <value>. Limit type: <type>. | Claude Code waits for the retry-after the gateway sends and retries on its own. If it keeps happening, run fewer parallel subagents or ask for a higher RPM limit. |
Every model fails with API Error: 404 or There's an issue with the selected model | The base URL ends in /v1, so Claude Code calls /v1/v1/messages, or it points at a path the gateway does not serve. | Set ANTHROPIC_BASE_URL to the bare root, see steps. |
Unable to connect to API with Connection refused and (ConnectionRefused) or (ECONNREFUSED) | Nothing answers at that address and port. Never reaches the gateway. | Check the address and the VPN, and check the gateway is up with curl https://gateway.example.com/health/liveliness. A leftover ANTHROPIC_BASE_URL pointing at a stopped local gateway causes this too. |
Can't reach the API server with (ENOTFOUND) | The host name does not resolve on this machine. Never reaches the gateway. | Check the spelling, the VPN and the company DNS. |
SSL certificate verification failed (UNABLE_TO_GET_ISSUER_CERT_LOCALLY) or Self-signed certificate detected (SELF_SIGNED_CERT_IN_CHAIN) while curl works | The gateway's certificate comes from a company or private authority that Claude Code's Node runtime does not trust. Never reaches the gateway. | Set NODE_EXTRA_CA_CERTS to the path of the company CA bundle. Never set NODE_TLS_REJECT_UNAUTHORIZED=0. |
API Error: 403 with an HTML page such as 403 Forbidden, and no row on Logs | A web application firewall in front of the gateway blocked the request body, because prompts with code and XML style tags look like an attack to body rules. Never reaches the gateway. | Exempt the gateway's /v1/messages path from request body inspection, for example the CrossSiteScripting_Body rule on AWS WAF. |
API returned an empty or malformed response (HTTP 200) | Something in front of the gateway, such as a sign-in page or a proxy error page, answered instead of the gateway. | Run the curl check and look at what comes back, then fix that hop. |
400 with Extra inputs are not permitted or naming thinking or adaptive | The provider behind the name rejects a field Claude Code sent. | See streaming, tools, images, caching and reasoning. |
400 with No deployment of model '<model>' satisfies the data policy | A data policy restricts code traffic and no deployment of that name meets it. | Use a model name whose deployments meet the policy, see data policy routing. |
A startup warning naming two credential sources, ending in auth may not work as expected | A gateway key and a saved claude.ai login are both active. | Run /logout to keep only the gateway key. |
| Claude Code opens the login screen although the curl check works | Claude Code found no key before its first run setup, for example because the key sits only in a project's settings file. | Put ANTHROPIC_AUTH_TOKEN in ~/.claude/settings.json or export it in the shell. |
ANTHROPIC_API_KEY is set but ignored, with no prompt | The key was declined once, and Claude Code does not ask again. | Turn it on under /config with Use custom API key, or use ANTHROPIC_AUTH_TOKEN. |
Your apiKeyHelper script is failing | The helper command printed nothing, an error, or extra text next to the key. | Run the command yourself and make it print only the key. |
/model misses a gateway model | Model discovery is off, or the model is served through a wildcard route. | Set CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1, or start with claude --model <name>. |
Administrator policy requires a Cloud gateway sign-in | Managed settings force gateway sign-in while a gateway key is also set. | Use one of the two setups, see sign in through the gateway. |
404 Claude Code gateway is not enabled | Gateway sign-in only. The inference, managed settings and telemetry routes answer this while enable_claude_code_gateway is off. The managed settings and telemetry routes answer 401 instead when the caller has no valid session. | Turn the protocol on with the card on the Skills page, which needs no restart, or set it to true in config.yaml and restart. |
404 {"error": "not_found"} | Gateway sign-in only. The /.well-known and /oauth/* sign-in routes answer in the OAuth error shape while enable_claude_code_gateway is off. | Turn the protocol on with the card on the Skills page, or set it to true in config.yaml and restart. |
/login refuses the gateway address | Gateway sign-in only. The gateway host resolves to a public address, or the URL is plain http:// on a host that is not loopback. | Give the gateway an internal DNS name with a private address, serve it over HTTPS, or declare your owned public block in gatewayInternalNetworks. |
/login shows no gateway option | Gateway sign-in only. forceLoginMethod and forceLoginGatewayUrl are not set on that machine. | Add both keys to the managed settings file or to ~/.claude/settings.json. |
404 on GET /managed/settings | Gateway sign-in only. No claude_code_gateway_managed_settings are configured. Claude Code treats this as no managed settings. | Add the settings block if you want them. |
Sign-in page never opens during /login | Gateway sign-in only. SSO is not configured on the gateway, so there is no browser leg. | Configure SSO, see SSO. |
| 401 after a while on a signed-in session | Gateway sign-in only. The session token expired and the refresh token was revoked, or the user was deactivated. | Run /login again. |
| Requests attributed to no team | Gateway sign-in only. The SSO user has no team. | Add the user to a team on Teams, or set a default team in SSO settings. |
Logs
| Level | Line | Meaning | Action needed |
|---|---|---|---|
| WARNING | Claude Code gateway login session is malformed: ... | A /oauth/token call carried a device code whose stored login session cannot be read, and Claude Code got 400 invalid_grant. | None for one occurrence, the developer signs in again. Many of them point at a broken cache or a client sending forged codes. |
Requests that Claude Code sends through the gateway are logged like any other request on Logs, see expected result.
Troubleshooting
- Run
/statusin Claude Code. TheAnthropic base URLline must show the gateway root and theAuth tokenorAPI keyline must name the setting you used. A missing line means the setting never reached this session, often because it was exported in another terminal or sits in the wrong file. - Run the curl check from step 2 in the same terminal. If curl works and Claude Code does not, the difference is in Claude Code's own settings, its certificate store or its model name, not in the gateway.
- Start
claude --debug. The debug log at~/.claude/debug/<session-id>.txtshows each request and its status, and the[gatewayDiscovery]lines show whether the model listing worked. The file name is the session id. - On the gateway, open Logs, filter Key Alias by the developer's key, or Session ID by that session id, and open the failing row. The drawer shows the status, the gateway's message, the deployment the router picked and the provider's answer. The
x-spanway-*headers from expected result repeat the routing on the client side. - No row on Logs means the request never reached the gateway. Work through the connection, TLS and firewall rows in errors, and the connect any client checks.
- For a whole session at once,
spanwayctl debug claude --session-id <id>writes a report of that session's requests, answers, spend and errors, see the CLI reference. On a test gateway,--detailed_debuglogs every request with the key check and the routing decision.
Rotate or remove the key
Rotate a developer's key when it may have leaked, when the developer changes team, or on a fixed schedule.
-
In Virtual Keys, open the key and click Regenerate Key. Set a Grace Period such as
24hso the old key keeps working while the developer switches, and copy the new key. From the API this is the call below. Both need an Enterprise license. Without one, create a new key with the same settings, switch the developer to it and delete the old one.curl -X POST https://gateway.example.com/key/sk-old-key/regenerate \-H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \-d '{"grace_period": "24h"}' -
Put the new key where the old one was:
env.ANTHROPIC_AUTH_TOKENin~/.claude/settings.json,claudeCode.environmentVariablesin VS Code, the repository secret for GitHub Actions, or the vault entry anapiKeyHelperreads. Withspanwayctl, runspanwayctl reconfigure claude --api-key <new key>. -
Run
/statusand send a prompt. The new key's alias shows on Logs.
To take Claude Code off the gateway, remove ANTHROPIC_BASE_URL and the key from the settings file and the shell profile, or run spanwayctl unconfigure claude. To cut a developer off at once, click Block Key in the key's actions menu, which can be undone with Unblock Key, or delete the key. Blocking stops every Claude Code surface that uses that key on its next request.
Related
- Coding agent setup for
spanwayctl configure claude, which writes these settings for you. - Make a key for a tool for every key field, rotation and per tool usage.
- Connect any client for the base URL rule, key headers and connection errors.
- Client error reference for every gateway error and the SDK exception it maps to.
- Troubleshooting client tools for symptom first notes and each client's debug switch.
- Claude Desktop for the desktop app's model gateway and connectors.
- MCP clients for adding the gateway's MCP servers to Claude Code.
- Claude Code plugin marketplace for hosting plugins Claude Code installs.
- Anthropic Messages for the inference route Claude Code uses.
- Routing headers for every
x-spanway-*routing header.