# Anthropic Messages The Anthropic Messages API streams Claude's output as typed events over HTTP. AI Transport's Anthropic adaptor carries that stream over an Ably channel, so the same server code reaches every subscribed client instead of a single HTTP response. The [Anthropic Messages API](https://platform.claude.com/docs/en/build-with-claude/streaming) is Anthropic's interface for calling Claude and getting back a stream of typed events: message and content block lifecycle events, and deltas for text, extended thinking and tool input. AI Transport writes that stream to an [Ably channel](https://ably.com/docs/channels.md), so the channel gives you reconnects, multi-device delivery, and replay from your database. [`anthropicAdaptor` and `anthropicDecoder`](https://ably.com/docs/ai-transport/api/javascript/anthropic.md), from `@ably/ai-transport/anthropic`, carry the Messages API's own stream events, plus an `input` event for the messages a prompt carries, and the API's `error` event for a reply that fails. The agent uses `anthropicAdaptor`, and the client uses `anthropicDecoder`. Install the packages: #### Shell ``` npm install @ably/ai-transport @ably/pubsub-server @ably/pubsub-device @anthropic-ai/sdk@^1 ``` ## What the Anthropic Messages API brings The `@anthropic-ai/sdk` npm package owns the model call and the typed event model: | Feature | Description | | --- | --- | | Messages streaming | `client.messages.stream()` returns a `MessageStream`, which yields the raw stream events and builds the message from them. `finalMessage()` resolves with the finished message. | | Tool use | You advertise client tools on the request. Claude emits `tool_use` blocks, you run them, and you send the results back as `tool_result` blocks on the next call. Server tools, such as web search, run on Anthropic's side and return their results as blocks in the same reply. | | Extended thinking | Thinking blocks carry Claude's reasoning, with a signature, so you can pass them back to the API on a later call. | | Citations | Text blocks carry citations that point into the documents and search results Claude used. | | Typed SDK | The official SDK owns auth, the HTTP call, streaming, and the Messages type definitions. | ## What AI Transport adds Everything below comes from AI Transport rather than the framework. | Feature | Description | | --- | --- | | Streams that outlive a connection | The reply flows through a channel rather than one HTTP response, so a client can reconnect and receive what it missed. | | Multi-device delivery | Every device subscribed to the conversation receives the same messages in realtime. | | History and replay | A client that loads the conversation from your database replays the channel from the stored serial, then receives live messages. | | Token compaction | A client that joins mid-reply receives the text so far in one delivery, rather than a replay of every token. | ## Where they connect On the server, AI Transport replaces the HTTP response with `pipe()`. To forward a Messages stream over HTTP yourself, you return the SDK's readable stream, and the one client that made the request reads it with `MessageStream.fromReadableStream()`: ### Javascript ``` // Agent code, without AI Transport. const stream = client.messages.stream({ model: 'claude-opus-5-5', max_tokens: 4096, messages }); return new Response(stream.toReadableStream()); ``` With AI Transport, the agent publishes the prompt with `send`, so that every subscribed client receives the prompt as well as the reply. A `MessageStream` yields the events the codec knows, so `pipe()` takes it directly: ### Javascript ``` // Agent code. const adaptor = anthropicAdaptor(channel); await adaptor.send({ type: 'input', messages }, { headers: { requestId } }); const stream = client.messages.stream({ model: 'claude-opus-5-5', max_tokens: 4096, messages: [...history, ...messages] }); const { serial } = await adaptor.pipe(stream, { signal: req.signal, headers: { requestId } }); const reply = await stream.finalMessage(); ``` Pass the stream to `pipe()` as soon as you create it. `MessageStream` starts its request when you create it, and only queues events for a reader once one is attached. The reply that `finalMessage()` returns is the one the SDK built on the agent, so store it for the next turn. The codec appends each streamed content block, such as a text, thinking or tool input block, to one message, and the block's `content_block_stop` closes it. Text goes on the channel once: `message_start` travels with an empty `content`, so a client builds each block from its deltas. The [API reference](https://ably.com/docs/ai-transport/api/javascript/anthropic.md#wire-changes) lists every event that changes on the wire. ## Merge a reply on the client Every subscribed client decodes the same events. A client can apply the text deltas to its UI itself, as the [quickstart](https://ably.com/docs/ai-transport/get-started/anthropic.md#merge) does, or merge each reply with the SDK's own `MessageStream`, which builds the whole message: text, thinking, tool use and citations. `MessageStream` builds one message from a stream of newline-delimited JSON, the format the SDK's `toReadableStream()` writes. The client opens a stream for each `message_start`, writes every event into it until `message_stop`, then closes it: ### Javascript ``` // Client code. import { MessageStream } from '@anthropic-ai/sdk/lib/MessageStream'; import { anthropicDecoder } from '@ably/ai-transport/anthropic'; const decoder = anthropicDecoder(); const encoder = new TextEncoder(); let reply; decoder.onEvent(({ event }) => { if (event === undefined || event.type === 'input') return; if (event.type === 'error') { // Fail the reply that is streaming, or show an error from a reply that never started. if (reply) reply.error(new Error(event.error.message)); else showError(event.error); reply = undefined; return; } if (event.type === 'message_start') { const stream = new ReadableStream({ start: (controller) => (reply = controller) }); MessageStream.fromReadableStream(stream) .on('streamEvent', (_event, message) => render(message)) .on('error', (error) => showError(error)); } reply?.enqueue(encoder.encode(`${JSON.stringify(event)}\n`)); if (event.type === 'message_stop') { reply?.close(); reply = undefined; } }); await channel.subscribe(decoder.receive); ``` The client handles `input` events itself, because they carry the messages a client sent rather than part of Claude's reply. ## Handle a failed reply When a reply fails, publish the codec's `error` event from the agent with `send`, so every client ends the reply. Without it, a client's `MessageStream` for the reply never ends, including on a client that reads the reply from history. Catch the failure from `finalMessage()`, which rejects for every failed reply. The pipe does not publish the failure for you. When the Messages API reports an error part-way through a reply, such as an `overloaded_error`, the Anthropic SDK throws it as an `APIError` instead of yielding it as a stream event, so the reply can fail while `pipe()` resolves. The `error` event is the Messages API's own `ErrorResponse`. Build it from the `APIError`, which carries the error's type, message and request id: ### Javascript ``` // Agent code. try { const stream = client.messages.stream(params, { signal: req.signal }); await adaptor.pipe(stream, { signal: req.signal }); const reply = await stream.finalMessage(); } catch (error) { const apiError = error instanceof Anthropic.APIError ? error : undefined; // Best effort: the publish can fail for the same reason the pipe did. await adaptor .send({ type: 'error', error: { type: apiError?.type ?? 'api_error', message: apiError?.apiMessage ?? String(error?.message ?? error) }, request_id: apiError?.requestID ?? null, }) .catch(() => {}); } ``` A client reads an `error` as the end of the reply that was streaming. When a request fails before Claude starts the reply, for example with a rate limit error, the agent publishes an `error` with no reply open, so the client shows it as an error of its own. ## Run tools The agent runs its tool loop as it would without AI Transport: call the Messages API, run the `tool_use` blocks in the reply when its `stop_reason` is `tool_use`, add the reply and a user message with the `tool_result` blocks to the messages, and call it again. Pipe each call's stream to the adaptor, so every subscribed client sees each reply as it streams. Each call is a reply of its own on the channel, with its own `message_start` and `message_stop`. ### Javascript ``` // Agent code. runTool is your own function, and returns a tool_result block. while (true) { const stream = client.messages.stream({ model: 'claude-opus-5-5', max_tokens: 4096, tools, messages }); await adaptor.pipe(stream, { signal: req.signal }); const reply = await stream.finalMessage(); messages.push({ role: 'assistant', content: reply.content }); if (reply.stop_reason !== 'tool_use') break; const results = await Promise.all(reply.content.filter((block) => block.type === 'tool_use').map(runTool)); const toolMessages = [{ role: 'user', content: results }]; // Publish the results, so every subscribed client receives them. await adaptor.send({ type: 'input', messages: toolMessages }); messages.push(...toolMessages); } ``` Keep the whole reply in the messages, as `finalMessage()` returns it. With extended thinking, the API needs the thinking blocks that came before a tool call when you pass the results back. Catch a failed call in the loop and publish an `error`, as in [handle a failed reply](#errors). A client that runs a tool itself, in the browser, POSTs the result to the agent as a user message with a `tool_result` block. The agent publishes it in an `input` event, so that every subscribed client receives it. ## Scope and trade-offs The codec carries the raw Messages events, so the channel uses Anthropic's own event model. Stored messages stay round-trippable to the Messages API, and a conversation is tied to the Messages shape. To work with several model providers behind one interface, use the [Vercel AI SDK](https://ably.com/docs/ai-transport/frameworks/vercel-ai-sdk-core.md). The codec carries the events of `client.messages.stream()` with the `@anthropic-ai/sdk` package at version 1. It does not carry the beta stream from `client.beta.messages.stream()`, or the Claude Agent SDK's messages. ## Read next - [Get started with Anthropic](https://ably.com/docs/ai-transport/get-started/anthropic.md): build a working chat app. - [Anthropic API reference](https://ably.com/docs/ai-transport/api/javascript/anthropic.md): `anthropicAdaptor`, `anthropicDecoder`, and the events the codec encodes and decodes. - [Codec architecture](https://ably.com/docs/ai-transport/internals/codec-architecture.md): how a codec translates a framework's events into Ably messages. ## Related Topics - [OpenAI responses](https://ably.com/docs/ai-transport/frameworks/openai.md): How Ably AI Transport integrates with the OpenAI Responses API. The OpenAI adaptor carries the Responses event stream over an Ably channel to every subscribed client. - [Vercel AI SDK](https://ably.com/docs/ai-transport/frameworks/vercel-ai-sdk-core.md): How Ably AI Transport integrates with the Vercel AI SDK: pipe the UI message stream from streamText on the server, and merge it with readUIMessageStream on every client. - [Vercel AI SDK UI](https://ably.com/docs/ai-transport/frameworks/vercel-ai-sdk-ui.md): How Ably AI Transport integrates with Vercel AI SDK UI: keep useChat, and stream each response over an Ably channel, so a tab that reloads during a response can resume it. - [Custom codec](https://ably.com/docs/ai-transport/frameworks/custom-codec.md): Build a custom codec with defineCodec so AI Transport carries your own event types over an Ably channel, beside or in place of the Vercel, OpenAI, Anthropic, and AG-UI codecs. ## Documentation Index To discover additional Ably documentation: 1. Fetch [llms.txt](https://ably.com/llms.txt) for the canonical list of available pages. 2. Identify relevant URLs from that index. 3. Fetch target pages as needed. Avoid using assumed or outdated documentation paths.