CCA-F › Wire-Format Reference

Wire-Format Reference

What actually goes to the model, and what actually comes back · 11 scenarios · Messages API

Why this section exists

The exam is scenario-driven, but the confusing part is underneath the scenarios: what exactly goes into the Messages API, and what exactly comes back. Once you can picture the JSON, half the distractors in Domains 1 and 4 stop being plausible — because they describe a field that does not exist, or put a value in the wrong half of the round trip.

So this is not a set of exam scenarios. It is a construct reference. Eleven entries, each with the same four parts, in the same order:

PartWhat it gives you
1 · ScenarioOne paragraph — the situation in plain language.
2 · Client codeThe minimal Python that produces the call.
3 · Request JSONThe body sent to the model, annotated field by field.
4 · Response JSONWhat comes back, annotated, including stop_reason.
11 entries Messages API only Python + raw JSON Domains 1 & 4
Provenance — read this once. The JSON below is written from the current Claude API reference: the field names, types and shapes are documented, not invented. But the values — message IDs, token counts, the exact wording Claude replies with — are illustrative. They are what a call of this shape returns, not a transcript of one specific call. If you want your own real captures, capture.py in this folder runs eight of these scenarios against a live API key and writes the actual request and response bodies to disk. See Capturing the real thing.

How to read any Messages API call

Four facts that explain most of the JSON

1 · The API is stateless. There is no conversation on the server. Every request carries the entire history, and the model's "memory" is just the array you resend. A 40-turn conversation means a 40-turn messages array on turn 40 — which is why context and caching are cost questions, not just capacity questions.

2 · There are three inputs, and their order is fixed. The prompt is assembled as tools → system → messages. That order is why tool definitions sit at the very front of the cache prefix, and why editing your tool list invalidates everything downstream of it.

3 · content is always an array of typed blocks — never a string. On the way in you may write a plain string as a shorthand; on the way back you always get an array. A response can hold a text block and two tool_use blocks at once. content[0].text is the single most common bug in beginner Claude code.

4 · stop_reason is the router. It tells your code what to do next, and the whole agentic loop is a switch over it:

ValueWhat your code must do
end_turnNothing — Claude finished. Exit the loop.
tool_useExecute the requested tool(s), append results, call again.
max_tokensOutput was truncated mid-thought. Raise max_tokens or stream.
stop_sequenceHit one of your custom stop strings.
pause_turnA long server-side tool turn — resend to resume. Do not add "Continue."
refusalDeclined on safety grounds. Check stop_details.
Where thinking fits. On Claude Opus 5 thinking is on by default — omitting the thinking parameter runs adaptive thinking. But display defaults to "omitted", so the reasoning is not readable in the response; pass thinking: {"type": "adaptive", "display": "summarized"} to get a summary back. The practical consequence for every example below: branch on block.type rather than assuming content[0] is your text.
Scope note. Everything here is the Messages API wire format — POST /v1/messages — plus the Batches endpoint. Agent SDK shapes (hooks, subagent spawn payloads) are deliberately excluded: they sit a layer above this one, and mixing them in would blur the exact distinction this page exists to make. Entry 10 is the one place two protocols appear side by side, and that contrast is the point of it.
Entry 01 · the baseline

Plain single-turn message

Scenario. The simplest possible call. One question, one answer, no tools, no system prompt, no history. Everything else on this page is this shape with more fields — so learn where each part lives here and the rest is additive.

Client code

import anthropic
client = anthropic.Anthropic()          # reads ANTHROPIC_API_KEY from the environment

response = client.messages.create(
    model="claude-opus-5",
    max_tokens=1024,
    messages=[{"role": "user", "content": "What is the capital of France?"}],
)

for block in response.content:          # content is a LIST of typed blocks
    if block.type == "text":
        print(block.text)

Request JSON — the body on the wire

POST https://api.anthropic.com/v1/messages
x-api-key: sk-ant-...
anthropic-version: 2023-06-01              ← required on every request, always this value
content-type: application/json

{
  "model": "claude-opus-5",                ← exact ID; never append a date suffix
  "max_tokens": 1024,                      ← REQUIRED. A hard ceiling on the response
  "messages": [
    {
      "role": "user",                      ← must be "user" for the first message
      "content": "What is the capital of France?"
    }                                        a plain string here is shorthand for
  ]                                          [{"type":"text","text":"..."}]
}

Response JSON — what comes back

{
  "id": "msg_01XFDUDYJgAACzvnptvVoYEL",    ← log this; it is what support asks for
  "type": "message",
  "role": "assistant",                     ← always "assistant" on a response
  "model": "claude-opus-5",                ← which model actually served it
  "content": [
    { "type": "text",
      "text": "The capital of France is Paris." }
  ],                                       ← an ARRAY. May also hold thinking / tool_use blocks
  "stop_reason": "end_turn",               ← finished naturally; nothing for you to do
  "stop_sequence": null,
  "usage": {
    "input_tokens": 14,                    ← what you were billed to send
    "output_tokens": 9                     ← what you were billed to receive (5x the input rate)
  }
}
The three fields that matter downstream. content (an array, always), stop_reason (your router), usage (your bill). Almost every later entry changes only what is inside content and what stop_reason says.
Entry 02 · how turns accumulate

System prompt + multi-turn history

Scenario. A third user message in an ongoing conversation, with a persistent instruction. This is where the statelessness becomes concrete: to ask the third question you must resend the first two exchanges, including Claude's own replies.

Client code

response = client.messages.create(
    model="claude-opus-5",
    max_tokens=1024,
    system="You are a terse geography tutor. Answer in one sentence.",
    messages=[
        {"role": "user",      "content": "What is the capital of France?"},
        {"role": "assistant", "content": "Paris is the capital of France."},   # Claude's PRIOR reply
        {"role": "user",      "content": "And its population?"},
    ],
)

Request JSON

{
  "model": "claude-opus-5",
  "max_tokens": 1024,
  "system": "You are a terse geography tutor. Answer in one sentence.",
                                           ← TOP-LEVEL, not a message with role "system"
  "messages": [
    { "role": "user",      "content": "What is the capital of France?" },
    { "role": "assistant", "content": "Paris is the capital of France." },
                                           ← you replay Claude's own words back to it
    { "role": "user",      "content": "And its population?" }
                                           ← "its" only resolves because of the history above
  ]
}

Response JSON

{
  "id": "msg_01BqXR7kL2mNpQrStUvWxYz",
  "type": "message", "role": "assistant", "model": "claude-opus-5",
  "content": [
    { "type": "text",
      "text": "Paris has a population of roughly 2.1 million in the city proper." }
  ],
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 48,                    ← grew: the whole history is re-billed every turn
    "output_tokens": 17
  }
}
The cost shape of a conversation. input_tokens climbs on every turn because you resend everything. A long chat is quadratic in total tokens, not linear — turn N re-bills turns 1…N−1. That is the entire economic case for prompt caching, and the reason context management is a Domain 5 topic rather than a footnote.
Two rules and one exception. The first message must be user. Consecutive same-role messages are legal — the API merges them into one turn. The exception: on Claude Opus 5 you may append a {"role": "system"} message mid-array for an operator instruction that arrives late — it must follow a user message and cannot be messages[0]. That is a cache-preserving trick, not the normal way to set a system prompt.
Entry 03 · the assistant turn that asks

Tool definition → stop_reason: "tool_use"

Scenario. You give Claude a tool and ask something it cannot answer without it. Claude does not call anything — it asks you to, and stops. Nothing has executed yet; the ball is in your court.

Client code

WEATHER_TOOL = {
    "name": "get_weather",
    "description": "Get the current weather for a location. Call this whenever the user "
                   "asks about current conditions, temperature, or whether to bring a coat.",
    "input_schema": {
        "type": "object",
        "properties": {
            "location": {"type": "string", "description": "City and country, e.g. Paris, France"},
            "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
        },
        "required": ["location"],
    },
}

response = client.messages.create(
    model="claude-opus-5", max_tokens=1024,
    tools=[WEATHER_TOOL],
    messages=[{"role": "user", "content": "What is the weather in Paris?"}],
)
print(response.stop_reason)     # "tool_use"

Request JSON

{
  "model": "claude-opus-5",
  "max_tokens": 1024,
  "tools": [                               ← rendered FIRST in the prompt, before system
    {
      "name": "get_weather",               ← how Claude will refer to it
      "description": "Get the current weather for a location. Call this whenever
                      the user asks about current conditions, temperature, or
                      whether to bring a coat.",
                                           ← the selection mechanism. Say WHEN, not just what
      "input_schema": {                    ← snake_case here. (MCP spells it inputSchema — entry 10)
        "type": "object",
        "properties": {
          "location": { "type": "string", "description": "City and country, e.g. Paris, France" },
          "unit":     { "type": "string", "enum": ["celsius", "fahrenheit"] }
                                           ← enum beats prose for a fixed value set
        },
        "required": ["location"]           ← "unit" is optional; Claude may omit it
      }
    }
  ],
  "messages": [
    { "role": "user", "content": "What is the weather in Paris?" }
  ]
}

Response JSON

{
  "id": "msg_01Aq9w8ZfLmNoPqRsTuVwXyZ",
  "type": "message", "role": "assistant", "model": "claude-opus-5",
  "content": [
    { "type": "text",
      "text": "Let me check the current weather in Paris." },
                                           ← optional. Claude may or may not narrate first
    { "type": "tool_use",
      "id": "toolu_01A09q90qw90lq917835lq9",
                                           ← REMEMBER THIS ID. You must echo it back verbatim
      "name": "get_weather",
      "input": { "location": "Paris, France" }
                                           ← already parsed JSON, matching your input_schema.
    }                                        Note "unit" is absent — it was optional
  ],
  "stop_reason": "tool_use",               ← THE SIGNAL: Claude is waiting on you
  "stop_sequence": null,
  "usage": { "input_tokens": 384, "output_tokens": 65 }
                                           ← input jumped: the tool definition is part of the prompt
}
Nothing has run. A tool_use block is a request, not an execution. The model has no ability to reach your function — it emits a structured intention and stops. Every side effect in an agent happens in your code, which is why approval gates live client-side and are actually enforceable.
Watch the token jump. 14 input tokens in entry 01, 384 here. The tool definition is prompt text, billed on every request that carries it — the concrete reason "connect fewer servers" is real advice and not just tidiness.
Entry 04 · the user turn that answers

Returning a tool_result — and ID pairing

Scenario. You ran get_weather("Paris, France") and got "18°C, light rain". Now you hand it back. The surprise for most people: the result goes in a message with role user, not "tool" — and it must quote the exact ID from entry 03.

Client code

tool_use = next(b for b in response.content if b.type == "tool_use")
result   = execute_tool(tool_use.name, tool_use.input)     # your code, your risk

followup = client.messages.create(
    model="claude-opus-5", max_tokens=1024,
    tools=[WEATHER_TOOL],                                  # tools must still be present
    messages=[
        {"role": "user",      "content": "What is the weather in Paris?"},
        {"role": "assistant", "content": response.content},  # the WHOLE content array
        {"role": "user", "content": [{
            "type": "tool_result",
            "tool_use_id": tool_use.id,                    # exact echo
            "content": result,
        }]},
    ],
)

Request JSON

{
  "model": "claude-opus-5",
  "max_tokens": 1024,
  "tools": [ { "name": "get_weather", ... } ],
                                           ← still required. Dropping it 400s: the history
                                             references a tool the request no longer declares
  "messages": [
    { "role": "user", "content": "What is the weather in Paris?" },

    { "role": "assistant",                 ← replay Claude's turn EXACTLY as it came back
      "content": [
        { "type": "text", "text": "Let me check the current weather in Paris." },
        { "type": "tool_use",
          "id": "toolu_01A09q90qw90lq917835lq9",
          "name": "get_weather",
          "input": { "location": "Paris, France" } }
      ] },

    { "role": "user",                      ← "user", NOT "tool". There is no tool role
      "content": [
        { "type": "tool_result",
          "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
                                           ← must match the tool_use id character for character
          "content": "18°C, light rain, wind 12 km/h"
        }                                  ← a string, or an array of blocks for richer results
      ] }
  ]
}

Response JSON

{
  "id": "msg_01CdEfGhIjKlMnOpQrStUvWx",
  "type": "message", "role": "assistant", "model": "claude-opus-5",
  "content": [
    { "type": "text",
      "text": "It's currently 18°C in Paris with light rain and a 12 km/h wind — worth taking an umbrella." }
  ],
  "stop_reason": "end_turn",               ← Claude had what it needed. The loop ends here
  "stop_sequence": null,
  "usage": { "input_tokens": 471, "output_tokens": 31 }
}
The three 400s that come from this one message.
1 · Dropping the assistant turn. Sending the tool_result without replaying the tool_use block that caused it — an orphaned result referencing an ID the conversation never mentioned.
2 · Appending only the text. {"role": "assistant", "content": block.text} silently discards the tool_use block. Append response.content, the whole array.
3 · A mismatched or invented tool_use_id. The pairing is how the API knows which request this answers; there is no positional fallback.
Entry 05 · the whole thing, end to end

A full two-iteration agentic loop

Scenario. Entries 03 and 04 joined up, seen as one flow. This is the agentic loop in its entirety — there is nothing else to it. Two HTTP requests, one tool execution in between, and a stop_reason switch controlling the whole thing.

Client code — the loop is a while over stop_reason

messages = [{"role": "user", "content": "What is the weather in Paris?"}]

while True:
    response = client.messages.create(
        model="claude-opus-5", max_tokens=1024,
        tools=[WEATHER_TOOL], messages=messages,
    )

    if response.stop_reason == "end_turn":
        break                                        # done

    if response.stop_reason == "pause_turn":         # long server-tool turn
        messages.append({"role": "assistant", "content": response.content})
        continue                                     # resend; do NOT add "Continue."

    # stop_reason == "tool_use"
    messages.append({"role": "assistant", "content": response.content})   # whole array

    results = []
    for block in response.content:
        if block.type == "tool_use":
            results.append({
                "type": "tool_result",
                "tool_use_id": block.id,
                "content": execute_tool(block.name, block.input),
            })
    messages.append({"role": "user", "content": results})   # ALL results, ONE message

print(next(b.text for b in response.content if b.type == "text"))

The wire trace — two round trips

┌─ REQUEST 1 ─────────────────────────────────────────────────────────┐
│ messages: [ user:"What is the weather in Paris?" ]                  │
│ tools:    [ get_weather ]                                           │
└─────────────────────────────────────────────────────────────────────┘
                              ↓
┌─ RESPONSE 1 ────────────────────────────────────────────────────────┐
│ content:     [ text, tool_use(id=toolu_01A09…, {location:"Paris"}) ] │
│ stop_reason: "tool_use"          ← your loop does NOT exit           │
│ usage:       in 384 / out 65                                        │
└─────────────────────────────────────────────────────────────────────┘
                              ↓
                 YOUR CODE RUNS THE TOOL — no network call to Anthropic
                 get_weather({"location": "Paris, France"}) → "18°C, light rain"
                              ↓
┌─ REQUEST 2 ─────────────────────────────────────────────────────────┐
│ messages: [ user:"What is the weather in Paris?",                   │
│             assistant:[text, tool_use(id=toolu_01A09…)],   ← replay │
│             user:[tool_result(tool_use_id=toolu_01A09…)]  ← pairing │
│ tools:    [ get_weather ]                          ← still present  │
└─────────────────────────────────────────────────────────────────────┘
                              ↓
┌─ RESPONSE 2 ────────────────────────────────────────────────────────┐
│ content:     [ text:"It's currently 18°C in Paris…" ]               │
│ stop_reason: "end_turn"          ← loop exits                       │
│ usage:       in 471 / out 31     ← request 1's tokens re-billed     │
└─────────────────────────────────────────────────────────────────────┘
Read the usage line twice. 384 + 65 + 471 + 31 for one weather question. The second request re-bills the first — history, tool definitions and all. An agent that takes ten tool-steps pays for the whole transcript ten times. This single fact explains prompt caching, context editing, compaction, and why "return fewer rows" is a cost decision rather than a style preference.
The loop terminates on end_turn, not on an answer. Beginner loops test "did I get text back?" — but a tool_use response often contains text too (the narration in entry 03). Switch on stop_reason; it is the only reliable signal.
Entry 06 · several at once

Parallel tool calls

Scenario. "Compare the weather in Paris, Tokyo and Cairo." Claude does not need the first answer to know it wants the other two, so it emits three tool_use blocks in a single assistant turn. Parallel calling is on by default.

Response JSON — one turn, three requests

{
  "id": "msg_01DeFgHiJkLmNoPqRsTuVwXy",
  "type": "message", "role": "assistant", "model": "claude-opus-5",
  "content": [
    { "type": "text", "text": "I'll check all three cities." },
    { "type": "tool_use", "id": "toolu_01aaa", "name": "get_weather",
      "input": { "location": "Paris, France" } },
    { "type": "tool_use", "id": "toolu_01bbb", "name": "get_weather",
      "input": { "location": "Tokyo, Japan" } },
    { "type": "tool_use", "id": "toolu_01ccc", "name": "get_weather",
      "input": { "location": "Cairo, Egypt" } }
                                           ← three blocks, three DISTINCT ids, one turn
  ],
  "stop_reason": "tool_use",               ← still just "tool_use" — no plural variant
  "usage": { "input_tokens": 402, "output_tokens": 132 }
}

Request JSON — all results in ONE user message

{ "role": "user",
  "content": [
    { "type": "tool_result", "tool_use_id": "toolu_01aaa", "content": "18°C, light rain" },
    { "type": "tool_result", "tool_use_id": "toolu_01bbb", "content": "24°C, clear"      },
    { "type": "tool_result", "tool_use_id": "toolu_01ccc", "content": "35°C, sunny"      }
  ] }                                      ← order does not matter; the ids do the pairing
The silent failure that trains the model out of parallelism. Splitting those three results across three separate user messages is not a hard error — the request usually succeeds. But it teaches Claude, in-context, that this conversation returns results one at a time, and it stops batching calls. You lose the concurrency and never see an error explaining why. All results from one assistant turn go back in one user message.
Execute them concurrently. The three calls are independent by construction — that is why Claude batched them. Running them in a sequential for loop throws away the entire benefit. And if one fails, still return a tool_result for it with is_error: true (entry 09) — never drop a block, or you orphan an ID.
To turn it off: add "disable_parallel_tool_use": true inside tool_choice — e.g. {"type": "auto", "disable_parallel_tool_use": true}. It is a field on tool_choice, not a top-level request parameter.
Entry 07 · forcing the model's hand

tool_choice: three responses, same request otherwise

Scenario. The user says "Hello! How are you today?" — a message that plainly needs no weather tool. Holding everything else constant and changing only tool_choice shows exactly what the parameter controls.

The four values

"tool_choice": { "type": "auto" }                          ← default. Claude decides
"tool_choice": { "type": "any" }                           ← must call SOMETHING, model picks which
"tool_choice": { "type": "tool", "name": "get_weather" }   ← must call THIS one
"tool_choice": { "type": "none" }                          ← may not call anything

Response A — {"type": "auto"}

  "content": [
    { "type": "text", "text": "I'm doing well, thank you! How can I help you today?" }
  ],
  "stop_reason": "end_turn"                ← correctly ignored the tool. No call needed

Response B — {"type": "any"}

  "content": [
    { "type": "tool_use", "id": "toolu_01ddd", "name": "get_weather",
      "input": { "location": "New York, USA" } }
                                           ← forced to call something, so it invented a plausible
  ],                                         argument. The user never mentioned a city
  "stop_reason": "tool_use"

Response C — {"type": "tool", "name": "get_weather"}

  "content": [
    { "type": "tool_use", "id": "toolu_01eee", "name": "get_weather",
      "input": { "location": "London, UK" } }
                                           ← same story: a required argument had to come from
  ],                                         somewhere, so the model supplied one
  "stop_reason": "tool_use"
This is the lesson, and it is an exam favourite. Forcing a tool does not make the call correct — it makes it mandatory. Claude must satisfy required: ["location"], so on a greeting it fabricates a location. Note also that with any or a forced tool, the narrating text block disappears: there is no room for "let me check" when the turn must be a tool call.
When forcing is right. Extraction and classification, where you already know a call is needed and only want the arguments — the tool is being used as a typed output schema rather than as an action. For that, prefer structured outputs (entry 08), which say what you mean. Forcing is also incompatible with programmatic tool calling.
Entry 08 · guaranteed shapes

Structured output — and what a schema violation looks like

Scenario. You need JSON you can hand straight to json.loads() and then to a typed model — no "sometimes it wraps it in a code fence" defensive parsing. Two different mechanisms do this, and they solve different halves of the problem.

Mechanism 1 · output_config.format — constrains the RESPONSE

{
  "model": "claude-opus-5",
  "max_tokens": 1024,
  "output_config": {
    "format": {
      "type": "json_schema",
      "schema": {
        "type": "object",
        "properties": {
          "name":           { "type": "string"  },
          "email":          { "type": "string"  },
          "plan":           { "type": "string"  },
          "demo_requested": { "type": "boolean" }
        },
        "required": ["name", "email", "plan", "demo_requested"],
        "additionalProperties": false      ← REQUIRED on every object. Not optional
      }
    }
  },
  "messages": [ { "role": "user",
    "content": "Extract: Jane Doe (jane@co.com) wants Enterprise and asked for a demo." } ]
}
  "content": [
    { "type": "text",
      "text": "{\"name\":\"Jane Doe\",\"email\":\"jane@co.com\",\"plan\":\"Enterprise\",\"demo_requested\":true}" }
  ],                                       ← still a text block — but guaranteed-valid JSON inside it
  "stop_reason": "end_turn"

Mechanism 2 · strict: true — constrains the TOOL INPUT

  "tools": [ {
      "name": "book_flight",
      "description": "Book a flight to a destination",
      "strict": true,                      ← TOP-LEVEL on the tool. NOT inside tool_choice,
                                             and not inside input_schema
      "input_schema": {
        "type": "object",
        "properties": {
          "destination": { "type": "string" },
          "date":        { "type": "string", "format": "date" },
          "passengers":  { "type": "integer", "enum": [1,2,3,4,5,6,7,8] }
        },
        "required": ["destination", "date", "passengers"],
        "additionalProperties": false
      } } ]

What a violation looks like — the reason strict exists

WITHOUT strict — the schema is a strong hint, and hints are sometimes missed:

  { "type": "tool_use", "name": "book_flight",
    "input": { "destination": "Tokyo",
               "passengers": "two",        ← STRING where the schema said integer
               "date": "March 15" } }      ← not an ISO date; "format":"date" was advisory

  → your code raises on int("two"), mid-agent, at runtime.

WITH strict: true — the decoder is constrained as tokens are generated:

  { "type": "tool_use", "name": "book_flight",
    "input": { "destination": "Tokyo", "date": "2026-03-15", "passengers": 2 } }

  → the invalid shape is not merely rejected. It cannot be produced.
The JSON Schema subset is smaller than you think. Supported: the basic types, enum, const, anyOf, allOf, $ref/$def, the string format keywords, and additionalProperties: false (required). Not supported: recursive schemas, numeric bounds (minimum/maximum), string length bounds, and complex array constraints. Note the workaround visible above — passengers uses enum: [1..8] precisely because maximum: 8 is unavailable.
Two failure modes survive both mechanisms. A stop_reason of max_tokens gives you truncated — therefore invalid — JSON, and a refusal bypasses the schema entirely. Check stop_reason before you parse. Structured outputs are also incompatible with citations (400) and with prefilling.
Entry 09 · when your tool fails

is_error on a tool_result, and what happens next

Scenario. Claude asked for the weather in "Atlantis". Your API returns 404. You have three options — crash, lie, or tell Claude the truth in a form it can act on. Only the third keeps the agent running.

Request JSON — the error result

{ "role": "user",
  "content": [
    { "type": "tool_result",
      "tool_use_id": "toolu_01fff",        ← still required. An error is still an ANSWER
      "content": "Error: no location named 'Atlantis'. Provide a real city and country.",
                                           ← write it for the model to act on, not for a log file
      "is_error": true                     ← snake_case. (MCP spells it isError — entry 10)
    }
  ] }

Response JSON — Claude adapts rather than stalls

  "content": [
    { "type": "text",
      "text": "I couldn't find a location called Atlantis — it isn't a real city. Did you mean Atlanta, in the USA?" }
  ],
  "stop_reason": "end_turn"                ← recovered in one turn, without a retry loop
The error message is a prompt. "Error: 400" tells Claude nothing and it will usually retry the identical call. "No location named 'Atlantis'. Provide a real city and country." names the problem and the recovery, and the model routes on it. This is the Messages API twin of the structured-error MCP server in MCP Skeletons 03 — same principle, one protocol lower.
Never drop the block. Omitting the tool_result for a failed call — because "it didn't work, so there's nothing to send" — leaves a tool_use with no answer, which is a 400 on the next request. Every tool_use gets exactly one tool_result, success or failure.
Two different error channels, easily confused. is_error: true is your tool reporting a failure — HTTP 200, the conversation continues, Claude sees it and adapts. An HTTP 4xx/5xx from /v1/messages is the API itself failing — no response body to hand to Claude, and your SDK raises. The first is a conversation event; the second is an outage.
Entry 10 · two protocols, one call

MCP as the model sees it vs. the MCP server's own wire format

Scenario. The single most clarifying entry on this page. An MCP tool and a hand-written tool look identical to the model — MCP is a protocol between the host and your server, and the model never speaks it. Here are both wire formats for the same tool, stacked.

Side A · the Messages API — using the MCP connector

{
  "model": "claude-opus-5",
  "max_tokens": 1024,
  "mcp_servers": [                         ← Anthropic makes the MCP connection server-side
    { "type": "url",
      "url": "https://weather.example.com/mcp",
      "name": "weather-mcp" }
  ],
  "tools": [
    { "type": "mcp_toolset",
      "mcp_server_name": "weather-mcp" }   ← MUST match a name in mcp_servers
  ],
  "messages": [ { "role": "user", "content": "What is the weather in Paris?" } ]
}
                                           requires header: anthropic-beta: mcp-client-2025-11-20
Both halves or neither. Sending mcp_servers without the matching mcp_toolset entry in tools is a validation error, not a silent no-op. Every server listed must be referenced by exactly one toolset.

Side B · the MCP server's own protocol — JSON-RPC 2.0

→ discovery, at connection time                            the HOST asks; the model is not involved
{ "jsonrpc": "2.0", "id": 1, "method": "tools/list" }

← the server answers
{ "jsonrpc": "2.0", "id": 1,
  "result": { "tools": [
    { "name": "get_weather",
      "description": "Get the current weather for a location.",
      "inputSchema": {                     ← camelCase. The Messages API says input_schema
        "type": "object",
        "properties": { "location": { "type": "string" } },
        "required": ["location"] } } ] } }

→ invocation
{ "jsonrpc": "2.0", "id": 2, "method": "tools/call",
  "params": { "name": "get_weather",
              "arguments": { "location": "Paris, France" } } }
                                           ← "arguments". The Messages API says "input"

← the result
{ "jsonrpc": "2.0", "id": 2,
  "result": { "content": [ { "type": "text", "text": "18°C, light rain" } ],
              "isError": false } }         ← camelCase. The Messages API says is_error

The translation table

ConceptMCP (JSON-RPC)Messages API
Tool's schemainputSchemainput_schema
Call argumentsparams.argumentstool_use.input
Failure flagisErroris_error
Correlationid (JSON-RPC, integer)tool_use_id (string)
Discoverytools/list, at connect timetools[], on every request
Namingget_weathermcp__weather-mcp__get_weather (host-prefixed)
The point. Two protocols, two vocabularies, camelCase on one side and snake_case on the other — and the model sees only the right-hand column. Whether a tool came from an MCP server, from your own code, or from a hosted Anthropic tool is invisible to it: it receives a name, a description and a schema, and emits a tool_use block. Every design decision in MCP Skeletons is about what lands in that right-hand column.
Entry 11 · the other endpoint

Message Batches — envelope, custom_id, retrieval

Scenario. Ten thousand support tickets to classify. Latency is irrelevant; cost is not. The Batches API runs the same Messages requests asynchronously at 50% of standard price — the same request bodies, wrapped in an envelope.

Client code

from anthropic.types.message_create_params import MessageCreateParamsNonStreaming
from anthropic.types.messages.batch_create_params import Request

batch = client.messages.batches.create(requests=[
    Request(custom_id=f"ticket-{t.id}",
            params=MessageCreateParamsNonStreaming(
                model="claude-haiku-4-5", max_tokens=50,
                messages=[{"role": "user", "content": f"Classify: {t.body}"}]))
    for t in tickets
])

while client.messages.batches.retrieve(batch.id).processing_status != "ended":
    time.sleep(60)

for result in client.messages.batches.results(batch.id):
    if result.result.type == "succeeded":
        store(result.custom_id, result.result.message.content[0].text)

Request JSON — POST /v1/messages/batches

{
  "requests": [
    { "custom_id": "ticket-8814",          ← YOUR key. The ONLY way to match results back
      "params": {                          ← a complete, ordinary Messages API body
        "model": "claude-haiku-4-5",
        "max_tokens": 50,
        "messages": [ { "role": "user", "content": "Classify: my order never arrived" } ]
      } },
    { "custom_id": "ticket-8815",
      "params": { "model": "claude-haiku-4-5", "max_tokens": 50,
                  "messages": [ { "role": "user", "content": "Classify: love the new packaging" } ] } }
  ]
}                                          up to 100,000 requests or 256 MB per batch

Response JSON — creation is immediate; the work is not

{
  "id": "msgbatch_013Zva2CMHLNnXjNJJKqJ2EF",
  "type": "message_batch",
  "processing_status": "in_progress",      ← in_progress → ended. Poll this, not the results
  "request_counts": {
    "processing": 2, "succeeded": 0, "errored": 0, "canceled": 0, "expired": 0
  },
  "created_at": "2026-08-23T11:02:14.061162Z",
  "expires_at": "2026-08-24T11:02:14.061162Z",
                                           ← 24h ceiling; most batches finish within the hour
  "results_url": null                      ← populated only once processing_status is "ended"
}

Results — JSONL, one object per line

{ "custom_id": "ticket-8815",              ← NOTE THE ORDER: 8815 came back before 8814
  "result": { "type": "succeeded",
    "message": { "id": "msg_01…", "type": "message", "role": "assistant",
                 "content": [ { "type": "text", "text": "positive" } ],
                 "stop_reason": "end_turn",
                 "usage": { "input_tokens": 19, "output_tokens": 2 } } } }

{ "custom_id": "ticket-8814",
  "result": { "type": "errored",
    "error": { "type": "invalid_request",  ← invalid_request = your bug, do not retry blindly.
               "message": "…" } } }          Anything else is server-side and safe to retry
Results arrive in ANY order. That is the whole reason custom_id exists, and the mistake the exam probes: zipping the results list against your input list by position silently mis-labels your data, with no error anywhere. Key by custom_id, always. And note that each result carries its own type — succeeded, errored, canceled, expired — so a batch that "ended" is not a batch that all worked.
What batches do not change. The params object is an ordinary Messages body — tools, vision, caching, structured outputs all work. What you give up is streaming and latency; what you get is half price. Results stay available for 29 days.

Field glossary — where everything lives

FieldWhereNotes
modelrequest, top levelExact ID, no date suffix. Echoed in the response.
max_tokensrequest, top levelRequired. A ceiling the model is unaware of; hitting it gives stop_reason: "max_tokens".
systemrequest, top levelNot a message. String, or an array of blocks when you need cache_control.
toolsrequest, top levelRendered first, before system. Must stay present for the whole conversation.
tool_choicerequest, top levelauto / any / tool / none. Hosts disable_parallel_tool_use.
strictrequest, on a toolTop-level on the tool object — not in input_schema, not in tool_choice.
output_configrequest, top levelHolds format (JSON schema) and effort. Replaces the deprecated output_format.
contentbothString shorthand accepted inbound; always an array outbound.
tool_use.idresponse blockEcho verbatim as tool_use_id. No positional fallback.
is_errorrequest, on a tool_resultYour tool failed. Not an HTTP error.
stop_reasonresponse, top levelThe loop router. Six values.
stop_detailsresponse, top levelPopulated only when stop_reason == "refusal"; null otherwise. Guard before reading.
usageresponse, top levelinput_tokens, output_tokens, plus cache_creation_input_tokens / cache_read_input_tokens.
custom_idbatches onlyYour correlation key. Results come back unordered.

Every field in a request and a response: what to study

This is the complete list for POST /v1/messages, checked against Anthropic's API reference on 31 October 2026 (API version 2026-10-21). Each row has a study label:

Must know means questions test it directly, so learn what it does and when to use it. Recognise means you should know what it's for if it appears in an option. Skip means it's not on the exam, and you can learn it later if you build with it.

Request: headers

HeaderWhat it doesStudy
x-api-key or Authorization: BearerYour credentialSkip
anthropic-versionWhich API version to useSkip
anthropic-betaTurns on beta featuresRecognise
anthropic-workspace-id, anthropic-user-profile-idWhich workspace or user the request belongs toSkip

Request: top-level body fields

FieldWhat it doesStudy
model (required)Which Claude model answersMust know
max_tokens (required)Maximum length of the reply. The model doesn't know about this limit; reaching it gives stop_reason: "max_tokens"Must know
messages (required)The conversation history, which you resend in full every time because the API keeps no stateMust know
systemThe system prompt: role, rules and toneMust know
toolsThe tools Claude may ask you to runMust know
tool_choiceauto, any, tool (one named tool) or none, plus disable_parallel_tool_useMust know
output_config.formatStructured outputs: the reply must match your JSON schema. Not in the exam guide, which uses a tool with a schema instead (see Exam vs 2026)Recognise
cache_controlPrompt caching, which saves cost and time when the start of the request repeats. The exam guide only expects you to know it existsRecognise
streamSends the reply as it's generated, as a series of eventsRecognise
stop_sequencesStrings that stop generation when they appearRecognise
thinkingLets Claude reason before answering (adaptive on current models)Recognise
output_config.effortlow to max: trades thoroughness against costRecognise
metadata.user_idAn anonymous user ID for abuse trackingSkip
service_tier, speed, inference_geoCapacity tier, fast mode, and the region where the model runsSkip
containerContainer for code execution and SkillsSkip
diagnosticsAsks the API to explain why the cache missedSkip
temperature, top_p, top_kSampling settings. They return an error on API version 2026-10-21, but older material still mentions themRecognise
Beta only: fallbacks, context_management, mcp_servers, task_budgetSwitch model after a refusal; clear or compact old context; connect remote MCP servers; a token budget for an agent loopSkip

Request: block types inside messages[].content

BlockUsed forStudy
textPlain textMust know
tool_result (tool_use_id, content, is_error)Your tool's answer, linked to Claude's call by ID. is_error: true means the tool ran but failedMust know
tool_useClaude's earlier tool call, sent back as part of the historyMust know
documentA PDF or text file (base64, URL or file ID), with optional citationsRecognise
imageA picture (base64, URL or file ID)Recognise
thinking, redacted_thinkingClaude's earlier thinking, sent back unchangedSkip
search_result, container_upload, server-tool result blocksYour own search results to cite, files for the container, earlier built-in tool resultsSkip

Request: fields on a custom tool in tools[]

FieldWhat it doesStudy
nameThe tool's nameMust know
descriptionThe main thing Claude reads when choosing a tool. Vague descriptions cause wrong choicesMust know
input_schemaJSON Schema for the inputs. Used as a form, it's also how you get structured data outMust know
strictGuarantees the inputs match the schema exactly (the shape, not whether the values are correct)Must know
defer_loadingHides the tool until tool search finds it, for when there are too many toolsRecognise
input_examplesExample inputs for the toolRecognise
cache_control, allowed_callers, eager_input_streamingCache breakpoint, programmatic tool calling, streaming large inputsSkip
Built-in tools by typeWeb search, web fetch, code execution, bash, text editor, memory, tool search, computer and browser toolsetsRecognise

Response: top-level fields

FieldWhat it isStudy
contentA list of blocks: text, tool calls, thinkingMust know
stop_reasonWhy Claude stopped. Your loop decides what to do next from this fieldMust know
usageToken counts, used for cost and cachingMust know
id, type, role, modelMessage ID, always "message", always "assistant", the model that answeredRecognise
stop_sequenceWhich of your stop strings was hitSkip
stop_detailsOnly for refusals: category and explanationSkip
container, diagnosticsContainer info, and the reason for a cache missSkip

Response: stop_reason values

ValueMeaning, and what your code doesStudy
tool_useClaude wants a tool run: run it, send a tool_result, and loop againMust know
end_turnClaude has finished: stop the loop and show the answerMust know
max_tokensThe reply hit your length limit: raise max_tokens or continueRecognise
stop_sequenceOne of your stop strings appearedRecognise
pause_turnA long server-side turn was paused: send it back to continueSkip
refusalDeclined for safety reasons: read stop_detailsSkip
model_context_window_exceededThe conversation is too long: trim or compact itSkip

Response: block types in content

BlockWhat it containsStudy
textThe answer, plus citations when documents were citedMust know
tool_use (id, name, input)Claude asking you to run a tool. input is the filled-in form, and id must be echoed back as tool_use_idMust know
thinking, redacted_thinkingClaude's reasoning (often hidden), with a signatureRecognise
server_tool_use and built-in tool result blocksWeb search, web fetch, code execution and tool search calls and their resultsSkip
container_uploadA file created in the containerSkip

Response: fields inside usage

FieldMeaningStudy
input_tokens, output_tokensTokens in and out. Output includes thinkingMust know
cache_creation_input_tokens, cache_read_input_tokensTokens written to the cache, and tokens read from it (much cheaper). If the read count stays at zero, the cache isn't workingRecognise
cache_creation (5-minute and 1-hour breakdown), output_tokens_details.thinking_tokensMore detailed breakdownsSkip
server_tool_use, service_tier, speed, inference_geoBuilt-in tool request counts, capacity tier, speed and region usedSkip

Streaming events (stream: true)

EventWhat it carriesStudy
message_start, content_block_start, content_block_delta, content_block_stop, message_delta, message_stopThe reply in pieces. Deltas carry text, tool input JSON, thinking or citations. message_delta carries the final stop_reason and usageSkip
The short list to learn: model, max_tokens, messages, system, tools (with name, description, input_schema and strict), tool_choice (auto, any, forced), tool_use and tool_result with is_error, stop_reason (tool_use and end_turn), and usage (input_tokens, output_tokens). For guaranteed JSON, the exam expects a tool with a schema, not output_config.format. Prompt caching and streaming are out of scope beyond knowing they exist. Those are about a dozen fields, and they cover nearly every API-level question.

Capturing the real thing

The shapes above are documented, not transcribed. To replace them with genuine captures from your own account:

cd CCA-F/Wire-Format-Reference
pip install anthropic
export ANTHROPIC_API_KEY=sk-ant-...

python capture.py            # all eight capturable scenarios
python capture.py 03 07a     # or just these

It POSTs each scenario with client.messages.with_raw_response.create(...) — the raw HTTP body, not the parsed SDK object — and writes captured/<id>_<name>/request.json and response.json. Total cost is a few cents at the max_tokens it sets.

Entries 04, 05 and 09 need a tool to actually execute between calls, entry 10 needs a live MCP server, and entry 11 is asynchronous — the script says so at the bottom and skips them rather than faking them.

Do this once if you can. Reading a documented shape and seeing your own msg_01… ID come back with your own token counts are different kinds of knowing, and the second one survives exam pressure better.

What this maps to on the exam

EntryDomainThe question shape it answers
1 · Single turnD1 · Messages API substrate"What is in a request/response?"
2 · System + historyD1 · Statelessness"Why do costs grow through a conversation?"
3 · tool_useD1 · Stop reasons · D2 · Tool definition"What does the model return when it wants a tool?"
4 · tool_resultD2 · The contract"Why does this request 400?"
5 · Full loopD1 · Loop mechanics"Walk through an agentic turn"
6 · Parallel callsD2 · Parallel tool use"Claude stopped batching calls"
7 · tool_choiceD2 · Tool choice control"It called the tool with a made-up argument"
8 · Structured outputD4 · Structured outputs"Guarantee parseable JSON"
9 · is_errorD2 · Results & errors"How should a failing tool report?"
10 · MCP both sidesD2 · MCP fundamentals"What does the model actually see from MCP?"
11 · BatchesD5 · Cost & throughput"10k items, latency irrelevant"

Pair this with MCP Skeletons — that page is about what to put in the tool list; this one is about what the wire does with it. Then re-sit Domain 1 sets 2–3 and Domain 2 sets 1 and 3.