Introducing a new way to review your PRs.

Read the announcement

alishahryar1 / free-claude-code

Use Claude Code, Codex, Antigravity, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)

View on GitHub

28 documents · Updated Nov 20, 2026

docs / anthropic-protocol-adapter

Anthropic protocol adapter

The Anthropic protocol adapter presents a stable Messages API to clients while provider systems may use a different request and response format. It preserves the meaning of text, images, tools, thinking, token usage, errors, and streamed message blocks across that boundary. See Protocol adapters for the wider adapter model, Gemini protocol adapter and Chat Completions protocol adapter for related adapters, and Anthropic API endpoints for the public endpoint view.

Request model

The Anthropic core in src/…/models.py defines the public message contract. A request can contain plain text or ordered content blocks for text, images, documents, tool calls, tool results, thinking, and server-side tool results. Extra protocol fields remain available so clients can use supported Anthropic extensions without losing their shape.

Native token-count requests use a separate shape that keeps the outer request strict while allowing the native content blocks to remain opaque. This lets the token endpoint estimate native Messages input without first forcing it through the compatibility message model.

Request serialization

Request serialization produces a JSON-ready view of the public Messages fields. It excludes routing state such as the original model and the provider-resolved model. Tool results become provider-safe text: text parts stay text, while structured values use JSON text.

References: src/…/models.py• L8-163 src/…/models.py• L166-187 src/…/request_serialization.py• L8-57

Provider conversion

The adapter converts Anthropic requests into the format expected by an upstream provider and converts the provider output back into Anthropic message events. Upstreams can use native Anthropic Messages or a compatibility format such as OpenAI-compatible chat, so the conversion must preserve message order and tool-call dependencies rather than only copy fields.

Content conversion

Text remains message text. User images become provider image parts from either a URL or validated base64 data. Base64 sources are normalized to a canonical data URL and accept only supported image media types. Invalid, empty, or mismatched image data becomes an explicit conversion error rather than silently changing the request.

Assistant tool use becomes a provider function call, and a later tool result becomes a provider tool message linked by its call ID. Tool-result content keeps its order across text and images. An image-bearing result also produces provider-visible image context while the linked tool message carries a marker for the result.

The converter preserves assistant content that follows a tool call as a later provider message. It also turns server-tool history into provider-readable context instead of silently dropping it. Adjacent user messages are combined only after transcript order is complete. Empty inline system messages are ignored in the compatibility conversion.

The conversion validates hosted tool history and rejects assistant blocks that the provider format cannot represent, such as assistant images. Unsupported input becomes an explicit conversion error instead of silently losing content. Unknown top-level fields are also rejected when they cannot be represented by the compatibility provider.

References: src/…/conversion.py• L85-100 src/…/conversion.py• L190-305 src/…/conversion.py• L328-465 src/…/conversion.py• L515-741 src/…/image_sources.py• L18-77 src/…/tool_results.py• L13-63

Tool conversion

Anthropic tools map to provider function tools with the same name, description, and input schema. Schema patterns are translated when the target provider needs a compatible form. An omitted tool choice becomes automatic selection when tools exist, while a choice with no tools is removed instead of being sent as an unusable provider setting.

Named, automatic, required, and disabled choices map to the closest provider choice. Provider name rules can be narrower than Anthropic name rules. OpenAIToolNameCodec gives non-portable names deterministic aliases and decodes those aliases before tool events return to the client. The same mapping covers tool declarations, historical tool calls, and an explicit tool choice.

Tool calls come from structured provider events. Ordinary model text that looks like a tool call remains visible text instead of being buffered or inferred as a call. Native tool argument fragments remain opaque during stream validation, then become an object only at a boundary that requires Anthropic tool_use input; malformed arguments produce an explicit provider failure.

References: src/…/conversion.py• L51-65 src/…/conversion.py• L803-836 src/…/tool_schema_patterns.py src/…/openai_tool_names.py• L11-124 src/…/native_stream.py• L205-236 src/…/sse_aggregation.py• L115-140

Native Messages transport

The native transport prepares a provider-ready Messages body after request validation and reasoning policy selection. It preserves supported native extensions, rejects unsafe overrides, places system content at the start of the request, and validates finite JSON before opening an upstream attempt. Resolved controls set the provider model, output limit, streaming mode, thinking settings, and output effort; native history must use signed thinking blocks when it carries reasoning.

The shared execution path resolves an endpoint for each attempt, prepares replay history, sets the Anthropic version and beta headers, and requires an SSE response. A presenter then maps the native stream to the selected public contract: Anthropic Messages, Chat Completions, Gemini, or Responses. Recovery can correct request state or continue a failed stream within bounded attempt and delivery rules, without repeating committed output.

References: src/…/native.py• L73-184 src/…/native_stream.py• L37-231 src/…/request_policy.py• L38-162 src/…/transport.py• L111-236 src/…/transport.py• L339-630

Native Messages passthrough

The native Messages passthrough carries an already formed native request without converting its content into the compatibility model. It checks the request envelope and JSON safety, keeps provider-owned fields and event payloads intact, and changes only the public model identity where the adapter must present one.

For a native non-streaming request, the provider response is read as JSON and must be a valid Anthropic Message. For a native streaming request, the passthrough decodes provider SSE, checks failure events, and relays the native lifecycle. Native history can contain adapter-owned replay markers for thinking blocks; the passthrough restores them only when the marker belongs to the same provider and model scope. Its relay accepts lifecycle events in order, ignores an initial ping, requires message_start before other message events, and requires message_stop to complete the stream.

References: src/…/passthrough.py• L1-105 src/…/provider.py• L150-178 src/…/passthrough.py• L58-180 src/…/passthrough.py• L184-285

Conversion pipeline

The request path keeps the public Anthropic contract at the API edge and applies provider-specific policy only after the shared conversion step.

flowchart LR
    A[Anthropic Messages request] --> B[Validate content and tool history]
    B --> C[Build provider request]
    C --> D[Provider stream]
    D --> E[Anthropic SSE blocks]
    E --> F{stream requested}
    F -->|yes| G[Stream to client]
    F -->|no| H[Aggregate into Message JSON]

The OpenAI chat request policy adds provider limits and name aliases after the common body is built. The native Messages policy instead preserves the Anthropic wire shape and adds native controls such as thinking, output limits, beta headers, and supported extensions. An opaque native request follows the passthrough path when the caller already supplies the native wire shape.

References: src/…/request_policy.py• L27-93 src/…/provider.py• L586-607 src/…/conversion.py• L853-894 src/…/request_policy.py• L38-162 src/…/transport.py• L145-337 src/…/passthrough.py• L17-105 src/…/messages.py• L101-148

Thinking and token handling

Thinking is an optional hidden-reasoning part of an Anthropic response. The adapter carries it as a distinct thinking block when the selected reasoning policy allows it, while keeping ordinary answer text and tool calls as separate content types.

Thinking blocks

The request can enable thinking and set a token budget. Its display mode can request summarized output, omitted output, or incremental updates. Provider-specific reasoning fields or <think>...</think> text are normalized into Anthropic thinking deltas. The stream ledger closes a text block before it opens a thinking block, and it closes thinking before it resumes text. Redacted thinking stays opaque and is not turned into visible answer text.

Native Messages requests resolve application reasoning intent into native thinking controls. Manual thinking needs a valid budget below the output limit, while adaptive thinking cannot carry an exact budget. Unsupported model capabilities become a request error rather than an unmarked change in reasoning behavior.

Historical assistant thinking can be replayed for providers that need it. The replay mode selects disabled handling, think tags, or a provider reasoning field; this choice affects the upstream history and does not change the public Anthropic block type. Structured reasoning details can preserve signed or encrypted reasoning metadata when the target response contract supports it.

References: src/…/models.py• L44-53 src/…/models.py• L108-115 src/…/thinking.py• L23-139 src/…/conversion.py• L40-55 src/…/conversion.py• L601-741 src/…/ledger.py• L269-285 src/…/ledger.py• L387-410 src/…/request_policy.py• L38-162

Token usage

Input token counting provides a safe estimate before provider execution. It counts message text, thinking, tool names and input, tool results, image cost estimates, server-tool blocks, tool schemas, and small per-message or per-block overheads. It is an estimate rather than a provider tokenizer result.

The estimator accepts both validated compatibility messages and native token-count messages. Native system blocks and tools can remain dictionaries so native requests are counted without changing their content shape. Image data uses an image cost estimate instead of counting its base64 payload as ordinary text.

When the provider returns usage, the adapter uses that value for final input and output counts. Cache-read and cache-creation counts are included only when they are valid parts of the inclusive input total. If output usage is absent, the stream ledger estimates output tokens from emitted text, thinking, and tool names with their raw argument text. Final Anthropic events always contain integer input_tokens and output_tokens fields. Locally completed server tools preserve integer provider usage when available and add a server-tool request count to the completion usage.

References: src/…/models.py• L166-187 src/…/tokens.py• L13-138 src/…/usage.py• L4-38 src/…/ledger.py• L345-361 src/…/ledger.py• L363-365 src/…/server_tool_sse.py• L202-240

Error translation

The adapter converts neutral execution failures into Anthropic error envelopes at the public wire boundary. This lets provider code report failure meaning without coupling it to Anthropic names or HTTP rules.

Error envelopes

Failure kinds map to Anthropic error types and standard HTTP statuses. Special status information can refine the type: a permission failure with status 402 becomes a billing error, a 404 invalid request becomes not found, a 413 invalid request becomes request too large, and a 504 timeout becomes a timeout error. Context-window failures use client-recognized prompt is too long wording.

Error messages pass through sensitive-text redaction. The response includes the request ID when one exists, which lets a client correlate the error with server traces without exposing provider internals.

References: src/…/errors.py• L8-97 src/…/request_errors.py• L33-55 src/…/messages.py• L250-294

Upstream error events

Native upstream error events become classified execution failures before they reach the public stream. Their status is derived from the Anthropic error type, context-window signals take precedence, and the displayed detail is redacted and size-limited. A non-success HTTP response uses the same bounded-body rule, while a response that is not an SSE stream is treated as a provider protocol failure. Native non-streaming responses also fail as provider protocol errors when their JSON is invalid or is not an Anthropic Message object.

References: src/…/wire.py• L29-59 src/…/wire.py• L62-129 src/…/transport.py• L457-463 src/…/passthrough.py• L121-152 src/…/diagnostics.py• L1-80

Streaming errors

A failure before the first stream frame becomes a normal JSON HTTP error. A failure after streaming starts becomes a terminal Anthropic event: error frame when the response wrapper can keep the stream contract. The SSE emitter uses the same Anthropic error payload for terminal egress failures and canonical execution failures. The wrapper also closes the body and preserves cancellation instead of hiding it as an API error.

References: src/…/emitter.py• L12-49 src/…/response_streams.py• L216-252 src/…/response_streams.py• L329-371

SSE stream contract

The Anthropic stream is a sequence of Server-Sent Events (SSE), where each event has a name and a JSON data object. The stream ledger owns message IDs, content-block indexes, open-block state, usage, and the final stop reason so each provider can produce one consistent Anthropic response shape.

Event sequence

Successful streams start with message_start, open one or more content blocks, send typed deltas, close each block, send message_delta, and end with message_stop. Text uses text_delta; thinking uses thinking_delta and may use signature_delta; tool input uses input_json_delta. Text blocks may also receive citations_delta events.

The contract permits server-tool, redacted-thinking, and eager-text blocks that use start and stop events without deltas. A block index must be an integer. It cannot be opened twice or reused after it closes. A delta must target an open block and must match that block's type. The final event must be message_stop unless the caller explicitly allows a protocol-native error. Completed native thinking also requires a signature.

The native relay applies the lifecycle part of this contract while preserving provider-owned payloads. It rewrites the model in message_start for the public response, rejects events before the start event, and rejects any event after message_stop. The wire reader treats ping events as keepalives and turns split response chunks into ordered named events.

The incremental decoder accepts provider text split at any point, emits only complete SSE events, and flushes one final unterminated event when the input ends. It can also preserve the original raw frames, including comments and unknown SSE fields, before the parser selects named JSON events. The parser keeps event data as a structured object when possible and preserves non-object or invalid JSON as data for the caller to handle. Native Messages validation also checks event identity, block lifecycle, tool identities, stop reasons, and message completion before the relay forwards an event. Native tool input remains opaque until the completed block crosses the conversion boundary.

When failure cleanup closes unclosed content, it does not synthesize a successful stop frame for an unfinished tool_use block. This keeps incomplete tool calls available to the failure path instead of presenting them as completed output.

References: src/…/stream_contracts.py• L17-39 src/…/stream_contracts.py• L50-102 src/…/stream_contracts.py• L105-173 src/…/decoder.py• L10-68 src/…/emitter.py• L33-62 src/…/ledger.py• L179-305 src/…/ledger.py• L329-365 src/…/native_stream.py• L37-231 src/…/passthrough.py• L76-105 src/…/wire.py• L29-59

Server-tool event frames

Locally completed web search and web fetch operations use the same Anthropic SSE contract as provider output. A server-tool stream starts with an assistant message and a server_tool_use block, reports a search or fetch result linked by tool_use_id, and ends with a text summary, usage, and message_stop.

The result block preserves the operation type. Search results carry titles and URLs, while fetch results carry a document with its media type, title, citations, and retrieval time. A failed operation keeps the same link and reports a typed unavailable result instead of breaking the stream shape.

Each tool call and result uses a distinct block index. Calls above the allowed limit receive an explicit max_uses_exceeded result, while the final usage records only the operations that ran. Provider usage is copied only from integer fields, and the completion adds the operation-specific server-tool request count.

References: src/…/server_tool_sse.py• L19-75 src/…/server_tool_sse.py• L79-177 src/…/server_tool_sse.py• L202-240 src/…/server_tool_types.py• L1-10 src/…/service.py• L204-259

SSE aggregation

Non-streaming compatibility Messages calls consume the same internal SSE stream instead of using a separate provider path. The aggregator decodes arbitrarily split events, collects the initial message data, joins deltas by block index, parses complete tool JSON, merges stop and usage data, then returns one Anthropic Message body. A top-level stream error is returned separately so the API can choose its HTTP status and error envelope.

Missing optional message fields receive safe defaults during aggregation. This design keeps streaming and non-streaming compatibility calls aligned: both see the same block order, thinking content, tool input, stop reason, and usage semantics. The opaque native passthrough instead validates a provider-supplied non-streaming Message directly, while its native streaming branch relays identities before the API-level response is delivered. If a streamed tool argument cannot become a finite JSON object, aggregation raises an upstream execution failure instead of returning an empty input object.

References: src/…/sse_aggregation.py• L1-154 src/…/decoder.py• L10-68 src/…/messages.py• L161-225 src/…/transport.py• L465-504 src/…/passthrough.py• L121-145

Stream recovery

Provider streams can end after visible output or while a tool JSON value is incomplete. The recovery path either requests a continuation that preserves the original tool contract or asks for an exact JSON suffix. It accepts a repair only when the result is valid JSON and matches the original tool schema.

Recovered text and thinking are appended without repeating the prefix. Recovered tool calls close the same Anthropic blocks and finish with the normal message delta and message stop events, so clients do not need a second response format for a repaired stream.

References: src/…/recovery.py• L22-174 src/…/provider.py• L952-1077 src/…/provider.py• L1180-1337

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the allowed content-block types, start/stop-only block kinds, delta types, and strict block-index rules aligned between stream_contracts.py, streaming/ledger.py, native stream validation, the native passthrough relay, and the non-streaming aggregator.
  • Keep image-source validation and tool-result decomposition aligned with provider image parts and tool-result markers.
  • Keep tool-name aliasing consistent across declarations, tool choices, historical assistant calls, and returned tool-use events.
  • Keep native tool argument fragments opaque through relay and stream state, then validate them when an object-valued Messages input is required.
  • Keep compatibility conversion allowlists, native request protections, extra-body handling, beta headers, endpoint paths, and opaque native request validation aligned with the upstream Messages contract.
  • Keep native replay markers scoped to the same provider and model before restoring provider-owned thinking history.
  • Keep the failure-kind map, HTTP status map, JSON error envelope, terminal SSE error frame, and SSE response headers aligned.
  • Keep token estimates, native token-count input shapes, cache partitions, final usage fields, and local server-tool usage counts compatible with both the request-time token counter and provider-reported usage.
  • Keep thinking replay policy aligned with the parser, native thinking controls, and the provider profile that reads reasoning deltas. Keep accepted thinking display modes aligned with the provider policies that consume them.
  • Keep server-tool block types, result links, block indexes, request-limit errors, operation-specific usage keys, and completion summaries aligned with the local web-tool service.
  • Keep endpoint resolution, replayed history, attempt admission, and recovery corrections aligned so retries do not replay committed public output or emit a second terminal event.

Important failure modes

TriggerConsequenceGuard
A tool result has no matching tool-use ID in the replayed historyThe provider request can violate its tool-call ordering contractThe conversion ledger tracks required tool IDs and rejects incomplete history
An image source has unsupported media, invalid base64, or a mismatched data-URL typeThe provider request can contain unusable image contentImage normalization validates the source and raises a conversion error
A compatibility request contains an unknown top-level fieldThe provider can receive a request with semantics the adapter cannot preserveCompatibility conversion rejects unsupported extra fields before request construction
A native request contains an unsupported extra field or non-finite JSON valueThe upstream can receive an unsafe or ambiguous requestNative request preparation applies an allowlist and validates finite UTF-8 JSON before opening the attempt
An opaque native request has no model or messages, or has a non-boolean stream fieldThe native provider path can receive an invalid request envelopeNativeMessagesRequest validates the required outer fields and copies only validated JSON
Native replay history comes from a different provider or model scopeProvider-owned thinking data can be restored into the wrong requestHistory restoration accepts only markers whose replay origin matches the current scope
A provider response is successful but does not have an SSE content typeThe relay cannot safely interpret the response as an Anthropic streamThe transport rejects the response as a provider protocol failure before opening the stream
A native non-streaming response is invalid JSON or is not a Message objectThe client can receive a body that violates the native Messages contractThe passthrough validates the decoded response before yielding it
An unknown tool alias or arguments that are not a finite JSON object reach the public boundaryThe client can receive an unknown tool or malformed tool_use inputThe name codec decodes only request-scoped aliases, and native aggregation rejects invalid arguments as an upstream failure
A native stream changes event type, repeats a block index, or ends with an open blockThe client receives an invalid Anthropic SSE sequenceNative stream state checks event identity, block lifecycle, tool identity, stop reason, and terminal-event rules
A passthrough event has the wrong payload type, arrives before message_start, or arrives after message_stopThe client receives an invalid native Messages streamThe lifecycle relay validates event identity and start/stop state before forwarding payloads
A stream uses an unsupported block type, a non-integer index, or a delta that does not match the open blockThe client receives an invalid Anthropic SSE sequenceThe stream contract allowlist, strict index check, and block-specific delta checks reject the event sequence
A local server-tool result uses the wrong tool_use_id or block indexThe client cannot link the result to the tool call or the stream fails validationServer-tool frame builders carry the shared tool ID and assign each call and result a distinct index
A local web operation fails or exceeds its use limitThe client can lose the tool result or receive a malformed completion streamThe service emits a typed error result and still closes the tool, summary, usage, and message frames
A provider fails after the first public frameA JSON error response would corrupt the SSE responseThe response wrapper emits a terminal Anthropic error frame and closes the stream
Provider usage is absent or malformedFinal usage can be missing or non-numericThe ledger and server-tool formatter use integer-safe values and estimate output usage when needed
Failure cleanup sees an unfinished streamed tool callA successful content_block_stop can falsely mark the call as completeThe ledger omits synthetic stop frames for unfinished tool_use blocks and leaves them to the failure path

Key files

FileWhy to read it
src/…/models.pyDefines the public request, native token-count, content-block, response, thinking, and usage shapes
src/…/conversion.pyExplains the shared Anthropic-to-provider message, reasoning, and tool meaning
src/…/native.pyDefines the native Messages wire body and its request safety rules
src/…/passthrough.pyPreserves already formed native requests and enforces the native SSE lifecycle
src/…/native_stream.pyValidates native event order, preserves tool argument fragments, and relays upstream identities to clients
src/…/provider.pyConnects native requests to replay restoration and the Anthropic provider transport
src/…/transport.pyConnects native request preparation, endpoint calls, SSE decoding, retries, recovery, and public stream presenters
src/…/passthrough.pyShows the native provider path for validated non-streaming responses and lifecycle-only streaming relay
src/…/wire.pyDefines Messages SSE decoding, keepalive handling, stop detection, and upstream failure evidence
src/…/request_policy.pyResolves native thinking, output limits, effort, and model capability controls
src/…/image_sources.pyShows how image URLs and base64 data cross the provider boundary
src/…/tool_results.pyShows how text and image tool results retain their meaning during conversion
src/…/openai_tool_names.pyShows how client tool names stay stable across provider name limits
src/…/server_tool_sse.pyDefines Anthropic SSE frames for local web-tool use, results, errors, summaries, and usage
src/…/server_tool_types.pyDefines the server-tool block names shared by formatters and stream validation
src/…/service.pyConnects local search and fetch operations to server-tool SSE frames and request limits
src/…/emitter.pyDefines common SSE serialization, response headers, stop-reason mapping, and terminal error frames
src/…/ledger.pyOwns streamed block state, usage, stop reasons, event order, token estimates, and incomplete-tool cleanup
src/…/decoder.pyShows how split transport chunks become ordered SSE events while preserving raw frames
src/…/stream_contracts.pyStates the minimal valid Anthropic SSE contract
src/…/sse_aggregation.pyShows how one SSE stream becomes a non-streaming Message body and rejects invalid tool input
src/…/tokens.pyEstimates compatibility and native request tokens across text, images, tools, tool results, and server-tool blocks
src/…/request_snapshot.pyDefines the trace-safe view shared by compatibility and native token-count requests
src/…/usage.pyDefines safe partitioning of provider input totals into Anthropic usage fields
src/…/errors.pyDefines public error names, status mapping, and safe error payloads
src/…/provider.pyConnects provider chunks, reasoning, tools, recovery, and Anthropic SSE output
src/…/messages.pyShows how the public Messages API selects streaming or aggregation