Guide · Amazon Bedrock · Observability

MCP Server Amazon Bedrock Invocation Logging — PutModelInvocationLoggingConfiguration, CloudWatch, S3

Amazon Bedrock invocation logging captures the full input and output of every model call your MCP server makes, writing structured JSON records to CloudWatch Logs or S3. You enable it once per AWS account per region with PutModelInvocationLoggingConfigurationCommand from @aws-sdk/client-bedrock — not the runtime package. Four things trip up MCP server authors: logging is account-scoped, so enabling it once covers all models and all callers in that region (there is no per-model toggle); the CloudWatch delivery role must be in the same account as the logging configuration and have a trust policy for delivery.logs.amazonaws.com, not bedrock.amazonaws.com; large payloads (above 100 KB) are automatically redirected to a companion S3 path specified in largeDataDeliveryS3Config — if you omit this, large invocations are silently dropped from CloudWatch; and the log entry contains the raw request and response bodies, so you must exclude logging or redact before enabling if you are passing PII through the model. For CloudWatch metrics on latency and error rates see Bedrock CloudWatch metrics; for handling throttling exceptions see Bedrock throttling and retry; for reading token usage from responses see Bedrock usage metadata.

TL;DR

Import PutModelInvocationLoggingConfigurationCommand from @aws-sdk/client-bedrock. Supply either a cloudWatchConfig (with logGroupName and a delivery role ARN) or an s3Config (with bucketName), or both. Set textDataDeliveryEnabled: true to capture text model I/O. Add a largeDataDeliveryS3Config bucket or large payloads will be silently dropped. Use GetModelInvocationLoggingConfigurationCommand with no arguments to read the current account-level config.

Why invocation logging matters for MCP servers

An MCP server is an intermediary: an AI agent calls a tool, the tool calls Bedrock, and the result flows back. When something goes wrong — a tool returns garbage, a model produces an unexpected refusal, latency spikes — you need to know exactly what prompt reached the model and what it returned. Without invocation logging, your only visibility into Bedrock calls is the response object in memory at the moment of the call; once it's gone, it's gone.

Invocation logging creates a durable, queryable audit trail. Each log entry captures the model ID, the full request body, the full response body, the input and output token counts, the latency, and the caller identity (IAM ARN). You can feed these logs into CloudWatch Insights queries to find anomalously long calls, models returning errors at high rates, or specific tool invocations where token counts spiked unexpectedly.

Logging is also the data source for cost attribution when $metadata token counts are not granular enough. If your MCP server routes calls to multiple models depending on the tool being invoked, invocation logs let you slice cost by model and by IAM principal even without code changes in the server itself.

Package and client setup

Invocation logging is configured through the Bedrock control-plane client, the same package used for model management and customization jobs:

npm install @aws-sdk/client-bedrock
import {
  BedrockClient,
  PutModelInvocationLoggingConfigurationCommand,
  GetModelInvocationLoggingConfigurationCommand,
} from "@aws-sdk/client-bedrock";

const bedrockClient = new BedrockClient({
  region: process.env.AWS_REGION ?? "us-east-1",
});

The runtime package (@aws-sdk/client-bedrock-runtime) is for invoking models. Configuration lives exclusively in the control-plane package. This is a frequent source of confusion — if you search for PutModelInvocationLoggingConfigurationCommand in @aws-sdk/client-bedrock-runtime, it will not be found.

Minimal CloudWatch logging configuration

The shortest viable 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 you must grant Bedrock permission to create it), a delivery IAM role must exist with the trust policy shown below, and the caller making the PutModelInvocationLoggingConfigurationCommand API call must have bedrock:PutModelInvocationLoggingConfiguration permission:

import {
  BedrockClient,
  PutModelInvocationLoggingConfigurationCommand,
} from "@aws-sdk/client-bedrock";

const bedrockClient = new BedrockClient({ region: "us-east-1" });

async function enableInvocationLogging(params: {
  logGroupName: string;
  deliveryRoleArn: string;
}): Promise<void> {
  await bedrockClient.send(
    new PutModelInvocationLoggingConfigurationCommand({
      loggingConfig: {
        // Enable logging of text model (LLM) invocations
        textDataDeliveryEnabled: true,
        // Image model invocations (Titan Image, Stability) are separate
        imageDataDeliveryEnabled: false,
        // Embedding model invocations (Titan Embeddings)
        embeddingDataDeliveryEnabled: false,

        cloudWatchConfig: {
          logGroupName: params.logGroupName,
          roleArn: params.deliveryRoleArn,
          // Required if any single log entry payload exceeds 100 KB.
          // Payloads above the threshold are written to S3 instead.
          largeDataDeliveryS3Config: {
            bucketName: "my-bedrock-logs-bucket",
            keyPrefix: "large-payloads/",
          },
        },
      },
    })
  );
  console.log("Bedrock invocation logging enabled.");
}

await enableInvocationLogging({
  logGroupName: "/aws/bedrock/invocations",
  deliveryRoleArn: "arn:aws:iam::123456789012:role/BedrockLoggingDeliveryRole",
});

The call returns no data on success — a resolved promise with no payload means the configuration was accepted. The configuration takes effect within a few seconds and applies to all subsequent Bedrock invocations in the region from any caller in the account.

IAM delivery role setup

The role you supply in cloudWatchConfig.roleArn is assumed by the CloudWatch Logs delivery service, not by Bedrock itself. This is a critical distinction: the trust policy principal must be delivery.logs.amazonaws.com, not bedrock.amazonaws.com:

// Trust policy for the delivery role
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "Service": "delivery.logs.amazonaws.com" },
      "Action": "sts:AssumeRole",
      "Condition": {
        "StringEquals": { "aws:SourceAccount": "123456789012" }
      }
    }
  ]
}

// Permission policy attached to the delivery 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:*"
      ]
    }
  ]
}

If you are also using the largeDataDeliveryS3Config, the delivery role needs additional S3 permissions for the large-payload bucket:

{
  "Effect": "Allow",
  "Action": ["s3:PutObject", "s3:GetBucketLocation"],
  "Resource": [
    "arn:aws:s3:::my-bedrock-logs-bucket",
    "arn:aws:s3:::my-bedrock-logs-bucket/large-payloads/*"
  ]
}

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 if the IAM role permissions are correct.

Reading the current logging configuration

GetModelInvocationLoggingConfigurationCommand takes no arguments and returns the account-level configuration for the region you constructed the client in. Use it to verify your setup or to read the current config before modifying it:

import {
  GetModelInvocationLoggingConfigurationCommand,
} from "@aws-sdk/client-bedrock";

async function getLoggingConfig() {
  const response = await bedrockClient.send(
    new GetModelInvocationLoggingConfigurationCommand({})
  );

  const cfg = response.loggingConfig;
  if (!cfg) {
    console.log("Invocation logging is not configured for this region.");
    return;
  }

  console.log("Text logging enabled:", cfg.textDataDeliveryEnabled);
  console.log("Image logging enabled:", cfg.imageDataDeliveryEnabled);
  console.log("Embedding logging enabled:", cfg.embeddingDataDeliveryEnabled);

  if (cfg.cloudWatchConfig) {
    console.log("CloudWatch log group:", cfg.cloudWatchConfig.logGroupName);
    console.log("Delivery role:", cfg.cloudWatchConfig.roleArn);
  }

  if (cfg.s3Config) {
    console.log("S3 bucket:", cfg.s3Config.bucketName);
    console.log("S3 key prefix:", cfg.s3Config.keyPrefix ?? "(none)");
  }
}

await getLoggingConfig();

The response does not include the actual log entries — only the delivery configuration. If response.loggingConfig is undefined, logging has never been configured in this account+region combination. If it exists but textDataDeliveryEnabled is false, text model calls are not being logged even though the configuration object is present.

Log entry format

Each invocation writes one JSON record to CloudWatch Logs (or S3). The record structure is consistent across models but the input.inputBodyJson and output.outputBodyJson fields contain the raw API payloads, which differ by model. For ConverseCommand calls, the body contains the Converse API request and response shapes; for direct InvokeModelCommand calls, it contains the model-native payload:

// CloudWatch log entry — representative shape for a Converse API 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",
  "operation": "Converse",
  "modelId": "anthropic.claude-3-haiku-20240307-v1:0",
  "errorCode": null,
  "input": {
    "inputTokenCount": 150,
    "inputBodyJson": "{\"messages\":[{\"role\":\"user\",\"content\":[{\"text\":\"What is the uptime of server mcp-server-123?\"}]}],\"inferenceConfig\":{\"maxTokens\":512}}"
  },
  "output": {
    "outputTokenCount": 78,
    "outputBodyJson": "{\"output\":{\"message\":{\"role\":\"assistant\",\"content\":[{\"text\":\"The server mcp-server-123 has been up for 99.7% of the last 30 days...\"}]}},\"stopReason\":\"end_turn\",\"usage\":{\"inputTokens\":150,\"outputTokens\":78,\"totalTokens\":228}}"
  }
}

Key fields to watch in MCP server debugging workflows:

Disabling or clearing logging

To disable all invocation logging, call PutModelInvocationLoggingConfigurationCommand with an empty loggingConfig that has all delivery flags set to false and no delivery targets:

async function disableInvocationLogging(): Promise<void> {
  await bedrockClient.send(
    new PutModelInvocationLoggingConfigurationCommand({
      loggingConfig: {
        textDataDeliveryEnabled: false,
        imageDataDeliveryEnabled: false,
        embeddingDataDeliveryEnabled: false,
      },
    })
  );
}

await disableInvocationLogging();

There is no DeleteModelInvocationLoggingConfigurationCommand. The PUT call with all flags false is idiomatic for clearing the configuration. This is an account-level, region-scoped operation — it disables logging for every model, every tool, and every caller in the region in one call.

Querying logs with CloudWatch Logs Insights

Once invocation logs land in a CloudWatch log group, you can query them with Insights. Useful queries for MCP server debugging:

-- Find 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
stats
  sum(input.inputTokenCount) as totalInput,
  sum(output.outputTokenCount) as totalOutput,
  count() as callCount
by modelId
| sort callCount desc

-- Identify the slowest tool calls (requires a correlating requestId in your app logs)
fields @timestamp, modelId, input.inputTokenCount, output.outputTokenCount
| filter operation = "Converse"
| sort input.inputTokenCount desc
| limit 20

CloudWatch Insights queries run directly against the compressed log data — no ETL required. For longer-horizon analytics (30+ days), configure an S3 delivery target alongside CloudWatch and query the S3 data with Athena using the standard Bedrock invocation log table schema provided in the AWS documentation.

Correlating log entries with MCP tool call errors

When an MCP tool call fails and you need to find the corresponding Bedrock log entry, use the requestId from the SDK's $metadata field. The requestId in the CloudWatch log entry matches the $metadata.requestId returned by the SDK on both successful and failed calls:

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().describe("MCP server endpoint 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 },
      }));

      // Capture requestId for log correlation
      requestId = response.$metadata.requestId;

      return {
        content: [{
          type: "text",
          // Include requestId in response so callers can correlate with Bedrock logs
          text: `${response.output?.message?.content?.[0]?.text ?? ""}\n\n[requestId: ${requestId}]`,
        }],
      };
    } catch (err: any) {
      // requestId is available even on error responses
      requestId = err.$metadata?.requestId;
      console.error(`Bedrock call failed — requestId: ${requestId}`, err.message);
      throw err;
    }
  }
);

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

Log the requestId in your application-level logs alongside the tool name, the user session, and the timestamp. When debugging, search CloudWatch Insights for that exact requestId in the Bedrock invocation log group to retrieve the full prompt and response — no guessing about what was sent to the model.

AliveMCP and Bedrock observability

AliveMCP monitors the availability and response time of MCP endpoints — the same endpoints your Bedrock-backed tools expose. If your MCP server uses Bedrock and starts logging ThrottlingExceptions or ModelTimeoutExceptions, AliveMCP will surface that as degraded health on your server's status page before your users notice. Pair Bedrock invocation logs (which tell you why calls fail) with AliveMCP's uptime monitoring (which tells you when your server is degraded end-to-end) for complete observability of AI-powered MCP infrastructure. See how AliveMCP monitors MCP endpoints →