Anthropic Messages API

SMG serves the Anthropic Messages API at /v1/messages and counts input tokens at /v1/messages/count_tokens. What happens to a request depends on the backend: with gRPC workers SMG implements the API itself, with HTTP workers it forwards the request to an engine that implements the Messages API, and with the Anthropic backend it forwards the request to the Anthropic API.


Endpoints

Method Path Description
POST /v1/messages Create a message. Set "stream": true to receive Server-Sent Events.
POST /v1/messages/count_tokens Count the input tokens of a Messages request without generating.

Both endpoints go through the same authentication and admission control as the other inference endpoints.


Supported Backends

Backend Configure with /v1/messages /v1/messages/count_tokens
gRPC workers grpc:// worker URLs SMG renders, tokenizes, and parses (details) Counted by SMG itself (details)
ZMQ workers ipc:// worker URLs Same as gRPC workers Same as gRPC workers
HTTP workers http:// or https:// worker URLs Forwarded to the worker Forwarded to one worker
HTTP PD --pd-disaggregation with HTTP workers Prefill/decode dual dispatch Forwarded to one prefill worker
Anthropic API --backend anthropic Forwarded to the Anthropic API, with an optional SMG-run MCP tool loop 501 Not Implemented

HTTP workers must implement the Messages API themselves; SMG forwards the request without translating it.

In IGW mode (--enable-igw), SMG picks the backend per request from the workers that serve the requested model. A model served by an external Anthropic worker goes to the Anthropic API backend (see External Providers). The other external providers answer /v1/messages with 501.

Token counting on gRPC and ZMQ workers applies since v1.13.0 (v1.12.0 and earlier answer 501 Not Implemented); see Backend Support.


Authentication

SMG's own authentication is separate from the credentials it passes to backends:

Hop Headers Behavior
Client to SMG Authorization: Bearer <key> Checked when --api-key or --tenant-api-key is set. x-api-key does not authenticate to SMG. A missing or unknown bearer token gets 401 Unauthorized.
SMG to HTTP workers Authorization The client's header is forwarded with the other allowlisted headers; x-api-key is not. A matched gateway key is removed at authentication, and the worker's own configured key, when it has one, is sent instead. See Authentication for worker API keys.
SMG to the Anthropic API x-api-key, Authorization The client's own key headers are forwarded as sent. When the client sends neither, SMG sends the worker's stored key as x-api-key, with anthropic-version: 2023-06-01 added when the client sent no version header.

Anthropic SDKs send their key in x-api-key, which the Anthropic API backend passes upstream. When gateway authentication is on, clients must also send the gateway key as Authorization: Bearer <key>. The gateway key never reaches Anthropic: it is removed from Authorization at authentication, and from x-api-key too when sent there, while the client's own Anthropic key in x-api-key passes through.


Create a Message

POST /v1/messages

Request Body

Field Type Required Description
model string Yes Model ID. Must not be empty.
messages array Yes At least one message, each with a role (user, assistant, or system) and content (a string or an array of content blocks).
max_tokens integer Yes Maximum number of tokens to generate. 0 is accepted; the response depends on the backend — see max_tokens of 0.
system string or array No System prompt, as a string or an array of text blocks.
stream boolean No Stream the response as Server-Sent Events.
temperature number No Sampling temperature, 0 to 1.
top_p number No Nucleus sampling, greater than 0 and at most 1.
top_k integer No Sample only from the top K tokens, 1 to 2147483647. Unlike Chat Completions and Responses, where top_k is signed and -1 disables it, this field is unsigned and has no disable value: a negative value is refused with 400.
stop_sequences array of strings No Sequences that stop generation.
tools array No Tool definitions; see Tool Use.
tool_choice object No {"type": "auto"}, {"type": "any"}, {"type": "tool", "name": "..."}, or {"type": "none"}. Every value except none requires tools, and tool must name one of them.
thinking object No {"type": "enabled", "budget_tokens": N}, {"type": "adaptive"}, {"type": "disabled"}, or {"type": "between_tools"} (no thinking up front; the model may think between its tool calls). enabled and adaptive also take display (summarized, omitted, or updates). between_tools takes type alone: a request that adds any other field, display or budget_tokens included, is refused with 400 (thinking_between_tools_takes_no_other_field), and the error message names each extra field.
output_config object No Output configuration. format asks for structured output, a JSON answer held to a schema; see Structured Output. effort, a string or a number taken as its text, is the reasoning effort the prompt is rendered with on gRPC and ZMQ workers. Other keys are kept and forwarded like unmodeled fields.
output_format object No The structured output format under its earlier top-level name, with the same shape as output_config.format; see Structured Output. When both are sent, output_config.format wins.
metadata object No Request metadata (user_id).
service_tier string No auto or standard_only.
container object No Container for code execution (beta).
mcp_servers array No MCP servers for the request (beta). Required when tools has an mcp_toolset entry; see MCP Tools.
thread object No Open or continue a message thread (beta): {"type": "create"} stores the request and its answer under the answer's id, and {"type": "continue", "previous_message_id": "msg_..."} sends only the messages since that answer. Needs the anthropic-beta: message-threads-2026-08-12 header; without it, a parsed body carrying thread is refused with 400 (thread_beta_required). See Message Threads.
rid string No Extension: request ID passed to the backend for log correlation. On a message thread turn, SMG replaces it with an ID it mints; see Request IDs on Thread Turns.

SMG validates the body before routing and answers 400 when a required field is missing or a rule above is broken. The one exception is a body that the HTTP router streams through unparsed; see HTTP and PD Workers. Fields SMG does not model, such as context_management, are kept and forwarded to HTTP workers and the Anthropic API.

Content blocks in messages may be text, image, document, tool_use, tool_result, thinking, redacted_thinking, server_tool_use, search_result, web_search_tool_result, tool_search_tool_result, tool_reference, mcp_tool_use, or mcp_tool_result. mcp_tool_use and mcp_tool_result replay the tool exchange of an earlier MCP answer; see Replaying MCP Blocks for what each backend does with them. A system-role message inside messages is accepted, because some clients send one mid-conversation.

A block whose type is not on this list, or any block SMG cannot read, is refused with 400; so is a content that is neither a string nor an array of blocks. The error message names the failure by its position and its own reason:

  • an unknown type: messages[1].content[0].type: unknown variant `container_upload`, ..., with the accepted types listed
  • a missing required field: messages[0].content[0]: missing field `tool_use_id`
  • a content of the wrong JSON type: messages[0].content: invalid type: null, expected a string or an array of content blocks

Blocks in a system prompt and in a tool_result's content are refused the same way. The error envelope's param also carries the position, as a path ending in the field at fault, such as messages[0].content[0].tool_use_id; see Errors.

An image block's source is one of three types: base64 (base64 data with its media_type), url (a URL or data: URL), or file, which names a file uploaded through Anthropic's Files API by its file_id. A document block's source is one of five: base64, text, url, content (a string or an array of content blocks), or file. A source of any other type is refused with 400 like any other unreadable block, with the accepted types listed.

Every source on these lists passes validation, whatever the backend. HTTP workers and the Anthropic API receive a file source exactly as sent, like the rest of the request; resolving the file_id is theirs — the Anthropic API reads the file from its Files API. For gRPC and ZMQ workers, SMG renders the prompt on the gateway, which has no Files API to read from: a file-source image, or a file-source document outside a tool_result, is refused with 400 naming the block; see gRPC and ZMQ Workers.

A search_result block — a search result the request injects — carries a source, a title, a content array, and optionally cache_control and a citations configuration such as {"enabled": true}. Its content holds only text blocks, each with its type, its text, and optionally cache_control and a citations list.

An item of a search result's content sent without its type is read as a text block, and SMG writes "type": "text" on every item when it serializes the request for an HTTP worker or the Anthropic API. An item whose type is anything other than text is refused with 400, named by its position like any other unreadable block. The same shape and rules apply to a search_result block inside a tool_result's content.

Example Request

curl http://localhost:30000/v1/messages \
  -H "Content-Type: application/json" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
    "model": "meta-llama/Llama-3.1-8B-Instruct",
    "max_tokens": 1024,
    "system": "You are a concise assistant.",
    "messages": [
      {"role": "user", "content": "What is the meaning of life?"}
    ]
  }'
curl http://localhost:30000/v1/messages \
  -H "Content-Type: application/json" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
    "model": "claude-sonnet-4-20250514",
    "max_tokens": 1024,
    "messages": [
      {"role": "user", "content": "What is the meaning of life?"}
    ]
  }'

Response

{
  "id": "msg_abc123",
  "type": "message",
  "role": "assistant",
  "content": [
    {"type": "text", "text": "There is no single answer..."}
  ],
  "model": "meta-llama/Llama-3.1-8B-Instruct",
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 27,
    "output_tokens": 112,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 0
  }
}

With gRPC workers SMG builds this response (details). With HTTP workers and the Anthropic API it comes from the backend.

max_tokens of 0

A max_tokens of 0 passes validation. On gRPC and ZMQ workers, SMG answers the request itself without generating: an empty message with stop_reason of max_tokens, whose usage reports the prompt's token count, counted exactly as /v1/messages/count_tokens counts it. No worker takes part, and no tenant rate-limit budget is reserved, though the request still counts in the gateway's request metrics.

{
  "id": "msg_abc123",
  "type": "message",
  "role": "assistant",
  "content": [],
  "model": "meta-llama/Llama-3.1-8B-Instruct",
  "stop_reason": "max_tokens",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 27,
    "output_tokens": 0,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 0
  }
}

With "stream": true, the answer is a three-event stream: message_start with the empty message — its usage already carries the prompt's token count — then message_delta with the stop reason and the usage counts, and message_stop.

A request whose prompt cannot be counted is refused as /v1/messages/count_tokens refuses it — an unknown model gets 404, a request that does not render gets 400, and the other refusals under Backend Support apply unchanged. When the model's workers advertise a context window, a prompt with more tokens than the smallest advertised window is refused with 400 context_length_exceeded, as a generating request would be.

On HTTP and PD workers, SMG refuses max_tokens: 0 with 400 (code max_tokens_zero_not_relayed) before any worker sees the request: the relay forwards a Messages request as sent and renders no prompt, so it cannot build the empty message. As with the other request rules, a body the HTTP router streams through unparsed reaches the worker unvalidated.

The Anthropic API backend forwards the request like any other and relays the upstream response.

In IGW mode, a max_tokens: 0 request for a model served over both gRPC and HTTP always goes to a gRPC router, so it gets the empty message; a model only HTTP workers serve gets the relay's 400.

Tool Use

Define each tool with a JSON Schema input_schema:

{
  "tools": [
    {
      "name": "get_weather",
      "description": "Get the current weather for a city",
      "input_schema": {
        "type": "object",
        "properties": {"city": {"type": "string"}},
        "required": ["city"]
      }
    }
  ],
  "tool_choice": {"type": "auto"}
}

A tool call comes back as a tool_use block, with stop_reason set to tool_use:

{
  "content": [
    {
      "type": "tool_use",
      "id": "toolu_0b7e5f1c9a2d4e6f8a1b3c5d",
      "name": "get_weather",
      "input": {"city": "Paris"}
    }
  ],
  "stop_reason": "tool_use"
}

Return the result in the next user message as a tool_result block whose tool_use_id is the id of the call.

Structured Output

Ask for a JSON answer with output_config.format, which names a JSON schema the model's text answer must fit:

{
  "output_config": {
    "format": {
      "type": "json_schema",
      "schema": {
        "type": "object",
        "properties": {"city": {"type": "string"}},
        "required": ["city"]
      }
    }
  }
}

json_schema is the only type: a format with another type or without schema is refused with 400, as is a schema that is not a JSON object (output_format_schema_not_an_object). The same format is also accepted under its earlier top-level name, output_format; when both fields are sent, output_config.format wins.

On gRPC and ZMQ workers, SMG enforces the schema with constrained decoding: the engine is held to the schema as it generates, so the returned text block is JSON that fits it. The engine needs a grammar backend (TokenSpeed and TensorRT-LLM must have one switched on — see Enforcement). Three exceptions:

  • A tool_choice that forces a tool call — any when at least one custom tool is declared, or tool naming one of the custom tools — takes precedence: the turn ends in a tool call, not a text answer, so the format constrains nothing.
  • On a model the hf Symphony table reads, a format the table has no tag for is refused with 400 (invalid_parser_configuration), unless the worker takes the whole-turn grammar described there.
  • MLX workers do not support constrained decoding and refuse a request that asks for a format with 400 (invalid_request_parameters).

HTTP workers and the Anthropic API receive output_config and output_format as sent; enforcing the format is left to them.


Streaming

Set "stream": true to receive the response as Server-Sent Events. Each event has an event: line naming its type and a data: line with the JSON payload. The stream ends with message_stop; there is no data: [DONE] line.

Event Payload
message_start The message, with empty content
content_block_start A new content block at index: thinking, text, or tool_use
content_block_delta A text_delta, thinking_delta, or input_json_delta (a fragment of the tool input JSON) for the block at index
content_block_stop The block at index is complete
message_delta stop_reason, stop_sequence, and the final usage
message_stop End of the message
ping Keep-alive; relayed from upstream, never sent by the gRPC path
error A failure after the stream started; see Errors

HTTP workers and the Anthropic API produce their own events, which SMG relays; the Anthropic API can send block and delta types beyond this table. A gRPC worker's stream for a short text answer looks like this:

event: message_start
data: {"type":"message_start","message":{"id":"msg_abc123","type":"message","role":"assistant","content":[],"model":"meta-llama/Llama-3.1-8B-Instruct","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0,"cache_creation_input_tokens":0,"cache_read_input_tokens":0}}}

event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"There is no single answer"}}

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

event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":112,"input_tokens":27,"cache_creation_input_tokens":0,"cache_read_input_tokens":0}}

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

Message Threads

Message threads (beta) let a client send only each turn's new messages: SMG keeps the conversation's earlier turns in its own memory and rebuilds the whole conversation on every continue. SMG resolves the thread before it selects a backend, so threads behave the same on every backend, and a backend — the Anthropic API included — always receives a plain request carrying the whole conversation, without the thread field.

Every thread turn, create and continue alike, must name the message-threads beta in its anthropic-beta header, alone or in a comma-separated list with other betas:

anthropic-beta: message-threads-2026-08-12

The header tells SMG to read the body before routing: the HTTP router buffers a request that names the beta, at any body size and under any retry setting, so SMG can rebuild the turn from the body and store its answer. A request whose parsed body carries a thread field without the header is refused with 400 (thread_beta_required) before any backend runs; see Thread Errors.

A request with thread: {"type": "create"} opens a thread. It is a complete request — the whole conversation so far, with its system, tools, and every other field — and SMG stores it with its answer under the answer's id:

curl http://localhost:30000/v1/messages \
  -H "Content-Type: application/json" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: message-threads-2026-08-12" \
  -d '{
    "model": "meta-llama/Llama-3.1-8B-Instruct",
    "max_tokens": 1024,
    "system": "You are a concise assistant.",
    "messages": [
      {"role": "user", "content": "What is the meaning of life?"}
    ],
    "thread": {"type": "create"}
  }'

A request with thread: {"type": "continue", "previous_message_id": "msg_..."} names the id of a stored answer and carries only the messages since that answer. SMG rebuilds the conversation — the create turn's system and tools, every stored turn's messages and answer, then the new messages — checks the fixed fields against the create turn's, and routes the result as a plain request:

curl http://localhost:30000/v1/messages \
  -H "Content-Type: application/json" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: message-threads-2026-08-12" \
  -d '{
    "model": "meta-llama/Llama-3.1-8B-Instruct",
    "max_tokens": 1024,
    "messages": [
      {"role": "user", "content": "And in one sentence?"}
    ],
    "thread": {"type": "continue", "previous_message_id": "msg_abc123"}
  }'

Always take previous_message_id from the id of the answer just received: when a backend's answer arrives under an id that already names a stored turn, SMG reissues the answer under a fresh id, in the store and in what the client reads — the body of a non-streaming answer, the message_start event of a streamed one. An id may be continued more than once — each continue forks the thread from that answer — and a second continue of the same id is never refused: SMG does not answer the Anthropic API's thread_already_continued error.

What a Continue Request Sends

Fields Rule
system, tools Must be omitted: the thread keeps the create request's. A continue carrying either is refused with 400 (thread_continue_carries_create_fields).
model, tool_choice, thinking, mcp_servers, container, output_config, output_format, and every field SMG does not model (such as context_management) Fixed: each must repeat exactly what the create request sent. Changing a value, adding a field the create request did not send, or dropping one it did is refused with 400 (thread_fingerprint_mismatch), and the error message names the changed fields.
messages The messages since the answer being continued — at least one. In a tool loop, a tool_result block that opens the continue request answers the stored answer's tool_use call; tool pairing is checked on the rebuilt conversation.
max_tokens, temperature, top_p, top_k, stop_sequences, metadata, stream, service_tier, rid Free: may change on every turn.

Storage and Lifetime

Turns live in the gateway process's own memory; threads do not use the history backend (--history-backend) that stores Responses. A restart loses every thread, and in a deployment with several gateway instances, a continue finds its thread only on the instance that served the earlier turns.

The store keeps at most --history-memory-max-responses turns (default 10,000) across all threads and tenants, each for --history-memory-retention-secs (default 86400, one day) after it was written. These are the memory history backend's bounds, and they govern the thread store under every --history-backend. Both bounds are checked on every write, the oldest turns evicted first; a retention of 0 keeps a turn until the count bound drops it. A thread whose create turn is gone can no longer be continued.

The Anthropic API deletes a thread no more than an hour after its last use, the reference for choosing a deployment's bounds: a retention of 3600 keeps threads within that hour.

A turn is stored when its answer is a 200 message, streamed or not. A non-streaming answer is read back whole and stored under its id. A streamed answer is stored from its own events: SMG reads them on their way to the client, folds the content blocks and the final message_delta into the complete message, and writes the turn when message_stop arrives. The stream the client receives is unchanged, except that a reissued answer's message_start event is rewritten to carry the fresh id. The turn can be continued once its stream completes: a continue sent while the answer still streams is answered 404 (thread_not_found).

An error response, an error event in the stream, and a stream that ends, fails, or is dropped before its message_stop leave the turn unstored. So does an answer SMG cannot read: a non-streaming body that is not a JSON message, stream events it cannot parse, or a streamed tool call whose input deltas do not add up to a JSON document. An answer too large for SMG to keep is also unstored, whether read back whole or assembled from its stream; for a streamed answer the bound is on content blocks as well as bytes. None of this changes what the client receives, with one exception: a non-streaming answer SMG cannot read back whole — over the size bound, or its body failing mid-read — is not relayed, and the request is answered 500 (thread_answer_unreadable) instead. An unstored turn's answer cannot be continued: the next continue is answered 404, and the client replays the conversation in a new create request (see Thread Errors).

An answer with a content block of a kind SMG does not model is still stored, with the block exactly as the backend wrote it. A continue replays each stored answer as an assistant message, so it needs every stored block in a form a request can carry — one of the content block types a request accepts. A continue over an answer holding a block a request has no form for is refused with the same 404.

Turns are scoped to the tenant that created them, under the same rule as stored Responses (see Tenant Scope): another tenant's previous_message_id is answered exactly as an unknown one, and a turn stored by a caller with no tenant identity can be continued by every caller.

Thread Errors

A thread turn that SMG cannot serve is refused before any backend runs:

Status Code Cause
400 thread_beta_required The body has a thread field but the request does not name the message-threads beta in its anthropic-beta header; create and continue turns alike. See the header requirement.
404 thread_not_found Nothing can be continued from previous_message_id: an unknown id, an evicted or expired turn, another tenant's thread, a turn that was never stored (an error response, a stream cut before its message_stop) or not stored yet (an answer still streaming), a stored answer with a content block a request has no form for, or new messages the rebuilt conversation does not accept, such as a tool_result that matches no stored tool_use.
400 thread_fingerprint_mismatch The continue request changed a fixed field; the error message names the fields.

All three carry their code in the X-SMG-Error-Code header; thread_not_found and thread_fingerprint_mismatch carry it in the body's error.details.error_code too:

{
  "type": "error",
  "error": {
    "type": "not_found_error",
    "message": "thread: no thread can be continued from `msg_abc123`; send the whole conversation in a new create request",
    "details": {"error_code": "thread_not_found"}
  },
  "request_id": "..."
}

Threads are best effort, and thread_not_found is the normal way one ends. Retrying the continue as sent changes nothing: replay the whole conversation — every turn's messages and answers — in a new create request, as the Anthropic SDKs' thread helper does on its own.

Request IDs on Thread Turns

On a thread turn, the rid in the body never becomes the message's id: SMG replaces it with a fresh msg_ id before routing, so a repeated client rid cannot make two turns share an id. The client's rid still comes back as the answer's request-id header — the header the Anthropic SDKs read the request id from — when it is 1 to 128 visible-ASCII characters and the response does not already carry that header.


Count Tokens

POST /v1/messages/count_tokens

Returns the number of input tokens a Messages request would use, without generating. Who counts depends on the backend: on gRPC and ZMQ workers, SMG counts the tokens itself from the model's tokenizer; on HTTP workers, it forwards the request to a worker that implements the endpoint and relays the worker's response. See Backend Support.

Request Body

Field Type Required Description
model string Yes Model ID; selects the worker (HTTP) or the tokenizer (gRPC/ZMQ).
messages array Yes Conversation, in the same format as /v1/messages.
system string or array No System prompt.
tools array No Tool definitions.
tool_choice object No Tool selection.
thinking object No Thinking configuration.
output_config object No effort shapes the rendered prompt as it does on /v1/messages; a format is accepted but takes no part in the count.

There is no max_tokens. Any other field, such as context_management or mcp_servers, is forwarded unchanged to HTTP workers; on gRPC and ZMQ backends such fields are accepted but take no part in the count, which uses only the fields above.

The one exception is thread, refused with 400 (thread_not_counted) whatever its value: a count reads a whole conversation, so to count a message thread's next turn, send the full conversation — system, tools, and all messages — without the thread field.

Example

curl http://localhost:30000/v1/messages/count_tokens \
  -H "Content-Type: application/json" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
    "model": "meta-llama/Llama-3.1-8B-Instruct",
    "system": "You are a concise assistant.",
    "messages": [
      {"role": "user", "content": "What is the meaning of life?"}
    ]
  }'
{
  "input_tokens": 27
}

Backend Support

Deployment Behavior
HTTP workers Routed like any other request (routing policy, retries, circuit breaker, load tracking) to one worker's /v1/messages/count_tokens. 404 (model_not_found) when no worker serves the model.
HTTP PD Sent to one prefill worker. No decode worker is involved and no bootstrap fields are added. 503 (no_prefill_servers) when no prefill worker is available.
gRPC or ZMQ workers Answered by SMG itself from the model's tokenizer; no worker takes part, so regular, PD (--pd-disaggregation), and EPD (--epd-disaggregation) deployments all serve it. See below.
Anthropic API backend 501 Not Implemented
IGW mode A model with an external worker goes to that provider's backend (501). Otherwise any of the model's self-hosted pools answers — gRPC, ZMQ, HTTP, and PD alike, a disaggregated pool qualifying by its prefill workers alone. A model no pool serves, including an unknown model, gets 404 (model_not_found).

On gRPC and ZMQ backends, SMG renders the request through the model's chat template exactly as /v1/messages renders it — the same tool filtering by tool_choice and the same media placeholders — and returns the rendered prompt's token count. Media is not fetched: an image counts as the placeholder the template writes for it, and a document counts as its text; a file-source image or a document source with no text is refused, as /v1/messages refuses it.

That path refuses a request the way /v1/messages would. An unknown model gets 404 (model_not_found), even when a removed worker's tokenizer is still registered.

A served model whose tokenizer the gateway is still loading gets 503 (tokenizer_not_ready) with a Retry-After: 1 header. A served model whose tokenizer will not load on its own — no path to load it from, the load failed, or the tokenizer was removed — gets 503 (tokenizer_load_failed) with no Retry-After and a message naming the reason. Retrying changes nothing until a tokenizer registers for the model, either by a worker re-registering with a usable path or by POST /v1/tokenizers. Under --disable-tokenizer-autoload, a served model with no tokenizer and no such load failure gets 500 (tokenizer_not_found).

A request that does not render gets 400 (process_messages_failed), and a rendered prompt that fails to encode gets 500 (tokenization_failed).

Gateway-side counting applies since v1.13.0. In v1.12.0 and earlier, gRPC and ZMQ workers answer /v1/messages/count_tokens with 501 Not Implemented, and IGW mode picks only among the model's HTTP and HTTP PD workers.


Request Headers

Headers specific to the Messages API:

Header Effect
X-SMG-MCP enabled makes SMG run the MCP tool loop itself for a request whose tools include an mcp_toolset entry, on the Anthropic API backend. See MCP Tools and MCP. Other backends ignore it, and SMG does not forward it.
anthropic-version Checked on /v1/messages and /v1/messages/count_tokens before routing: the value must be a real calendar date of 2023 or later, written YYYY-MM-DD. Anything else, including an impossible date such as 2023-02-30, is refused with 400 (invalid_anthropic_version). A request without the header is served, and a valid value does not change how SMG handles the request. Forwarded to HTTP and PD workers and to the Anthropic API.
anthropic-beta Read on /v1/messages for two rules. An entry starting with interleaved-thinking lets thinking.budget_tokens be at or above max_tokens; without it, such a budget is refused with 400 (thinking_budget_exceeds_max_tokens). A body with a thread field needs the entry message-threads-2026-08-12; without it, a parsed body carrying thread is refused with 400 (thread_beta_required). Naming the message-threads beta also makes the HTTP router buffer the body; see Message Threads. Forwarded to HTTP and PD workers and to the Anthropic API.
x-api-key Not used to authenticate to SMG. Forwarded only to the Anthropic API; a gateway key sent there is removed at authentication. See Authentication.

Like the request-body rules, the anthropic-version and anthropic-beta checks are skipped for a /v1/messages request whose body the HTTP router streams through unparsed (see HTTP and PD Workers). A request that names the message-threads beta never takes that path: the header itself makes the router buffer the body, so a thread turn is always checked. A /v1/messages/count_tokens body is always buffered, so its anthropic-version check always runs.

Forwarded Headers

For HTTP and PD workers, SMG forwards only these request headers (it sets Content-Type itself):

Header Purpose
Authorization Credentials for the worker; see Authentication
anthropic-version, anthropic-beta API version and beta features for engines that serve /v1/messages (smg-project/smg#2638)
x-request-id, x-correlation-id, and any header starting with x-request-id- Request correlation
traceparent, tracestate W3C trace context
x-smg-routing-key SMG routing hint
x-override-priority SGLang's request priority, read by an engine started with SGLANG_ENABLE_REQUEST_HEADER_OVERRIDES=true and not by SMG; newer than v1.13.0 (smg-project/smg#3510)

Every other request header, including x-api-key, is dropped. The Anthropic API backend forwards a different set — Authorization, x-api-key, anthropic-version, and anthropic-beta — and nothing else. When the request carries neither Authorization nor x-api-key (a gateway key is removed at authentication), SMG adds the worker's stored key as x-api-key, with anthropic-version: 2023-06-01 when that header is absent. gRPC and ZMQ workers receive a tokenized request, not HTTP headers.


gRPC and ZMQ Workers

With gRPC workers (SGLang, vLLM, TensorRT-LLM, TokenSpeed, or MLX), and ZMQ workers that use the same pipeline, SMG implements the Messages API itself. It renders the conversation with the model's chat template, tokenizes it, sends token IDs to the engine, and builds the Anthropic response from the generated tokens. The pipeline serves regular, PD (--pd-disaggregation), and EPD (--epd-disaggregation) deployments. SMG needs the model's tokenizer (--model-path); see gRPC Workers.

Request field Handling
system, messages Rendered with the chat template. Text and image blocks in user turns, tool_use and thinking blocks in assistant turns, and tool_result blocks are converted. A system-role message inside messages keeps its position. A replayed mcp_tool_use or mcp_tool_result block is refused with 400; see Replaying MCP Blocks. A file-source image, or a file-source document outside a tool_result, is refused with 400 naming the block; see below. Images go through SMG's multimodal pipeline.
max_tokens, temperature, top_p, top_k Sent to the engine as sampling parameters. A max_tokens of 0 never reaches the engine; see max_tokens of 0.
stop_sequences Sent as stop strings to vLLM, TensorRT-LLM, and TokenSpeed gRPC workers. For SGLang gRPC workers and ZMQ workers, SMG matches them itself and sends only single-token stops to the engine, as stop token IDs.
tools Custom tools (those with an input_schema) are passed to the chat template and the tool parser; with a tool_choice of tool, only that tool is passed to the chat template. Other tool types, such as mcp_toolset, bash, text editor, web search, and tool search, are dropped.
tool_choice Mapped to Chat Completions semantics: auto to auto, any to required, tool to that function, none to none. SMG enforces any and tool with constrained decoding.
thinking enabled and adaptive turn on the chat template's thinking mode and run the model's reasoning parser. disabled and between_tools turn thinking mode off. Without thinking, the template default applies. A display of omitted withholds the reasoning text: the thinking blocks and their signature stay in place, with empty text; in a stream, the thinking block opens and closes without thinking_delta events. With summarized, updates, or no display, the reasoning text is returned as the model wrote it; SMG does not summarize. budget_tokens is not sent to the engine.
output_config.format, output_format The answer's JSON schema is sent to the engine as a constraint and enforced with constrained decoding, unless tool_choice forces a tool call; see Structured Output.
output_config.effort Rendered into the prompt as the chat template's reasoning_effort; not itself sent to the engine.
metadata, service_tier, container, mcp_servers, output_config's other keys, extra fields such as context_management Not sent to the engine.

A file source names a file uploaded through Anthropic's Files API, which this pipeline cannot read. An image with a file source is refused wherever the image stands — in a user message's content or inside a tool_result — and so is a file-source document in a user message's content. The refusal is 400 (process_messages_failed), before any worker takes part, and the error names the block and the sources to send instead:

messages.0.content.1: image source type 'file' is not supported; send the image as a base64 or url source
messages.0.content.0: document source type 'file' is not supported; send the document as a text or content source

A document inside a tool_result is not refused: a tool result contributes its text and its images to the rendered prompt, never its documents, so a file source there is never read.

MLX workers answer 400 to a request with images, with stop_sequences, with a structured output format (output_config.format or output_format), or with a tool_choice of any or tool.

How the response is built:

  • Tool calls and reasoning are extracted by SMG's tool and reasoning parsers, which SMG picks for the model or you set with --tool-call-parser and --reasoning-parser. A thinking block comes first, then text, then tool_use blocks. Thinking blocks carry an empty signature.
  • tool_use ids use Anthropic's toolu_ prefix: a parser id of the form call_<suffix> is returned as toolu_<suffix>, the same in streaming and non-streaming responses. Model-specific id formats are returned unchanged (smg-project/smg#2111).
  • stop_reason is tool_use when the output has tool calls, stop_sequence when one of stop_sequences ended generation (the matched string is in stop_sequence), max_tokens when the token limit was reached, and end_turn otherwise.
  • usage reports cache_creation_input_tokens and cache_read_input_tokens as 0, never null. In a stream, message_start carries zero counters, and the final message_delta carries output_tokens and, once the engine has reported it, input_tokens (smg-project/smg#2269).
  • Context window: when the selected worker advertises its context length, SMG rejects a prompt with more tokens than the window with 400 context_length_exceeded before dispatch. In PD mode the smaller of the prefill and decode windows applies. Whether the prompt plus max_tokens must fit is left to the engine (smg-project/smg#2618).
  • Tenant rate limiting, when enabled, covers this endpoint; see Tenant Rate Limiting.

HTTP and PD Workers

With HTTP workers, SMG forwards /v1/messages to the selected worker. It normally buffers the request, validates it, and re-serializes it: fields SMG does not model are kept, a --model-alias name is replaced by the canonical model ID, and numbers keep the values the client sent. When the HTTP router instead streams the body through (see Request Streaming), it forwards the raw body and leaves validation to the worker. Either way, only the allowlisted headers are forwarded, and the worker's response, including error responses and SSE streams, is relayed unchanged.

With --pd-disaggregation and HTTP workers, /v1/messages uses the same prefill/decode dual dispatch as chat completions: SMG selects a prefill and decode pair and dispatches the request to both (smg-project/smg#2250). See PD Disaggregation.

On both deployments, a parsed body with max_tokens: 0 is refused with 400 before a worker is selected; see max_tokens of 0.


Anthropic API Backend

Point SMG at the Anthropic API:

smg launch --backend anthropic --worker-urls https://api.anthropic.com

Clients then call SMG as in the Anthropic API example.

  • SMG sends each request to <worker URL>/v1/messages, so the worker URL is the API origin without /v1. The request carries the client's x-api-key, Authorization, anthropic-version, and anthropic-beta headers; when it arrives with neither key header, SMG adds the worker's stored key as x-api-key (see Authentication).
  • Streaming responses are relayed as they arrive. A successful non-streaming response is also relayed as Anthropic wrote it, under the upstream's status and content type: SMG records the response's usage token counts in its metrics and otherwise leaves the body untouched, so content blocks and fields it does not model reach the client as sent. When SMG runs the MCP tool loop itself, it instead parses each answer into its own Messages schema to find the tool calls and builds the final response.
  • The relayed body must be a JSON object; an answer that is not one returns 502 (parse_error). When the request timeout expires while the body is being read, the response is 504 (timeout); any other failure reading the body returns 502 (request_failed).
  • An upstream error is returned with its status and body, minus the organization and project identifiers in the body's error.message (see Provider Error Responses). An error Anthropic answers as an SSE stream is relayed as it arrives.
  • /v1/messages/count_tokens returns 501.

MCP Tools

SMG can run MCP tools for Messages requests on the Anthropic API backend. gRPC workers drop mcp_toolset tools, and HTTP workers receive them in the request body.

SMG runs the tool loop itself when the request has the X-SMG-MCP: enabled header and tools contains at least one mcp_toolset entry. Without the header, mcp_servers and the mcp_toolset entries are forwarded to Anthropic, together with the client's anthropic-beta header, and Anthropic's MCP connector runs the tools.

curl http://localhost:30000/v1/messages \
  -H "Content-Type: application/json" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "X-SMG-MCP: enabled" \
  -d '{
    "model": "claude-sonnet-4-20250514",
    "max_tokens": 1024,
    "messages": [
      {"role": "user", "content": "Search the web for SMG and summarize the top result."}
    ],
    "mcp_servers": [
      {"type": "url", "name": "search", "url": "https://mcp.example.com/mcp"}
    ],
    "tools": [
      {"type": "mcp_toolset", "mcp_server_name": "search"}
    ]
  }'
Field Description
mcp_servers[].name Server name that mcp_toolset entries refer to.
mcp_servers[].url http:// or https:// URL. SMG connects over Streamable HTTP. A URL containing /sse selects the legacy SSE transport, which SMG can no longer connect to.
mcp_servers[].authorization_token Sent to the MCP server as Authorization: Bearer <token>.
mcp_toolset.mcp_server_name The server whose tools the model may call.
mcp_toolset.default_config.enabled Whether the server's tools are enabled (default true).
mcp_toolset.configs Per-tool settings keyed by tool name. When present, only the tools listed here are exposed, each if its enabled is true (or unset, falling back to default_config.enabled).
defer_loading in default_config or configs Copied onto the tools SMG passes to the model.

What SMG does:

  1. Connects to the servers in mcp_servers. If none connects, it returns 502 with code mcp_connection_failed.
  2. Replaces mcp_servers and the mcp_toolset entries with the enabled MCP tools as regular tools, and sets tool_choice to auto if the request had none.
  3. Runs each tool the model calls, sends the results back to the model, and repeats until the model stops calling tools, for at most 10 rounds of tool calls. If the model still calls tools after the 10th round, a non-streaming request fails with 502 (mcp_max_iterations). A stream ends with an error event right after the 10th round, without calling the model again.
  4. Returns each call as an mcp_tool_use block (id prefixed mcptoolu_) followed by its mcp_tool_result block, then the model's final content. Every mcp_tool_result carries is_error — false for a call that succeeded, true for one that failed, never null:
{
  "content": [
    {
      "type": "mcp_tool_use",
      "id": "mcptoolu_01AbCdEf",
      "name": "web_search",
      "server_name": "search",
      "input": {"query": "SMG"}
    },
    {
      "type": "mcp_tool_result",
      "tool_use_id": "mcptoolu_01AbCdEf",
      "content": [{"type": "text", "text": "..."}],
      "is_error": false
    },
    {"type": "text", "text": "The top result describes..."}
  ],
  "stop_reason": "end_turn"
}

In a stream, SMG forwards the upstream events, emits the model's tool calls as mcp_tool_use blocks and each result as an mcp_tool_result block carrying the same is_error boolean, and ends with a single message_delta and message_stop.

Tool calls use policy-only approval: SMG never pauses the request to ask the client. The gateway runs its built-in default policy, which allows every tool, because the policy section of the MCP configuration file is not applied in v1.11.0. See MCP for server configuration.

Replaying MCP Blocks

A later request may send an earlier answer's mcp_tool_use and mcp_tool_result blocks back in messages, for example by appending the whole answer as an assistant message. A message thread likewise continues over a stored answer that carries them.

When SMG runs the tool loop itself, before calling the upstream it rewrites each replayed exchange into the plain pair the model saw the first time: an mcp_tool_use becomes a tool_use block that stays in the assistant message, and its mcp_tool_result becomes a tool_result block that opens a user message right after it, both keeping the ids the answer carries. A block of another kind after the results, such as the answer's final text, starts the next assistant message. Consecutive call-and-result pairs — how a non-streaming answer records parallel calls — stay together as one assistant message of calls followed by one user message of results. A request without mcp_tool_use or mcp_tool_result blocks is left as it came, including one whose history already uses plain tool_use and tool_result blocks.

When SMG does not run the loop, nothing is rewritten. The Anthropic API and HTTP workers receive the blocks unchanged in the forwarded body. gRPC and ZMQ workers run no MCP loop and cannot carry the exchange in the rendered prompt, so a request with either block is refused with 400 (process_messages_failed) before any worker takes part; the error message names the first such block and its position in messages. Send such a conversation to a backend that takes the blocks — the Anthropic API or an HTTP worker — or drop the exchange from the history.


Errors

SMG produces Anthropic's error format ({"type": "error", ...}) only inside an SSE stream. Elsewhere the shape depends on where the error comes from:

Source Status Body
Body is not valid JSON, or a field is missing, unknown, or holds the wrong type or value 400 {"error": {"message": "...", "type": "invalid_request_error", "param": "...", "code": "..."}} — code and param are described below
Body fails validation (for example empty messages or tool_choice without tools) 400 {"error": {"message": "...", "type": "invalid_request_error", "code": 400}}
Gateway authentication fails 401 Empty
SMG itself: routing, the gRPC pipeline, the MCP tool loop Varies The standard JSON error envelope, plus an X-SMG-Error-Code header
HTTP or PD worker Upstream status The upstream body, unchanged
The Anthropic API Upstream status The upstream body, minus the organization and project identifiers in its error message (see Anthropic API Backend)

In the 400 for a body SMG cannot read, code names the failure:

Failure code
The body is not valid JSON invalid_json
A required field is not there missing_required_parameter
A field the API does not know unknown_parameter
A value of the wrong shape invalid_type
A value outside an enumeration, an unknown block type included invalid_value
A negative integer where the field cannot be negative integer_below_min_value
The Content-Type: application/json header is missing, or the body fails to parse for any other reason json_parse_error

param is the failing field's path, null when no field is known. A content block SMG cannot read is named by its position, in param and in the message; see Request Body.

The standard envelope carries the Messages API's error type in type (invalid_request_error for a 400, authentication_error, permission_error, not_found_error, request_too_large, rate_limit_error, overloaded_error for a 503, timeout_error for a 504, api_error for another 5xx) and repeats code in the X-SMG-Error-Code header. For example, an over-long prompt on a gRPC worker:

{
  "error": {
    "type": "invalid_request_error",
    "code": "context_length_exceeded",
    "message": "This model's maximum context length is 32768 tokens. However, your request has 40210 input tokens. Please reduce the length of the input.",
    "param": null
  }
}

A few gateway answers are plain text instead: the 404 when no router serves the request in IGW mode and the 501 from a backend that does not serve the endpoint.

A /v1/messages/count_tokens body that does not parse or fails validation is refused with the same 400 invalid_request_error envelope as a /v1/messages body.

That envelope applies since v1.13.0: in v1.12.0 and earlier, the count_tokens answer to a body that does not parse is plain text (400 for invalid JSON, 415 without Content-Type: application/json, 422 for a missing field or a field of the wrong type).

Errors that SMG detects before the stream starts are returned as ordinary HTTP error responses, not as a stream, even when stream is true. After the stream has started, the gRPC path and SMG's MCP tool loop report a failure as an Anthropic error event and end the stream. The MCP tool loop starts its stream before it first calls the model, so even an upstream error on that first call arrives this way:

event: error
data: {"type":"error","error":{"type":"api_error","message":"..."}}

HTTP workers and the Anthropic API stream their own error events, which SMG relays.