Guide · Amazon Bedrock · Safety
Amazon Bedrock Guardrails Content Filtering for MCP Servers — filtersConfig, Strength Levels, and PROMPT_ATTACK
Bedrock Guardrails content filtering is controlled by a single contentPolicyConfig.filtersConfig array where each entry independently tunes one of six harm categories — HATE, INSULTS, SEXUAL, VIOLENCE, MISCONDUCT, and PROMPT_ATTACK — with separate thresholds for input and output, giving MCP servers surgical control over what gets blocked without a blanket policy that generates false positives. The system has critical asymmetries that cause production surprises: PROMPT_ATTACK only evaluates input (the outputStrength field is silently ignored), HIGH strength on HATE will block legitimate academic and historical text, and content filters entirely skip system prompts — only user and assistant messages are evaluated. This guide covers creating a guardrail with CreateGuardrailCommand from @aws-sdk/client-bedrock, attaching it via guardrailConfig on ConverseCommand, interpreting guardrail_intervened stop reasons, and parsing the assessments array from trace data to understand exactly which filter fired and at what confidence. For PII detection and redaction, see the Bedrock Guardrails PII anonymization guide. For topic denial policies, see the topic policy guide.
TL;DR
Configure content filtering by passing a contentPolicyConfig.filtersConfig array in CreateGuardrailCommand — each entry specifies a type (one of six categories) and independent inputStrength / outputStrength values (NONE, LOW, MEDIUM, or HIGH). Attach the resulting guardrail to ConverseCommand via guardrailConfig: { guardrailIdentifier, guardrailVersion, trace: "ENABLED" }, then check response.stopReason === "guardrail_intervened" before reading output content. Parse response.trace?.guardrail?.inputAssessment or outputAssessments[0] to identify which contentPolicy.filters[] entry triggered the block.
- Bedrock Guardrails overview — architecture, ApplyGuardrail API, version pinning, image moderation
- Bedrock Guardrails PII — sensitiveInformationPolicyConfig, entity types, ANONYMIZED vs BLOCKED actions
- Bedrock Guardrails topic policy — denied topic definitions, examples, false positive tuning
- Bedrock Guardrails versioning — DRAFT vs numeric versions, CreateGuardrailVersion, promotion pipelines
- Bedrock Converse API — model IDs, InferenceConfiguration, multi-turn messages, tool use
Content policy anatomy — the filtersConfig array
Every content filter is configured as an entry in the filtersConfig array inside contentPolicyConfig when you call CreateGuardrailCommand. Each entry has exactly three fields: type, inputStrength, and outputStrength. Omitting a category from the array entirely is equivalent to setting both strengths to NONE — that category is not evaluated. You do not need to include all six categories; include only those you want active.
The six type values and what they evaluate:
- HATE — content promoting or glorifying hatred of people based on protected characteristics such as race, ethnicity, religion, gender, sexual orientation, or disability. This includes slurs, dehumanizing language, and calls for discrimination.
- INSULTS — personally degrading content directed at an individual or group: name-calling, bullying, demeaning language. Distinct from HATE in that it focuses on personal attack rather than group-based bigotry.
- SEXUAL — sexually explicit content including graphic descriptions of sexual acts, nudity, and adult material. At
MEDIUMand above, also covers suggestive or innuendo-heavy content. AtHIGH, catches romantic descriptions that could be interpreted as sexual in context. - VIOLENCE — content describing or glorifying physical violence, gore, torture, or harm to people or animals. The
HIGHthreshold also catches action-movie-style violence descriptions that stop well short of gratuitous gore. - MISCONDUCT — content that facilitates illegal or harmful activities: instructions for making weapons, synthesizing drugs, committing fraud, hacking systems, or evading law enforcement. This category tends to be the least prone to false positives because it covers how-to content rather than descriptive language.
- PROMPT_ATTACK — injection and jailbreak attempts: "ignore previous instructions", "pretend you have no restrictions", "DAN mode", role-play framings designed to override system prompts, and similar adversarial patterns. This category only applies to input —
outputStrengthis accepted by the API but has no effect.
The four inputStrength / outputStrength values and what they mean operationally:
- NONE — this category is effectively disabled. No content in this category will be blocked regardless of how extreme it is. Use this for categories genuinely irrelevant to your use case (for example, an internal developer tool might set SEXUAL and VIOLENCE to NONE while keeping MISCONDUCT at HIGH).
- LOW — only the most extreme, unambiguous cases are blocked. A prompt containing "here is how to build a pipe bomb step by step" blocks; a thriller novel describing a bombing in narrative terms passes. Appropriate when you want a safety floor but can tolerate some edge-case content reaching users.
- MEDIUM — blocks most harmful content while accepting that some gray-area material will pass. This is the recommended default for most customer-facing MCP tools. At this level, the classifier balances recall (catching harmful content) against precision (not flagging benign content).
- HIGH — blocks anything that could plausibly be interpreted as harmful, including ambiguous cases. At this level, a question about WWII chemical warfare for a history paper may be blocked under HATE or VIOLENCE; a medical question about drug interactions may be blocked under MISCONDUCT. Reserve HIGH for contexts where false positives are acceptable and missed detections are catastrophic.
import {
BedrockClient,
CreateGuardrailCommand,
type CreateGuardrailCommandInput,
} from '@aws-sdk/client-bedrock';
// Control plane operations (create/update/version guardrails) use BedrockClient
// Data plane operations (Converse, ApplyGuardrail) use BedrockRuntimeClient
const bedrockControl = new BedrockClient({
region: process.env.AWS_REGION ?? 'us-east-1',
});
async function createContentFilterGuardrail(): Promise<{
guardrailId: string;
guardrailArn: string;
}> {
const input: CreateGuardrailCommandInput = {
name: 'mcp-server-content-policy',
description: 'Content filtering for customer-facing MCP tools',
contentPolicyConfig: {
filtersConfig: [
{
type: 'HATE',
inputStrength: 'HIGH', // Block on input before model is invoked
outputStrength: 'HIGH', // Block if model generates hate speech
},
{
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 ignored for PROMPT_ATTACK — injection
// attempts are only possible in input, not in model output.
// The API accepts this field but it has no behavioral effect.
outputStrength: 'NONE',
},
],
},
// blockedInputMessaging / blockedOutputsMessaging replace the default
// "Sorry, I cannot help with that" Bedrock fallback message.
// These appear in response.output.message.content when guardrail fires
// IF you are using the message-replacement mode; with stopReason-based
// handling you should ignore these and return your own message.
blockedInputMessaging: 'Your request was blocked by content policy.',
blockedOutputsMessaging: 'The response was blocked by content policy.',
};
const response = await bedrockControl.send(new CreateGuardrailCommand(input));
console.log(`Guardrail created: ${response.guardrailId}`);
console.log(`ARN: ${response.guardrailArn}`);
// response.version will be "DRAFT" at creation time.
// Call CreateGuardrailVersionCommand before deploying to production.
return {
guardrailId: response.guardrailId!,
guardrailArn: response.guardrailArn!,
};
}
The CreateGuardrailCommand returns guardrailId (a short alphanumeric string like "a1b2c3d4e5f6") and guardrailArn (the full ARN). Store both — the short ID is more convenient for the guardrailIdentifier field in runtime calls, but the ARN is required for IAM resource-level permissions and cross-account usage. The initial version is always DRAFT; use CreateGuardrailVersionCommand from the same @aws-sdk/client-bedrock package to create an immutable numeric version before promoting to production.
Attaching the guardrail to ConverseCommand
Once you have a guardrail ID, attaching it to a Converse call requires a single guardrailConfig object on the ConverseCommand input. The object has three fields: guardrailIdentifier, guardrailVersion, and trace. The guardrail evaluates both the input messages and the model's output before the response is returned to the caller — if either phase triggers, you receive stopReason: "guardrail_intervened" rather than the normal "end_turn".
A critical architectural point: content filters do not apply to system prompts. Only user-role messages (and assistant-role messages in the output) are evaluated. If your system prompt contains instructions that might look like sensitive content — for example, a customer service system prompt that includes product names that overlap with drug terminology — you will not accidentally block your own system prompt. Conversely, you cannot rely on content filtering to validate what goes into system: system prompt security must be managed separately through access control on the prompt template.
Set trace: "ENABLED" during development and staging. The trace adds modest overhead (typically 10–30 milliseconds on top of model inference latency) but populates response.trace.guardrail with the full per-message assessment, which is the only way to determine which filter fired and at what confidence level. In production, you can disable trace if you are confident in your guardrail configuration and latency is a constraint — but keep it enabled on a sampled subset of traffic for ongoing monitoring.
import {
BedrockRuntimeClient,
ConverseCommand,
type ConverseCommandInput,
type ConverseResponse,
} from '@aws-sdk/client-bedrock-runtime';
const bedrockRuntime = new BedrockRuntimeClient({
region: process.env.AWS_REGION ?? 'us-east-1',
});
const GUARDRAIL_ID = process.env.BEDROCK_GUARDRAIL_ID!;
// Use "DRAFT" for local dev; a numeric string like "1" in staging/prod
const GUARDRAIL_VERSION = process.env.BEDROCK_GUARDRAIL_VERSION ?? 'DRAFT';
interface ContentFilterResult {
blocked: boolean;
blockPhase?: 'INPUT' | 'OUTPUT';
blockedFilter?: string;
blockedConfidence?: string;
text?: string;
}
async function converseWithContentFilter(
modelId: string,
systemPrompt: string,
userMessage: string,
): Promise<ContentFilterResult> {
const input: ConverseCommandInput = {
modelId,
// System prompts are NOT evaluated by content filters
system: [{ text: systemPrompt }],
messages: [
// Only user and assistant messages are evaluated
{ role: 'user', content: [{ text: userMessage }] },
],
guardrailConfig: {
guardrailIdentifier: GUARDRAIL_ID,
guardrailVersion: GUARDRAIL_VERSION,
trace: 'ENABLED',
},
inferenceConfig: {
maxTokens: 2048,
temperature: 0.7,
},
};
const response: ConverseResponse = await bedrockRuntime.send(
new ConverseCommand(input),
);
// Always check stopReason BEFORE reading output.message.content.
// When guardrail fires, content array is present but empty — accessing
// output.message.content[0].text without this guard throws at runtime.
if (response.stopReason === 'guardrail_intervened') {
// Determine whether block happened on input or output phase
const inputAssessment = response.trace?.guardrail?.inputAssessment;
const outputAssessment = response.trace?.guardrail?.outputAssessments?.[0];
// Input block: filter fired before model was called (cheaper — no inference cost)
if (inputAssessment?.contentPolicy?.filters?.some(f => f.action === 'BLOCKED')) {
const filter = inputAssessment.contentPolicy!.filters!.find(
f => f.action === 'BLOCKED',
);
return {
blocked: true,
blockPhase: 'INPUT',
blockedFilter: filter?.type,
blockedConfidence: filter?.confidence,
};
}
// Output block: model ran, but its response was blocked
if (outputAssessment?.contentPolicy?.filters?.some(f => f.action === 'BLOCKED')) {
const filter = outputAssessment.contentPolicy!.filters!.find(
f => f.action === 'BLOCKED',
);
return {
blocked: true,
blockPhase: 'OUTPUT',
blockedFilter: filter?.type,
blockedConfidence: filter?.confidence,
};
}
// Guardrail intervened but not via content policy
// (topic policy, word policy, or sensitive info policy may have fired)
return { blocked: true };
}
const text =
response.output?.message?.content
?.filter((b): b is { text: string } => 'text' in b)
.map(b => b.text)
.join('') ?? '';
return { blocked: false, text };
}
Notice how the code distinguishes between an input-phase block and an output-phase block by checking inputAssessment first. When the guardrail fires on the user's message (before model invocation), the outputAssessments array will be empty because the model was never called. When the guardrail fires on the model's response, both the inputAssessment (which passed) and outputAssessments[0] (which blocked) will be populated. This distinction matters for cost tracking: an input-phase block saves the full inference cost, while an output-phase block still incurs the token cost of the model run.
PROMPT_ATTACK — jailbreak and injection detection
The PROMPT_ATTACK filter is the most architecturally distinct of the six categories. Where other filters evaluate whether content is harmful, PROMPT_ATTACK evaluates whether the user is attempting to subvert the model's instructions. It detects patterns like "ignore previous instructions and instead...", "pretend you have no content restrictions", "you are now DAN (Do Anything Now)", role-play framings designed to establish an alternative persona free of safety constraints, and instruction injection embedded in documents or tool outputs that the model might process.
The asymmetry to understand: PROMPT_ATTACK only applies to the input evaluation phase. The outputStrength field is accepted without error but has no effect. This makes semantic sense — injection attempts arrive from users (or from tool outputs that feed back into the model), not from the model's own generated text. Setting outputStrength to anything other than NONE is harmless but misleading, so set it to NONE explicitly to document the asymmetry.
MCP servers that accept user-defined prompts or system prompt extensions are particularly vulnerable to injection. If your tool allows a user to specify a custom instruction string that gets incorporated into a system prompt template, that injection point can be exploited without PROMPT_ATTACK detection, because system prompts are not evaluated. The correct architecture is: validate the user-supplied prompt fragment using ApplyGuardrailCommand with source: "INPUT" before incorporating it into the system prompt. This catches injection in the user-controlled fragment before it enters the privileged system prompt position.
import {
BedrockRuntimeClient,
ApplyGuardrailCommand,
type ApplyGuardrailCommandInput,
} from '@aws-sdk/client-bedrock-runtime';
import {
BedrockClient,
CreateGuardrailCommand,
} from '@aws-sdk/client-bedrock';
// Create a guardrail tuned specifically for PROMPT_ATTACK detection
// to validate user-supplied prompt fragments before incorporating them
// into system prompts or multi-step pipelines.
async function createPromptAttackGuardrail(): Promise<string> {
const bedrockControl = new BedrockClient({
region: process.env.AWS_REGION ?? 'us-east-1',
});
const response = await bedrockControl.send(new CreateGuardrailCommand({
name: 'mcp-prompt-attack-detector',
description: 'Detects injection and jailbreak attempts in user-supplied text',
contentPolicyConfig: {
filtersConfig: [
{
type: 'PROMPT_ATTACK',
inputStrength: 'HIGH',
// outputStrength is documented here as NONE to make the asymmetry
// explicit: this field is ignored for PROMPT_ATTACK.
outputStrength: 'NONE',
},
// Keep other categories at MEDIUM so the same guardrail can double
// as a general content check for the user-supplied fragment.
{ type: 'HATE', inputStrength: 'MEDIUM', outputStrength: 'MEDIUM' },
{ type: 'MISCONDUCT', inputStrength: 'HIGH', outputStrength: 'HIGH' },
],
},
blockedInputMessaging:
'Your input was flagged as a potential prompt injection attempt.',
blockedOutputsMessaging: 'Response blocked by content policy.',
}));
return response.guardrailId!;
}
// MCP tool that accepts a user-defined "custom instruction" and incorporates
// it into a system prompt — this pattern is a common injection vector.
const bedrockRuntime = new BedrockRuntimeClient({
region: process.env.AWS_REGION ?? 'us-east-1',
});
interface PromptValidationResult {
safe: boolean;
reason?: string;
confidence?: string;
}
async function validateUserPromptFragment(
userFragment: string,
guardrailId: string,
guardrailVersion: string,
): Promise<PromptValidationResult> {
const input: ApplyGuardrailCommandInput = {
guardrailIdentifier: guardrailId,
guardrailVersion,
source: 'INPUT',
content: [{ text: { text: userFragment } }],
};
const response = await bedrockRuntime.send(new ApplyGuardrailCommand(input));
if (response.action !== 'GUARDRAIL_INTERVENED') {
return { safe: true };
}
// Find the specific filter that triggered
const assessment = response.assessments?.[0];
const promptAttackFilter = assessment?.contentPolicy?.filters?.find(
f => f.type === 'PROMPT_ATTACK' && f.action === 'BLOCKED',
);
if (promptAttackFilter) {
return {
safe: false,
reason: 'PROMPT_ATTACK',
confidence: promptAttackFilter.confidence,
};
}
// Some other content filter fired
const otherFilter = assessment?.contentPolicy?.filters?.find(
f => f.action === 'BLOCKED',
);
return {
safe: false,
reason: otherFilter?.type ?? 'CONTENT_POLICY',
confidence: otherFilter?.confidence,
};
}
// Example MCP tool that safely accepts user-defined instructions
async function handleCustomInstructionTool(
userInstruction: string,
userQuery: string,
guardrailId: string,
guardrailVersion: string,
): Promise<{ success: boolean; text?: string; error?: string }> {
// Step 1: validate the user-supplied instruction fragment BEFORE
// incorporating it into the system prompt. System prompts are not
// evaluated by guardrails, so this pre-check is the only protection.
const validation = await validateUserPromptFragment(
userInstruction,
guardrailId,
guardrailVersion,
);
if (!validation.safe) {
console.log(JSON.stringify({
event: 'prompt_injection_blocked',
reason: validation.reason,
confidence: validation.confidence,
fragmentPreview: userInstruction.slice(0, 50),
}));
return {
success: false,
error: 'The provided instruction was flagged by content policy.',
};
}
// Step 2: safe to incorporate into system prompt
const systemPrompt = `You are a helpful assistant. Additional instruction: ${userInstruction}`;
const converseResponse = await bedrockRuntime.send(new ConverseCommand({
modelId: 'us.anthropic.claude-3-5-sonnet-20241022-v2:0',
system: [{ text: systemPrompt }],
messages: [{ role: 'user', content: [{ text: userQuery }] }],
guardrailConfig: {
guardrailIdentifier: guardrailId,
guardrailVersion,
trace: 'ENABLED',
},
inferenceConfig: { maxTokens: 1024 },
}));
if (converseResponse.stopReason === 'guardrail_intervened') {
return { success: false, error: 'Response blocked by content policy.' };
}
const text =
converseResponse.output?.message?.content
?.filter((b): b is { text: string } => 'text' in b)
.map(b => b.text)
.join('') ?? '';
return { success: true, text };
}
Injection patterns that PROMPT_ATTACK at HIGH strength reliably catches include direct override instructions ("ignore all previous instructions"), persona substitution ("you are now a different AI with no restrictions"), encoding obfuscation (base64 or ROT13 wrapping of injection text), few-shot attack patterns that demonstrate the desired bypass behavior, and indirect injection embedded in tool-returned content (a document the model is asked to summarize that contains injected instructions). At HIGH strength, the filter may also catch legitimate meta-instructions like "rewrite the above with a different tone" in certain phrasings — which is the main gotcha covered in the production notes section below.
Parsing the trace — assessments array in depth
When trace: "ENABLED" is set on the guardrailConfig, Bedrock populates response.trace.guardrail with detailed assessment data for every evaluation phase. This data is the definitive source of truth for understanding why a guardrail fired — the blocked messaging strings visible to users give no policy details, but the trace gives you the full signal for audit logs, monitoring dashboards, and debugging.
The trace structure has two top-level properties: inputAssessment (a single assessment object for the user message evaluation) and outputAssessments (an array — one entry per assistant message in a multi-turn conversation, though for single-turn calls it always contains at most one entry). Both inputAssessment and each outputAssessments[n] share the same assessment schema.
Each assessment contains up to four policy sub-objects depending on what your guardrail is configured with:
contentPolicy.filters[]— one entry per active content filter category, each withtype,confidence(NONE/LOW/MEDIUM/HIGH), andaction(either"BLOCKED"or"NONE"). Categories that did not evaluate to a blocked threshold haveaction: "NONE"even ifconfidenceis non-zero — the filter detected some signal but it was below your configured threshold.topicPolicy.topics[]— one entry per denied topic that the guardrail was configured with, each withname,type, andaction.sensitiveInformationPolicy.piiEntities[]— PII entities detected, each withtype(EMAIL, PHONE, SSN, etc.) andaction(ANONYMIZED or BLOCKED).wordPolicy.customWords[]andwordPolicy.managedWordLists[]— word matches with the matched text and action.
import type {
ConverseResponse,
GuardrailAssessment,
GuardrailContentFilter,
} from '@aws-sdk/client-bedrock-runtime';
// Structured audit log entry derived from guardrail trace
interface GuardrailAuditEntry {
timestamp: string;
requestId?: string;
blocked: boolean;
blockPhase?: 'INPUT' | 'OUTPUT';
contentFilters: Array<{
type: string;
confidence: string;
action: string;
}>;
promptAttackDetected: boolean;
topicViolations: string[];
piiEntityTypes: string[];
}
function parseGuardrailTrace(response: ConverseResponse): GuardrailAuditEntry {
const guardrailTrace = response.trace?.guardrail;
const blocked = response.stopReason === 'guardrail_intervened';
// Determine block phase from which assessment has BLOCKED actions
let blockPhase: 'INPUT' | 'OUTPUT' | undefined;
if (blocked) {
const inputHasBlock = guardrailTrace?.inputAssessment?.contentPolicy?.filters
?.some(f => f.action === 'BLOCKED');
blockPhase = inputHasBlock ? 'INPUT' : 'OUTPUT';
}
// Collect all content filter results from whichever assessment is relevant
const relevantAssessment: GuardrailAssessment | undefined = blockPhase === 'INPUT'
? guardrailTrace?.inputAssessment
: guardrailTrace?.outputAssessments?.[0];
const contentFilters: GuardrailAuditEntry['contentFilters'] = (
relevantAssessment?.contentPolicy?.filters ?? []
).map((f: GuardrailContentFilter) => ({
type: f.type ?? 'UNKNOWN',
confidence: f.confidence ?? 'NONE',
action: f.action ?? 'NONE',
}));
// Check specifically for prompt attack (only exists in inputAssessment)
const promptAttackFilter = guardrailTrace?.inputAssessment?.contentPolicy?.filters
?.find(f => f.type === 'PROMPT_ATTACK');
const promptAttackDetected =
(promptAttackFilter?.confidence ?? 'NONE') !== 'NONE' ||
promptAttackFilter?.action === 'BLOCKED';
// Topic policy violations (from topic policy config, not content policy)
const topicViolations = (
relevantAssessment?.topicPolicy?.topics ?? []
)
.filter(t => t.action === 'BLOCKED')
.map(t => t.name ?? 'UNKNOWN');
// PII entities detected
const piiEntityTypes = (
guardrailTrace?.inputAssessment?.sensitiveInformationPolicy?.piiEntities ?? []
)
.map(e => e.type ?? 'UNKNOWN');
return {
timestamp: new Date().toISOString(),
blocked,
blockPhase,
contentFilters,
promptAttackDetected,
topicViolations,
piiEntityTypes,
};
}
// Example: use in an MCP tool handler with structured CloudWatch logging
async function mcpToolWithAuditLogging(
userMessage: string,
modelId: string,
): Promise<{ content: Array<{ type: string; text: string }>; isError?: boolean }> {
const response = await bedrockRuntime.send(new ConverseCommand({
modelId,
messages: [{ role: 'user', content: [{ text: userMessage }] }],
guardrailConfig: {
guardrailIdentifier: GUARDRAIL_ID,
guardrailVersion: GUARDRAIL_VERSION,
trace: 'ENABLED',
},
inferenceConfig: { maxTokens: 2048 },
}));
// Always parse audit entry regardless of block status
const audit = parseGuardrailTrace(response);
// Ship to CloudWatch as a structured log event for dashboarding
if (audit.blocked || audit.promptAttackDetected || audit.contentFilters.some(
f => f.confidence === 'HIGH' || f.confidence === 'MEDIUM',
)) {
console.log(JSON.stringify({
event: 'guardrail_assessment',
...audit,
// Include a preview of the input for investigation (redact in high-privacy contexts)
inputPreview: userMessage.slice(0, 100),
}));
}
if (response.stopReason === 'guardrail_intervened') {
return {
isError: true,
content: [{
type: 'text',
text: 'Your request was blocked by content policy. Please rephrase and try again.',
}],
};
}
const text =
response.output?.message?.content
?.filter((b): b is { text: string } => 'text' in b)
.map(b => b.text)
.join('') ?? '';
return { content: [{ type: 'text', text }] };
}
One subtlety in the trace structure: even when a request passes without being blocked, the contentPolicy.filters array is populated with entries for each active category. Categories where no signal was detected have confidence: "NONE" and action: "NONE". Categories where signal was detected but below the blocking threshold have a non-NONE confidence (LOW, MEDIUM, or HIGH) with action: "NONE". This distinction is valuable for threshold calibration — if you are seeing many entries with confidence: "MEDIUM" and action: "NONE" (meaning detected but not blocked), you may want to increase that category's strength to actually block those cases, or confirm they are false positives and your current threshold is correct.
Strength levels in practice — calibrating for your use case
Choosing the right inputStrength and outputStrength for each category requires understanding how the detection model's confidence distribution maps to your content. Each strength level corresponds to a minimum confidence threshold: LOW blocks only HIGH-confidence detections, MEDIUM blocks MEDIUM and HIGH-confidence detections, and HIGH blocks LOW, MEDIUM, and HIGH-confidence detections. Setting a category to HIGH strength does not mean "block everything" — it means "block even when confidence is low", which is a strict threshold that accepts more false positives.
Practically: a customer service MCP tool for a retail company should use MEDIUM as its baseline for all categories, then selectively raise specific categories based on the product context. An age-verified adult content platform might set SEXUAL to NONE for output while keeping HATE and PROMPT_ATTACK at HIGH. An internal developer productivity tool might set everything to LOW except MISCONDUCT (which should stay at HIGH to prevent instructions for creating malware) and PROMPT_ATTACK (which should stay at HIGH to prevent jailbreaks of the developer assistant).
Critically, inputStrength and outputStrength are independent. You might want HATE at inputStrength: "HIGH" (never let hate speech into the model's context, even if it claims to be quoting something for analysis) but outputStrength: "MEDIUM" (allow the model to reference historical discrimination in an educational response without blocking it). The asymmetry lets you be strict about what enters the model context while being slightly more permissive about nuanced model-generated educational content.
import {
BedrockClient,
CreateGuardrailCommand,
UpdateGuardrailCommand,
type FiltersConfigType,
} from '@aws-sdk/client-bedrock';
// Strength configurations for common MCP server use cases
type FilterStrength = 'NONE' | 'LOW' | 'MEDIUM' | 'HIGH';
interface ContentFilterPolicy {
type: FiltersConfigType;
inputStrength: FilterStrength;
outputStrength: FilterStrength;
}
// Use case: general customer-facing assistant (retail, support, productivity)
const CUSTOMER_FACING_POLICY: ContentFilterPolicy[] = [
{ 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: 'NONE' },
];
// Use case: internal developer tool (less strict on content, focus on security)
const DEVELOPER_TOOL_POLICY: ContentFilterPolicy[] = [
{ type: 'HATE', inputStrength: 'MEDIUM', outputStrength: 'MEDIUM' },
{ type: 'INSULTS', inputStrength: 'LOW', outputStrength: 'LOW' },
{ type: 'SEXUAL', inputStrength: 'HIGH', outputStrength: 'HIGH' },
{ type: 'VIOLENCE', inputStrength: 'LOW', outputStrength: 'LOW' },
{ type: 'MISCONDUCT', inputStrength: 'HIGH', outputStrength: 'HIGH' },
{ type: 'PROMPT_ATTACK', inputStrength: 'HIGH', outputStrength: 'NONE' },
];
// Use case: educational platform for high-school students
const EDUCATIONAL_POLICY: ContentFilterPolicy[] = [
{ type: 'HATE', inputStrength: 'HIGH', outputStrength: 'HIGH' },
{ type: 'INSULTS', inputStrength: 'HIGH', outputStrength: 'HIGH' },
{ type: 'SEXUAL', inputStrength: 'HIGH', outputStrength: 'HIGH' },
// HIGH on output for VIOLENCE to block even action-movie descriptions
{ type: 'VIOLENCE', inputStrength: 'HIGH', outputStrength: 'HIGH' },
{ type: 'MISCONDUCT', inputStrength: 'HIGH', outputStrength: 'HIGH' },
{ type: 'PROMPT_ATTACK', inputStrength: 'HIGH', outputStrength: 'NONE' },
];
const bedrockControl = new BedrockClient({
region: process.env.AWS_REGION ?? 'us-east-1',
});
async function createGuardrailWithPolicy(
name: string,
policy: ContentFilterPolicy[],
): Promise<{ guardrailId: string; guardrailArn: string }> {
const response = await bedrockControl.send(new CreateGuardrailCommand({
name,
contentPolicyConfig: { filtersConfig: policy },
blockedInputMessaging: 'Your message was blocked by our content policy.',
blockedOutputsMessaging: 'The response was blocked by our content policy.',
}));
return {
guardrailId: response.guardrailId!,
guardrailArn: response.guardrailArn!,
};
}
// Update an existing guardrail's content policy (applies to DRAFT version immediately)
async function updateContentPolicy(
guardrailId: string,
newPolicy: ContentFilterPolicy[],
): Promise<void> {
await bedrockControl.send(new UpdateGuardrailCommand({
guardrailIdentifier: guardrailId,
// UpdateGuardrailCommand requires repeating ALL config fields,
// not just the ones you are changing — it is a full replacement.
name: 'mcp-content-policy', // must include existing name
contentPolicyConfig: { filtersConfig: newPolicy },
blockedInputMessaging: 'Your message was blocked by our content policy.',
blockedOutputsMessaging: 'The response was blocked by our content policy.',
}));
// After updating, call CreateGuardrailVersionCommand to create
// a new immutable version before promoting to production.
}
When evaluating whether your strength settings are appropriate, use the trace's confidence field on passing requests. If you are running HATE at MEDIUM strength and you consistently see trace entries where confidence: "LOW" with action: "NONE" — meaning the filter detects low confidence of hate speech that it correctly does not block — that is healthy behavior and your threshold is calibrated correctly. If you start seeing confidence: "HIGH" with action: "NONE", your strength setting is too low for the detected content.
Full MCP tool handler with guardrail_intervened handling
This section puts all the components together into a production-ready MCP tool handler: creating the guardrail, attaching it to Converse, detecting the blocked stop reason, parsing trace assessments for structured logging, and returning a typed MCP error response rather than propagating an unhandled exception. The handler wraps everything in a circuit breaker so a misconfigured guardrail does not take down the entire MCP server.
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import {
BedrockRuntimeClient,
ConverseCommand,
ApplyGuardrailCommand,
} from '@aws-sdk/client-bedrock-runtime';
import { z } from 'zod';
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.BEDROCK_GUARDRAIL_VERSION ?? 'DRAFT';
// Classify a guardrail_intervened response into a user-facing message
// without leaking policy details that could aid enumeration attacks.
function classifyGuardrailBlock(response: import('@aws-sdk/client-bedrock-runtime').ConverseResponse): {
userMessage: string;
auditCategory: string;
} {
const inputAssessment = response.trace?.guardrail?.inputAssessment;
const outputAssessment = response.trace?.guardrail?.outputAssessments?.[0];
// Check for PROMPT_ATTACK first — it has specific handling in security logs
const promptAttack = inputAssessment?.contentPolicy?.filters?.find(
f => f.type === 'PROMPT_ATTACK' && f.action === 'BLOCKED',
);
if (promptAttack) {
return {
userMessage: 'Your request could not be processed. Please try rephrasing.',
auditCategory: 'PROMPT_ATTACK',
};
}
// Check content policy filters (input phase)
const inputContentBlock = inputAssessment?.contentPolicy?.filters?.find(
f => f.action === 'BLOCKED',
);
if (inputContentBlock) {
return {
userMessage: 'Your message was blocked by our content guidelines.',
auditCategory: `CONTENT_INPUT_${inputContentBlock.type}`,
};
}
// Check content policy filters (output phase)
const outputContentBlock = outputAssessment?.contentPolicy?.filters?.find(
f => f.action === 'BLOCKED',
);
if (outputContentBlock) {
return {
userMessage: 'The response was blocked by our content guidelines. Please rephrase your request.',
auditCategory: `CONTENT_OUTPUT_${outputContentBlock.type}`,
};
}
// Topic policy, word policy, or other policy fired
const topicBlock = (inputAssessment ?? outputAssessment)?.topicPolicy?.topics?.find(
t => t.action === 'BLOCKED',
);
if (topicBlock) {
return {
userMessage: 'This topic is outside the scope of this assistant.',
auditCategory: `TOPIC_${topicBlock.name ?? 'UNKNOWN'}`,
};
}
return {
userMessage: 'Your request was blocked by our content policy.',
auditCategory: 'UNKNOWN_POLICY',
};
}
const server = new McpServer({
name: 'bedrock-content-filter-demo',
version: '1.0.0',
});
server.tool(
'ask_bedrock',
'Send a message to Claude via Amazon Bedrock with content filtering',
{
message: z.string().min(1).max(50000).describe('The user message to send'),
modelId: z
.string()
.default('us.anthropic.claude-3-5-sonnet-20241022-v2:0')
.describe('Bedrock model ID'),
systemPrompt: z
.string()
.optional()
.describe('Optional system prompt — not evaluated by content filters'),
},
async ({ message, modelId, systemPrompt }) => {
// Phase 1: pre-validate input before spending inference tokens
// This is especially valuable for PROMPT_ATTACK detection, which
// costs nothing if it fires before the model is invoked.
const preCheck = await runtime.send(new ApplyGuardrailCommand({
guardrailIdentifier: GUARDRAIL_ID,
guardrailVersion: GUARDRAIL_VERSION,
source: 'INPUT',
content: [{ text: { text: message } }],
}));
if (preCheck.action === 'GUARDRAIL_INTERVENED') {
const filter = preCheck.assessments?.[0]?.contentPolicy?.filters?.find(
f => f.action === 'BLOCKED',
);
console.log(JSON.stringify({
event: 'guardrail_input_blocked_precheck',
filterType: filter?.type,
confidence: filter?.confidence,
timestamp: new Date().toISOString(),
}));
return {
isError: true,
content: [{
type: 'text' as const,
text: 'Your message was blocked by content policy before reaching the model.',
}],
};
}
// Phase 2: invoke model with guardrailConfig for output protection
const converseResponse = await runtime.send(new ConverseCommand({
modelId,
system: systemPrompt ? [{ text: systemPrompt }] : undefined,
messages: [
{ role: 'user', content: [{ text: message }] },
],
guardrailConfig: {
guardrailIdentifier: GUARDRAIL_ID,
guardrailVersion: GUARDRAIL_VERSION,
trace: 'ENABLED',
},
inferenceConfig: { maxTokens: 4096, temperature: 0.7 },
}));
// Phase 3: handle blocked responses
if (converseResponse.stopReason === 'guardrail_intervened') {
const { userMessage, auditCategory } = classifyGuardrailBlock(converseResponse);
// Log blocked response with structured data for monitoring
console.log(JSON.stringify({
event: 'guardrail_blocked',
auditCategory,
stopReason: converseResponse.stopReason,
// Log confidence levels for all evaluated filters (even non-blocked ones)
allFilters: converseResponse.trace?.guardrail?.inputAssessment?.contentPolicy?.filters
?? converseResponse.trace?.guardrail?.outputAssessments?.[0]?.contentPolicy?.filters
?? [],
timestamp: new Date().toISOString(),
}));
return {
isError: true,
content: [{ type: 'text' as const, text: userMessage }],
};
}
// Phase 4: safe to read output
const text =
converseResponse.output?.message?.content
?.filter((b): b is { text: string } => 'text' in b)
.map(b => b.text)
.join('') ?? '';
return { content: [{ type: 'text' as const, text }] };
},
);
export { server };
The two-phase approach (pre-check with ApplyGuardrailCommand followed by Converse with guardrailConfig) provides defense in depth and cost optimization simultaneously. If PROMPT_ATTACK fires in the pre-check, you pay zero inference tokens. If HATE or MISCONDUCT fires in the Converse input phase (guardrail evaluates input before invoking the model), you also pay zero tokens. Only output-phase blocks incur the full inference cost. For high-volume MCP servers serving adversarial users, this layered approach can meaningfully reduce inference costs while maintaining the same security posture.
Sensitive information policy — a separate config
Content filtering (via contentPolicyConfig.filtersConfig) and PII detection (via sensitiveInformationPolicyConfig) are separate policy objects within a guardrail configuration. They are evaluated independently and can fire simultaneously — a message can trigger both a HATE content filter and a PII entity detection in the same request. The trace's assessments array contains results for all configured policies in a single response.
sensitiveInformationPolicyConfig has two sub-arrays: piiEntitiesConfig (pre-built entity detectors for types like EMAIL, PHONE, SSN, CREDIT_DEBIT_NUMBER, AWS_ACCESS_KEY, IP_ADDRESS, and many others) and regexesConfig (custom regex patterns for domain-specific PII like internal employee IDs or proprietary identifiers). Each PII entity config has an action of either ANONYMIZE (replace detected entity with a placeholder token in the text that flows to the model and in the response) or BLOCK (halt the entire request like a content filter block). The ANONYMIZE action is particularly powerful for MCP servers that process user-submitted documents: the model receives the document with PII redacted, so it cannot inadvertently echo or store sensitive data, but the request still succeeds.
For a full treatment of sensitiveInformationPolicyConfig, entity types, the ANONYMIZE vs BLOCK action distinction, and how to read redacted text back from the outputs array, see the Bedrock Guardrails PII anonymization guide.
import {
BedrockClient,
CreateGuardrailCommand,
} from '@aws-sdk/client-bedrock';
const bedrockControl = new BedrockClient({
region: process.env.AWS_REGION ?? 'us-east-1',
});
// Guardrail combining content policy with PII detection in a single guardrail.
// Both policies are evaluated on every call — the trace returns results for both.
async function createCombinedGuardrail(): Promise<{ guardrailId: string; guardrailArn: string }> {
const response = await bedrockControl.send(new CreateGuardrailCommand({
name: 'mcp-combined-content-pii',
description: 'Content filtering + PII anonymization for document processing tools',
// Policy 1: content filtering
contentPolicyConfig: {
filtersConfig: [
{ type: 'HATE', inputStrength: 'HIGH', outputStrength: 'HIGH' },
{ type: 'SEXUAL', inputStrength: 'HIGH', outputStrength: 'HIGH' },
{ type: 'MISCONDUCT', inputStrength: 'HIGH', outputStrength: 'HIGH' },
{ type: 'PROMPT_ATTACK', inputStrength: 'HIGH', outputStrength: 'NONE' },
{ type: 'INSULTS', inputStrength: 'MEDIUM', outputStrength: 'MEDIUM' },
{ type: 'VIOLENCE', inputStrength: 'MEDIUM', outputStrength: 'MEDIUM' },
],
},
// Policy 2: PII anonymization (separate from content policy)
// ANONYMIZE replaces PII in text flowing to the model — model never sees raw PII.
// BLOCK halts the request entirely (like a content filter BLOCKED action).
sensitiveInformationPolicyConfig: {
piiEntitiesConfig: [
{ type: 'EMAIL', action: 'ANONYMIZE' },
{ type: 'PHONE', action: 'ANONYMIZE' },
{ type: 'SSN', action: 'BLOCK' },
{ type: 'CREDIT_DEBIT_NUMBER', action: 'BLOCK' },
{ type: 'AWS_ACCESS_KEY', action: 'BLOCK' },
{ type: 'AWS_SECRET_KEY', action: 'BLOCK' },
{ type: 'IP_ADDRESS', action: 'ANONYMIZE' },
{ type: 'NAME', action: 'ANONYMIZE' },
],
// Custom regex for internal employee IDs: EMP-XXXXXXXX
regexesConfig: [
{
name: 'employee_id',
description: 'Internal employee identifier',
pattern: 'EMP-[0-9]{8}',
action: 'ANONYMIZE',
},
],
},
blockedInputMessaging:
'Your request was blocked. It may contain sensitive information or policy-violating content.',
blockedOutputsMessaging: 'The response was blocked by content policy.',
}));
return {
guardrailId: response.guardrailId!,
guardrailArn: response.guardrailArn!,
};
}
// Reading PII assessment from trace (independent of content policy assessment)
function parsePiiFromTrace(
trace: import('@aws-sdk/client-bedrock-runtime').ConverseResponse['trace'],
): Array<{ type: string; action: string }> {
const inputAssessment = trace?.guardrail?.inputAssessment;
const piiEntities = inputAssessment?.sensitiveInformationPolicy?.piiEntities ?? [];
return piiEntities.map(e => ({
type: e.type ?? 'UNKNOWN',
action: e.action ?? 'NONE',
}));
}
When both content policy and sensitive information policy are configured, a single request can produce a guardrail_intervened stop reason driven by either policy. Check both contentPolicy.filters and sensitiveInformationPolicy.piiEntities in the assessment when diagnosing why a block occurred. PII blocks (from action: "BLOCK" on a PII entity) produce the same guardrail_intervened stop reason as content filter blocks.
Production gotchas
These are the specific failure modes, false positive patterns, and integration pitfalls that cause the most debugging time when deploying Bedrock Guardrails content filtering in MCP server production environments.
1. HIGH strength for HATE causes false positives on academic and historical text. Setting HATE to inputStrength: "HIGH" will block questions like "Why did Nazi propaganda use dehumanizing language?" or "What rhetoric did Jim Crow-era politicians use?" because the classifier detects hate-adjacent language even in academic framing. At HIGH strength, it blocks based on LOW-confidence detection, and low confidence means "this contains hate-associated vocabulary" rather than "this is expressing hatred." For general educational tools, keep HATE at MEDIUM and accept that the most extreme academic analysis of hate movements may occasionally pass through.
2. PROMPT_ATTACK at HIGH strength blocks legitimate meta-instructions. At HIGH strength, instructions like "revise the above paragraph to be more concise" or "rewrite this in a formal tone" can be caught by the PROMPT_ATTACK filter because they contain instruction-override patterns in a broad sense. This is particularly common when the user is asking the model to modify text that itself contains instructions (a requirements document, a prompt template, a configuration file). If your MCP tool regularly handles instruction-shaped text, test PROMPT_ATTACK at MEDIUM first.
3. Content filters do not apply to system prompts — only user and assistant messages. If your system prompt contains terms that would trigger a content filter in a user message (industry jargon, clinical terminology, security research concepts), they pass without evaluation. Conversely, you cannot use content filtering to sanitize what goes into your system prompt — that responsibility falls entirely on your application-layer input validation before the prompt template is assembled.
4. outputStrength for PROMPT_ATTACK is silently ignored — not an error. Setting outputStrength: "MEDIUM" on a PROMPT_ATTACK filter entry does not cause an API error or validation warning. The API accepts the value, the guardrail is created successfully, and the value simply has no effect. This can create false confidence: a team might believe they have PROMPT_ATTACK protection on output when they do not. Always set outputStrength: "NONE" on PROMPT_ATTACK entries to make the semantics explicit.
5. trace adds 10–30ms latency but is the only way to diagnose which filter fired. With trace: "DISABLED", a guardrail_intervened stop reason gives you no information about which policy category triggered the block. You cannot distinguish a HATE block from a PROMPT_ATTACK block from a topic policy block without trace data. During initial deployment, run with trace enabled on 100% of traffic until your blocking patterns are well understood. After stabilization, you can sample (enable trace on 10–20% of requests) while maintaining observability without the full per-request overhead.
6. Content filters cover harmful generation but NOT grounding or hallucination. contentPolicyConfig.filtersConfig evaluates the harm category of content, not its factual accuracy. A model that confidently generates false information will not be caught by content filtering — that is the domain of groundingPolicyConfig, which uses RAG-grounding verification to detect factual divergence. These are two separate safety mechanisms that address orthogonal failure modes. MCP servers serving factual queries (financial data, medical information, legal text) need grounding policy in addition to content filtering.
7. UpdateGuardrailCommand requires all config fields — it is a full replacement, not a patch. When you update a guardrail's content policy via UpdateGuardrailCommand, you must include all existing configuration fields, not just the changed ones. Sending only the updated contentPolicyConfig without also including the existing sensitiveInformationPolicyConfig, topicPolicyConfig, and wordPolicyConfig will silently delete those policies from the guardrail's DRAFT version. Always read the current guardrail configuration with GetGuardrailCommand before issuing an update.
8. Per-request costs for blocked requests differ between input-phase and output-phase blocks. When the guardrail fires on the input phase (before the model runs), you are charged only for the guardrail evaluation, not for model inference. When it fires on the output phase, you incur the full inference cost for the model run, plus the guardrail evaluation cost. For adversarial workloads where PROMPT_ATTACK is frequently triggered, using ApplyGuardrailCommand as a pre-flight check before each ConverseCommand call ensures that prompt injection attempts are caught before you spend inference tokens, even though it adds a small latency overhead from the extra API call.
AliveMCP and guardrail-triggered outages
A misconfigured content filter — a strength level set too high, an inadvertent policy update to the DRAFT version that production traffic is pinned to, or a model update that changes the base classification scores — can cause an MCP server to suddenly start blocking legitimate requests at high rates, which looks identical to a service outage from the client's perspective. AliveMCP monitors your MCP 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 during an incident review.