Guide · Amazon Bedrock · Converse API · Tool Use
MCP Server Bedrock Converse Tool Use — multi-turn loops, ToolUseBlock, parallel calls
The AWS Bedrock Converse API's tool use system lets MCP server handlers run a full agentic loop — the model decides which tools to call, your code executes them, and the loop continues until the model is done. This page goes deeper than the Bedrock Converse API overview, which covers model IDs, InferenceConfiguration, basic streaming, and ConverseToolConfig at a high level. Here we cover the precise shape of ToolConfiguration, all three ToolChoice modes and which models support them, the exact multi-turn loop structure with stopReason: 'tool_use', parallel ToolUseBlock execution, and the ToolResultBlock contract including error responses and rich content types. The API is in @aws-sdk/client-bedrock-runtime and the key types are ToolConfiguration, Tool, ToolUseBlock, ToolResultBlock, ContentBlock, Message, and StopReason. For streaming tool calls see Converse streaming; for returning images and documents from tools see rich tool results with images; for multi-turn system prompts see system prompts for multi-turn; for a heavier orchestration alternative see Bedrock Inline Agents.
TL;DR
Pass toolConfig in ConverseCommandInput with an array of Tool objects (each carrying a JSON Schema for inputs). Loop: call ConverseCommand, if stopReason === 'tool_use' extract all ToolUseBlock entries, run them all in parallel, build one user turn containing all ToolResultBlock entries echoing the exact toolUseId, append both the assistant turn and the new user turn to messages, repeat. Exit when stopReason === 'end_turn'.
ToolConfiguration structure
Tools are declared in the toolConfig field of ConverseCommandInput. The field accepts a ToolConfiguration object with two properties: tools (an array of Tool objects) and an optional toolChoice (covered in the next section). Each Tool in the array is a discriminated union — in practice you always use the toolSpec variant:
import {
BedrockRuntimeClient,
ConverseCommand,
ConverseCommandInput,
Tool,
ToolConfiguration,
ToolUseBlock,
ToolResultBlock,
ContentBlock,
Message,
StopReason,
} from "@aws-sdk/client-bedrock-runtime";
// A Tool object with a full JSON Schema for its input
const weatherTool: Tool = {
toolSpec: {
name: "get_weather", // [a-zA-Z0-9_-]{1,64} — no spaces or dots
description:
"Fetch the current weather for a city. Returns temperature in Celsius, " +
"humidity percentage, and a short condition string.",
inputSchema: {
json: {
// Root must be type: 'object' — arrays and primitives are rejected
$schema: "http://json-schema.org/draft-07/schema#",
type: "object",
properties: {
city: {
type: "string",
description: "City name, e.g. 'Berlin' or 'Tokyo'",
},
units: {
type: "string",
enum: ["celsius", "fahrenheit"],
description: "Temperature unit. Defaults to celsius.",
},
},
required: ["city"],
},
},
},
};
const calendarTool: Tool = {
toolSpec: {
name: "list_calendar_events",
description: "List upcoming calendar events for a date range.",
inputSchema: {
json: {
$schema: "http://json-schema.org/draft-07/schema#",
type: "object",
properties: {
start_date: {
type: "string",
format: "date",
description: "Start of the range in YYYY-MM-DD format",
},
end_date: {
type: "string",
format: "date",
description: "End of the range in YYYY-MM-DD format",
},
max_results: {
type: "integer",
minimum: 1,
maximum: 50,
description: "Maximum number of events to return",
},
},
required: ["start_date", "end_date"],
},
},
},
};
const toolConfig: ToolConfiguration = {
tools: [weatherTool, calendarTool],
// toolChoice defaults to AUTO — omit it unless you need specific behavior
};
Key constraints for toolSpec fields:
| Field | Constraint | Violation result |
|---|---|---|
name | Regex [a-zA-Z0-9_-]{1,64} | ValidationException |
description | Max 1,000 characters; required | ValidationException |
inputSchema.json root type | Must be "object" | ValidationException |
inputSchema.json.$schema | Optional; JSON Schema draft-07 recommended | No error if omitted |
| Number of tools | Up to 64 per request on most models | ValidationException |
The most common mistake is using a dot or space in the tool name (e.g., "get.weather" or "get weather"). Both cause a ValidationException before the model is called. Use underscores or hyphens as word separators. Also note that the JSON Schema for tool inputs must have type: "object" at the root — a schema rooted at type: "array" or a primitive like type: "string" is rejected even if it is otherwise valid JSON Schema.
ToolChoice: AUTO, ANY, and TOOL
The optional toolChoice field inside ToolConfiguration controls whether the model must call a tool. There are three variants:
| toolChoice value | Meaning | Models |
|---|---|---|
{ auto: {} } | Model decides whether to call a tool or reply in text. Default when omitted. | All |
{ any: {} } | Model must call at least one tool. Cannot reply in pure text. | Claude only |
{ tool: { name: "get_weather" } } | Model must call this specific tool and no other. | Claude only |
toolChoice: { any: {} } and toolChoice: { tool: { name: '...' } } throw ValidationException for Amazon Titan and Meta Llama models. These models only support auto (or omitting toolChoice entirely). Always guard ANY and TOOL choices behind model-family detection:
type SupportedModel =
| "anthropic.claude-3-5-sonnet-20241022-v2:0"
| "anthropic.claude-3-haiku-20240307-v1:0"
| "anthropic.claude-3-sonnet-20240229-v1:0"
| "amazon.nova-pro-v1:0"
| "amazon.nova-lite-v1:0"
| "meta.llama3-70b-instruct-v1:0"
| "amazon.titan-text-premier-v1:0";
function isClaudeModel(modelId: string): boolean {
return modelId.startsWith("anthropic.claude");
}
function buildToolConfig(
tools: Tool[],
forceToolName?: string
): ToolConfiguration {
const toolConfig: ToolConfiguration = { tools };
if (forceToolName) {
if (!isClaudeModel(MODEL_ID)) {
throw new Error(
`toolChoice: TOOL is not supported by model ${MODEL_ID}. ` +
`Only Anthropic Claude models on Bedrock support forced tool calls.`
);
}
toolConfig.toolChoice = { tool: { name: forceToolName } };
}
return toolConfig;
}
The toolChoice: { tool: { name: '...' } } variant (forced tool call) is especially useful for structured output extraction: declare a single tool whose JSON Schema describes the structure you want, force the model to call it, then read input from the ToolUseBlock as your structured JSON without having to parse prose. This pattern is covered in detail in the forceToolUse pattern section below.
The multi-turn tool use loop
The Converse API is stateless — it does not remember past turns. 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 call tools, it sets stopReason to 'tool_use' and includes ToolUseBlock entries in response.output.message.content. Your code must run those tools and feed the results back as a new user turn, then call the API again. The loop continues until stopReason is 'end_turn'.
import { randomUUID } from "node:crypto";
import {
BedrockRuntimeClient,
ConverseCommand,
ConverseCommandInput,
Tool,
ToolConfiguration,
ToolUseBlock,
ToolResultBlock,
ContentBlock,
Message,
} from "@aws-sdk/client-bedrock-runtime";
const client = new BedrockRuntimeClient({
region: process.env.AWS_REGION ?? "us-east-1",
});
const MODEL_ID =
process.env.BEDROCK_MODEL_ID ?? "anthropic.claude-3-haiku-20240307-v1:0";
// --- Tool implementations ---
interface WeatherResult {
city: string;
temp_c: number;
humidity: number;
condition: string;
}
async function getWeather(
city: string,
units: "celsius" | "fahrenheit" = "celsius"
): Promise<WeatherResult> {
// Real implementation would call a weather API
return { city, temp_c: 18, humidity: 72, condition: "partly cloudy" };
}
async function listCalendarEvents(
startDate: string,
endDate: string,
maxResults = 10
): Promise<{ events: Array<{ title: string; date: string }> }> {
// Real implementation would call Google Calendar / Exchange
return { events: [{ title: "Team standup", date: startDate }] };
}
// --- Tool dispatch table ---
type ToolHandler = (input: Record<string, unknown>) => Promise<unknown>;
const TOOL_HANDLERS: Record<string, ToolHandler> = {
get_weather: async (input) => {
const city = input.city as string;
const units = (input.units as "celsius" | "fahrenheit") ?? "celsius";
return getWeather(city, units);
},
list_calendar_events: async (input) => {
return listCalendarEvents(
input.start_date as string,
input.end_date as string,
(input.max_results as number) ?? 10
);
},
};
// --- Core multi-turn loop ---
async function runConverseLoop(
systemPrompt: string,
userMessage: string,
tools: Tool[]
): Promise<string> {
const messages: Message[] = [
{ role: "user", content: [{ text: userMessage }] },
];
const toolConfig: ToolConfiguration = { tools };
let finalText = "";
// Loop until end_turn (or max iterations as a safety limit)
for (let iteration = 0; iteration < 10; iteration++) {
const input: ConverseCommandInput = {
modelId: MODEL_ID,
system: [{ text: systemPrompt }],
messages,
toolConfig,
inferenceConfig: { maxTokens: 2048, temperature: 0.1 },
};
const response = await client.send(new ConverseCommand(input));
const assistantMessage = response.output?.message;
if (!assistantMessage) {
throw new Error("Converse returned no message in output");
}
// Always append the assistant's turn to the history
messages.push(assistantMessage);
if (response.stopReason === "end_turn") {
// Extract text from the final assistant message
for (const block of assistantMessage.content ?? []) {
if ("text" in block && typeof block.text === "string") {
finalText += block.text;
}
}
break;
}
if (response.stopReason === "tool_use") {
// Collect every ToolUseBlock in this assistant turn
const toolUseBlocks: ToolUseBlock[] = [];
for (const block of assistantMessage.content ?? []) {
if ("toolUse" in block && block.toolUse) {
toolUseBlocks.push(block.toolUse as ToolUseBlock);
}
}
if (toolUseBlocks.length === 0) {
throw new Error(
"stopReason is tool_use but no ToolUseBlock found in content"
);
}
// Execute ALL tool calls in parallel
const toolResults = await Promise.all(
toolUseBlocks.map(async (tu): Promise<ContentBlock> => {
const handler = TOOL_HANDLERS[tu.name ?? ""];
let resultContent: ContentBlock["toolResult"] extends infer T
? T extends { content: Array<infer C> } ? C[] : never
: never;
if (!handler) {
// Unknown tool — return an error result
return {
toolResult: {
toolUseId: tu.toolUseId!, // must echo exactly
status: "error",
content: [
{
text: `Unknown tool: ${tu.name}. Available tools: ${Object.keys(TOOL_HANDLERS).join(", ")}`,
},
],
},
};
}
try {
const result = await handler(
(tu.input as Record<string, unknown>) ?? {}
);
return {
toolResult: {
toolUseId: tu.toolUseId!, // must echo exactly — mismatch = ValidationException
status: "success",
content: [{ text: JSON.stringify(result) }],
},
};
} catch (err) {
// Do NOT throw — return error status so the model can recover
return {
toolResult: {
toolUseId: tu.toolUseId!,
status: "error",
content: [
{
text: `Tool execution failed: ${err instanceof Error ? err.message : String(err)}`,
},
],
},
};
}
})
);
// ALL tool results go into a SINGLE new user turn
messages.push({
role: "user",
content: toolResults,
});
// Continue the loop — the model will synthesize the tool results
continue;
}
// Handle other stop reasons (max_tokens, stop_sequence, guardrail_intervened)
break;
}
return finalText;
}
Three rules you cannot violate without triggering a ValidationException: First, toolUseId in each ToolResultBlock must match the toolUseId from the corresponding ToolUseBlock exactly — a mismatch (even by capitalization) causes a ValidationException on the next API call. Second, all ToolUseBlock entries from one assistant turn must be answered in a single user turn — you cannot answer them one at a time across multiple user turns. Third, the content array inside a ToolResultBlock must not be empty; at minimum include one TextBlock. An empty content array causes a ValidationException.
Parallel tool calls
Claude models on Bedrock can emit multiple ToolUseBlock entries in a single assistant response. For example, given the prompt "What is the weather in Berlin and what meetings do I have today?", Claude may return one assistant turn that contains both a get_weather ToolUseBlock and a list_calendar_events ToolUseBlock. Both must be executed and both results returned together in one user turn — not in two separate user turns.
// Correct: all results in one user turn
messages.push({
role: "user",
content: [
{
toolResult: {
toolUseId: "tooluse_abc123", // get_weather result
status: "success",
content: [{ text: '{"city":"Berlin","temp_c":14,"condition":"cloudy"}' }],
},
},
{
toolResult: {
toolUseId: "tooluse_def456", // list_calendar_events result
status: "success",
content: [{ text: '{"events":[{"title":"Standup","date":"2026-11-26"}]}' }],
},
},
],
});
// WRONG: results split across two user turns — causes ValidationException
messages.push({ role: "user", content: [{ toolResult: { toolUseId: "tooluse_abc123", ... } }] });
messages.push({ role: "user", content: [{ toolResult: { toolUseId: "tooluse_def456", ... } }] });
Amazon Titan and Meta Llama models return at most one ToolUseBlock per assistant turn, so they never trigger the parallel-execution path. Claude 3 Haiku, Sonnet, and Opus — and Amazon Nova models — can return multiple. Write your loop to always collect all blocks before executing, regardless of model, so the code works correctly with any model you configure.
Use Promise.all (as shown in the loop above) rather than sequential await inside a for loop. If the two tool calls take 500ms each, Promise.all costs 500ms total; sequential execution costs 1,000ms. For MCP server handlers where latency is user-visible, this matters.
ToolResultBlock structure in depth
The ToolResultBlock interface has three fields: toolUseId, status, and content. The content field is an array that can hold TextBlock, ImageBlock, or DocumentBlock entries — not arbitrary JSON. Here are all three variants:
import {
ToolResultBlock,
ImageBlock,
DocumentBlock,
} from "@aws-sdk/client-bedrock-runtime";
// 1. Text result — most common, works for all models
const textResult: ContentBlock = {
toolResult: {
toolUseId: "tooluse_abc123",
status: "success",
content: [
{ text: JSON.stringify({ city: "Berlin", temp_c: 14 }) },
],
},
};
// 2. Image result — return a screenshot, chart, or photo from a tool
// Model must support vision (Claude 3+, Nova Pro/Lite)
const imageResult: ContentBlock = {
toolResult: {
toolUseId: "tooluse_bcd234",
status: "success",
content: [
{ text: "Here is the requested chart:" },
{
image: {
format: "png", // "png" | "jpeg" | "gif" | "webp"
source: {
bytes: Buffer.from(pngBytes), // Uint8Array of raw image bytes
},
},
},
],
},
};
// 3. Document result — return a PDF or text file from a tool
const documentResult: ContentBlock = {
toolResult: {
toolUseId: "tooluse_cde345",
status: "success",
content: [
{
document: {
format: "pdf", // "pdf" | "csv" | "doc" | "docx" | "xls" | "xlsx" | "html" | "txt" | "md"
name: "quarterly_report",
source: {
bytes: Buffer.from(pdfBytes),
},
},
},
],
},
};
// 4. Error result — signals tool execution failure without throwing
const errorResult: ContentBlock = {
toolResult: {
toolUseId: "tooluse_def456",
status: "error",
content: [
{
text: "Failed to fetch weather: upstream API returned HTTP 503. " +
"Please try again or use a different city.",
},
],
},
};
When you set status: "error", the model receives the error message and can decide how to respond — it may retry with different parameters, explain the failure to the user, or fall back to general knowledge. This is far better than throwing an exception from your tool handler, which would crash the entire loop and return an error to the MCP caller with no useful output. Always catch errors inside the per-tool execution and encode them as status: "error" results. For more on image and document results see rich tool results with images and documents.
forceToolUse pattern 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. This is the cleanest structured-output pattern available in the Converse API.
import {
BedrockRuntimeClient,
ConverseCommand,
ConverseCommandInput,
Tool,
ToolConfiguration,
} from "@aws-sdk/client-bedrock-runtime";
// Schema for extracting structured job posting data
const extractJobTool: Tool = {
toolSpec: {
name: "extract_job_data",
description:
"Extract structured data from a job posting. Call this tool with all " +
"fields you can identify from the posting text.",
inputSchema: {
json: {
$schema: "http://json-schema.org/draft-07/schema#",
type: "object",
properties: {
title: { type: "string", description: "Job title" },
company: { type: "string", description: "Company name" },
location: {
type: "string",
description: "Location or 'Remote'",
},
salary_min: {
type: "number",
description: "Minimum annual salary in USD, if stated",
},
salary_max: {
type: "number",
description: "Maximum annual salary in USD, if stated",
},
required_skills: {
type: "array",
items: { type: "string" },
description: "List of required technical skills",
},
seniority: {
type: "string",
enum: ["junior", "mid", "senior", "staff", "principal", "unknown"],
},
},
required: ["title", "company", "location", "required_skills", "seniority"],
},
},
},
};
interface ExtractedJob {
title: string;
company: string;
location: string;
salary_min?: number;
salary_max?: number;
required_skills: string[];
seniority: "junior" | "mid" | "senior" | "staff" | "principal" | "unknown";
}
async function extractJobPosting(postingText: string): Promise<ExtractedJob> {
// Only Claude supports toolChoice: TOOL — guard accordingly
if (!MODEL_ID.startsWith("anthropic.claude")) {
throw new Error(
"Forced tool call requires a Claude model. " +
`Current model: ${MODEL_ID}`
);
}
const input: ConverseCommandInput = {
modelId: MODEL_ID,
system: [
{
text: "You are a data extraction assistant. Extract all available " +
"structured data from the provided job posting.",
},
],
messages: [
{
role: "user",
content: [{ text: `Extract data from this job posting:\n\n${postingText}` }],
},
],
toolConfig: {
tools: [extractJobTool],
toolChoice: {
tool: { name: "extract_job_data" }, // force this exact tool
},
},
inferenceConfig: { maxTokens: 1024, temperature: 0 },
};
const response = await client.send(new ConverseCommand(input));
// With toolChoice: TOOL, stopReason will be 'tool_use' on the first call
if (response.stopReason !== "tool_use") {
throw new Error(`Unexpected stopReason: ${response.stopReason}`);
}
const content = response.output?.message?.content ?? [];
for (const block of content) {
if ("toolUse" in block && block.toolUse?.name === "extract_job_data") {
return block.toolUse.input as ExtractedJob;
}
}
throw new Error("extract_job_data tool call not found in response");
}
Because the model is forced to call the tool and the tool's schema defines required fields, the returned toolUse.input is a JSON object conforming to the schema. Set 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.
MCP-specific pattern: bedrock_llm_query tool
The natural MCP pattern for Bedrock Converse tool use is to expose the entire agentic loop as a single MCP tool. The MCP client (Claude Desktop, Cursor, etc.) passes a prompt plus optional tool schemas and receives the final assistant text after the loop completes. This decouples the tool implementations from the MCP layer — the MCP server handles the loop internally.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import {
BedrockRuntimeClient,
ConverseCommand,
Tool,
Message,
ContentBlock,
} from "@aws-sdk/client-bedrock-runtime";
const bedrockClient = new BedrockRuntimeClient({
region: process.env.AWS_REGION ?? "us-east-1",
});
const MODEL_ID =
process.env.BEDROCK_MODEL_ID ?? "anthropic.claude-3-haiku-20240307-v1:0";
// Tool schema passed in by the MCP caller as JSON strings
const ToolSchemaInput = z.object({
name: z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/, {
message: "Tool name must match [a-zA-Z0-9_-]{1,64}",
}),
description: z.string().max(1000),
input_schema: z.record(z.unknown()),
});
// Tool result passed back by the MCP caller
const ToolResultInput = z.object({
tool_use_id: z.string(),
content: z.string(), // JSON-encoded result
is_error: z.boolean().default(false),
});
const server = new McpServer({ name: "bedrock-converse-server", version: "1.0.0" });
server.tool(
"bedrock_llm_query",
{
prompt: z.string().describe("User message to send to the model"),
system: z.string().optional().describe("System prompt for the model"),
tool_schemas: z
.array(ToolSchemaInput)
.optional()
.describe("Optional tool schemas the model may call"),
prior_tool_results: z
.array(ToolResultInput)
.optional()
.describe(
"Tool results from a previous bedrock_llm_query call, " +
"used to continue a tool-use loop across MCP invocations"
),
model_id: z
.string()
.optional()
.describe("Override the default model ID"),
},
async ({ prompt, system, tool_schemas, prior_tool_results, model_id }) => {
const effectiveModel = model_id ?? MODEL_ID;
// Build Tool objects from the caller-supplied schemas
const tools: Tool[] = (tool_schemas ?? []).map((s) => ({
toolSpec: {
name: s.name,
description: s.description,
inputSchema: { json: s.input_schema },
},
}));
const messages: Message[] = [];
// If there are prior tool results, reconstruct a partial conversation
if (prior_tool_results && prior_tool_results.length > 0) {
// Caller is continuing a loop — the prompt here is the original user message
messages.push({ role: "user", content: [{ text: prompt }] });
// The prior assistant turn (which made tool calls) is not known here,
// so callers must pass the assistant's raw content blocks separately for
// multi-turn resumption. For single-pass use, prior_tool_results is empty.
messages.push({
role: "user",
content: prior_tool_results.map((r): ContentBlock => ({
toolResult: {
toolUseId: r.tool_use_id,
status: r.is_error ? "error" : "success",
content: [{ text: r.content }],
},
})),
});
} else {
messages.push({ role: "user", content: [{ text: prompt }] });
}
// Run the full agentic loop
for (let i = 0; i < 10; i++) {
const response = await bedrockClient.send(
new ConverseCommand({
modelId: effectiveModel,
system: system ? [{ text: system }] : undefined,
messages,
toolConfig: tools.length > 0 ? { tools } : undefined,
inferenceConfig: { maxTokens: 4096, 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") {
const textParts = (assistantMsg.content ?? [])
.filter((b): b is { text: string } => "text" in b)
.map((b) => b.text)
.join("");
return { content: [{ type: "text", text: textParts }] };
}
if (response.stopReason === "tool_use") {
// Collect tool use requests and return them to the MCP caller
// so they can execute the tools (they know the implementations)
const toolCalls = (assistantMsg.content ?? [])
.filter((b): b is { toolUse: { toolUseId: string; name: string; input: unknown } } =>
"toolUse" in b && !!b.toolUse
)
.map((b) => ({
tool_use_id: b.toolUse.toolUseId,
name: b.toolUse.name,
input: b.toolUse.input,
}));
// Surface the tool calls to the MCP caller as structured JSON
return {
content: [{
type: "text",
text: JSON.stringify({
status: "tool_use_required",
tool_calls: toolCalls,
message: "Execute these tool calls and pass results to bedrock_llm_query as prior_tool_results",
}),
}],
};
}
// stop_sequence, max_tokens, etc.
const finalText = (assistantMsg.content ?? [])
.filter((b): b is { text: string } => "text" in b)
.map((b) => b.text)
.join("");
return {
content: [{
type: "text",
text: finalText || `Loop ended with stopReason: ${response.stopReason}`,
}],
};
}
return {
content: [{ type: "text", text: "Loop iteration limit reached" }],
};
}
);
This pattern surfaces tool call requests to the MCP caller as JSON rather than executing them inside the server. The MCP client (or a workflow layer above it) can then execute the tools using its own context (file system access, network calls, etc.) and feed the results back via a follow-up bedrock_llm_query call. For server-side tool execution (where the MCP server itself owns the tool implementations), use the full loop pattern from the previous section instead.
TypeScript types reference
All the types you need for Converse tool use come from a single package:
import {
// Client and command
BedrockRuntimeClient,
ConverseCommand,
ConverseCommandInput,
ConverseCommandOutput,
// Tool declaration
Tool, // { toolSpec: ToolSpec }
ToolSpecification, // name, description, inputSchema
ToolInputSchema, // { json: Record<string, unknown> }
ToolConfiguration, // { tools: Tool[], toolChoice?: ToolChoice }
// ToolChoice variants — all are discriminated union members
// Use as: { auto: {} } | { any: {} } | { tool: { name: string } }
// Message and content
Message, // { role: "user" | "assistant", content: ContentBlock[] }
ContentBlock, // discriminated union of TextBlock | ImageBlock | DocumentBlock | ToolUseBlock | ToolResultBlock | ...
// Tool call and result
ToolUseBlock, // { toolUseId: string, name: string, input: unknown }
ToolResultBlock, // { toolUseId: string, status: "success" | "error", content: ToolResultContentBlock[] }
// Stop reason
StopReason, // "end_turn" | "tool_use" | "max_tokens" | "stop_sequence" | "guardrail_intervened" | "content_filtered"
// Inference config
InferenceConfiguration,
// Error types
ValidationException,
ThrottlingException,
ServiceUnavailableException,
ModelNotReadyException,
ModelErrorException,
} from "@aws-sdk/client-bedrock-runtime";
One frequently confused distinction: ToolResultBlock is the type for the data you assemble in your loop code. ContentBlock is the union type for items in message.content — a ContentBlock that contains a tool result is shaped as { toolResult: ToolResultBlock }, not a bare ToolResultBlock. When building the user turn that returns tool results, you create ContentBlock[] where each element is { toolResult: { toolUseId, status, content } }.
IAM permissions
Converse API calls require either bedrock:InvokeModel (the classic model invocation action) or the newer bedrock:Converse action. Both work. The recommended minimum policy for an MCP server that uses Converse with tool use:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "BedrockConverseAccess",
"Effect": "Allow",
"Action": [
"bedrock:InvokeModel",
"bedrock:Converse"
],
"Resource": [
"arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-3-haiku-20240307-v1:0",
"arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-3-5-sonnet-20241022-v2:0",
"arn:aws:bedrock:us-east-1::foundation-model/amazon.nova-lite-v1:0",
"arn:aws:bedrock:us-east-1::foundation-model/amazon.nova-pro-v1:0"
]
}
]
}
Use arn:aws:bedrock:REGION::foundation-model/* during development to avoid updating the policy every time you try a new model. Scope it to specific model ARNs for production. The resource ARN format for Bedrock foundation models uses a double colon (::) between the account segment and foundation-model — the account ID is omitted because foundation models are AWS-managed resources, not account-specific ones. Using a single colon here produces an IAM policy that looks valid but never matches and results in an AccessDeniedException.
Attaching the policy
aws iam create-policy \
--policy-name AliveMCPConverseToolUsePolicy \
--policy-document file://converse-tool-use-policy.json
# For ECS Fargate task role
aws iam attach-role-policy \
--role-name alivemcp-ecs-task-role \
--policy-arn arn:aws:iam::123456789012:policy/AliveMCPConverseToolUsePolicy
# For Lambda execution role
aws iam attach-role-policy \
--role-name alivemcp-lambda-role \
--policy-arn arn:aws:iam::123456789012:policy/AliveMCPConverseToolUsePolicy
Error handling and common ValidationExceptions
Most ValidationException errors from Converse tool use have deterministic causes. Here are the most common ones and how to handle them:
import {
BedrockRuntimeClient,
ConverseCommand,
ValidationException,
ThrottlingException,
ServiceUnavailableException,
ModelNotReadyException,
} from "@aws-sdk/client-bedrock-runtime";
async function converseWithRetry(
input: ConverseCommandInput,
maxRetries = 3
): Promise<ConverseCommandOutput> {
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await client.send(new ConverseCommand(input));
} catch (err) {
if (err instanceof ValidationException) {
// Deterministic — do not retry
// Common causes:
// - toolUseId mismatch in ToolResultBlock
// - tool name does not match [a-zA-Z0-9_-]{1,64}
// - toolChoice: ANY or TOOL used with Titan/Llama
// - empty ToolResultBlock content array
// - inputSchema root is not type: 'object'
// - ToolResultBlock content missing for one of the ToolUseBlocks
console.error("Converse ValidationException:", err.message);
throw err; // Propagate — retrying will not help
}
if (
(err instanceof ThrottlingException ||
err instanceof ServiceUnavailableException) &&
attempt < maxRetries
) {
const backoffMs = Math.min(1000 * Math.pow(2, attempt), 16000);
await new Promise((r) => setTimeout(r, backoffMs));
continue;
}
if (err instanceof ModelNotReadyException) {
// Model is warming up — brief retry
if (attempt < maxRetries) {
await new Promise((r) => setTimeout(r, 2000));
continue;
}
}
throw err;
}
}
throw new Error("Max retries exceeded");
}
| Cause | Exception | Fix |
|---|---|---|
| Tool name contains space or dot | ValidationException |
Rename to match [a-zA-Z0-9_-]{1,64} |
toolUseId mismatch in result |
ValidationException |
Echo toolUseId from the ToolUseBlock exactly |
Not all ToolUseBlocks answered in one turn |
ValidationException |
Collect all blocks; return all results in one user turn |
Empty ToolResultBlock content |
ValidationException |
Always include at least one TextBlock |
toolChoice: ANY with Llama/Titan |
ValidationException |
Only use ANY/TOOL with Claude models |
JSON Schema root not type: 'object' |
ValidationException |
Wrap primitive schemas in an object property |
| Bedrock TPS quota exceeded | ThrottlingException |
Exponential backoff; request quota increase |
Monitor your Bedrock Converse MCP tool handlers with AliveMCP
AliveMCP monitors MCP server endpoints for uptime, latency spikes, and error rates. When a Bedrock Converse tool-use loop starts throwing ValidationExceptions or the multi-turn latency climbs above your SLA, AliveMCP alerts you before the issue reaches end users.
Start free monitoring