Guide · Amazon Bedrock · CloudWatch

MCP Server Amazon Bedrock CloudWatch Metrics — InvocationLatency, InputTokenCount, Alarms

Amazon Bedrock publishes built-in metrics to CloudWatch under the AWS/Bedrock namespace — no agent, no custom instrumentation, no extra config required. The metrics cover invocation count, latency, error rates, and token usage, all dimensioned by ModelId. Four things catch MCP server builders off-guard: metrics are emitted on a 1-minute resolution by default, so a latency spike narrower than 60 seconds may not appear; the InvocationLatency metric measures time from first byte sent to last byte received, so it includes response streaming time for streaming calls — not just time-to-first-token; throttled calls count as InvocationClientErrors (not a separate metric), so your error rate alarm will fire on sustained throttling even if no data is lost thanks to client-side retries; and InputTokenCount and OutputTokenCount are per-invocation sums — to get total tokens over a period, use the Sum statistic, not Average. For enabling full request/response logging see Bedrock invocation logging; for handling throttling see Bedrock throttling and retry; for per-call token counts in code see Bedrock usage metadata.

TL;DR

Namespace is AWS/Bedrock. Primary dimension is ModelId — the exact foundation model ID string (e.g., anthropic.claude-3-haiku-20240307-v1:0). Key metrics: Invocations (Sum), InvocationLatency (Average/p99), InvocationClientErrors (Sum), InvocationServerErrors (Sum), InputTokenCount (Sum), OutputTokenCount (Sum). Query with GetMetricStatisticsCommand from @aws-sdk/client-cloudwatch; create alarms with PutMetricAlarmCommand.

Available metrics in the AWS/Bedrock namespace

Bedrock emits metrics automatically for every invocation. No opt-in is required beyond having IAM permissions to read CloudWatch metrics (cloudwatch:GetMetricStatistics or cloudwatch:GetMetricData). The full set of metrics published as of late 2026:

// Metric reference — AWS/Bedrock namespace
//
// Metric name             | Unit          | Useful statistic | What it measures
// ----------------------- | ------------- | ---------------- | -----------------------------------------
// Invocations             | Count         | Sum              | Successful model invocations
// InvocationLatency       | Milliseconds  | Average, p99     | End-to-end latency (request to full response)
// InvocationClientErrors  | Count         | Sum              | 4xx errors: throttling, validation, auth
// InvocationServerErrors  | Count         | Sum              | 5xx errors: timeouts, service unavailable
// InputTokenCount         | Count         | Sum, Average     | Input tokens consumed per invocation
// OutputTokenCount        | Count         | Sum, Average     | Output tokens generated per invocation

// Primary dimension
// ModelId: exact foundation model ID string
// Example values:
//   "anthropic.claude-3-haiku-20240307-v1:0"
//   "anthropic.claude-3-sonnet-20240229-v1:0"
//   "amazon.nova-micro-v1:0"
//   "amazon.nova-pro-v1:0"
//   "amazon.titan-text-lite-v1"

When no dimension is specified in a query, CloudWatch aggregates the metric across all models in the region. Specifying ModelId gives you per-model granularity. There is no dimension for the calling IAM ARN or for a specific MCP tool — if you need that level of attribution, enable invocation logging and query it via CloudWatch Insights or Athena.

Querying metrics programmatically

Use GetMetricStatisticsCommand from @aws-sdk/client-cloudwatch to pull metric data into your MCP server's monitoring dashboard or operational runbooks:

npm install @aws-sdk/client-cloudwatch
import {
  CloudWatchClient,
  GetMetricStatisticsCommand,
  StandardUnit,
  Statistic,
} from "@aws-sdk/client-cloudwatch";

const cw = new CloudWatchClient({ region: "us-east-1" });

async function getBedrockLatencyStats(params: {
  modelId: string;
  startTime: Date;
  endTime: Date;
  periodSeconds?: number;
}): Promise<{ average: number; max: number; sampleCount: number } | null> {
  const { Datapoints } = await cw.send(
    new GetMetricStatisticsCommand({
      Namespace: "AWS/Bedrock",
      MetricName: "InvocationLatency",
      Dimensions: [{ Name: "ModelId", Value: params.modelId }],
      StartTime: params.startTime,
      EndTime: params.endTime,
      // Minimum period is 60 seconds for most Bedrock metrics
      Period: params.periodSeconds ?? 300,
      Statistics: [Statistic.Average, Statistic.Maximum, Statistic.SampleCount],
      Unit: StandardUnit.Milliseconds,
    })
  );

  if (!Datapoints || Datapoints.length === 0) return null;

  // Datapoints are not guaranteed to be in order
  Datapoints.sort((a, b) => (a.Timestamp?.getTime() ?? 0) - (b.Timestamp?.getTime() ?? 0));

  // Aggregate across all returned datapoints for the full window
  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);
  const max = Math.max(...Datapoints.map(d => d.Maximum ?? 0));

  return {
    average: totalCount > 0 ? totalWeighted / totalCount : 0,
    max,
    sampleCount: totalCount,
  };
}

// Example: last-hour average latency for Claude 3 Haiku
const now = new Date();
const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);

const stats = await getBedrockLatencyStats({
  modelId: "anthropic.claude-3-haiku-20240307-v1:0",
  startTime: oneHourAgo,
  endTime: now,
  periodSeconds: 300,
});

console.log("Avg latency (ms):", stats?.average.toFixed(0));
console.log("Max latency (ms):", stats?.max.toFixed(0));
console.log("Total invocations:", stats?.sampleCount);

For high-frequency monitoring (multiple metrics at once), prefer GetMetricDataCommand over GetMetricStatisticsCommand — it supports fetching multiple metrics in a single API call, can compute percentile statistics (p99), and has better cost efficiency at scale.

Fetching error rate and token usage

async function getBedrockErrorRate(modelId: string, windowMinutes = 60): Promise<number> {
  const now = new Date();
  const start = new Date(now.getTime() - windowMinutes * 60 * 1000);
  const period = Math.max(60, windowMinutes * 60);

  const fetchCount = 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],
        Unit: StandardUnit.Count,
      })
    );
    return Datapoints?.reduce((s, d) => s + (d.Sum ?? 0), 0) ?? 0;
  };

  const [invocations, clientErrors, serverErrors] = await Promise.all([
    fetchCount("Invocations"),
    fetchCount("InvocationClientErrors"),
    fetchCount("InvocationServerErrors"),
  ]);

  const totalAttempts = invocations + clientErrors + serverErrors;
  if (totalAttempts === 0) return 0;
  return ((clientErrors + serverErrors) / totalAttempts) * 100;
}

async function getTokenUsage(modelId: string, windowMinutes = 60): Promise<{
  inputTokens: number;
  outputTokens: number;
}> {
  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],
        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 };
}

Remember to use Sum (not Average) for InputTokenCount and OutputTokenCount — the per-datapoint value is already a sum of tokens across all invocations in that period, so averaging it would divide by the number of datapoints rather than giving you the total token consumption.

Setting up CloudWatch alarms for Bedrock health

For production MCP servers, create alarms that fire before users notice degradation. Three alarms cover the most common Bedrock failure modes:

import {
  CloudWatchClient,
  PutMetricAlarmCommand,
  ComparisonOperator,
  TreatMissingData,
  Statistic,
  StandardUnit,
} from "@aws-sdk/client-cloudwatch";

const cw = new CloudWatchClient({ region: "us-east-1" });

// Alarm 1: High client error rate — fires when >10% of calls are 4xx (throttling, auth, validation)
// on Claude 3 Haiku over any 5-minute window
await cw.send(new PutMetricAlarmCommand({
  AlarmName: "Bedrock-Haiku-ClientErrorRate-High",
  AlarmDescription: "Bedrock Claude 3 Haiku client error rate exceeds 10% over 5 minutes",
  Namespace: "AWS/Bedrock",
  MetricName: "InvocationClientErrors",
  Dimensions: [{ Name: "ModelId", Value: "anthropic.claude-3-haiku-20240307-v1:0" }],
  Statistic: Statistic.Sum,
  Period: 300,         // 5 minutes
  EvaluationPeriods: 1,
  Threshold: 10,       // 10 errors in 5 minutes
  ComparisonOperator: ComparisonOperator.GreaterThanOrEqualToThreshold,
  TreatMissingData: TreatMissingData.notBreaching,
  AlarmActions: [
    "arn:aws:sns:us-east-1:123456789012:mcp-server-alerts",
  ],
}));

// Alarm 2: High average latency — fires when average latency exceeds 8 seconds over 10 minutes
// (Haiku is fast; 8s average suggests something is wrong)
await cw.send(new PutMetricAlarmCommand({
  AlarmName: "Bedrock-Haiku-Latency-High",
  AlarmDescription: "Bedrock Claude 3 Haiku average latency exceeds 8 seconds",
  Namespace: "AWS/Bedrock",
  MetricName: "InvocationLatency",
  Dimensions: [{ Name: "ModelId", Value: "anthropic.claude-3-haiku-20240307-v1:0" }],
  Statistic: Statistic.Average,
  Unit: StandardUnit.Milliseconds,
  Period: 600,          // 10 minutes
  EvaluationPeriods: 2, // must breach 2 consecutive periods to alarm
  Threshold: 8000,      // 8 seconds in milliseconds
  ComparisonOperator: ComparisonOperator.GreaterThanOrEqualToThreshold,
  TreatMissingData: TreatMissingData.notBreaching,
  AlarmActions: [
    "arn:aws:sns:us-east-1:123456789012:mcp-server-alerts",
  ],
}));

// Alarm 3: Server errors — any 5xx error fires immediately
// (InvocationServerErrors are Bedrock-side failures, always worth paging on)
await cw.send(new PutMetricAlarmCommand({
  AlarmName: "Bedrock-ServerErrors-Any",
  AlarmDescription: "Bedrock returned 5xx errors",
  Namespace: "AWS/Bedrock",
  MetricName: "InvocationServerErrors",
  // No 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",
  ],
}));

Using metric math for derived signals

CloudWatch metric math lets you compute derived metrics — like error rate as a percentage of total calls — directly in the CloudWatch console or via the GetMetricDataCommand API. This is cleaner than computing ratios client-side because the alarm can reference the computed expression:

import {
  CloudWatchClient,
  GetMetricDataCommand,
} from "@aws-sdk/client-cloudwatch";

async function getBedrockDashboardData(modelId: string): Promise<void> {
  const now = new Date();
  const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);

  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,  // used in expression only
      },
      {
        Id: "clientErrors",
        MetricStat: {
          Metric: {
            Namespace: "AWS/Bedrock",
            MetricName: "InvocationClientErrors",
            Dimensions: [{ Name: "ModelId", Value: modelId }],
          },
          Period: 300,
          Stat: "Sum",
        },
        ReturnData: false,
      },
      {
        Id: "errorRate",
        // Error rate as % of total attempts (invocations + errors = total attempts)
        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",
        },
        ReturnData: true,
        Label: "P99 Latency (ms)",
      },
    ],
  }));

  for (const result of response.MetricDataResults ?? []) {
    console.log(`${result.Label}:`);
    result.Values?.forEach((v, i) => {
      const ts = result.Timestamps?.[i]?.toISOString() ?? "";
      console.log(`  ${ts}: ${v.toFixed(2)}`);
    });
  }
}

The + 0.001 in the expression prevents division-by-zero when invocations + clientErrors is zero (no calls in the period). CloudWatch metric math expressions follow a simple language documented in the CloudWatch User Guide — available operators include arithmetic, math functions, and time-series operations like FILL for filling gaps.

AliveMCP and Bedrock health monitoring

CloudWatch tells you about Bedrock's internal health — but it doesn't tell you 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 the tools/list endpoint and checking for valid JSON-RPC responses. When a Bedrock-related issue (throttling spike, model timeout) causes your MCP tool to start returning errors to callers, AliveMCP will mark the endpoint degraded on the public dashboard. Pair Bedrock's CloudWatch alarms (internal health) with AliveMCP's uptime monitoring (external health) for a complete picture of your AI infrastructure. See how AliveMCP monitors MCP endpoints →