Amazon Bedrock · PutModelInvocationLoggingConfiguration, AWS/Bedrock CloudWatch, ThrottlingException, response.usage · 2026-11-27 · Bedrock Runtime Monitoring arc
Amazon Bedrock Observability for MCP Servers: Invocation Logging, CloudWatch Metrics, Throttle Handling, and Cost Tracking
Four Bedrock Runtime Monitoring arc pages synthesised into a complete production observability playbook for MCP server developers — covering invocation logging (PutModelInvocationLoggingConfigurationCommand from the control-plane package, delivery.logs.amazonaws.com trust policy not bedrock.amazonaws.com, largeDataDeliveryS3Config silent-drop gotcha, requestId correlation, CloudWatch Insights queries), CloudWatch metrics (AWS/Bedrock namespace built-in metrics, Sum not Average for token counts, GetMetricDataCommand for multi-metric p99 queries, PutMetricAlarmCommand for error rate and latency thresholds, metric math for derived error rate), throttle handling (ThrottlingException HTTP 429 with no Retry-After header, default TPS limits by model, SDK maxAttempts:10, full jitter exponential backoff, cross-region inference escape valve, Service Quotas increase, interactive tool retry budget), and usage metadata (response.usage.inputTokens/outputTokens synchronously in Converse response, streaming usage arrives in final metadata event, tool use rounds counted separately, per-model cost rate table, per-tool attribution, DailyBudgetGuard pattern). Ten consolidated production gotchas at the end.
Why observability is non-negotiable for Bedrock-backed MCP servers
An MCP server that calls Amazon Bedrock sits at the intersection of two failure domains: the AI model layer (which can throttle, time out, return unexpected refusals, or cost ten times more than expected when a prompt grows out of control) and the MCP protocol layer (where an agent calling your tool expects a response within some implicit timeout, and an error propagates directly to the user's AI assistant session).
Without observability, you are flying blind on three questions that matter most in production:
- What exactly was sent to the model? When a tool returns garbage, you need the full prompt that reached Bedrock — not what your code intended to send, but what was actually serialised and transmitted. Invocation logging answers this.
- Is the model behaving normally right now? Latency spikes, error rate jumps, and token consumption anomalies need to surface before users notice. CloudWatch metrics answer this.
- How much is this costing, and which tool is responsible? An MCP server that exposes multiple tools can have wildly different token consumption profiles per tool. Per-call usage metadata answers this.
Bedrock gives you all three observability surfaces out of the box. This guide walks through each one in production-ready detail, then consolidates the ten gotchas that catch most teams on first deployment.
Part 1: Invocation Logging — the durable audit trail
Invocation logging creates a persistent, structured JSON record of every Bedrock call your server makes. It captures the full request body, the full response body, token counts, latency, the calling IAM ARN, and a request ID that you can correlate against your application logs. It is configured once at the account level and applies to all callers, all models, and all tools in a region.
The package split that trips everyone up
Bedrock's SDK is split into two packages: @aws-sdk/client-bedrock-runtime for invoking models (ConverseCommand, InvokeModelCommand), and @aws-sdk/client-bedrock for the control plane (logging configuration, model management, customization jobs). Invocation logging lives exclusively in the control-plane package. If you search for PutModelInvocationLoggingConfigurationCommand in @aws-sdk/client-bedrock-runtime, you will not find it:
npm install @aws-sdk/client-bedrock # control-plane: logging config, model listing
npm install @aws-sdk/client-bedrock-runtime # data-plane: ConverseCommand, InvokeModelCommand
import {
BedrockClient,
PutModelInvocationLoggingConfigurationCommand,
GetModelInvocationLoggingConfigurationCommand,
} from "@aws-sdk/client-bedrock";
// Note: BedrockClient from client-bedrock, not BedrockRuntimeClient from client-bedrock-runtime
const bedrockControl = new BedrockClient({
region: process.env.AWS_REGION ?? "us-east-1",
});
Enabling logging: CloudWatch delivery configuration
The minimal configuration routes text model I/O to a CloudWatch log group. You need three things before making the call: the log group must exist (or Bedrock must have permission to create it), a delivery IAM role must be in place with the trust policy shown below, and the caller must have bedrock:PutModelInvocationLoggingConfiguration in their policy:
async function enableInvocationLogging(params: {
logGroupName: string;
deliveryRoleArn: string;
largePayloadBucket: string;
}): Promise<void> {
await bedrockControl.send(
new PutModelInvocationLoggingConfigurationCommand({
loggingConfig: {
textDataDeliveryEnabled: true, // text LLM calls
imageDataDeliveryEnabled: false, // Titan Image, Stability — separate toggle
embeddingDataDeliveryEnabled: false, // Titan Embeddings — separate toggle
cloudWatchConfig: {
logGroupName: params.logGroupName,
roleArn: params.deliveryRoleArn,
// REQUIRED if any payload exceeds 100 KB — omitting causes silent drops
largeDataDeliveryS3Config: {
bucketName: params.largePayloadBucket,
keyPrefix: "large-payloads/",
},
},
},
})
);
console.log("Bedrock invocation logging enabled — applies to all callers in this region.");
}
await enableInvocationLogging({
logGroupName: "/aws/bedrock/invocations",
deliveryRoleArn: "arn:aws:iam::123456789012:role/BedrockLoggingDeliveryRole",
largePayloadBucket: "my-bedrock-logs-bucket",
});
The IAM trust policy gotcha: delivery.logs.amazonaws.com, not bedrock.amazonaws.com
The role you supply in cloudWatchConfig.roleArn is assumed by the CloudWatch Logs delivery service, not by Bedrock. This is why the trust principal must be delivery.logs.amazonaws.com. Using bedrock.amazonaws.com will cause the role assumption to fail silently — the configuration call succeeds, but no logs are written:
// Trust policy for the delivery role — MUST use delivery.logs.amazonaws.com
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "delivery.logs.amazonaws.com" },
"Action": "sts:AssumeRole",
"Condition": {
"StringEquals": { "aws:SourceAccount": "123456789012" }
}
}
]
}
// Permission policy on the same role
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:DescribeLogGroups",
"logs:DescribeLogStreams",
"logs:PutLogEvents"
],
"Resource": [
"arn:aws:logs:us-east-1:123456789012:log-group:/aws/bedrock/invocations:*"
]
},
{
// Required if using largeDataDeliveryS3Config
"Effect": "Allow",
"Action": ["s3:PutObject", "s3:GetBucketLocation"],
"Resource": [
"arn:aws:s3:::my-bedrock-logs-bucket",
"arn:aws:s3:::my-bedrock-logs-bucket/large-payloads/*"
]
}
]
}
Beyond the IAM role permissions, you also need an S3 bucket policy that grants delivery.logs.amazonaws.com write access from your account. Without the bucket-side policy, large invocations will silently fail to log even when the role permissions are correctly configured. This is a common second-step omission.
Log entry format and key fields
Each invocation writes one JSON record to CloudWatch. The body fields (inputBodyJson and outputBodyJson) are model-specific, but the envelope is consistent across all models:
// Representative log entry for a ConverseCommand call
{
"schemaType": "ModelInvocationLog",
"schemaVersion": "1.0",
"timestamp": "2026-11-27T10:23:45.123Z",
"accountId": "123456789012",
"identity": {
"arn": "arn:aws:iam::123456789012:role/my-mcp-server-role",
"type": "AssumedRole"
},
"region": "us-east-1",
"requestId": "req-abc123-def456", // matches response.$metadata.requestId
"operation": "Converse",
"modelId": "anthropic.claude-3-haiku-20240307-v1:0",
"errorCode": null, // non-null on failure, e.g. "ThrottlingException"
"input": {
"inputTokenCount": 150,
"inputBodyJson": "{ ... full request JSON ... }"
},
"output": {
"outputTokenCount": 78,
"outputBodyJson": "{ ... full response JSON ... }"
}
}
The four fields that matter most for MCP server debugging:
requestId— matchesresponse.$metadata.requestIdfrom the SDK. This is how you correlate a failed tool call in your application logs with the specific Bedrock log entry that shows the full prompt.errorCode— non-null when the call failed. When set,output.outputBodyJsonmay be absent. Query for non-nullerrorCodein CloudWatch Insights to find all failed invocations.identity.arn— the IAM ARN that made the call. For MCP servers where different tools assume different roles, this lets you attribute cost and errors per tool without code changes.input.inputTokenCount— Bedrock's authoritative billing count, measured before the response is generated. Use this for cost attribution, not client-side estimates.
Correlating log entries with MCP tool call errors
Always capture and log the requestId from every Bedrock call, including failed ones. The $metadata.requestId is populated on both successful responses and caught exceptions:
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import { BedrockRuntimeClient, ConverseCommand } from "@aws-sdk/client-bedrock-runtime";
const runtime = new BedrockRuntimeClient({ region: "us-east-1" });
const server = new McpServer({ name: "alivemcp-tools", version: "1.0.0" });
server.tool(
"check_mcp_server_health",
{ endpoint: z.string().url() },
async ({ endpoint }) => {
let requestId: string | undefined;
try {
const response = await runtime.send(new ConverseCommand({
modelId: "anthropic.claude-3-haiku-20240307-v1:0",
messages: [{
role: "user",
content: [{ text: `Analyze the health check response from: ${endpoint}` }],
}],
inferenceConfig: { maxTokens: 256 },
}));
requestId = response.$metadata.requestId;
return {
content: [{
type: "text",
text: `${response.output?.message?.content?.[0]?.text ?? ""}\n\n[requestId: ${requestId}]`,
}],
};
} catch (err: any) {
// $metadata.requestId is available even on error responses
requestId = err.$metadata?.requestId;
console.error(`Bedrock call failed — tool: check_mcp_server_health, requestId: ${requestId}`, err.message);
throw err;
}
}
);
CloudWatch Insights queries for MCP debugging
Once invocation logs are flowing, these Insights queries cover the most common debugging scenarios:
-- All failed invocations in the last 24 hours
fields @timestamp, modelId, errorCode, identity.arn
| filter errorCode != null
| sort @timestamp desc
| limit 50
-- Token usage by model over the last 7 days (sum, not average)
stats
sum(input.inputTokenCount) as totalInput,
sum(output.outputTokenCount) as totalOutput,
count() as callCount
by modelId
| sort callCount desc
-- Calls with highest input token counts (long prompts, potential runaway)
fields @timestamp, modelId, input.inputTokenCount, identity.arn
| filter operation = "Converse"
| sort input.inputTokenCount desc
| limit 20
Part 2: CloudWatch Metrics — real-time health monitoring
While invocation logging gives you a queryable audit trail of every call, CloudWatch metrics give you real-time aggregate signals across all calls. Bedrock publishes metrics automatically to the AWS/Bedrock namespace — no configuration, no opt-in, no extra instrumentation needed. The only IAM requirement is cloudwatch:GetMetricStatistics or cloudwatch:GetMetricData on the monitoring caller.
The metric reference table
// AWS/Bedrock namespace metrics — primary dimension is ModelId
//
// Metric | Unit | Useful statistic | Notes
// --------------------- | -------------- | ---------------- | ----------------------------
// Invocations | Count | Sum | Successful calls
// InvocationLatency | Milliseconds | Average, p99 | End-to-end incl. streaming
// InvocationClientErrors| Count | Sum | 4xx: throttling, auth, validation
// InvocationServerErrors| Count | Sum | 5xx: timeout, service unavailable
// InputTokenCount | Count | Sum | Tokens in — use Sum, not Average
// OutputTokenCount | Count | Sum | Tokens out — use Sum, not Average
// ModelId dimension values (examples):
// "anthropic.claude-3-haiku-20240307-v1:0"
// "anthropic.claude-3-5-sonnet-20241022-v2:0"
// "amazon.nova-micro-v1:0"
// "amazon.nova-pro-v1:0"
Three things to know before you start querying:
- Metrics resolve at 1-minute granularity. A latency spike narrower than 60 seconds may not be visible. For fine-grained call-level timing, use invocation logs.
- InvocationLatency measures time to last byte, not time to first token. For streaming calls, this includes the time to generate the full response. If your tool sends a prompt and processes chunks as they arrive, the CloudWatch latency metric will not reflect your user-visible time-to-first-token.
- ThrottlingExceptions count as InvocationClientErrors. A sustained throttle will fire your error-rate alarm even if client-side retries eventually succeed. This is by design — you want to know that throttling is happening, even when it's invisible to users.
Querying metrics programmatically
import {
CloudWatchClient,
GetMetricStatisticsCommand,
GetMetricDataCommand,
StandardUnit,
Statistic,
} from "@aws-sdk/client-cloudwatch";
const cw = new CloudWatchClient({ region: "us-east-1" });
// Single-metric query with GetMetricStatisticsCommand
async function getBedrockLatency(modelId: string, windowMinutes = 60) {
const now = new Date();
const start = new Date(now.getTime() - windowMinutes * 60 * 1000);
const { Datapoints } = await cw.send(
new GetMetricStatisticsCommand({
Namespace: "AWS/Bedrock",
MetricName: "InvocationLatency",
Dimensions: [{ Name: "ModelId", Value: modelId }],
StartTime: start,
EndTime: now,
Period: 300, // 5-minute resolution
Statistics: [Statistic.Average, Statistic.Maximum, Statistic.SampleCount],
Unit: StandardUnit.Milliseconds,
})
);
if (!Datapoints || Datapoints.length === 0) return null;
Datapoints.sort((a, b) => (a.Timestamp?.getTime() ?? 0) - (b.Timestamp?.getTime() ?? 0));
const totalWeighted = Datapoints.reduce(
(s, d) => s + (d.Average ?? 0) * (d.SampleCount ?? 0), 0
);
const totalCount = Datapoints.reduce((s, d) => s + (d.SampleCount ?? 0), 0);
return {
averageMs: totalCount > 0 ? totalWeighted / totalCount : 0,
maxMs: Math.max(...Datapoints.map(d => d.Maximum ?? 0)),
sampleCount: totalCount,
};
}
For querying multiple metrics at once (which is the typical production case — you want error rate, latency, and token counts in one pass), use GetMetricDataCommand. It supports fetching multiple metrics in a single API call, can compute percentile statistics like p99, and is more cost-efficient at scale than multiple GetMetricStatistics calls:
The Sum vs Average trap for token counts
The InputTokenCount and OutputTokenCount metrics are per-invocation sums already aggregated by CloudWatch within each period. When you query them, use the Sum statistic — not Average. Using Average would divide the sum of tokens in the period by the number of data points, giving you a meaningless fraction rather than the total token consumption:
// WRONG — Average divides the already-summed period value by datapoint count
await fetchMetricStatistic("InputTokenCount", Statistic.Average);
// CORRECT — Sum gives you total tokens consumed across the period
async function getTokenUsage(modelId: string, windowMinutes = 60) {
const now = new Date();
const start = new Date(now.getTime() - windowMinutes * 60 * 1000);
const period = Math.max(60, windowMinutes * 60);
const fetchSum = async (metricName: string) => {
const { Datapoints } = await cw.send(
new GetMetricStatisticsCommand({
Namespace: "AWS/Bedrock",
MetricName: metricName,
Dimensions: [{ Name: "ModelId", Value: modelId }],
StartTime: start,
EndTime: now,
Period: period,
Statistics: [Statistic.Sum], // Always Sum for token counts
Unit: StandardUnit.Count,
})
);
return Datapoints?.reduce((s, d) => s + (d.Sum ?? 0), 0) ?? 0;
};
const [inputTokens, outputTokens] = await Promise.all([
fetchSum("InputTokenCount"),
fetchSum("OutputTokenCount"),
]);
return { inputTokens, outputTokens };
}
Setting up production alarms
Three alarms cover the most common Bedrock failure modes for MCP servers. Set them up at deploy time, not after the first incident:
import {
PutMetricAlarmCommand,
ComparisonOperator,
TreatMissingData,
} from "@aws-sdk/client-cloudwatch";
// Alarm 1: sustained client error rate (throttling + validation + auth)
await cw.send(new PutMetricAlarmCommand({
AlarmName: "Bedrock-Haiku-ClientErrorRate-High",
Namespace: "AWS/Bedrock",
MetricName: "InvocationClientErrors",
Dimensions: [{ Name: "ModelId", Value: "anthropic.claude-3-haiku-20240307-v1:0" }],
Statistic: Statistic.Sum,
Period: 300,
EvaluationPeriods: 1,
Threshold: 10, // more than 10 errors in any 5-minute window
ComparisonOperator: ComparisonOperator.GreaterThanOrEqualToThreshold,
TreatMissingData: TreatMissingData.notBreaching,
AlarmActions: ["arn:aws:sns:us-east-1:123456789012:mcp-server-alerts"],
}));
// Alarm 2: sustained high latency (average over two 10-minute windows)
await cw.send(new PutMetricAlarmCommand({
AlarmName: "Bedrock-Haiku-Latency-High",
Namespace: "AWS/Bedrock",
MetricName: "InvocationLatency",
Dimensions: [{ Name: "ModelId", Value: "anthropic.claude-3-haiku-20240307-v1:0" }],
Statistic: Statistic.Average,
Unit: StandardUnit.Milliseconds,
Period: 600,
EvaluationPeriods: 2, // must breach two consecutive 10-minute periods
Threshold: 8000, // 8 seconds average is anomalous for Haiku
ComparisonOperator: ComparisonOperator.GreaterThanOrEqualToThreshold,
TreatMissingData: TreatMissingData.notBreaching,
AlarmActions: ["arn:aws:sns:us-east-1:123456789012:mcp-server-alerts"],
}));
// Alarm 3: any server-side error (5xx — always page immediately)
await cw.send(new PutMetricAlarmCommand({
AlarmName: "Bedrock-ServerErrors-Any",
Namespace: "AWS/Bedrock",
MetricName: "InvocationServerErrors",
// No ModelId dimension — alarm on any model in the region
Statistic: Statistic.Sum,
Period: 60,
EvaluationPeriods: 1,
Threshold: 1,
ComparisonOperator: ComparisonOperator.GreaterThanOrEqualToThreshold,
TreatMissingData: TreatMissingData.notBreaching,
AlarmActions: ["arn:aws:sns:us-east-1:123456789012:mcp-server-alerts"],
}));
Metric math for derived error rate
CloudWatch metric math lets you express error rate as a percentage of total calls directly in the API, without computing it client-side. This is useful for dashboards and for creating alarms on the derived rate rather than raw counts:
const response = await cw.send(new GetMetricDataCommand({
StartTime: oneHourAgo,
EndTime: now,
MetricDataQueries: [
{
Id: "invocations",
MetricStat: {
Metric: {
Namespace: "AWS/Bedrock",
MetricName: "Invocations",
Dimensions: [{ Name: "ModelId", Value: modelId }],
},
Period: 300,
Stat: "Sum",
},
ReturnData: false, // intermediate variable only
},
{
Id: "clientErrors",
MetricStat: {
Metric: {
Namespace: "AWS/Bedrock",
MetricName: "InvocationClientErrors",
Dimensions: [{ Name: "ModelId", Value: modelId }],
},
Period: 300,
Stat: "Sum",
},
ReturnData: false,
},
{
Id: "errorRate",
// The +0.001 prevents division-by-zero when no calls occurred in the period
Expression: "100 * clientErrors / (invocations + clientErrors + 0.001)",
Label: "Client Error Rate (%)",
ReturnData: true,
},
{
Id: "latencyP99",
MetricStat: {
Metric: {
Namespace: "AWS/Bedrock",
MetricName: "InvocationLatency",
Dimensions: [{ Name: "ModelId", Value: modelId }],
},
Period: 300,
Stat: "p99", // percentile stats require GetMetricDataCommand, not GetMetricStatistics
},
ReturnData: true,
Label: "P99 Latency (ms)",
},
],
}));
Part 3: Throttle Handling — keeping tool calls responsive under TPS limits
Bedrock enforces per-account, per-region, per-model TPS limits on the on-demand tier. When you exceed them, every call returns a ThrottlingException with HTTP 429. For an MCP server, this is especially painful: the agent calling your tool is waiting synchronously, and a 429 that is not handled gracefully propagates as a tool failure to the user's AI assistant.
Default TPS limits by model
These are soft limits that can be raised via Service Quotas. They vary by account history and region. These are representative defaults as of late 2026:
// On-demand TPS defaults (requests per second)
// Source: AWS Service Quotas, Bedrock section
// Always verify with: aws service-quotas list-service-quotas --service-code bedrock
const DEFAULT_TPS_LIMITS = {
// Anthropic Claude 3
"anthropic.claude-3-haiku-20240307-v1:0": { tps: 50, tokenRpm: 100_000 },
"anthropic.claude-3-sonnet-20240229-v1:0": { tps: 10, tokenRpm: 50_000 },
"anthropic.claude-3-opus-20240229-v1:0": { tps: 5, tokenRpm: 20_000 },
"anthropic.claude-3-5-sonnet-20241022-v2:0": { tps: 20, tokenRpm: 100_000 },
"anthropic.claude-3-5-haiku-20241022-v1:0": { tps: 50, tokenRpm: 100_000 },
// Amazon Nova
"amazon.nova-micro-v1:0": { tps: 300, tokenRpm: 1_000_000 },
"amazon.nova-lite-v1:0": { tps: 100, tokenRpm: 500_000 },
"amazon.nova-pro-v1:0": { tps: 40, tokenRpm: 300_000 },
};
TPS limits count at the request level — one ConverseCommand = one request regardless of token count. Separate token-per-minute limits apply to some models. If you send many short prompts quickly, you hit the TPS limit first. If you send few long prompts, you may hit the TPM limit first. Both return the same ThrottlingException.
Identifying ThrottlingException
Use err.name for classification. The AWS SDK v3 uses string names, not typed exception classes, as the primary error identifier:
try {
return await runtime.send(new ConverseCommand({ ... }));
} catch (err: any) {
if (err.name === "ThrottlingException") {
// HTTP 429 — TPS or TPM limit exceeded
// No Retry-After header — you must implement your own backoff
throw err;
}
if (err.name === "ServiceUnavailableException") {
// HTTP 503 — Bedrock service issue, transient
throw err;
}
if (err.name === "ModelTimeoutException") {
// Model failed to generate a response within the timeout window
throw err;
}
// ValidationException, AccessDeniedException — not retryable
throw err;
}
The right retry strategy: full jitter exponential backoff
The AWS SDK v3 retries on ThrottlingException by default, but its default cap is 3 total attempts (2 retries). For MCP servers under burst load, 2 retries is rarely enough. The recommended approach is to either increase maxAttempts in the client config, or implement a custom retry wrapper with full jitter:
// Option 1: increase maxAttempts on the SDK client config
// SDK handles backoff automatically — simpler, less control over logging
const runtimeHighRetry = new BedrockRuntimeClient({
region: "us-east-1",
maxAttempts: 10, // 10 total attempts = up to 9 retries
});
// Option 2: custom retry wrapper with full jitter
// (use when you need per-attempt logging or circuit-breaking)
const RETRYABLE = new Set([
"ThrottlingException",
"ServiceUnavailableException",
"ModelTimeoutException",
]);
async function withBedrockRetry<T>(
fn: () => Promise<T>,
options: { maxAttempts?: number; baseDelayMs?: number; maxDelayMs?: number } = {}
): Promise<T> {
const { maxAttempts = 8, baseDelayMs = 100, maxDelayMs = 30_000 } = options;
for (let attempt = 0; attempt < maxAttempts; attempt++) {
try {
return await fn();
} catch (err: any) {
if (!RETRYABLE.has(err.name) || attempt === maxAttempts - 1) throw err;
// Full jitter: randomise across the full exponential window
// This spreads retries maximally to prevent retry storms
const exponential = Math.min(2 ** attempt * baseDelayMs, maxDelayMs);
const jittered = Math.random() * exponential;
console.warn(
`Bedrock ${err.name} attempt ${attempt + 1}/${maxAttempts} — retrying in ${jittered.toFixed(0)}ms`
);
await new Promise(r => setTimeout(r, jittered));
}
}
throw new Error("withBedrockRetry: exhausted all attempts"); // unreachable but satisfies TypeScript
}
// Usage
const response = await withBedrockRetry(() =>
runtime.send(new ConverseCommand({
modelId: "anthropic.claude-3-haiku-20240307-v1:0",
messages: [{ role: "user", content: [{ text: prompt }] }],
inferenceConfig: { maxTokens: 512 },
}))
);
Full jitter (randomising across the full exponential window) is preferred over equal jitter for Bedrock because it spreads concurrent retries across the widest possible window, reducing the probability of a retry storm where many parallel tool calls all retry simultaneously and re-trigger the throttle.
Cross-region inference as an immediate escape valve
Cross-region inference profile IDs (prefixed with a region code like us.) route calls across multiple AWS regions and are covered by a separate, usually higher, quota pool. Switching to a cross-region profile is the fastest way to add burst capacity without waiting 1–3 business days for a quota increase:
// Direct model ID — us-east-1 quota pool only
const DIRECT = "anthropic.claude-3-haiku-20240307-v1:0";
// Cross-region inference profile — combined us-east-1/us-west-2/etc. quota pool
// Typically 2–5× higher effective TPS than direct model ID
const CROSS_REGION = "us.anthropic.claude-3-haiku-20240307-v1:0";
// Fallback strategy: try direct first, switch to cross-region on throttle
async function callWithFallback(prompt: string): Promise<string> {
for (const modelId of [DIRECT, CROSS_REGION]) {
try {
const response = await runtime.send(new ConverseCommand({
modelId,
messages: [{ role: "user", content: [{ text: prompt }] }],
inferenceConfig: { maxTokens: 512 },
}));
return response.output?.message?.content?.[0]?.text ?? "";
} catch (err: any) {
if (err.name === "ThrottlingException" && modelId === DIRECT) {
console.warn("Direct quota exhausted — falling back to cross-region inference");
continue;
}
throw err;
}
}
throw new Error("All model routing strategies exhausted");
}
Cross-region inference adds 20–80 ms latency over same-region calls. For interactive MCP tools this is usually acceptable. The latency cost is negligible compared to waiting multiple seconds for retries to clear a sustained throttle.
Keeping interactive tools within their retry budget
An MCP tool call has an implicit timeout — if the tool takes too long, the agent framework may cancel it. With 8 retry attempts and exponential backoff, the theoretical maximum delay before giving up exceeds 90 seconds. Cap the total retry budget for interactive tools:
server.tool(
"summarize_mcp_server_logs",
{ logs: z.string() },
async ({ logs }) => {
const response = await withBedrockRetry(
() => runtime.send(new ConverseCommand({
modelId: "anthropic.claude-3-haiku-20240307-v1:0",
messages: [{ role: "user", content: [{ text: `Summarize these logs:\n\n${logs}` }] }],
inferenceConfig: { maxTokens: 300 },
})),
{
maxAttempts: 5,
baseDelayMs: 500,
maxDelayMs: 5_000, // cap retry window at ~15s total
}
);
return {
content: [{ type: "text", text: response.output?.message?.content?.[0]?.text ?? "" }],
};
}
);
Part 4: Usage Metadata — per-call cost tracking and budget control
Every ConverseCommand response includes a usage object with the exact token counts Bedrock used for billing. These numbers are available synchronously in the response before you close the connection. For MCP servers that process arbitrary user inputs, tracking these per tool call is the only reliable way to understand cost attribution and prevent runaway spend.
Reading usage from a Converse response
The usage field is a sibling of output at the top level of the response — not nested inside output.message:
import { BedrockRuntimeClient, ConverseCommand } from "@aws-sdk/client-bedrock-runtime";
const runtime = new BedrockRuntimeClient({ region: "us-east-1" });
async function callAndTrackUsage(modelId: string, prompt: string) {
const response = await runtime.send(new ConverseCommand({
modelId,
messages: [{ role: "user", content: [{ text: prompt }] }],
inferenceConfig: { maxTokens: 1024 },
}));
// response.usage is always defined on success
const { inputTokens, outputTokens, totalTokens } = response.usage!;
// $metadata.requestId matches the CloudWatch invocation log entry
const requestId = response.$metadata.requestId!;
// $metadata.attempts tells you how many times the SDK tried before succeeding
const attempts = response.$metadata.attempts ?? 1;
if (attempts > 1) {
console.warn(`Bedrock required ${attempts} SDK attempts — throttle pressure likely`);
}
console.log(`model: ${modelId} | input: ${inputTokens} | output: ${outputTokens} | total: ${totalTokens}`);
console.log(`requestId: ${requestId}`);
return { text: response.output?.message?.content?.[0]?.text ?? "", inputTokens, outputTokens, requestId };
}
Note that totalTokens is simply inputTokens + outputTokens. There is no separate "system prompt tokens" field — system prompt tokens are folded into inputTokens. Tool definitions in ToolConfiguration also contribute to inputTokens regardless of whether the model calls any tools.
Reading usage from streaming responses
For ConverseStreamCommand, the usage block arrives in a metadata event that is emitted after all content chunks. You must consume the full stream to access billing-accurate token counts:
import { ConverseStreamCommand } from "@aws-sdk/client-bedrock-runtime";
async function streamAndTrackUsage(modelId: string, prompt: string) {
const response = await runtime.send(new ConverseStreamCommand({
modelId,
messages: [{ role: "user", content: [{ text: prompt }] }],
inferenceConfig: { maxTokens: 1024 },
}));
let fullText = "";
let inputTokens = 0;
let outputTokens = 0;
for await (const event of response.stream ?? []) {
if (event.contentBlockDelta?.delta?.text) {
fullText += event.contentBlockDelta.delta.text;
// yield or forward chunk to client here
}
// metadata event arrives AFTER all contentBlockDelta events
if (event.metadata?.usage) {
inputTokens = event.metadata.usage.inputTokens ?? 0;
outputTokens = event.metadata.usage.outputTokens ?? 0;
}
}
// Record cost after stream fully consumed
const cost = estimateCostUsd(modelId, inputTokens, outputTokens);
console.log(`Stream complete — tokens: ${inputTokens}/${outputTokens} — cost: $${cost.toFixed(6)}`);
return { fullText, inputTokens, outputTokens };
}
// WRONG: do not estimate from chunk sizes — not proportional to token counts
// CORRECT: wait for the metadata event at the end of the stream
Tool use rounds counted separately
If the model calls a tool during a conversation and you then submit the tool result and get a final response, that exchange involves two ConverseCommand calls — each with its own usage object. To get the total token cost of a multi-turn tool use exchange, sum all usage objects across the full agentic loop:
async function runToolLoop(modelId: string, messages: Message[]): Promise<{
finalText: string;
totalInputTokens: number;
totalOutputTokens: number;
}> {
let totalInput = 0;
let totalOutput = 0;
const history = [...messages];
while (true) {
const response = await runtime.send(new ConverseCommand({
modelId,
messages: history,
toolConfig: { tools: mcpToolDefinitions },
}));
const { inputTokens, outputTokens } = response.usage!;
totalInput += inputTokens;
totalOutput += outputTokens;
if (response.stopReason === "end_turn") {
return {
finalText: response.output?.message?.content?.[0]?.text ?? "",
totalInputTokens: totalInput,
totalOutputTokens: totalOutput,
};
}
if (response.stopReason === "tool_use") {
// Add assistant message to history
history.push(response.output!.message!);
// Execute tools and collect results
const toolResults = await executeTools(response.output!.message!.content!);
// Add tool results as user message — this is a NEW invocation = new usage
history.push({ role: "user", content: toolResults });
}
}
}
Per-model cost rate table and estimation
type ModelCost = { inputPerMTok: number; outputPerMTok: number };
const BEDROCK_COST_RATES: Record<string, ModelCost> = {
// Anthropic Claude 3 family (USD per million tokens)
"anthropic.claude-3-haiku-20240307-v1:0": { inputPerMTok: 0.25, outputPerMTok: 1.25 },
"anthropic.claude-3-sonnet-20240229-v1:0": { inputPerMTok: 3.00, outputPerMTok: 15.00 },
"anthropic.claude-3-opus-20240229-v1:0": { inputPerMTok: 15.00, outputPerMTok: 75.00 },
"anthropic.claude-3-5-sonnet-20241022-v2:0": { inputPerMTok: 3.00, outputPerMTok: 15.00 },
"anthropic.claude-3-5-haiku-20241022-v1:0": { inputPerMTok: 0.80, outputPerMTok: 4.00 },
// Amazon Nova family
"amazon.nova-micro-v1:0": { inputPerMTok: 0.035, outputPerMTok: 0.14 },
"amazon.nova-lite-v1:0": { inputPerMTok: 0.06, outputPerMTok: 0.24 },
"amazon.nova-pro-v1:0": { inputPerMTok: 0.80, outputPerMTok: 3.20 },
// Amazon Titan Text
"amazon.titan-text-lite-v1": { inputPerMTok: 0.30, outputPerMTok: 0.40 },
"amazon.titan-text-express-v1": { inputPerMTok: 0.80, outputPerMTok: 1.60 },
};
function estimateCostUsd(modelId: string, inputTokens: number, outputTokens: number): number {
const rates = BEDROCK_COST_RATES[modelId];
if (!rates) return 0; // unknown model — return 0 rather than throw
return (inputTokens / 1_000_000) * rates.inputPerMTok
+ (outputTokens / 1_000_000) * rates.outputPerMTok;
}
// Example: 1,500 input + 300 output on Claude 3 Haiku
const cost = estimateCostUsd("anthropic.claude-3-haiku-20240307-v1:0", 1500, 300);
// → $0.000750
Per-tool cost attribution with structured logging
When a single MCP server exposes multiple tools, each calling Bedrock with potentially different models and prompt lengths, structured JSON logging per tool call lets you slice cost by tool in CloudWatch Insights or any log aggregator:
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
const server = new McpServer({ name: "alivemcp-tools", version: "1.0.0" });
function logToolCall(params: {
toolName: string;
modelId: string;
inputTokens: number;
outputTokens: number;
requestId: string;
durationMs: number;
}): void {
const cost = estimateCostUsd(params.modelId, params.inputTokens, params.outputTokens);
// Structured JSON for CloudWatch Logs Insights / Datadog / etc.
console.log(JSON.stringify({
event: "bedrock_tool_call",
...params,
estimatedCostUsd: cost,
timestamp: new Date().toISOString(),
}));
}
server.tool(
"analyze_server_latency_spike",
{
serverSlug: z.string(),
logSample: z.string(),
},
async ({ serverSlug, logSample }) => {
const modelId = "anthropic.claude-3-haiku-20240307-v1:0";
const t0 = Date.now();
const response = await runtime.send(new ConverseCommand({
modelId,
messages: [{
role: "user",
content: [{ text: `Analyze latency spike in MCP server '${serverSlug}':\n\n${logSample}` }],
}],
inferenceConfig: { maxTokens: 600 },
}));
const { inputTokens, outputTokens } = response.usage!;
const requestId = response.$metadata.requestId!;
logToolCall({
toolName: "analyze_server_latency_spike",
modelId,
inputTokens,
outputTokens,
requestId,
durationMs: Date.now() - t0,
});
return {
content: [{ type: "text", text: response.output?.message?.content?.[0]?.text ?? "" }],
};
}
);
Daily budget guard pattern
For production MCP servers where runaway LLM costs are a business risk, combine per-call tracking with a soft daily budget limit that returns a user-visible error before overspend occurs:
class DailyBudgetGuard {
private spendUsd = 0;
private resetDate = new Date().toDateString();
constructor(private limitUsd: number) {}
private maybeReset() {
const today = new Date().toDateString();
if (today !== this.resetDate) {
this.spendUsd = 0;
this.resetDate = today;
}
}
check(estimatedCostUsd: number): void {
this.maybeReset();
if (this.spendUsd + estimatedCostUsd > this.limitUsd) {
throw new Error(
`Daily Bedrock budget of $${this.limitUsd.toFixed(2)} exceeded. ` +
`Accumulated: $${this.spendUsd.toFixed(4)}.`
);
}
}
record(actualCostUsd: number): void {
this.maybeReset();
this.spendUsd += actualCostUsd;
}
}
const budget = new DailyBudgetGuard(5.00); // $5/day per server instance
async function callBedrockWithBudget(modelId: string, prompt: string): Promise<string> {
// Pre-flight check with estimated cost
const estimatedInput = prompt.length / 4; // rough char-to-token estimate
budget.check(estimateCostUsd(modelId, estimatedInput, 500));
const response = await runtime.send(new ConverseCommand({
modelId,
messages: [{ role: "user", content: [{ text: prompt }] }],
inferenceConfig: { maxTokens: 500 },
}));
const { inputTokens, outputTokens } = response.usage!;
budget.record(estimateCostUsd(modelId, inputTokens, outputTokens));
return response.output?.message?.content?.[0]?.text ?? "";
}
Consolidated production gotchas
- Logging is in
@aws-sdk/client-bedrock, not@aws-sdk/client-bedrock-runtime.PutModelInvocationLoggingConfigurationCommandlives in the control-plane package. Searching for it in the runtime package yields nothing. - The delivery role trust policy must name
delivery.logs.amazonaws.com, notbedrock.amazonaws.com. Using the wrong principal causes the role assumption to fail silently — the configuration PUT succeeds, but no logs appear. - Omitting
largeDataDeliveryS3Configcauses large payloads to be silently dropped. Any invocation payload above 100 KB (a long conversation with tool definitions, for example) will not appear in CloudWatch if you omit the companion S3 bucket configuration. No error is returned — the log entry simply does not exist. - Logging is account-scoped and region-scoped. There is no per-model toggle. Enabling text logging once covers all models and all callers in that region, including any IAM principal in the account.
- InvocationClientErrors includes
ThrottlingException. CloudWatch will not distinguish between throttled calls and validation errors in the error rate alarm. If you need to know specifically how many calls were throttled (not just how many client errors occurred), query the invocation logerrorCodefield via CloudWatch Insights. - InvocationLatency measures time to last byte, not time to first token. For streaming calls, the latency metric includes the full response generation time. If latency is your primary SLO concern, consider time-to-first-chunk tracking in your own application code rather than relying solely on the CloudWatch metric.
- Use
Sum, notAverage, for InputTokenCount and OutputTokenCount. The CloudWatch datapoints are already per-period sums. Averaging them divides the token count by the number of datapoints rather than giving you total consumption. - The AWS SDK default of 3 total attempts is too few for burst throttling. Set
maxAttempts: 10on theBedrockRuntimeClientconfig, or implement a custom retry wrapper with full jitter backoff. Full jitter (randomising across the full exponential window) is preferred over equal jitter to prevent retry storms. ThrottlingExceptioncarries noRetry-Afterheader. Unlike many other rate-limited APIs, Bedrock does not tell you how long to wait. You must implement your own backoff interval.- For streaming responses, usage tokens arrive in the last
metadataevent. Do not attempt to estimate token counts mid-stream from chunk sizes — chunk byte sizes are not proportional to token counts. Wait for theevent.metadata.usageevent at the end of the stream for the billing-authoritative count.
AliveMCP and end-to-end Bedrock observability
The four observability surfaces covered in this guide — invocation logging, CloudWatch metrics, throttle handling, and usage metadata — give you deep visibility into Bedrock's internal behaviour. What they don't cover is whether your MCP server endpoint is reachable by agents in the first place.
AliveMCP monitors your MCP server's external availability every 60 seconds, pinging your tools/list endpoint and validating JSON-RPC responses. When a Bedrock-related issue (sustained throttling, model timeout, invocation logging misconfiguration that blocks a required IAM action) causes your MCP tool to start returning errors to callers, AliveMCP will mark the endpoint degraded on the public dashboard within 60 seconds — before your users notice. For Author and Team plan subscribers, this triggers a Slack or webhook alert immediately.
Pair Bedrock's internal observability (invocation logs showing why calls fail, CloudWatch alarms showing when error rates breach thresholds) with AliveMCP's external monitoring (showing whether your server is reachable end-to-end for agents) for complete observability coverage of your AI-powered MCP infrastructure. See how AliveMCP monitors MCP endpoints →