Guide · Amazon Bedrock · Safety
Amazon Bedrock Guardrails Versioning for MCP Servers — DRAFT vs Numbered Versions, Lifecycle, and Standalone ApplyGuardrailCommand
Every Amazon Bedrock Guardrail has exactly one mutable DRAFT version and any number of immutable numbered versions — but the asymmetry between them causes the most common production safety failures in MCP server deployments. The core danger: UpdateGuardrailCommand always overwrites DRAFT, never creates a numbered version, and any in-flight production traffic pinned to DRAFT silently picks up policy changes the moment an engineer edits the guardrail configuration. Beyond version pinning, four topics dominate guardrail lifecycle work for MCP servers: the exact workflow for CreateGuardrailVersionCommand (its parameters, return shape, and ARN format), gradual production rollout patterns using environment variables, the constraints on DeleteGuardrailVersionCommand vs the destructive DeleteGuardrailCommand (which nukes all versions without confirmation), and ApplyGuardrailCommand from the runtime package — not the control-plane package — for scanning webhook payloads, tool inputs, and third-party API responses without calling any foundation model. For the broader guardrails integration pattern see Bedrock Guardrails overview; for content filter threshold configuration see content filtering; for PII anonymization see PII anonymization; for topic policy rules see topic policy.
TL;DR
Never use DRAFT in production. After every policy change, run CreateGuardrailVersionCommand (control-plane @aws-sdk/client-bedrock), validate the returned numeric version string against a test suite of known-pass and known-block inputs, then update your GUARDRAIL_VERSION env var and redeploy. For scanning content without a model call use ApplyGuardrailCommand from @aws-sdk/client-bedrock-runtime with source: "INPUT" | "OUTPUT".
- Bedrock Guardrails overview — guardrailConfig on ConverseCommand, stopReason detection, BLOCKED responses
- Bedrock Guardrails content filtering — harmful content filter thresholds, HATE/VIOLENCE/SEXUAL/MISCONDUCT types
- Bedrock Guardrails PII — ANONYMIZED vs BLOCKED, piiEntities types, regex patterns, audit logging
- Bedrock Guardrails topic policy — denied topics, definition strings, threshold configuration
- Bedrock Converse API — ConverseCommand structure, guardrailConfig attachment, stopReason values
DRAFT vs numbered versions — the lifecycle model
When you create a Bedrock Guardrail with CreateGuardrailCommand, Bedrock creates exactly one version: DRAFT. This is the only version that is ever mutable. Every call to UpdateGuardrailCommand targets DRAFT regardless of which version you currently use in production — there is no "update version 3" operation. DRAFT always represents the latest unsnapshot state of your guardrail configuration.
Numbered versions — "1", "2", "3" and so on — are immutable snapshots created on demand by CreateGuardrailVersionCommand. Once you create version "2", nothing can change it. You can delete it, but you cannot modify it. This immutability is what makes numbered versions safe to pin in production: guardrailVersion: "2" in a ConverseCommand will apply exactly the same policy configuration six months from now as it does today, regardless of how many times the guardrail has been edited since.
The practical workflow is a strict three-step loop: (1) edit via UpdateGuardrailCommand, which modifies DRAFT; (2) test DRAFT in a development or staging environment; (3) snapshot with CreateGuardrailVersionCommand and deploy the numeric version to production. Never skip step 2 — the only gate between a misconfigured policy and a production outage is your pre-snapshot test suite.
A second critical invariant: GetGuardrailCommand with guardrailVersion: "DRAFT" always returns the current edit state of the guardrail, including all policy config blocks. Use this during development to inspect current configuration. Use it with caution in security-sensitive environments — the response includes regexesConfig patterns that may expose internal data-matching logic if logged.
import {
BedrockClient,
UpdateGuardrailCommand,
GetGuardrailCommand,
CreateGuardrailVersionCommand,
type UpdateGuardrailCommandInput,
} from '@aws-sdk/client-bedrock';
// Control-plane operations use BedrockClient (NOT BedrockRuntimeClient)
const controlPlane = new BedrockClient({ region: process.env.AWS_REGION ?? 'us-east-1' });
const GUARDRAIL_ID = process.env.BEDROCK_GUARDRAIL_ID!;
// Step 1: Update DRAFT — always targets DRAFT, no version param
async function updateGuardrailDraft() {
const input: UpdateGuardrailCommandInput = {
guardrailIdentifier: GUARDRAIL_ID,
name: 'mcp-content-safety',
description: 'Content safety guardrail for MCP tool handler inputs and outputs',
// UpdateGuardrailCommand replaces the ENTIRE guardrail config.
// If you omit topicPolicyConfig here, any existing topic policies are CLEARED.
// Always read DRAFT first with GetGuardrailCommand and merge, never partial-update.
contentPolicyConfig: {
filtersConfig: [
{ type: 'HATE', inputStrength: 'HIGH', outputStrength: 'HIGH' },
{ type: 'INSULTS', inputStrength: 'MEDIUM', outputStrength: 'MEDIUM' },
{ type: 'SEXUAL', inputStrength: 'HIGH', outputStrength: 'HIGH' },
{ type: 'VIOLENCE', inputStrength: 'HIGH', outputStrength: 'HIGH' },
{ type: 'MISCONDUCT', inputStrength: 'MEDIUM', outputStrength: 'MEDIUM' },
{ type: 'PROMPT_ATTACK', inputStrength: 'HIGH', outputStrength: 'NONE' },
],
},
sensitiveInformationPolicyConfig: {
piiEntitiesConfig: [
{ type: 'EMAIL', action: 'ANONYMIZE' },
{ type: 'PHONE', action: 'ANONYMIZE' },
{ type: 'SSN', action: 'BLOCK' },
{ type: 'CREDIT_DEBIT_NUMBER', action: 'BLOCK' },
],
},
blockedInputMessaging: 'Your input was blocked by content policy.',
blockedOutputsMessaging: 'The response was blocked by content policy.',
};
const response = await controlPlane.send(new UpdateGuardrailCommand(input));
console.log(`DRAFT updated. guardrailId=${response.guardrailId}, version=${response.version}`);
// response.version is always "DRAFT" here — UpdateGuardrailCommand never creates a snapshot
}
// Step 2: Inspect DRAFT before snapshotting
async function inspectDraft() {
const response = await controlPlane.send(new GetGuardrailCommand({
guardrailIdentifier: GUARDRAIL_ID,
guardrailVersion: 'DRAFT',
}));
console.log('Current DRAFT config:', JSON.stringify({
name: response.name,
version: response.version, // "DRAFT"
contentPolicy: response.contentPolicy,
sensitiveInformationPolicy: response.sensitiveInformationPolicy,
// WARNING: response includes regexesConfig patterns — do not log in production
}, null, 2));
}
CreateGuardrailVersionCommand — parameters, response shape, and ARN format
CreateGuardrailVersionCommand takes a snapshot of the current DRAFT and assigns the next sequential integer as the version string. It lives in the control-plane package @aws-sdk/client-bedrock, not the runtime package. The required parameter is guardrailIdentifier, which accepts either the short guardrail ID (e.g., "a1b2c3d4e5f6") or the full base ARN (arn:aws:bedrock:REGION:ACCOUNT_ID:guardrail/GUARDRAIL_ID). The base ARN does not include a version suffix — version-specific ARNs are returned by the create-version response and are distinct from the base ARN.
The optional description parameter is worth populating in production — it creates an auditable changelog inside Bedrock itself. Use semantic versioning notation or link your internal ticket system: "v2.1.0 — added finance topic block; tightened SSN to BLOCK; see JIRA-4421". The optional clientRequestToken parameter enables idempotency: if you retry a failed create-version call with the same token within a one-hour window, Bedrock returns the existing version rather than creating a duplicate.
The response contains three fields you need to persist: guardrailId (same short ID you passed in), version (an integer string like "1", "2"), and guardrailArn. The returned guardrailArn includes a version suffix: it has the form arn:aws:bedrock:REGION:ACCOUNT_ID:guardrail/GUARDRAIL_ID/GUARDRAIL_VERSION. You can use this versioned ARN directly as guardrailIdentifier in ConverseCommand and ApplyGuardrailCommand calls — Bedrock parses the version out of the ARN so you do not need to supply guardrailVersion separately when you use the versioned ARN form.
import {
BedrockClient,
CreateGuardrailVersionCommand,
GetGuardrailCommand,
type CreateGuardrailVersionCommandInput,
} from '@aws-sdk/client-bedrock';
import {
BedrockRuntimeClient,
ApplyGuardrailCommand,
} from '@aws-sdk/client-bedrock-runtime';
const controlPlane = new BedrockClient({ region: process.env.AWS_REGION ?? 'us-east-1' });
const runtime = new BedrockRuntimeClient({ region: process.env.AWS_REGION ?? 'us-east-1' });
interface VersionPublishResult {
guardrailId: string;
version: string; // e.g. "2" — always a string, typeof version === "string"
guardrailArn: string; // arn:aws:bedrock:REGION:ACCOUNT:guardrail/ID/VERSION (versioned)
baseArn: string; // arn:aws:bedrock:REGION:ACCOUNT:guardrail/ID (no version suffix)
}
async function publishGuardrailVersion(
guardrailIdentifier: string,
description: string,
clientRequestToken?: string,
): Promise<VersionPublishResult> {
const input: CreateGuardrailVersionCommandInput = {
guardrailIdentifier,
description, // e.g. "v3.0.0 — enabled word blocklist; see DEPLOY-2024-11-27"
// clientRequestToken enables idempotency within a 1-hour window
...(clientRequestToken ? { clientRequestToken } : {}),
};
const response = await controlPlane.send(new CreateGuardrailVersionCommand(input));
// response.version is a string like "1", "2", "3" — NEVER a number
// response.guardrailArn includes the version suffix:
// arn:aws:bedrock:us-east-1:123456789012:guardrail/a1b2c3d4e5f6/2
// The base ARN (no version suffix) is:
// arn:aws:bedrock:us-east-1:123456789012:guardrail/a1b2c3d4e5f6
const versionedArn = response.guardrailArn!;
// Strip version suffix to derive base ARN:
const baseArn = versionedArn.replace(/\/\d+$/, '');
console.log(JSON.stringify({
event: 'guardrail_version_published',
guardrailId: response.guardrailId,
version: response.version,
versionedArn,
baseArn,
description,
timestamp: new Date().toISOString(),
}));
return {
guardrailId: response.guardrailId!,
version: response.version!,
guardrailArn: versionedArn,
baseArn,
};
}
// Using versioned ARN directly — no need to supply guardrailVersion separately
async function scanWithVersionedArn(text: string, versionedArn: string) {
// versionedArn form: arn:aws:bedrock:REGION:ACCOUNT:guardrail/ID/VERSION
const response = await runtime.send(new ApplyGuardrailCommand({
guardrailIdentifier: versionedArn, // Bedrock parses the version from the ARN
guardrailVersion: 'DRAFT', // This is ignored when versioned ARN is used
source: 'INPUT',
content: [{ text: { text } }],
}));
return response.action; // "NONE" | "GUARDRAIL_INTERVENED"
}
// Inspect a specific numeric version's configuration:
async function getVersionConfig(guardrailId: string, version: string) {
const response = await controlPlane.send(new GetGuardrailCommand({
guardrailIdentifier: guardrailId,
guardrailVersion: version, // "1", "2", "DRAFT"
}));
return response;
}
Full deployment workflow — UpdateGuardrailCommand through production deploy
The complete lifecycle for shipping a guardrail policy change to production follows a strict ordering of operations that cannot be safely reordered. The key insight is that UpdateGuardrailCommand does a full replacement — not a merge — of the guardrail's policy config. If you call it with only contentPolicyConfig set and omit topicPolicyConfig, any previously configured topic policies are silently deleted from DRAFT. This means every update must start by reading the current DRAFT configuration with GetGuardrailCommand, merging your changes in application code, and passing the full merged config to UpdateGuardrailCommand.
After updating DRAFT, run a test suite against DRAFT using ApplyGuardrailCommand before snapshotting. This catches misconfigurations before they become an immutable numbered version. Test cases should cover: (a) inputs that must pass through, (b) inputs that must be blocked, and (c) inputs that must be PII-redacted. Asserting the correct action ("NONE" vs "GUARDRAIL_INTERVENED") and the specific assessments sub-fields is more reliable than asserting on the redacted output text, which may change formatting between SDK versions.
Once the test suite passes against DRAFT, call CreateGuardrailVersionCommand to create an immutable snapshot. Write the returned version string to your secrets store or SSM Parameter Store, then trigger a deployment to update the GUARDRAIL_VERSION environment variable read by your MCP server. The MCP server deployment reads the new version at startup and uses it for all subsequent guardrail calls. Never hot-patch a running process's env var — always go through a full deploy to ensure the version change is tracked in your deployment history.
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';
expectPii?: string[]; // PII types that should be detected
label: string;
}
async function fullDeploymentWorkflow(
policyChanges: Partial<UpdateGuardrailCommandInput>,
testCases: TestCase[],
changeDescription: string,
): Promise<{ version: string; passed: boolean; failures: string[] }> {
// Step 1: Read current DRAFT to avoid accidental policy deletion on update
const current = await controlPlane.send(new GetGuardrailCommand({
guardrailIdentifier: GUARDRAIL_ID,
guardrailVersion: 'DRAFT',
}));
// Step 2: Merge changes — UpdateGuardrailCommand requires FULL config
// Omitting a policy type here clears it from DRAFT
const updateInput = {
guardrailIdentifier: GUARDRAIL_ID,
name: current.name!,
description: current.description,
blockedInputMessaging: current.blockedInputMessaging!,
blockedOutputsMessaging: current.blockedOutputsMessaging!,
// Preserve existing policies and overlay changes
contentPolicyConfig: policyChanges.contentPolicyConfig
?? (current.contentPolicy ? {
filtersConfig: current.contentPolicy.filters?.map(f => ({
type: f.type!,
inputStrength: f.inputStrength!,
outputStrength: f.outputStrength!,
})) ?? [],
}
: undefined),
sensitiveInformationPolicyConfig: policyChanges.sensitiveInformationPolicyConfig
?? (current.sensitiveInformationPolicy ? {
piiEntitiesConfig: current.sensitiveInformationPolicy.piiEntities?.map(e => ({
type: e.type!,
action: e.action!,
})) ?? [],
regexesConfig: current.sensitiveInformationPolicy.regexes?.map(r => ({
name: r.name!,
description: r.description,
pattern: r.pattern!,
action: r.action!,
})) ?? [],
}
: undefined),
topicPolicyConfig: policyChanges.topicPolicyConfig
?? (current.topicPolicy ? {
topicsConfig: current.topicPolicy.topics?.map(t => ({
name: t.name!,
definition: t.definition!,
examples: t.examples?.map(e => e.text!),
type: t.type!,
})) ?? [],
}
: undefined),
...policyChanges,
};
await controlPlane.send(new UpdateGuardrailCommand(updateInput));
console.log('DRAFT updated successfully');
// Step 3: Validate DRAFT against test suite 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 } }],
}));
const action = result.action;
if (action !== tc.expectAction) {
failures.push(
`[${tc.label}] expected action="${tc.expectAction}", got action="${action}"`
);
}
if (tc.expectPii && tc.expectPii.length > 0) {
const detectedTypes = result.assessments?.[0]
?.sensitiveInformationPolicy?.piiEntities
?.map(e => e.type!) ?? [];
for (const expectedType of tc.expectPii) {
if (!detectedTypes.includes(expectedType as any)) {
failures.push(`[${tc.label}] expected PII type "${expectedType}" not detected`);
}
}
}
}
if (failures.length > 0) {
console.error('Test suite failed — aborting version creation:', failures);
return { version: '', passed: false, failures };
}
// Step 4: Snapshot DRAFT into an immutable numbered version
const versionResponse = await controlPlane.send(new CreateGuardrailVersionCommand({
guardrailIdentifier: GUARDRAIL_ID,
description: changeDescription,
clientRequestToken: `deploy-${GUARDRAIL_ID}-${Date.now()}`,
}));
const newVersion = versionResponse.version!;
console.log(JSON.stringify({
event: 'guardrail_version_created',
version: newVersion,
guardrailArn: versionResponse.guardrailArn,
description: changeDescription,
testsPassed: testCases.length,
timestamp: new Date().toISOString(),
}));
// Step 5: Push new version to SSM Parameter Store / Secrets Manager
// Then trigger your MCP server redeployment:
// aws ssm put-parameter --name /myapp/GUARDRAIL_VERSION --value "3" --overwrite
// Then: kubectl rollout restart deploy/mcp-server (or ECS force-new-deployment)
return { version: newVersion, passed: true, failures: [] };
}
// Type alias to avoid import error (interface is structural)
type UpdateGuardrailCommandInput = Parameters<typeof controlPlane.send>[0] extends
import('@aws-sdk/client-bedrock').UpdateGuardrailCommand
? ConstructorParameters<typeof import('@aws-sdk/client-bedrock').UpdateGuardrailCommand>[0]
: never;
Version-pinned production pattern and gradual rollout
The simplest production versioning pattern uses a single environment variable: GUARDRAIL_VERSION starts as "1" (the first snapshot you created), and you bump it to "2", "3" etc. as part of each guardrail deployment. Your MCP server reads this variable at startup and uses it for every ConverseCommand and ApplyGuardrailCommand call. Because numbered versions are immutable, a restarted process — after a crash, a scale event, or a cold start — will always use the same policy as the process it replaced, as long as the env var is unchanged.
For MCP servers that handle high-stakes or regulated content, a shadow testing rollout is worth implementing before fully switching to a new guardrail version. The technique: for a configurable percentage of requests, evaluate both the current production version and the new candidate version, log both results, but only act on the production version's result. After collecting enough data to compare the block rates and false-positive rates between versions, switch GUARDRAIL_VERSION over. This catches cases where a new policy is more aggressive than intended and would block legitimate requests that your test suite did not cover.
A common pitfall in the rollout pattern is treating the version as a number in application code. The Bedrock SDK returns version as a string — typeof response.version === "string". If you coerce it to a number anywhere in your config management pipeline (JSON parsing, environment variable handling, database storage), you can accidentally pass a numeric 1 instead of the string "1" to guardrailVersion, which will throw a ValidationException. Store and pass the version as a string at all times.
import {
BedrockRuntimeClient,
ConverseCommand,
ApplyGuardrailCommand,
} from '@aws-sdk/client-bedrock-runtime';
const runtime = new BedrockRuntimeClient({ region: process.env.AWS_REGION ?? 'us-east-1' });
// Version-pinned production config — read once at startup
const GUARDRAIL_ID = process.env.BEDROCK_GUARDRAIL_ID!;
// GUARDRAIL_VERSION is always a string; never parse to number
const GUARDRAIL_VERSION = process.env.GUARDRAIL_VERSION ?? '1';
// Shadow rollout config — set SHADOW_GUARDRAIL_VERSION in a canary deployment
const SHADOW_VERSION = process.env.SHADOW_GUARDRAIL_VERSION;
const SHADOW_SAMPLE_RATE = parseFloat(process.env.SHADOW_SAMPLE_RATE ?? '0.1'); // 10%
async function runGuardrailWithShadow(
text: string,
source: 'INPUT' | 'OUTPUT',
): Promise<'NONE' | 'GUARDRAIL_INTERVENED'> {
// Always run production version — this is the authoritative result
const productionResult = await runtime.send(new ApplyGuardrailCommand({
guardrailIdentifier: GUARDRAIL_ID,
guardrailVersion: GUARDRAIL_VERSION, // e.g. "1" — string, not number
source,
content: [{ text: { text } }],
}));
// Shadow test: fire-and-forget on a sample of requests
if (SHADOW_VERSION && Math.random() < SHADOW_SAMPLE_RATE) {
runtime.send(new ApplyGuardrailCommand({
guardrailIdentifier: GUARDRAIL_ID,
guardrailVersion: SHADOW_VERSION, // e.g. "2"
source,
content: [{ text: { text } }],
})).then(shadowResult => {
const productionAction = productionResult.action;
const shadowAction = shadowResult.action;
if (productionAction !== shadowAction) {
// Log divergence for analysis — do NOT block based on shadow result
console.log(JSON.stringify({
event: 'guardrail_shadow_divergence',
productionVersion: GUARDRAIL_VERSION,
shadowVersion: SHADOW_VERSION,
productionAction,
shadowAction,
source,
inputLength: text.length,
timestamp: new Date().toISOString(),
}));
} else {
console.log(JSON.stringify({
event: 'guardrail_shadow_match',
productionVersion: GUARDRAIL_VERSION,
shadowVersion: SHADOW_VERSION,
action: productionAction,
}));
}
}).catch(err => {
// Shadow errors must never affect production path
console.warn('Shadow guardrail error (ignored):', err.message);
});
}
// Return only the production result
return productionResult.action as 'NONE' | 'GUARDRAIL_INTERVENED';
}
// Version-pinned Converse helper — env var determines guardrail version
async function converseWithPinnedGuardrail(
modelId: string,
userMessage: string,
): Promise<{ blocked: boolean; text: string }> {
const response = await runtime.send(new ConverseCommand({
modelId,
messages: [{ role: 'user', content: [{ text: userMessage }] }],
guardrailConfig: {
guardrailIdentifier: GUARDRAIL_ID,
guardrailVersion: GUARDRAIL_VERSION, // pinned string, e.g. "1"
trace: 'ENABLED',
},
inferenceConfig: { maxTokens: 1024 },
}));
if (response.stopReason === 'guardrail_intervened') {
return { blocked: true, text: 'Request blocked by content policy.' };
}
const text = response.output?.message?.content
?.filter((b): b is { text: string } => 'text' in b)
.map(b => b.text)
.join('') ?? '';
return { blocked: false, text };
}
ApplyGuardrailCommand — scanning without a foundation model call
ApplyGuardrailCommand is the most underused capability in the Bedrock Guardrails API. It applies a guardrail's full policy suite — content filters, PII detection, topic blocking, word lists — to any text without invoking any foundation model. This makes it ideal for three scenarios that come up repeatedly in MCP server deployments: (a) validating user-supplied tool arguments before passing them to downstream services; (b) scanning webhook payloads received from external systems (Slack events, GitHub webhooks, Zapier triggers) before processing their content; and (c) scanning tool results returned by external APIs before incorporating them into an LLM conversation context.
ApplyGuardrailCommand lives in @aws-sdk/client-bedrock-runtime — the same package as ConverseCommand, not the control-plane @aws-sdk/client-bedrock package. This catches developers who have only imported the control-plane client. The request requires four parameters: guardrailIdentifier (ID or ARN), guardrailVersion (numeric string or "DRAFT"), source ("INPUT" for content you are receiving, "OUTPUT" for content you are about to send), and content — an array of content blocks.
The response's action field is either "NONE" (guardrail did not intervene) or "GUARDRAIL_INTERVENED" (at least one policy fired). The outputs array contains the same number of entries as your input content array — if PII anonymization is configured, PII entities in the output text are replaced with tokens like [EMAIL] or [PHONE]. The assessments array contains per-content-block assessment details. The usage object contains billing counters: topicPolicyUnits, contentPolicyUnits, wordPolicyUnits, sensitiveInformationPolicyUnits, contextualGroundingPolicyUnits, and contentPolicyImageUnits. ApplyGuardrailCommand is billed per unit processed — track these usage fields the same way you track token usage from ConverseCommand.
import {
BedrockRuntimeClient,
ApplyGuardrailCommand,
type ApplyGuardrailResponse,
} from '@aws-sdk/client-bedrock-runtime';
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';
interface ScanResult {
action: 'NONE' | 'GUARDRAIL_INTERVENED';
redactedText: string;
blocked: boolean;
assessmentSummary: {
topicViolations: string[];
contentViolations: Array<{ type: string; confidence: string }>;
piiDetected: string[];
wordViolations: string[];
};
usage: {
topicPolicyUnits: number;
contentPolicyUnits: number;
wordPolicyUnits: number;
sensitiveInformationPolicyUnits: number;
contextualGroundingPolicyUnits: number;
contentPolicyImageUnits: number;
};
}
// Scan a webhook payload before processing — no model call, no model cost
async function scanWebhookPayload(
payload: string,
source: 'INPUT' | 'OUTPUT' = 'INPUT',
): Promise<ScanResult> {
const response: ApplyGuardrailResponse = await runtime.send(new ApplyGuardrailCommand({
guardrailIdentifier: GUARDRAIL_ID,
guardrailVersion: GUARDRAIL_VERSION,
source,
content: [{ text: { text: payload } }],
}));
const assessment = response.assessments?.[0] ?? {};
const topicViolations = (assessment.topicPolicy?.topics ?? [])
.filter(t => t.action === 'BLOCKED')
.map(t => t.name ?? 'unknown');
const contentViolations = (assessment.contentPolicy?.filters ?? [])
.filter(f => f.action === 'BLOCKED')
.map(f => ({ type: f.type ?? 'UNKNOWN', confidence: f.confidence ?? 'NONE' }));
const piiDetected = (assessment.sensitiveInformationPolicy?.piiEntities ?? [])
.filter(e => e.action === 'ANONYMIZED' || e.action === 'BLOCKED')
.map(e => e.type ?? 'UNKNOWN');
const wordViolations = [
...(assessment.wordPolicy?.customWords ?? [])
.filter(w => w.action === 'BLOCKED')
.map(w => w.match ?? ''),
...(assessment.wordPolicy?.managedWordLists ?? [])
.filter(w => w.action === 'BLOCKED')
.map(w => w.match ?? ''),
];
const u = response.usage ?? {};
return {
action: response.action as 'NONE' | 'GUARDRAIL_INTERVENED',
redactedText: response.outputs?.[0]?.text ?? payload,
blocked: response.action === 'GUARDRAIL_INTERVENED',
assessmentSummary: { topicViolations, contentViolations, piiDetected, wordViolations },
usage: {
topicPolicyUnits: u.topicPolicyUnits ?? 0,
contentPolicyUnits: u.contentPolicyUnits ?? 0,
wordPolicyUnits: u.wordPolicyUnits ?? 0,
sensitiveInformationPolicyUnits: u.sensitiveInformationPolicyUnits ?? 0,
contextualGroundingPolicyUnits: u.contextualGroundingPolicyUnits ?? 0,
contentPolicyImageUnits: u.contentPolicyImageUnits ?? 0,
},
};
}
// Scan a tool result from an external API before incorporating into conversation
async function scanToolResult(toolName: string, toolOutput: string): Promise<string> {
const scan = await scanWebhookPayload(toolOutput, 'OUTPUT');
if (scan.blocked) {
console.warn(JSON.stringify({
event: 'tool_result_blocked_by_guardrail',
toolName,
violations: scan.assessmentSummary,
usage: scan.usage,
timestamp: new Date().toISOString(),
}));
return `[Tool result from ${toolName} was blocked by content policy and cannot be displayed]`;
}
// Return redacted text — PII has been replaced with tokens if anonymization is configured
return scan.redactedText;
}
// MCP tool handler: scan input, run tool, scan output
export async function handleSearchTool(query: string): Promise<string> {
// 1. Scan user query before processing
const inputScan = await scanWebhookPayload(query, 'INPUT');
if (inputScan.blocked) {
return 'Query blocked by content policy.';
}
// 2. Use redacted query (PII stripped) for downstream search
const safeQuery = inputScan.redactedText;
const searchResult = await callExternalSearchApi(safeQuery);
// 3. Scan search result before returning to MCP client
return scanToolResult('external-search', searchResult);
}
async function callExternalSearchApi(query: string): Promise<string> {
// Placeholder: replace with your actual search API call
return `Search results for: ${query}`;
}
ListGuardrailsCommand — version history and audit queries
ListGuardrailsCommand returns all guardrails in your account for a given region. It supports pagination via nextToken but does not natively filter to a specific guardrail's version history — when called without a guardrailIdentifier parameter, it returns one entry per guardrail showing only the DRAFT version metadata. To list all versions of a specific guardrail, pass guardrailIdentifier in the request; Bedrock then returns one entry per version including DRAFT and all numbered snapshots, each with its version, description, createdAt, and updatedAt timestamps.
The version history from ListGuardrailsCommand is useful for auditing: you can see when each version was created, what description was supplied, and which versions are currently active. Use this for compliance reporting — a regulator asking "what content policy was in effect on a given date" can be answered by comparing the version createdAt timestamps against your deployment history to determine which version was active at the time of a specific request.
Note that ListGuardrailsCommand is in the control-plane package (@aws-sdk/client-bedrock), not the runtime package. The control-plane and runtime clients use separate IAM action namespaces: control-plane operations require bedrock:GetGuardrail, bedrock:ListGuardrails, bedrock:CreateGuardrailVersion etc., while runtime operations require bedrock:ApplyGuardrail. MCP server execution roles typically only need the runtime permission; deployment pipeline IAM roles need the control-plane permissions.
import {
BedrockClient,
ListGuardrailsCommand,
type GuardrailSummary,
} from '@aws-sdk/client-bedrock';
const controlPlane = new BedrockClient({ region: process.env.AWS_REGION ?? 'us-east-1' });
interface VersionHistoryEntry {
version: string; // "DRAFT", "1", "2", ...
description?: string;
createdAt: Date;
updatedAt: Date;
status: string;
}
// List all versions of a specific guardrail — pass guardrailIdentifier to filter
async function listGuardrailVersions(guardrailId: string): Promise<VersionHistoryEntry[]> {
const versions: VersionHistoryEntry[] = [];
let nextToken: string | undefined;
do {
const response = await controlPlane.send(new ListGuardrailsCommand({
guardrailIdentifier: guardrailId, // filter to this guardrail's versions
maxResults: 50,
...(nextToken ? { nextToken } : {}),
}));
for (const summary of response.guardrails ?? []) {
versions.push({
version: summary.version ?? 'UNKNOWN',
description: summary.description,
createdAt: summary.createdAt ?? new Date(0),
updatedAt: summary.updatedAt ?? new Date(0),
status: summary.status ?? 'UNKNOWN',
});
}
nextToken = response.nextToken;
} while (nextToken);
// Sort by version — DRAFT last, numbers ascending
return versions.sort((a, b) => {
if (a.version === 'DRAFT') return 1;
if (b.version === 'DRAFT') return -1;
return parseInt(a.version, 10) - parseInt(b.version, 10);
});
}
// Print version history table for audit or deployment review
async function printVersionHistory(guardrailId: string) {
const history = await listGuardrailVersions(guardrailId);
console.log(`\nGuardrail version history for ${guardrailId}:`);
console.log('Version | Status | Created | Description');
console.log('---------|-----------|----------------------|-----------------------------------');
for (const entry of history) {
const created = entry.createdAt.toISOString().slice(0, 19).replace('T', ' ');
const desc = (entry.description ?? '(no description)').slice(0, 36);
const version = entry.version.padEnd(8);
const status = entry.status.padEnd(9);
console.log(`${version} | ${status} | ${created} | ${desc}`);
}
}
// Find which version was active at a given timestamp
// (requires your deployment system to record when each version was deployed)
function findActiveVersionAtTime(
history: VersionHistoryEntry[],
deploymentLog: Array<{ version: string; deployedAt: Date }>,
targetTime: Date,
): string | null {
// Sort deployments chronologically
const sorted = [...deploymentLog].sort(
(a, b) => a.deployedAt.getTime() - b.deployedAt.getTime()
);
// Find the last deployment before or at targetTime
let activeVersion: string | null = null;
for (const deploy of sorted) {
if (deploy.deployedAt <= targetTime) {
activeVersion = deploy.version;
}
}
return activeVersion;
}
DeleteGuardrailVersionCommand and DeleteGuardrailCommand — constraints and dangers
DeleteGuardrailVersionCommand deletes a single numbered version of a guardrail. It requires two parameters: guardrailIdentifier (ID or ARN) and guardrailVersion (the numeric string to delete). You cannot delete the DRAFT version with this command — DRAFT exists as long as the guardrail exists. You also cannot delete a version if callers are actively using it, though this is best-effort: Bedrock does not maintain a lock or reference-count mechanism, so the constraint is advisory rather than enforced. In practice, if you delete version "1" while a running MCP server instance still uses it, the next guardrail API call from that instance will fail with a ResourceNotFoundException.
DeleteGuardrailCommand (without a version parameter) is significantly more dangerous: it deletes the entire guardrail resource including DRAFT and all numbered versions simultaneously. There is no confirmation prompt, no recycle bin, no soft delete, and no undo. The operation is immediate and irreversible. If your execution environment has bedrock:DeleteGuardrail in its IAM policy and that permission is broader than intended — for example, the resource ARN is * instead of a specific guardrail ARN — a misconfigured script or a compromised dependency could permanently destroy your production guardrail configuration. Restrict this permission to deployment pipeline IAM roles only, not to the execution role used by running MCP server instances.
The correct cleanup pattern for retiring an old version is: (a) verify no running process uses the version (check your deployment records), (b) delete the version with DeleteGuardrailVersionCommand, and (c) log the deletion with a timestamp and the actor's identity. For full guardrail deletion as part of a service teardown, run ListGuardrailsCommand first to confirm you have the right guardrail ID, then delete after confirming no active traffic.
import {
BedrockClient,
DeleteGuardrailVersionCommand,
DeleteGuardrailCommand,
ListGuardrailsCommand,
} from '@aws-sdk/client-bedrock';
const controlPlane = new BedrockClient({ region: process.env.AWS_REGION ?? 'us-east-1' });
// Safe: delete a single numbered version
async function deleteGuardrailVersion(
guardrailId: string,
version: string, // numeric string e.g. "1" — cannot be "DRAFT"
actor: string, // who is performing the deletion, for audit log
) {
if (version === 'DRAFT') {
throw new Error('Cannot delete DRAFT version — delete the entire guardrail to remove DRAFT');
}
// Check whether any running deployment still uses this version
// This is a best-effort check — Bedrock has no reference-counting lock
const activeDeployments = await checkActiveDeployments(guardrailId, version);
if (activeDeployments.length > 0) {
throw new Error(
`Version "${version}" is still referenced by: ${activeDeployments.join(', ')}. ` +
`Redeploy those services to a newer version before deleting.`
);
}
await controlPlane.send(new DeleteGuardrailVersionCommand({
guardrailIdentifier: guardrailId,
guardrailVersion: version,
}));
console.log(JSON.stringify({
event: 'guardrail_version_deleted',
guardrailId,
version,
actor,
timestamp: new Date().toISOString(),
}));
}
// DESTRUCTIVE: delete entire guardrail (all versions + DRAFT)
// Use only during full service teardown — no recycle bin, no undo
async function deleteEntireGuardrail(
guardrailId: string,
actor: string,
confirmationToken: string, // require caller to pass guardrailId as confirmation
) {
if (confirmationToken !== guardrailId) {
throw new Error(
`Confirmation token mismatch. Pass guardrailId="${guardrailId}" as confirmationToken to confirm deletion.`
);
}
// Verify ID before deletion by listing — prevents wildcard ARN mistakes
const list = await controlPlane.send(new ListGuardrailsCommand({
guardrailIdentifier: guardrailId,
}));
const found = list.guardrails?.find(g => g.id === guardrailId || g.arn?.includes(guardrailId));
if (!found) {
throw new Error(`Guardrail "${guardrailId}" not found — aborting deletion`);
}
console.warn(JSON.stringify({
event: 'guardrail_full_delete_initiated',
guardrailId,
actor,
guardrailName: found.name,
timestamp: new Date().toISOString(),
}));
await controlPlane.send(new DeleteGuardrailCommand({
guardrailIdentifier: guardrailId,
// No guardrailVersion param — deletes ALL versions including DRAFT
}));
console.warn(JSON.stringify({
event: 'guardrail_full_delete_completed',
guardrailId,
actor,
timestamp: new Date().toISOString(),
}));
}
// Placeholder: query your deployment system for active version references
async function checkActiveDeployments(
guardrailId: string,
version: string,
): Promise<string[]> {
// In practice: query your config store (SSM, Consul, etc.) for all running
// instances and their GUARDRAIL_VERSION env var value
return []; // return service names that still reference this version
}
Production gotchas
The following are specific, non-obvious failure modes that occur regularly in MCP server deployments using Bedrock Guardrails versioning:
1. DRAFT in production means any developer immediately affects all callers. UpdateGuardrailCommand modifies DRAFT synchronously. If your production GUARDRAIL_VERSION env var is set to "DRAFT", any guardrail edit — including a typo that accidentally removes a topic policy or lowers a content filter threshold — takes effect immediately on all running production instances. There is no deployment gate, no approval workflow, and no way to roll back without re-applying the previous configuration manually. Always use a numeric version in production.
2. Version numbers are strings, not integers. typeof response.version === "string". The Bedrock SDK types version as string throughout. If your CI/CD pipeline serializes the version to JSON and reads it back, a JSON parser will not auto-convert "1" to a number, but AWS CDK outputs, SSM Parameter Store reads, and some ORMs may coerce it. Passing guardrailVersion: 1 (number) instead of guardrailVersion: "1" (string) throws a ValidationException: 1 validation error detected: 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.
3. UpdateGuardrailCommand replaces the entire guardrail config. There is no partial-update or patch operation. If you call UpdateGuardrailCommand with only contentPolicyConfig and omit topicPolicyConfig, all topic policies are silently deleted from DRAFT. The API returns 200 OK with no warning. The correct pattern is to always read the current DRAFT first with GetGuardrailCommand, merge your changes in memory, and pass the full merged config to UpdateGuardrailCommand.
4. ApplyGuardrailCommand is in the runtime package, not the control-plane package. A common mistake is importing ApplyGuardrailCommand from @aws-sdk/client-bedrock (the control-plane package used for CreateGuardrailVersionCommand, ListGuardrailsCommand, etc.). ApplyGuardrailCommand lives in @aws-sdk/client-bedrock-runtime alongside ConverseCommand, and you must use a BedrockRuntimeClient instance to call it. The IAM action is also different: control-plane operations use bedrock:* actions; ApplyGuardrailCommand requires bedrock:ApplyGuardrail on the runtime.
5. There is no "current production version" pointer in Bedrock. Bedrock has no concept of a "promoted" or "stable" version that you can query. There is no GetCurrentProductionVersion API. Your application code is fully responsible for managing the mapping between environments and version strings. If two MCP server deployments (staging and production) are using different guardrail versions, the only way to know this is to compare your deployment records. Build version tracking into your config management system from the start, not as an afterthought.
6. GetGuardrailCommand returns regexesConfig patterns — be careful with logging. When you inspect a guardrail's configuration via GetGuardrailCommand, the response includes the full sensitiveInformationPolicyConfig.regexesConfig array with the actual regex pattern strings your guardrail uses to match sensitive data. If your debug logging pipeline captures the full GetGuardrailCommand response, you are logging your data-matching patterns in plaintext — which could be used to craft inputs that evade detection. Redact the regexesConfig[].pattern fields before logging, or avoid logging GetGuardrailCommand responses in production environments.
7. DeleteGuardrailCommand (no version) deletes all versions without confirmation. Unlike many AWS delete operations, DeleteGuardrailCommand has no mandatory confirmation parameter, no MFA delete requirement, and no soft-delete / recycle bin. It immediately and permanently deletes the guardrail and all versions. Restrict the bedrock:DeleteGuardrail IAM action to deployment pipeline roles with strict human-in-the-loop approval, never to the execution role used by running MCP server processes.
8. ApplyGuardrailCommand incurs usage charges per unit — track the usage response field. Every ApplyGuardrailCommand call is billed independently of model inference costs. The usage object in the response contains topicPolicyUnits, contentPolicyUnits, wordPolicyUnits, sensitiveInformationPolicyUnits, contextualGroundingPolicyUnits, and contentPolicyImageUnits — each is billed at a separate per-unit rate. MCP servers that call ApplyGuardrailCommand on every tool input and tool output can generate 2-4x the number of guardrail API calls relative to servers that only use guardrailConfig on ConverseCommand. Aggregate these usage counters per tool call and log them alongside model token usage for accurate cost attribution.
// Gotcha 2 illustration: version-as-string enforcement
const rawVersion = process.env.GUARDRAIL_VERSION; // e.g. "2"
// WRONG: coercing to number will cause ValidationException
// const version = Number(rawVersion); // 2 (number) — breaks the API call
// CORRECT: always keep as string
const version: string = rawVersion ?? '1';
// Defensive check at startup:
if (!/^([1-9][0-9]{0,7}|DRAFT)$/.test(version)) {
throw new Error(
`Invalid GUARDRAIL_VERSION="${version}". Must be "DRAFT" or a positive integer string like "1", "2".`
);
}
// Gotcha 8 illustration: accumulate usage costs from ApplyGuardrail
interface GuardrailUsageAccumulator {
topicPolicyUnits: number;
contentPolicyUnits: number;
wordPolicyUnits: number;
sensitiveInformationPolicyUnits: number;
contextualGroundingPolicyUnits: number;
contentPolicyImageUnits: number;
callCount: number;
}
const sessionUsage: GuardrailUsageAccumulator = {
topicPolicyUnits: 0,
contentPolicyUnits: 0,
wordPolicyUnits: 0,
sensitiveInformationPolicyUnits: 0,
contextualGroundingPolicyUnits: 0,
contentPolicyImageUnits: 0,
callCount: 0,
};
function accumulateGuardrailUsage(
usage: Partial<GuardrailUsageAccumulator> | undefined,
acc: GuardrailUsageAccumulator,
) {
if (!usage) return;
acc.topicPolicyUnits += usage.topicPolicyUnits ?? 0;
acc.contentPolicyUnits += usage.contentPolicyUnits ?? 0;
acc.wordPolicyUnits += usage.wordPolicyUnits ?? 0;
acc.sensitiveInformationPolicyUnits += usage.sensitiveInformationPolicyUnits ?? 0;
acc.contextualGroundingPolicyUnits += usage.contextualGroundingPolicyUnits ?? 0;
acc.contentPolicyImageUnits += usage.contentPolicyImageUnits ?? 0;
acc.callCount += 1;
}
AliveMCP and guardrail version drift
When a Bedrock Guardrail version is deleted or reconfigured mid-deployment, MCP server tools start returning unexpected blocked responses or ResourceNotFoundException errors — from the outside, this is indistinguishable from an MCP server outage. AliveMCP monitors your MCP server endpoints continuously and surfaces these error spikes immediately, letting you correlate guardrail version changes with tool failure rates before users notice degraded behavior.