# Claude Code Third-Party API Setup: TokLab, Codex & OpenCode

By TokLab · Published 2026-11-23 · Updated 2026-11-23

Claude Code is a strong terminal coding agent, but running it exclusively on a fixed consumer plan or full list API rates gets awkward fast. Heavy multi-file refactors replay your system prompt, tool schemas, and repository context on every turn, multiplying token volume by ten to fifty times compared to normal chat. A single afternoon of iterative debugging can burn through a rolling subscription window or stack up an unexpected bill.

What many developers overlook is that Claude Code is a thin client over the Anthropic Messages protocol. It does not hard-code Anthropic's production host. By setting a few environment variables (or dropping them into `~/.claude/settings.json`), you can route Claude Code through TokLab's Anthropic-compatible endpoint, pay per token from one prepaid balance that never expires, and share that exact same key with Codex CLI and OpenCode.

This guide walks through the full configuration, explains why the base URL path differs between Anthropic and OpenAI clients, shows how to keep Claude Code's background aliases working, and lists the exact fixes for the auth and HTTP errors that trip up most first-time setups.

## How Claude Code resolves its backend

Before editing any config file, it helps to know what Claude Code sends over the wire. On startup, the CLI checks your shell environment and `~/.claude/settings.json` for a base URL and credentials. When `ANTHROPIC_BASE_URL` is set, Claude Code redirects every `POST /v1/messages` request to that host instead of `https://api.anthropic.com`.

Three protocol details cause almost every setup mistake:

1. **No `/v1` suffix on `ANTHROPIC_BASE_URL`.** Claude Code appends `/v1/messages` automatically. If you set `ANTHROPIC_BASE_URL=https://api.toklab.ai/v1`, the client requests `/v1/v1/messages` and every turn fails with HTTP `404`.
2. **OpenAI-compatible tools do need `/v1`.** Codex CLI, OpenCode, and OpenAI SDK scripts expect `https://api.toklab.ai/v1` because they append `/responses` or `/chat/completions`. Same host, different path rule.
3. **One auth variable, not two.** Claude Code supports both `ANTHROPIC_AUTH_TOKEN` (sent as `Authorization: Bearer <key>`) and `ANTHROPIC_API_KEY` (sent as `x-api-key: <key>`). TokLab accepts either header on `POST https://api.toklab.ai/v1/messages`, but setting both variables at the same time in your shell or settings file can cause header conflicts and `401` errors. Pick one and unset the other.

Once those three rules are clear, the rest of the setup takes about five minutes.

## Step-by-step Claude Code setup on TokLab

### Step 1: Install Claude Code and generate a TokLab key

If Claude Code is not installed yet, run the official installer for your platform and verify it is on your `PATH`:

```bash
# macOS / Linux
curl -fsSL https://claude.ai/install.sh | bash
claude --version
```

On Windows PowerShell, use `irm https://claude.ai/install.ps1 | iex`. Do not sign in with a consumer Anthropic account if you plan to bill exclusively to TokLab; you will authenticate with your TokLab key in the next step.

Next, sign in to TokLab, add credit on the [Credits](https://toklab.ai/billing) page (balances do not expire and failed requests are not charged), and create a dedicated API key for your local coding tools. Using a separate key for local agents makes it easy to inspect spend in your [LLM logs](https://toklab.ai/usage) or revoke the key without touching production services.

### Step 2: Configure `~/.claude/settings.json`

The cleanest way to wire Claude Code to TokLab is `~/.claude/settings.json` (on Windows, `%USERPROFILE%\.claude\settings.json`). Putting the variables inside the `env` block isolates them to Claude Code instead of leaking `ANTHROPIC_BASE_URL` into unrelated Python or Node scripts in your shell.

```json
{
  "env": {
    "ANTHROPIC_BASE_URL": "https://api.toklab.ai",
    "ANTHROPIC_AUTH_TOKEN": "YOUR_TOKLAB_API_KEY",
    "ANTHROPIC_MODEL": "claude-opus-5-5",
    "ANTHROPIC_DEFAULT_OPUS_MODEL": "claude-opus-5-5",
    "ANTHROPIC_DEFAULT_SONNET_MODEL": "claude-sonnet-5-5",
    "ANTHROPIC_DEFAULT_HAIKU_MODEL": "claude-haiku-5-5"
  }
}
```

If you prefer shell exports (useful when you only want TokLab active in one terminal tab), export the same variables in bash or zsh:

```bash
export ANTHROPIC_BASE_URL="https://api.toklab.ai"
export ANTHROPIC_AUTH_TOKEN="YOUR_TOKLAB_API_KEY"
export ANTHROPIC_DEFAULT_OPUS_MODEL="claude-opus-5-5"
export ANTHROPIC_DEFAULT_SONNET_MODEL="claude-sonnet-5-5"
export ANTHROPIC_DEFAULT_HAIKU_MODEL="claude-haiku-5-5"

claude --model claude-opus-5-5
```

Notice the three `ANTHROPIC_DEFAULT_*_MODEL` entries. Even when you start a session with `--model claude-opus-5-5`, Claude Code dispatches smaller background jobs (such as conversation compaction, file summaries, and lightweight subagents) to its internal `haiku` and `sonnet` aliases. If those aliases point at an outdated or unavailable upstream snapshot string, background tasks silently error out mid-session. Mapping all three aliases to live TokLab IDs prevents that failure mode completely.

### Step 3: Verify the endpoint before opening a large repo

Before launching Claude Code inside a production repository, send a minimal `curl` request against TokLab's Messages endpoint. This separates network or key problems from Claude Code client issues in five seconds:

```bash
curl https://api.toklab.ai/v1/messages \
  -H "Authorization: Bearer $ANTHROPIC_AUTH_TOKEN" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-haiku-5-5",
    "max_tokens": 32,
    "messages": [{"role": "user", "content": "Reply with OK."}]
  }'
```

When that returns a valid JSON message object, start `claude` in a scratch directory and ask it to inspect a single file. On the first launch, Claude Code asks you to confirm that you want to use the custom API key instead of a Claude subscription. Approve it once, then check your TokLab [LLM logs](https://toklab.ai/usage) to confirm the request landed on the expected model ID and token count.

## Choosing the right TokLab model for each coding job

Because TokLab bills by tokens rather than locking you into one subscription tier, you can match the model to the difficulty of the session instead of paying flagship rates for every rename and test stub. All current rates are published in the [model catalog](https://toklab.ai/models) and [pricing page](https://toklab.ai/pricing).

| Model ID            | Protocol on TokLab         | TokLab Input / Output (per 1M) | Best coding role                                             |
| ------------------- | -------------------------- | -----------------------------: | ------------------------------------------------------------ |
| `claude-haiku-5-5`  | Anthropic Messages, OpenAI |        $0.035 / $0.175 (≤100K) | Background summaries, fast triage, high-volume subagents     |
| `claude-sonnet-5-5` | Anthropic Messages, OpenAI |                  $0.70 / $3.50 | Everyday feature edits, PR reviews, balanced speed and cost  |
| `claude-opus-5-5`   | Anthropic Messages, OpenAI |                  $1.40 / $7.00 | Primary interactive coding loop, multi-file debugging        |
| `claude-fable-5-2`  | Anthropic Messages, OpenAI |                 $2.80 / $14.00 | Long-horizon refactors, deep architecture work, hard bugs    |
| `gpt-6.2-sol`       | OpenAI Responses, Chat     |          $0.20 / $1.00 (≤272K) | Fast default in Codex CLI and OpenCode                       |
| `gpt-6.2-astra`     | OpenAI Responses, Chat     |          $0.80 / $4.00 (≤272K) | Escalation pass in Codex CLI for ambiguous cross-module bugs |

In practice, a strong default inside Claude Code is `claude-opus-5-5` for your main loop with `claude-haiku-5-5` bound to the Haiku alias for cheap background calls. When you hit a gnarly concurrency bug or a multi-package migration that Opus cannot crack cleanly on the first attempt, switch just that session with `claude --model claude-fable-5-2`, with no config rewrite, no new key, and no separate invoice.

## Using the same TokLab key with Codex CLI and OpenCode

Most engineers do not stop at one CLI agent. You might run Claude Code for large TypeScript refactors, Codex CLI for [GPT-6.2 Sol](https://toklab.ai/models/gpt-6-2-sol) and [GPT-6.2 Astra](https://toklab.ai/models/gpt-6-2-astra) reviews, and OpenCode when you want a fast terminal switcher across providers. Pointing all three at TokLab consolidates your keys, logs, and spending cap into one balance.

### Codex CLI (`~/.codex/config.toml`)

Add a `toklab` provider block to your user-level `~/.codex/config.toml`. Note that Codex CLI ignores `model_provider` overrides placed inside a project-level `.codex/config.toml`, so always put this in your home directory:

```toml
model = "gpt-6.2-sol"
model_provider = "toklab"

[model_providers.toklab]
name = "TokLab"
base_url = "https://api.toklab.ai/v1"
env_key = "TOKLAB_API_KEY"
wire_api = "responses"
```

Export `TOKLAB_API_KEY` in your shell profile, then test with `codex exec "Reply with OK."`. When a task needs heavier reasoning, override the model for a single run with `codex -m gpt-6.2-astra` without changing your default. Full reference details live in TokLab's [Coding Agents documentation](https://toklab.ai/docs/api/coding-agents).

### OpenCode (`OPENAI_BASE_URL`)

OpenCode speaks the standard OpenAI-compatible API format, so you can route it to TokLab with two environment variables or a custom provider entry in `opencode.json`:

```bash
export OPENAI_BASE_URL="https://api.toklab.ai/v1"
export OPENAI_API_KEY="YOUR_TOKLAB_API_KEY"
```

Because TokLab exposes both the Claude 5.x family and [GPT-6.2 Sol](https://toklab.ai/models/gpt-6-2-sol) / [GPT-6.2 Astra](https://toklab.ai/models/gpt-6-2-astra) on `https://api.toklab.ai/v1/chat/completions` and `/v1/responses`, OpenCode lets you compare Claude and GPT-6.2 side by side inside the same terminal session against the exact same repository state.

## Wiring MCP servers alongside a third-party API

A frequent worry before switching `ANTHROPIC_BASE_URL` is whether Model Context Protocol (MCP) servers will break. They do not. Claude Code runs MCP servers locally (over `stdio`) or over HTTPS directly from your machine, then passes the discovered tool definitions inside the standard `tools` array of each Messages request. Because TokLab forwards the official Anthropic Messages `tools` and `tool_result` contract transparently, local MCP servers for Postgres, GitHub, Playwright, or your internal docs continue working without changes.

There are two practical MCP tips worth knowing when running on a third-party gateway:

1. **Watch tool-schema token bloat.** Every enabled MCP server injects its full JSON schema into the system prefix on every turn. Enabling six servers you are not using on the current task can add 10,000+ input tokens per turn. Keep heavy MCP servers scoped to project-level `.mcp.json` files instead of enabling them globally.
2. **Add TokLab's MCP server when you need media inside coding workflows.** If you want Claude Code or Codex to generate UI mockups, hero artwork, or test video clips using [GPT Image 2.6](https://toklab.ai/models/gpt-image-2-6) or [Kling Image 4.0](https://toklab.ai/models/kling-image-4-0) directly from the terminal, wire up the [TokLab MCP server](https://toklab.ai/docs/api/mcp) using the same `TOKLAB_API_KEY`.

## Troubleshooting common 401, 404, 400, and 429 errors

Almost every failed Claude Code or Codex setup traces back to one of five concrete issues. Start Claude Code with `claude --debug` to see the exact request URL, headers, and response body.

| Symptom                           | Root cause                                                                                             | Fix                                                                                                                                                                                         |
| --------------------------------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `401 Unauthorized`                | Wrong key, expired key, or both `ANTHROPIC_API_KEY` and `ANTHROPIC_AUTH_TOKEN` are set simultaneously. | Set only one of the two auth variables, verify the raw key has no stray spaces or `Bearer ` prefix when using `ANTHROPIC_AUTH_TOKEN`, and test with `curl`.                                 |
| `404 Not Found` on every turn     | Trailing `/v1` or `/v1/messages` added to `ANTHROPIC_BASE_URL`, or missing `/v1` in Codex/OpenCode.    | Use `https://api.toklab.ai` for Claude Code and `https://api.toklab.ai/v1` for Codex CLI and OpenCode.                                                                                      |
| `400 Bad Request`                 | Invalid model ID, unsupported experimental beta header, or legacy sampling parameter.                  | Confirm the model ID exists in [TokLab Models](https://toklab.ai/models). If Claude Code sends an experimental beta header your route rejects, add `"CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS": "1"` to `env`. |
| Prompted to log in with Anthropic | Shell or editor terminal did not reload updated environment variables.                                 | Fully quit and reopen your terminal (and VS Code or Cursor if using their integrated terminals), or move the config into `~/.claude/settings.json`.                                         |
| `429 Too Many Requests`           | Too many concurrent sessions or parallel subagents hitting the gateway at once.                        | Reduce parallel subagent fan-out, wait for the `Retry-After` header, and keep background aliases on `claude-haiku-5-5`.                                                                     |

## Security hygiene and switching back

Whenever you store an API key in `~/.claude/settings.json`, remember that file spends real balance. Never commit `.claude/settings.json` inside a repository. If you use a project-scoped settings file for team model defaults, put only the non-secret `ANTHROPIC_MODEL` fields in git and keep `ANTHROPIC_AUTH_TOKEN` in your user-level config or a secrets manager.

Switching back to a native Anthropic subscription or direct API key takes ten seconds. Remove or rename the `env` block in `~/.claude/settings.json` (or run `unset ANTHROPIC_BASE_URL ANTHROPIC_AUTH_TOKEN` in your shell) and restart `claude`. Many developers keep two tiny shell functions (`claude-toklab` and `claude-direct`) so they can jump between pay-as-you-go TokLab routing and a native plan without ever editing JSON by hand.

## Practical edge cases: headless CI, cache resets, and IDE terminals

Once the basic interactive loop works, three real-world workflow details separate a smooth setup from a noisy one:

* **Headless and CI usage.** You can run Claude Code non-interactively in GitHub Actions or local scripts with `claude -p "Summarize the breaking changes in this diff" --output-format json` while pointing `ANTHROPIC_BASE_URL` at TokLab. Always pass `--max-turns` in automated pipelines so a flaky test failure cannot spin an unbounded loop, and use a dedicated CI API key with a tight budget cap.
* **Mid-session `/model` switches reset prompt cache warmth.** Claude Code lets you jump from `claude-opus-5-5` to `claude-fable-5-2` inside an active thread, which is convenient when a bug turns out to be trickier than expected. Keep in mind that each model maintains its own prompt cache, so switching models triggers a cold cache write on the next turn. Finish the current subtask before escalating rather than bouncing back and forth every two messages.
* **IDE integrated terminals inherit stale environments.** On macOS and Windows, VS Code and Cursor cache the environment snapshot from the moment the editor launched. Editing `~/.zshrc` or Windows User variables will not update an already-open IDE terminal. Either store your TokLab config in `~/.claude/settings.json` (which Claude Code reads fresh on every launch regardless of parent shell state) or fully quit and reopen the editor before debugging auth failures.

## Sources

* [TokLab Coding Agents Documentation](https://toklab.ai/docs/api/coding-agents) — Official Claude Code and Codex CLI configuration for `api.toklab.ai`.
* [TokLab MCP Server Documentation](https://toklab.ai/docs/api/mcp) — Connecting coding agents to TokLab image and video tools.
* [TokLab Model Catalog](https://toklab.ai/models) and [Pricing](https://toklab.ai/pricing) — Live model IDs and per-million-token rates for Claude 5.x and GPT-6.2.
* [Claude Code Settings & Environment Variables](https://docs.anthropic.com/en/docs/claude-code/settings) — Official reference for `ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN`, and model alias overrides.
