Amazon Bedrock · CreateGuardrailCommand, filtersConfig, sensitiveInformationPolicyConfig, topicPolicyConfig, CreateGuardrailVersionCommand · 2026-11-27 · Bedrock Guardrails Deep Dive arc

Amazon Bedrock Guardrails for MCP Servers: Content Filtering, PII Anonymization, Topic Policy, and Versioning

Four Bedrock Guardrails deep-dive pages synthesised into a complete production safety playbook for MCP server developers — content filtering (contentPolicyConfig.filtersConfig array with six harm categories HATE/INSULTS/SEXUAL/VIOLENCE/MISCONDUCT/PROMPT_ATTACK, four independent strength levels per category for input and output, PROMPT_ATTACK outputStrength silently ignored, content filters skip system prompts, guardrail_intervened stopReason handling, trace assessment parsing to identify which filter fired, input-phase block saves full inference cost), PII anonymization (sensitiveInformationPolicyConfig with 30+ PIIEntityType enum values, ANONYMIZE replaces entity spans with {TYPE} curly-brace tokens and allows processing to continue while BLOCK stops the entire response, BLOCK wins when mixed with ANONYMIZE in a single call, ApplyGuardrailCommand from @aws-sdk/client-bedrock-runtime for scanning tool results without a model call, two-pass INPUT then OUTPUT scanning pattern, assessment action values are past tense "ANONYMIZED"/"BLOCKED"), topic policy (topicPolicyConfig.topicsConfig using semantic similarity not keyword matching, definition anatomy with up to 30 topics and 200-char definitions, broad definitions cause false positives ("financial advice" blocks "how much does this plan cost?"), examples must be triggering messages not safe messages, no confidence score in trace — only BLOCKED or absent, trace numeric string key "0" not integer), and versioning (DRAFT is mutable and immediately live — never use in production, CreateGuardrailVersionCommand creates immutable numbered snapshots, version is a string not a number, UpdateGuardrailCommand replaces entire config silently deleting omitted policies, DeleteGuardrailCommand destroys all versions without confirmation, shadow rollout pattern for safe promotion). Fourteen consolidated production gotchas at the end.

Why guardrails are non-negotiable for customer-facing MCP servers

An MCP server that calls Amazon Bedrock on behalf of users sits at a uniquely exposed position. The model is powerful enough to generate harmful content, leak PII inadvertently echoed from tool results, stray into regulated domains (legal advice, medical guidance, investment recommendations), and be manipulated by prompt injection attacks embedded in documents or tool outputs. Without a guardrail layer, every tool call is a potential liability.

Bedrock Guardrails addresses all four threat vectors with a single guardrail resource that combines content filtering, PII detection, topic blocking, and word policies in one configuration object. The guardrail attaches to ConverseCommand calls via a single guardrailConfig field, runs transparently before model invocation (input phase) and after model generation (output phase), and fires a distinctive guardrail_intervened stop reason when any policy triggers. The same guardrail can be applied independently of model calls via ApplyGuardrailCommand — which is the right tool for scanning webhook payloads, external API responses, and user-submitted documents without paying inference costs.

This guide covers all four dimensions of the guardrail system in production-ready depth, then consolidates the fourteen most commonly hit failure modes in a single reference section.

Part 1: Content Filtering — filtersConfig, strength levels, and PROMPT_ATTACK

Content filtering is configured via the contentPolicyConfig.filtersConfig array in CreateGuardrailCommand. The control-plane and data-plane operations use different SDK packages: @aws-sdk/client-bedrock (with BedrockClient) for creating and updating guardrails, and @aws-sdk/client-bedrock-runtime (with BedrockRuntimeClient) for the runtime operations ConverseCommand and ApplyGuardrailCommand. Getting this wrong is the first production trip wire.

The six filter categories

Each entry in filtersConfig tunes one of six harm categories with independent inputStrength and outputStrength values:

Strength levels — what they actually mean

Each strength level corresponds to a minimum detection confidence threshold, not an absolute severity scale:

A key insight: inputStrength and outputStrength are fully independent. You can set HATE to inputStrength: "HIGH" (never let hate speech into the model's context) while keeping outputStrength: "MEDIUM" (allow nuanced educational model responses that reference historical discrimination). This asymmetry is intentional.

Creating a guardrail and attaching it to Converse

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

// Control-plane: create/update/version guardrails
const bedrockControl = new BedrockClient({
  region: process.env.AWS_REGION ?? 'us-east-1',
});

// Data-plane: Converse + ApplyGuardrail
const bedrockRuntime = new BedrockRuntimeClient({
  region: process.env.AWS_REGION ?? 'us-east-1',
});

async function createContentGuardrail(): Promise<string> {
  const response = await bedrockControl.send(new CreateGuardrailCommand({
    name: 'mcp-server-content-policy',
    contentPolicyConfig: {
      filtersConfig: [
        { type: 'HATE',          inputStrength: 'HIGH',   outputStrength: 'HIGH'   },
        { type: 'INSULTS',       inputStrength: 'MEDIUM', outputStrength: 'MEDIUM' },
        { type: 'SEXUAL',        inputStrength: 'HIGH',   outputStrength: 'HIGH'   },
        { type: 'VIOLENCE',      inputStrength: 'MEDIUM', outputStrength: 'MEDIUM' },
        { type: 'MISCONDUCT',    inputStrength: 'HIGH',   outputStrength: 'HIGH'   },
        { type: 'PROMPT_ATTACK', inputStrength: 'HIGH',
          // outputStrength is silently ignored for PROMPT_ATTACK.
          // Set NONE explicitly to document the asymmetry.
          outputStrength: 'NONE' },
      ],
    },
    blockedInputMessaging: 'Your request was blocked by content policy.',
    blockedOutputsMessaging: 'The response was blocked by content policy.',
  }));
  // version is "DRAFT" at creation — call CreateGuardrailVersionCommand before prod
  return response.guardrailId!;
}

// Attach to ConverseCommand via guardrailConfig
async function converseWithGuardrail(
  userMessage: string,
  guardrailId: string,
  guardrailVersion: string,  // always a STRING: "1", "2", or "DRAFT" — never a number
): Promise<{ blocked: boolean; text?: string; blockPhase?: string }> {
  const response = await bedrockRuntime.send(new ConverseCommand({
    modelId: 'us.anthropic.claude-3-5-sonnet-20241022-v2:0',
    messages: [{ role: 'user', content: [{ text: userMessage }] }],
    guardrailConfig: {
      guardrailIdentifier: guardrailId,
      guardrailVersion,
      trace: 'ENABLED',  // needed to identify which filter fired
    },
    inferenceConfig: { maxTokens: 2048 },
  }));

  // Always check stopReason BEFORE reading output content.
  // When guardrail fires, content array is empty — accessing [0].text throws.
  if (response.stopReason === 'guardrail_intervened') {
    const inputBlocked = response.trace?.guardrail?.inputAssessment
      ?.contentPolicy?.filters?.some(f => f.action === 'BLOCKED');
    return {
      blocked: true,
      blockPhase: inputBlocked ? 'INPUT' : 'OUTPUT',
    };
  }

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

  return { blocked: false, text };
}

PROMPT_ATTACK and prompt injection in MCP servers

MCP servers that accept user-defined prompt fragments and incorporate them into system prompts are a classic injection vector. The guardrail's content filters do not evaluate system prompts — only user and assistant messages. This means you cannot rely on the guardrail to protect a system prompt that includes user-supplied text. The correct architecture: validate the user-supplied fragment using ApplyGuardrailCommand with source: "INPUT" before incorporating it into the system prompt template. This catches injection in the user-controlled fragment before it reaches the privileged system prompt position.

At HIGH strength, PROMPT_ATTACK reliably catches direct overrides ("ignore previous instructions"), persona substitutions ("you are now DAN"), encoding obfuscation (base64 or ROT13 wrapping), and indirect injection embedded in documents the model is asked to summarize. The main false positive at HIGH strength: legitimate meta-instructions like "rewrite the above in a formal tone" can trigger the filter because they contain instruction-override patterns in a broad sense. Test at MEDIUM first if your MCP tool regularly handles instruction-shaped text.

Input-phase blocks save the full inference cost. When the guardrail fires before invoking the model, you pay only for the guardrail evaluation. Using ApplyGuardrailCommand as an explicit pre-flight check before each ConverseCommand call adds a small latency overhead but ensures that PROMPT_ATTACK attempts are caught before you spend inference tokens on them.

Part 2: PII Detection and Anonymization — sensitiveInformationPolicyConfig, ANONYMIZE vs BLOCK

PII detection is configured via sensitiveInformationPolicyConfig in the same CreateGuardrailCommand call as content filtering. The two policies are evaluated independently and can fire simultaneously. sensitiveInformationPolicyConfig has two sub-configurations: piiEntitiesConfig for the 30-plus built-in entity types, and regexesConfig for custom patterns.

ANONYMIZE vs BLOCK — the semantics that matter most

These two actions behave fundamentally differently and cannot be used interchangeably:

ANONYMIZE replaces detected entity spans with curly-brace tokens — {NAME}, {EMAIL}, {US_SOCIAL_SECURITY_NUMBER} — and allows processing to continue. The guardrail's action in the response is "NONE", not "GUARDRAIL_INTERVENED", because the guard transformed but did not block. The anonymized text is available in outputs[0].text. Use ANONYMIZE for high-frequency personal data (names, emails, phone numbers) where the downstream LLM task (summarization, classification, routing) can proceed meaningfully with tokenized identifiers.

BLOCK returns action: "GUARDRAIL_INTERVENED" and suppresses the entire content. No usable text is returned. Use BLOCK for credentials and high-risk identifiers: AWS access keys, raw payment card numbers, CVV codes, SSNs. If you accidentally configure BLOCK on a high-frequency entity like NAME or DATE_TIME, nearly every real-world input is rejected.

When BLOCK and ANONYMIZE fire in the same call, BLOCK wins. The entire response is suppressed even if only one BLOCK entity was present alongside ten ANONYMIZE entities. Plan your entity-action assignments so combinations you expect to co-occur give the right result.

Configuring a PII guardrail

import {
  BedrockClient,
  CreateGuardrailCommand,
} from '@aws-sdk/client-bedrock';
import {
  BedrockRuntimeClient,
  ApplyGuardrailCommand,
} from '@aws-sdk/client-bedrock-runtime';

// ApplyGuardrailCommand lives in @aws-sdk/client-bedrock-runtime,
// NOT in @aws-sdk/client-bedrock.

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

const GUARDRAIL_ID = process.env.BEDROCK_GUARDRAIL_ID!;
const GUARDRAIL_VERSION = process.env.GUARDRAIL_VERSION ?? '1';

async function createPIIGuardrail(): Promise<string> {
  const bedrockAdmin = new BedrockClient({
    region: process.env.AWS_REGION ?? 'us-east-1',
  });

  const response = await bedrockAdmin.send(new CreateGuardrailCommand({
    name: 'mcp-server-pii-guardrail',
    sensitiveInformationPolicyConfig: {
      piiEntitiesConfig: [
        // Hard BLOCK for credentials — these must never reach a model
        { type: 'AWS_ACCESS_KEY',              action: 'BLOCK' },
        { type: 'AWS_SECRET_KEY',              action: 'BLOCK' },
        { type: 'PASSWORD',                    action: 'BLOCK' },
        { type: 'CREDIT_DEBIT_CARD_NUMBER',    action: 'BLOCK' },
        { type: 'CREDIT_DEBIT_CARD_CVV',       action: 'BLOCK' },
        { type: 'US_SOCIAL_SECURITY_NUMBER',   action: 'BLOCK' },
        // ANONYMIZE for personal identifiers — allow processing with tokens
        { type: 'NAME',       action: 'ANONYMIZE' },
        { type: 'EMAIL',      action: 'ANONYMIZE' },
        { type: 'PHONE',      action: 'ANONYMIZE' },
        { type: 'ADDRESS',    action: 'ANONYMIZE' },
        { type: 'IP_ADDRESS', action: 'ANONYMIZE' },
      ],
      regexesConfig: [
        {
          name: 'internal-api-token',
          description: 'Internal API tokens: sk_live_ or sk_test_ prefix',
          // No look-behind support — include the prefix in the match span itself
          pattern: 'sk_(?:live|test)_[A-Za-z0-9]{24,}',
          action: 'BLOCK',
        },
        {
          name: 'employee-id',
          description: 'Employee IDs: EMP + 6 digits',
          // Non-capturing group required — group captures are ignored
          pattern: 'EMP(?:\\d{6})',
          action: 'ANONYMIZE',
        },
      ],
    },
    blockedInputMessaging: 'Your message contains restricted information.',
    blockedOutputsMessaging: 'The response contained restricted information and was blocked.',
  }));

  return response.guardrailId!;
}

ApplyGuardrailCommand — scanning tool results without a model call

The most important use case for PII scanning in an MCP server is filtering what an external API or database returns before passing it to the calling LLM agent. MCP tools frequently call third-party REST APIs that return records containing personal data. Without scanning, any PII in those records flows unexamined through your tool handler and back to the agent, where it may be logged, stored, or echoed in downstream responses.

The content array for ApplyGuardrailCommand uses a double-nested shape that differs from ConverseCommand messages: { text: { text: "the string here" } }. The outer text key selects the content block type; the inner text key carries the actual string. Getting the nesting wrong silently sends the wrong structure and may return an error or empty assessment.

The two-pass PII scanning pattern

Complete PII coverage for an MCP tool that calls an external API requires two guardrail scans per tool call:

// Two-pass PII scanning: scan user INPUT, then scan tool result OUTPUT

async function applyGuardrail(
  text: string,
  source: 'INPUT' | 'OUTPUT',
): Promise<{ safe: boolean; safeText: string; detected: string[] }> {
  const response = await runtime.send(new ApplyGuardrailCommand({
    guardrailIdentifier: GUARDRAIL_ID,
    guardrailVersion:    GUARDRAIL_VERSION,
    source,
    // Double-nested content shape — { text: { text: "..." } }
    // Different from ConverseCommand message shape { text: "..." }
    content: [{ text: { text } }],
  }));

  const safe = response.action !== 'GUARDRAIL_INTERVENED';

  const policy = response.assessments?.[0]?.sensitiveInformationPolicy;

  // Assessment action values are PAST TENSE: "ANONYMIZED" and "BLOCKED"
  // NOT the config values "ANONYMIZE" and "BLOCK"
  const detected = [
    ...(policy?.piiEntities ?? []).map(e => e.type ?? 'UNKNOWN'),
    ...(policy?.regexes ?? []).map(r => r.name ?? 'custom'),
  ];

  if (detected.length > 0) {
    console.log(JSON.stringify({
      event: 'pii_detected', source, entities: detected,
      blocked: !safe, ts: new Date().toISOString(),
    }));
  }

  // When ANONYMIZE entities are found, outputs[0].text has {TOKEN} replacements.
  // When BLOCK fires, outputs[0].text contains the blockedOutputsMessaging string
  // — do NOT return this as a fallback, return empty string instead.
  const safeText = safe
    ? (response.outputs?.[0]?.text ?? text)
    : '';

  return { safe, safeText, detected };
}

// MCP tool handler: two-pass pattern
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';

const server = new McpServer({ name: 'pii-aware-server', version: '1.0.0' });

server.tool(
  'query_customer_database',
  'Query customer database with PII scanning on input and output',
  { query: z.string().min(1).max(2000) },
  async ({ query }) => {
    // Pass 1: scan user input (INPUT) — strip PII before forwarding to external API
    const inputScan = await applyGuardrail(query, 'INPUT');
    if (!inputScan.safe) {
      return {
        isError: true,
        content: [{ type: 'text' as const, text: 'Your query contains restricted information.' }],
      };
    }

    // Call external API with sanitized query (PII replaced with tokens)
    let rawApiResponse: string;
    try {
      rawApiResponse = await fetchFromExternalApi(inputScan.safeText);
    } catch (err) {
      return {
        isError: true,
        content: [{ type: 'text' as const, text: 'External API call failed.' }],
      };
    }

    // Pass 2: scan tool result (OUTPUT) — redact PII before returning to agent
    const outputScan = await applyGuardrail(rawApiResponse, 'OUTPUT');
    if (!outputScan.safe) {
      return {
        isError: true,
        content: [{ type: 'text' as const, text: 'API response contained restricted information.' }],
      };
    }

    // safeText has PII replaced with {NAME}, {EMAIL}, etc.
    return { content: [{ type: 'text' as const, text: outputScan.safeText }] };
  },
);

async function fetchFromExternalApi(query: string): Promise<string> {
  // Replace with real API call
  return `Results for: ${query}`;
}

Pass 1 (INPUT) prevents seeding the external API with the user's PII, which also prevents exfiltration attacks where an adversary crafts input whose PII content — when reflected back in the API response — reveals data about other users. Pass 2 (OUTPUT) is the more critical scan: external APIs have no knowledge of your guardrail policies and may return records containing arbitrary PII that would flow directly to the LLM agent without scanning.

Part 3: Topic Policy — semantic matching, definition writing, and trace analytics

Topic policy lets you block entire categories of conversation — not by keyword, but by semantic similarity. Bedrock embeds the message and the topic definition into a shared vector space and blocks if the distance is below a threshold. This has profound implications for how to write effective definitions.

Topic definition anatomy

Each topic entry in topicPolicyConfig.topicsConfig has four fields:

Topics have no confidence score in the trace. A topic is either BLOCKED or absent — you cannot distinguish "barely triggered" from "clearly triggered" and cannot implement soft-blocking at the guardrail level. If you need graduated responses, handle that in application code outside the guardrail layer.

Writing definitions that avoid false positives

The most common failure mode is a definition that is too broad. The classic trap: "financial advice" defined as "questions about money, costs, or financial decisions" will block your pricing FAQ bot when users ask "how much does the enterprise plan cost?" because "costs" is semantically close to the topic center. The fix is scoping: state the specific harm (personalized investment, tax, or financial planning recommendations) rather than the general domain.

// POOR definition — causes false positives on pricing questions
const poorTopic = {
  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,
};
// Will also block: "how much does the pro plan cost?" and "is there a free tier?"

// BETTER definition — scoped to the specific harm
const betterTopic = {
  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?',
    'Is it better to max my 401k or invest in index funds this year?',
    'Should I use a Roth IRA or a traditional IRA for my situation?',
    '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 from the definition center and passes

Four principles for definitions that work:

  1. 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's semantic content.
  2. The definition establishes the cluster center; examples push the boundary. If the definition is too broad, no number of edge-case examples will save you — narrow the definition first.
  3. Avoid words you do not want to block. Including the word "costs" in a "financial advice" definition embeds it in the topic vector, making pricing questions semantically adjacent.
  4. Examples must be triggering messages, not safe messages. The examples array is positive evidence for the topic. Including safe counterexamples pulls the topic boundary toward legitimate content and creates false positives.

Parsing topic trace data

Topics appear in the trace under response.trace?.guardrail?.inputAssessment?.["0"]?.topicPolicy?.topics. Note the numeric string key "0" — JavaScript automatically coerces integer property access to strings, but the SDK type definitions may only define the string key form. Use the string key explicitly to match the SDK types and avoid compiler errors.

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

interface BlockedTopicInfo {
  source: 'input' | 'output';
  topicName: string;
}

async function converseWithTopicGuardrail(
  messages: Message[],
  guardrailId: string,
  guardrailVersion: string,
): Promise<{ text: string | null; blockedTopics: BlockedTopicInfo[] }> {
  const runtime = new BedrockRuntimeClient({ region: process.env.AWS_REGION ?? 'us-east-1' });

  const response = await runtime.send(new ConverseCommand({
    modelId: process.env.BEDROCK_MODEL_ID ?? 'us.anthropic.claude-3-5-sonnet-20241022-v2:0',
    messages,
    guardrailConfig: {
      guardrailIdentifier: guardrailId,
      guardrailVersion,
      trace: 'ENABLED',  // required — without this, trace is undefined, not empty
    },
  }));

  const blockedTopics: BlockedTopicInfo[] = [];

  // Note: numeric STRING key "0", not integer 0
  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 });
    }
  }

  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 });
    }
  }

  // A single message can trigger MULTIPLE topics simultaneously —
  // read the full array, not just blockedTopics[0]
  if (response.stopReason === 'guardrail_intervened') {
    return { text: null, blockedTopics };
  }

  const textContent = response.output?.message?.content?.find(c => c.text !== undefined);
  return { text: textContent?.text ?? null, blockedTopics };
}

An output block (topic fires on the model's generated response) typically indicates a system prompt configuration issue — the model is steering into restricted territory that your prompt should constrain. An input block indicates a user attempting a restricted request. Log both sources separately: the patterns inform different remediation actions.

Part 4: Version Lifecycle — DRAFT vs numbered versions, deployment workflow

Every guardrail has exactly one mutable DRAFT version and any number of immutable numbered versions. UpdateGuardrailCommand always overwrites DRAFT. If production traffic is pinned to DRAFT, any engineer edit — including a typo that removes a topic policy — takes effect immediately on all in-flight requests with no deployment gate. This is the most common guardrail safety failure in production.

The correct version workflow

The workflow is a strict three-step loop you cannot safely reorder:

  1. Edit via UpdateGuardrailCommand — always targets DRAFT. Critical: this is a full replacement, not a patch. Omitting topicPolicyConfig silently deletes all topic policies from DRAFT. Always read the current DRAFT with GetGuardrailCommand first, merge your changes in memory, then call UpdateGuardrailCommand with the full merged config.
  2. Test DRAFT with ApplyGuardrailCommand against a suite of known-pass and known-block inputs.
  3. Snapshot with CreateGuardrailVersionCommand and deploy the numeric version to production.
import {
  BedrockClient,
  GetGuardrailCommand,
  UpdateGuardrailCommand,
  CreateGuardrailVersionCommand,
} from '@aws-sdk/client-bedrock';
import {
  BedrockRuntimeClient,
  ApplyGuardrailCommand,
} from '@aws-sdk/client-bedrock-runtime';

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

const GUARDRAIL_ID = process.env.BEDROCK_GUARDRAIL_ID!;

interface TestCase {
  input: string;
  expectAction: 'NONE' | 'GUARDRAIL_INTERVENED';
  label: string;
}

async function deployGuardrailChange(
  policyOverrides: Parameters<typeof controlPlane.send>[0] extends never ? never : object,
  testCases: TestCase[],
  changeDescription: string,
): Promise<{ version: string; passed: boolean }> {

  // Step 1: read DRAFT first to avoid accidental policy deletion
  const current = await controlPlane.send(new GetGuardrailCommand({
    guardrailIdentifier: GUARDRAIL_ID,
    guardrailVersion: 'DRAFT',
  }));

  // Step 2: merge and update — FULL config required
  await controlPlane.send(new UpdateGuardrailCommand({
    guardrailIdentifier: GUARDRAIL_ID,
    name: current.name!,
    description: current.description,
    blockedInputMessaging: current.blockedInputMessaging!,
    blockedOutputsMessaging: current.blockedOutputsMessaging!,
    // Carry over existing topic policy if not overriding it
    topicPolicyConfig: current.topicPolicy ? {
      topicsConfig: current.topicPolicy.topics?.map(t => ({
        name: t.name!, definition: t.definition!,
        examples: t.examples ?? [], type: t.type!,
      })) ?? [],
    } : undefined,
    // ... carry over other policy configs similarly
  }));

  // Step 3: validate DRAFT before snapshotting
  const failures: string[] = [];
  for (const tc of testCases) {
    const result = await runtime.send(new ApplyGuardrailCommand({
      guardrailIdentifier: GUARDRAIL_ID,
      guardrailVersion: 'DRAFT',
      source: 'INPUT',
      content: [{ text: { text: tc.input } }],
    }));

    if (result.action !== tc.expectAction) {
      failures.push(`[${tc.label}] expected="${tc.expectAction}", got="${result.action}"`);
    }
  }

  if (failures.length > 0) {
    console.error('Test suite failed — aborting version creation:', failures);
    return { version: '', passed: false };
  }

  // Step 4: snapshot into an immutable numbered version
  const versionResponse = await controlPlane.send(new CreateGuardrailVersionCommand({
    guardrailIdentifier: GUARDRAIL_ID,
    description: changeDescription,
    // clientRequestToken enables idempotency within a 1-hour window on retry
    clientRequestToken: `deploy-${GUARDRAIL_ID}-${Date.now()}`,
  }));

  // response.version is a STRING like "1", "2" — NEVER a number
  const newVersion = versionResponse.version!;
  console.log(`Version ${newVersion} created — update GUARDRAIL_VERSION env var and redeploy`);

  return { version: newVersion, passed: true };
}

Shadow rollout for risky changes

For topic definition changes — where a small wording shift can move the semantic boundary enough to block legitimate traffic — run a shadow test before fully promoting. Fire both the production version and the candidate version on a sample of real traffic, log both results, but only act on the production result. After 24 hours of data, compare topic fire rates. Promote only if the new version does not show a meaningful increase in input-block rate on traffic the production version was passing.

const PROD_VERSION = process.env.GUARDRAIL_VERSION ?? '1';
const SHADOW_VERSION = process.env.SHADOW_GUARDRAIL_VERSION;
const SHADOW_SAMPLE_RATE = parseFloat(process.env.SHADOW_SAMPLE_RATE ?? '0.1');

async function runWithShadow(
  text: string,
  source: 'INPUT' | 'OUTPUT',
): Promise<'NONE' | 'GUARDRAIL_INTERVENED'> {
  const productionResult = await runtime.send(new ApplyGuardrailCommand({
    guardrailIdentifier: GUARDRAIL_ID,
    guardrailVersion: PROD_VERSION,  // string "1", not number 1
    source,
    content: [{ text: { text } }],
  }));

  if (SHADOW_VERSION && Math.random() < SHADOW_SAMPLE_RATE) {
    runtime.send(new ApplyGuardrailCommand({
      guardrailIdentifier: GUARDRAIL_ID,
      guardrailVersion: SHADOW_VERSION,
      source,
      content: [{ text: { text } }],
    })).then(shadowResult => {
      if (productionResult.action !== shadowResult.action) {
        console.log(JSON.stringify({
          event: 'guardrail_shadow_divergence',
          productionVersion: PROD_VERSION,
          shadowVersion: SHADOW_VERSION,
          productionAction: productionResult.action,
          shadowAction: shadowResult.action,
          source,
          ts: new Date().toISOString(),
        }));
      }
    }).catch(() => {}); // shadow errors must never affect production path
  }

  return productionResult.action as 'NONE' | 'GUARDRAIL_INTERVENED';
}

Deletion constraints

DeleteGuardrailVersionCommand deletes a single numbered version. DRAFT cannot be deleted this way. DeleteGuardrailCommand (without a version parameter) is the dangerous one: it deletes the entire guardrail resource including DRAFT and all numbered versions simultaneously, with no confirmation prompt, no soft delete, and no undo. Restrict bedrock:DeleteGuardrail in IAM to deployment pipeline roles only — never to the execution role used by running MCP server processes.

Consolidated production gotchas — fourteen failure modes

1. BedrockClient vs BedrockRuntimeClient — the package split bites everyone. CreateGuardrailCommand, UpdateGuardrailCommand, CreateGuardrailVersionCommand, GetGuardrailCommand, and ListGuardrailsCommand live in @aws-sdk/client-bedrock and require a BedrockClient. ConverseCommand and ApplyGuardrailCommand live in @aws-sdk/client-bedrock-runtime and require a BedrockRuntimeClient. These are separate IAM action namespaces too: control-plane calls require bedrock:GetGuardrail, bedrock:CreateGuardrailVersion, etc.; runtime calls require bedrock:ApplyGuardrail. MCP server execution roles typically only need the runtime permission.

2. Never use DRAFT as the production guardrail version. UpdateGuardrailCommand overwrites DRAFT synchronously. If your production GUARDRAIL_VERSION env var is "DRAFT", any engineer edit — including a typo that removes a topic policy or accidentally lowers a content filter threshold — takes effect immediately on all running production instances with no deployment gate and no rollback capability. Always pin production to a numeric version string.

3. UpdateGuardrailCommand is a full replacement — read DRAFT first or silently lose policies. There is no partial-update or patch operation. Calling UpdateGuardrailCommand with only contentPolicyConfig and omitting topicPolicyConfig silently deletes all topic policies from DRAFT. The API returns 200 OK with no warning. Always read the current DRAFT with GetGuardrailCommand first, merge your changes in memory, and pass the full merged config.

4. PROMPT_ATTACK outputStrength is silently ignored — set it to NONE explicitly. The API accepts any strength value for outputStrength on a PROMPT_ATTACK entry without error. The guardrail is created successfully. The value simply has no behavioral effect. Setting it to MEDIUM or HIGH creates false confidence that you have PROMPT_ATTACK protection on output. Always set outputStrength: "NONE" to document the asymmetry explicitly.

5. Content filters do not apply to system prompts. Only user and assistant messages are evaluated by content and topic policy. If your system prompt contains terms that would trigger a content filter in a user message — clinical terminology, security research concepts, industry jargon — they pass through without evaluation. Conversely, you cannot use content filtering to sanitize user-supplied text that gets incorporated into a system prompt. Validate user-supplied prompt fragments using ApplyGuardrailCommand with source: "INPUT" before incorporating them into the system prompt template.

6. HIGH strength on HATE blocks academic and historical text. At HIGH strength, HATE blocks based on LOW-confidence detection, which means "contains hate-associated vocabulary" rather than "expresses hatred." Questions like "Why did Nazi propaganda use dehumanizing language?" and "What rhetoric did Jim Crow-era politicians use?" are blocked. For educational tools, keep HATE at MEDIUM and accept that the most extreme academic analysis of hate movements may occasionally pass. Raise to HIGH only in contexts where false positives are acceptable and missed detections are catastrophic.

7. ANONYMIZE token format is {NAME} curly braces, not [NAME] square brackets. Some AWS documentation examples and earlier SDK versions used square brackets. The actual replacement token in outputs[0].text uses curly braces. If your downstream code parses or matches square-bracket tokens, it will fail silently — the curly-brace tokens pass through unparsed. Verify the actual format by running a known input through ApplyGuardrailCommand and inspecting outputs[0].text directly.

8. PII detection is probabilistic — short inputs frequently miss entities. The built-in entity detector is an NLP model, not a rule-based parser. Inputs under roughly 15–20 tokens often fail to detect PII that a human would recognize. A bare SSN like 123-45-6789 in isolation may not trigger US_SOCIAL_SECURITY_NUMBER if there is no surrounding context ("SSN:", "social security number:") to disambiguate it from a phone number or date. Never use Bedrock Guardrails PII detection as a sole compliance control for regulated data — pair it with format-validation logic in your application code.

9. Assessment action values are past tense: "ANONYMIZED" and "BLOCKED", not "ANONYMIZE" and "BLOCK". When you read back assessment data to build an audit log, the action field on each detected entity or regex match uses past-tense values. Code that compares the assessment action to the configuration values (if (entity.action === 'ANONYMIZE')) will silently mismatch and always evaluate to false. This applies to both piiEntities[n].action and regexes[n].action in the assessment.

10. Broad topic definitions cause false positives that are hard to diagnose. A "financial advice" topic defined as "questions about money, costs, or pricing" silently blocks your pricing FAQ bot without any error — users just get a blocked response. The first diagnostic step when users report unreasonable refusals is to enable trace and check the topic assessment for which topic fired, then compare the blocked message against the definition. The fix is scoping the definition to the specific harm (personalized investment or tax advice) rather than the general domain (money).

11. Topic trace has no confidence score — only BLOCKED or absent, no soft-block. You cannot implement graduated responses ("allow but add a disclaimer if confidence is medium") at the guardrail level. If you need this, call ApplyGuardrailCommand before ConverseCommand and use the assessment result to conditionally modify the system prompt. Also: response.trace is undefined (not an empty object) when trace is not set to "ENABLED" in guardrailConfig — if topic analytics are suddenly showing no data, check that trace: "ENABLED" is still present in every ConverseCommand call.

12. Version is a STRING — passing a number throws ValidationException. The Bedrock SDK types version as string throughout. If your CI/CD pipeline serializes the version to JSON, reads it from an environment variable via a numeric type, or uses an ORM that coerces string-numeric values, you can end up passing guardrailVersion: 1 (number) instead of guardrailVersion: "1" (string). The error message is: Value '1' at 'guardrailVersion' failed to satisfy constraint: Member must satisfy regular expression pattern: (([1-9][0-9]{0,7})|(DRAFT)). Test your config management pipeline end-to-end.

13. ApplyGuardrailCommand double-nested content shape is different from ConverseCommand messages. The correct content shape for ApplyGuardrailCommand is [{ text: { text: "the string" } }] — the outer text key selects the content block type, and the inner text key carries the actual string value. This is different from the message content shape in ConverseCommand, which is [{ text: "the string" }]. Getting the nesting wrong may produce a runtime serialization error or an empty assessment with no PII detected.

14. DeleteGuardrailCommand destroys all versions without confirmation — restrict IAM scope. DeleteGuardrailCommand without a guardrailVersion parameter immediately and permanently deletes the entire guardrail resource including DRAFT and all numbered versions. There is no confirmation prompt, no soft delete, and no undo. A misconfigured script or a compromised dependency with bedrock:DeleteGuardrail in its IAM policy can permanently destroy your production guardrail configuration. Restrict this IAM action to deployment pipeline roles with strict human-in-the-loop approval workflows, never to the execution role used by running MCP server processes.

AliveMCP and guardrail-triggered outages

A misconfigured guardrail — a strength level set too high, a policy update accidentally applied to the DRAFT version that production traffic is pinned to, or a topic definition change that shifts the semantic boundary enough to block legitimate requests — produces an outage that is indistinguishable from infrastructure failure from the client's perspective. AliveMCP monitors your MCP server endpoints continuously and surfaces sudden changes in error rates and blocked response patterns, so you catch guardrail misconfigurations the moment they start affecting users rather than hours later when an incident review surfaces the correlation.