Amazon Bedrock · ConverseCommand, ConverseStreamCommand, ImageBlock, DocumentBlock, SystemContentBlock · 2026-11-27 · Bedrock Converse Extended arc

Amazon Bedrock Converse API for MCP Servers: Tool Loops, Streaming, Multimodal, and Conversation Management

Four Bedrock Converse Extended arc pages synthesised into a complete production playbook for MCP server developers — covering multi-turn tool use loops (ToolConfiguration shape, three ToolChoice modes, the full agentic loop, parallel ToolUseBlock execution and the single-user-turn rule, forceToolUse for structured output), ConverseStreamCommand streaming (seven event types, error chunks that arrive inside the stream not as thrown exceptions, partial tool input JSON assembly, AbortController timeout, stream.return() on early break, the no-resume constraint on retry), ImageBlock and DocumentBlock multimodal inputs (source.bytes must be Uint8Array not base64, DocumentBlock name is required, per-model support matrix, S3 location service principal, scanned PDF rendering), and system prompts and conversation management (SystemContentBlock constraints, MCP-specific prompt design, sliding window algorithm for history trimming, tool-use pair atomicity, token estimation). Twelve consolidated production gotchas at the end.

The Converse API as the backbone of Bedrock-powered MCP tools

When an MCP server needs to call a large language model — to run a multi-step reasoning loop, analyze a document a user passed to it, or maintain a multi-turn conversation across tool calls — the Bedrock Converse API is the right starting point. It presents a unified interface across all Bedrock-hosted foundation models: Claude, Nova, Llama, Mistral, Titan, and Cohere. One SDK, one conversation format, model-agnostic code.

The API lives in @aws-sdk/client-bedrock-runtime:

npm install @aws-sdk/client-bedrock-runtime

The core types you will use across all patterns in this guide:

import {
  BedrockRuntimeClient,
  ConverseCommand,
  ConverseStreamCommand,
  type Message,
  type ContentBlock,
  type SystemContentBlock,
  type Tool,
  type ToolConfiguration,
  type ToolUseBlock,
  type ToolResultBlock,
  type StopReason,
  ValidationException,
  ThrottlingException,
  ServiceUnavailableException,
} 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",
});

const MODEL_ID =
  process.env.BEDROCK_MODEL_ID ??
  "us.anthropic.claude-3-5-sonnet-20241022-v2:0";

Using a cross-region inference profile ID (the us. prefix) rather than a bare model ID gives higher TPS limits automatically — Bedrock load-balances across regions within the prefix's availability zone. This matters for MCP servers under sustained query load.

This guide covers four major topics: tool use, streaming, multimodal inputs, and conversation management. Each maps to a distinct set of production failure modes. Read the sections relevant to your current work, or work through all four before writing any Bedrock-dependent MCP tool handler.

Part 1: Multi-turn tool use — the agentic loop

Tool use is what turns a Bedrock Converse call from a text completion into an agentic loop. The model decides which tools to call, your code executes them, and the loop continues until the model has enough information to produce a final answer. Getting this loop right requires understanding five independent rules — violating any one causes a ValidationException.

ToolConfiguration: declaring tools the model can call

Tools are declared in the toolConfig field of ConverseCommandInput. Each Tool has a toolSpec with a name, description, and JSON Schema for its inputs. The JSON Schema root must be type: "object":

const weatherTool: Tool = {
  toolSpec: {
    name: "get_weather",           // [a-zA-Z0-9_-]{1,64} — no spaces or dots
    description:
      "Fetch current weather for a city. Returns temperature in Celsius, " +
      "humidity percentage, and a short condition string.",
    inputSchema: {
      json: {
        $schema: "http://json-schema.org/draft-07/schema#",
        type: "object",          // root MUST be object — array or primitive rejected
        properties: {
          city: { type: "string", description: "City name, e.g. 'Berlin'" },
          units: { type: "string", enum: ["celsius", "fahrenheit"] },
        },
        required: ["city"],
      },
    },
  },
};

const toolConfig: ToolConfiguration = {
  tools: [weatherTool, calendarTool],
  // toolChoice defaults to AUTO — omit unless you need specific behavior
};

Key constraints enforced at the API level before the model is ever invoked:

ToolChoice: who controls whether a tool is called

The optional toolChoice field inside ToolConfiguration has three variants:

Passing { any: {} } or { tool: {...} } with Amazon Titan or Meta Llama models causes a ValidationException. Guard these modes behind a model-family check:

function isClaudeModel(modelId: string): boolean {
  return modelId.startsWith("anthropic.claude") ||
    modelId.startsWith("us.anthropic.claude") ||
    modelId.startsWith("eu.anthropic.claude");
}

function buildToolConfig(tools: Tool[], forceToolName?: string): ToolConfiguration {
  const config: ToolConfiguration = { tools };
  if (forceToolName) {
    if (!isClaudeModel(MODEL_ID)) {
      throw new Error(`toolChoice TOOL is not supported by ${MODEL_ID}`);
    }
    config.toolChoice = { tool: { name: forceToolName } };
  }
  return config;
}

The agentic loop: collect all tool calls, execute in parallel, return in one turn

The Converse API is stateless. You maintain the conversation history yourself as an array of Message objects and pass the full array on every call. When the model wants to run tools it sets stopReason to 'tool_use' and includes ToolUseBlock entries in the assistant message content. You run those tools, build a user turn containing all results, append both messages to the array, and call the API again. The loop exits when stopReason === 'end_turn':

async function runConverseLoop(
  systemPrompt: string,
  userMessage: string,
  tools: Tool[]
): Promise<string> {
  const messages: Message[] = [
    { role: "user", content: [{ text: userMessage }] },
  ];

  for (let iteration = 0; iteration < 10; iteration++) {
    const response = await client.send(new ConverseCommand({
      modelId: MODEL_ID,
      system: [{ text: systemPrompt }],
      messages,
      toolConfig: { tools },
      inferenceConfig: { maxTokens: 2048, temperature: 0.1 },
    }));

    const assistantMsg = response.output?.message;
    if (!assistantMsg) throw new Error("No message in Converse output");
    messages.push(assistantMsg);

    if (response.stopReason === "end_turn") {
      return (assistantMsg.content ?? [])
        .filter((b): b is { text: string } => "text" in b)
        .map((b) => b.text)
        .join("");
    }

    if (response.stopReason === "tool_use") {
      // Collect EVERY ToolUseBlock in this turn
      const toolUseBlocks = (assistantMsg.content ?? [])
        .filter((b): b is { toolUse: ToolUseBlock } => "toolUse" in b && !!b.toolUse)
        .map((b) => b.toolUse as ToolUseBlock);

      // Execute all in parallel — do NOT execute sequentially or in separate turns
      const toolResults = await Promise.all(
        toolUseBlocks.map(async (tu): Promise<ContentBlock> => {
          const handler = TOOL_HANDLERS[tu.name ?? ""];
          try {
            const result = handler
              ? await handler((tu.input as Record<string, unknown>) ?? {})
              : null;
            return {
              toolResult: {
                toolUseId: tu.toolUseId!,  // echo exactly — mismatch = ValidationException
                status: result !== null ? "success" : "error",
                content: [{ text: result !== null
                  ? JSON.stringify(result)
                  : `Unknown tool: ${tu.name}` }],
              },
            };
          } catch (err) {
            // Do NOT throw — encode error so the model can recover
            return {
              toolResult: {
                toolUseId: tu.toolUseId!,
                status: "error",
                content: [{ text: `Tool failed: ${(err as Error).message}` }],
              },
            };
          }
        })
      );

      // ALL results go in a SINGLE new user turn
      messages.push({ role: "user", content: toolResults });
      continue;
    }

    break; // max_tokens, stop_sequence, guardrail_intervened
  }

  return "";
}

Three rules you cannot break without triggering a ValidationException:

forceToolUse for structured output

Setting toolChoice: { tool: { name: 'extract_data' } } forces the model to call the named tool and nothing else. Because the tool's inputSchema is a JSON Schema, you get the model's output as a typed JSON object without parsing prose — the cleanest structured-output pattern available in the Converse API:

async function extractStructuredData<T>(
  text: string,
  toolName: string,
  schema: Record<string, unknown>,
  schemaDescription: string
): Promise<T> {
  if (!isClaudeModel(MODEL_ID)) {
    throw new Error("forceToolUse requires a Claude model");
  }

  const response = await client.send(new ConverseCommand({
    modelId: MODEL_ID,
    system: [{ text: "Extract structured data from the input. " + schemaDescription }],
    messages: [{ role: "user", content: [{ text }] }],
    toolConfig: {
      tools: [{
        toolSpec: {
          name: toolName,
          description: schemaDescription,
          inputSchema: { json: { type: "object", ...schema } },
        },
      }],
      toolChoice: { tool: { name: toolName } },  // force this exact tool
    },
    inferenceConfig: { maxTokens: 1024, temperature: 0 },
  }));

  if (response.stopReason !== "tool_use") {
    throw new Error(`Expected tool_use, got: ${response.stopReason}`);
  }

  for (const block of response.output?.message?.content ?? []) {
    if ("toolUse" in block && block.toolUse?.name === toolName) {
      return block.toolUse.input as T;
    }
  }
  throw new Error(`Tool call ${toolName} not found in response`);
}

Use temperature: 0 for deterministic extraction. This pattern replaces ad-hoc JSON parsing and is significantly more reliable than asking the model to "respond only with JSON" in prose — especially when the schema has required fields that must all be present.

Part 2: Streaming with ConverseStreamCommand

ConverseStreamCommand accepts the same input shape as ConverseCommand but delivers the response as an AsyncIterable<ConverseStreamOutput>. It is worth using in MCP tool handlers even when you accumulate the full response before returning — because it allows the connection to be aborted mid-generation if the MCP tool call is cancelled, something the non-streaming command cannot do.

The ConverseStreamOutput event union

Every iteration of for await (const event of response.stream) yields exactly one of seven event types:

The most missed gotcha: error events arrive as chunks, not as thrown exceptions

This is the most commonly misunderstood aspect of ConverseStreamCommand. The outer try/catch around client.send(command) catches errors that occur before the stream starts — authentication failures, network timeouts before the first byte, malformed request bodies. But a throttlingException that fires mid-generation, or an internalServerException during model inference, arrives as a chunk inside the for await loop and will not be caught by the outer try/catch. You must check for them on every loop iteration:

async function assembleStreamResponse(messages: Message[]): Promise<{
  content: ContentBlock[];
  stopReason: string;
  inputTokens: number;
  outputTokens: number;
}> {
  const command = new ConverseStreamCommand({
    modelId: MODEL_ID,
    messages,
    inferenceConfig: { maxTokens: 4096, temperature: 0.7 },
  });

  const response = await client.send(command);

  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) {
    // Check all four error event types INSIDE the loop
    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(`Stream validation error: ${event.validationException.message}`);
    }
    if (event.throttlingException) {
      throw new Error(`Throttled mid-stream: ${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) {
        textByIndex.set(
          contentBlockIndex,
          (textByIndex.get(contentBlockIndex) ?? "") + delta.text
        );
      } else if (delta?.toolUse?.input !== undefined) {
        // PARTIAL JSON — do NOT parse here; accumulate the full string
        const block = toolUseByIndex.get(contentBlockIndex);
        if (block) block.inputJson += delta.toolUse.input;
      }
    }

    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 content array in block index order
  const sortedIndexes = [...new Set([
    ...textByIndex.keys(), ...toolUseByIndex.keys()
  ])].sort((a, b) => a - b);

  const content: ContentBlock[] = sortedIndexes.map((idx) => {
    if (textByIndex.has(idx)) return { text: textByIndex.get(idx)! };
    const block = toolUseByIndex.get(idx)!;
    return {
      toolUse: {
        toolUseId: block.toolUseId,
        name: block.name,
        // Safe to parse now — contentBlockStop has fired for this block
        input: JSON.parse(block.inputJson || "{}"),
      },
    };
  });

  return { content, stopReason, inputTokens, outputTokens };
}

Streaming tool calls: collect everything before executing

When stopReason === 'tool_use' from a streaming response, the message may contain multiple parallel tool calls. All are in the assembled content array after the loop exits. Execute them only after the full stream is consumed — never mid-stream. The pattern is identical to the non-streaming case: collect all ToolUseBlock entries, run them in parallel with Promise.all, return all results in one user turn.

AbortController and releasing the connection on early break

Pass an AbortSignal to enforce timeouts on long-running generations:

import { AbortController } from "@smithy/abort-controller";

async function streamWithTimeout(messages: Message[], timeoutMs = 30_000): Promise<string> {
  const abortController = new AbortController();
  const timeoutHandle = setTimeout(
    () => abortController.abort(new Error(`Timed out after ${timeoutMs}ms`)),
    timeoutMs
  );

  try {
    const command = new ConverseStreamCommand({
      modelId: MODEL_ID,
      messages,
      inferenceConfig: { maxTokens: 4096 },
    });

    const response = await client.send(command, {
      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.throttlingException) throw new Error(event.throttlingException.message);
      if (event.contentBlockDelta?.delta?.text) text += event.contentBlockDelta.delta.text;
      if (event.messageStop) break;
    }

    // After break, release the HTTP connection — otherwise the response body
    // continues downloading in the background and leaks connection handles
    await (response.stream as AsyncGenerator).return?.(undefined);

    return text;
  } catch (err: unknown) {
    if (err instanceof Error &&
        (err.name === "AbortError" || err.message.includes("aborted"))) {
      return "[response cancelled]";
    }
    throw err;
  } finally {
    clearTimeout(timeoutHandle);
  }
}

The stream.return() call is mandatory when exiting via break. Without it, the HTTP connection stays open until the full response downloads — a connection handle leak in a long-running MCP server.

No resume token: full retry on stream error

Unlike some streaming APIs, Bedrock Converse does not issue resume tokens. When a network error or mid-stream throttle interrupts a ConverseStreamCommand, the entire call must be retried from scratch with the original messages array. Never append partial assistant content to the messages array before retrying — an incomplete assistant message causes a ValidationException on the retry.

ConverseCommand vs ConverseStreamCommand: when to use each

Use ConverseCommand when: tool use input is what matters (the tool call JSON is fully parsed in one shot); the downstream MCP client does not need incremental text; or simplicity is more valuable than time-to-first-token. Use ConverseStreamCommand when: the response is user-facing and time-to-first-character matters; 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, the streaming assembly complexity adds nothing.

Part 3: Multimodal inputs — ImageBlock and DocumentBlock

The Converse API accepts images and documents alongside text in the same messages[i].content array. Getting multimodal inputs right requires knowing two specific gotchas before writing a single line of code.

Gotcha 1: source.bytes is a Uint8Array, never a base64 string

The single most common multimodal mistake. The source.bytes field expects a Uint8Array of raw binary data. Passing a base64-encoded string — a natural instinct when the image came to your server as a base64 field in a JSON request — causes ValidationException: Invalid image bytes immediately:

import * as fs from "node:fs";
import * as path from "node:path";

// fs.readFileSync returns Buffer (a Uint8Array subclass) — works directly
const imageBytes: Uint8Array = fs.readFileSync("/tmp/screenshot.png");

// From base64 string (received over HTTP):
const imageFromBase64: Uint8Array = Buffer.from(b64str, "base64");
// Buffer.from(b64str, 'base64') returns a Buffer which IS a Uint8Array — no extra conversion

// From data URI (data:image/png;base64,...):
function dataUriToBytes(dataUri: string): { bytes: Uint8Array; format: string } {
  const match = dataUri.match(/^data:(image\/[^;]+);base64,(.+)$/);
  if (!match) throw new Error("Invalid data URI");
  const formatMap: Record<string, string> = {
    "image/jpeg": "jpeg", "image/jpg": "jpeg",
    "image/png": "png", "image/gif": "gif", "image/webp": "webp",
  };
  return {
    bytes: Buffer.from(match[2], "base64"),
    format: formatMap[match[1]] ?? "jpeg",
  };
}

// Correct ImageBlock construction:
const messages: Message[] = [{
  role: "user",
  content: [
    {
      image: {
        format: "png",             // 'jpeg' | 'png' | 'gif' | 'webp'
        source: { bytes: imageBytes },  // Uint8Array — NOT a string
      },
    },
    { text: "Describe what you see in this screenshot." },
  ],
}];

Gotcha 2: DocumentBlock name is required

DocumentBlock follows the same pattern as ImageBlock but adds a required name field. The model uses it in citations ("According to document 'contract.pdf', the clause states…"). Omitting name causes ValidationException: DocumentBlock name is required:

const docBytes: Uint8Array = fs.readFileSync("/tmp/quarterly-report.pdf");

const messages: Message[] = [{
  role: "user",
  content: [
    {
      document: {
        format: "pdf",
        name: path.basename("/tmp/quarterly-report.pdf"),  // "quarterly-report.pdf"
        // name is required — not optional. Use path.basename to strip directory path.
        source: { bytes: docBytes },
      },
    },
    { text: "Summarize the key financial metrics from this report." },
  ],
}];

Supported format values for DocumentBlock: 'pdf', 'csv', 'doc', 'docx', 'xls', 'xlsx', 'html', 'txt', 'md'.

Per-model support matrix

Not all Bedrock models support image and document inputs via Converse. Sending an unsupported block type produces a ValidationException:

Model familyImageBlockDocumentBlock
Anthropic Claude 3, 3.5, 4YesYes
Amazon Nova ProYesNo — ValidationException
Amazon Nova LiteYesNo — ValidationException
Amazon Nova MicroNoNo
Meta Llama 3.2 Vision (11B, 90B)YesNo — ValidationException
Meta Llama 3.1, 3.3 (non-vision)NoNo
Amazon Titan (all)NoNo
Cohere Command R+NoNo
Mistral (all)NoNo

The error message for sending a DocumentBlock to Nova Pro/Lite is "Document type not supported for this model" — not an image-related error message even when documents are the problem. Check capability before constructing multimodal content when your MCP tool needs to support multiple models.

File size limits and context window budget

Context window token consumption also matters. Each image uses 1,000–4,000 tokens depending on dimensions and content complexity. For Claude 3.5 Sonnet (200k context), 20 large images consume up to 80,000 tokens — leaving 120,000 for text and response. For Claude 3 Haiku (48k context), 20 large images would overflow entirely. Validate byte sizes and estimate token consumption before batching images.

S3 location: Bedrock uses its own service principal

Instead of embedding raw bytes, both block types can reference S3 objects via source.s3Location. The critical IAM detail: when Bedrock fetches objects from S3, it uses the Bedrock service principal (bedrock.amazonaws.com) — not your Lambda execution role or ECS task role. Grant s3:GetObject to the Bedrock service principal in your bucket policy, not to your application role:

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "Service": "bedrock.amazonaws.com" },
    "Action": "s3:GetObject",
    "Resource": "arn:aws:s3:::my-bucket/bedrock-inputs/*",
    "Condition": {
      "StringEquals": { "aws:SourceAccount": "123456789012" }
    }
  }]
}

// S3 location usage:
const messages: Message[] = [{
  role: "user",
  content: [
    {
      document: {
        format: "pdf",
        name: "contract.pdf",
        source: {
          s3Location: {
            uri: "s3://my-bucket/contracts/contract.pdf",
            mediaType: "application/pdf",
          },
        },
      },
    },
    { text: "Review this contract and identify any unusual clauses." },
  ],
}];

The S3 bucket must be in the same AWS region as the Bedrock endpoint. Cross-region S3 references produce an access error from Bedrock regardless of bucket policy.

Scanned PDFs: render to images for OCR

When a PDF is passed as a DocumentBlock, Claude extracts and reads the text layer. For scanned PDFs — where pages are photographed images with no selectable text — the text layer is empty and Claude cannot read the content via DocumentBlock. The correct approach is to convert each page to a raster image and pass it as an ImageBlock:

import * as pdfjsLib from "pdfjs-dist/legacy/build/pdf.mjs";
import { createCanvas } from "canvas";

async function pdfPagesToImages(
  pdfBytes: Uint8Array,
  maxPages = 5
): Promise<Uint8Array[]> {
  const pdfDoc = await pdfjsLib.getDocument({ data: pdfBytes }).promise;
  const pageCount = Math.min(pdfDoc.numPages, maxPages);
  const pages: Uint8Array[] = [];

  for (let pageNum = 1; pageNum <= pageCount; pageNum++) {
    const page = await pdfDoc.getPage(pageNum);
    const viewport = page.getViewport({ scale: 2.0 }); // 2x for legibility
    const canvas = createCanvas(viewport.width, viewport.height);
    await page.render({
      canvasContext: canvas.getContext("2d") as unknown as CanvasRenderingContext2D,
      viewport,
    }).promise;
    pages.push(canvas.toBuffer("image/png")); // Buffer is Uint8Array subclass
  }

  return pages;
}

// In the MCP tool handler:
const pageImages = await pdfPagesToImages(pdfBytes, 5);
const messages: Message[] = [{
  role: "user",
  content: [
    ...pageImages.map((pageBytes) => ({
      image: { format: "png" as const, source: { bytes: pageBytes } },
    })),
    { text: `${pageImages.length} pages from a scanned PDF. Extract all text in document order.` },
  ],
}];

Limit pages per Converse call. Each rendered page at 2x scale is 300–800 KB and 2,000–4,000 tokens. Ten pages at the high end consumes 40,000 tokens just for images. For PDFs longer than 10 pages, process in batches of 5–10 pages and concatenate the extracted text.

Part 4: System prompts and conversation management

System prompts shape model behavior. Conversation history carries context across turns. Both have structural rules that cause ValidationException when violated, and both interact with the model's context window in ways that can silently degrade quality if ignored.

SystemContentBlock: the only valid form

The system field of ConverseCommandInput is typed as SystemContentBlock[] | undefined. The only valid element shape is { text: string }. Three constraints:

// Multiple blocks are concatenated — split for readability, not semantic separation
const system: SystemContentBlock[] = [
  { text: "You are a monitoring assistant for AliveMCP." },
  { text: "Users ask about their MCP server uptime, latency metrics, and alert configuration." },
  { text: "Respond in concise Markdown. Never fabricate server names or metric values." },
];

System prompt design for MCP tool contexts

An MCP tool handler calling Converse is different from a user-facing chatbot in several ways: the "user" is typically another LLM (the MCP host), tool call arguments carry structured intent, and the response will often be parsed by software. These differences should shape your system prompt:

Message array structural rules

The messages array must satisfy three structural constraints at every API call:

// Conversation history that includes a tool-use exchange
const messages: Message[] = [
  // Turn 1: user asks
  { role: "user", content: [{ text: "What is the latency of prod-01?" }] },
  // Turn 2: assistant calls a tool
  {
    role: "assistant",
    content: [{
      toolUse: {
        toolUseId: "tool-call-001",  // must echo exactly in next turn
        name: "get_server_status",
        input: { serverId: "prod-01" },
      },
    }],
  },
  // Turn 3: user provides tool result — must follow immediately
  {
    role: "user",
    content: [{
      toolResult: {
        toolUseId: "tool-call-001",  // must match exactly
        content: [{ text: JSON.stringify({ serverId: "prod-01", p99LatencyMs: 42, status: "up" }) }],
      },
    }],
  },
  // Turn 4: assistant synthesizes
  { role: "assistant", content: [{ text: "Server prod-01 is up with p99 latency of 42ms." }] },
  // Turn 5: user follow-up
  { role: "user", content: [{ text: "Is that within normal range?" }] },
];

Context window limits by model

The API does not enforce context limits at input validation — the model throws or truncates silently when exceeded. Know the limits before you hit them:

ModelContext Window
Claude 3.5 Sonnet v2 / Claude 4 Sonnet / Claude 3.5 Haiku200,000 tokens
Amazon Nova Lite / Nova Pro300,000 tokens
Amazon Nova Micro / Meta Llama 3.1 70B128,000 tokens
Mistral Large / Amazon Titan Premier32,000 tokens

Mistral Large and Titan Premier have the most constrained windows. With a 500-token system prompt, 10 tool schemas averaging 300 tokens each, and an 80% utilization target, you have roughly 22,100 tokens of message history budget — approximately 16–20 exchanges of moderate length. Tool schemas count against the context window too — measure them at startup:

function estimateTokens(text: string): number {
  return Math.ceil(text.length / 4);  // ~4 chars/token for English; code may be ~3
}

function estimateToolSchemaTokens(tools: Tool[]): number {
  return tools.reduce((sum, t) =>
    sum +
    estimateTokens(t.toolSpec?.name ?? "") +
    estimateTokens(t.toolSpec?.description ?? "") +
    estimateTokens(JSON.stringify(t.toolSpec?.inputSchema?.json ?? {})),
  0);
}

const TOOL_SCHEMA_TOKEN_ESTIMATE = estimateToolSchemaTokens(MY_TOOLS);
console.log(`Tool schema overhead: ~${TOOL_SCHEMA_TOKEN_ESTIMATE} tokens`);

Sliding window for long conversation histories

When conversation history grows long enough to approach the context limit, trim old turns from the front. The invariants you must preserve:

interface SlidingWindowConfig {
  modelContextLimit: number;
  systemTokens: number;
  toolSchemaTokens: number;
  utilizationTarget: number;  // e.g. 0.8
}

function applySlididingWindow(
  messages: Message[],
  config: SlidingWindowConfig
): Message[] {
  const messageBudget =
    Math.floor(config.modelContextLimit * config.utilizationTarget) -
    config.systemTokens - config.toolSchemaTokens;

  let trimmed = [...messages];

  while (trimmed.length > 1 && estimateMessageTokens(trimmed) > messageBudget) {
    if (trimmed[0]?.role !== "user") break;

    const isToolUseTurn =
      trimmed[1]?.role === "assistant" &&
      trimmed[1]?.content?.some((b) => "toolUse" in b) &&
      trimmed[2]?.role === "user" &&
      trimmed[2]?.content?.some((b) => "toolResult" in b);

    if (isToolUseTurn && trimmed.length >= 4) {
      trimmed = trimmed.slice(4);  // drop user, assistant(toolUse), user(toolResult), assistant(text)
    } else if (trimmed.length >= 2) {
      trimmed = trimmed.slice(2);  // drop user, assistant(text)
    } else {
      break;
    }
  }

  return trimmed;
}

function estimateMessageTokens(messages: Message[]): number {
  return messages.reduce((sum, msg) => {
    for (const block of msg.content ?? []) {
      if ("text" in block) sum += estimateTokens(block.text ?? "");
      if ("toolUse" in block && block.toolUse) {
        sum += estimateTokens(block.toolUse.name ?? "");
        sum += estimateTokens(JSON.stringify(block.toolUse.input ?? {}));
      }
      if ("toolResult" in block && block.toolResult) {
        for (const c of block.toolResult.content ?? []) {
          if ("text" in c) sum += estimateTokens(c.text ?? "");
        }
      }
    }
    return sum;
  }, 0);
}

Stateless MCP servers: history comes from the client

MCP servers are typically stateless — they receive a tool call, do work, and return a result with no persistent in-memory state between calls. The pattern for Bedrock Converse in a stateless MCP server: the client serializes conversation history into the tool call arguments; the handler deserializes it, rebuilds Message[], appends the new user message, applies the sliding window, calls Converse, and returns the assistant response. The client then stores the new assistant turn for the next call.

Do NOT maintain an in-memory Map<sessionId, Message[]> unless the server is explicitly designed as a stateful session server with TTL eviction and horizontal scale handling. In-memory state silently breaks when the process restarts or scales to multiple instances. If you need server-side session state, use DynamoDB or Redis keyed by session ID with an explicit TTL.

Prompt caching for static system prompts

If your system prompt is the same string on every request, Bedrock prompt caching can significantly reduce input token billing. Add the cachePoint marker after the last system block you want cached:

const system: SystemContentBlock[] = [
  { text: "You are an uptime monitoring assistant for AliveMCP." },
  { text: "Respond in Markdown. Never fabricate metric values." },
  // Cache point: everything above is the cached prefix (must be ≥1,024 tokens)
  { cachePoint: { type: "default" } } as unknown as SystemContentBlock,
  // Dynamic suffix (varies per request):
  { text: `User is on the ${userPlan} plan.` },
];

The minimum cacheable prefix length is 1,024 tokens for most models. Requests that hit the cache are charged at a discounted input token rate. Verify cache hits from the response's usage.cacheReadInputTokenCount field. See the full Bedrock prompt caching guide for placement rules and cache TTL behavior.

Handling guardrail_intervened

When Bedrock Guardrails are configured and a turn is blocked, the response has stopReason: "guardrail_intervened" and an empty or redacted content array — this is not an exception, it is HTTP 200. Check stopReason explicitly and return a user-friendly message rather than attempting to parse an empty content array:

const assistantText = response.stopReason === "guardrail_intervened"
  ? "I'm not able to respond to that request."
  : (response.output?.message?.content ?? [])
      .filter((b): b is { text: string } => "text" in b)
      .map((b) => b.text)
      .join("") ?? "";

Twelve production gotchas consolidated

  1. Tool name contains space or dot. get.weather and get weather both cause ValidationException before the model is invoked. Name must match [a-zA-Z0-9_-]{1,64}.
  2. toolUseId mismatch in ToolResultBlock. Echo the exact string from the ToolUseBlock. Even a capitalization difference causes ValidationException on the next call.
  3. Tool results split across two user turns. When the model calls two tools in one turn, both results must be in a single subsequent user turn. Two consecutive user messages is a role-alternation violation.
  4. Empty ToolResultBlock content. Always include at least one TextBlock. An empty content array causes ValidationException.
  5. toolChoice: ANY or TOOL with Llama/Titan. These modes are Claude-only. Passing them with other model families causes ValidationException.
  6. JSON Schema root is not type: 'object'. The inputSchema.json root must be an object schema. Array and primitive roots are rejected.
  7. Error events arrive as chunks, not throws. internalServerException, modelStreamErrorException, validationException, and throttlingException appear as event properties inside the for await loop. The outer try/catch around client.send() does not catch them.
  8. Partial tool input JSON — parse only at contentBlockStop. Each contentBlockDelta for a tool use block delivers a JSON fragment. Concatenate all fragments and call JSON.parse only after the corresponding contentBlockStop.
  9. Call stream.return() on early break. Exiting the for await loop via break without calling stream.return() leaves the HTTP connection open — a connection handle leak in a long-running server.
  10. source.bytes is Uint8Array, never base64 string. The most common multimodal mistake. Buffer.from(b64str, 'base64') converts to Uint8Array correctly.
  11. DocumentBlock name is required. Omitting it causes ValidationException: DocumentBlock name is required. Use the filename without the directory path.
  12. Dropping half a tool-use pair when trimming history. The assistant ToolUseBlock turn and the following user ToolResultBlock turn are an atomic unit. Dropping one without the other leaves an orphaned block that breaks role alternation.

Putting it all together: a complete production MCP tool handler

This handler combines all four patterns — tool use loop, streaming for user-visible responses, multimodal input handling, and conversation management with sliding window context trimming:

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import {
  BedrockRuntimeClient,
  ConverseCommand,
  type Message,
  type ContentBlock,
  type SystemContentBlock,
  type Tool,
} from "@aws-sdk/client-bedrock-runtime";
import * as fs from "node:fs";
import * as path from "node:path";

const client = new BedrockRuntimeClient({ region: process.env.AWS_REGION ?? "us-east-1" });
const MODEL_ID = process.env.BEDROCK_MODEL_ID ?? "us.anthropic.claude-3-5-sonnet-20241022-v2:0";

const SYSTEM: SystemContentBlock[] = [
  { text: "You are an intelligent assistant for AliveMCP. Help users analyze files, " +
           "query data sources, and monitor their MCP server infrastructure." },
  { text: "Respond in Markdown. Never fabricate server names, metric values, or file contents." },
];
const SYSTEM_TOKEN_ESTIMATE = Math.ceil(
  SYSTEM.reduce((s, b) => s + (b.text?.length ?? 0), 0) / 4
);

const TOOLS: Tool[] = [/* your tool definitions */];
const TOOL_SCHEMA_TOKENS = estimateToolSchemaTokens(TOOLS);

const server = new McpServer({ name: "production-bedrock-server", version: "1.0.0" });

server.tool(
  "bedrock_agent",
  {
    message: z.string().describe("User message"),
    file_path: z.string().optional().describe("Optional file to analyze (image or document)"),
    conversation_history: z.array(z.object({
      role: z.enum(["user", "assistant"]),
      content: z.string(),
    })).optional().describe("Prior conversation turns"),
  },
  async ({ message, file_path, conversation_history }) => {
    // Build content blocks for this user turn
    const userContent: ContentBlock[] = [];

    if (file_path && fs.existsSync(file_path)) {
      const bytes = fs.readFileSync(file_path);
      const ext = path.extname(file_path).toLowerCase().slice(1);
      const imageExts = { jpg: "jpeg", jpeg: "jpeg", png: "png", gif: "gif", webp: "webp" };
      const docExts = { pdf: "pdf", csv: "csv", docx: "docx", xlsx: "xlsx", txt: "txt", md: "md" };

      if (imageExts[ext]) {
        userContent.push({ image: { format: imageExts[ext] as any, source: { bytes } } });
      } else if (docExts[ext]) {
        userContent.push({ document: { format: docExts[ext] as any, name: path.basename(file_path), source: { bytes } } });
      }
    }

    userContent.push({ text: message });

    // Build and trim message history
    const history: Message[] = (conversation_history ?? []).map((t) => ({
      role: t.role,
      content: [{ text: t.content }],
    }));
    history.push({ role: "user", content: userContent });

    const trimmed = applySlididingWindow(history, {
      modelContextLimit: 200_000,
      systemTokens: SYSTEM_TOKEN_ESTIMATE,
      toolSchemaTokens: TOOL_SCHEMA_TOKENS,
      utilizationTarget: 0.8,
    });

    // Run the agentic loop
    const responseText = await runConverseLoop(SYSTEM, trimmed, TOOLS);
    return { content: [{ type: "text", text: responseText }] };
  }
);

Monitor your Bedrock Converse MCP tools with AliveMCP

AliveMCP monitors MCP server endpoints for uptime, latency spikes, and error rates. When a Bedrock Converse tool handler starts throwing ValidationExceptions from malformed tool configurations, hitting context window limits, or returning mid-stream errors, AliveMCP alerts you before it impacts downstream agents and users.

Start free monitoring