Guide · Amazon Bedrock · Converse API

MCP Server Bedrock Converse System Prompts and Conversation History

System prompts and conversation history are the two inputs that most directly shape model behavior in the Bedrock Converse API — and both have structural rules that produce ValidationException when violated. The system field in ConverseCommandInput is typed as SystemContentBlock[], where every element must be a plain { text: string } object; the Converse API does not accept guardrail blocks or image blocks in the system position. The messages array must alternate strictly between user and assistant roles, must start with a user turn, and when any prior turn included tool calls the history must contain the matching ToolUseBlock and ToolResultBlock pair in the correct positions or the API rejects the entire request. MCP servers add a third concern: they are typically stateless — conversation history comes from the client on each tool call, the server rebuilds the Message[] array, and the total token count of system prompt + messages + tool schemas must stay within the model's context window. This page covers the type definitions, best practices for structuring system prompts for MCP use cases, the sliding window algorithm for trimming history, per-model context limits, token estimation without a dedicated counting endpoint, and the guardrail intervention stop reason. For the Converse API overview see Bedrock Converse API overview; for tool use in multi-turn conversations see Converse multi-turn tool use.

TL;DR

The system field is SystemContentBlock[] — always { text: string } blocks, never empty array. The messages array must start with user, alternate roles, and preserve ToolUseBlock/ToolResultBlock pairs when trimming history. MCP servers are stateless — the client passes history, the server builds the array per call. Apply a sliding window when estimated tokens exceed ~80% of the model's context limit.

SystemContentBlock — type definition and constraints

The system field of ConverseCommandInput is typed in the AWS SDK as SystemContentBlock[] | undefined. As of late 2026, the Converse API accepts only one variant of SystemContentBlock:

// From @aws-sdk/client-bedrock-runtime type definitions:
// type SystemContentBlock =
//   | SystemContentBlock.TextMember        // { text: string }
//   | SystemContentBlock.GuardrailContentMember  // NOT accepted by ConverseCommand
//   | SystemContentBlock.$UnknownMember

// The only valid form for ConverseCommand:
const systemBlock: SystemContentBlock = { text: "You are a helpful assistant." };

// Multiple blocks are concatenated — split for readability, not for semantic separation:
const system: SystemContentBlock[] = [
  { text: "You are a monitoring assistant for AliveMCP." },
  { text: "Users ask about their MCP server uptime, latency metrics, and alert configuration." },
  { text: "Respond in concise Markdown. Never fabricate server names or metric values." },
];

Three constraints enforced at the API level:

Nova models (Micro, Lite, Pro) support system prompts and accept the same { text: string } syntax. Keep system prompts under 32k tokens for all models — that is the system prompt limit for Titan Premier and Mistral Large, the most constrained models in the Converse-compatible lineup.

System prompt best practices for MCP server tools

An MCP tool handler calling the Converse API is different from a user-facing chatbot in several ways: the "user" is typically another LLM (the MCP host), the tool call arguments carry structured intent, and the response will be parsed by software. These differences should shape how you write system prompts.

Define role and task scope precisely

The first sentence should state exactly what the model is and what it is not. Vague role descriptions ("You are a helpful assistant") produce vague outputs. Task-scoped roles produce consistent, actionable outputs:

// Vague — produces inconsistent output format and scope
const vague = `You are a helpful assistant that knows about cloud services.`;

// Precise — model knows its scope, response format, and what not to do
const precise = `You are a JSON-only configuration auditor for Amazon Bedrock Converse API calls. \
Given a ConverseCommandInput object, identify structural problems that would cause \
ValidationException. Output ONLY a JSON object with shape: \
{ "valid": boolean, "errors": string[], "warnings": string[] }. \
Never include prose outside the JSON object. Never invent errors that are not present.`;

Describe the response format explicitly

If the MCP tool will parse the model's response, tell the model exactly what format to produce. Ambiguity about format forces you to write brittle string parsers. The three formats relevant to MCP tool outputs:

// JSON output — tell the model the exact schema
const jsonSystemPrompt = [
  { text: "You are a metric analysis engine for AliveMCP." },
  { text: "Output ONLY valid JSON matching this schema:" },
  { text: JSON.stringify({
      type: "object",
      properties: {
        summary: { type: "string" },
        anomalies: { type: "array", items: { type: "string" } },
        severity: { type: "string", enum: ["low", "medium", "high", "critical"] },
      },
      required: ["summary", "anomalies", "severity"],
    }, null, 2)
  },
  { text: "Never include prose, markdown fences, or explanation outside the JSON object." },
];

// Markdown output — tell the model the heading structure
const markdownSystemPrompt = [
  { text: "You are a documentation writer for MCP server configurations." },
  { text: "Format responses in Markdown with H2 for main sections, H3 for subsections." },
  { text: "Use fenced code blocks with language identifiers. Keep each section under 200 words." },
];

// Plain text — tell the model to avoid all markup
const plainTextSystemPrompt = [
  { text: "You are a concise summarizer for uptime reports." },
  { text: "Respond in plain prose only. No headers, no bullets, no markdown, no code blocks." },
  { text: "Maximum 3 sentences per response." },
];

Inject tool capability context

When the model's job is to decide which tool to call or how to interpret tool results, the system prompt should describe what tools are available and what their outputs mean — especially when tool schemas alone are not self-documenting:

function buildSystemPromptWithToolContext(availableTools: string[]): SystemContentBlock[] {
  return [
    { text: "You are an orchestration assistant for AliveMCP server monitoring." },
    { text: `Available tools: ${availableTools.join(", ")}.` },
    { text: "get_server_status returns JSON with fields: serverId, status (up|down|degraded), p99LatencyMs, lastCheckAt." },
    { text: "list_alerts returns JSON array of { alertId, condition, threshold, lastFiredAt }." },
    { text: "When the user asks about a server, always call get_server_status first before drawing conclusions." },
    { text: "Never state a server is down unless get_server_status.status === 'down'. Do not infer status from latency alone." },
  ];
}

Constrain scope to prevent hallucination

Explicitly instruct the model to ask for clarification rather than fabricate. Models operating in multi-turn MCP tool chains are more likely to hallucinate when given broad freedom:

const antiHallucinationConstraints: SystemContentBlock[] = [
  { text: "Only reference server names, metric values, and alert IDs that appear explicitly in the conversation history or tool results." },
  { text: "If asked about a server not mentioned in prior turns, respond: 'I don\'t have data for that server. Which server ID should I look up?'" },
  { text: "Never invent metric values, timestamps, or configuration details." },
];

Llama and Mistral: use imperative formatting

Llama 3 and Mistral models on Bedrock accept system prompts via the same SystemContentBlock structure, but they are more sensitive to instruction formatting than Claude models. Use direct, imperative language. Avoid nested bullets, XML-style tags, or JSON within the system prompt text — these models process the prompt as plain text and do not benefit from structured markup in the same way Claude does:

// Works well for Llama 3 and Mistral — imperative, plain prose
const llamaSystemPrompt: SystemContentBlock[] = [
  { text: "You are a monitoring assistant. Answer questions about MCP server uptime." },
  { text: "Always respond in plain text. Keep answers under 100 words." },
  { text: "If you do not have the information needed, say so directly." },
];

Multi-turn message array structure

The messages field of ConverseCommandInput is typed as Message[], where each Message has a role ("user" or "assistant") and a content: ContentBlock[]. The ContentBlock union supports text, image, document, tool use, and tool result blocks. Three structural rules are enforced by the API:

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

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

// Minimal valid two-turn conversation history
const messages: Message[] = [
  {
    role: "user",
    content: [{ text: "What is the uptime of server prod-01?" }],
  },
  {
    role: "assistant",
    content: [{ text: "I'll check the status of server prod-01 for you." }],
  },
  {
    role: "user",
    content: [{ text: "Can you also check prod-02?" }],
  },
];

const system: SystemContentBlock[] = [
  { text: "You are an uptime monitoring assistant for AliveMCP." },
];

const response = await client.send(new ConverseCommand({
  modelId: "anthropic.claude-3-5-sonnet-20241022-v2:0",
  system,
  messages,
  inferenceConfig: { maxTokens: 512, temperature: 0.0 },
}));

Conversation history with tool-use turns

When a prior assistant turn called tools, the conversation history must preserve the full tool call/result exchange. If you drop an assistant turn that contains ToolUseBlock entries while keeping the subsequent user turn with ToolResultBlock entries — or vice versa — the API throws ValidationException: messages must alternate between user and assistant roles. The ToolUseBlock/ToolResultBlock pair must be treated as an atomic unit when managing conversation history:

// Conversation history that includes a tool-use exchange
const messagesWithToolUse: Message[] = [
  // Turn 1: user asks
  {
    role: "user",
    content: [{ text: "What is the latency of prod-01?" }],
  },
  // Turn 2: assistant calls a tool — ToolUseBlock required
  {
    role: "assistant",
    content: [
      {
        toolUse: {
          toolUseId: "tool-call-001",
          name: "get_server_status",
          input: { serverId: "prod-01" },
        },
      },
    ],
  },
  // Turn 3: user provides tool result — ToolResultBlock required
  // This turn MUST follow the assistant tool-use turn immediately
  {
    role: "user",
    content: [
      {
        toolResult: {
          toolUseId: "tool-call-001",  // must match the toolUseId above
          content: [{ text: JSON.stringify({ serverId: "prod-01", p99LatencyMs: 42, status: "up" }) }],
        },
      },
    ],
  },
  // Turn 4: assistant synthesizes the result
  {
    role: "assistant",
    content: [{ text: "Server prod-01 is up with p99 latency of 42ms." }],
  },
  // Turn 5: user follow-up
  {
    role: "user",
    content: [{ text: "Is that latency within normal range?" }],
  },
];

// When the assistant calls multiple tools in a single turn,
// ALL tool results must be in a SINGLE subsequent user turn —
// not spread across multiple user messages.
const multiToolAssistantTurn: Message = {
  role: "assistant",
  content: [
    {
      toolUse: {
        toolUseId: "tool-call-002",
        name: "get_server_status",
        input: { serverId: "prod-01" },
      },
    },
    {
      toolUse: {
        toolUseId: "tool-call-003",
        name: "get_server_status",
        input: { serverId: "prod-02" },
      },
    },
  ],
};

// CORRECT: both results in one user turn
const correctResultsTurn: Message = {
  role: "user",
  content: [
    {
      toolResult: {
        toolUseId: "tool-call-002",
        content: [{ text: JSON.stringify({ serverId: "prod-01", status: "up" }) }],
      },
    },
    {
      toolResult: {
        toolUseId: "tool-call-003",
        content: [{ text: JSON.stringify({ serverId: "prod-02", status: "degraded" }) }],
      },
    },
  ],
};

// WRONG: splitting results into two user turns causes ValidationException
// because it creates two consecutive user turns

Context window limits per model

The Bedrock Converse API does not enforce context limits at the input validation stage — the model itself throws a ModelTimeoutException or truncates silently when the input token count exceeds the limit. Know the limits before you hit them. The total input token budget is consumed by the system prompt, all messages in the history, and all tool schema definitions sent with the request.

Model Model ID Context Window
Claude 3.5 Sonnet v2 anthropic.claude-3-5-sonnet-20241022-v2:0 200,000 tokens
Claude 3.5 Haiku anthropic.claude-3-5-haiku-20241022-v1:0 200,000 tokens
Claude 4 Sonnet anthropic.claude-sonnet-4-5 200,000 tokens
Amazon Nova Micro amazon.nova-micro-v1:0 128,000 tokens
Amazon Nova Lite amazon.nova-lite-v1:0 300,000 tokens
Amazon Nova Pro amazon.nova-pro-v1:0 300,000 tokens
Meta Llama 3.1 70B meta.llama3-1-70b-instruct-v1:0 128,000 tokens
Mistral Large mistral.mistral-large-2402-v1:0 32,000 tokens
Amazon Titan Premier amazon.titan-text-premier-v1:0 32,000 tokens

Mistral Large and Amazon Titan Premier have the most constrained windows at 32k tokens. With a 500-token system prompt, 10 tool schemas averaging 300 tokens each (3,000 tokens total), and an 80% utilization target, you have roughly 22,100 tokens of message history budget — approximately 16–20 exchanges of moderate length. For Claude and Nova models the window is large enough that most MCP conversations fit without trimming, but long tool result payloads (embedding full API responses) can still fill a 128k–200k window in dozens of turns.

Token estimation without a counting endpoint

The Bedrock Converse API does not expose a dedicated count-tokens endpoint the way some other APIs do. The response's usage field tells you the actual input token count after the fact, but you need an estimate before the request to decide whether to trim history. Two approaches:

Character-based estimation

For English text, 1 token is approximately 4 characters. This estimate degrades for code, JSON, and non-English text (code is denser; non-Latin scripts may use more tokens per character), but it is fast and sufficient for a sliding window guard:

/**
 * Estimate token count for Bedrock Converse inputs.
 * Uses ~4 chars/token heuristic for English text.
 * JSON and code may be ~3 chars/token; non-Latin scripts may be ~2 chars/token.
 */
function estimateTokens(text: string): number {
  return Math.ceil(text.length / 4);
}

function estimateSystemTokens(system: SystemContentBlock[]): number {
  return system.reduce((sum, block) => {
    if ("text" in block) return sum + estimateTokens(block.text ?? "");
    return sum;
  }, 0);
}

function estimateMessageTokens(messages: Message[]): number {
  return messages.reduce((sum, msg) => {
    for (const block of msg.content ?? []) {
      if ("text" in block) sum += estimateTokens(block.text ?? "");
      if ("toolUse" in block && block.toolUse) {
        sum += estimateTokens(block.toolUse.name ?? "");
        sum += estimateTokens(JSON.stringify(block.toolUse.input ?? {}));
      }
      if ("toolResult" in block && block.toolResult) {
        for (const c of block.toolResult.content ?? []) {
          if ("text" in c) sum += estimateTokens(c.text ?? "");
        }
      }
    }
    return sum;
  }, 0);
}

/**
 * Estimate tokens consumed by tool schemas passed in the tools array.
 * A tool with a medium-complexity inputSchema can run 200–500 tokens.
 * Measure once at startup and cache the result.
 */
function estimateToolSchemaTokens(tools: Tool[]): number {
  return tools.reduce((sum, tool) => {
    return sum +
      estimateTokens(tool.toolSpec?.name ?? "") +
      estimateTokens(tool.toolSpec?.description ?? "") +
      estimateTokens(JSON.stringify(tool.toolSpec?.inputSchema?.json ?? {}));
  }, 0);
}

// Measure your static tool schemas once at startup
import type { Tool } from "@aws-sdk/client-bedrock-runtime";

const MY_TOOLS: Tool[] = [/* your tool definitions */];
const TOOL_SCHEMA_TOKEN_ESTIMATE = estimateToolSchemaTokens(MY_TOOLS);
console.log(`Tool schema token overhead: ~${TOOL_SCHEMA_TOKEN_ESTIMATE} tokens`);

Using usage metrics from prior responses

After each successful Converse call, the response includes usage.inputTokens and usage.outputTokens. You can use these as calibration data to adjust your character-per-token ratio for the specific model and content type in your application:

async function converseAndTrackTokens(
  modelId: string,
  system: SystemContentBlock[],
  messages: Message[],
  tools: Tool[]
): Promise<{ responseText: string; inputTokens: number; outputTokens: number }> {
  const response = await client.send(new ConverseCommand({
    modelId,
    system,
    messages,
    toolConfig: tools.length ? { tools } : undefined,
    inferenceConfig: { maxTokens: 1024 },
  }));

  const inputTokens = response.usage?.inputTokens ?? 0;
  const outputTokens = response.usage?.outputTokens ?? 0;

  const responseText = response.output?.message?.content
    ?.filter((b): b is { text: string } => "text" in b)
    .map((b) => b.text)
    .join("") ?? "";

  return { responseText, inputTokens, outputTokens };
}

Sliding window context management

When conversation history grows long enough to approach the context limit, you must trim old turns from the front of the message array. The invariants during trimming:

interface SlidingWindowConfig {
  modelContextLimit: number;
  systemTokens: number;        // pre-computed: measure system prompt once
  toolSchemaTokens: number;    // pre-computed: measure tool schemas once
  utilizationTarget: number;   // 0.8 = keep total under 80% of context limit
}

/**
 * Trim the message array to fit within the context window.
 * Drops oldest complete turn-pairs from the front while the estimated
 * token count exceeds the utilization target.
 *
 * Returns a new array; never mutates the input.
 */
function applySlididingWindow(
  messages: Message[],
  config: SlidingWindowConfig
): Message[] {
  const tokenBudget = Math.floor(config.modelContextLimit * config.utilizationTarget);
  const overhead = config.systemTokens + config.toolSchemaTokens;
  const messageBudget = tokenBudget - overhead;

  let trimmed = [...messages];

  while (trimmed.length > 1 && estimateMessageTokens(trimmed) > messageBudget) {
    // Identify the size of the first logical turn to drop.
    // A "logical turn" is either:
    //   (a) one user+assistant text pair (2 entries), or
    //   (b) one user text message, one assistant ToolUseBlock message,
    //       one user ToolResultBlock message, one assistant text message (4 entries)
    const firstRole = trimmed[0]?.role;
    if (firstRole !== "user") break; // safety guard — should not happen

    const isToolUseTurn =
      trimmed[1]?.role === "assistant" &&
      trimmed[1]?.content?.some((b) => "toolUse" in b) &&
      trimmed[2]?.role === "user" &&
      trimmed[2]?.content?.some((b) => "toolResult" in b);

    if (isToolUseTurn && trimmed.length >= 4) {
      // Drop: user, assistant(toolUse), user(toolResult), assistant(text)
      trimmed = trimmed.slice(4);
    } else if (trimmed.length >= 2) {
      // Drop: user, assistant(text)
      trimmed = trimmed.slice(2);
    } else {
      break; // only the current user turn remains — cannot trim further
    }
  }

  return trimmed;
}

// Example usage in an MCP tool handler
server.tool(
  "continue_conversation",
  {
    model_id: z.string().default("anthropic.claude-3-5-sonnet-20241022-v2:0"),
    history: z.array(z.object({
      role: z.enum(["user", "assistant"]),
      text: z.string(),
    })).describe("Prior conversation turns from the client"),
    message: z.string().describe("Current user message"),
  },
  async ({ model_id, history, message }) => {
    const system: SystemContentBlock[] = [
      { text: "You are a helpful assistant for AliveMCP users." },
    ];

    // Rebuild Message[] from client-provided history
    const priorMessages: Message[] = history.map((turn) => ({
      role: turn.role,
      content: [{ text: turn.text }],
    }));

    // Append the current user message
    const allMessages: Message[] = [
      ...priorMessages,
      { role: "user", content: [{ text: message }] },
    ];

    // Apply sliding window before sending
    const contextConfig: SlidingWindowConfig = {
      modelContextLimit: 200_000,
      systemTokens: estimateSystemTokens(system),
      toolSchemaTokens: TOOL_SCHEMA_TOKEN_ESTIMATE,
      utilizationTarget: 0.8,
    };
    const trimmedMessages = applySlididingWindow(allMessages, contextConfig);

    const response = await client.send(new ConverseCommand({
      modelId: model_id,
      system,
      messages: trimmedMessages,
      inferenceConfig: { maxTokens: 1024 },
    }));

    const responseText = response.output?.message?.content
      ?.filter((b): b is { text: string } => "text" in b)
      .map((b) => b.text)
      .join("") ?? "";

    return { content: [{ type: "text", text: responseText }] };
  }
);

State management in stateless MCP servers

The majority of MCP servers are stateless processes: they receive a tool call, perform work, and return a result — with no persistent in-memory state between calls. This is intentional. The MCP host (the LLM client, the calling agent) maintains the conversation state and passes it into each tool call. The pattern for Bedrock Converse in a stateless MCP server:

  1. The client serializes the conversation history into the tool call arguments.
  2. The MCP tool handler deserializes the history, rebuilds Message[], appends the new user message, and applies the sliding window.
  3. The handler calls Converse, gets the assistant response, and returns it.
  4. The client appends the assistant response to its own history store for the next turn.

The server should NOT maintain an in-memory Map<sessionId, Message[]> unless it is explicitly designed as a stateful session server and handles process restarts, horizontal scaling, and TTL-based eviction. In-memory state silently breaks when the process restarts or scales to multiple instances. If you need server-side session state, use an external store (DynamoDB, Redis) keyed by session ID, with an explicit TTL:

// AVOID in a typical MCP server — breaks on restart and multi-instance deployments
const inMemoryHistory = new Map<string, Message[]>();

// PREFERRED for stateless MCP servers — history comes from the client
server.tool(
  "bedrock_chat",
  {
    // Client serializes only text turns for simplicity;
    // for tool-use history, use a richer serialization format
    conversation_history: z.array(z.object({
      role: z.enum(["user", "assistant"]),
      content: z.string(),
    })).describe("All prior turns in the conversation, oldest first"),
    new_message: z.string().describe("The new user message to send"),
  },
  async ({ conversation_history, new_message }) => {
    const system: SystemContentBlock[] = [
      { text: "You are an AliveMCP monitoring assistant. Answer questions about MCP server uptime and latency." },
    ];

    const messages: Message[] = [
      ...conversation_history.map((t) => ({
        role: t.role as "user" | "assistant",
        content: [{ text: t.content }],
      })),
      { role: "user" as const, content: [{ text: new_message }] },
    ];

    const trimmed = applySlididingWindow(messages, {
      modelContextLimit: 200_000,
      systemTokens: estimateSystemTokens(system),
      toolSchemaTokens: 0, // no tools in this handler
      utilizationTarget: 0.8,
    });

    const response = await client.send(new ConverseCommand({
      modelId: "anthropic.claude-3-5-sonnet-20241022-v2:0",
      system,
      messages: trimmed,
      inferenceConfig: { maxTokens: 1024 },
    }));

    const assistantText = response.output?.message?.content
      ?.filter((b): b is { text: string } => "text" in b)
      .map((b) => b.text)
      .join("") ?? "";

    // Return both the response and the full history so the client
    // can store it for the next turn
    return {
      content: [{
        type: "text",
        text: JSON.stringify({
          response: assistantText,
          // Client should append { role: "assistant", content: assistantText }
          // to its local history before the next call
        }),
      }],
    };
  }
);

Prompt caching for static system prompts

If your system prompt is the same string on every request — a common pattern when the MCP tool always uses the same role definition and format instructions — Bedrock prompt caching can significantly reduce input token billing. The cache TTL for Bedrock prompt caching is 5 minutes. Requests that hit the cache are charged at a discounted input token rate rather than the full rate.

To enable caching for a system prompt, add the cachePoint marker after the last system block you want cached. The cache point tells Bedrock where to split the prefix (cached) from the suffix (dynamic per-request):

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

// Static prefix — same on every request, eligible for caching
const staticSystemPrefix: SystemContentBlock[] = [
  { text: "You are an uptime monitoring assistant for AliveMCP." },
  { text: "Users ask about their MCP server status, latency percentiles, and alert history." },
  { text: "Respond in Markdown. Never fabricate server names, metric values, or timestamps." },
  { text: "If you lack the data needed to answer, say so and suggest which tool to call." },
  // Cache point: everything above this is the cached prefix
  // Cast required because cachePoint is an SDK extension field
  { cachePoint: { type: "default" } } as unknown as SystemContentBlock,
];

// Dynamic suffix — can vary per request (e.g., injecting user plan tier)
function buildDynamicSystemSuffix(userPlan: string): SystemContentBlock[] {
  return [
    { text: `The user is on the ${userPlan} plan.` },
  ];
}

// Combined system array for each request
function buildSystem(userPlan: string): SystemContentBlock[] {
  return [
    ...staticSystemPrefix,
    ...buildDynamicSystemSuffix(userPlan),
  ];
}

See the full Bedrock prompt caching guide for cache point placement rules, the minimum cacheable prefix length (1,024 tokens for most models), and how to verify cache hits from the response's usage.cacheReadInputTokenCount field.

Handling guardrail_intervened stop reason

When Bedrock Guardrails are configured on the Converse request and a turn is blocked, the response will have stopReason: "guardrail_intervened" and an empty or redacted content array. This is not an exception — the API returns HTTP 200 with the blocked response. Your handler must check stopReason explicitly and return a user-friendly message rather than attempting to parse an empty content array:

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

const guardrailConfig: GuardrailConfiguration = {
  guardrailIdentifier: process.env.BEDROCK_GUARDRAIL_ID!,
  guardrailVersion: process.env.BEDROCK_GUARDRAIL_VERSION ?? "DRAFT",
  trace: "enabled",  // captures which policy triggered the block
};

async function converseWithGuardrails(
  system: SystemContentBlock[],
  messages: Message[]
): Promise<{ text: string; blocked: boolean; traceInfo?: string }> {
  const response: ConverseCommandOutput = await client.send(new ConverseCommand({
    modelId: "anthropic.claude-3-5-sonnet-20241022-v2:0",
    system,
    messages,
    guardrailConfig,
    inferenceConfig: { maxTokens: 1024 },
  }));

  if (response.stopReason === "guardrail_intervened") {
    // Extract trace info to understand which policy fired — useful for debugging
    // The trace is in response.trace.guardrail when trace is enabled
    const traceInfo = response.trace?.guardrail
      ? JSON.stringify(response.trace.guardrail, null, 2)
      : undefined;

    // Log for observability — do not throw, do not surface raw trace to users
    console.warn("Guardrail intervened:", traceInfo ?? "(no trace)");

    return {
      text: "I'm not able to respond to that request. Please rephrase your question or contact support if you believe this is an error.",
      blocked: true,
      traceInfo,
    };
  }

  const text = response.output?.message?.content
    ?.filter((b): b is { text: string } => "text" in b)
    .map((b) => b.text)
    .join("") ?? "";

  return { text, blocked: false };
}

server.tool(
  "guarded_chat",
  {
    history: z.array(z.object({
      role: z.enum(["user", "assistant"]),
      content: z.string(),
    })),
    message: z.string(),
  },
  async ({ history, message }) => {
    const system: SystemContentBlock[] = [
      { text: "You are an AliveMCP assistant. Help users understand their server monitoring data." },
    ];

    const messages: Message[] = [
      ...history.map((t) => ({
        role: t.role as "user" | "assistant",
        content: [{ text: t.content }],
      })),
      { role: "user" as const, content: [{ text: message }] },
    ];

    const { text, blocked } = await converseWithGuardrails(system, messages);

    return {
      content: [{
        type: "text",
        text: JSON.stringify({ response: text, blocked }),
      }],
    };
  }
);

See Bedrock Guardrails deep dive for trace field structure, the difference between INPUT and OUTPUT interventions, and how to configure guardrail policies that do not block legitimate monitoring queries.

Common gotchas

Monitor your Bedrock Converse MCP tools with AliveMCP

AliveMCP monitors MCP server endpoints for uptime, latency spikes, and error rates. When a Converse tool handler starts throwing ValidationExceptions from malformed conversation history or hitting context window limits, AliveMCP alerts you before it impacts your users.

Start free monitoring