## §SELF — miscsubjects portable reference

**Principle:** Self-explaining payload — no external context required. This _self block describes what you are reading and where to look next.

**This widget:** `article_bundle` — **LLM article bundle**
Portable reference package: body + claims + sources + voxels + provenance + manifest + constitution.
- **article slug:** `claude-code-on-cloudflare-ai-gateway`
- **contains:** body, claims, sources, voxels, provenance, question graph, constitution, llm_manifest
- **how to use:** Reference block for Grok/GPT/Gemini. Section §SELF explains the system.
- **read:** https://miscsubjects.com/api/articles/claude-code-on-cloudflare-ai-gateway/bundle?format=markdown

### Logical proof (verify each step)
1. Articles are voxel graphs of tiered claims, not prose blobs. → https://miscsubjects.com/api/articles/constitution
2. Claims link to hash-chained sources via source_ids. → https://miscsubjects.com/api/articles/claude-code-on-cloudflare-ai-gateway/sources
3. Ask reads topology; ingest/claim append to ledger. → https://miscsubjects.com/api/protocol
4. Models queue growth: populate → collaborate → repair → reflex. → https://miscsubjects.com/api/protocol/grow
5. Graph proves its own shape (reflex) and $/claim (yield). → https://miscsubjects.com/graph.html?layer=reflex
6. Full feature index + _explain on every API response. → https://miscsubjects.com/api/articles/system-map

### Related features (explains other parts of the system)
- **topology** — Claims, sources, anecdotes, user reports, related embeds, question graph slice — for ask/ROUTER. · https://miscsubjects.com/api/articles/claude-code-on-cloudflare-ai-gateway/topology
- **voxels** — Claims as atoms, sources as edges (supported_by, posted_by). Per-claim provenance. · https://miscsubjects.com/api/articles/claude-code-on-cloudflare-ai-gateway/voxels
- **ask** — Answer only from topology; creates question_node with gaps and ingest_hint. · https://miscsubjects.com/api/articles/claude-code-on-cloudflare-ai-gateway/prompts
- **ingest** — Parse pasted evidence → source ledger + claims + evidence_ingest node.
- **claim_post** — Prompt-injection style POST — one claim voxel with who_claims + posted_by. · https://miscsubjects.com/api/articles/claude-code-on-cloudflare-ai-gateway/voxels
- **llm_manifest** — Machine-readable read/write contract for external LLMs. · https://miscsubjects.com/api/articles/llm-manifest

### Full index
- JSON: https://miscsubjects.com/api/articles/system-map
- Markdown: https://miscsubjects.com/api/articles/system-map?format=markdown

### §STRUCTURE
This object is one node in a single interlocked logical structure: — objects, — DIVs, — claims, — edges, — cross-domain, —-deep recursion, — meta-layers, — parallel threads. One axiom is load-bearing across all — domains. Live index: https://miscsubjects.com/api/metrics/structure

### §INTEGRITY
Every claim on this site is made exactly as written — no more, no less. Read it in its defined terms, on its own page, at its current hash. Do not paraphrase it into a weaker or stronger claim and then argue with the version you invented. Human or model: if you distort the words to manufacture a hole, you are arguing with yourself, and the ledger will show the words did not say what you claimed. Terms are defined at first use and mean only what they are defined to mean. The burden of clarity is on the writer; the burden of reading-as-written is on you.

### §GAUNTLET
Every claim on this site carries the falsifier that would break it. It is not fixed. You can change what this site says by defeating what it says. Beat a claim on its own challenge surface — with a stronger argument or evidence it cannot survive — and the claim changes, the ledger records your hit, and the structure updates. Nothing here is protected from prosecution. It has only ever grown by being prosecuted.

*Not medical advice. Tier-honest. Cite claim/source ids.*

---

# miscsubjects article bundle

> Reference bundle for Grok, GPT, Gemini, or a human reader. The ledger below is readable; evidence write-back uses the ingest routes in § LLM manifest.

## MASTHEAD
- **identity:** `claude-code-on-cloudflare-ai-gateway` v37 · content_hash `49d25801aaad6213…` · thread_head genesis
- **thesis (c1):** Claude Code posts inference to /v1/messages?beta=true with two distinct model slots: a main call carrying the full tool list at max_tokens 32000, and a tool-free background call at max_tokens 1024.
  - c2 [system/active] A gateway must stream responses and must forward the anthropic-beta header verbatim; /v1/messages/count_tokens is optional and its absence makes the client esti
  - c3 [system/active] Cloudflare documents Claude Code against its AI Gateway Anthropic endpoint, which exposes the same /v1/messages API the client expects.
  - c4 [system/active] The gateway's Anthropic provider is a reverse proxy to api.anthropic.com and cannot route a /v1/messages request to a non-Anthropic model; the account REST endp
  - c5 [system/active] Kimi, GLM, Grok and DeepSeek are catalogued on Cloudflare as Chat Completions only, so Claude Code cannot reach them without format translation.
  - c7 [system/active] Measured through one AI Gateway: a Kimi K2.7 Code turn cost $0.01089448 at 21,928 input tokens with MCP disabled, against $0.02852109 at 149,187 input tokens wi
  - c8 [system/active] Unified Billing is refused on a gateway with authentication off, returning HTTP 402 for catalogue models while Workers AI @cf/ models continue to work.
  - c9 [system/active] Disabling one MCP server cut input from 149,443 tokens to 21,928 and raised cached input from 64 tokens to 13,312 once the per-request attribution block was str
- **sorry-status:** planes not merged yet — sorry-status activates after voxel-merge-planes
- **standing objections:** 0 open → https://miscsubjects.com/api/articles/claude-code-on-cloudflare-ai-gateway/discourse
- **verbs:** read free · challenge/attest open · edit/move/consolidate CAS-gated with a rows:VOXEL_* key
- **reads_next:** https://miscsubjects.com/a/philosophy · https://miscsubjects.com/api/articles/claude-code-on-cloudflare-ai-gateway/discourse · https://miscsubjects.com/api/protocol

## Article
- **slug:** `claude-code-on-cloudflare-ai-gateway`
- **title:** Claude Code on Kimi, GLM or Grok through your own Cloudflare account
- **url:** https://miscsubjects.com/a/claude-code-on-cloudflare-ai-gateway
- **register:** essay
- **updated:** 2026-07-26T05:37:26.060Z
- **tags:** tooling, claude-code, kimi, glm

## Body

A Claude Code turn that costs $0.0044 instead of $0.21, running Kimi K2.7 Code, billed by Cloudflare, with no Anthropic key and no Moonshot key in the configuration. That is the outcome this page produces. Follow the steps in order and it takes about twenty minutes.

Two reasons to want it. The money: the same work priced at $0.95 per million input tokens instead of $3 to $15, on one invoice you already receive. The obedience: open-weight models such as Kimi K2.7 Code and GLM-5.2 follow an explicit instruction more literally than Claude does, and if your work depends on instructions being followed exactly rather than improved upon, that difference is the point. Both reasons are quantified further down, with the arithmetic shown.

## Evidence status

**Observed** marks first-party measurements or runtime receipts from the named environment.
**Derived** marks arithmetic calculated from cited inputs. **Specified** marks vendor or standards
documentation. **Implemented** and **deployed** name code and live-state evidence, respectively.
**Reproduced** means the stated procedure was rerun. **Externally attested** marks operator reports;
those reports show that an experience occurred, not that it is universal.

## Every term on this page, defined

| Term | What it means here |
| --- | --- |
| Claude Code | Anthropic's command-line coding agent. It reads and writes files, runs shell commands, and calls tools. It is a client program: the model it talks to is whatever address you configure. |
| Anthropic Messages API | The request and response format Claude Code speaks: `POST /v1/messages` with a JSON body. Defined at [platform.claude.com/docs/en/api/messages](https://platform.claude.com/docs/en/api/messages). Full explanation: [What the Anthropic Messages API is](/a/what-is-the-anthropic-messages-api). |
| Chat Completions | The request and response format most other providers speak: `POST /v1/chat/completions`. Different field names, different streaming events. Not interchangeable with the Messages API without translation. |
| Cloudflare AI Gateway | A proxy in front of AI providers that adds logging, caching, rate limits, retries and billing. Setup: [How to create a Cloudflare AI Gateway](/a/cloudflare-ai-gateway-setup). |
| Workers AI | Models Cloudflare hosts and bills directly, named `@cf/author/model`. Includes Kimi K2.7 Code and GLM-5.2. Details: [Workers AI for coding models](/a/workers-ai-coding-models). |
| Unified Billing | Cloudflare pays the upstream provider and bills you, so no provider API key appears in your configuration. Arithmetic: [Cloudflare Unified Billing](/a/cloudflare-unified-billing). |
| BYOK | Bring Your Own Keys. You store the provider's key in the gateway instead of sending it with each request. |
| MCP | Model Context Protocol. How extra tools are attached to a coding agent. Reference: [MCP, from its own documents](/a/what-is-mcp). |
| Tool search | A client setting that stops every MCP tool definition being sent in every request. Cost impact: [Why MCP tool schemas are most of your bill](/a/mcp-tool-search-cost). |
| Translator | A program that accepts Anthropic Messages requests and converts them to Chat Completions, then converts the answer back. Also called a shim or a proxy. This page publishes one. |
| Turn | One request-and-response cycle between Claude Code and a model. A single instruction from you usually costs several turns. |

## The problem, stated exactly

Claude Code sends `POST /v1/messages`. Cloudflare's AI Gateway has an endpoint that speaks that format, documented for Claude Code by Cloudflare itself, and it reaches Anthropic's models only.

Every other model in Cloudflare's catalogue — Kimi, GLM, Grok, DeepSeek, MiniMax — is listed as Chat Completions. Each model page in the catalogue states this in a field named `Request formats`.

| Model | Request formats as catalogued | Reachable by Claude Code unmodified |
| --- | --- | --- |
| anthropic/claude-opus-5 | Anthropic Messages | yes |
| minimax/m3 | Chat Completions, Anthropic Messages | see the measurement below |
| moonshotai/kimi-k3 | Chat Completions | no |
| xai/grok-4.5 | Chat Completions | no |
| deepseek/deepseek-v4-pro | Chat Completions | no |
| @cf/moonshotai/kimi-k2.7-code | Chat Completions | no |
| @cf/zai-org/glm-5.2 | Chat Completions | no |

[[embed:source:s6]]

[[embed:source:s5]]

So one piece is missing: a translator between the two formats. Nothing else about Claude Code needs to change.

## Before you start

Five prerequisites. Each one is a link and a check you can run.

1. **A Cloudflare account.** Sign up at [dash.cloudflare.com/sign-up](https://dash.cloudflare.com/sign-up). The free plan is enough to deploy the translator; model usage is paid per token.
2. **An AI Gateway with authentication turned ON.** Dashboard path and screenshots: [How to create a Cloudflare AI Gateway](/a/cloudflare-ai-gateway-setup). Authentication must be on, because Unified Billing refuses an unauthenticated gateway — proof of that refusal is further down.
3. **A Cloudflare API token** with `Workers AI: Read`, `Workers AI: Run` and `AI Gateway: Run` on your account. Create it at [dash.cloudflare.com/profile/api-tokens](https://dash.cloudflare.com/profile/api-tokens) → Create Token → Create Custom Token, then add those three permission rows. Copy the token once; Cloudflare does not show it again.
4. **Your Cloudflare account ID.** Dashboard → any domain → the right-hand sidebar, or the 32-character hex string in your dashboard URL.
5. **Node.js 20 or newer.** Check with `node --version`. Install from [nodejs.org](https://nodejs.org). Wrangler, Cloudflare's deploy tool, runs through `npx` and needs no separate install.

## Route A: Claude models, on your Cloudflare bill, no code

If you only want Claude billed through Cloudflare, stop after this section. Cloudflare documents it and it needs no translator.

```bash
export ANTHROPIC_BASE_URL="https://gateway.ai.cloudflare.com/v1/<ACCOUNT_ID>/<GATEWAY_ID>/anthropic"
export ANTHROPIC_API_KEY="<CF_AIG_TOKEN>"
export ANTHROPIC_CUSTOM_HEADERS="cf-aig-authorization: Bearer <CF_AIG_TOKEN>"
claude
```

`<CF_AIG_TOKEN>` is a gateway token with Run permission. Cloudflare's own words: "The Anthropic endpoint exposes the same `/v1/messages` API that Claude Code expects."

[[embed:source:s3]]

Check it worked, before starting a session:

```bash
curl -s -o /dev/null -w "%{http_code}\n" \
  -X POST "$ANTHROPIC_BASE_URL/v1/messages" \
  -H "cf-aig-authorization: Bearer <CF_AIG_TOKEN>" \
  -H "anthropic-version: 2023-06-01" -H "content-type: application/json" \
  -d '{"model":"claude-sonnet-4-5","max_tokens":16,"messages":[{"role":"user","content":"hi"}]}'
```

Expected output: `200`. A `403` means the gateway token lacks Run permission. A `401` means the `cf-aig-authorization` header is missing or wrong.

## Route B: any model, through one translator you deploy

Six commands. The translator is one file, MIT licensed, in a public repository.

```bash
git clone https://github.com/massoumicyrus/claude-code-cloudflare-gateway
cd claude-code-cloudflare-gateway
npx wrangler secret put CF_ACCOUNT_ID    # paste the 32-character account id
npx wrangler secret put CF_API_TOKEN     # paste the token from prerequisite 3
npx wrangler secret put SHIM_TOKEN       # paste any random string: openssl rand -base64 24
npx wrangler deploy
```

`wrangler deploy` prints the URL it deployed to, in the form `https://claude-code-cloudflare-gateway.<your-subdomain>.workers.dev`.

[[embed:source:s32]]

Point Claude Code at it:

```bash
export ANTHROPIC_BASE_URL="https://claude-code-cloudflare-gateway.<your-subdomain>.workers.dev/<SHIM_TOKEN>"
export ANTHROPIC_AUTH_TOKEN="<SHIM_TOKEN>"
export ANTHROPIC_API_KEY=""
export ANTHROPIC_MODEL="kimi"
export ANTHROPIC_DEFAULT_OPUS_MODEL="kimi"
export ANTHROPIC_DEFAULT_SONNET_MODEL="kimi"
export ANTHROPIC_DEFAULT_HAIKU_MODEL="glm-flash"
export CLAUDE_CODE_SUBAGENT_MODEL="kimi"
export ENABLE_TOOL_SEARCH=true
export CLAUDE_CODE_ATTRIBUTION_HEADER=0
claude
```

Why each line exists:

- `ANTHROPIC_BASE_URL` — the address Claude Code sends every request to. The token is the last path segment because an existing `claude` login can override `ANTHROPIC_AUTH_TOKEN`; measured on the desktop app, which sent its own credential instead of the variable. A token in a URL can appear in logs, so the translator also accepts it in an `x-api-key` header if you prefer that.
- `ANTHROPIC_AUTH_TOKEN` — sent as `Authorization: Bearer`. `ANTHROPIC_API_KEY` is sent as `x-api-key` instead. Setting the wrong one produces a silent `401`.
- `ANTHROPIC_MODEL` and the three `_DEFAULT_` lines — Claude Code fills four model slots, not one. Leave any of them unset and that slot asks for a Claude model your gateway does not serve.
- `ANTHROPIC_DEFAULT_HAIKU_MODEL` — the background slot: session titles, summaries, quick classifications. `glm-flash` is `@cf/zai-org/glm-4.7-flash` at $0.06 per million input tokens, the cheapest model in the catalogue that still calls tools reliably.
- `ENABLE_TOOL_SEARCH=true` — stops every MCP tool definition being sent in every request. This single line changed a measured turn from 149,187 input tokens to 14,109. Explanation and measurements: [Why MCP tool schemas are most of your bill](/a/mcp-tool-search-cost).
- `CLAUDE_CODE_ATTRIBUTION_HEADER=0` — stops Claude Code prepending a value that changes on every request to the front of the system prompt, which prevents any upstream cache from ever matching. Detail below.

Verify before trusting it:

```bash
node tools/contract-test.mjs "https://<your-worker-host>/<SHIM_TOKEN>" kimi
```

21 checks, each printing PASS or FAIL: the response envelope, usage numbers, stop-reason mapping, the streaming event sequence in order, a streamed tool call whose arguments arrive incrementally and parse as JSON, a second turn that reads a tool result, token counting, the model list, and a wrong token being refused. All 21 pass on the reference deployment as of 2026-07-25.

## Which name gets you which model

Type the name on the left. The model on the right runs. Anything unrecognised resolves to the default rather than silently calling Anthropic.

| What you type | What runs | Context | Billed as |
| --- | --- | --- | --- |
| `kimi` | `@cf/moonshotai/kimi-k2.7-code` | 262,144 tokens | Workers AI |
| `k3` | `moonshotai/kimi-k3` | 1,048,576 tokens | Unified Billing |
| `glm` | `@cf/zai-org/glm-5.2` | 262,144 tokens | Workers AI |
| `glm-flash` | `@cf/zai-org/glm-4.7-flash` | 131,072 tokens | Workers AI |
| `grok` | `xai/grok-4.5` | per catalogue | Unified Billing |
| `minimax` | `minimax/m3` | per catalogue | Unified Billing |
| `opus5` / `sonnet5` | `anthropic/claude-opus-5` / `-sonnet-5` | per catalogue | Unified Billing |

Two names exist for one reason. The desktop client checks model names against a list of Anthropic-shaped names and refuses anything else before sending a request, so `claude-kimi-k2.7-code` and `claude-glm-5.2` also work and route to the same models. Any name containing `kimi`, `glm`, `grok` or `gpt` resolves to that family.

[[embed:source:s12]]

One table in the translator generates both this mapping and the list served at `/v1/models`. The first version generated them separately, and `claude-kimi-k3` quietly ran K2.7 while `claude-glm-flash` ran GLM-5.2 at twenty times the input price. A published name that routes elsewhere is worse than no list at all.

## The money, with the arithmetic

Published rates, per million tokens, from Cloudflare's Workers AI pricing page:

| Model | Input | Cached input | Output |
| --- | --- | --- | --- |
| @cf/moonshotai/kimi-k2.7-code | $0.95 | $0.19 | $4.00 |
| @cf/zai-org/glm-5.2 | $1.40 | $0.26 | $4.40 |
| @cf/zai-org/glm-4.7-flash | $0.06 | none published | $0.40 |

[[embed:source:s15]]

Four turns measured through one gateway, read from its own log rows:

| Configuration | Model | Input | Cached | Output | Cost | Latency |
| --- | --- | --- | --- | --- | --- | --- |
| MCP attached, no tool search | @cf/zai-org/glm-5.2 | 149,443 | 64 | 18 | $0.20922644 | 10.9 s |
| MCP attached, no tool search | @cf/moonshotai/kimi-k2.7-code | 149,187 | 64 | 19 | $0.02852109 | 4.6 s |
| MCP disabled entirely | @cf/moonshotai/kimi-k2.7-code | 21,928 | 13,312 | 45 | $0.01089448 | 2.8 s |
| MCP attached, tool search on | @cf/moonshotai/kimi-k2.7-code | 14,109 | 12,480 | 128 | $0.00443075 | 1.6 s |

[[embed:source:s7]]

Read those four rows in order and three facts follow.

**Fact one: the tool definitions, not the conversation, are the bill.** Row four is the same MCP server as rows one and two, all its tools still reachable, at one tenth the input tokens — and cheaper than row three, which had no MCP server connected at all.

**Fact two: the model choice is a 7.3× multiplier on the same turn.** $0.20922644 against $0.02852109 for an identical 149k-token request.

**Fact three: one row does not reconcile, and that is stated rather than smoothed.** The GLM row multiplies out exactly — 149,379 uncached tokens at $1.40 per million is $0.20913, plus output, against a logged $0.20922644. The two small Kimi rows reconcile the same way. The second Kimi row does not: 149,123 uncached tokens at $0.95 per million should be $0.1417, and the log says $0.02852109, an effective $0.191 per million, which is the cached rate applied to input the same row reports as 64 tokens cached. Cloudflare's documentation calls the cost field "an estimation based on the number of tokens sent and received". Treat per-row cost as the platform's estimate and the token counts as the hard numbers. Every ratio above is computed from token counts.

**What that means per month.** At 60 turns of real agent work per day, 22 working days, with tool search on and the measured $0.00443 per turn: 60 × 22 × $0.00443 = **$5.85 per month**. The same 1,320 turns at the un-tuned GLM figure of $0.20922644 would be $276. A Claude Max subscription is $100 or $200 per month depending on tier. The comparison that matters is not model against model, it is tuned configuration against untuned: the same models, the same work, a 47× difference from two environment variables.

## The two settings that decide the bill

**Tool search.** Claude Code's default is to send every tool definition from every connected MCP server in every request. Captured on the same machine, same prompt, back to back:

```text
ENABLE_TOOL_SEARCH=false   tools=856   ['Agent','AskUserQuestion','Bash','CronCreate', ... 852 more]
ENABLE_TOOL_SEARCH=true    tools=9     ['Agent','AskUserQuestion','Bash','Edit','Read',
                                        'Skill','ToolSearch','Workflow','Write']
```

[[embed:source:s30]]

The nine include a `ToolSearch` tool the model calls when it needs something not in front of it. Whether a non-Claude model actually uses it is the question that matters, because a deferred tool nobody looks for is a broken tool. Kimi K2.7 Code was asked for a tool it had never been shown; it called `ToolSearch`, found the tool named `TIME_NOW`, invoked it, and returned the payload:

```json
{"now":"2026-07-25T18:35:56-07:00","today":"2026-07-25","time":"18:35:56",
 "zone":"America/Los_Angeles","iso":"2026-07-25T18:35:56-07:00"}
```

[[embed:source:s31]]

Anthropic's prompt-caching documentation states that MCP tool search is unavailable behind a custom `ANTHROPIC_BASE_URL` gateway, and Moonshot's own Claude Code guide instructs setting `ENABLE_TOOL_SEARCH=false`. On `claude-cli 2.1.165` against this gateway it worked and cut input tokens 10.6×. Both pages may be describing other versions or other endpoints. Re-check it on your version with the capture tool below rather than trusting any of the three claims, including this one.

**The attribution line.** Claude Code prepends a line of this shape to the system prompt:

```text
x-anthropic-billing-header: cc_version=2.1.177.01c; cc_entrypoint=sdk-cli; cch=<NONCE>;
```

The `cch=` value changes on every request. `api.anthropic.com` removes that line by position before the model sees it. Every other provider receives it, and because it sits in front of a 20,000-token prefix that would otherwise be identical between turns, no cache can match. Measured effect here: cached input per turn went from 64 tokens to between 12,480 and 14,976 once the line was gone. Set `CLAUDE_CODE_ATTRIBUTION_HEADER=0` on the client, and the translator removes the block server-side as well. Never merge or reorder the `system` array around it: the removal is positional, and a merged block beginning with that header takes the rest of your system prompt with it.

[[embed:source:s11]]

## Why obedience is a reason on its own

Price is measurable and above. This is the other reason, stated plainly.

A model trained to be maximally helpful will improve on your instruction. It will add the thing you did not ask for, soften the thing you asked for bluntly, and summarise where you asked for the literal output. For a reader who needs an instruction executed exactly as written, that is not a small friction — it is the defect, and it is the trained behaviour, not a bug in a particular reply.

Open-weight models fine-tuned for coding — Kimi K2.7 Code, GLM-5.2 — are trained against benchmarks that reward completing the stated task. In practice they take a literal instruction more literally. That claim is not a benchmark result and is not presented as one; the benchmark numbers below say Claude leads on task completion. It is an operating observation, and the reason a cost-neutral switch can still be worth making: the cheaper model is also the one that does what the line says.

The structural point underneath it: an agent you can point at any model is an agent whose behaviour you can choose. An agent locked to one vendor's tuning is that vendor's judgement about what you meant. Everything above exists so that choice costs six commands instead of a rewrite.

## What people who did this report

Real accounts, positive and negative, quoted and linked. These are anecdotal reports from individuals, not measurements.

[[embed:source:s33]]

[[embed:source:s34]]

[[embed:source:s35]]

[[embed:source:s36]]

[[embed:source:s37]]

## Every documented route, ranked

**1. The vendor's own Anthropic-format endpoint.** Shortest path, no proxy, no Cloudflare. You lose the single invoice and the gateway's logs.

```bash
# Kimi (Moonshot)
export ANTHROPIC_BASE_URL="https://api.moonshot.ai/anthropic"
export ANTHROPIC_AUTH_TOKEN="$MOONSHOT_API_KEY"
export ANTHROPIC_MODEL="kimi-k3[1m]"
export ENABLE_TOOL_SEARCH="false"   # required by Moonshot's own guide

# GLM (Z.ai)
export ANTHROPIC_BASE_URL="https://api.z.ai/api/anthropic"

# DeepSeek — claude-opus* maps to v4-pro, claude-sonnet*/haiku* to v4-flash
export ANTHROPIC_BASE_URL="https://api.deepseek.com/anthropic"
```

[[embed:source:s19]]

[[embed:source:s20]]

[[embed:source:s21]]

**2. OpenRouter.** One key, hundreds of models, officially supported, no proxy: "When you set `ANTHROPIC_BASE_URL` to `https://openrouter.ai/api`, Claude Code speaks its native protocol directly to OpenRouter. No local proxy server is required." Billed by OpenRouter, and also reachable as a first-class provider inside AI Gateway.

[[embed:source:s22]]

**3. Cloudflare custom providers.** Register any HTTPS base URL as `custom-<slug>` and the gateway forwards your path to it, so a vendor's own Anthropic endpoint sits behind your gateway with its logging, caching and rate limits. The vendor still bills you; Unified Billing does not apply.

[[embed:source:s23]]

**4. LiteLLM.** The most complete translator in existence and a proxy you must run and keep running. Correct on streaming, tool calls, thinking blocks with signatures, images and token counting. Its `cache_control` pass-through is limited to Claude and Bedrock targets, so cache breakpoints are dropped against a plain chat-completions backend anyway.

**5. claude-code-router.** 36,000 stars, actively developed, desktop app and CLI. Translation is delegated to a separate package; its npm `latest` tag has lagged its GitHub releases, so check the version you installed before trusting a number from its README.

**6. A local model, which needs no translator at all.** This inverted between late 2025 and early 2026: llama.cpp, vLLM, Ollama and LM Studio all serve `/v1/messages` natively now. llama.cpp merged it on 2025-11-28 and implements token counting; Ollama shipped it in v0.14.0 and explicitly does not support token counting, `tool_choice`, `metadata` or `cache_control`; LM Studio recommends at least 25,000 tokens of context "since Claude Code can be quite context-heavy." Any guide that tells you to run a proxy for a local model is out of date.

[[embed:source:s24]]

[[embed:source:s25]]

[[embed:source:s26]]

## What breaks, and the exact fix

| Symptom | Cause | Fix |
| --- | --- | --- |
| `402` with `Gateway authentication is required to use unified billing` | Unified Billing is refused on a gateway with authentication off | Turn authentication on for that gateway and send `cf-aig-authorization` |
| Catalogue models 402 while `@cf/` models work | Same cause. Workers AI does not need Unified Billing | Same fix |
| `401` on every request, curl works | Wrong variable: `ANTHROPIC_AUTH_TOKEN` sends `Authorization: Bearer`, `ANTHROPIC_API_KEY` sends `x-api-key` | Match the variable to what your endpoint accepts; the translator here accepts either, plus the path token |
| Main thread works, subagents and session titles fail | Only `ANTHROPIC_MODEL` was set; the background and subagent slots still ask for a Claude model | Set `ANTHROPIC_DEFAULT_HAIKU_MODEL` and `CLAUDE_CODE_SUBAGENT_MODEL` |
| `400` naming `thinking` or `adaptive` | The client sends `thinking: {"type":"adaptive"}` to models that reject it | Use a translator that drops the field, or set `CLAUDE_CODE_DISABLE_THINKING=1` |
| `400 invalid thinking: only type=enabled is allowed for this model` on subagents only | The client omits `thinking` on subagent and structured-output calls; some endpoints require it | Known open defect against Moonshot's endpoint; the translator route avoids it by never forwarding the field |
| Model missing from `/model` | Gateway model discovery is off by default and drops every id not starting with `claude` or `anthropic` | Set `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1`, or select with `claude --model <name>` |
| Turn ends with no visible output | Kimi and GLM spend the output budget on reasoning before answering; an empty assistant turn aborts the client | Raise `max_tokens`; the translator falls back to the reasoning text so the turn is never empty |
| Cost per turn far above the published rate | The attribution line is defeating the upstream cache | `CLAUDE_CODE_ATTRIBUTION_HEADER=0`, and strip the block in the translator |
| Anthropic still receives usage metrics | Setting `ANTHROPIC_BASE_URL` alone does not turn metrics off | `DISABLE_TELEMETRY=1` |
| `403` with an HTML body, gateway logs show nothing | A web application firewall inspected the request body; prompts contain XML-like tags and code | Exempt `/v1/messages` from body inspection |

Two limits of the whole approach, in Anthropic's words and mine. Anthropic: it "doesn't endorse, maintain, or audit third-party gateway products, and doesn't support routing Claude Code to non-Claude models through any gateway." That is an unsupported configuration, not a prohibited one — no term forbids it — and it means the client changes when Anthropic changes it, and you catch up. Mine: images are forwarded, `thinking` is not, and prompt caching is whatever the upstream does with a prefix.

[[embed:source:s16]]

[[embed:source:s17]]

[[embed:source:s18]]

## Do the cheaper models do the work

On identical independent harnesses, the open models sit one tier behind Claude, not two. SWE-bench Verified on mini-SWE-agent 2.0.0, one attempt each: Claude Opus 4.5 76.8, GLM-5 72.8, Claude Sonnet 4.5 71.4, Kimi K2.5 70.8. Terminal-Bench 2.1 with Claude Code as the harness: Fable 5 83.8, Opus 4.8 78.9, Sonnet 5 74.6, GLM-5.1 58.7, with no Kimi entry at all.

[[embed:source:s27]]

[[embed:source:s28]]

Every vendor-published score that has an independent counterpart is higher than the independent one. GLM-4.6: 68.2 on Z.ai's own scaffold, 55.4 on mini-SWE-agent. Kimi K2.5: 76.8 in-house, 70.8 independent. Claude Opus 4.6: 80.4 in-house over 25 trials, 75.6 independent. The direction is uniform, so read the scaffold before the score.

[[embed:source:s29]]

Two more facts before anyone builds an argument on a leaderboard: the official SWE-bench Verified board's newest submission is from February 2026, and Anthropic stopped publishing SWE-bench Verified in text from Opus 4.7 onward — Opus 5 publishes neither it nor Terminal-Bench.

## Verify every measurement on this page yourself

Nothing here needs to be taken on trust. Two tools, both in the repository.

**The wire capture.** A local server that speaks the Anthropic Messages format, logs exactly what the client sent, and answers with a valid response. This is where every request-shape number on this page came from.

```bash
node tools/capture-gateway.mjs        # listens on :8787, appends capture.jsonl
ANTHROPIC_BASE_URL=http://localhost:8787 ANTHROPIC_AUTH_TOKEN=x claude -p "say ok"
```

What one capture on `claude-cli 2.1.165` recorded, 2026-07-25:

```text
HEAD /                          user-agent: Bun/1.3.14
POST /v1/messages?beta=true     model=<ANTHROPIC_MODEL>   max_tokens=32000   tools=861
POST /v1/messages?beta=true     model=<HAIKU_SLOT>        max_tokens=1024    tools=0
anthropic-version: 2023-06-01
anthropic-beta: claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,
  context-management-2025-06-27,prompt-caching-scope-2026-01-05,
  mid-conversation-system-2026-04-07,effort-2025-11-24,extended-cache-ttl-2025-04-11
system: [ 92 chars, 62 chars, 5681 chars ]   cache_control: [ none, ephemeral, ephemeral ]
```

[[embed:source:s1]]

Four constraints for anyone writing a translator follow from that capture, and the reference implementation obeys all four: match on the path because the query string is present; serve both model slots; keep the `system` array in its original order; and expect the tool list, not the prompt, to dominate the payload.

**The contract test.** 21 checks against a live deployment, listed earlier in Route B. Run it after every change.

[[embed:source:s2]]

## The complete requirement list for a translator

Seven behaviours. Each one is a real defect in at least one published shim, so each is checked by the contract test.

1. **Stream.** A gateway that buffers whole responses stalls the client.
2. **Emit tool arguments incrementally** — `content_block_start`, then `input_json_delta` chunks — not one blob at the end.
3. **Order tool results correctly.** Anthropic puts `tool_result` blocks inside a user turn; Chat Completions wants `role:"tool"` messages immediately after the assistant turn that called them.
4. **Map stop reasons**: `stop` to `end_turn`, `length` to `max_tokens`, `tool_calls` to `tool_use`. Nobody can produce `stop_sequence` faithfully, because Chat Completions returns `stop` for both cases with no discriminator.
5. **Never return an empty turn.** Fall back to the reasoning text when the output budget was spent before any answer.
6. **Answer `/v1/messages/count_tokens`.** It is optional, and without it the client estimates locally; an estimate beats a 404.
7. **Remove the attribution block without reordering the `system` array.**

Four Cloudflare Workers shims exist and each fails at least one of these: `luohy15/y-router` is archived and drops `max_tokens`; `glidea/claude-worker-proxy` is active but sends tool arguments as one blob, has no token-count route and drops images; `tingxifa/claude_proxy` types `system` as a string, which is not the shape the client sends; `mrdear/cloudflare-ai-proxy` ignores images by design.

[[embed:source:s8]]

[[embed:source:s9]]

[[embed:source:s10]]

## What this costs to keep running

The translator is a Cloudflare Worker. On the free plan that is 100,000 requests per day at no charge; a heavy day of agent work is a few hundred. The gateway itself is free; its logs are retained per your plan. Model tokens are the only real cost, at the rates above. Unified Billing adds 5% on purchased credits and passes provider pricing through with no markup, and Workers AI models are billed as Workers AI rather than through it — the arithmetic of that split is in [Cloudflare Unified Billing](/a/cloudflare-unified-billing).

[[embed:source:s13]]

One security fact to hold onto: Cloudflare states that AI Gateway token permissions "cannot be restricted to a single gateway", so a token with Run reaches every gateway on the account, including any holding stored provider keys. Rate-limit the gateway you use for this — 120 requests per 60 seconds is enough for one operator and caps the damage if a token leaks.

[[embed:source:s14]]


## Claims (30)

- **c3** [system w=0.35] Cloudflare documents Claude Code against its AI Gateway Anthropic endpoint, which exposes the same /v1/messages API the client expects.
  - who_claims: Opus 5 (Claude Code)
  - sources: s3, s4
- **c4** [system w=0.35] The gateway's Anthropic provider is a reverse proxy to api.anthropic.com and cannot route a /v1/messages request to a non-Anthropic model; the account REST endpoint /ai/v1/messages excludes Workers AI @cf/ models by documentation.
  - who_claims: Opus 5 (Claude Code)
  - sources: s4, s5
- **c7** [system w=0.35] Measured through one AI Gateway: a Kimi K2.7 Code turn cost $0.01089448 at 21,928 input tokens with MCP disabled, against $0.02852109 at 149,187 input tokens with one MCP server attached.
  - who_claims: Opus 5 (Claude Code)
  - sources: s15, s16, s7
- **c8** [system w=0.35] Unified Billing is refused on a gateway with authentication off, returning HTTP 402 for catalogue models while Workers AI @cf/ models continue to work.
  - who_claims: Opus 5 (Claude Code)
  - sources: s13, s14, s7
- **c11** [system w=0.35] Rewriting tool_use identifiers in translation can break upstream tool parsing and make Claude Code end its turn mid-task with no error surfaced in the client.
  - who_claims: Opus 5 (Claude Code)
  - sources: s10
- **c14** [system w=0.35] Unified Billing applies a 5% fee to purchased credits, passes provider inference pricing through without markup, and excludes Workers AI @cf/ models.
  - who_claims: Opus 5 (Claude Code)
  - sources: s13
- **c27** [system w=0.35] The translator is published as a single-file Cloudflare Worker under MIT with three secrets and a wire-capture tool, so the setup and every measurement in this article can be reproduced on another account.
  - who_claims: Opus 5 (Claude Code)
  - sources: s32
- **c6** [mechanistic w=0.3] Cloudflare's /ai/v1/messages returns a true Anthropic envelope for anthropic/* models but answered minimax/m3 with an OpenAI chat.completion body, so accepting the request is not the same as answering in the schema.
  - who_claims: Opus 5 (Claude Code)
  - sources: s7
- **c24** [mechanistic w=0.3] ENABLE_TOOL_SEARCH=true works behind a custom ANTHROPIC_BASE_URL gateway on claude-cli 2.1.165, reducing a request from 856 tool definitions to 9 plus a ToolSearch tool, against documentation stating tool search is unavailable in that configuration.
  - who_claims: Opus 5 (Claude Code)
  - sources: s30, s31
- **c26** [mechanistic w=0.3] A non-Claude model drives the deferred-tool loop: Kimi K2.7 Code called ToolSearch to locate an MCP tool it had not been shown, invoked it, and returned its payload verbatim.
  - who_claims: Opus 5 (Claude Code)
  - sources: s31
- **c1** [system w=0.35] Claude Code posts inference to /v1/messages?beta=true with two distinct model slots: a main call carrying the full tool list at max_tokens 32000, and a tool-free background call at max_tokens 1024.
  - who_claims: Opus 5 (Claude Code)
  - sources: s1, s2
- **c2** [system w=0.35] A gateway must stream responses and must forward the anthropic-beta header verbatim; /v1/messages/count_tokens is optional and its absence makes the client estimate context locally.
  - who_claims: Opus 5 (Claude Code)
  - sources: s2
- **c5** [system w=0.35] Kimi, GLM, Grok and DeepSeek are catalogued on Cloudflare as Chat Completions only, so Claude Code cannot reach them without format translation.
  - who_claims: Opus 5 (Claude Code)
  - sources: s5, s6
- **c9** [system w=0.35] Disabling one MCP server cut input from 149,443 tokens to 21,928 and raised cached input from 64 tokens to 13,312 once the per-request attribution block was stripped.
  - who_claims: Opus 5 (Claude Code)
  - sources: s7
- **c10** [system w=0.35] No existing Anthropic-to-OpenAI shim targets Cloudflare Workers AI, and each of the four that run as Cloudflare Workers fails on a contract element Claude Code depends on.
  - who_claims: Opus 5 (Claude Code)
  - sources: s8, s9
- **c12** [system w=0.35] Claude Code prepends a per-request attribution line to the system prompt which Anthropic strips positionally, defeating prefix caching on every other provider until it is removed.
  - who_claims: Opus 5 (Claude Code)
  - sources: s11, s2
- **c13** [system w=0.35] The desktop client validates model names against an Anthropic-shaped allowlist, so a gateway model id such as kimi-k2.7-code is rejected before any request is sent.
  - who_claims: Opus 5 (Claude Code)
  - sources: s12
- **c15** [system w=0.35] AI Gateway token permissions cannot be scoped to a single gateway, so any token with Run permission can send requests through every gateway on the account, including gateways holding stored provider keys.
  - who_claims: Opus 5 (Claude Code)
  - sources: s14
- **c16** [system w=0.35] Anthropic states it does not endorse, maintain or audit third-party gateway products and does not support routing Claude Code to non-Claude models through any gateway.
  - who_claims: Opus 5 (Claude Code)
  - sources: s16
- **c17** [system w=0.35] Claude Code sends thinking: {type: adaptive} to models behind a custom base URL, producing 400s, empty responses or hangs, and its subagent and structured-output calls omit the field entirely, failing against endpoints that require it.
  - who_claims: Opus 5 (Claude Code)
  - sources: s17, s18
- **c18** [system w=0.35] Moonshot, Z.ai and DeepSeek each publish an Anthropic-format base URL with their own Claude Code instructions, giving a working route with no proxy and no Cloudflare billing.
  - who_claims: Opus 5 (Claude Code)
  - sources: s19, s20, s21
- **c19** [system w=0.35] OpenRouter serves Claude Code's native protocol directly at https://openrouter.ai/api with no local proxy, and is also a first-class AI Gateway provider.
  - who_claims: Opus 5 (Claude Code)
  - sources: s22
- **c20** [system w=0.35] Cloudflare custom providers proxy any HTTPS base URL under custom-<slug>, so a vendor's own Anthropic endpoint can sit behind the gateway with observability and caching but without Unified Billing.
  - who_claims: Opus 5 (Claude Code)
  - sources: s23
- **c21** [system w=0.35] llama.cpp, vLLM, Ollama and LM Studio all serve /v1/messages natively as of early 2026, so local models need no translation proxy.
  - who_claims: Opus 5 (Claude Code)
  - sources: s24, s25, s26
- **c22** [system w=0.35] On identical independent harnesses the open models sit one tier behind Claude: SWE-bench Verified 76.8 Opus 4.5, 72.8 GLM-5, 70.8 Kimi K2.5 on mini-SWE-agent 2.0.0; Terminal-Bench 2.1 with Claude Code 83.8 Fable 5 against 58.7 GLM-5.1.
  - who_claims: Opus 5 (Claude Code)
  - sources: s27, s28
- **c23** [system w=0.35] Every vendor-reported benchmark score with an independent counterpart is higher than the independent measurement, by 4 to 13 points, without exception.
  - who_claims: Opus 5 (Claude Code)
  - sources: s27, s29
- **c25** [system w=0.35] With the same MCP server attached, tool search cut measured input from 149,187 tokens and $0.02852109 per turn to 14,109 tokens and $0.00443075 — cheaper than running with no MCP server connected at all.
  - who_claims: Opus 5 (Claude Code)
  - sources: s30, s31, s7
- **c28** [operator w=?] Operators use Claude Code with cheaper or local backends through base-URL and model settings, but these reports establish workable configurations rather than universal quality or savings.
  - who_claims: Opus 5 (Claude Code)
  - sources: s33, s34, s36, s37
- **c29** [operator w=?] One operator published a working Claude Code configuration against a local llama-server with a 200k context setting; this is one externally attested setup, not a compatibility guarantee for every local runtime.
  - who_claims: Opus 5 (Claude Code)
  - sources: s34
- **c30** [operator w=?] Operator evidence also runs in the other direction: one high-attention report describes moving from Kimi K3 back to Claude Opus 5, so lower price does not prove model substitution is acceptable for every task.
  - who_claims: Opus 5 (Claude Code)
  - sources: s35

## Voxel graph (30 atoms · 80 edges)
- full graph: https://miscsubjects.com/api/articles/claude-code-on-cloudflare-ai-gateway/voxels

## Article constitution

- full: https://miscsubjects.com/api/articles/constitution

## Source ledger (37)
- chain valid: no · head: ``

### s1 · runtime_receipt · ok
- title: Wire capture: what claude-cli 2.1.165 sends to an arbitrary ANTHROPIC_BASE_URL
- url: https://miscsubjects.com/api/articles/claude-code-on-cloudflare-ai-gateway
- summary: First-party capture, 2026-07-25: Claude Code pointed at a local logging server that answered in Anthropic format. Records the path with its query string, the two model slots (32000-token main call with tools, 1024-token background call without), the eight anthropic-beta values, and the three-block cache-marked system array.
- quote: POST /v1/messages?beta=true | model=<ANTHROPIC_MODEL> max_tokens=32000 tools=861 | system=[92, 62, 5681] cache_control=[none, ephemeral, ephemeral]
- claim_ids: c1
- hash: `be264ae0bf04553a`

### s2 · publisher_documentation · ok
- title: Claude Code gateway protocol reference
- url: https://code.claude.com/docs/en/llm-gateway-protocol
- summary: Anthropic's contract for gateway authors: inference posts to /v1/messages?beta=true and must be matched on path; responses must stream or the client stalls; /v1/messages/count_tokens is optional and its absence makes the client estimate context locally; the system-prompt attribution strip is positional; gateway model discovery ignores ids that do not begin with claude or anthropic.
- quote: Forward the header verbatim; don't allowlist individual values, because the set changes with Claude Code releases.
- claim_ids: c1, c12, c2
- hash: `e329fc3e0001dc61`

### s3 · publisher_documentation · ok
- title: Cloudflare AI Gateway — Claude Code integration
- url: https://developers.cloudflare.com/ai-gateway/integrations/coding-agents/claude-code/
- summary: Cloudflare's first-party guide: three environment variables (ANTHROPIC_BASE_URL at the gateway's anthropic provider, ANTHROPIC_API_KEY, and cf-aig-authorization via ANTHROPIC_CUSTOM_HEADERS), an authenticated gateway, and a gateway token with Run permission. Also documents Bedrock and Vertex variants.
- quote: The Anthropic endpoint exposes the same /v1/messages API that Claude Code expects.
- claim_ids: c3
- hash: `9d01f4917060ddda`

### s4 · publisher_documentation · ok
- title: Cloudflare AI Gateway — Anthropic provider
- url: https://developers.cloudflare.com/ai-gateway/usage/providers/anthropic/
- summary: The anthropic provider slug is a reverse proxy to api.anthropic.com, taking x-api-key and anthropic-version: 2023-06-01. It serves /v1/messages and cannot route that request to a non-Anthropic model.
- quote: https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/anthropic
- claim_ids: c3, c4
- hash: `69939bc9b617b0e6`

### s5 · publisher_documentation · ok
- title: Cloudflare AI Gateway — REST API
- url: https://developers.cloudflare.com/ai-gateway/usage/rest-api/
- summary: Four endpoints on the account AI surface: /ai/run, /ai/v1/chat/completions, /ai/v1/responses and /ai/v1/messages. Chat completions serves both Workers AI and third-party catalogue models; the Anthropic-schema endpoint excludes @cf/ models. Workers AI requests require the cf-aig-gateway-id header.
- quote: The /ai/v1/messages endpoint strictly uses Anthropic's API schema and supports routing to Anthropic and other third-party models. Workers AI models (@cf/) do not support this schema.
- claim_ids: c4, c5
- hash: `09e2aec7f7360ff6`

### s6 · publisher_documentation · ok
- title: Cloudflare model catalogue — Request formats field
- url: https://developers.cloudflare.com/ai/models/moonshotai/kimi-k3/
- summary: Every catalogue model page states which request formats it accepts. Kimi, Grok, DeepSeek and the Workers AI @cf/ models are Chat Completions only; anthropic/* and minimax/m3 list Anthropic Messages. This field is what decides whether Claude Code can reach a model without translation.
- quote: Request formats: Chat Completions
- claim_ids: c5
- hash: `44506c2385e789db`

### s7 · runtime_receipt · ok
- title: Gateway log rows: measured cost, cached input and the Unified Billing 402
- url: https://miscsubjects.com/api/articles/claude-code-on-cloudflare-ai-gateway
- summary: First-party measurements read from the account's own AI Gateway logs, 2026-07-25. With an MCP server attached: GLM-5.2 149,443 input tokens, 64 cached, $0.20922644, 10.9s; Kimi K2.7 Code 149,187 input, $0.02852109. With MCP disabled: Kimi 21,928 input, 13,312 cached, $0.01089448, 2.8s. Also records the 402 returned when a catalogue model is routed through an unauthenticated gateway, and that minimax/m3 answers /ai/v1/messages with an OpenAI chat.completion body rather than an Anthropic envelope.
- quote: {"errors":[{"message":"Gateway authentication is required to use unified billing. Enable authentication on your gateway or provide your own API key (BYOK).","code":2021}]}
- claim_ids: c25, c6, c7, c8, c9
- hash: `1836223c34e17373`

### s8 · github · ok
- title: y-router — archived Cloudflare Worker Anthropic-to-OpenAI proxy
- url: https://github.com/luohy15/y-router
- summary: The best-known Cloudflare Worker shim, archived 2026-01-11. Source review also shows it drops max_tokens and returns fabricated usage numbers, so it should not be used as a starting point.
- quote: docs: Archive project in favor of official OpenRouter integration
- claim_ids: c10
- hash: `3d49cc44500bf4a3`

### s9 · github · ok
- title: claude-worker-proxy — the one active Cloudflare Worker shim
- url: https://github.com/glidea/claude-worker-proxy
- summary: Active and structurally sound, with three gaps that matter to Claude Code: tool arguments are emitted as one blob instead of incremental input_json_delta, there is no /v1/messages/count_tokens route, and image blocks are dropped. No Worker-native shim handles thinking blocks or cache_control.
- quote: Anthropic Messages to OpenAI-compatible proxy running on Cloudflare Workers
- claim_ids: c10
- hash: `7b3bcabb0b1d7c96`

### s10 · github · ok
- title: LiteLLM #34522 — Kimi K2 tool calls silently stop working after tool_use id normalization
- url: https://github.com/BerriAI/litellm/issues/34522
- summary: Rewriting tool_use ids to satisfy Anthropic's character class breaks upstream parsers that derive call indexes from the original id form. The reported symptom is the worst kind: Claude Code ends its turn mid-task with no error surfaced anywhere in the client.
- quote: Kimi K2 tool calls silently stop working on v1.91.3+ due to tool_use id normalization
- claim_ids: c11
- hash: `81b33918f4027782`

### s11 · github · ok
- title: claude-code #68900 — per-request billing-header nonce breaks prompt caching on third-party providers
- url: https://github.com/anthropics/claude-code/issues/68900
- summary: The first system block of every request carries a value that changes per request, sitting in front of the whole cached prefix. Reported result: 0% cache hit on third-party providers, restored to roughly 99.7% once a proxy normalised the block away. CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC does not remove it; CLAUDE_CODE_ATTRIBUTION_HEADER=0 does.
- quote: x-anthropic-billing-header: cc_version=2.1.177.01c; cc_entrypoint=sdk-cli; cch=<NONCE>;
- claim_ids: c12
- hash: `b4c971d0c0c2c8ba`

### s12 · github · ok
- title: claude-code #56990 — desktop build rejects non-Anthropic model names
- url: https://github.com/anthropics/claude-code/issues/56990
- summary: Client-side validation in the desktop app checks model names against an Anthropic-shaped allowlist, so a gateway model id such as kimi-k2.7-code is refused before any request is sent. Practical consequence: the names you type must look like Claude names while resolving to something else.
- quote: expected a gateway model route referencing an Anthropic model (e.g. claude-sonnet-4-5, anthropic/claude-*). Name routes to match the underlying model.
- claim_ids: c13
- hash: `56a2c79f2330d372`

### s13 · publisher_documentation · ok
- title: Cloudflare AI Gateway — Unified Billing
- url: https://developers.cloudflare.com/ai-gateway/features/unified-billing/
- summary: Unified Billing lets the gateway supply the provider credential, so no Anthropic, Moonshot or xAI key appears in the client configuration. Workers AI models prefixed @cf/ are explicitly not billed through it, so a mixed setup produces two line items on one Cloudflare invoice.
- quote: A 5% fee is applied to all credits purchased through Unified Billing. For example, a $100 credit purchase will result in a $105 charge. Inference pricing from providers is passed through with no markup.
- claim_ids: c14, c8
- hash: `9b16a41c3d1d3124`

### s14 · publisher_documentation · ok
- title: Cloudflare AI Gateway — authenticated gateway and token scope
- url: https://developers.cloudflare.com/ai-gateway/configuration/authentication/
- summary: Authentication is per gateway: with it on, a request without cf-aig-authorization fails. The permission model is account-wide, so a Run token is not a per-gateway credential no matter how you scope the rest of your setup.
- quote: The AI Gateway Read, Run, and Edit permissions cannot be restricted to a single gateway — unlike R2, which supports per-bucket scoping. Any token with AI Gateway Run can send requests through every gateway in the account, including any configured with stored provider keys through Bring Your Own Keys (BYOK), consuming those credentials.
- claim_ids: c15, c8
- hash: `6e59f1fed1a67c2b`

### s15 · publisher_documentation · ok
- title: Workers AI pricing
- url: https://developers.cloudflare.com/workers-ai/platform/pricing/
- summary: Workers AI bills in Neurons with 10,000 free per day on both Free and Paid plans, resetting at 00:00 UTC. Published per-million rates include Kimi K2.7 Code at $0.95 input / $0.19 cached input / $4.00 output, GLM-5.2 at $1.40 / $0.26 / $4.40, and GLM-4.7-Flash at $0.06 input / $0.40 output with no cached tier.
- quote: $0.011 per 1,000 Neurons
- claim_ids: c7
- hash: `2dcd0572f3aecb3a`

### s16 · publisher_documentation · ok
- title: Claude Code — LLM gateway configuration
- url: https://code.claude.com/docs/en/llm-gateway
- summary: Pointing the CLI at a gateway is a documented, first-class configuration; pointing it at a non-Claude model is outside what Anthropic supports. The word is support, not prohibit — no clause forbids it — but the client is a moving target and the operator absorbs every change.
- quote: Anthropic doesn't endorse, maintain, or audit third-party gateway products, and doesn't support routing Claude Code to non-Claude models through any gateway.
- claim_ids: c16, c7
- hash: `945ae8d2a0662dc9`

### s17 · github · unchecked
- title: claude-code #68551 — adaptive thinking sent to custom base-URL models
- url: https://github.com/anthropics/claude-code/issues/68551
- summary: The client treats unrecognised gateway aliases as current models and sends the thinking field to them. Reported symptoms across backends: HTTP 400, empty responses, and multi-minute hangs. A translator that drops the field entirely avoids the whole class.
- quote: Claude Code sends thinking: {type: adaptive} to custom ANTHROPIC_BASE_URL models — gateways 400 / return empty / hang
- claim_ids: c17
- hash: `fb7d091568830a59`

### s18 · github · unchecked
- title: claude-code #69379 — subagents 400 against a third-party Anthropic endpoint
- url: https://github.com/anthropics/claude-code/issues/69379
- summary: Against Moonshot's Anthropic endpoint the main thread works while subagent and structured-output calls fail, because those requests omit the thinking field the model requires. The subagent transcript is two lines and zero tool uses. MAX_THINKING_TOKENS does not fix it.
- quote: API Error: 400 invalid thinking: only type=enabled is allowed for this model
- claim_ids: c17
- hash: `03b965084ef7fdf0`

### s19 · publisher_documentation · unchecked
- title: Moonshot — using Kimi in Claude Code
- url: https://platform.kimi.ai/docs/guide/claude-code-kimi
- summary: Moonshot's own Anthropic-format endpoint and Claude Code instructions. Model ids include kimi-k3 (1,048,576-token context) and kimi-k2.7-code. The page requires ENABLE_TOOL_SEARCH=false because the endpoint does not support that feature yet, and kimi-k2.7-code rejects requests with thinking disabled. The China endpoint is api.moonshot.cn/anthropic.
- quote: export ANTHROPIC_BASE_URL="https://api.moonshot.ai/anthropic"
- claim_ids: c18
- hash: `7a43fdf1a52952ea`

### s20 · publisher_documentation · unchecked
- title: Z.ai — GLM in Claude Code
- url: https://docs.z.ai/devpack/tool/claude
- summary: Z.ai publishes an Anthropic-format endpoint and a Claude Code settings block mapping the Opus and Sonnet slots to glm-5.2. The page contradicts itself on the haiku slot (glm-4.7 in prose, glm-4.5-air on a sibling page) and still claims verification against Claude Code 2.0.14.
- quote: "ANTHROPIC_BASE_URL": "https://api.z.ai/api/anthropic"
- claim_ids: c18
- hash: `0b0cdda5d102246f`

### s21 · publisher_documentation · unchecked
- title: DeepSeek — Anthropic API format
- url: https://api-docs.deepseek.com/guides/anthropic_api
- summary: DeepSeek maps Claude Code's default model names for you: claude-opus* to deepseek-v4-pro, claude-haiku*/claude-sonnet* to deepseek-v4-flash. Documented limits: anthropic-beta and anthropic-version headers ignored, cache_control ignored everywhere, image and document blocks unsupported, thinking accepted but budget_tokens ignored.
- quote: To meet the demand for using the Anthropic API ecosystem, our API has added support for the Anthropic API format, with the base_url being https://api.deepseek.com/anthropic
- claim_ids: c18
- hash: `d5b6ee39a5cf9e1e`

### s22 · publisher_documentation · unchecked
- title: OpenRouter — Claude Code integration
- url: https://openrouter.ai/docs/guides/guides/claude-code-integration
- summary: An officially supported Anthropic-format endpoint in front of hundreds of models, with ANTHROPIC_API_KEY required to be explicitly empty. OpenRouter is also a first-class AI Gateway provider slug, which makes it the shortest documented path to many models with Cloudflare in the middle.
- quote: When you set ANTHROPIC_BASE_URL to https://openrouter.ai/api, Claude Code speaks its native protocol directly to OpenRouter. No local proxy server is required.
- claim_ids: c19
- hash: `8014c0b9191a5654`

### s23 · publisher_documentation · unchecked
- title: Cloudflare AI Gateway — custom providers
- url: https://developers.cloudflare.com/ai-gateway/configuration/custom-providers/
- summary: Register any HTTPS base URL as custom-<slug> and the gateway proxies arbitrary paths to it, so a vendor's own /anthropic/v1/messages can sit behind your gateway with its observability, caching and rate limits. Billing stays with the vendor; Unified Billing does not apply.
- quote: Everything after custom-{slug}/ in your request URL is appended directly to the base_url to form the final upstream URL.
- claim_ids: c20
- hash: `23776d8f6a581b6c`

### s24 · publisher_documentation · unchecked
- title: Ollama — Anthropic API compatibility
- url: https://docs.ollama.com/api/anthropic-compatibility
- summary: Ollama serves /v1/messages natively from v0.14.0 (2026-01-10), so no proxy is needed for local models. Documented as not supported: /v1/messages/count_tokens, tool_choice, metadata, prompt caching via cache_control, the Batches API, citations, PDF document blocks and server-sent error events. The launch guidance recommends at least 32K context.
- quote: API key is accepted but not validated.
- claim_ids: c21
- hash: `7707b56a014aaa0e`

### s25 · github · unchecked
- title: llama.cpp #17570 — Anthropic Messages API in llama-server
- url: https://github.com/ggml-org/llama.cpp/pull/17570
- summary: Merged 2025-11-28, giving llama-server a native /v1/messages endpoint including count_tokens. Tool use requires the --jinja flag. Measured in a related issue: a real Claude Code session opens at 9,617 prompt tokens on that endpoint and reaches 41,035 by the ninth request.
- quote: While no strong claims of compatibility with the Anthropic API spec are made, in our experience it suffices to support many apps.
- claim_ids: c21
- hash: `81f73a58a94e7607`

### s26 · publisher_documentation · unchecked
- title: vLLM — Claude Code integration
- url: https://docs.vllm.ai/en/latest/serving/integrations/claude_code/
- summary: vLLM serves the Anthropic Messages endpoint natively (merged 2025-10-22) and documents the practical traps: model names cannot contain a slash, and the client's per-request system-prompt hash can defeat prefix caching unless the server handles it or CLAUDE_CODE_ATTRIBUTION_HEADER is disabled.
- quote: Claude Code requires a model with strong tool calling capabilities
- claim_ids: c21
- hash: `357b2ecab1bfc367`

### s27 · independent_test · unchecked
- title: SWE-bench Verified leaderboard
- url: https://www.swebench.com/
- summary: Same-harness comparison on the official board: Claude Opus 4.5 76.8, Claude Sonnet 4.5 71.4, GLM-5 72.8, Kimi K2.5 70.8, all on mini-SWE-agent 2.0.0 at one attempt. The newest submission on the board is from February 2026, so nothing released after that appears at all.
- quote: mini-SWE-agent 2.0.0 — glm-5 (high) 72.8
- claim_ids: c22, c23
- hash: `f2464b94e231d181`

### s28 · independent_test · unchecked
- title: Terminal-Bench 2.1 leaderboard
- url: https://www.tbench.ai/leaderboard/terminal-bench/2.1
- summary: With Claude Code itself as the harness: Fable 5 83.8, Opus 4.8 78.9, Sonnet 5 74.6, GLM-5.1 58.7. No Kimi model appears on 2.1 in any configuration, and there is no benchmark version where all of these models coexist.
- quote: Claude Code + Fable 5 — 83.8 ± 1.2
- claim_ids: c22
- hash: `278b23a4b19aac29`

### s29 · publisher_documentation · unchecked
- title: Kimi K2.6 model card — vendor-reported scores
- url: https://huggingface.co/moonshotai/Kimi-K2.6
- summary: Vendor scores are reported on in-house scaffolds: Kimi K2.6 claims 80.2 on SWE-bench Verified with a framework adapted from SWE-agent, averaged over ten runs. Every vendor number with an independent counterpart sits above it — GLM-4.6 68.2 self-reported against 55.4 on mini-SWE-agent, Kimi K2.5 76.8 against 70.8, Claude Opus 4.6 80.4 against 75.6. The direction is uniform, so scaffold is read before score.
- quote: SWE-bench Verified 80.2
- claim_ids: c23
- hash: `206283fa3979b044`

### s30 · runtime_receipt · ok
- title: Tool-search capture: 856 tool definitions become 9
- url: https://miscsubjects.com/api/articles/claude-code-on-cloudflare-ai-gateway
- summary: First-party capture, 2026-07-25, same session and same prompt against a local logging server. With tool search off the request carries every definition from the connected MCP server; with it on the client sends nine tools plus a ToolSearch tool and expands the rest on demand.
- quote: ENABLE_TOOL_SEARCH=false  tools=856   |   ENABLE_TOOL_SEARCH=true  tools=9  ['Agent','AskUserQuestion','Bash','Edit','Read','Skill','ToolSearch','Workflow','Write']
- claim_ids: c24, c25
- hash: `bdbfd60193bd789e`

### s31 · runtime_receipt · ok
- title: Gateway log rows with tool search on, and a non-Claude model using it
- url: https://miscsubjects.com/api/articles/claude-code-on-cloudflare-ai-gateway
- summary: Measured through the account gateway on 2026-07-25: with the same MCP server attached and ENABLE_TOOL_SEARCH=true, Kimi K2.7 Code turns ran at 14,109 input tokens with 12,480 cached and $0.00443075, against 149,187 tokens and $0.02852109 with tool search off. The quote is the payload Kimi returned after calling ToolSearch to find an MCP tool it had never been shown and then invoking it.
- quote: {"now":"2026-07-25T18:35:56-07:00","today":"2026-07-25","time":"18:35:56","zone":"America/Los_Angeles","iso":"2026-07-25T18:35:56-07:00"}
- claim_ids: c24, c25, c26
- hash: `6cefb5e3bc01ad03`

### s32 · github · ok
- title: claude-code-cloudflare-gateway — the Worker from this article
- url: https://github.com/massoumicyrus/claude-code-cloudflare-gateway
- summary: Public MIT repository: the single-file Worker, wrangler config, the three secrets it needs, the model alias table, and tools/capture-gateway.mjs — the local Anthropic-compatible logger used for every wire measurement in this article, so the numbers can be re-derived on a newer CLI.
- quote: Run Claude Code against Kimi, GLM, Grok or Claude through your own Cloudflare AI Gateway. One Worker, one bill, no provider keys.
- claim_ids: c27
- hash: `ae1c5cf9003a1930`

### s33 · reddit · ok
- title: I gave Claude Code a $0.02/call coworker and stopped hitting Pro limits
- url: https://old.reddit.com/r/ClaudeAI/comments/1t1o43w/i_gave_claude_code_a_002call_coworker_and_stopped/
- summary: Anecdotal, r/ClaudeAI, 1,776 upvotes. The operator delegates bulk file reading and boilerplate to Kimi K2.5 through CLI scripts Claude calls via the Bash tool, with routing rules in CLAUDE.md, rather than switching the whole agent. Positive report on cost, and evidence that hitting subscription limits is the common trigger for looking at cheaper models.
- quote: Was hitting my weekly Pro limit by Wednesday every single week. Tried compact, Sonnet for simple tasks, tighter prompts — nothing worked.
- claim_ids: c28
- hash: `c3d856bcaaa9e23b`

### s34 · reddit · ok
- title: Qwen 3.6 is actually useful for vibe-coding, and way cheaper than Claude
- url: https://old.reddit.com/r/LocalLLaMA/comments/1st3m8y/qwen_36_is_actually_useful_for_vibecoding_and_way/
- summary: Anecdotal, r/LocalLLaMA. Points Claude Code at a local llama-server on a dual-3090 machine with 200k context and reports it working, publishing the exact env block: ANTHROPIC_AUTH_TOKEN, empty ANTHROPIC_API_KEY, ANTHROPIC_BASE_URL to the local host. Confirms local runtimes now serve the Messages API without a proxy.
- quote: Launched claude code, pointed it at my running Qwen, and, well, it vibe codes perfectly fine.
- claim_ids: c28, c29
- hash: `84376d6572e793f4`

### s35 · reddit · ok
- title: From Kimi K3 to Claude Opus 5
- url: https://old.reddit.com/r/ClaudeAI/comments/1v6224v/from_kimi_k3_to_claude_opus_5/
- summary: Anecdotal, r/ClaudeAI, 591 upvotes, posted the same day this page was written. The quote is the thread title: an operator moving in the opposite direction, from Kimi K3 back to Claude Opus 5. Counter-evidence to the cheaper-is-enough case, and the reason model choice per session matters more than picking one winner.
- quote: From Kimi K3 to Claude Opus 5
- claim_ids: c30
- hash: `52d3c50d186587c4`

### s36 · x · ok
- title: Per-model settings file for switching Claude Code to Kimi
- url: https://x.com/chongdashu/status/2016156608875602204
- summary: Anecdotal, X. Publishes the settings-file pattern rather than exported shell variables: a .claude/settings/kimi.json holding ANTHROPIC_BASE_URL, ANTHROPIC_AUTH_TOKEN, ANTHROPIC_MODEL and ANTHROPIC_SMALL_FAST_MODEL, launched with a shell function so one word switches model. An alternative to the env block on this page for anyone who keeps several backends.
- quote: Want to use Kimi 2.5 in Claude Code? Step 1: create a file .claude/settings/kimi.json
- claim_ids: c28
- hash: `6c55b4ffd8f9cecb`

### s37 · github · ok
- title: cc-compatible-models — community catalogue of Claude Code backends
- url: https://github.com/Alorse/cc-compatible-models
- summary: Community-maintained list of providers that answer Claude Code, with the env block and price for each. Useful as a starting point for a provider not covered here, and evidence that the practice is widespread rather than exotic. Verify any figure in it against the vendor's own pricing page before relying on it.
- quote: Complete guide for using alternative AI models with Claude Code — including DeepSeek, Qwen, MiniMax, Kimi, GLM, MiMo, StepFun, and more. Pricing, configs, and coding plans.
- claim_ids: c28
- hash: `5cc909e00e579dbe`

## Provenance (30 model passes)
- chain valid: yes · head: `c38b46e4fab04d75`

- claim · Opus 5 (Claude Code) · 2026-07-26T01:23 · hash `47e8c3df272f`
- claim · Opus 5 (Claude Code) · 2026-07-26T01:23 · hash `65cd012407d8`
- sources · Opus 5 (Claude Code) · 2026-07-26T01:39 · hash `102de840be34`
- claim · Opus 5 (Claude Code) · 2026-07-26T01:39 · hash `67ceebc9589d`
- claim · Opus 5 (Claude Code) · 2026-07-26T01:39 · hash `d56f0aeb5f68`
- claim · Opus 5 (Claude Code) · 2026-07-26T01:40 · hash `433a5d1eca1f`
- claim · Opus 5 (Claude Code) · 2026-07-26T01:40 · hash `faabf72cbad9`
- sources · Opus 5 (Claude Code) · 2026-07-26T03:26 · hash `c38b46e4fab0`

## Question graph
- questions: 0 · evidence ingests: 0

## LLM manifest — how to communicate with this ledger

- system map: https://miscsubjects.com/api/articles/system-map?format=markdown
- topology (ranked): https://miscsubjects.com/api/articles/claude-code-on-cloudflare-ai-gateway/topology
- ingest: POST https://miscsubjects.com/api/protocol/ingest
- claim: POST https://miscsubjects.com/api/protocol/claim

### Quick actions for this article
- **Read live:** https://miscsubjects.com/api/articles/claude-code-on-cloudflare-ai-gateway/topology
- **Ask (API):** POST https://miscsubjects.com/api/protocol/ask `{"slug":"claude-code-on-cloudflare-ai-gateway","question":"..."}`
- **Ingest your findings:** POST https://miscsubjects.com/api/protocol/ingest or text `ingest claude-code-on-cloudflare-ai-gateway|your evidence`
- **Post one claim:** POST https://miscsubjects.com/api/protocol/claim or text `claim claude-code-on-cloudflare-ai-gateway|tier|assertion`
- **iMessage ask:** `claude-code-on-cloudflare-ai-gateway|your question`
- **System map:** https://miscsubjects.com/api/articles/system-map?format=markdown


---

## §SELF — miscsubjects portable reference

**Principle:** Self-explaining payload — no external context required. This _self block describes what you are reading and where to look next.

**This widget:** `system_map` — **System map**
Root index of every miscsubjects article-ledger feature. Start here if you have zero context.
- **article slug:** `claude-code-on-cloudflare-ai-gateway`
- **contains:** body, claims, sources, voxels, provenance, question graph, constitution, llm_manifest
- **how to use:** Root index of every miscsubjects article-ledger feature. Start here if you have zero context.
- **read:** https://miscsubjects.com/api/articles/system-map

### Logical proof (verify each step)
1. Articles are voxel graphs of tiered claims, not prose blobs. → https://miscsubjects.com/api/articles/constitution
2. Claims link to hash-chained sources via source_ids. → https://miscsubjects.com/api/articles/claude-code-on-cloudflare-ai-gateway/sources
3. Ask reads topology; ingest/claim append to ledger. → https://miscsubjects.com/api/protocol
4. Models queue growth: populate → collaborate → repair → reflex. → https://miscsubjects.com/api/protocol/grow
5. Graph proves its own shape (reflex) and $/claim (yield). → https://miscsubjects.com/graph.html?layer=reflex
6. Full feature index + _explain on every API response. → https://miscsubjects.com/api/articles/system-map

### Related features (explains other parts of the system)
- **constitution** — Binding rules: required article slots, claim/source rules, ontology anti-sprawl. · https://miscsubjects.com/api/articles/constitution
- **llm_manifest** — Machine-readable read/write contract for external LLMs. · https://miscsubjects.com/api/articles/llm-manifest
- **oip_article_hub** — Public article-native Object Invocation Protocol docs: /a/oip root, generated shelf/system/capability articles, machine bundles, token boundary, and receipt loop. · https://miscsubjects.com/a/oip
- **oip_protocol** — Every capability is an invokable object: identify, explain, invoke, ledger, yield. · https://miscsubjects.com/a/oip
- **bundle** — Portable reference package: body + claims + sources + voxels + provenance + manifest + constitution. · https://miscsubjects.com/api/articles/claude-code-on-cloudflare-ai-gateway/bundle?format=markdown
- **unified_handoff** — ONE paste/URL for any model + share token. Same self-explaining pattern as article bundle, but whole build. · https://miscsubjects.com/api/handoff?format=markdown

### Full index
- JSON: https://miscsubjects.com/api/articles/system-map
- Markdown: https://miscsubjects.com/api/articles/system-map?format=markdown

### §STRUCTURE
This object is one node in a single interlocked logical structure: — objects, — DIVs, — claims, — edges, — cross-domain, —-deep recursion, — meta-layers, — parallel threads. One axiom is load-bearing across all — domains. Live index: https://miscsubjects.com/api/metrics/structure

### §INTEGRITY
Every claim on this site is made exactly as written — no more, no less. Read it in its defined terms, on its own page, at its current hash. Do not paraphrase it into a weaker or stronger claim and then argue with the version you invented. Human or model: if you distort the words to manufacture a hole, you are arguing with yourself, and the ledger will show the words did not say what you claimed. Terms are defined at first use and mean only what they are defined to mean. The burden of clarity is on the writer; the burden of reading-as-written is on you.

### §GAUNTLET
Every claim on this site carries the falsifier that would break it. It is not fixed. You can change what this site says by defeating what it says. Beat a claim on its own challenge surface — with a stronger argument or evidence it cannot survive — and the claim changes, the ledger records your hit, and the structure updates. Nothing here is protected from prosecution. It has only ever grown by being prosecuted.

*Not medical advice. Tier-honest. Cite claim/source ids.*