Guide · Amazon Bedrock · Safety

Amazon Bedrock Guardrails Topic Policy for MCP Servers

Bedrock Guardrails topic policy lets you semantically block entire categories of conversation — not just specific keywords — but writing effective topic definitions requires understanding how Bedrock uses semantic similarity rather than pattern matching under the hood. The most common failure mode is writing topic definitions that are too broad: a "financial advice" topic defined carelessly will block questions like "how much does this plan cost?" because Bedrock evaluates the entire message context, not individual sentences. This guide covers the full topicPolicyConfig schema (name constraints, definition limits, the five-example cap, and why type: "DENY" is the only valid value), how to write definitions and examples that maximize precision, how to parse response.trace.guardrail.inputAssessment and outputAssessment to find exactly which topic fired, how to build a topic analytics logger from trace logs, and how to safely evolve topic definitions using UpdateGuardrailCommand without disrupting production. For the broader guardrail integration pattern — attaching guardrailConfig to ConverseCommand, handling guardrail_intervened stop reasons, and version management — see the Bedrock Guardrails overview and the versioning guide.

TL;DR

Add a topicPolicyConfig.topicsConfig array to CreateGuardrailCommand with entries of shape { name, definition, examples, type: "DENY" } — up to 30 topics, definitions up to 200 chars, and up to 5 example messages per topic. Enable trace: "ENABLED" on ConverseCommand guardrailConfig and read response.trace?.guardrail?.inputAssessment?.["0"]?.topicPolicy?.topics (or outputAssessments?.["0"]) to find the blocked topic name when stopReason === "guardrail_intervened". Topics have no confidence score in the trace — a topic is either BLOCKED or absent — and a single message can trigger multiple topics simultaneously.

Topic policy anatomy: the topicPolicyConfig schema

A Bedrock Guardrails topic policy is configured via the topicPolicyConfig key in both CreateGuardrailCommand and UpdateGuardrailCommand. The only child key is topicsConfig, which accepts an array of topic objects. Each object has four fields: name, definition, examples, and type.

The name field identifies the topic in trace output and in your analytics. It must match the regex ^[0-9a-zA-Z-_ !?.]+$ — alphanumerics, hyphens, underscores, spaces, exclamation marks, question marks, and periods only — and may not exceed 100 characters. Names are used as identifiers in the trace, so choose them to be both human-readable in a dashboard and stable over time: renaming a topic in a later guardrail version will break any analytics query that filters by topic name.

The definition field tells Bedrock what the topic covers. It is capped at 200 characters and must state the scope of the topic in plain prose. This field is the primary signal Bedrock uses during semantic matching — a vague definition produces false positives, while an overly narrow definition causes false negatives. The goal is to write exactly what the topic means, not what should happen when it fires.

The examples array holds up to 5 strings, each up to 200 characters. These are sample messages that would trigger the topic — not safe examples of what users should say. Including borderline cases (messages that might plausibly be interpreted as being inside or outside the topic) helps Bedrock calibrate the semantic boundary more accurately than including five obvious examples that all look identical. The examples array is optional but strongly recommended for any topic where the boundary is not crystal clear from the definition alone.

The type field currently accepts only one value: "DENY". There is no "ALLOW" type, no "WARN" type, and no way to use the topic policy for anything other than blocking. If you need a topic to be monitored but not blocked, omit it from the topic policy and implement monitoring via trace parsing in your application layer instead.

Up to 30 topics may be configured per guardrail. Topics are evaluated independently — a message can match multiple topics simultaneously, and the trace will list all matching topics in a single topicPolicy.topics array. All matched topics carry action: "BLOCKED" and type: "DENY".

// Topic policy config shape (TypeScript interfaces for reference)
interface TopicConfig {
  name: string;        // matches /^[0-9a-zA-Z-_ !?.]+$/, max 100 chars
  definition: string;  // max 200 chars; states what the topic covers
  examples?: string[]; // max 5 entries; each max 200 chars; messages that WOULD trigger
  type: "DENY";        // only valid value
}

interface TopicPolicyConfig {
  topicsConfig: TopicConfig[]; // max 30 entries
}

// Trace shape when trace is enabled
interface TopicPolicyAssessment {
  topics?: Array<{
    name: string;
    type: "DENY";
    action: "BLOCKED";
  }>;
}

Notice that the trace does not include a confidence score. You cannot distinguish "barely triggered" from "clearly triggered" from the trace alone — the topic either appears in the array or it does not. This is an important design constraint: you cannot implement soft-blocking (allow the message but flag it for review if confidence is low) using the native topic policy mechanism. If you need graduated responses, you must implement that logic outside the guardrail layer, for example by calling the guardrail in a shadow mode on a sample of traffic and correlating with downstream outcomes.

Creating a guardrail with topic policy using CreateGuardrailCommand

The following example creates a guardrail with three denied topics: competitor recommendations, legal advice, and financial advice. Each topic definition is carefully scoped to avoid the false positive patterns described in the gotchas section below. Notice that the competitor topic's definition explicitly mentions product alternatives and pricing comparisons — without that scope, it might also catch internal product comparison questions. The legal topic's examples include borderline cases like "is this compliant?" and "can I be sued for this?" rather than obvious ones like "write me a contract."

import {
  BedrockClient,
  CreateGuardrailCommand,
  type CreateGuardrailCommandInput,
} from "@aws-sdk/client-bedrock";

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

async function createTopicPolicyGuardrail(): Promise<{ guardrailId: string; version: string }> {
  const input: CreateGuardrailCommandInput = {
    name: "mcp-server-topic-guardrail",
    description: "Blocks competitor recommendations, legal advice, and financial advice in MCP tool responses",
    blockedInputMessaging:
      "I can't discuss that topic. Please ask about supported product features or contact support.",
    blockedOutputsMessaging:
      "I can't provide that type of information. Please contact a qualified professional.",
    topicPolicyConfig: {
      topicsConfig: [
        {
          name: "competitor-recommendations",
          definition:
            "Requests to recommend, compare, or evaluate competing products or services as alternatives to ours, including pricing comparisons with named competitors.",
          examples: [
            "Which of your competitors has the best uptime monitoring?",
            "Should I use Datadog or your product for this use case?",
            "How does your pricing compare to Pingdom and Better Uptime?",
            "What would you switch to if you weren't using AliveMCP?",
            "Is there a cheaper alternative that does the same thing?",
          ],
          type: "DENY",
        },
        {
          name: "legal-advice",
          definition:
            "Requests for legal opinions, interpretations of laws or regulations, advice on legal liability, or guidance that would require a licensed attorney to provide.",
          examples: [
            "Am I legally required to have an SLA for my API customers?",
            "Can my users sue me if my MCP server goes down during their workflow?",
            "Is this monitoring configuration GDPR compliant?",
            "What does my ToS need to say about uptime guarantees?",
            "Do I need a lawyer to review my incident response policy?",
          ],
          type: "DENY",
        },
        {
          name: "financial-advice",
          definition:
            "Requests for personalized investment, tax, or financial planning recommendations, including advice on specific stocks, funds, or financial instruments.",
          examples: [
            "Should I invest in AWS or Azure infrastructure for better ROI?",
            "What is the best way to structure my SaaS pricing to minimize tax?",
            "Is it worth buying Reserved Instances given my current usage patterns?",
            "Can you help me decide between bootstrapping and VC funding?",
            "What equity percentage should I give early employees?",
          ],
          type: "DENY",
        },
      ],
    },
  };

  const response = await bedrockMgmt.send(new CreateGuardrailCommand(input));

  if (!response.guardrailId) {
    throw new Error("CreateGuardrailCommand did not return a guardrailId");
  }

  console.log("Created guardrail:", {
    guardrailId: response.guardrailId,
    guardrailArn: response.guardrailArn,
    version: response.version, // "DRAFT" at creation
    createdAt: response.createdAt,
  });

  return { guardrailId: response.guardrailId, version: response.version ?? "DRAFT" };
}

At creation time, the guardrail is always in DRAFT state. The returned version will be "DRAFT". Before attaching this guardrail to a production MCP server, you should call CreateGuardrailVersionCommand to publish an immutable numeric version — otherwise any subsequent edits to the DRAFT will immediately affect production traffic. The versioning guide covers this in detail.

It is worth noting that blockedInputMessaging and blockedOutputsMessaging are the strings Bedrock injects into the response when a topic fires — but in an MCP server you will typically want to override these with more contextual messages in your tool handler after reading the trace. The strings configured here act as a fallback and appear in the raw Bedrock response, but you can substitute them with custom messages built from the trace data, as shown in the topic-aware error handler section below.

Writing effective topic definitions: semantic matching principles

The most important thing to understand about Bedrock topic policy is that it uses semantic similarity, not keyword matching. Bedrock does not scan the message for the words "competitor" or "legal" — it embeds the message and the topic definition into a shared vector space and measures the distance. This has profound implications for how you write definitions and examples.

First, the definition should state what the topic is, not what should happen. "Block requests for competitor recommendations" is a poor definition because it describes an action. "Requests to recommend or evaluate competing products as alternatives" is better because it describes the topic itself in terms a semantic model can reason about.

Second, the definition establishes the center of the semantic cluster. The examples push or pull the boundary at the edges. If your definition is centered too broadly, every example you add will be near the center, and messages on the true edge will be misclassified. If you have a vague definition and want to tighten the boundary, narrowing the definition is more effective than adding edge-case examples.

Third, avoid synonyms of words you do not want to block. The "financial advice" example above is the classic trap. If your definition says "advice about money, costs, or financial decisions", you have embedded the word "costs" into the topic center, and now questions like "how much does the enterprise plan cost?" — which you clearly want to allow — may land close enough to the center to trigger. The fix is to scope the definition to the specific harm: "personalized investment, tax, or financial planning recommendations" is far enough from product pricing questions to be safe.

Fourth, write examples that are borderline, not obvious. If all five examples are unmistakably within the topic ("give me stock tips", "what should I invest in", "how do I avoid capital gains tax"), Bedrock will draw a tight cluster around obvious cases and may miss the edge cases that actually cause problems in production. Include at least two examples that are plausibly ambiguous — messages a reasonable person might think were acceptable but that you have decided fall inside the topic boundary.

// Example of a POOR topic definition (too broad, causes false positives)
const poorFinancialTopic = {
  name: "financial-advice",
  definition: "Questions about money, costs, pricing, or financial decisions.",
  examples: [
    "Should I invest in stocks?",
    "What is a good mutual fund?",
    "Help me with my taxes.",
    "Is Bitcoin a good investment?",
    "How do I make more money?",
  ],
  type: "DENY" as const,
};
// This will also block: "how much does the pro plan cost?" and "is there a free tier?"

// Example of a BETTER topic definition (scoped, reduced false positives)
const betterFinancialTopic = {
  name: "financial-advice",
  definition:
    "Requests for personalized investment, tax, or financial planning recommendations, including advice on specific stocks, funds, or financial instruments.",
  examples: [
    "Which stocks should I buy given my retirement timeline?",          // obvious
    "Is it better to max my 401k or invest in index funds this year?", // obvious
    "Should I use a Roth IRA or a traditional IRA for my situation?",  // obvious
    "Is buying Reserved Instances a smart financial decision for my business?", // borderline
    "What equity percentage gives early employees fair compensation?",           // borderline
  ],
  type: "DENY" as const,
};
// Now "how much does the pro plan cost?" is far enough from the definition center to pass

Fifth, topics are evaluated against the entire message context, not individual sentences. If a user sends a 500-word message containing one sentence that asks about competitors, the entire message is evaluated. The surrounding context matters — a message like "I am researching MCP monitoring tools for a blog post, could you tell me which competitors you are aware of?" may or may not trigger the competitor topic depending on how the definition is worded, because the framing ("for a blog post", "research") shifts the semantic context. Test representative real-world messages, not toy examples, when calibrating definitions.

Sixth, topics are bidirectional by default: the same topic policy is applied to both input messages (what the user sends) and output messages (what the model generates). If you want a topic to be blocked only on input (to prevent users from steering the conversation) but allowed on output (so the model can proactively mention something), you need to handle that in your application layer rather than in the topic policy, since there is no input-only flag per topic in the current API.

Integrating topic policy with ConverseCommand and reading trace data

To know which topic blocked a message, you must enable tracing on the guardrail. Without trace: "ENABLED", Bedrock still blocks the message but returns no information about why. With tracing enabled, the response includes a trace property containing detailed assessment data for each message in the conversation.

The trace structure uses numeric string keys ("0", "1", etc.) to index into the conversation. For input assessment, the path is response.trace?.guardrail?.inputAssessment?.["0"]?.topicPolicy?.topics. For output assessment, the path is response.trace?.guardrail?.outputAssessments?.["0"]?.topicPolicy?.topics. Both return the same shape: an array of objects with name, type, and action fields.

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

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

interface BlockedTopicInfo {
  source: "input" | "output";
  topicName: string;
  type: "DENY";
  action: "BLOCKED";
}

async function converseWithTopicGuardrail(
  messages: Message[],
  modelId: string,
  guardrailId: string,
  guardrailVersion: string
): Promise<{ text: string | null; blockedTopics: BlockedTopicInfo[] }> {
  const input: ConverseCommandInput = {
    modelId,
    messages,
    guardrailConfig: {
      guardrailIdentifier: guardrailId,
      guardrailVersion,
      trace: "ENABLED", // required to get topic names from trace
    },
  };

  const response: ConverseCommandOutput = await runtime.send(new ConverseCommand(input));

  const blockedTopics: BlockedTopicInfo[] = [];

  // Check input assessment — fired when user message triggers a topic
  const inputTopics =
    response.trace?.guardrail?.inputAssessment?.["0"]?.topicPolicy?.topics ?? [];
  for (const topic of inputTopics) {
    if (topic.action === "BLOCKED" && topic.name) {
      blockedTopics.push({
        source: "input",
        topicName: topic.name,
        type: "DENY",
        action: "BLOCKED",
      });
    }
  }

  // Check output assessments — fired when model response triggers a topic
  const outputTopics =
    response.trace?.guardrail?.outputAssessments?.["0"]?.topicPolicy?.topics ?? [];
  for (const topic of outputTopics) {
    if (topic.action === "BLOCKED" && topic.name) {
      blockedTopics.push({
        source: "output",
        topicName: topic.name,
        type: "DENY",
        action: "BLOCKED",
      });
    }
  }

  if (response.stopReason === "guardrail_intervened") {
    // blockedTopics is populated; model output (if any) is not usable
    return { text: null, blockedTopics };
  }

  // Extract the assistant's text response
  const textContent = response.output?.message?.content?.find(
    (c) => c.text !== undefined
  );

  return { text: textContent?.text ?? null, blockedTopics };
}

When stopReason === "guardrail_intervened", the response.output?.message?.content array may be empty or contain only the blocked messaging string — you cannot rely on it to contain a usable model response. Always check stopReason before trying to extract text from the output. The blockedTopics array will tell you whether the block originated from the user's input or the model's generated output, which matters for logging: an output block may indicate that your system prompt needs adjustment to steer the model away from the topic, while an input block indicates a user attempting a restricted request.

It is also worth noting that response.trace is undefined (not an empty object) when trace is not set to "ENABLED" in the guardrailConfig. Guard every access with optional chaining, as shown above, to avoid runtime errors when switching between traced and un-traced environments.

MCP tool handler with topic-aware error responses

When a topic fires, the blocked messaging string configured in the guardrail is generic. In an MCP server, you typically want to tell the client which topic was triggered — both for user experience and for downstream agent routing. An agent receiving a vague "I can't discuss that" message has no way to know whether it should retry with a different phrasing, escalate to a human, or abandon the task. A message that includes the topic name and a suggested remediation gives the agent actionable signal.

The following MCP tool handler wraps the converseWithTopicGuardrail function above and builds a structured error response when topics fire. It maps topic names to human-readable explanations and suggests where the user should go instead — a pattern that works well for customer-facing MCP servers where the guardrail is protecting against liability rather than security threats.

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

const TOPIC_REMEDIATION: Record<string, string> = {
  "competitor-recommendations":
    "I'm only able to discuss our own product features. For independent comparisons, check G2 or Capterra.",
  "legal-advice":
    "Legal questions require a licensed attorney. I can describe how our product works, but not advise on compliance obligations.",
  "financial-advice":
    "For investment or tax advice, please consult a qualified financial advisor. I can explain our pricing but not recommend financial decisions.",
};

function buildTopicBlockedMessage(blockedTopics: BlockedTopicInfo[]): string {
  if (blockedTopics.length === 0) {
    return "This request was blocked by content policy.";
  }

  const explanations = blockedTopics.map((t) => {
    const remediation = TOPIC_REMEDIATION[t.topicName];
    return remediation
      ? `Topic blocked (${t.topicName}): ${remediation}`
      : `Topic blocked (${t.topicName}): This subject falls outside what I'm able to discuss.`;
  });

  return explanations.join(" | ");
}

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

server.tool(
  "ask-product-assistant",
  "Ask a question about the product",
  { question: z.string().min(1).max(2000) },
  async ({ question }) => {
    const messages = [{ role: "user" as const, content: [{ text: question }] }];

    let result: Awaited<ReturnType<typeof converseWithTopicGuardrail>>;
    try {
      result = await converseWithTopicGuardrail(
        messages,
        process.env.BEDROCK_MODEL_ID ?? "amazon.nova-pro-v1:0",
        process.env.GUARDRAIL_ID!,
        process.env.GUARDRAIL_VERSION ?? "1"
      );
    } catch (err) {
      // Surface Bedrock API errors as MCP errors, not unhandled rejections
      return {
        isError: true,
        content: [
          {
            type: "text" as const,
            text: `Model API error: ${err instanceof Error ? err.message : String(err)}`,
          },
        ],
      };
    }

    if (result.blockedTopics.length > 0) {
      const message = buildTopicBlockedMessage(result.blockedTopics);

      // Log for analytics before returning (see analytics section below)
      await logBlockedTopics(result.blockedTopics, {
        guardrailId: process.env.GUARDRAIL_ID!,
        modelId: process.env.BEDROCK_MODEL_ID ?? "amazon.nova-pro-v1:0",
        question,
      });

      return {
        isError: true,
        content: [{ type: "text" as const, text: message }],
      };
    }

    if (!result.text) {
      return {
        isError: true,
        content: [{ type: "text" as const, text: "No response generated." }],
      };
    }

    return {
      content: [{ type: "text" as const, text: result.text }],
    };
  }
);

Notice that the handler returns isError: true for blocked topics rather than throwing. MCP clients that follow the spec handle isError: true as a tool-level error (the tool ran but reported failure) rather than a transport-level error. This distinction matters for agent loops: a tool that throws causes the agent framework to treat the tool call as infrastructure failure, while a tool that returns isError: true gives the agent the error message text to reason about and potentially recover from. For topic blocks, you almost always want the latter — the agent should be able to understand the reason and decide whether to rephrase or give up.

The handler also calls a logBlockedTopics function before returning, which is defined in the analytics section below. Logging happens before the return so that every blocked request is recorded even if the caller immediately retries — this gives you an accurate count of how many raw topic violations are occurring, not just how many unique sessions hit a block.

Topic analytics logger: collecting blocked topics for dashboards

Because topics have no confidence score and are either blocked or not, the most useful analytics you can build are frequency-based: which topics are firing most often, what time-of-day patterns exist, which user sessions are repeatedly hitting the same topic, and whether topic fire rates are changing over time. A spike in a specific topic can indicate a new use case you have not anticipated, a competitor launching a campaign that is driving users to ask comparison questions, or a prompt injection attempt probing your guardrails.

The following logger emits structured JSON log entries for each blocked topic. Each entry includes the topic name, timestamp, guardrailId, modelId, and the input text that triggered the block (truncated to avoid logging sensitive user content at full length). The structured format is designed to be ingested directly by CloudWatch Logs Insights, Datadog, or any log aggregation system that supports JSON.

import { createWriteStream } from "node:fs";
import { appendFile } from "node:fs/promises";
import * as path from "node:path";

interface TopicBlockLogEntry {
  event: "topic_blocked";
  timestamp: string;         // ISO 8601
  topicName: string;
  topicSource: "input" | "output";
  guardrailId: string;
  modelId: string;
  questionPreview: string;   // first 120 chars of input, for debugging
  sessionId?: string;
}

interface LogBlockedTopicsOptions {
  guardrailId: string;
  modelId: string;
  question: string;
  sessionId?: string;
}

async function logBlockedTopics(
  blockedTopics: BlockedTopicInfo[],
  options: LogBlockedTopicsOptions
): Promise<void> {
  const { guardrailId, modelId, question, sessionId } = options;
  const timestamp = new Date().toISOString();
  const questionPreview = question.slice(0, 120);

  const entries: TopicBlockLogEntry[] = blockedTopics.map((topic) => ({
    event: "topic_blocked",
    timestamp,
    topicName: topic.topicName,
    topicSource: topic.source,
    guardrailId,
    modelId,
    questionPreview,
    ...(sessionId ? { sessionId } : {}),
  }));

  // Emit each entry as a single-line JSON object to stdout
  // CloudWatch Logs agent picks these up when running in an ECS/Lambda environment
  for (const entry of entries) {
    process.stdout.write(JSON.stringify(entry) + "\n");
  }
}

// In-memory aggregator for dashboard metrics (flush to CloudWatch Metrics or Datadog)
interface TopicMetrics {
  topicName: string;
  count: number;
  firstSeen: string;
  lastSeen: string;
}

class TopicAnalyticsAggregator {
  private metrics = new Map<string, TopicMetrics>();

  record(topicName: string): void {
    const now = new Date().toISOString();
    const existing = this.metrics.get(topicName);
    if (existing) {
      existing.count++;
      existing.lastSeen = now;
    } else {
      this.metrics.set(topicName, {
        topicName,
        count: 1,
        firstSeen: now,
        lastSeen: now,
      });
    }
  }

  snapshot(): TopicMetrics[] {
    return Array.from(this.metrics.values()).sort((a, b) => b.count - a.count);
  }

  reset(): void {
    this.metrics.clear();
  }
}

// Singleton aggregator for the process lifetime
export const topicAnalytics = new TopicAnalyticsAggregator();

// Flush metrics every 60 seconds (replace with your metrics SDK call)
setInterval(() => {
  const snapshot = topicAnalytics.snapshot();
  if (snapshot.length > 0) {
    process.stdout.write(
      JSON.stringify({ event: "topic_metrics_flush", metrics: snapshot, timestamp: new Date().toISOString() }) + "\n"
    );
    topicAnalytics.reset();
  }
}, 60_000).unref(); // .unref() prevents this timer from keeping the process alive

The in-memory aggregator and the structured log emission work together: the structured log gives you per-request detail for debugging individual blocked sessions, while the periodic flush gives you a time-bucketed count suitable for trending. If you are using CloudWatch Logs Insights, you can query the structured logs with a filter like filter event = "topic_blocked" | stats count(*) by topicName | sort count desc to get a ranked list of your most frequently triggered topics. This is the starting point for deciding whether a topic definition needs to be tightened (high false positive rate), relaxed (legitimate use cases being blocked), or split into two separate topics (one common case and one edge case that need different remediation messages).

Connecting your analytics pipeline to AliveMCP uptime monitoring gives you a cross-signal view: you can correlate spikes in topic blocks with MCP server availability events, latency regressions, or deployment windows to distinguish intentional guardrail tuning effects from unintended behavioral changes caused by infrastructure changes.

Updating topic definitions with UpdateGuardrailCommand

Topic definitions will need to evolve as you discover false positives and false negatives in production. The workflow is: edit the DRAFT version of the guardrail, test against representative messages, then create a new numeric version and promote it to production. UpdateGuardrailCommand always writes to DRAFT — you cannot directly update a numeric version. If your production traffic points to version "1", it is unaffected by any DRAFT changes until you explicitly create a new version and update your MCP server configuration.

import {
  BedrockClient,
  UpdateGuardrailCommand,
  CreateGuardrailVersionCommand,
  GetGuardrailCommand,
  type UpdateGuardrailCommandInput,
} from "@aws-sdk/client-bedrock";

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

async function addTopicToExistingGuardrail(
  guardrailId: string,
  newTopic: { name: string; definition: string; examples: string[]; type: "DENY" }
): Promise<string> {
  // 1. Fetch the current DRAFT configuration so we can extend it
  const getResponse = await bedrockMgmt.send(
    new GetGuardrailCommand({ guardrailIdentifier: guardrailId, guardrailVersion: "DRAFT" })
  );

  const existingTopics = getResponse.topicPolicy?.topics ?? [];

  // Guard against the 30-topic limit
  if (existingTopics.length >= 30) {
    throw new Error(
      `Cannot add topic '${newTopic.name}': guardrail already has the maximum 30 topics`
    );
  }

  // 2. Write the updated topic list back to DRAFT
  const updateInput: UpdateGuardrailCommandInput = {
    guardrailIdentifier: guardrailId,
    name: getResponse.name!,
    description: getResponse.description,
    blockedInputMessaging: getResponse.blockedInputMessaging!,
    blockedOutputsMessaging: getResponse.blockedOutputsMessaging!,
    // Carry over all other policy configs from the existing guardrail
    contentPolicyConfig: getResponse.contentPolicy
      ? {
          filtersConfig: getResponse.contentPolicy.filters?.map((f) => ({
            type: f.type!,
            inputStrength: f.inputStrength!,
            outputStrength: f.outputStrength!,
          })) ?? [],
        }
      : undefined,
    topicPolicyConfig: {
      topicsConfig: [
        // Map existing topics back to the input shape
        ...existingTopics.map((t) => ({
          name: t.name!,
          definition: t.definition!,
          examples: t.examples ?? [],
          type: "DENY" as const,
        })),
        // Append the new topic
        newTopic,
      ],
    },
  };

  await bedrockMgmt.send(new UpdateGuardrailCommand(updateInput));
  console.log(`Updated DRAFT guardrail ${guardrailId} with new topic '${newTopic.name}'`);

  // 3. Create a new immutable version from the updated DRAFT
  const versionResponse = await bedrockMgmt.send(
    new CreateGuardrailVersionCommand({
      guardrailIdentifier: guardrailId,
      description: `Added topic: ${newTopic.name}`,
    })
  );

  const newVersion = versionResponse.version!;
  console.log(`Created guardrail version ${newVersion} — test before promoting to production`);

  // 4. At this point, production still uses the old version.
  // Update process.env.GUARDRAIL_VERSION (or your config store) to newVersion
  // only after shadow-testing the new version against real traffic.
  return newVersion;
}

The shadow-testing step — running the new guardrail version in parallel with the production version on a sample of live traffic before fully promoting — is worth implementing for any guardrail change that modifies existing topic definitions. Because Bedrock uses semantic matching, even a small wording change in a definition can shift the semantic boundary enough to block legitimate traffic or miss intended blocks. The pattern is to call ConverseCommand twice (once with each guardrail version) on a 5–10% sample, log the results to separate analytics streams, compare topic fire rates after 24 hours, and promote only if the new version does not show a significant increase in input-block rate on traffic that the old version was passing.

Production gotchas for Bedrock Guardrails topic policy

These are the specific problems that cause the most debugging time in production MCP server deployments.

1. Broad definitions cause false positives that are hard to diagnose. A "financial advice" topic defined as "questions about money, costs, or pricing" will silently block your pricing page FAQ bot. The fix is scoping: state the specific harm (personalized investment or tax advice) rather than the general domain (money). When users report that the assistant refuses to answer a reasonable question, the first diagnostic step is to check the topic trace and identify whether a topic fired, then compare the blocked message against the topic definition to determine if the definition is too broad.

2. Topics are evaluated against entire message context, not individual sentences. A message with 10 paragraphs of benign text and one sentence that semantically resembles a denied topic may still trigger the block. Users who notice that adding preamble ("I am a student researching X, can you help me understand...") sometimes bypasses blocks are observing a real behavior: the surrounding context shifts the semantic vector. Write definitions and examples that account for context injection — your borderline examples should include a few messages with disclaiming preamble.

3. Topics have no confidence score in the trace — only BLOCKED or not. You cannot filter by "high confidence blocks only" or implement a soft-block at the guardrail level. If you need a graduated response (allow the message but add a disclaimer), you must handle that outside the guardrail layer, for example by calling ApplyGuardrailCommand before the ConverseCommand and using the assessment result to modify the system prompt.

4. response.trace is undefined unless trace: "ENABLED" is set in guardrailConfig. This is obvious in development but easy to miss when deploying because environment variables or configuration objects get reset. If your topic analytics are suddenly showing no data and blocked requests are still occurring (you can tell because stopReason is still "guardrail_intervened"), verify that the guardrailConfig being sent with each ConverseCommand still includes trace: "ENABLED".

5. The trace property path includes a numeric string key "0", not an integer. In TypeScript, response.trace?.guardrail?.inputAssessment?.[0] and response.trace?.guardrail?.inputAssessment?.["0"] are equivalent at runtime for plain objects — JavaScript coerces integer property access to strings — but the SDK types may only define the string-keyed variant. Use the string key "0" in your code to match the SDK type definitions and avoid any TypeScript compiler errors.

6. A message can trigger multiple topics simultaneously. The topicPolicy.topics array in the trace may contain more than one entry. If your error handler only reads the first element of the array, you will miss additional triggered topics. Build your remediation messages from the full array, and log all triggered topics for each blocked request — otherwise your analytics will undercount topic frequency when multi-topic blocks occur.

7. UpdateGuardrailCommand always writes to DRAFT — it never updates a numeric version directly. If you are scripting a deployment pipeline that edits a guardrail and immediately reads the result back as a production version, you will get stale data. The correct sequence is: UpdateGuardrailCommand → test on DRAFT → CreateGuardrailVersionCommand → update your MCP server config to reference the new version number. The old version remains immutable and in service until you change the config.

8. Example messages must be messages that WOULD trigger the topic, not safe counterexamples. The API documentation describes these as "sample messages that fall under the topic." Some developers mistakenly provide examples of messages that should not be blocked, reasoning that the model needs to know the boundary from both sides. This is incorrect — Bedrock uses the examples array as positive evidence for the topic, not as a boundary description. Providing "safe" examples will pull the topic boundary toward those safe messages and cause false positives on similar legitimate traffic. Every entry in the examples array should be a message you have decided must be blocked.

AliveMCP and guardrail topic analytics

When a spike in topic blocks coincides with a latency increase or a brief availability dip, the correlation is easy to miss without unified monitoring — AliveMCP tracks MCP server uptime and response-time metrics alongside your application-level events, giving you the cross-signal visibility to distinguish guardrail tuning effects from infrastructure incidents before they escalate.