Guide · Amazon Bedrock · Converse Streaming
MCP Server Bedrock Converse Streaming — ConverseStreamCommand, event types, error chunks
Streaming with ConverseStreamCommand gives MCP server tool handlers incremental output from Bedrock foundation models — but the stream is a typed event union, not a byte stream, and the gotchas are non-obvious. The response's stream field is an AsyncIterable<ConverseStreamOutput> where each iteration yields one of seven distinct event types: messageStart, contentBlockStart, contentBlockDelta, contentBlockStop, messageStop, metadata, and four error event types (internalServerException, modelStreamErrorException, validationException, throttlingException) that arrive inside the stream as chunks — not as thrown exceptions. Getting streaming right means understanding the full event sequence, knowing when to parse tool use input (at contentBlockStop, never at contentBlockDelta), handling error chunks in the loop body, and releasing the HTTP connection when exiting early. This page covers all of it with complete, production-ready TypeScript. For the overview of ConverseCommand and model IDs see Bedrock Converse API overview; for multi-turn tool use loops see Bedrock Converse tool use.
TL;DR
Import ConverseStreamCommand from @aws-sdk/client-bedrock-runtime. Send the command and iterate response.stream with for await. Accumulate text deltas by block index; accumulate tool use input as a string and JSON.parse it only at contentBlockStop. Check for internalServerException and modelStreamErrorException inside the loop — they arrive as chunks, not throws. On early exit, call response.stream.return() to release the connection.
Package setup and ConverseStreamCommand import
Streaming uses the same package as the non-streaming ConverseCommand — @aws-sdk/client-bedrock-runtime. No separate streaming package is required:
npm install @aws-sdk/client-bedrock-runtime
Import the command and its input type. The stream type is AsyncIterable<ConverseStreamOutput> and is the return type of response.stream:
import {
BedrockRuntimeClient,
ConverseStreamCommand,
ConverseStreamCommandInput,
ConverseStreamOutput,
Message,
ContentBlock,
} from "@aws-sdk/client-bedrock-runtime";
// Create once at module level — do not create per-request
const client = new BedrockRuntimeClient({
region: process.env.AWS_REGION ?? "us-east-1",
});
// Use cross-region inference profile IDs in production for higher TPS limits
const MODEL_ID =
process.env.BEDROCK_MODEL_ID ??
"us.anthropic.claude-3-5-sonnet-20241022-v2:0";
Critical constraint: a ConverseStreamCommand object is consumed by a single send call. You cannot call client.send(command) twice with the same command instance and get two independent streams — the second call will fail. Create a new ConverseStreamCommand for each request.
The ConverseStreamOutput event union
Every iteration of for await (const event of response.stream) yields a ConverseStreamOutput value. This is a TypeScript discriminated union where exactly one property is set on each event object. The seven event types arrive in a predictable sequence for a single response turn:
| Event type | Key fields | Notes |
|---|---|---|
messageStart |
role: 'assistant' |
Always first. Signals the start of a new assistant message. |
contentBlockStart |
contentBlockIndex, start.toolUse.toolUseId, start.toolUse.name |
One per content block. For text blocks, start is undefined. For tool use blocks, start.toolUse carries the toolUseId and tool name. |
contentBlockDelta |
contentBlockIndex, delta.text, delta.toolUse.input |
Many per block. delta.text for text blocks; delta.toolUse.input (a partial JSON string fragment) for tool use blocks. |
contentBlockStop |
contentBlockIndex |
Signals a block is complete. At this point a tool use input string is complete — safe to JSON.parse. |
messageStop |
stopReason |
Signals the full message is done. stopReason is one of 'end_turn', 'tool_use', 'max_tokens', 'stop_sequence', 'guardrail_intervened'. Arrives before metadata. |
metadata |
usage.inputTokens, usage.outputTokens |
Arrives after messageStop. Contains token counts for the completed response. |
| Error events | internalServerException, modelStreamErrorException, validationException, throttlingException |
Arrive as chunks inside the stream, not as thrown exceptions. Must be checked in the loop body. |
The sequence for a text-only response is: messageStart → one or more contentBlockStart/contentBlockDelta/contentBlockStop triples → messageStop → metadata. For a response that includes tool calls, one or more of the content blocks will be tool use blocks.
Assembling a complete message from the stream
The stream delivers content in fragments. To reconstruct the complete Message you need to accumulate deltas per block index and combine them after messageStop. This pattern is the foundation of all stream consumers in this guide:
import {
BedrockRuntimeClient,
ConverseStreamCommand,
Message,
ContentBlock,
} from "@aws-sdk/client-bedrock-runtime";
interface AssembledMessage {
role: "assistant";
content: ContentBlock[];
stopReason: string;
inputTokens: number;
outputTokens: number;
}
async function converseStream(
messages: Message[],
systemPrompt?: string
): Promise<AssembledMessage> {
const command = new ConverseStreamCommand({
modelId: MODEL_ID,
messages,
system: systemPrompt ? [{ text: systemPrompt }] : undefined,
inferenceConfig: { maxTokens: 4096, temperature: 0.7 },
});
const response = await client.send(command);
// Per-block accumulators
const textByIndex = new Map<number, string>();
const toolUseByIndex = new Map<number, {
toolUseId: string;
name: string;
inputJson: string;
}>();
let stopReason = "end_turn";
let inputTokens = 0;
let outputTokens = 0;
for await (const event of response.stream) {
// --- Error events arrive as chunks, not thrown exceptions ---
if (event.internalServerException) {
throw new Error(
`Bedrock internal error: ${event.internalServerException.message}`
);
}
if (event.modelStreamErrorException) {
throw new Error(
`Model stream error: ${event.modelStreamErrorException.message}`
);
}
if (event.validationException) {
throw new Error(
`Validation error in stream: ${event.validationException.message}`
);
}
if (event.throttlingException) {
throw new Error(
`Throttled mid-stream: ${event.throttlingException.message}`
);
}
// --- Normal event handling ---
if (event.messageStart) {
// role is always 'assistant' here; nothing to accumulate
}
if (event.contentBlockStart) {
const { contentBlockIndex, start } = event.contentBlockStart;
if (start?.toolUse) {
// Tool use block: record toolUseId and name; input accumulates in deltas
toolUseByIndex.set(contentBlockIndex, {
toolUseId: start.toolUse.toolUseId ?? "",
name: start.toolUse.name ?? "",
inputJson: "",
});
} else {
// Text block: initialize accumulator
textByIndex.set(contentBlockIndex, "");
}
}
if (event.contentBlockDelta) {
const { contentBlockIndex, delta } = event.contentBlockDelta;
if (delta?.text !== undefined) {
// Text delta: append to block's accumulator
const existing = textByIndex.get(contentBlockIndex) ?? "";
textByIndex.set(contentBlockIndex, existing + delta.text);
} else if (delta?.toolUse?.input !== undefined) {
// Tool use input delta: PARTIAL JSON — accumulate, do not parse yet
const block = toolUseByIndex.get(contentBlockIndex);
if (block) {
block.inputJson += delta.toolUse.input;
}
}
}
if (event.contentBlockStop) {
// Block is complete. Tool use input JSON is now fully assembled.
// Parsing happens below when building the content array.
}
if (event.messageStop) {
stopReason = event.messageStop.stopReason ?? "end_turn";
}
if (event.metadata) {
inputTokens = event.metadata.usage?.inputTokens ?? 0;
outputTokens = event.metadata.usage?.outputTokens ?? 0;
}
}
// Build the content block array in block index order
const allIndexes = new Set([
...textByIndex.keys(),
...toolUseByIndex.keys(),
]);
const sortedIndexes = [...allIndexes].sort((a, b) => a - b);
const content: ContentBlock[] = [];
for (const idx of sortedIndexes) {
if (textByIndex.has(idx)) {
content.push({ text: textByIndex.get(idx)! });
} else if (toolUseByIndex.has(idx)) {
const block = toolUseByIndex.get(idx)!;
content.push({
toolUse: {
toolUseId: block.toolUseId,
name: block.name,
// Safe to parse now — contentBlockStop has fired for this index
input: JSON.parse(block.inputJson || "{}"),
},
});
}
}
return {
role: "assistant",
content,
stopReason,
inputTokens,
outputTokens,
};
}
The key ordering rule: messageStop arrives before metadata. This means you have stopReason before you know the token counts. If you need to gate retry logic on token counts, wait until after the full for await loop completes before making decisions.
Streaming tool calls — contentBlockStart through contentBlockStop
When the model decides to call one or more tools, the response contains tool use blocks interleaved with or in place of text blocks. The streaming sequence for a tool use block is:
contentBlockStartwithstart.toolUse.toolUseIdandstart.toolUse.name— this is when you learn the tool name and ID- Many
contentBlockDeltaevents withdelta.toolUse.inputas partial JSON string fragments — do not attempt to parse these contentBlockStop— the input JSON string is now complete and safe toJSON.parse
A critical constraint for parallel tool calls: when messageStop has stopReason: 'tool_use', the message may contain multiple tool use blocks (parallel tool calls). You must collect all tool use blocks from the full stream before executing any of them — you do not know how many there are until messageStop fires. Here is a complete MCP tool handler that uses streaming and handles tool calls:
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import {
BedrockRuntimeClient,
ConverseStreamCommand,
ConverseToolConfig,
Message,
Tool,
} from "@aws-sdk/client-bedrock-runtime";
const client = new BedrockRuntimeClient({ region: "us-east-1" });
const MODEL_ID = "us.anthropic.claude-3-5-sonnet-20241022-v2:0";
const server = new McpServer({ name: "streaming-tool-server", version: "1.0.0" });
// Tool definitions passed to the model
const tools: Tool[] = [
{
toolSpec: {
name: "get_weather",
description: "Get current weather for a city",
inputSchema: {
json: {
type: "object",
properties: {
city: { type: "string", description: "City name" },
units: { type: "string", enum: ["celsius", "fahrenheit"] },
},
required: ["city"],
},
},
},
},
{
toolSpec: {
name: "get_forecast",
description: "Get 7-day forecast for a city",
inputSchema: {
json: {
type: "object",
properties: {
city: { type: "string" },
days: { type: "integer", minimum: 1, maximum: 7 },
},
required: ["city"],
},
},
},
},
];
const toolConfig: ConverseToolConfig = { tools };
interface ToolCall {
toolUseId: string;
name: string;
input: Record<string, unknown>;
}
async function streamAndCollectToolCalls(
messages: Message[]
): Promise<{ textChunks: string[]; toolCalls: ToolCall[]; stopReason: string }> {
const command = new ConverseStreamCommand({
modelId: MODEL_ID,
messages,
toolConfig,
inferenceConfig: { maxTokens: 2048 },
});
const response = await client.send(command);
const textByIndex = new Map<number, string>();
const toolUseByIndex = new Map<number, {
toolUseId: string;
name: string;
inputJson: string;
}>();
const textChunks: string[] = []; // ordered text fragments for streaming to MCP client
let stopReason = "end_turn";
for await (const event of response.stream) {
if (event.internalServerException) {
throw new Error(`Stream error: ${event.internalServerException.message}`);
}
if (event.modelStreamErrorException) {
throw new Error(`Model stream error: ${event.modelStreamErrorException.message}`);
}
if (event.throttlingException) {
throw new Error(`Throttled: ${event.throttlingException.message}`);
}
if (event.contentBlockStart) {
const { contentBlockIndex, start } = event.contentBlockStart;
if (start?.toolUse) {
toolUseByIndex.set(contentBlockIndex, {
toolUseId: start.toolUse.toolUseId ?? "",
name: start.toolUse.name ?? "",
inputJson: "",
});
} else {
textByIndex.set(contentBlockIndex, "");
}
}
if (event.contentBlockDelta) {
const { contentBlockIndex, delta } = event.contentBlockDelta;
if (delta?.text !== undefined) {
const prev = textByIndex.get(contentBlockIndex) ?? "";
textByIndex.set(contentBlockIndex, prev + delta.text);
// Capture each text fragment in order for downstream streaming
textChunks.push(delta.text);
} else if (delta?.toolUse?.input !== undefined) {
const block = toolUseByIndex.get(contentBlockIndex);
if (block) {
// PARTIAL JSON — do not parse here
block.inputJson += delta.toolUse.input;
}
}
}
if (event.messageStop) {
stopReason = event.messageStop.stopReason ?? "end_turn";
}
}
// Build tool call objects — JSON.parse is safe here because all contentBlockStop events
// have already fired (we consumed the entire stream above)
const toolCalls: ToolCall[] = [];
for (const [, block] of toolUseByIndex) {
toolCalls.push({
toolUseId: block.toolUseId,
name: block.name,
input: JSON.parse(block.inputJson || "{}"),
});
}
return { textChunks, toolCalls, stopReason };
}
server.tool(
"weather_assistant",
{
query: z.string().describe("Weather question from the user"),
},
async ({ query }) => {
const messages: Message[] = [
{ role: "user", content: [{ text: query }] },
];
const { textChunks, toolCalls, stopReason } = await streamAndCollectToolCalls(messages);
if (stopReason !== "tool_use" || toolCalls.length === 0) {
// Model answered directly without calling tools
return {
content: [{ type: "text", text: textChunks.join("") }],
};
}
// Execute all tool calls collected from the stream
// All are available now — do not execute mid-stream
const toolResults = await Promise.all(
toolCalls.map(async (tc) => {
const result = await executeWeatherTool(tc.name, tc.input);
return {
toolUseId: tc.toolUseId,
result,
};
})
);
// Build the next turn: append assistant message + tool results
const assistantMessage: Message = {
role: "assistant",
content: toolCalls.map((tc) => ({
toolUse: { toolUseId: tc.toolUseId, name: tc.name, input: tc.input },
})),
};
const toolResultMessage: Message = {
role: "user",
content: toolResults.map((tr) => ({
toolResult: {
toolUseId: tr.toolUseId,
content: [{ text: JSON.stringify(tr.result) }],
},
})),
};
// Stream the final answer
const finalMessages = [...messages, assistantMessage, toolResultMessage];
const { textChunks: finalChunks } = await streamAndCollectToolCalls(finalMessages);
return {
content: [{ type: "text", text: finalChunks.join("") }],
};
}
);
async function executeWeatherTool(
name: string,
input: Record<string, unknown>
): Promise<Record<string, unknown>> {
// Real implementation would call a weather API
if (name === "get_weather") {
return { city: input.city, temp: 22, condition: "partly cloudy" };
}
if (name === "get_forecast") {
return { city: input.city, forecast: "Warm and sunny for the next 3 days." };
}
return { error: "Unknown tool" };
}
Notice that executeWeatherTool is called only after the entire for await loop has finished — after the full response stream is consumed, including messageStop. If the model is making two parallel tool calls, both will be in toolCalls at that point and both can be executed with Promise.all.
Error events inside the stream
This is the most commonly misunderstood aspect of ConverseStreamCommand. The AWS SDK documentation for Bedrock Converse lists InternalServerException, ModelStreamErrorException, ValidationException, and ThrottlingException as possible errors — but these can arrive inside the stream as event chunks after the HTTP connection is established and after some content has already been delivered. They are not equivalent to thrown exceptions.
The outer try/catch around client.send(command) catches errors that occur before the stream starts — for example, an authentication failure, a network timeout before the first byte, or a ValidationException for a malformed request body. But a throttlingException that fires mid-generation, or an internalServerException during model inference, arrives as a chunk and will only be seen if you check for it in the loop body. Here is the defensive pattern that handles both paths:
async function streamWithFullErrorHandling(
messages: Message[]
): Promise<string> {
let command: ConverseStreamCommand;
let response: Awaited<ReturnType<typeof client.send>>;
try {
command = new ConverseStreamCommand({
modelId: MODEL_ID,
messages,
inferenceConfig: { maxTokens: 2048 },
});
// Errors here: auth failure, network error, ValidationException for bad request shape
response = await client.send(command);
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
throw new Error(`Bedrock stream setup failed: ${msg}`);
}
let text = "";
let stopReason = "";
try {
for await (const event of response.stream) {
// Check all four error event types in the loop body
if (event.internalServerException) {
// Bedrock-side infrastructure error — may be transient
throw new Error(
`Bedrock internal server error: ${event.internalServerException.message ?? "unknown"}`
);
}
if (event.modelStreamErrorException) {
// Model-level streaming error — the model's output was interrupted
throw new Error(
`Model stream error (originalStatusCode=${
(event.modelStreamErrorException as { originalStatusCode?: number }).originalStatusCode
}): ${event.modelStreamErrorException.message ?? "unknown"}`
);
}
if (event.validationException) {
// Should have been caught in the outer try/catch but can appear mid-stream
// for certain input validation failures that only manifest during generation
throw new Error(
`Validation error mid-stream: ${event.validationException.message ?? "unknown"}`
);
}
if (event.throttlingException) {
// Rate limit hit mid-stream — entire response must be retried
throw new Error(
`Throttled mid-stream: ${event.throttlingException.message ?? "unknown"}`
);
}
if (event.contentBlockDelta?.delta?.text) {
text += event.contentBlockDelta.delta.text;
}
if (event.messageStop) {
stopReason = event.messageStop.stopReason ?? "";
}
}
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
throw new Error(`Error during stream consumption: ${msg}`);
}
return text;
}
modelStreamErrorException includes an originalStatusCode and originalMessage from the underlying model service. These can help distinguish transient infrastructure issues (5xx) from model-specific failures. For retry logic, treat both internalServerException and modelStreamErrorException as potentially transient and implement exponential backoff on the full ConverseStreamCommand call — there is no way to resume a Bedrock stream mid-way (see the reconnect section below).
AbortController for cancellation
MCP tool handlers run in a request context that can be cancelled by the MCP client — for example, when the user interrupts a long-running operation. Passing an AbortSignal to the Bedrock client allows the HTTP request to be cancelled cleanly, releasing the connection immediately rather than waiting for the full response:
import { AbortController } from "@smithy/abort-controller";
async function streamWithCancellation(
messages: Message[],
timeoutMs = 30_000
): Promise<string> {
// AbortController from @smithy/abort-controller is compatible with the AWS SDK
const abortController = new AbortController();
// Enforce a hard timeout: abort the stream if it takes too long
const timeoutHandle = setTimeout(() => {
abortController.abort(new Error(`Stream timed out after ${timeoutMs}ms`));
}, timeoutMs);
try {
const command = new ConverseStreamCommand({
modelId: MODEL_ID,
messages,
inferenceConfig: { maxTokens: 4096 },
});
const response = await client.send(command, {
// Pass abortSignal in the requestOptions (second arg to send())
abortSignal: abortController.signal,
});
let text = "";
for await (const event of response.stream) {
if (event.internalServerException) {
throw new Error(event.internalServerException.message);
}
if (event.modelStreamErrorException) {
throw new Error(event.modelStreamErrorException.message);
}
if (event.contentBlockDelta?.delta?.text) {
text += event.contentBlockDelta.delta.text;
}
if (event.messageStop) {
break; // normal completion — exit the loop
}
}
return text;
} catch (err: unknown) {
if (
err instanceof Error &&
(err.name === "AbortError" || err.message.includes("aborted"))
) {
// Clean cancellation — not a real error from the caller's perspective
return "[response cancelled]";
}
throw err;
} finally {
clearTimeout(timeoutHandle);
}
}
// MCP tool handler that respects a 20-second timeout per Bedrock call
server.tool(
"summarize_with_timeout",
{
text: z.string().describe("Text to summarize"),
},
async ({ text }) => {
const messages: Message[] = [
{ role: "user", content: [{ text: `Summarize the following:\n\n${text}` }] },
];
const summary = await streamWithCancellation(messages, 20_000);
return { content: [{ type: "text", text: summary }] };
}
);
When the abort signal fires during stream iteration, the for await loop throws an AbortError. This is distinct from an error event inside the stream — it comes from the HTTP layer, not from Bedrock's inference. Always catch it separately and decide whether to surface it as an error or as a graceful truncation.
Releasing the connection when exiting early via break
If you exit a for await loop over the stream using break (for example, once you have enough content), the HTTP connection may remain open and the response body will continue downloading in the background. To release it immediately, call response.stream.return():
async function streamFirstNChars(
messages: Message[],
maxChars: number
): Promise<string> {
const command = new ConverseStreamCommand({
modelId: MODEL_ID,
messages,
inferenceConfig: { maxTokens: 4096 },
});
const response = await client.send(command);
let text = "";
try {
for await (const event of response.stream) {
if (event.internalServerException) throw new Error(event.internalServerException.message);
if (event.contentBlockDelta?.delta?.text) {
text += event.contentBlockDelta.delta.text;
if (text.length >= maxChars) {
break; // exit early — must release the stream
}
}
}
} finally {
// Always release the underlying HTTP connection when exiting early
// response.stream is an AsyncIterable with a return() method
await (response.stream as AsyncGenerator).return?.(undefined);
}
return text.slice(0, maxChars);
}
The return() call on the async generator signals that the consumer is done. The SDK will close the underlying HTTP connection. Skipping this in a long-running MCP server causes connection handle leaks over time — each early-exit request leaves an open socket that is not cleaned up until the response fully downloads.
Reconnect pattern on network error mid-stream
Unlike some streaming APIs, Bedrock Converse does not issue a resume token. The API is stateless — each ConverseStreamCommand call is a complete, independent inference request. If a network error interrupts the stream mid-way (a TCP reset, a proxy timeout, or an SDK-level read error), the entire call must be retried with the same messages array. Any partial content received before the error is discarded:
async function streamWithRetry(
messages: Message[],
maxAttempts = 3,
baseDelayMs = 1_000
): Promise<AssembledMessage> {
let lastError: unknown;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
// converseStream() is the full stream assembly function defined earlier
return await converseStream(messages);
} catch (err: unknown) {
lastError = err;
const isRetryable =
err instanceof Error &&
(err.message.includes("throttled") ||
err.message.includes("internal server error") ||
err.message.includes("ECONNRESET") ||
err.message.includes("socket hang up") ||
err.message.includes("ETIMEDOUT"));
if (!isRetryable || attempt === maxAttempts) {
throw err;
}
// Exponential backoff with jitter
const delay = baseDelayMs * Math.pow(2, attempt - 1) * (0.5 + Math.random() * 0.5);
await new Promise((r) => setTimeout(r, Math.min(delay, 60_000)));
}
}
throw lastError;
}
The key design constraint: when retrying after a mid-stream network error, pass the original messages array — do not include any partial assistant content that arrived before the error. Bedrock Converse validates the message array structure strictly. An incomplete assistant message (one with a partial text block) will produce a ValidationException on the retry. The retry starts the generation completely fresh.
For throttlingException events that arrive mid-stream: these also require a full retry of the ConverseStreamCommand. Use the same backoff logic. The model's generation is interrupted when throttling occurs — there is no guarantee the response before the throttle event was coherent or complete.
MCP pattern — streaming partial text back to the MCP client
MCP 1.x defines a content streaming extension that allows tool handlers to push partial text chunks to the MCP client as they arrive rather than waiting for the full response. When the MCP client signals support for streaming content (via the capabilities negotiation), the tool handler can emit incremental updates. For MCP clients that do not support content streaming, the handler accumulates and returns the full response:
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import {
BedrockRuntimeClient,
ConverseStreamCommand,
Message,
} from "@aws-sdk/client-bedrock-runtime";
const client = new BedrockRuntimeClient({ region: "us-east-1" });
const MODEL_ID = "us.anthropic.claude-3-5-sonnet-20241022-v2:0";
const server = new McpServer({ name: "streaming-mcp-server", version: "1.0.0" });
server.tool(
"ask_bedrock_streaming",
{
prompt: z.string().describe("User prompt to send to the model"),
system: z.string().optional().describe("Optional system prompt"),
},
async ({ prompt, system }) => {
const messages: Message[] = [
{ role: "user", content: [{ text: prompt }] },
];
const command = new ConverseStreamCommand({
modelId: MODEL_ID,
messages,
system: system ? [{ text: system }] : undefined,
inferenceConfig: { maxTokens: 4096, temperature: 0.7 },
});
const response = await client.send(command);
// Accumulate full response for clients that do not support streaming
let fullText = "";
let stopReason = "end_turn";
for await (const event of response.stream) {
if (event.internalServerException) {
throw new Error(`Bedrock error: ${event.internalServerException.message}`);
}
if (event.modelStreamErrorException) {
throw new Error(`Model stream error: ${event.modelStreamErrorException.message}`);
}
if (event.throttlingException) {
throw new Error(`Throttled: ${event.throttlingException.message}`);
}
if (event.contentBlockDelta?.delta?.text) {
fullText += event.contentBlockDelta.delta.text;
}
if (event.messageStop) {
stopReason = event.messageStop.stopReason ?? "end_turn";
}
}
// Return the complete assembled response
return {
content: [
{
type: "text",
text: fullText,
},
],
};
}
);
For most production MCP server use cases — where the MCP client is Claude Desktop or a programmatic agent that calls your tool and waits for the result — accumulating and returning the full response is the correct pattern. The streaming benefit for MCP tools is primarily in reducing time-to-first-byte for user-visible interfaces, not in reducing total latency or cost. The ConverseStreamCommand is still worth using over ConverseCommand in this pattern because it allows the connection to be aborted mid-generation if the MCP tool call is cancelled.
Converse vs ConverseStream — when to use each
Both commands accept exactly the same ConverseCommandInput shape (model ID, messages, system prompt, inference config, tool config). The only operational difference is in how the response is delivered:
| ConverseCommand | ConverseStreamCommand | |
|---|---|---|
| Response delivery | Single resolved ConverseResponse object after full generation |
AsyncIterable<ConverseStreamOutput> with incremental events |
| Tool use input | Fully parsed Record<string, unknown> immediately available |
Must accumulate partial JSON strings per block; parse at contentBlockStop |
| Error handling | All errors are thrown exceptions | Some errors arrive as stream chunks — must check in loop body |
| Cancellation | Abort signal stops the HTTP request | Abort signal stops the HTTP request; also need stream.return() on early break |
| Time to first token | N/A — full response arrives at once | First contentBlockDelta arrives within ~1–3 seconds for most models |
Use ConverseCommand when: the tool handler calls the model purely to decide which tools to call (the tool use input is what matters, not the text); when the downstream MCP client does not support or benefit from incremental text; or when simplicity is more valuable than latency. Use ConverseStreamCommand when: the response is user-facing and time-to-first-character matters; when the generation may be long enough that a 30-second wait for the full response would cause timeouts; or when you need to enforce a generation time budget with AbortController.
For pure tool-call-only patterns — where the model's role is to parse a request and return structured function arguments — ConverseCommand is cleaner. The streaming assembly pattern for tool use (accumulating partial JSON) adds complexity without benefit when you do not need to show partial output.
Backpressure considerations
JavaScript's for await...of provides natural backpressure: the runtime does not request the next event from the async iterable until the current loop body has completed. For most MCP tool handlers — where each iteration appends a string — this is fast enough that backpressure is never a concern. The network is always the bottleneck, not the loop body.
Backpressure becomes relevant only if the loop body does expensive synchronous work per chunk — for example, running a regex or DOM parse on every text delta. In practice, MCP tool handlers should not do this. Buffer the full text and process it after the loop completes. The only time per-chunk processing is justified is if you are implementing a streaming MCP content response that needs to forward each delta to a WebSocket or SSE connection — in that case, the downstream write is the slow operation, and you should use an async queue or bounded channel between the Bedrock stream and the downstream writer rather than doing the write inline in the loop body.
Complete production-ready MCP tool handler
Combining all the patterns above: a production MCP tool handler that uses ConverseStreamCommand, handles all error event types, enforces a timeout, retries on transient failures, and returns the assembled response:
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import {
BedrockRuntimeClient,
ConverseStreamCommand,
Message,
} from "@aws-sdk/client-bedrock-runtime";
import { AbortController } from "@smithy/abort-controller";
const client = new BedrockRuntimeClient({
region: process.env.AWS_REGION ?? "us-east-1",
maxAttempts: 1, // Handle retries manually for stream commands
});
const MODEL_ID =
process.env.BEDROCK_MODEL_ID ??
"us.anthropic.claude-3-5-sonnet-20241022-v2:0";
const server = new McpServer({ name: "production-streaming-server", version: "1.0.0" });
async function runStreamingRequest(
messages: Message[],
systemPrompt: string | undefined,
timeoutMs: number,
maxAttempts: number
): Promise<{ text: string; stopReason: string; inputTokens: number; outputTokens: number }> {
let lastError: unknown;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
const abortController = new AbortController();
const timeoutHandle = setTimeout(
() => abortController.abort(new Error("Stream timeout")),
timeoutMs
);
try {
const command = new ConverseStreamCommand({
modelId: MODEL_ID,
messages,
system: systemPrompt ? [{ text: systemPrompt }] : undefined,
inferenceConfig: { maxTokens: 4096, temperature: 0.7 },
});
const response = await client.send(command, {
abortSignal: abortController.signal,
});
let text = "";
let stopReason = "end_turn";
let inputTokens = 0;
let outputTokens = 0;
for await (const event of response.stream) {
if (event.internalServerException) {
throw new Error(
`Bedrock internal error: ${event.internalServerException.message ?? "unknown"}`
);
}
if (event.modelStreamErrorException) {
throw new Error(
`Model stream error: ${event.modelStreamErrorException.message ?? "unknown"}`
);
}
if (event.validationException) {
// ValidationException mid-stream is not retryable
throw Object.assign(
new Error(`Validation: ${event.validationException.message ?? "unknown"}`),
{ retryable: false }
);
}
if (event.throttlingException) {
throw Object.assign(
new Error(`Throttled: ${event.throttlingException.message ?? "unknown"}`),
{ retryable: true }
);
}
if (event.contentBlockDelta?.delta?.text) {
text += event.contentBlockDelta.delta.text;
}
if (event.messageStop) {
stopReason = event.messageStop.stopReason ?? "end_turn";
}
if (event.metadata) {
inputTokens = event.metadata.usage?.inputTokens ?? 0;
outputTokens = event.metadata.usage?.outputTokens ?? 0;
}
}
return { text, stopReason, inputTokens, outputTokens };
} catch (err: unknown) {
lastError = err;
// Do not retry non-retryable errors
const isExplicitlyNonRetryable =
err instanceof Error && (err as Error & { retryable?: boolean }).retryable === false;
const isAbort =
err instanceof Error &&
(err.name === "AbortError" || err.message.includes("aborted") || err.message.includes("timeout"));
if (isExplicitlyNonRetryable || isAbort || attempt === maxAttempts) {
throw err;
}
// Exponential backoff with full jitter
const delay =
Math.random() * Math.min(60_000, 1_000 * Math.pow(2, attempt));
await new Promise((r) => setTimeout(r, delay));
} finally {
clearTimeout(timeoutHandle);
}
}
throw lastError;
}
server.tool(
"bedrock_complete",
{
messages: z
.array(
z.object({
role: z.enum(["user", "assistant"]),
text: z.string(),
})
)
.min(1)
.describe("Conversation messages"),
system: z.string().optional().describe("System prompt"),
timeout_seconds: z.number().int().min(5).max(120).default(60),
},
async ({ messages: rawMessages, system, timeout_seconds }) => {
const messages: Message[] = rawMessages.map((m) => ({
role: m.role,
content: [{ text: m.text }],
}));
const { text, stopReason, inputTokens, outputTokens } =
await runStreamingRequest(messages, system, timeout_seconds * 1000, 3);
return {
content: [
{
type: "text",
text: JSON.stringify({
response: text,
stopReason,
usage: { inputTokens, outputTokens },
}),
},
],
};
}
);
Key gotchas — reference summary
- Error events arrive as chunks, not throws.
internalServerException,modelStreamErrorException,validationException, andthrottlingExceptionwill appear as properties on aConverseStreamOutputevent inside the loop. The outertry/catcharoundclient.send()does not catch them. You must check for them on every iteration. - Tool use input is partial JSON until
contentBlockStop. EachcontentBlockDeltafor a tool use block delivers a fragment of the input JSON. These fragments are not valid JSON on their own. Concatenate them all and callJSON.parseonly after the correspondingcontentBlockStopevent. messageStoparrives beforemetadata.stopReasonis onmessageStop; token counts are on the subsequentmetadataevent. If you exit the loop onmessageStopyou will miss the token counts.- The
streamfield is consumed once. Iteratingresponse.streama second time will produce no events (the iterator is exhausted). Create a newConverseStreamCommandfor each request. - Collect all tool calls before executing any. When
stopReasonis'tool_use', the message may contain multiple tool use blocks (parallel tool calls). Execute them only after the full stream is consumed and all blocks are assembled. - Call
stream.return()on early break. If you exit thefor awaitloop viabreak, the underlying HTTP connection stays open until you callstream.return(). In a long-running server, this causes connection handle leaks. - No resume token on error. When a stream error occurs mid-generation (network drop, mid-stream throttle), the entire
ConverseStreamCommandmust be retried from scratch. Do not append partial content to the message array before retrying. ConverseStreamCommandobjects are single-use. Do not reuse a command object across retry attempts — instantiate a newConverseStreamCommandinside the retry loop.
Monitor your Bedrock Converse MCP tools with AliveMCP
AliveMCP monitors MCP server endpoints for uptime, latency spikes, and error rates. When a Bedrock Converse streaming tool handler starts returning mid-stream errors or elevated time-to-first-token, AliveMCP alerts you before it impacts downstream agents and users.
Start free monitoring