Guide · Amazon Bedrock · MCP Tool Handler Pattern

Bedrock Cross-Region Inference in MCP Tool Handlers — ThrottlingException Retry and Streaming

Using a Bedrock inference profile in an MCP tool handler reduces throttling failures from capacity constraints but does not eliminate them — cross-region capacity is shared across all accounts and can still be exhausted during peak load. A production MCP server needs two additional layers beyond the profile ID swap: ThrottlingException retry with exponential backoff and jitter (Bedrock signals a retry window in the Retry-After header; ignoring it and retrying immediately makes throttling worse) and startup validation (verifying the profile is accessible before accepting tool calls prevents a class of runtime failures that only manifest under load). This page shows the complete TypeScript implementation for both non-streaming and streaming MCP tool handlers backed by Bedrock cross-region inference, the IAM policy template, and how to monitor inference profile usage in CloudWatch. For the overview of inference profiles and the model access per-region prerequisite, see Cross-Region Inference Overview. For creating application inference profiles with cost-allocation tags, see Application Inference Profiles.

TL;DR

Use an inference profile ID or application profile ARN as modelId in ConverseCommand. Wrap the call in a retry loop that catches ThrottlingException, reads the Retry-After header from the error metadata, and sleeps that many seconds plus random jitter before retrying. Validate the profile is ACTIVE on MCP server startup. Store the profile ARN in an environment variable — do not hardcode it or look it up per request.

The complete Bedrock inference client module

This module handles everything the MCP server needs: retry logic, profile validation, non-streaming and streaming invocations:

import {
  BedrockClient,
  GetInferenceProfileCommand,
} from "@aws-sdk/client-bedrock";
import {
  BedrockRuntimeClient,
  ConverseCommand,
  ConverseStreamCommand,
  type Message,
  type ContentBlock,
  type SystemContentBlock,
} from "@aws-sdk/client-bedrock-runtime";

// ----------------------------------------------------------------
// Configuration — set at startup from environment variables
// ----------------------------------------------------------------
const 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";
// Can be a system profile ID ("us.anthropic.claude-...") or
// an application profile ARN ("arn:aws:bedrock:...:application-inference-profile/...")

const bedrockClient = new BedrockClient({ region: REGION });
const runtimeClient = new BedrockRuntimeClient({ region: REGION });

// ----------------------------------------------------------------
// Startup validation
// ----------------------------------------------------------------
export async function validateInferenceProfile(): Promise<void> {
  const profileId = MODEL_ID;
  try {
    const response = await bedrockClient.send(new GetInferenceProfileCommand({
      inferenceProfileIdentifier: profileId,
    }));

    if (response.status !== "ACTIVE") {
      throw new Error(
        `Bedrock inference profile "${profileId}" status is "${response.status}" — expected "ACTIVE". ` +
        `The profile may be in a transitional state. Wait and retry.`
      );
    }

    const targetRegions = (response.models ?? [])
      .map(m => m.modelArn?.split(":")[3])
      .filter(Boolean);

    console.log(
      `[bedrock] Profile OK: "${profileId}" ACTIVE. ` +
      `Routes to: ${targetRegions.join(", ")}`
    );
  } catch (err: any) {
    if (err.name === "ResourceNotFoundException") {
      throw new Error(
        `Bedrock inference profile "${profileId}" not found in region "${REGION}". ` +
        `Check the MODEL_ID environment variable. ` +
        `System profiles use format "us.anthropic.claude-...", ` +
        `application profiles use the full ARN.`
      );
    }
    if (err.name === "AccessDeniedException") {
      throw new Error(
        `AccessDeniedException on GetInferenceProfileCommand for "${profileId}". ` +
        `Add bedrock:GetInferenceProfile to the task/function IAM role.`
      );
    }
    throw err;
  }
}

// ----------------------------------------------------------------
// Retry helper
// ----------------------------------------------------------------
interface RetryOptions {
  maxAttempts?: number;
  baseDelayMs?: number;
  maxDelayMs?: number;
}

async function withBedrockRetry<T>(
  fn: () => Promise<T>,
  opts: RetryOptions = {}
): Promise<T> {
  const { maxAttempts = 4, baseDelayMs = 1000, maxDelayMs = 30_000 } = opts;

  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await fn();
    } catch (err: any) {
      const isThrottling =
        err.name === "ThrottlingException" ||
        err.name === "ServiceUnavailableException" ||
        (err.$metadata?.httpStatusCode === 429) ||
        (err.$metadata?.httpStatusCode === 503);

      if (!isThrottling || attempt === maxAttempts) throw err;

      // Respect Retry-After header if present
      const retryAfterHeader = err.$response?.headers?.["retry-after"];
      let delayMs: number;

      if (retryAfterHeader) {
        // Retry-After is in seconds
        delayMs = parseInt(retryAfterHeader, 10) * 1000;
      } else {
        // Exponential backoff: 1s, 2s, 4s, 8s...
        delayMs = Math.min(baseDelayMs * Math.pow(2, attempt - 1), maxDelayMs);
      }

      // Add jitter: ±20% of the delay to avoid thundering herd
      const jitter = delayMs * 0.2 * (Math.random() * 2 - 1);
      delayMs = Math.max(0, delayMs + jitter);

      console.warn(
        `[bedrock] ${err.name} on attempt ${attempt}/${maxAttempts}. ` +
        `Retrying in ${Math.round(delayMs)}ms.`
      );
      await new Promise(resolve => setTimeout(resolve, delayMs));
    }
  }

  throw new Error("[bedrock] unreachable: exceeded maxAttempts without returning or throwing");
}

// ----------------------------------------------------------------
// Non-streaming invocation (for tools that return a final answer)
// ----------------------------------------------------------------
export async function invokeModel(params: {
  messages: Message[];
  system?: SystemContentBlock[];
  maxTokens?: number;
  temperature?: number;
  toolConfig?: Parameters<typeof ConverseCommand>[0]["toolConfig"];
}): Promise<{
  text: string;
  stopReason: string;
  inputTokens: number;
  outputTokens: number;
}> {
  return withBedrockRetry(async () => {
    const response = await runtimeClient.send(new ConverseCommand({
      modelId: MODEL_ID,
      system: params.system,
      messages: params.messages,
      toolConfig: params.toolConfig,
      inferenceConfig: {
        maxTokens: params.maxTokens ?? 4096,
        temperature: params.temperature ?? 0.0,
      },
    }));

    const content = response.output?.message?.content ?? [];
    const textBlocks = content.filter((b): b is { text: string } =>
      "text" in b && typeof b.text === "string"
    );

    return {
      text: textBlocks.map(b => b.text).join(""),
      stopReason: response.stopReason ?? "end_turn",
      inputTokens: response.usage?.inputTokens ?? 0,
      outputTokens: response.usage?.outputTokens ?? 0,
    };
  });
}

// ----------------------------------------------------------------
// Streaming invocation (for tools that return progressive output)
// ----------------------------------------------------------------
export async function* streamModel(params: {
  messages: Message[];
  system?: SystemContentBlock[];
  maxTokens?: number;
}): AsyncGenerator<string> {
  // ConverseStream cannot be retried mid-stream, so the retry wraps the
  // initial connection. Once streaming starts, errors propagate to the caller.
  const response = await withBedrockRetry(() =>
    runtimeClient.send(new ConverseStreamCommand({
      modelId: MODEL_ID,
      system: params.system,
      messages: params.messages,
      inferenceConfig: {
        maxTokens: params.maxTokens ?? 4096,
      },
    }))
  );

  for await (const event of response.stream ?? []) {
    if (event.contentBlockDelta?.delta?.text) {
      yield event.contentBlockDelta.delta.text;
    }
    // Log stop reason when stream ends
    if (event.messageStop?.stopReason) {
      console.log(`[bedrock] stream complete, stopReason=${event.messageStop.stopReason}`);
    }
  }
}

Wiring the module into an MCP server

Call validateInferenceProfile() before the MCP server starts accepting connections, then use invokeModel or streamModel in tool handlers:

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { validateInferenceProfile, invokeModel, streamModel } from "./bedrock-client.js";
import { z } from "zod";

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

// Tool: summarize text using Claude via cross-region inference
server.tool(
  "summarize",
  "Summarize a document using Claude",
  { text: z.string().describe("The text to summarize"), maxWords: z.number().optional() },
  async ({ text, maxWords = 200 }) => {
    const result = await invokeModel({
      messages: [{ role: "user", content: [{ text }] }],
      system: [{
        text: `You are a summarization assistant. Summarize the input in at most ${maxWords} words.`
      }],
      maxTokens: 512,
      temperature: 0.0,
    });

    return {
      content: [{ type: "text", text: result.text }],
      isError: false,
    };
  }
);

// Streaming tool: generate code with real-time output
server.tool(
  "generate_code",
  "Generate TypeScript code for a given specification",
  { spec: z.string().describe("Code specification"), language: z.string().default("TypeScript") },
  async ({ spec, language }) => {
    const chunks: string[] = [];
    for await (const chunk of streamModel({
      messages: [{ role: "user", content: [{ text: spec }] }],
      system: [{ text: `Generate ${language} code. Return only the code, no explanation.` }],
      maxTokens: 2048,
    })) {
      chunks.push(chunk);
    }

    return {
      content: [{ type: "text", text: chunks.join("") }],
      isError: false,
    };
  }
);

// Startup: validate profile, then start accepting connections
async function main() {
  await validateInferenceProfile();
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.log("[mcp] Server started");
}

main().catch(err => {
  console.error("[mcp] Fatal startup error:", err.message);
  process.exit(1);
});

ThrottlingException anatomy and what the retry-after header means

When Bedrock returns ThrottlingException (HTTP 429), the response includes a Retry-After header indicating how many seconds the caller should wait before retrying. Ignoring this header and retrying immediately has two negative effects:

The retry helper above reads err.$response?.headers?.["retry-after"]. This requires that the AWS SDK v3 error object retains the HTTP response metadata. Errors from @aws-sdk/client-bedrock-runtime always include $metadata (HTTP status code) but the response headers are only available if the SDK does not strip them before throwing. In practice, ThrottlingException in AWS SDK v3 preserves the headers.

Add a failure counter to detect looping throttle:

// In withBedrockRetry, after maxAttempts is exceeded:
if (consecutiveThrottleAttempts >= maxAttempts) {
  throw new Error(
    `Bedrock ThrottlingException persists after ${maxAttempts} retries. ` +
    `Possible causes: (1) model access not enabled in all regions of the ` +
    `cross-region profile, (2) account-level quota exhausted, ` +
    `(3) region-wide Bedrock service event. ` +
    `Profile: ${MODEL_ID}. Last error: ${err.message}`
  );
}

Monitoring inference profile usage in CloudWatch

Bedrock emits CloudWatch metrics for every invocation. For cross-region inference profiles, the relevant metrics are:

MetricNamespaceWhat it shows
InvocationLatencyAWS/BedrockTotal end-to-end latency per invocation; use P99 to detect cross-region routing overhead
InputTokenCountAWS/BedrockInput tokens consumed; correlates with cost
OutputTokenCountAWS/BedrockOutput tokens generated; primary cost driver for Claude
InvocationClientErrorsAWS/Bedrock4xx errors; spikes indicate ThrottlingException or malformed requests
InvocationServerErrorsAWS/Bedrock5xx errors; indicate Bedrock service issues in target regions

The metrics are dimensioned by ModelId. For system inference profiles, the ModelId dimension value is the profile ID string (e.g., us.anthropic.claude-3-5-sonnet-20241022-v2:0). For application inference profiles, the dimension is the application profile ARN. Create a CloudWatch alarm on InvocationClientErrors with a threshold of more than 5 errors per minute to alert on sustained throttling.

// CDK: alarm on sustained ThrottlingException
import * as cloudwatch from "aws-cdk-lib/aws-cloudwatch";

const throttlingAlarm = new cloudwatch.Alarm(this, "BedrockThrottlingAlarm", {
  metric: new cloudwatch.Metric({
    namespace: "AWS/Bedrock",
    metricName: "InvocationClientErrors",
    dimensionsMap: {
      ModelId: process.env.BEDROCK_MODEL_ID!,
    },
    statistic: "Sum",
    period: Duration.minutes(1),
  }),
  threshold: 5,
  evaluationPeriods: 3,
  comparisonOperator: cloudwatch.ComparisonOperator.GREATER_THAN_THRESHOLD,
  treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING,
  alarmDescription: "Bedrock cross-region inference sustained throttling",
});

IAM policy for the full MCP server pattern

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "BedrockCrossRegionInvokeProfile",
      "Effect": "Allow",
      "Action": [
        "bedrock:InvokeModel",
        "bedrock:InvokeModelWithResponseStream"
      ],
      "Resource": [
        "arn:aws:bedrock:us-east-1::foundation-model/us.anthropic.claude-3-5-sonnet-20241022-v2:0",
        "arn:aws:bedrock:us-east-1:ACCOUNT_ID:application-inference-profile/mcp-server-claude-prod"
      ]
    },
    {
      "Sid": "BedrockProfileValidation",
      "Effect": "Allow",
      "Action": [
        "bedrock:GetInferenceProfile",
        "bedrock:ListInferenceProfiles"
      ],
      "Resource": "*"
    }
  ]
}

Include both the system profile ARN and the application profile ARN if your MCP server uses one of each — for example, us.anthropic.claude-3-5-sonnet-20241022-v2:0 for primary invocations and an application profile for cost-tagged invocations of a specific tool.

When cross-region inference is not enough: escalation path

If your MCP server still encounters ThrottlingException after switching to a cross-region inference profile and implementing proper retry logic, the remaining options are:

  1. Provisioned throughput. Reserve a fixed number of Model Units for your workload. Provisioned throughput guarantees capacity within those units regardless of account-wide throttling. The minimum commitment is 1 month. See Bedrock Model Invocation for provisioned throughput setup.
  2. Service Quotas increase. File a quota increase request for Amazon Bedrock — Requests per minute for Anthropic Claude 3.5 Sonnet v2 on-demand throughput. AWS typically approves increases for accounts with demonstrated production usage patterns.
  3. Request batching. If your MCP tools are called in bulk (data enrichment pipelines, batch processing), use Bedrock Batch Inference to process large datasets asynchronously at higher throughput limits than on-demand.

AliveMCP monitors the external uptime and response latency of your MCP server endpoints. When ThrottlingException-driven failures inflate your tool call latency or cause tool timeout errors, AliveMCP detects the degradation from outside your AWS infrastructure and fires an alert — complementing the internal CloudWatch metrics on Bedrock invocations with an external view that reflects the experience of the AI agents calling your tools.

Related pages in this arc

For the fundamentals of ConverseCommand without cross-region, see Bedrock Converse API for MCP Servers. For Bedrock Guardrails layered on top of inference profiles, see Bedrock Guardrails.