Guide · Amazon Bedrock · Cost Tracking

MCP Server Amazon Bedrock Usage Metadata — inputTokens, outputTokens, Cost Tracking

Every ConverseCommand response from Amazon Bedrock includes a usage object with inputTokens, outputTokens, and totalTokens — the exact token counts Bedrock uses for billing, available synchronously in the response before you close the connection. For MCP servers that process arbitrary user inputs, tracking these numbers per tool call is the only way to understand cost attribution and prevent runaway spend. Four gotchas for MCP server authors: response.usage is in the Converse response body, not in $metadata; for streaming calls (ConverseStreamCommand), the usage block arrives in the metadata event at the end of the stream, not before the first content chunk; totalTokens is simply inputTokens + outputTokens — there is no separate "system prompt tokens" field, those are folded into inputTokens; and tool use rounds each count separately — if the model calls a tool and then receives a tool result and responds again, that is two invocations and you must add both usage objects to get total tokens for the full multi-turn exchange. For logging all invocations durably see Bedrock invocation logging; for CloudWatch alarms on token volume see Bedrock CloudWatch metrics; for handling throttling when token budgets trigger rate limits see Bedrock throttling and retry.

TL;DR

Read response.usage.inputTokens, response.usage.outputTokens, and response.usage.totalTokens from every ConverseCommand response. For streaming, collect the metadata event at the end of the stream. Multiply by per-model rates (see table below) to get USD cost. Log response.$metadata.requestId alongside your tool name so you can correlate cost to specific MCP tool invocations.

Reading usage from a Converse response

The usage field is always present on successful ConverseCommand responses. It is not nested inside output — it is a sibling field at the top level of the response object:

import { BedrockRuntimeClient, ConverseCommand } from "@aws-sdk/client-bedrock-runtime";

const runtime = new BedrockRuntimeClient({ region: "us-east-1" });

async function callAndTrackUsage(modelId: string, prompt: string): Promise<{
  text: string;
  inputTokens: number;
  outputTokens: number;
  requestId: 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!;

  const text = response.output?.message?.content?.[0]?.text ?? "";

  console.log(`Bedrock call — model: ${modelId}`);
  console.log(`  requestId: ${requestId}`);
  console.log(`  inputTokens: ${inputTokens}  outputTokens: ${outputTokens}  total: ${totalTokens}`);

  return { text, inputTokens, outputTokens, requestId };
}

const result = await callAndTrackUsage(
  "anthropic.claude-3-haiku-20240307-v1:0",
  "What is the typical response time for a healthy MCP server endpoint?"
);
console.log("Response:", result.text);

The $metadata object is populated by the SDK on both successful and failed calls. Even if you catch a ThrottlingException and retry, the final successful attempt will have a fresh $metadata.requestId that you can log. $metadata.attempts tells you how many times the SDK tried before succeeding, and $metadata.totalRetryDelay gives you the total milliseconds spent waiting between retries — useful for detecting when throttle pressure is adding real latency to your MCP tool calls.

Reading usage from a streaming response

For ConverseStreamCommand, token counts arrive in a metadata event that is emitted after all content chunks. You must consume the full stream to access usage data:

import {
  BedrockRuntimeClient,
  ConverseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime";

async function streamAndTrackUsage(modelId: string, prompt: string): Promise<{
  fullText: string;
  inputTokens: number;
  outputTokens: number;
}> {
  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) {
      // Accumulate text chunks as they arrive
      fullText += event.contentBlockDelta.delta.text;
    }

    if (event.metadata?.usage) {
      // Usage data arrives at the end of the stream
      inputTokens = event.metadata.usage.inputTokens ?? 0;
      outputTokens = event.metadata.usage.outputTokens ?? 0;
    }
  }

  console.log(`Streaming call — inputTokens: ${inputTokens}  outputTokens: ${outputTokens}`);
  return { fullText, inputTokens, outputTokens };
}

Do not attempt to estimate token counts mid-stream from chunk sizes — the token count in the final metadata event is the authoritative billing count. Chunk byte sizes are not proportional to token counts, especially for structured outputs or code.

Per-model cost rates (approximate, as of late 2026)

Bedrock pricing is per million tokens, with separate rates for input and output. Output tokens typically cost 3–6× more than input tokens because they require autoregressive generation while input tokens are processed in parallel. These are on-demand rates — Provisioned Throughput has different pricing. Always verify current rates in the AWS Bedrock pricing page:

// Approximate on-demand rates (USD per million tokens) — late 2026
// Verify at https://aws.amazon.com/bedrock/pricing/ before production use

type ModelCost = { inputPerMTok: number; outputPerMTok: number };

const BEDROCK_COST_RATES: Record<string, ModelCost> = {
  // Anthropic Claude 3 family
  "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

  const inputCost  = (inputTokens  / 1_000_000) * rates.inputPerMTok;
  const outputCost = (outputTokens / 1_000_000) * rates.outputPerMTok;
  return inputCost + outputCost;
}

// Example: 1,500 input tokens + 300 output tokens on Claude 3 Haiku
const cost = estimateCostUsd(
  "anthropic.claude-3-haiku-20240307-v1:0",
  1500, 300
);
console.log(`Estimated cost: $${cost.toFixed(6)}`); // → $0.000750

Per-tool cost attribution in MCP servers

When a single MCP server exposes multiple tools and each tool calls Bedrock with potentially different models and prompt lengths, you need per-tool cost attribution to understand which tools are expensive and whether a user is abusing a tool that generates long outputs:

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";

// Simple in-memory cost accumulator — replace with your DB or metrics system
const toolCostAccumulator = new Map<string, { totalUsd: number; callCount: number }>();

function trackToolCost(
  toolName: string,
  modelId: string,
  inputTokens: number,
  outputTokens: number,
  requestId: string
): void {
  const cost = estimateCostUsd(modelId, inputTokens, outputTokens);

  const existing = toolCostAccumulator.get(toolName) ?? { totalUsd: 0, callCount: 0 };
  toolCostAccumulator.set(toolName, {
    totalUsd: existing.totalUsd + cost,
    callCount: existing.callCount + 1,
  });

  // Log structured record for downstream ingestion (CloudWatch, Datadog, etc.)
  console.log(JSON.stringify({
    event: "bedrock_tool_call",
    toolName,
    modelId,
    inputTokens,
    outputTokens,
    estimatedCostUsd: cost,
    requestId,
    timestamp: new Date().toISOString(),
  }));
}

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

server.tool(
  "analyze_server_latency_spike",
  {
    serverSlug: z.string().describe("MCP server slug from the AliveMCP registry"),
    logSample: z.string().describe("Sample of server logs showing the latency spike"),
  },
  async ({ serverSlug, logSample }) => {
    const modelId = "anthropic.claude-3-haiku-20240307-v1:0";

    const response = await runtime.send(new ConverseCommand({
      modelId,
      messages: [{
        role: "user",
        content: [{
          text: `Analyze this latency spike in MCP server '${serverSlug}':\n\n${logSample}\n\nIdentify the root cause and recommend a fix.`,
        }],
      }],
      inferenceConfig: { maxTokens: 600 },
    }));

    const { inputTokens, outputTokens } = response.usage!;
    const requestId = response.$metadata.requestId!;

    // Track cost for this specific tool
    trackToolCost("analyze_server_latency_spike", modelId, inputTokens, outputTokens, requestId);

    return {
      content: [{
        type: "text",
        text: response.output?.message?.content?.[0]?.text ?? "",
      }],
    };
  }
);

// Expose accumulated cost data as a tool for ops visibility
server.tool(
  "get_tool_cost_summary",
  {},
  async () => {
    const summary: Record<string, unknown> = {};
    for (const [tool, stats] of toolCostAccumulator) {
      summary[tool] = {
        totalUsd: stats.totalUsd.toFixed(6),
        callCount: stats.callCount,
        avgCostPerCall: (stats.totalUsd / stats.callCount).toFixed(6),
      };
    }
    return { content: [{ type: "text", text: JSON.stringify(summary, null, 2) }] };
  }
);

await server.connect(/* transport */);

Budget alerting with accumulated token spend

For production MCP servers where runaway LLM costs are a business risk, combine per-call tracking with a soft budget limit that returns a user-visible error before overspend occurs:

// Daily budget tracker — resets at midnight UTC
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 exceeded ($${this.limitUsd.toFixed(2)} limit). ` +
        `Accumulated: $${this.spendUsd.toFixed(4)}.`
      );
    }
  }

  record(actualCostUsd: number): void {
    this.maybeReset();
    this.spendUsd += actualCostUsd;
  }

  get remainingUsd(): number {
    this.maybeReset();
    return Math.max(0, this.limitUsd - this.spendUsd);
  }
}

// $5/day limit per MCP server instance
const budgetGuard = new DailyBudgetGuard(5.00);

async function callBedrockWithBudget(
  modelId: string,
  inputTokenEstimate: number,
  prompt: string
): Promise<string> {
  // Rough pre-call budget check using estimated input + expected output
  const estimatedOutputTokens = 500;
  const estimatedCost = estimateCostUsd(modelId, inputTokenEstimate, estimatedOutputTokens);

  budgetGuard.check(estimatedCost);

  const response = await runtime.send(new ConverseCommand({
    modelId,
    messages: [{ role: "user", content: [{ text: prompt }] }],
    inferenceConfig: { maxTokens: estimatedOutputTokens },
  }));

  const { inputTokens, outputTokens } = response.usage!;
  const actualCost = estimateCostUsd(modelId, inputTokens, outputTokens);
  budgetGuard.record(actualCost);

  console.log(
    `Budget used: $${actualCost.toFixed(6)} | remaining today: $${budgetGuard.remainingUsd.toFixed(4)}`
  );

  return response.output?.message?.content?.[0]?.text ?? "";
}

AliveMCP and AI cost visibility

AliveMCP monitors MCP server availability, but cost spikes and degraded endpoints often go hand in hand — an MCP server that starts returning slow or error responses may be hitting Bedrock throttling caused by a runaway tool. If you are building a Bedrock-backed MCP server and publishing it in the AliveMCP registry, adding per-call cost tracking (as shown above) means you will spot the runaway before your AWS bill does. AliveMCP's real-time response-time history on each server's status page gives you the external view; your Bedrock usage metadata gives you the internal one. See AliveMCP's public dashboard for the MCP ecosystem →