Guide · Amazon Bedrock · Reranking · Knowledge Bases

MCP Server Bedrock Reranking — Knowledge Base source type, combined retrieve and rerank

When your documents live in an Amazon Bedrock Knowledge Base, the KNOWLEDGE_BASE source type lets you retrieve and rerank in a single RerankCommand call rather than chaining a separate RetrieveCommand followed by an inline reranking call. This reduces round-trips and simplifies error handling in MCP tool handlers. Three aspects of the Knowledge Base source type differ from inline reranking: the retrieval configuration is embedded inside the source definition rather than being a separate API call, so you configure vector search parameters, hybrid search type, and metadata filters all within the source; the response schema differs from inline reranking — results contain the Knowledge Base citation data (source location, text excerpt, metadata) rather than a simple index-back-to-your-array structure; and you cannot mix KNOWLEDGE_BASE and INLINE sources in the same call, so if you need to rerank documents from multiple sources including non-KB sources, you must retrieve from the KB separately and then merge into an inline reranking call. For inline document reranking see inline reranking; for model selection see Cohere vs Amazon Rerank 1; for the base RerankCommand structure see Bedrock Reranking overview.

TL;DR

Use type: "KNOWLEDGE_BASE" in sources and embed your retrieval configuration in knowledgeBaseSource.retrieve. The response rerankingResults contains the KB retrieved content with relevance scores instead of index references. For multi-KB or KB + custom vector store scenarios, retrieve separately then rerank as inline documents.

KNOWLEDGE_BASE source type: combined retrieve + rerank

The KNOWLEDGE_BASE source type embeds a retrieval call inside the reranking request. Bedrock retrieves documents from the Knowledge Base and then passes them directly to the reranking model — you never see the intermediate retrieved-but-not-reranked list. This is the simplest pattern when your document corpus lives entirely in one Bedrock Knowledge Base:

import {
  BedrockAgentRuntimeClient,
  RerankCommand,
} from "@aws-sdk/client-bedrock-agent-runtime";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";

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

const AMAZON_RERANK_ARN =
  "arn:aws:bedrock:us-east-1::foundation-model/amazon.rerank-v1:0";

const KB_ID = process.env.KNOWLEDGE_BASE_ID ?? "";

const server = new McpServer({ name: "kb-rag-server", version: "1.0.0" });

server.tool(
  "search_knowledge_base",
  { query: z.string().describe("Search query") },
  async ({ query }) => {
    const response = await client.send(
      new RerankCommand({
        rerankingConfiguration: {
          type: "BEDROCK_RERANKING_MODEL",
          bedrockRerankingConfiguration: {
            modelConfiguration: {
              modelArn: AMAZON_RERANK_ARN,
            },
            numberOfResults: 5, // return top 5 after reranking
          },
        },
        sources: [
          {
            type: "KNOWLEDGE_BASE",
            knowledgeBaseSource: {
              retrieve: {
                knowledgeBaseId: KB_ID,
                retrievalQuery: {
                  text: query,
                },
                retrievalConfiguration: {
                  vectorSearchConfiguration: {
                    numberOfResults: 20, // retrieve 20, rerank to top 5
                  },
                },
              },
            },
          },
        ],
        query: {
          type: "TEXT",
          textQuery: { text: query },
        },
      })
    );

    const results = response.rerankingResults ?? [];
    if (results.length === 0) {
      return { content: [{ type: "text", text: "No relevant results found." }] };
    }

    const formatted = results.map((r, i) => {
      const score = (r.relevanceScore ?? 0).toFixed(3);
      // For KB sources, content is in r.document?.text or retrieved chunk content
      return `[${i + 1}] score=${score}\n${extractResultText(r)}`;
    }).join("\n\n---\n\n");

    return { content: [{ type: "text", text: formatted }] };
  }
);

function extractResultText(result: { relevanceScore?: number; [key: string]: unknown }): string {
  // The exact shape depends on SDK version — check for text content
  const doc = (result as Record<string, unknown>).document as Record<string, unknown> | undefined;
  if (doc?.text) return doc.text as string;
  return JSON.stringify(result).slice(0, 500);
}

Notice the retrieval configuration uses numberOfResults: 20 at the KB level (fetch 20 candidates) while the reranking configuration uses numberOfResults: 5 (keep top 5 after reranking). This retrieve-more-rerank-less pattern is the core value of reranking — the vector retrieval layer casts a wide net for semantic matches, and the reranker selects the most precisely relevant documents from that wider set.

Response structure for Knowledge Base sources

The response from a Knowledge Base source reranking call differs from inline reranking. Instead of index references back to your original document array, each result contains the retrieved Knowledge Base chunk data inline — text content, source location, and metadata:

// Type annotations showing the shape of KB reranking results
interface KBRerankResult {
  relevanceScore?: number;
  document?: {
    text?: string; // The retrieved chunk text
    // Additional fields may be present depending on KB data source type
  };
  // KB-specific citation fields (shape varies by SDK version)
  // Check response in development to confirm exact field names
}

// Practical parsing: extract text and score from KB results
interface ParsedKBResult {
  text: string;
  score: number;
  rank: number;
}

function parseKBResults(
  results: Array<{ relevanceScore?: number; document?: { text?: string } }>
): ParsedKBResult[] {
  return results
    .map((r, i) => ({
      text: r.document?.text ?? "(no text)",
      score: r.relevanceScore ?? 0,
      rank: i + 1,
    }))
    .filter((r) => r.text !== "(no text)");
}

// In production: log the full response object in development
// to confirm field names for your SDK version and KB data source type
async function debugKBReranking(query: string) {
  const response = await client.send(new RerankCommand({ /* ... */ }));
  console.log(JSON.stringify(response.rerankingResults?.[0], null, 2));
  // Inspect the actual structure before writing production parsing code
}

The KB source response structure may include citation metadata beyond just the text — source location (S3 URI, Web URL, or Confluence page ID depending on your KB data source type), chunk metadata, and document attributes. The exact fields depend on your SDK version and KB configuration. Always log the first result during development to confirm the shape before writing production parsing code, since the SDK types may be more permissive (unknown or Record<string, unknown>) than the actual response.

Hybrid search with reranking

Bedrock Knowledge Bases support hybrid search (combining semantic vector search with keyword BM25 search). When using the KNOWLEDGE_BASE source type for reranking, you can enable hybrid search in the retrieval configuration, which typically improves the initial candidate pool before reranking:

const response = await client.send(
  new RerankCommand({
    rerankingConfiguration: {
      type: "BEDROCK_RERANKING_MODEL",
      bedrockRerankingConfiguration: {
        modelConfiguration: { modelArn: AMAZON_RERANK_ARN },
        numberOfResults: 5,
      },
    },
    sources: [
      {
        type: "KNOWLEDGE_BASE",
        knowledgeBaseSource: {
          retrieve: {
            knowledgeBaseId: KB_ID,
            retrievalQuery: { text: query },
            retrievalConfiguration: {
              vectorSearchConfiguration: {
                numberOfResults: 20,
                overrideSearchType: "HYBRID", // enables BM25 + semantic
              },
            },
          },
        },
      },
    ],
    query: { type: "TEXT", textQuery: { text: query } },
  })
);

// HYBRID retrieval + reranking is particularly effective for:
// 1. Technical queries with specific identifiers (function names, error codes)
//    where BM25 keyword matching improves recall
// 2. Short queries where semantic embedding has less signal
// 3. Domain-specific vocabulary that embedding models may underweight

Hybrid search and reranking complement each other well: hybrid retrieval improves the recall of the initial 20 candidates (fewer relevant documents missed), and reranking improves the precision of the final 5 (better ranking within the retrieved set). Using both together gives you a higher quality final context window than either technique alone. For detailed hybrid search configuration see Bedrock KB Hybrid Search.

Metadata filtering in Knowledge Base source reranking

The retrieval configuration inside the Knowledge Base source supports the same metadata filter syntax as a standalone RetrieveCommand. You can filter the candidate pool before reranking, ensuring that only documents matching certain attribute values are considered:

const response = await client.send(
  new RerankCommand({
    rerankingConfiguration: {
      type: "BEDROCK_RERANKING_MODEL",
      bedrockRerankingConfiguration: {
        modelConfiguration: { modelArn: AMAZON_RERANK_ARN },
        numberOfResults: 5,
      },
    },
    sources: [
      {
        type: "KNOWLEDGE_BASE",
        knowledgeBaseSource: {
          retrieve: {
            knowledgeBaseId: KB_ID,
            retrievalQuery: { text: query },
            retrievalConfiguration: {
              vectorSearchConfiguration: {
                numberOfResults: 20,
                overrideSearchType: "HYBRID",
                filter: {
                  // Only include documents with product = "enterprise"
                  equals: {
                    key: "product_tier",
                    value: "enterprise",
                  },
                },
              },
            },
          },
        },
      },
    ],
    query: { type: "TEXT", textQuery: { text: query } },
  })
);

// Compound filter example: product tier AND document version
const compoundFilter = {
  andAll: [
    { equals: { key: "product_tier", value: "enterprise" } },
    { greaterThan: { key: "doc_version", value: 2 } },
  ],
};

// Use compoundFilter in vectorSearchConfiguration.filter for multi-condition filtering

Metadata filtering restricts the retrieval pool before it reaches the reranker — only documents passing the filter are retrieved and scored. This is different from post-filtering after reranking, which would be wasteful (you'd retrieve and score documents you then discard). Pre-filter with metadata, then rerank the filtered set for maximum efficiency. For the full metadata filter operator reference see Bedrock KB Metadata Filtering.

Full RAG pipeline: retrieve → rerank → generate

The complete pattern for an MCP tool that combines KB reranking with generation creates a pipeline where retrieval quality directly controls generation quality. Here is a production-ready implementation using Bedrock Reranking (KB source) followed by Claude via ConverseCommand:

import { BedrockRuntimeClient, ConverseCommand } from "@aws-sdk/client-bedrock-runtime";
import { BedrockAgentRuntimeClient, RerankCommand } from "@aws-sdk/client-bedrock-agent-runtime";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";

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

const CLAUDE_MODEL = "us.anthropic.claude-sonnet-4-6-20251101-v1:0";
const AMAZON_RERANK_ARN =
  "arn:aws:bedrock:us-east-1::foundation-model/amazon.rerank-v1:0";
const KB_ID = process.env.KNOWLEDGE_BASE_ID ?? "";

const server = new McpServer({ name: "rag-server", version: "1.0.0" });

server.tool(
  "answer_question",
  {
    question: z.string().describe("Question to answer using the knowledge base"),
    min_score: z.number().min(0).max(1).default(0.2),
  },
  async ({ question, min_score }) => {
    // Step 1: Retrieve + Rerank (single call via KB source type)
    const rerankResponse = await agentRuntimeClient.send(
      new RerankCommand({
        rerankingConfiguration: {
          type: "BEDROCK_RERANKING_MODEL",
          bedrockRerankingConfiguration: {
            modelConfiguration: { modelArn: AMAZON_RERANK_ARN },
            numberOfResults: 8, // keep top 8 for generation context
          },
        },
        sources: [{
          type: "KNOWLEDGE_BASE",
          knowledgeBaseSource: {
            retrieve: {
              knowledgeBaseId: KB_ID,
              retrievalQuery: { text: question },
              retrievalConfiguration: {
                vectorSearchConfiguration: {
                  numberOfResults: 25, // wide retrieval net
                  overrideSearchType: "HYBRID",
                },
              },
            },
          },
        }],
        query: { type: "TEXT", textQuery: { text: question } },
      })
    );

    const results = rerankResponse.rerankingResults ?? [];

    // Apply relevance threshold
    const relevant = results.filter(
      (r) => (r.relevanceScore ?? 0) >= min_score
    );

    if (relevant.length === 0) {
      return {
        content: [{
          type: "text",
          text: "I couldn't find relevant information in the knowledge base to answer this question.",
        }],
      };
    }

    // Build context from reranked results
    const context = relevant
      .map((r, i) => {
        const text = (r as Record<string, unknown>).document
          ? ((r as Record<string, unknown>).document as Record<string, unknown>).text as string
          : "(content unavailable)";
        return `[Source ${i + 1}, relevance=${(r.relevanceScore ?? 0).toFixed(2)}]\n${text}`;
      })
      .join("\n\n");

    // Step 2: Generate answer using the reranked context
    const generateResponse = await runtimeClient.send(
      new ConverseCommand({
        modelId: CLAUDE_MODEL,
        system: [{
          text: `You are a helpful assistant. Answer questions using ONLY the provided context.
If the context does not contain sufficient information, say so explicitly.
Always cite which source numbers you used in your answer.`,
        }],
        messages: [{
          role: "user",
          content: [{
            text: `Context:\n${context}\n\nQuestion: ${question}`,
          }],
        }],
        inferenceConfig: {
          maxTokens: 1024,
          temperature: 0.1,
        },
      })
    );

    const answer = generateResponse.output?.message?.content?.[0]?.text
      ?? "Failed to generate answer.";

    return {
      content: [{
        type: "text",
        text: answer,
      }],
    };
  }
);

This pipeline has two sequential API calls: one to Bedrock Agent Runtime for the reranked retrieval, and one to Bedrock Runtime for generation. The min_score parameter — exposed as a tool input — lets the calling agent adjust how strict the relevance filter is. A low-confidence agent might set it to 0.1 to get broader context; a high-confidence agent might set it to 0.6 to ensure only highly relevant documents enter the generation step.

Separate retrieve then inline rerank: when to prefer it

Using the KNOWLEDGE_BASE source type is simpler but less flexible than doing a separate RetrieveCommand followed by inline reranking. The KB source type is the right choice when all your documents are in one Knowledge Base and you don't need to inspect the intermediate retrieved-but-not-reranked results. The separate approach is better when:

// Scenario: documents from multiple sources need a unified reranking
// KB source type can't mix sources — inline reranking can

async function hybridMultiSourceSearch(query: string) {
  // Retrieve from two separate Knowledge Bases concurrently
  const [kb1Results, kb2Results] = await Promise.all([
    retrieveFromKB(query, process.env.KB_ID_1!),
    retrieveFromKB(query, process.env.KB_ID_2!),
  ]);

  // Convert to inline documents for unified reranking
  const allDocs = [
    ...kb1Results.map((r) => ({
      id: `kb1-${r.metadata?.chunk_id}`,
      text: r.content.text ?? "",
      source: "kb1",
    })),
    ...kb2Results.map((r) => ({
      id: `kb2-${r.metadata?.chunk_id}`,
      text: r.content.text ?? "",
      source: "kb2",
    })),
  ].filter((d) => d.text.length > 0);

  if (allDocs.length === 0) return [];

  // Rerank the merged list as inline documents
  const safeTopN = Math.min(5, allDocs.length);
  const response = await agentRuntimeClient.send(
    new RerankCommand({
      rerankingConfiguration: {
        type: "BEDROCK_RERANKING_MODEL",
        bedrockRerankingConfiguration: {
          modelConfiguration: {
            modelArn: AMAZON_RERANK_ARN,
          },
          numberOfResults: safeTopN,
        },
      },
      sources: allDocs.map((doc) => ({
        type: "INLINE",
        inlineDocumentSource: {
          type: "TEXT",
          textDocument: { text: doc.text },
        },
      })),
      query: { type: "TEXT", textQuery: { text: query } },
    })
  );

  return (response.rerankingResults ?? []).map((r) => ({
    ...allDocs[r.index!],
    score: r.relevanceScore ?? 0,
  }));
}

// Retrieve helper using RetrieveCommand
import { RetrieveCommand } from "@aws-sdk/client-bedrock-agent-runtime";

async function retrieveFromKB(
  query: string,
  kbId: string,
  limit: number = 10
) {
  const response = await agentRuntimeClient.send(
    new RetrieveCommand({
      knowledgeBaseId: kbId,
      retrievalQuery: { text: query },
      retrievalConfiguration: {
        vectorSearchConfiguration: {
          numberOfResults: limit,
          overrideSearchType: "HYBRID",
        },
      },
    })
  );
  return response.retrievalResults ?? [];
}

The multi-KB pattern retrieves from two KBs in parallel with Promise.all, then merges and reranks inline. The reranker normalizes the relevance scores across both KBs, eliminating the problem of incomparable similarity scores from different embedding spaces. This is a good architecture for MCP servers that federate domain-specific Knowledge Bases (e.g., one KB for product documentation, one for support tickets) where a single query might need context from both.

RetrieveAndGenerateCommand vs Rerank + Converse

Bedrock also offers a RetrieveAndGenerateCommand that combines KB retrieval, context injection, and generation in a single API call. The difference versus using RerankCommand plus ConverseCommand separately:

// Option A: RetrieveAndGenerateCommand
// - Single API call
// - Bedrock manages context window injection
// - Less control over retrieved documents before they enter context
// - Response includes citations automatically
// - Cannot apply a reranking step between retrieval and generation

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

const ragResponse = await agentRuntimeClient.send(
  new RetrieveAndGenerateCommand({
    input: { text: question },
    retrieveAndGenerateConfiguration: {
      type: "KNOWLEDGE_BASE",
      knowledgeBaseConfiguration: {
        knowledgeBaseId: KB_ID,
        modelArn: CLAUDE_MODEL,
        retrievalConfiguration: {
          vectorSearchConfiguration: { numberOfResults: 10 },
        },
      },
    },
  })
);

// Option B: RerankCommand (KB source) + ConverseCommand
// - Two API calls
// - You control document selection after reranking
// - Apply relevance threshold to filter low-quality candidates
// - Format context window explicitly
// - Integrate results from non-KB sources

// Use RetrieveAndGenerateCommand when:
// - Simplicity matters more than retrieval precision
// - Citations need to be automatically formatted
// - Latency budget is tight (one round trip instead of two)

// Use RerankCommand + ConverseCommand when:
// - Retrieval precision is critical (reranking reduces noise)
// - Multiple retrieval sources need to be merged
// - Custom context formatting is required
// - You need to inspect or log the retrieved documents before generation

For MCP server tools where answer quality matters and the latency of an extra API call is acceptable, the RerankCommand + ConverseCommand pattern is usually the better choice — the reranking step materially improves answer quality by reducing irrelevant context from entering the generation step. The RetrieveAndGenerateCommand is better suited for prototyping or cases where the simplicity of a single API call outweighs the precision benefit of reranking.

Error handling specific to Knowledge Base sources

The KNOWLEDGE_BASE source type can fail for reasons that inline reranking cannot — KB not found, retrieval timeout, insufficient permissions on the KB. These need separate handling:

import {
  ResourceNotFoundException,
  ThrottlingException,
  ValidationException,
  AccessDeniedException,
} from "@aws-sdk/client-bedrock-agent-runtime";

async function safeKBRerank(
  query: string,
  kbId: string,
  topN: number = 5
): Promise<Array<{ text: string; score: number }>> {
  try {
    const response = await agentRuntimeClient.send(
      new RerankCommand({
        rerankingConfiguration: {
          type: "BEDROCK_RERANKING_MODEL",
          bedrockRerankingConfiguration: {
            modelConfiguration: { modelArn: AMAZON_RERANK_ARN },
            numberOfResults: topN,
          },
        },
        sources: [{
          type: "KNOWLEDGE_BASE",
          knowledgeBaseSource: {
            retrieve: {
              knowledgeBaseId: kbId,
              retrievalQuery: { text: query },
              retrievalConfiguration: {
                vectorSearchConfiguration: { numberOfResults: 20 },
              },
            },
          },
        }],
        query: { type: "TEXT", textQuery: { text: query } },
      })
    );

    return (response.rerankingResults ?? []).map((r) => ({
      text: ((r as Record<string, unknown>).document as Record<string, unknown>)?.text as string ?? "",
      score: r.relevanceScore ?? 0,
    })).filter((r) => r.text.length > 0);

  } catch (err) {
    if (err instanceof ResourceNotFoundException) {
      // KB does not exist — log and return empty (not a transient error)
      console.error(`Knowledge Base ${kbId} not found:`, err.message);
      return [];
    }
    if (err instanceof AccessDeniedException) {
      // Missing bedrock:Retrieve or bedrock:Rerank permission
      console.error("Missing permissions for KB reranking:", err.message);
      return [];
    }
    if (err instanceof ThrottlingException) {
      // Transient — caller should retry with backoff
      throw err;
    }
    if (err instanceof ValidationException) {
      // Configuration error — log details to diagnose
      console.error("Validation error in KB reranking:", err.message);
      return [];
    }
    throw err; // Unknown error — propagate
  }
}

The key distinction is between permanent errors (ResourceNotFoundException, AccessDeniedException, ValidationException) that returning an empty array is appropriate for, and transient errors (ThrottlingException) that should be retried with backoff. For AccessDeniedException specifically, the required IAM actions for KB reranking are both bedrock:Rerank (for the reranking model) and bedrock:Retrieve (for the Knowledge Base). Missing either one causes this error.

Production gotchas

KNOWLEDGE_BASE and INLINE sources cannot be mixed

All entries in the sources array must use the same type. Mixing type: "KNOWLEDGE_BASE" and type: "INLINE" in the same call returns a ValidationException. For multi-source scenarios, retrieve from the KB separately via RetrieveCommand and pass the results as inline documents.

Retrieved count affects reranking quality

The numberOfResults in vectorSearchConfiguration (retrieval) should be significantly larger than the numberOfResults in bedrockRerankingConfiguration (how many to keep). A ratio of 3:1 to 5:1 is typical — retrieve 15–25, keep 3–5. If you retrieve only 5 and keep 5, there is no filtering happening and the reranker provides no benefit over direct vector retrieval. The filtering ratio is where the precision improvement comes from.

KB permissions must include bedrock:Retrieve

Using a Knowledge Base source for reranking requires bedrock:Retrieve permission on the Knowledge Base resource in addition to bedrock:Rerank on the reranking model. Add both to the IAM policy for the MCP server's execution role:

{
  "Effect": "Allow",
  "Action": ["bedrock:Rerank"],
  "Resource": ["arn:aws:bedrock:us-east-1::foundation-model/amazon.rerank-v1:0"]
},
{
  "Effect": "Allow",
  "Action": ["bedrock:Retrieve"],
  "Resource": ["arn:aws:bedrock:us-east-1:ACCOUNT:knowledge-base/KB_ID"]
}

Empty Knowledge Bases return zero results without error

If the Knowledge Base has no indexed documents (newly created, or all data sources unsynced), the reranking call succeeds but returns an empty rerankingResults array. This can be mistaken for a code bug when it is actually a data problem. Add observability on result count — alert when zero results are returned more than once to detect KB sync failures early.

Monitor your RAG pipeline MCP tools with AliveMCP

AliveMCP monitors MCP server endpoints for uptime, latency, and error rates. When your KB reranking pipeline returns persistent empty results or elevated errors, AliveMCP surfaces the issue before it silently degrades agent quality.

Start free monitoring