Guide · Amazon Bedrock · Knowledge Base Retrieval
Amazon Bedrock Knowledge Base Hybrid Search for MCP Servers — SEMANTIC vs HYBRID Mode
Amazon Bedrock Knowledge Base supports three retrieval modes — SEMANTIC, HYBRID, and HYBRID_SEARCH_AUTO — controlled via the overrideSearchType field in RetrieveCommand. SEMANTIC mode uses only vector similarity (cosine distance in the embedding space). HYBRID mode combines vector similarity with BM25 keyword matching and merges the two result sets using Reciprocal Rank Fusion (RRF). For MCP tool handlers that surface knowledge base results to AI agents, the right mode depends on query character: conceptual questions favor SEMANTIC, while exact-term lookups — model names, error codes, product identifiers, AWS service names — favor HYBRID. The most common mistake is leaving overrideSearchType unset (which defaults to SEMANTIC) and observing poor retrieval on queries like "ListInferenceProfilesCommand returns empty" because the query contains identifiers that BM25 handles better than dense vectors. This guide covers the mechanics of each mode, the numberOfResults knob, score-based post-filtering, and a complete TypeScript pattern for a retrieval tool that selects the search mode at call time. For filtering results by document attributes, see Metadata Filtering. For end-to-end RAG in a single call, see RetrieveAndGenerate. For data source sync and chunking, see Data Sources.
TL;DR
Set overrideSearchType: "HYBRID" in vectorSearchConfiguration for queries that contain product names, error codes, or exact identifiers. Use "SEMANTIC" for conceptual questions. Use "HYBRID_SEARCH_AUTO" to let Bedrock decide per query. Set numberOfResults to 10–20 for LLM reranking, or 3–5 for direct injection. HYBRID requires an OpenSearch vector store; SEMANTIC works with all storage backends.
Why search mode matters for MCP server retrieval tools
An MCP server that wraps a Bedrock Knowledge Base typically exposes one or more retrieval tools: search_docs, query_knowledge_base, or find_relevant_context. The AI agent calling those tools issues queries derived from its current task — sometimes conversational ("what are the retry guidelines for Bedrock?"), sometimes literal ("ThrottlingException from BedrockRuntimeClient when using us. prefix").
Dense vector retrieval is excellent at the first type of query. The embedding model encodes the semantic meaning of the sentence and finds chunks that are conceptually close, even if no keywords overlap. But dense vectors struggle with the second type: a query that contains a specific API method name, an exception class, or a product version string often retrieves conceptually related chunks that do not actually mention the identifier. BM25 keyword matching handles these cases because it rewards exact token overlap.
Hybrid search runs both methods independently and merges the ranked lists with Reciprocal Rank Fusion, a rank-aggregation algorithm that promotes documents appearing near the top of both lists while still surfacing documents that scored highly in just one. For a knowledge base about AWS services that contains both conceptual explanations and SDK reference material, hybrid mode nearly always outperforms pure semantic mode.
The three search modes
| Mode | How it works | Requires OpenSearch? | Best for |
|---|---|---|---|
SEMANTIC | Vector similarity only (cosine in embedding space) | No — works with all storage backends (OpenSearch, Aurora pgvector, Pinecone, MongoDB, Redis) | Conceptual, paraphrased, or intent-based queries |
HYBRID | BM25 + vector, merged with Reciprocal Rank Fusion | Yes — BM25 index requires OpenSearch | Exact identifier lookups, error codes, API names, mixed queries |
HYBRID_SEARCH_AUTO | Bedrock classifies the query and routes to SEMANTIC or HYBRID | Yes (falls back to SEMANTIC if no OpenSearch) | General-purpose tool where query type varies at runtime |
HYBRID_SEARCH_AUTO was introduced in mid-2026. If you are on an SDK version older than @aws-sdk/client-bedrock-agent-runtime@3.600.0, the value will be unknown to the client but the service still accepts it; upgrade the SDK to get TypeScript type safety for this enum member.
Gotcha: HYBRID silently degrades to SEMANTIC on non-OpenSearch backends
If your knowledge base uses Aurora pgvector, Pinecone, MongoDB Atlas, or Redis as the vector store, Bedrock does not have a BM25 index to query. Setting overrideSearchType: "HYBRID" does not throw an error — it silently falls back to SEMANTIC retrieval. You will not get an error response, just semantic-only results. The retrieval response does not indicate which mode was actually used. If your knowledge base was created with a non-OpenSearch backend and you need hybrid search, you must recreate the knowledge base with an OpenSearch Serverless collection.
RetrieveCommand with hybrid search
The overrideSearchType field lives inside retrievalConfiguration.vectorSearchConfiguration. The structure is straightforward but easy to confuse with the top-level retrievalConfiguration wrapper:
import {
BedrockAgentRuntimeClient,
RetrieveCommand,
type RetrieveCommandInput,
} from "@aws-sdk/client-bedrock-agent-runtime";
const client = new BedrockAgentRuntimeClient({ region: "us-east-1" });
export interface RetrievalResult {
text: string;
score: number;
sourceUri?: string;
metadata?: Record<string, string | number | boolean | string[]>;
}
export async function retrieveHybrid(
knowledgeBaseId: string,
query: string,
numberOfResults = 10,
): Promise<RetrievalResult[]> {
const input: RetrieveCommandInput = {
knowledgeBaseId,
retrievalQuery: { text: query },
retrievalConfiguration: {
vectorSearchConfiguration: {
numberOfResults,
overrideSearchType: "HYBRID",
},
},
};
const response = await client.send(new RetrieveCommand(input));
const results = response.retrievalResults ?? [];
return results.map((r) => ({
text: r.content?.text ?? "",
score: r.score ?? 0,
sourceUri: r.location?.s3Location?.uri
?? r.location?.webLocation?.url
?? undefined,
metadata: r.metadata as Record<string, string | number | boolean | string[]> | undefined,
}));
}
The response includes a score field on each RetrievalResult. This score is not normalized — it is a relative ranking signal within the result set, not a probability. Do not use it as a threshold across different queries or knowledge bases. Use it only for within-query filtering: for example, dropping results with score < 0.3 * topScore to remove stragglers when the top result is very strong.
Choosing numberOfResults
The numberOfResults parameter controls how many chunks Bedrock returns before any downstream filtering you apply. The right value depends on what you do with the results:
| Use case | Recommended value | Reasoning |
|---|---|---|
| Direct injection into LLM context window | 3–5 | Inject top-N chunks verbatim; too many chunks dilute the signal and push out context |
| LLM reranking (ask the model to pick the best chunks) | 10–20 | Give the LLM enough candidates; it will select the 3–5 most relevant |
| Keyword summary / entity extraction across corpus | 50–100 | Broad sweep; score-filter afterward |
| RetrieveAndGenerateCommand (RAG in one call) | Not applicable — set via numberOfResults in generationConfiguration | RetrieveAndGenerate uses a separate config object |
The API maximum for numberOfResults is 100. Requesting more than 100 throws ValidationException: numberOfResults must be less than or equal to 100. There is no way to paginate a retrieval query — the assumption is that the top-100 results cover the useful signal for any query.
Score-based post-filtering
After retrieval, MCP tool handlers commonly apply a score cutoff to drop low-quality results before passing chunks to the calling agent:
export async function retrieveWithScoreCutoff(
knowledgeBaseId: string,
query: string,
options: {
numberOfResults?: number;
minScoreRatio?: number; // 0–1; fraction of top score
searchType?: "SEMANTIC" | "HYBRID" | "HYBRID_SEARCH_AUTO";
} = {},
): Promise<RetrievalResult[]> {
const {
numberOfResults = 15,
minScoreRatio = 0.25,
searchType = "HYBRID",
} = options;
const raw = await retrieveHybrid(knowledgeBaseId, query, numberOfResults);
if (raw.length === 0) return [];
const topScore = raw[0].score; // results are pre-sorted descending by score
if (topScore === 0) return raw; // all scores zero — return everything
return raw.filter((r) => r.score >= topScore * minScoreRatio);
}
Using a ratio of the top score (rather than an absolute threshold) is robust across query types. A conceptual question might return all results with scores in the 0.7–0.9 range; a very specific identifier query might return a top result at 0.95 and a tail at 0.1. The ratio filter handles both without manual calibration.
Mode-aware MCP tool handler
For MCP servers that expose retrieval as a tool, it is useful to let the calling agent specify the search mode — or to auto-select based on a heuristic:
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
const KNOWLEDGE_BASE_ID = process.env.BEDROCK_KB_ID!;
const server = new McpServer({ name: "docs-retrieval", version: "1.0.0" });
server.tool(
"search_knowledge_base",
{
query: z.string().describe("The search query"),
mode: z
.enum(["auto", "semantic", "hybrid"])
.default("auto")
.describe("Search mode: 'hybrid' for exact terms, 'semantic' for concepts, 'auto' to decide"),
max_results: z.number().int().min(1).max(20).default(8),
},
async ({ query, mode, max_results }) => {
// Heuristic: if query contains uppercase identifiers or camelCase method names, prefer hybrid
const looksLiteral = /[A-Z]{2,}|[a-z][A-Z]/.test(query);
const searchType =
mode === "semantic" ? "SEMANTIC"
: mode === "hybrid" ? "HYBRID"
: looksLiteral ? "HYBRID"
: "HYBRID_SEARCH_AUTO";
const results = await retrieveWithScoreCutoff(KNOWLEDGE_BASE_ID, query, {
numberOfResults: max_results,
searchType,
});
if (results.length === 0) {
return { content: [{ type: "text", text: "No relevant documents found." }] };
}
const formatted = results
.map((r, i) => `[${i + 1}] (score: ${r.score.toFixed(3)}) ${r.text}`)
.join("\n\n---\n\n");
return { content: [{ type: "text", text: formatted }] };
},
);
await server.connect(transport);
The identifier heuristic (/[A-Z]{2,}|[a-z][A-Z]/) catches most SDK method names and AWS error codes that benefit from BM25. It is a rough proxy — feel free to replace it with a more domain-specific check for your knowledge base content.
Pagination and the nextToken field
The RetrieveCommand response includes a nextToken field. This is not a standard pagination token for retrieving more results for the same query — it is used by Bedrock internally and is not publicly documented as pageable in the standard sense. If nextToken appears in a response, the safest practice is to increase numberOfResults rather than attempting to paginate, as the semantics of passing nextToken back in a subsequent call may change between API versions. If you need more than 100 results, consider a client-side fan-out: issue multiple queries with different phrasings of the original question and deduplicate by chunk ID.
Monitoring retrieval quality with AliveMCP
Retrieval quality degradation is subtle: the knowledge base still returns results, but they are the wrong chunks. AliveMCP can monitor your retrieval MCP tool at the call level — tracking latency, error rate, and tool call frequency — so you are alerted immediately if the RetrieveCommand starts throwing ResourceNotFoundException (knowledge base ID changed or deleted), ServiceQuotaExceededException (rate limit on retrievals per knowledge base), or ValidationException (invalid filter expression after a schema change). Without active monitoring, retrieval failures often manifest as silent quality regressions in agent outputs rather than explicit errors.
Related pages in this arc
- Metadata Filtering — attribute filter expressions, S3 .metadata.json structure, multi-tenant isolation patterns
- RetrieveAndGenerate — single-call RAG, citations, sessionId for multi-turn conversation, guardrail embedding
- Data Sources — S3 vs web crawler vs Confluence, chunking strategies, ingestion job polling
For the foundational Bedrock Knowledge Base overview, see Bedrock Knowledge Base for MCP Servers. For embedding generation patterns, see Bedrock Embeddings.