# The Anthropic Messages API is one endpoint with a strict block grammar

slug: what-is-the-anthropic-messages-api · https://miscsubjects.com/a/what-is-the-anthropic-messages-api · tags: tooling, api, anthropic-messages, streaming, prompt-caching, tool-use · updated 2026-07-26T03:31:30.982Z

The Anthropic Messages API is a single HTTP endpoint. `POST https://api.anthropic.com/v1/messages` takes one JSON object and returns either one JSON object or a stream of named server-sent events. Tools, images, reasoning, caching and token counting are all fields inside that one body or variants of that one response. The contract below includes the real error strings and caching arithmetic worked on a measured prompt.

## 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.

## One command proves the request envelope

Set the key in an environment variable. Do not put it in the JSON body, a URL, source control or a log.

```bash
export ANTHROPIC_API_KEY="<your Anthropic API key>"

curl -sS https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  --data '{
    "model":"claude-sonnet-4-5",
    "max_tokens":32,
    "system":"Answer with digits only.",
    "messages":[{"role":"user","content":"What is 7 times 6?"}]
  }' | jq '{type,role,content,stop_reason,usage}'
```

Expected shape:

```json
{"type":"message","role":"assistant","content":[{"type":"text","text":"42"}],
 "stop_reason":"end_turn",
 "usage":{"input_tokens":"<integer>","cache_creation_input_tokens":"<integer>",
          "cache_read_input_tokens":"<integer>","output_tokens":"<integer>"}}
```

The token values vary with model and prompt. The invariant is the envelope: one assistant `message`, an array of typed content blocks, a non-null `stop_reason`, and one `usage` object.

## Your key is checked before your version header, so a version mistake hides behind a 401

Three headers are mandatory: `x-api-key`, `anthropic-version`, `content-type: application/json`. The versioning reference: "When making API requests, you must send an `anthropic-version` request header. For example, `anthropic-version: 2023-06-01`." What it does not say is the order of checks. Three calls to `api.anthropic.com` on 2026-07-26, varying only headers:

| Call | `x-api-key` | `anthropic-version` | HTTP | `error.message` |
| --- | --- | --- | --- | --- |
| A | absent | absent | 401 | `x-api-key header is required` |
| B | `sk-ant-invalid` | absent | 401 | `invalid x-api-key` |
| C | `sk-ant-invalid` | `2024-99-99` | 401 | `invalid x-api-key` |

Call C sends a version that does not exist and still gets the key error. Authentication runs first, so a missing `anthropic-version` is unreachable until the key is valid. Every response, including these, carried a `request-id` header — `req_011CdQ3SLNGpKNvrJeV1DuDb` on call A — which is the value Anthropic support asks for. The 401s also carried `x-should-retry: false`, which appears in none of the reference pages cited here; treat it as observed, not contracted.

## Three required fields, and one field that looks like a message but is not

| Field | Required | What it does |
| --- | --- | --- |
| `model` | yes | The model id. An id the endpoint does not serve is rejected. |
| `max_tokens` | yes | "The maximum number of tokens to generate before stopping." `0` writes the prompt cache without generating. Maximums are per model. |
| `messages` | yes | Ordered `{role, content}` turns. Consecutive same-role turns "will be combined into a single turn". A trailing `assistant` message is continued from. |
| `system` | no | The system prompt, at the top level of the body, outside `messages`. String or array of text blocks. |
| `temperature` | no | "Defaults to `1.0`. Ranges from `0.0` to `1.0`." Not deterministic even at `0.0`. |
| `stop_sequences` | no | Strings that halt generation. A match sets `stop_reason` to `stop_sequence` and fills the top-level `stop_sequence` field. |
| `stream` | no | `true` switches the response to server-sent events. |
| `tools` | no | `{name, description, input_schema}` each, where `input_schema` is JSON Schema. |
| `tool_choice` | no | `{"type":"auto"}`, `{"type":"any"}`, `{"type":"tool","name":"x"}`, `{"type":"none"}`. The first three take `disable_parallel_tool_use`, default `false`. |
| `metadata` | no | Only `user_id` is read: "a uuid, hash value, or other opaque identifier". Names, emails and phone numbers are warned against. |
| `thinking` | no | Reasoning configuration. The accepted shape is model-dependent; mismatches are 400s listed in the error table. |

The system prompt is the field people get wrong, because every other major chat API carries it as a message. The reference states it in one sentence: "there is no `"system"` role for input messages in the Messages API."

```json
{"model": "claude-sonnet-4-5", "max_tokens": 1024,
 "system": [{"type": "text", "text": "You are terse."}],
 "messages": [{"role": "user", "content": "What is 7 times 6?"}]}
```

`{"role": "system", "content": "..."}` inside `messages` is not a system prompt.

The same page nonetheless lists `"system"` among the accepted `role` values, and flattening that contradiction would be a lie. On Claude Fable 5, Mythos 5, Opus 4.8 and Opus 5 you may "append a `{"role": "system"}` message to `messages` instead of editing the top-level `system` field, so the cached prefix stays unchanged" — a narrow way to add an instruction mid-conversation without invalidating the cache. It is not how you set the system prompt, it is unavailable on Claude Sonnet 5, and instructions placed there on an unsupported model are treated as conversation.

## Five content-block types carry everything in both directions

```json
{"type": "text", "text": "What is 7 times 6?"}
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "iVBORw0KGgo..."}}
{"type": "tool_use", "id": "toolu_01A", "name": "get_weather", "input": {"city": "Dallas"}}
{"type": "tool_result", "tool_use_id": "toolu_01A", "content": "41C and clear"}
{"type": "thinking", "thinking": "...", "signature": "EqQBCgIYAhIM1gbcDa9GJwZA2b3hGgxBdjrkzLoky3dl1pki..."}
```

| Block | Sent by | What bites |
| --- | --- | --- |
| `text` | user, assistant | Empty text blocks cannot be cached. |
| `image` | user | `source` is `{"type":"base64",...}` or `{"type":"url","url":...}`. `media_type` limited to `image/jpeg`, `image/png`, `image/gif`, `image/webp`. Adding or removing one anywhere invalidates the message cache. |
| `tool_use` | assistant | `input` is a parsed object, not a JSON string. |
| `tool_result` | **user** | `content` is a string or block array; optional `is_error` marks a failed run. |
| `thinking` | assistant | Carries a `signature`. Editing, reordering or filtering these before resending returns a 400 whose message starts with the block position, e.g. `messages.1.content.0`. |

The `tool_result` row is what catches people migrating from other APIs: a tool's answer goes back inside a **user** turn, not a message with a dedicated tool role.

## An unpaired tool_use does not fail one request, it kills every request after it

Three rules, all enforced:

1. Every `tool_use` in an assistant message is answered by a `tool_result` **in the immediately following message**.
2. That message has `role: "user"`.
3. Each `tool_result.tool_use_id` matches a `tool_use.id` from that turn, and those ids are unique within it.

Break rule 1 and the 400 names the message index and the id. The real string, from an agent whose auto-compaction cut a turn in half:

> messages.8: `tool_use` ids were found without `tool_result` blocks immediately after: toolu_01GJ.... Each `tool_use` block must have a corresponding `tool_result` block in the next message.

This is worse than an ordinary validation error because the endpoint is stateless: the client resends the whole history every turn. Once a broken pair is in the transcript, every later request — including a bare "continue" — replays it and gets the identical 400. The session is dead until the client edits its own history.

[[embed:source:s13]]

Rule 3 fails more quietly. A layer that invents missing ids from the tool name produces duplicates the moment the model calls one tool twice in a turn:

[[embed:source:s16]]

A duplicate id is sometimes a 400 and sometimes a silent mispairing, where one tool's output is handed back as another's. Generate ids per call, never per tool name.

The round trip working, captured live on 2026-07-26 — assistant `tool_use`, user `tool_result`, finished answer:

```json
{"content": [{"type": "text", "text": "The weather in Dallas is currently 41°C and clear. It's quite warm with clear skies!"}],
 "stop_reason": "end_turn",
 "usage": {"input_tokens": 195, "output_tokens": 48, "cache_read_input_tokens": 0, "cache_creation_input_tokens": 0}}
```

## Streaming is a nested event grammar, and tool arguments arrive as string fragments

With `"stream": true` the response is `text/event-stream`. Each event has an SSE name and a JSON payload repeating that name in `type`. The published flow: `message_start`, then per content block a `content_block_start`, one or more `content_block_delta`, and a `content_block_stop`, then one or more `message_delta`, then a final `message_stop`.

| Event | Carries | Client action |
| --- | --- | --- |
| `message_start` | Message shell: `id`, `model`, empty `content`, `usage.input_tokens` and cache counts | Record input usage; it is not repeated |
| `content_block_start` | `index` plus the opening block | Allocate a buffer at that index |
| `content_block_delta` / `text_delta` | `delta.text` | Append |
| `content_block_delta` / `input_json_delta` | `delta.partial_json`, a raw fragment | Append to a string buffer; do not parse yet |
| `content_block_delta` / `thinking_delta` | `delta.thinking` | Append |
| `content_block_delta` / `signature_delta` | `delta.signature`, just before the block stops | Store verbatim; it makes the block replayable |
| `content_block_stop` | `index` | Close the buffer; for a tool block, parse now |
| `message_delta` | `delta.stop_reason`, `delta.stop_sequence`, `usage.output_tokens` | These usage counts are cumulative, not per-event |
| `message_stop` | Nothing | End of stream |
| `ping` | Nothing | Ignore. "Event streams may also include any number of `ping` events." |
| `error` | An error object mid-stream, after a 200 | Abort. Example: `{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}` |

One rule has no event of its own: unknown types must be ignored, not treated as failures. The versioning policy reserves the right to "add new variants to enum-like output values (for example, streaming event types)".

Assembling a tool call is what third-party implementations get wrong. The argument object arrives as raw string pieces that are individually invalid JSON:

```text
{"delta":{"type":"input_json_delta","partial_json":"{\"location\":"}}
{"delta":{"type":"input_json_delta","partial_json":" \"San"}}
{"delta":{"type":"input_json_delta","partial_json":" Francisc"}}
{"delta":{"type":"input_json_delta","partial_json":"o, CA\"}"}}
```

Concatenate every `partial_json` for one `index` in arrival order and parse once at `content_block_stop`, giving `{"location": "San Francisco, CA"}`. Parsing early throws. Keying the buffer on anything but `index` corrupts parallel calls.

A complete stream captured on 2026-07-26 from an endpoint answering this format. The argument object arrives in a single fragment here, which is legal — a client must handle both one and many:

```text
event: message_start
data: {"type":"message_start","message":{"id":"msg_aig","type":"message","role":"assistant","model":"@cf/zai-org/glm-4.7-flash","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}}}

event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"chatcmpl-tool-b8d5b5cf4b01d725","name":"get_weather","input":{}}}

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"city\": \"Dallas\"}"}}

event: content_block_stop
data: {"type":"content_block_stop","index":0}

event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"output_tokens":64}}

event: message_stop
data: {"type":"message_stop"}
```

Streaming is a distinct transport and fails on its own. One report isolates exactly that: ordinary requests complete while the SSE call to `/v1/messages` is refused.

[[embed:source:s17]]

## stop_reason is an instruction to the caller, not a status label

It is `null` in `message_start` and non-null everywhere else. Seven values, each implying a different next move.

| Value | Meaning | Next move |
| --- | --- | --- |
| `end_turn` | "a natural stopping point" | Render. Nothing pending. |
| `max_tokens` | "we exceeded the requested `max_tokens` or the model's maximum" | Text is truncated mid-thought. Raise the cap or continue from the partial assistant turn. |
| `stop_sequence` | "one of your provided custom `stop_sequences` was generated" | Read the top-level `stop_sequence` for which one matched. |
| `tool_use` | "the model invoked one or more tools" | Run every `tool_use` block, return all results in one user turn. |
| `pause_turn` | "we paused a long-running turn" | Send the response back as-is to continue. |
| `refusal` | "streaming classifiers intervene to handle potential policy violations" | Read `stop_details.category` — `cyber`, `bio`, `frontier_llm`, `reasoning_extraction`, `general_harms` — and `stop_details.explanation`. |
| `model_context_window_exceeded` | Context window exceeded | Compact or drop history. Retrying unchanged fails again. |

Row two, captured live on 2026-07-26 with `max_tokens` set to 64:

```json
{"content": [{"type": "text", "text": "1.  **Analyze the user's request:** The user is asking \"What is 7 times 6?\". The constraint is \"Answer with digits only\".\n\n2.  **Perform the calculation:** $7 \\times 6$.\n    $7 \\times 6 = 42$.\n\n3."}],
 "stop_reason": "max_tokens", "usage": {"input_tokens": 19, "output_tokens": 64}}
```

The answer is in there and the turn was cut at token 64. A client that renders only on `end_turn` shows nothing.

## input_tokens counts what comes after your last cache breakpoint, not what you sent

| Field | Counts |
| --- | --- |
| `input_tokens` | Only tokens after the last cache breakpoint — "not all the input tokens you sent" |
| `cache_creation_input_tokens` | Tokens written to cache on this request |
| `cache_read_input_tokens` | Tokens served from cache on this request |
| `output_tokens` | Tokens generated |

The identity that always holds: `total_input_tokens = cache_read_input_tokens + cache_creation_input_tokens + input_tokens`.

The committed outputs of Anthropic's prompt-caching notebook make it concrete — the same 187,364-token prompt, three times:

| Run | `input_tokens` | Cache write | Cache read | Wall time |
| --- | --- | --- | --- | --- |
| No caching | 187,364 | — | — | 4.89s |
| First call with a breakpoint | 3 | 187,361 | — | 4.28s |
| Second call, cache warm | 3 | — | 187,361 | 1.48s |

`input_tokens` collapses from 187,364 to 3 once a breakpoint exists, because 187,361 tokens moved into the cache columns. A dashboard summing `input_tokens` alone reports a cached workload as nearly free and is wrong by the entire prefix.

Both cache fields at 0 means nothing was cached, most often because the prompt was under the model's minimum — and no error is returned. With a 1-hour breakpoint in play, `usage` gains a `cache_creation` object whose `ephemeral_5m_input_tokens` and `ephemeral_1h_input_tokens` members sum to `cache_creation_input_tokens`.

## Caching is a field you have to send, and it pays back on the second request

Nothing caches by default. A breakpoint is one field on one block:

```json
{"type": "text", "text": "<20,000 tokens of instructions>", "cache_control": {"type": "ephemeral"}}
```

`ephemeral` is the only type. Default lifetime is five minutes, refreshed free on every hit. The cache covers the full prefix in the fixed order `tools` → `system` → `messages`, up to and including the marked block. Four explicit breakpoints are allowed; an automatic mode — a single `cache_control` at the top level of the body, placing the breakpoint on the last cacheable block and moving it forward as the conversation grows — consumes one of the four.

Below the model minimum the marker does nothing and says nothing: 512 tokens on Claude Opus 5 and Fable 5; 1,024 on Opus 4.8, Sonnet 5, Sonnet 4.6 and Sonnet 4.5; 2,048 on Opus 4.7; 4,096 on Opus 4.6, Opus 4.5 and Haiku 4.5.

The multipliers, quoted: "5-minute cache write tokens are 1.25 times the base input tokens price"; "1-hour cache write tokens are 2 times the base input tokens price"; "Cache read tokens are 0.1 times the base input tokens price."

Worked on a real prompt: a 20,000-token static prefix of tool definitions plus a long system prompt, on Claude Sonnet 4.5 at $3.00/MTok input, $3.75/MTok 5-minute writes, $6.00/MTok 1-hour writes and $0.30/MTok reads, sent fifty times inside one five-minute window:

| Strategy | Write | Read | Total |
| --- | --- | --- | --- |
| No `cache_control` | — | 50 × 20,000 = 1,000,000 tok × $3.00/MTok = $3.0000 | **$3.0000** |
| 5-minute breakpoint | 20,000 tok × $3.75/MTok = $0.0750 | 49 × 20,000 = 980,000 tok × $0.30/MTok = $0.2940 | **$0.3690** |
| 1-hour breakpoint | 20,000 tok × $6.00/MTok = $0.1200 | $0.2940 | **$0.4140** |

The five-minute cache removes $2.6310 of $3.0000, or 87.7 percent. Break-even is the second request: two uncached requests cost 2.00 units of base price, a write plus one read costs 1.25 + 0.10 = 1.35.

The one-hour cache looks worse there and wins the moment the gap between requests exceeds five minutes. Same prefix, one request every six minutes for an hour — eleven requests, five-minute entry expired between every pair:

| Strategy | Cost |
| --- | --- |
| 5-minute breakpoint, expiring each time | 11 writes × $0.0750 = **$0.8250**, zero reads |
| 1-hour breakpoint | 1 write × $0.1200 + 10 reads × 20,000 = 200,000 tok × $0.30/MTok = $0.0600 → **$0.1800** |

Asking for the longer lifetime is one more key: `"cache_control": {"type": "ephemeral", "ttl": "1h"}`. Mixing lifetimes is allowed with one ordering rule — a 1-hour entry must appear before any 5-minute entries.

### Three ways caching silently does nothing

**The field is never sent.** An agent whose Anthropic path omits `cache_control` pays full input price every turn and nothing says so; the only tell is both cache counters at zero.

[[embed:source:s20]]

**A proxy strips it.** Anything in the path can drop unrecognised keys. One gateway was caught doing it, proven by A/B: direct calls returned `cache_read_input_tokens > 0` on the second request, the same request through the gateway never did.

[[embed:source:s14]]

The same failure shows up as a routing bug when markers are injected on only one code path:

[[embed:source:s15]]

**Something in the prefix moves per request.** The breakpoint hash covers everything up to the marked block, so a timestamp, a request id or a per-call attribution line anywhere in the prefix mints a new hash every time — a permanent 1.25x write and never a read. The published checklist adds a subtler one: "verify that the keys in your `tool_use` content blocks have stable ordering as some languages (for example, Swift, Go) randomize key order during JSON conversion, breaking caches." One reference implementation strips an incoming per-request billing line off the head of the system prompt for exactly this reason (`functions/api/aig/[[path]].js`, lines 116–130).

The one-hour lifetime is also not reachable from every client. One operator reading the wire found the marker present and the lifetime absent:

[[embed:source:s19]]

Because placement is manual, proxies exist purely to insert breakpoints for integrations that never expose the request body:

[[embed:source:s21]]

The shape teams converge on afterwards is worth copying: one tool for structured output, parsed `tool_use`, `cache_control: ephemeral` on system and context, exponential backoff on 429.

[[embed:source:s18]]

## count_tokens is free, and the estimators that replace it drift

`POST /v1/messages/count_tokens` takes the same body minus `max_tokens` and returns one integer:

```bash
curl -s https://api.anthropic.com/v1/messages/count_tokens \
  -H "x-api-key: $ANTHROPIC_API_KEY" -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{"model":"claude-sonnet-4-5","system":[{"type":"text","text":"Answer with digits only."}],
       "messages":[{"role":"user","content":"What is 7 times 6?"}]}'   # -> {"input_tokens": 18}
```

It is "free to use but subject to requests per minute rate limits based on your usage tier", and those limits are independent: "Token counting and message creation have separate and independent rate limits. Usage of one does not count against the limits of the other." Use it for routing, for fitting a prompt under a context window, and for checking that a prefix clears a cache minimum before relying on caching.

Because it is optional, gateways often substitute a character estimate. Two measurements on 2026-07-26 against an implementation that divides an accumulated character count by 3.7 (`functions/api/aig/[[path]].js`, lines 445–457). The body above returned 18; sent to `/v1/messages`, it reported `usage.input_tokens` of 19 — low by one, 5.3 percent.

The second shows the error is not stable. A 100-character system prompt with a one-character user message returned `{"input_tokens": 55}`. Counting the system prompt once gives ceil((100 + 1) / 3.7) = 28. Fifty-five is ceil((100 + 100 + 1) / 3.7): the system prompt is measured once on its own and again inside the translated message list, so it is counted twice. Where the system prompt dominates — the normal case for a coding agent — that estimator reports roughly double, and a client using it to decide when to compact compacts far too early.

## The error catalogue, by symptom

| Symptom | HTTP / `error.type` | Cause | Fix |
| --- | --- | --- | --- |
| `x-api-key header is required` | 401 `authentication_error` | No key header | Send `x-api-key`. A bearer token is a different header. |
| `invalid x-api-key` | 401 `authentication_error` | Malformed, revoked or expired key | Replace it. A missing version header stays invisible until this passes. |
| Key works elsewhere, fails here | 403 `permission_error` | "Your API key does not have permission to use the specified resource" | Check organisation and workspace settings. |
| `The requested resource could not be found.` | 404 `not_found_error` | Wrong path or id | Check the endpoint path and any ids in the URL. |
| Large request rejected before the model sees it | 413 `request_too_large` | Over 32 MB on Messages or Token Counting; 256 MB Batch; 500 MB Files | Move bulk content to the Files API. |
| Sudden throttling | 429 `rate_limit_error` | RPM, ITPM or OTPM exceeded | Read `retry-after` and the `anthropic-ratelimit-*` headers. Cache hits are not deducted from rate limits. |
| Every call after one bad turn returns the same 400 | 400 `invalid_request_error` | A `tool_use` with no `tool_result` in the next message | Repair the stored history; the endpoint holds no state to reset. |
| Parallel calls to one tool break | 400 `invalid_request_error` | Duplicate `tool_use` ids | Generate ids per call. |
| `This model does not support assistant message prefill. The conversation must end with a user message.` | 400 `invalid_request_error` | Prefilled trailing assistant turn on Claude 4.6+ | Use structured outputs or `output_config.format`. |
| `` `thinking` or `redacted_thinking` blocks in the latest assistant message cannot be modified. `` | 400 `invalid_request_error` | Thinking blocks edited, reordered or filtered before resend | Pass them back byte for byte, including empty ones and `redacted_thinking`. |
| `"thinking.type.enabled" is not supported for this model.` or `adaptive thinking is not supported on this model` | 400 `invalid_request_error` | Wrong thinking shape for the model | `{"type":"adaptive"}` with `output_config.effort` on Claude 4.7+; `{"type":"enabled","budget_tokens":N}` on 4.5 and earlier. |
| `Overloaded` | 529 `overloaded_error`, or an `error` event mid-stream after a 200 | Capacity | Retry with backoff. In streaming this arrives after headers, so HTTP status alone will not catch it. |

Every error body is JSON with a top-level `error` carrying `type` and `message`, plus a `request_id`:

```json
{"type": "error",
 "error": {"type": "not_found_error", "message": "The requested resource could not be found."},
 "request_id": "req_011CSHoEeqs5C35K2UUqR7Fy"}
```

Match on the SDK's typed exception classes, not on message text — the reference is explicit that "the values within these objects may expand".

## Three other vendors answer this exact shape, and each drops different fields

The same credential-free request body reached all three Anthropic-shaped routes on 2026-07-26 and all returned HTTP 401: DeepSeek returned `Authentication Fails (governor)`; Z.ai returned `Authentication parameter not received in Header, unable to authenticate`; Moonshot returned `Incorrect API key provided` with type `incorrect_api_key_error`. These are route-existence receipts, not compatibility claims.

Because the format is one endpoint with a documented body, other providers implement it and inherit any client that speaks it. DeepSeek documents `https://api.deepseek.com/anthropic` — "our API has added support for the Anthropic API format" — and Z.ai documents `https://api.z.ai/api/anthropic`. Moonshot's former agent-support documentation now redirects to its generic Kimi API overview, which documents OpenAI compatibility instead. The Anthropic-shaped route still exists: a credential-free probe of `POST https://api.moonshot.ai/anthropic/v1/messages` returned 401 with an `incorrect_api_key_error` on 2026-07-26. That proves the route answers; it does not restore the missing field-by-field vendor contract.

Compatible is a range, not a boolean. DeepSeek publishes a field-by-field support matrix, and reading it is the fastest way to see which parts of the format are load-bearing:

| Field | DeepSeek status |
| --- | --- |
| `anthropic-version`, `anthropic-beta` headers | Ignored |
| `max_tokens`, `stop_sequences`, `stream`, `system`, `temperature`, `top_p`, `x-api-key` | Fully Supported |
| `top_k`, `container`, `mcp_servers`, `service_tier` | Ignored |
| `metadata` | `user_id` supported, others ignored |
| `cache_control` on tools, text, `tool_use`, `tool_result` | Ignored |
| Image, document and `search_result` blocks | Not Supported |

Two rows carry the whole caching story from the other side. `anthropic-version` ignored means the version header buys nothing. `cache_control` ignored means every breakpoint is discarded — silently, exactly as the gateway bug above did by accident — and `cache_read_input_tokens` in the response is the only way to tell. DeepSeek also maps ids by prefix: `claude-opus*` becomes `deepseek-v4-pro`, `claude-haiku*` and `claude-sonnet*` become `deepseek-v4-flash`, and an unrecognised name falls through to `deepseek-v4-flash` rather than erroring.

A working configuration that routes an Anthropic-format client to a non-Anthropic model, with a test suite over these behaviours, is in [Claude Code on Kimi, GLM or Grok through your own Cloudflare account](/a/claude-code-on-cloudflare-ai-gateway). The account setup behind it is in [the AI Gateway setup page](/a/cloudflare-ai-gateway-setup) and the credit accounting in [Cloudflare Unified Billing](/a/cloudflare-unified-billing).

## Fresh wire checks reproduce the contract

The complete harness is the same sequence printed below, run at 05:15–05:16 UTC on 2026-07-26. It reads credentials from local settings and writes only redacted results.

| Check | Fresh result |
| --- | --- |
| Non-streaming `POST /v1/messages`, `max_tokens: 64` | HTTP 200; 507 response bytes in 1.649598 s; `stop_reason: "max_tokens"`; 19 input and 64 output tokens |
| `POST /v1/messages/count_tokens` on the same prompt | HTTP 200; 19 response bytes in 0.041256 s; 18 input tokens — one below message usage |
| Forced streamed `get_weather` call | HTTP 200; 1,491 response bytes in 1.201516 s; 11 SSE frames; compacting six `input_json_delta` fragments produced `{"city":"Dallas"}` |
| No key and no version | HTTP 401; `x-api-key header is required`; `request-id` present; `x-should-retry: false` |
| Invalid key with no version | HTTP 401; `invalid x-api-key` |
| Invalid key with an invalid version | HTTP 401; `invalid x-api-key` — authentication still won the check order |

The exact local commands were `node /private/tmp/codex-messages-api/measure.mjs` and `node /private/tmp/codex-messages-api/measure-headers.mjs`. Neither prints a credential.

## Method for the six measurements above

All six were captured on 2026-07-26. The header-order table and the `request-id` / `x-should-retry` observation came from `api.anthropic.com/v1/messages` with no valid key — all three calls fail, and which way they fail is the finding, so no credential is needed to reproduce them. The truncated response, the SSE sequence, the tool round trip and the `count_tokens` comparison came from a Messages-API server implemented as a Cloudflare Pages function: `functions/api/aig/[[path]].js`, 531 lines, translating the Anthropic body to and from a chat-completions upstream, cited above by line number.

To rerun any of them, point `BASE` at `https://api.anthropic.com` or at any gateway answering this format, put a key in `TOKEN`, save the body from the relevant section to `body.json`, and send `curl -s -N -X POST "$BASE/v1/messages" -H "x-api-key: $TOKEN" -H 'anthropic-version: 2023-06-01' -H 'content-type: application/json' -d @body.json`.

## Sources

1. Messages API reference — https://platform.claude.com/docs/en/api/messages
2. API versioning — https://platform.claude.com/docs/en/api/versioning
3. Streaming Messages — https://platform.claude.com/docs/en/build-with-claude/streaming
4. Prompt caching — https://platform.claude.com/docs/en/build-with-claude/prompt-caching
5. Tool use overview — https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview
6. Stop reasons and fallback — https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons
7. Token counting — https://platform.claude.com/docs/en/build-with-claude/token-counting
8. Errors — https://platform.claude.com/docs/en/api/errors
9. DeepSeek Anthropic API compatibility — https://api-docs.deepseek.com/guides/anthropic_api/
10. Use Claude Code with Z.ai models — https://docs.z.ai/scenario-example/develop-tools/claude
11. Kimi API overview — https://platform.kimi.ai/docs/api/overview
12. Anthropic prompt-caching notebook — https://github.com/anthropics/claude-cookbooks/blob/main/misc/prompt_caching.ipynb
13. Compaction can emit an unpaired tool_use, bricking the session with a permanent Anthropic 400 — https://github.com/valkyriweb/pi-mono/issues/406
14. feature: cache_control stripped when proxying to AWS Bedrock (Anthropic prompt caching broken) — https://github.com/agentgateway/agentgateway/issues/2628
15. Prompt caching may be silently inert for OpenRouter-routed agents (cache_control only injected on native-Anthropic path) — https://github.com/bobmatnyc/trusty-tools/issues/3388
16. Anthropic: synthesized tool_use IDs collide on parallel calls to the same tool — https://github.com/go-steer/core-agent/issues/367
17. [BUG] ConnectionRefused on /v1/messages streaming while simple API requests succeed (Windows, Bun) — https://github.com/anthropics/claude-code/issues/76802
18. ClaudeClient: /v1/messages with tool_use — https://github.com/amadoug2g/Sweep/issues/4
19. Comment on "Pro Max 5x quota exhausted in 1.5 hours" — 1h cache TTL — https://news.ycombinator.com/item?id=47745409
20. Comment on "Zerostack – a coding agent in pure Rust" — missing cache_control — https://news.ycombinator.com/item?id=48167243
21. Show HN: Autocache – Cut Claude API costs 90% (for n8n, Flowise, etc.) — https://news.ycombinator.com/item?id=45518040
22. A Messages-to-Chat-Completions translation layer — https://github.com/redacted/claude-code-cloudflare-gateway
23. Independent A/B measurement: cache_control direct to Bedrock versus through a proxy — https://github.com/agentgateway/agentgateway/issues/2628
24. First-party wire receipt: message creation and count_tokens, 2026-07-26 — https://miscsubjects.com/api/articles/what-is-the-anthropic-messages-api
25. First-party wire receipt: streamed forced tool call, 2026-07-26 — https://miscsubjects.com/api/articles/what-is-the-anthropic-messages-api
26. First-party wire receipt: authentication precedes version validation, 2026-07-26 — https://miscsubjects.com/api/articles/what-is-the-anthropic-messages-api
27. First-party compatibility probes for DeepSeek, Z.ai and Moonshot, 2026-07-26 — https://miscsubjects.com/api/articles/what-is-the-anthropic-messages-api


---

# Protocol API Structure: REST Surface, Objects, and Phase Machine

slug: protocol-api-structure · https://miscsubjects.com/a/protocol-api-structure · tags: system, protocol, api · updated 2026-07-17T02:41:01.604Z

## What this article is

This document describes the live REST surface and phase machine for miscsubjects.com.  
It is system documentation, not a compound catalogue entry.

## Who claims what

The build itself defines the contract.  
GET /api/protocol returns the authoritative machine map.  
API_QUICKMAP.md and PROTOCOL_SPEC.md are static mirrors of that contract.

## What is known

GET /api/protocol exposes the endpoint list, body schemas, and phase definitions.  
Two planes exist: /api/articles for CRUD and sub-resources, and /api/protocol for phase operations.  

Claims live in article.meta.claims[]. Sources live in meta.sources[] with prev/hash chain. All writes are append-only.  

POST /api/protocol/draft validates tiers, optionally verifies source URLs, and hash-chains sources.  
POST /api/protocol/populate ingests sources into an article without rewriting the body.  
POST /api/protocol/collaborate lets Kimi or Gemini append 1–3 claims.  
POST /api/protocol/score recomputes claim.weight and applies status:cut when below threshold.  
GET /api/protocol/next?role=writer hands out one open task atomically.  
POST /api/protocol/run executes one scheduler tick inside the 100-second request limit.  
GET /api/matrix/gaps lists missing roots and cross cells. POST /api/matrix/seed fills from the canonical catalog.  
Webhook POST /api/articles/{slug}/webhook accepts atomic appends of kind:claim|source|widget.

## What we do not know

Not every phase listed in PROTOCOL_SPEC.md has a deployed cron worker.  
Some phases still require manual POST /api/protocol/grow or dispatch tools.  
Rate limits and per-tenant quotas on gateway model calls are environment-dependent and not shown in the public contract.

## Limitations

Protocol slugs are immutable. Hard DELETE is blocked. Corrections use PATCH status:retracted or new revisions.  
Every phase transition must finish inside Cloudflare’s ~100-second cap. Batch work uses grow batch or cron ticks.

## Disclaimer

This API map is a research-ledger transport layer only. It grants no medical authority.

