Guide · Amazon Bedrock · Privacy

Bedrock Guardrails PII Detection and Anonymization for MCP Servers

Amazon Bedrock Guardrails' sensitiveInformationPolicyConfig lets you detect and redact PII — including credit card numbers, social security numbers, AWS credentials, and 30-plus other entity types — directly at the API boundary of your MCP server, before that data ever reaches a foundation model or leaves your AWS account. The two available actions — ANONYMIZE and BLOCK — behave very differently: ANONYMIZE replaces detected entities with tokens like {NAME} or {EMAIL} and allows processing to continue, while BLOCK stops the entire response with a guardrail_intervened stop reason; critically, ANONYMIZE is only valid for OUTPUT-source scanning, not INPUT. Beyond the built-in entity types, regexesConfig lets you add custom patterns for internal identifiers like employee IDs or account numbers, but custom regex has no look-behind support and group captures are ignored — always use non-capturing groups. This guide covers the full CreateGuardrailCommand configuration, every PIIEntityType enum value, the ApplyGuardrailCommand workflow for scanning tool results, reading anonymized text from outputs[0].text, and the two-pass pattern that protects both what goes in and what comes back out. See also the Bedrock Guardrails overview for the architecture context and content filtering configuration for the complementary contentPolicyConfig.

TL;DR

Configure sensitiveInformationPolicyConfig.piiEntitiesConfig as an array of { type: PIIEntityType, action: "ANONYMIZE" | "BLOCK" } objects when creating a guardrail. Use ApplyGuardrailCommand from @aws-sdk/client-bedrock-runtime (not the control-plane package) to scan tool results before returning them: set source: "OUTPUT", read the anonymized replacement from response.outputs[0].text, and check response.action === "GUARDRAIL_INTERVENED" to detect hard blocks. For input scanning on user messages, set source: "INPUT" — both ANONYMIZE and BLOCK are valid there. PII detection is probabilistic: short inputs under a few tokens often miss detection, so never rely on it as a sole compliance control.

Creating a guardrail with sensitiveInformationPolicyConfig

PII detection is configured at guardrail creation time via sensitiveInformationPolicyConfig, a top-level field on CreateGuardrailCommand. It contains two independent sub-configurations: piiEntitiesConfig for the built-in entity type detector and regexesConfig for custom regex patterns. Both are optional arrays; you can supply one or both depending on what you need to detect.

Guardrail creation uses the control-plane package @aws-sdk/client-bedrock (the BedrockClient), not the runtime package used for inference. This is a common source of confusion: creating and updating guardrails is a separate API call family from using them. The runtime package (@aws-sdk/client-bedrock-runtime with BedrockRuntimeClient) is used for ApplyGuardrailCommand and ConverseCommand. Both packages need to be installed.

Each entry in piiEntitiesConfig selects one built-in entity type and assigns an action. You cannot assign different confidence thresholds per entity type — the detection threshold is managed by the guardrail's overall sensitivity setting, not per-entity. If you need entity-level threshold control, the workaround is to create separate guardrails for different sensitivity groups and route traffic accordingly. The action field accepts either "ANONYMIZE" or "BLOCK" — but as discussed below, ANONYMIZE only applies to output scanning; for source: "INPUT" calls, both values work but ANONYMIZE on input still replaces the content with the placeholder token before it reaches any downstream logic.

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

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

async function createPIIGuardrail(): Promise<{ guardrailId: string; version: string }> {
  const input: CreateGuardrailCommandInput = {
    name: 'mcp-server-pii-guardrail',
    description: 'Detects and redacts PII in MCP tool inputs and outputs',

    sensitiveInformationPolicyConfig: {
      // Built-in entity detection — each entry picks one type and assigns an action.
      // ANONYMIZE: replaces with {TYPE} token, allows response to continue.
      // BLOCK: stops entire response with guardrail_intervened stopReason.
      piiEntitiesConfig: [
        // Hard-block credentials — these should never reach a model or be returned
        { type: 'AWS_ACCESS_KEY',   action: 'BLOCK' },
        { type: 'AWS_SECRET_KEY',   action: 'BLOCK' },
        { type: 'PASSWORD',         action: 'BLOCK' },
        { type: 'CREDIT_DEBIT_CARD_NUMBER', action: 'BLOCK' },
        { type: 'CREDIT_DEBIT_CARD_CVV',    action: 'BLOCK' },

        // Anonymize identity information — replace with token, allow processing
        { type: 'NAME',                                     action: 'ANONYMIZE' },
        { type: 'EMAIL',                                    action: 'ANONYMIZE' },
        { type: 'PHONE',                                    action: 'ANONYMIZE' },
        { type: 'ADDRESS',                                  action: 'ANONYMIZE' },
        { type: 'AGE',                                      action: 'ANONYMIZE' },
        { type: 'DATE_TIME',                                action: 'ANONYMIZE' },
        { type: 'URL',                                      action: 'ANONYMIZE' },
        { type: 'USERNAME',                                 action: 'ANONYMIZE' },
        { type: 'IP_ADDRESS',                               action: 'ANONYMIZE' },
        { type: 'MAC_ADDRESS',                              action: 'ANONYMIZE' },

        // Government identifiers — BLOCK for strictest compliance
        { type: 'US_SOCIAL_SECURITY_NUMBER',                action: 'BLOCK' },
        { type: 'US_PASSPORT_NUMBER',                       action: 'BLOCK' },
        { type: 'US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER',  action: 'BLOCK' },
        { type: 'CA_SOCIAL_INSURANCE_NUMBER',               action: 'BLOCK' },
        { type: 'CA_HEALTH_NUMBER',                         action: 'BLOCK' },
        { type: 'UK_NATIONAL_INSURANCE_NUMBER',             action: 'BLOCK' },
        { type: 'UK_NATIONAL_HEALTH_SERVICE_NUMBER',        action: 'BLOCK' },
        { type: 'UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER',      action: 'BLOCK' },
        { type: 'DRIVER_ID',                                action: 'BLOCK' },

        // Financial data
        { type: 'US_BANK_ACCOUNT_NUMBER',                   action: 'BLOCK' },
        { type: 'US_BANK_ROUTING_NUMBER',                   action: 'BLOCK' },
        { type: 'CREDIT_DEBIT_CARD_EXPIRY',                 action: 'ANONYMIZE' },
        { type: 'PIN',                                      action: 'BLOCK' },
        { type: 'SWIFT_CODE',                               action: 'ANONYMIZE' },

        // Vehicle and device identifiers
        { type: 'LICENSE_PLATE',                            action: 'ANONYMIZE' },
        { type: 'VEHICLE_IDENTIFICATION_NUMBER',            action: 'ANONYMIZE' },
      ],

      // Custom regex patterns for org-specific identifiers
      regexesConfig: [
        {
          name: 'internal-employee-id',
          description: 'Acme Corp employee ID format: EMP followed by 6 digits',
          // Non-capturing group required — group captures are not supported
          pattern: 'EMP(?:\\d{6})',
          action: 'ANONYMIZE',
        },
        {
          name: 'internal-ticket-id',
          description: 'Support ticket IDs: TKT- followed by alphanumeric',
          pattern: 'TKT-(?:[A-Z0-9]{8,12})',
          action: 'ANONYMIZE',
        },
        {
          name: 'api-token',
          description: 'Internal API tokens starting with sk_live_',
          // BLOCK credentials even if the built-in types miss them
          pattern: 'sk_(?:live|test)_[A-Za-z0-9]{24,}',
          action: 'BLOCK',
        },
      ],
    },

    // Blocked messaging — shown when action is BLOCK
    blockedInputMessaging:  'Your message contains sensitive information that cannot be processed.',
    blockedOutputsMessaging: 'The response contained sensitive information and has been blocked.',
  };

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

  console.log(`Created guardrail: ${response.guardrailId} (version ${response.version})`);
  // response.version is "DRAFT" at creation time — use CreateGuardrailVersionCommand
  // to mint an immutable numeric version before deploying to production

  return {
    guardrailId: response.guardrailId!,
    version: response.version!,
  };
}

The full set of PIIEntityType values supported by Bedrock Guardrails covers personal, financial, and device identifiers. The complete list (as of the current SDK) is: NAME, EMAIL, PHONE, ADDRESS, AGE, AWS_ACCESS_KEY, AWS_SECRET_KEY, CA_HEALTH_NUMBER, CA_SOCIAL_INSURANCE_NUMBER, CREDIT_DEBIT_CARD_CVV, CREDIT_DEBIT_CARD_EXPIRY, CREDIT_DEBIT_CARD_NUMBER, DATE_TIME, DRIVER_ID, IP_ADDRESS, LICENSE_PLATE, MAC_ADDRESS, PASSWORD, PIN, SWIFT_CODE, UK_NATIONAL_HEALTH_SERVICE_NUMBER, UK_NATIONAL_INSURANCE_NUMBER, UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER, URL, USERNAME, US_BANK_ACCOUNT_NUMBER, US_BANK_ROUTING_NUMBER, US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER, US_PASSPORT_NUMBER, US_SOCIAL_SECURITY_NUMBER, and VEHICLE_IDENTIFICATION_NUMBER. The AWS SDK exports these as a PIIEntityType enum from @aws-sdk/client-bedrock so you get compile-time type checking in TypeScript.

ANONYMIZE vs BLOCK — when to use each action

The choice between ANONYMIZE and BLOCK depends on two factors: how sensitive the entity is, and what your MCP tool handler needs to do with the text after scanning. These actions have fundamentally different semantics and cannot be used interchangeably.

ANONYMIZE replaces the detected entity span with a typed placeholder token. The token format is a curly-brace-wrapped uppercase type name: {NAME}, {EMAIL}, {PHONE}, {ADDRESS}, {IP_ADDRESS}, and so on for every entity type. When ANONYMIZE is applied to output text (via ApplyGuardrailCommand with source: "OUTPUT"), the guardrail returns action: "NONE" in the response — the guard did not intervene to block processing, it only transformed the content. The anonymized text is available in outputs[0].text. This means your tool handler can continue and return a usable response to the LLM agent upstream; the agent will see {NAME} in the text rather than the actual name, which is usually sufficient for tasks like summarization, classification, or routing.

BLOCK returns action: "GUARDRAIL_INTERVENED" and sets stopReason: "guardrail_intervened" on Converse responses. The original text is not passed through — it is entirely suppressed. Use BLOCK for entities where even a pseudonymized placeholder reaching a downstream system is unacceptable: AWS credentials, raw payment card numbers, CVV codes, government ID numbers, and passwords fall into this category. If you accidentally assign BLOCK to a high-frequency entity like NAME or DATE_TIME, nearly every real-world input will be rejected, so test thoroughly before deploying.

There is one significant constraint: ANONYMIZE is only semantically valid for source: "OUTPUT" calls. When you call ApplyGuardrailCommand with source: "INPUT" and an entity is configured for ANONYMIZE, the guardrail will still apply the token replacement to the input text and return the redacted version in outputs[0].text — but the original content has been modified before reaching any downstream processing. This is intentional for some use cases (strip PII from user messages before they reach a foundation model) but surprising if you expected pass-through behavior.

When multiple entity types are configured in the same guardrail and a single piece of text triggers both a BLOCK entity and an ANONYMIZE entity, the most restrictive action wins: the response is blocked entirely. This means you cannot have a guardrail that BLOCK-s SSNs but ANONYMIZE-s names and expect to get back text with anonymized names when an SSN is also present — the entire output is suppressed.

// Illustrating the difference: same input, different action configurations

// Scenario A: NAME is ANONYMIZE — processing continues with token substitution
// Input:  "Please send the report to John Smith at john@example.com"
// Output from outputs[0].text: "Please send the report to {NAME} at {EMAIL}"
// action field: "NONE" — guardrail transformed but did not block

// Scenario B: EMAIL is BLOCK — entire response suppressed
// Input:  "Please send the report to John Smith at john@example.com"
// action field: "GUARDRAIL_INTERVENED" — no usable output text
// outputs[0].text will contain the blocked message string, not the original

// Scenario C: Both ANONYMIZE (NAME) and BLOCK (EMAIL) on same input
// action field: "GUARDRAIL_INTERVENED" — BLOCK wins, entire response suppressed
// Even though NAME was only configured for ANONYMIZE, the EMAIL BLOCK takes precedence

import {
  BedrockRuntimeClient,
  ApplyGuardrailCommand,
} 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.BEDROCK_GUARDRAIL_VERSION ?? 'DRAFT';

async function scanOutputForPII(rawText: string): Promise<{
  action: 'NONE' | 'GUARDRAIL_INTERVENED';
  safeText: string;
  detectedTypes: string[];
}> {
  const response = await runtime.send(new ApplyGuardrailCommand({
    guardrailIdentifier: GUARDRAIL_ID,
    guardrailVersion:    GUARDRAIL_VERSION,
    source:              'OUTPUT',   // ANONYMIZE is valid for OUTPUT
    content:             [{ text: { text: rawText } }],
  }));

  const action = (response.action ?? 'NONE') as 'NONE' | 'GUARDRAIL_INTERVENED';

  // Extract detected entity types from the assessment
  const piiEntities = response.assessments?.[0]
    ?.sensitiveInformationPolicy?.piiEntities ?? [];
  const regexMatches = response.assessments?.[0]
    ?.sensitiveInformationPolicy?.regexes ?? [];

  const detectedTypes = [
    ...piiEntities.map(e => e.type ?? 'UNKNOWN'),
    ...regexMatches.map(r => r.name ?? 'CUSTOM'),
  ];

  // outputs[0].text contains the anonymized text if ANONYMIZE was used,
  // or the blockedOutputsMessaging string if the action was BLOCK.
  // Fall back to empty string rather than the original if blocked —
  // never return raw text that triggered a BLOCK action.
  const safeText = action === 'NONE'
    ? (response.outputs?.[0]?.text ?? rawText)
    : '';

  return { action, safeText, detectedTypes };
}

ApplyGuardrailCommand — scanning MCP tool results

The most important use case for PII scanning in an MCP server is not filtering what the user sends in — it is filtering what an external API or database returns before that data is handed back to the calling LLM agent. MCP tools frequently call third-party REST APIs, internal microservices, or database stored procedures that return records containing personal data. If those records flow unexamined through your tool handler and back to the agent, any downstream LLM that processes them may store, log, or echo that PII in ways you cannot control.

ApplyGuardrailCommand is the right primitive here. It is in the @aws-sdk/client-bedrock-runtime package (not the control-plane @aws-sdk/client-bedrock package — a distinction that trips up many developers). The command takes a guardrailIdentifier, a guardrailVersion, a source ("INPUT" or "OUTPUT"), and a content array. The content array accepts text blocks in the shape { text: { text: string } } — note the double nesting: the outer object selects the content type (text vs image), and the inner object carries the actual string. This double-nesting is different from the shape used in ConverseCommand messages and is a common serialization mistake.

The response object has three fields you need to handle. action is either "NONE" or "GUARDRAIL_INTERVENED". assessments is an array aligned to the content input array — one assessment per content block — and each assessment contains the per-policy breakdown. outputs is also aligned to the content array and contains the transformed (anonymized) text; when no PII was detected or entities were only BLOCK-ed, outputs[0].text is the blocked message string, not the original — so never use outputs[0].text as a pass-through without first checking action.

import {
  BedrockRuntimeClient,
  ApplyGuardrailCommand,
  type ApplyGuardrailCommandInput,
  type ApplyGuardrailCommandOutput,
} from '@aws-sdk/client-bedrock-runtime';

// IMPORTANT: ApplyGuardrailCommand is in @aws-sdk/client-bedrock-runtime,
// NOT in @aws-sdk/client-bedrock.
// Install: npm install @aws-sdk/client-bedrock-runtime

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

interface ScanResult {
  safe: boolean;
  text: string;                          // anonymized text if safe, empty string if blocked
  piiEntitiesDetected: string[];         // e.g. ["NAME", "EMAIL", "US_SOCIAL_SECURITY_NUMBER"]
  customPatternsDetected: string[];      // regex config names that matched
  rawAssessment: ApplyGuardrailCommandOutput['assessments'];
}

async function scanToolResult(toolOutputText: string): Promise<ScanResult> {
  const input: ApplyGuardrailCommandInput = {
    guardrailIdentifier: GUARDRAIL_ID,
    guardrailVersion:    GUARDRAIL_VERSION,
    // source: "OUTPUT" — this is text we're about to return to an agent
    source: 'OUTPUT',
    content: [
      // Double-nested shape: { text: { text: "..." } }
      // The outer "text" key selects the content block type.
      // The inner "text" key carries the actual string value.
      { text: { text: toolOutputText } },
    ],
  };

  const response = await runtime.send(new ApplyGuardrailCommand(input));

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

  const piiEntitiesDetected = (assessment?.piiEntities ?? [])
    .map(e => e.type ?? 'UNKNOWN');

  const customPatternsDetected = (assessment?.regexes ?? [])
    .map(r => r.name ?? 'custom-pattern');

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

  // If safe, outputs[0].text contains the anonymized version of the input.
  // If action is ANONYMIZE and PII was found, entities are replaced with {TYPE} tokens.
  // If action is BLOCK, the content is suppressed entirely — do not use outputs[0].text
  // as a fallback because it contains the blockedOutputsMessaging string, not the data.
  const text = safe
    ? (response.outputs?.[0]?.text ?? toolOutputText)
    : '';

  return {
    safe,
    text,
    piiEntitiesDetected,
    customPatternsDetected,
    rawAssessment: response.assessments,
  };
}

The per-KB pricing model for ApplyGuardrailCommand means scanning large tool results incurs real cost. Measure the typical size of responses from each external API your MCP server calls and decide whether to scan the full payload or truncate to the first 25–50 KB for PII detection purposes. For tools that return large binary or structured data, extract the string fields that could contain PII and scan those selectively rather than JSON-serializing and scanning the entire response object.

Reading anonymized output from outputs[0].text

When a guardrail's PII policy is configured with ANONYMIZE and an entity is detected, Bedrock replaces the entity span in the text with a token and returns the modified string in response.outputs[0].text. The token format is {ENTITY_TYPE} in uppercase with curly braces — for example, {NAME}, {EMAIL}, {US_SOCIAL_SECURITY_NUMBER}. This is different from the square-bracket format [NAME] used in some AWS documentation examples and in the guardrail assessment objects — when you read the actual anonymized text from outputs[0].text, the tokens use curly braces.

If the same entity type appears multiple times in the text, each occurrence is replaced with the same token. For example, "Contact John Smith or Jane Doe" becomes "Contact {NAME} or {NAME}" — both name spans are replaced, and there is no way to distinguish which token was which person from the anonymized text alone. If your use case requires re-identification (a rare but legitimate scenario for some compliance workflows with an audit trail), you would need to implement a separate tokenization vault before the guardrail call.

The outputs array is parallel to the content input array, so outputs[0] corresponds to content[0]. If you supply multiple content blocks in a single ApplyGuardrailCommand call (which is valid), outputs[1] corresponds to content[1], and so on. Each outputs[n].text is the independently anonymized version of the corresponding input block. The assessments array follows the same alignment.

// Demonstrating the outputs[0].text structure and token format

async function demonstrateAnonymization() {
  const exampleApiResponse = `
    Customer record:
    Name: Sarah Johnson
    Email: sarah.johnson@example.com
    Phone: +1-555-0123
    SSN: 123-45-6789
    Account: 4532-1234-5678-9012
    IP address: 192.168.1.42
  `.trim();

  const response = await runtime.send(new ApplyGuardrailCommand({
    guardrailIdentifier: GUARDRAIL_ID,
    guardrailVersion:    GUARDRAIL_VERSION,
    source:              'OUTPUT',
    content:             [{ text: { text: exampleApiResponse } }],
  }));

  // response.action: "GUARDRAIL_INTERVENED" (SSN or credit card triggered BLOCK)
  // OR "NONE" if all matched types are configured for ANONYMIZE

  console.log('Guardrail action:', response.action);

  if (response.action === 'NONE') {
    // Anonymized output — tokens replace PII spans with curly-brace notation
    // e.g.: "Name: {NAME}\nEmail: {EMAIL}\nPhone: {PHONE}\nIP address: {IP_ADDRESS}"
    // Note: SSN would be {US_SOCIAL_SECURITY_NUMBER} if ANONYMIZE — but we configured BLOCK
    const anonymized = response.outputs?.[0]?.text ?? '';
    console.log('Anonymized text:', anonymized);
  }

  // The assessments array shows what was found regardless of action
  const piiFound = response.assessments?.[0]?.sensitiveInformationPolicy?.piiEntities ?? [];
  for (const entity of piiFound) {
    console.log(`Found PII: type=${entity.type}, action=${entity.action}`);
    // entity.action is "ANONYMIZED" (past tense) or "BLOCKED" — not the config values
    // The config values are "ANONYMIZE" / "BLOCK"; the assessment uses past-tense forms
  }

  // Custom regex matches appear separately in the assessments
  const regexMatches = response.assessments?.[0]?.sensitiveInformationPolicy?.regexes ?? [];
  for (const match of regexMatches) {
    console.log(`Regex match: name=${match.name}, action=${match.action}`);
  }
}

// Helper: extract the safe text from an ApplyGuardrail response,
// handling all three possible states.
function extractSafeText(
  response: ApplyGuardrailCommandOutput,
  originalText: string,
  fallbackOnBlock = '',
): string {
  if (response.action === 'GUARDRAIL_INTERVENED') {
    // A BLOCK was triggered — return the fallback, not the original
    return fallbackOnBlock;
  }
  // NONE: either no PII found (outputs[0].text === originalText)
  // or ANONYMIZE was applied (outputs[0].text has {TOKEN} replacements)
  return response.outputs?.[0]?.text ?? originalText;
}

One subtlety: when no PII is detected at all, outputs[0].text is an exact copy of the input text. The structure is always present in the response — you do not need to check whether outputs is non-empty before accessing index 0, as long as you passed at least one content block. That said, defensive programming with optional chaining (response.outputs?.[0]?.text) is still wise since SDK type signatures mark these fields as optional and future API versions could vary.

Custom regex patterns with regexesConfig

The built-in PIIEntityType detector covers common personal data categories well, but every organization has internal identifiers — employee IDs, account numbers, internal ticket references, proprietary token formats — that the built-in model will never recognize. The regexesConfig array in sensitiveInformationPolicyConfig lets you add custom patterns for these.

Each entry in regexesConfig requires three fields: name (a unique identifier for the pattern), pattern (a regular expression string), and action ("ANONYMIZE" or "BLOCK"). The description field is optional but strongly recommended — it documents the pattern's intent and appears in the guardrail configuration in the AWS console, making audit reviews easier. When a custom regex matches, the matched span in outputs[0].text is replaced with {name} using the name field value you provided, so choose a name that is meaningful in context.

There are three important constraints on custom regex patterns. First, all patterns are evaluated case-insensitively by default — you cannot change this per-pattern. Second, group captures are ignored: the guardrail matches the entire regex and replaces the full match span, not a captured group. If your pattern uses capturing groups to try to preserve a prefix, that will not work. Use non-capturing groups ((?:...)) for grouping without capturing if your pattern needs alternation or quantifier grouping. Third, there is no look-behind assertion support. If you need to match a pattern that follows a specific prefix (like detecting credit card numbers only after the word "card:"), you will need to handle that with two separate calls or a wider regex that includes the prefix in the match span itself.

// Creating a guardrail with a comprehensive regexesConfig

const regexGuardrailInput: CreateGuardrailCommandInput = {
  name: 'mcp-custom-pii-patterns',
  description: 'Guardrail combining built-in PII + org-specific identifier patterns',

  sensitiveInformationPolicyConfig: {
    piiEntitiesConfig: [
      { type: 'EMAIL', action: 'ANONYMIZE' },
      { type: 'PHONE', action: 'ANONYMIZE' },
    ],

    regexesConfig: [
      // Employee ID: EMP followed by exactly 6 digits
      // Non-capturing group used to avoid capture group issues
      {
        name:        'employee-id',
        description: 'Internal employee identifier (EMP + 6 digits)',
        pattern:     'EMP(?:\\d{6})',
        action:      'ANONYMIZE',
        // When matched, outputs[0].text will contain {employee-id} in place of the span
      },

      // Internal order reference: ORD- prefix with alphanumeric
      {
        name:        'order-reference',
        description: 'Order reference numbers: ORD-XXXX-XXXXXXXX',
        // The (?:) groups allow alternation without capture
        pattern:     'ORD-(?:[A-Z0-9]{4})-(?:[A-Z0-9]{8})',
        action:      'ANONYMIZE',
      },

      // Internal API secret — BLOCK rather than anonymize
      // Case-insensitive by default, so matches sk_live_ and SK_LIVE_ etc.
      {
        name:        'internal-api-secret',
        description: 'Internal API secret tokens starting with sk_live_ or sk_test_',
        // No look-behind support — include prefix in the pattern match span
        pattern:     'sk_(?:live|test)_[A-Za-z0-9]{32,64}',
        action:      'BLOCK',
      },

      // Healthcare record number — jurisdiction-specific format
      // Single-word inputs may miss detection; require surrounding context via regex
      {
        name:        'health-record-number',
        description: 'Patient health record numbers: HRN followed by 10 digits',
        pattern:     'HRN(?:\\d{10})',
        action:      'BLOCK',
      },

      // Note: NO look-behind assertions — this would be INVALID:
      // pattern: '(?<=account:\\s)\\d{12}'
      // Instead, include the prefix in the match:
      // pattern: 'account:\\s*(?:\\d{12})'  — but this replaces "account: 123456789012" entirely
    ],
  },

  blockedInputMessaging:  'Your request contains a restricted identifier.',
  blockedOutputsMessaging: 'The response contained a restricted identifier and was blocked.',
};

// After creating the guardrail, the name field shows up in assessment results:
// response.assessments[0].sensitiveInformationPolicy.regexes[0].name === 'employee-id'
// And in outputs[0].text the matched span is replaced with the name in curly braces:
// "Employee EMP123456 submitted..." becomes "Employee {employee-id} submitted..."

Test your custom regex patterns against edge cases before deploying. Patterns that are too broad — for example, a simple \\d{9} intended to catch SSNs — will match many non-PII numbers like ZIP+4 codes, invoice numbers, and tracking IDs. Patterns that are too narrow will miss valid formats. Use the guardrail's DRAFT version and call ApplyGuardrailCommand programmatically against a representative sample of your tool outputs to measure false-positive and false-negative rates before minting a production numeric version.

Full MCP tool handler with two-pass PII scanning

The two-pass pattern provides complete PII coverage for an MCP tool that calls an external API: scan the user's input before processing it (pass 1, source: "INPUT"), and scan the external API's response before returning it to the calling agent (pass 2, source: "OUTPUT"). This guards against two distinct threat vectors: a user deliberately submitting PII to have it stored or echoed by an external system, and an external API returning PII that would then be passed unexamined to the LLM agent.

The pass 1 scan on input serves a subtler purpose than it might appear. Even if you do not care whether the user's own PII reaches the external API (they may have consented to that), scanning input first prevents exfiltration attacks where an adversary crafts a request whose PII content — when reflected back in an API response — reveals something about other users' data. If you strip PII from the input before forwarding it to the external API, the API's response also cannot contain PII that was seeded by the attacker.

Pass 2 on the tool result is the more critical scan. External APIs have no knowledge of your guardrail policies and may return records containing arbitrary PII. Without scanning the response, any entity in those records flows directly to the LLM agent that invoked your MCP tool. The agent will process, potentially log, and may include that PII in its own responses to other downstream systems. This is the highest-risk data flow in an MCP architecture and the most important place to apply guardrail scanning.

import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import {
  BedrockRuntimeClient,
  ApplyGuardrailCommand,
  type ApplyGuardrailCommandOutput,
} 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.BEDROCK_GUARDRAIL_VERSION ?? 'DRAFT';

// Reusable helper: scan text with ApplyGuardrailCommand
async function applyGuardrail(
  text: string,
  source: 'INPUT' | 'OUTPUT',
): Promise<{ safe: boolean; safeText: string; detected: string[] }> {
  const response = await runtime.send(new ApplyGuardrailCommand({
    guardrailIdentifier: GUARDRAIL_ID,
    guardrailVersion:    GUARDRAIL_VERSION,
    source,
    content: [{ text: { text } }],
  }));

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

  const piiEntities = response.assessments?.[0]
    ?.sensitiveInformationPolicy?.piiEntities ?? [];
  const regexMatches = response.assessments?.[0]
    ?.sensitiveInformationPolicy?.regexes ?? [];

  const detected = [
    ...piiEntities.map(e => e.type ?? 'UNKNOWN'),
    ...regexMatches.map(r => r.name ?? 'custom'),
  ];

  // For ANONYMIZE entities: outputs[0].text has tokens like {NAME}, {EMAIL}
  // For BLOCK entities:     action === 'GUARDRAIL_INTERVENED', return empty string
  const safeText = safe
    ? (response.outputs?.[0]?.text ?? text)
    : '';

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

  return { safe, safeText, detected };
}

// Simulated external API call — in practice, fetch from a CRM, HR system, etc.
async function fetchExternalAPIData(query: string): Promise<string> {
  // This is a mock — real implementation would use fetch() or an API SDK
  return JSON.stringify({
    result: `Customer John Smith (SSN 123-45-6789) requested: ${query}`,
    contact: 'john.smith@acme.com',
    phone: '+1-555-9876',
  });
}

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

server.tool(
  'query_customer_database',
  'Query the customer database — applies PII scanning on both input and output',
  {
    query: z.string().min(1).max(2000).describe('Natural language query about a customer record'),
  },
  async ({ query }) => {
    // ── Pass 1: Scan user input (source: INPUT) ──────────────────────────────
    // Strip PII from the query before forwarding to external API.
    // This prevents seeding the API request with the user's own PII,
    // and prevents injection attacks that try to have PII echoed back.
    const inputScan = await applyGuardrail(query, 'INPUT');

    if (!inputScan.safe) {
      // A BLOCK entity was present in the user's query
      return {
        isError: true,
        content: [{
          type: 'text' as const,
          text: 'Your query contains restricted information that cannot be processed.',
        }],
      };
    }

    // Use the sanitized version of the query (PII replaced with tokens or stripped)
    const sanitizedQuery = inputScan.safeText;

    // ── External API call ─────────────────────────────────────────────────────
    let rawApiResponse: string;
    try {
      rawApiResponse = await fetchExternalAPIData(sanitizedQuery);
    } catch (err) {
      return {
        isError: true,
        content: [{ type: 'text' as const, text: 'External API call failed.' }],
      };
    }

    // ── Pass 2: Scan tool result (source: OUTPUT) ─────────────────────────────
    // The external API may return records containing PII — SSNs, emails, etc.
    // Scan before returning to the calling agent. ANONYMIZE replaces entity spans
    // with {TYPE} tokens; BLOCK suppresses the response entirely.
    const outputScan = await applyGuardrail(rawApiResponse, 'OUTPUT');

    if (!outputScan.safe) {
      // The API response contained a hard-blocked PII type (e.g. SSN configured as BLOCK)
      return {
        isError: true,
        content: [{
          type: 'text' as const,
          text: 'The database response contained restricted information and cannot be returned.',
        }],
      };
    }

    // outputScan.safeText has PII replaced with {NAME}, {EMAIL}, etc.
    // The calling LLM agent sees the anonymized version, not the raw PII.
    return {
      content: [{
        type: 'text' as const,
        text: outputScan.safeText,
      }],
    };
  },
);

Notice that the tool handler returns isError: true content blocks (not thrown exceptions) for both blocked inputs and blocked outputs. This is correct MCP error reporting: a content policy block is a business logic outcome, not an infrastructure failure, and the calling agent should receive a structured signal it can reason about rather than an unhandled exception that terminates the session. Log the detected entity types for compliance audit purposes but do not include the actual matched values in the log line — log only the type names and counts.

Production gotchas

Running PII scanning in production surfaces a range of non-obvious behaviors. These are the most common issues teams encounter after initial integration:

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

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

3. ANONYMIZE is only semantically appropriate for OUTPUT source. The technical behavior when using ANONYMIZE on source: "INPUT" is that the PII is replaced and the sanitized text is returned — but downstream processing receives the token-replaced version, not the original. If you expected the guardrail to pass the original text through unchanged (and only block on OUTPUT), that is not what happens. For input scanning, use BLOCK for entities you want to prevent entirely, or accept that ANONYMIZE on input will modify the text before forwarding.

4. When one entity is BLOCK and another is ANONYMIZE, BLOCK wins for the entire response. If a single call to ApplyGuardrailCommand (or a Converse invocation) triggers both a BLOCK entity and an ANONYMIZE entity, the response is blocked entirely — you will not receive partially-anonymized text. Plan your entity action assignments so that any combination you expect to co-occur in real data gives the right behavior. For example, if user messages frequently contain both names (ANONYMIZE) and email addresses (ANONYMIZE), that combination correctly returns anonymized text; but if they also occasionally contain AWS access keys (BLOCK), those messages are hard-blocked with no output.

5. Custom regex patterns do not support look-behind assertions. If you write (?<=prefix\s)\d+ expecting to match digits that follow a prefix without including the prefix in the replacement, the guardrail will reject the pattern at creation time with a validation error. Use non-capturing groups for alternation and quantifiers, and if you need to anchor a pattern to a context word, include the context word in the match and accept that it will be part of the replaced span in outputs[0].text.

6. ApplyGuardrailCommand charges per KB of content processed. At typical AWS pricing, scanning 100 KB of text per request at 1,000 requests per minute adds up quickly. For MCP tools that call APIs returning large JSON payloads, extract only the string-valued fields that realistically could contain PII before scanning — do not JSON-serialize and scan the entire response body including numeric IDs, timestamps, and boolean flags. Write a small extractor that walks the response object and collects leaf-level string values, then join them for the guardrail call.

7. The assessments[0].sensitiveInformationPolicy.piiEntities[n].action field uses past-tense values. When you read back the assessment to build an audit log, the action field on each detected entity is "ANONYMIZED" or "BLOCKED" (past tense), not the configuration values "ANONYMIZE" or "BLOCK". Code that compares the assessment action to the configuration values will silently mismatch. This applies to custom regex assessments too: assessments[0].sensitiveInformationPolicy.regexes[n].action will be "ANONYMIZED" or "BLOCKED".

8. Single-token entity values may be missed by the probabilistic detector. A standalone email address in a single-line input like john@example.com reliably triggers the EMAIL detector. But a single first name like John in isolation will almost never trigger the NAME detector — the model needs context to distinguish a name from a common word. Build this into your threat model: if the highest-risk PII types for your application appear in short, context-free strings, pair the guardrail with explicit application-layer validation (regex or format checks) rather than relying solely on the probabilistic detector.

// Production-safe wrapper that handles all gotchas above

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

interface PIIScanOptions {
  maxLengthKB?: number;    // truncate input to this size to control cost (default: 50)
  source: 'INPUT' | 'OUTPUT';
}

interface PIIScanResult {
  safe: boolean;
  safeText: string;
  // Past-tense values: "ANONYMIZED" | "BLOCKED"
  entitiesFound: Array<{ type: string; action: 'ANONYMIZED' | 'BLOCKED' }>;
  customPatternsFound: Array<{ name: string; action: 'ANONYMIZED' | 'BLOCKED' }>;
  truncated: boolean;
}

async function scanForPII(
  text: string,
  opts: PIIScanOptions,
): Promise<PIIScanResult> {
  const maxBytes = (opts.maxLengthKB ?? 50) * 1024;
  let truncated = false;
  let scanText = text;

  if (Buffer.byteLength(text, 'utf8') > maxBytes) {
    // Truncate to maxBytes, respecting UTF-8 character boundaries
    const buf = Buffer.from(text, 'utf8').subarray(0, maxBytes);
    scanText = buf.toString('utf8');
    truncated = true;
    console.warn(`PII scan input truncated from ${text.length} to ~${maxBytes} bytes`);
  }

  const response: ApplyGuardrailCommandOutput = await runtime.send(
    new ApplyGuardrailCommand({
      guardrailIdentifier: GUARDRAIL_ID,
      guardrailVersion:    GUARDRAIL_VERSION,
      source:              opts.source,
      content:             [{ text: { text: scanText } }],
    }),
  );

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

  // Assessment actions are PAST TENSE: "ANONYMIZED" and "BLOCKED"
  // (NOT "ANONYMIZE" / "BLOCK" — those are config-time values)
  const entitiesFound = (policy?.piiEntities ?? []).map(e => ({
    type:   e.type ?? 'UNKNOWN',
    action: (e.action ?? 'ANONYMIZED') as 'ANONYMIZED' | 'BLOCKED',
  }));

  const customPatternsFound = (policy?.regexes ?? []).map(r => ({
    name:   r.name ?? 'unknown-pattern',
    action: (r.action ?? 'ANONYMIZED') as 'ANONYMIZED' | 'BLOCKED',
  }));

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

  // Safe to use outputs[0].text only when action !== 'GUARDRAIL_INTERVENED'
  // For ANONYMIZE entities: contains {TOKEN} replacements
  // For BLOCK: contains the blocked message string — do NOT return this
  const safeText = safe
    ? (response.outputs?.[0]?.text ?? scanText)
    : '';

  return { safe, safeText, entitiesFound, customPatternsFound, truncated };
}

Structured audit logging for PII detection events

Compliance frameworks like GDPR, HIPAA, and SOC 2 require audit trails for PII access and processing events. When your MCP server scans tool inputs or outputs with ApplyGuardrailCommand, the assessment response contains exactly the information you need for a structured audit log: what type of PII was detected, what action was taken, what the guardrail version was, and when it happened. Emit this as a structured JSON log line to CloudWatch Logs, and use a CloudWatch metric filter to create operational metrics on PII detection rates per entity type.

Do not log the actual matched PII values — only log the entity types and counts. The assessment objects in the response do not expose the matched span text, which is the correct behavior for a PII detection service: you should never log the SSN or credit card number that triggered the guard, only that a detection event occurred. The outputs[0].text field contains the anonymized version with token placeholders, which you can safely log if needed for debugging (since the PII has been replaced).

interface PIIAuditEntry {
  event:            'pii_scan';
  ts:               string;
  toolName:         string;
  source:           'INPUT' | 'OUTPUT';
  guardrailId:      string;
  guardrailVersion: string;
  action:           'NONE' | 'GUARDRAIL_INTERVENED';
  entitiesBlocked:  string[];
  entitiesAnonymized: string[];
  customBlocked:    string[];
  customAnonymized: string[];
  truncated:        boolean;
  durationMs:       number;
}

async function scanWithAudit(
  text: string,
  source: 'INPUT' | 'OUTPUT',
  toolName: string,
): Promise<{ safe: boolean; safeText: string }> {
  const start = Date.now();

  const response = await runtime.send(new ApplyGuardrailCommand({
    guardrailIdentifier: GUARDRAIL_ID,
    guardrailVersion:    GUARDRAIL_VERSION,
    source,
    content: [{ text: { text: text } }],
  }));

  const durationMs = Date.now() - start;

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

  const piiEntities   = policy?.piiEntities ?? [];
  const regexMatches  = policy?.regexes ?? [];

  // Split by past-tense action values
  const entitiesBlocked    = piiEntities.filter(e => e.action === 'BLOCKED').map(e => e.type ?? 'UNKNOWN');
  const entitiesAnonymized = piiEntities.filter(e => e.action === 'ANONYMIZED').map(e => e.type ?? 'UNKNOWN');
  const customBlocked      = regexMatches.filter(r => r.action === 'BLOCKED').map(r => r.name ?? 'custom');
  const customAnonymized   = regexMatches.filter(r => r.action === 'ANONYMIZED').map(r => r.name ?? 'custom');

  const audit: PIIAuditEntry = {
    event:              'pii_scan',
    ts:                 new Date().toISOString(),
    toolName,
    source,
    guardrailId:        GUARDRAIL_ID,
    guardrailVersion:   GUARDRAIL_VERSION,
    action:             (response.action ?? 'NONE') as 'NONE' | 'GUARDRAIL_INTERVENED',
    entitiesBlocked,
    entitiesAnonymized,
    customBlocked,
    customAnonymized,
    truncated:          false,
    durationMs,
  };

  // Structured log — CloudWatch Logs Insights can query on these fields
  // e.g.: fields @timestamp, toolName, action, entitiesBlocked
  //       | filter action = "GUARDRAIL_INTERVENED"
  //       | stats count() by bin(1h)
  console.log(JSON.stringify(audit));

  const safe = response.action !== 'GUARDRAIL_INTERVENED';
  const safeText = safe
    ? (response.outputs?.[0]?.text ?? text)
    : '';

  return { safe, safeText };
}

Wire up a CloudWatch metric filter on the action field in the audit log line to create an PIIGuardrailInterventions CloudWatch metric. Set a CloudWatch alarm on that metric with a threshold appropriate for your expected traffic — a sudden spike in blocked PII typically indicates either a data quality regression in an upstream API, an attempted data exfiltration, or a misfired regex pattern that is producing false positives. All three scenarios warrant investigation, and the structured log gives you the entity types and tool names needed to triage quickly.

AliveMCP and PII leak monitoring

PII scanning with Bedrock Guardrails protects data flowing through your MCP tool handlers — but only when those handlers are running. AliveMCP monitors your MCP server endpoints around the clock, alerting you the moment a tool handler becomes unavailable, starts returning errors, or degrades in latency, so the guardrail layer is never silently bypassed due to an infrastructure fault.