Guide · Amazon Bedrock · Knowledge Base Retrieval

Amazon Bedrock Knowledge Base Metadata Filtering for MCP Servers — Attribute Filters and Multi-Tenant Isolation

Amazon Bedrock Knowledge Base metadata filtering lets MCP servers scope retrieval to a subset of documents without changing the query — by applying attribute filter expressions that evaluate against document-level metadata fields. Filters are specified in retrievalConfiguration.vectorSearchConfiguration.filter and work at both the chunk and document level: a chunk is returned only if the metadata attached to its parent document satisfies the filter expression. The two most common patterns are multi-tenant isolation (filtering by customerId or teamId so each user only retrieves their own documents) and content-type scoping (filtering by documentType to retrieve only release notes, only runbooks, or only API references). The most common failure mode is querying an attribute that was not indexed — Bedrock silently returns zero results instead of throwing an error, making it look like your query found nothing when the actual problem is a missing attribute schema. This guide covers the S3 .metadata.json file format, all supported filter operators, how to combine filters with andAll and orAll, and a TypeScript pattern for building filter expressions safely. For search mode selection (SEMANTIC vs HYBRID), see Hybrid Search. For single-call RAG with citations, see RetrieveAndGenerate. For data source sync, see Data Sources.

TL;DR

Attach a docs/my-file.pdf.metadata.json companion file in S3 beside each source document, with {"metadataAttributes": {"teamId": "platform", "docType": "runbook"}}. Add those attribute names to the knowledge base schema before syncing. Query with filter: { equals: { key: "teamId", value: { stringValue: "platform" } } } in vectorSearchConfiguration. Attributes not in the schema return zero results, not an error.

How metadata works in Bedrock Knowledge Base

When Bedrock ingests documents from an S3 data source, it looks for a companion metadata file for each source document. The metadata file must be in the same S3 prefix as the document, with the same filename plus a .metadata.json suffix. For example:

The metadata file is a JSON object with a metadataAttributes key containing key-value pairs. Each key is the attribute name and each value is the attribute content:

{
  "metadataAttributes": {
    "teamId": "platform",
    "docType": "runbook",
    "version": "2.1",
    "lastReviewedYear": 2026,
    "deprecated": false,
    "tags": ["deploy", "kubernetes", "rollback"]
  }
}

Bedrock stores these attributes alongside the chunk embeddings. At retrieval time, the filter expression is evaluated against these stored attributes before scores are computed — it is a pre-filter, not a post-filter. Only chunks whose parent document satisfies the filter are even considered for vector/BM25 scoring.

Attribute types

JSON type in .metadata.jsonBedrock attribute typeFilter value field
StringSTRINGstringValue
Number (integer or float)NUMBERnumberValue
BooleanBOOLEANbooleanValue
Array of stringsSTRING_LISTlistValue (array of strings)

Arrays of numbers or arrays of mixed types are not supported. If you need multi-value numeric filtering, store values as strings and use in/notIn rather than range operators.

Registering attributes in the knowledge base schema

An attribute must be declared in the knowledge base's metadata schema before it can be used in a filter. This is configured when creating the knowledge base (or by updating the data source configuration). In CDK:

import * as bedrock from "aws-cdk-lib/aws-bedrock";

const kb = new bedrock.CfnKnowledgeBase(this, "DocsKB", {
  name: "platform-docs",
  roleArn: kbRole.roleArn,
  knowledgeBaseConfiguration: {
    type: "VECTOR",
    vectorKnowledgeBaseConfiguration: {
      embeddingModelArn:
        "arn:aws:bedrock:us-east-1::foundation-model/amazon.titan-embed-text-v2:0",
    },
  },
  storageConfiguration: {
    type: "OPENSEARCH_SERVERLESS",
    opensearchServerlessConfiguration: {
      collectionArn: collection.attrArn,
      vectorIndexName: "bedrock-knowledge-base-index",
      fieldMapping: {
        vectorField: "embedding",
        textField: "text",
        metadataField: "metadata",
      },
    },
  },
});

const dataSource = new bedrock.CfnDataSource(this, "DocsS3", {
  knowledgeBaseId: kb.attrKnowledgeBaseId,
  name: "docs-s3",
  dataSourceConfiguration: {
    type: "S3",
    s3Configuration: {
      bucketArn: docsBucket.bucketArn,
      inclusionPrefixes: ["docs/"],
    },
  },
  vectorIngestionConfiguration: {
    customTransformationConfiguration: undefined,
    chunkingConfiguration: {
      chunkingStrategy: "SEMANTIC",
      semanticChunkingConfiguration: {
        maxTokens: 300,
        bufferSize: 1,
        breakpointPercentileThreshold: 95,
      },
    },
  },
});

As of late 2026, metadata attribute schema registration can also be done in the console under Knowledge base → Data source → Edit → Metadata and filtering. The schema takes effect on the next full sync — existing chunks do not have their metadata backfilled from new schema entries retroactively.

Gotcha: missing attribute returns zero results, not an error

If you filter on an attribute that was never added to the schema, or was added after the last sync but before the metadata files were present, Bedrock evaluates the filter against an empty attribute set. The filter expression equals: { key: "teamId", value: ... } against a document with no teamId attribute evaluates to false. Every document fails the filter. The API returns an empty retrievalResults array with HTTP 200. There is no FilterAttributeNotIndexed error. Always validate your schema includes every attribute you filter on before deploying to production.

Filter operators

OperatorApplies toDescription
equalsSTRING, NUMBER, BOOLEANExact equality match
notEqualsSTRING, NUMBER, BOOLEANExcludes exact match
inSTRING, NUMBERAttribute value is in the provided list
notInSTRING, NUMBERAttribute value is NOT in the provided list
startsWithSTRINGString prefix match
greaterThanNUMBERNumeric greater-than
greaterThanOrEqualsNUMBERNumeric ≥
lessThanNUMBERNumeric less-than
lessThanOrEqualsNUMBERNumeric ≤
listContainsSTRING_LISTArray attribute contains the specified string
andAllFilter combinatorAll child filters must match
orAllFilter combinatorAt least one child filter must match

TypeScript filter builder pattern

Building RetrievalFilter objects inline leads to deep nesting that is hard to read. A small builder function makes the common cases readable:

import type { RetrievalFilter } from "@aws-sdk/client-bedrock-agent-runtime";

function eq(key: string, value: string | number | boolean): RetrievalFilter {
  if (typeof value === "string")
    return { equals: { key, value: { stringValue: value } } };
  if (typeof value === "boolean")
    return { equals: { key, value: { booleanValue: value } } };
  return { equals: { key, value: { numberValue: value } } };
}

function inList(key: string, values: string[]): RetrievalFilter {
  return { in: { key, value: { listValue: values } } };
}

function listContains(key: string, item: string): RetrievalFilter {
  return { listContains: { key, value: { stringValue: item } } };
}

function and(...filters: RetrievalFilter[]): RetrievalFilter {
  return { andAll: filters };
}

function or(...filters: RetrievalFilter[]): RetrievalFilter {
  return { orAll: filters };
}

// Usage — retrieve only platform-team runbooks that are not deprecated
const filter = and(
  eq("teamId", "platform"),
  eq("docType", "runbook"),
  eq("deprecated", false),
);

// Usage — retrieve docs tagged with either "deploy" or "rollback"
const tagFilter = or(
  listContains("tags", "deploy"),
  listContains("tags", "rollback"),
);

Multi-tenant isolation pattern

For SaaS products that store per-customer documents in a shared knowledge base, metadata filtering is the enforcement mechanism that prevents cross-tenant data leakage. The pattern is to inject the caller's tenant ID as a mandatory filter in every retrieval call — never trust the calling agent to include it:

import {
  BedrockAgentRuntimeClient,
  RetrieveCommand,
} from "@aws-sdk/client-bedrock-agent-runtime";

const client = new BedrockAgentRuntimeClient({ region: "us-east-1" });

export async function retrieveForTenant(
  knowledgeBaseId: string,
  tenantId: string,
  query: string,
  additionalFilter?: RetrievalFilter,
): Promise<string[]> {
  const tenantFilter = eq("tenantId", tenantId);
  const combinedFilter = additionalFilter
    ? and(tenantFilter, additionalFilter)
    : tenantFilter;

  const response = await client.send(
    new RetrieveCommand({
      knowledgeBaseId,
      retrievalQuery: { text: query },
      retrievalConfiguration: {
        vectorSearchConfiguration: {
          numberOfResults: 10,
          overrideSearchType: "HYBRID",
          filter: combinedFilter,
        },
      },
    }),
  );

  return (response.retrievalResults ?? []).map((r) => r.content?.text ?? "");
}

The key design decision here: tenantId is never an optional parameter. The function signature enforces that every call includes a tenant scope. Failure to scope will silently return results from all tenants, so the defense must be in the retrieval layer rather than in the agent prompt.

Combining filters: andAll vs orAll nesting

Filters can be nested up to 5 levels deep. andAll and orAll are both variadic — they accept arrays of child filters, each of which can be an operator or another andAll/orAll. The most common nesting pattern is an outer andAll with one mandatory equality (e.g., tenant isolation) and an inner orAll for type enumeration:

// Retrieve platform-team docs that are either runbooks OR postmortems,
// and are not from the deprecated 1.x schema
const complexFilter = and(
  eq("tenantId", "platform"),
  or(
    eq("docType", "runbook"),
    eq("docType", "postmortem"),
  ),
  { notEquals: { key: "schemaVersion", value: { stringValue: "1.x" } } },
);

There is no explicit nesting depth error from the API when you exceed 5 levels — the request returns ValidationException with a message about the maximum filter depth. Test complex filters locally before deploying by calling RetrieveCommand with a small test query and verifying the result count matches expectations.

Metadata filtering with RetrieveAndGenerate

The same filter expressions work in RetrieveAndGenerateCommand within the retrieveAndGenerateConfiguration.knowledgeBaseConfiguration.retrievalConfiguration.vectorSearchConfiguration.filter path. The nesting is deeper but the filter object structure is identical. See RetrieveAndGenerate for the full configuration example including filter placement inside a RAG call.

Monitoring filter-scoped retrieval with AliveMCP

When metadata filtering is in use for multi-tenant isolation, a misconfigured filter — wrong attribute name, wrong type, or stale tenant ID — returns zero results rather than an error. From the agent's perspective, the knowledge base "has no relevant information", which produces hallucinated responses. AliveMCP monitors your retrieval MCP tool for unexpected zero-result response rates: a sudden spike in empty retrievalResults arrays is a signal that a filter misconfiguration or ingestion job failure has silently broken scoping for one or more tenants.

Related pages in this arc

For the foundational overview, see Bedrock Knowledge Base for MCP Servers.