Amazon Bedrock · RerankCommand, Inline Sources, Knowledge Base Sources & Model Selection · 2026-11-26 · Bedrock Reranking arc

Amazon Bedrock Reranking for MCP Servers: A Complete Retrieve-Rerank-Generate Playbook

Four Bedrock Reranking arc pages synthesised into a complete production playbook for MCP server developers — covering the core RerankCommand API (which lives in bedrock-agent-runtime, not bedrock-runtime, with a double-colon ARN format that trips up nearly every first-time user), inline document reranking (TEXT and JSON source types, threshold filtering strategies, two-stage reranking for large candidate sets), Knowledge Base source reranking (combined retrieve + rerank in one call, hybrid search, metadata pre-filtering, full RAG pipeline), and model selection (Cohere Rerank v3 Multilingual for 100+ languages and max_chunks_per_doc control vs Amazon Rerank 1 for simpler English workloads). The production gotchas extracted from all four pages are consolidated at the end — each one silently breaks a real deployment.

Why reranking matters in MCP server RAG tools

Vector retrieval from a Knowledge Base or embedding store returns documents ranked by cosine similarity — a semantic distance metric that works well on average but fails on precise factual queries where keyword specificity matters as much as semantic proximity. When an MCP tool handler passes the top-10 similarity results directly to a generation model, the context window often contains documents that look thematically related but do not actually contain the specific fact the user is asking about. The generation model hallucinates to fill the gap.

A reranker fixes this by scoring each candidate document against the actual query using a cross-encoder model: it reads query and document together in a single forward pass, not as independent embeddings, which produces substantially more accurate relevance scores at the cost of a separate API call. The practical result is that a 20-document retrieval pass followed by a reranking step that keeps only the top 5 produces a context window with higher precision than passing all 20 documents — and the smaller context window speeds up and cheapens the generation step.

Amazon Bedrock Reranking makes this available as a managed API without requiring you to deploy or operate a reranker model yourself. No EC2, no inference endpoints, no model management. One extra API call in your MCP tool handler replaces an entire infrastructure category.

The retrieve-rerank-generate pattern for an MCP tool handler looks like this:

  1. Retrieve the top-20 (or top-25) candidates from your vector store or Bedrock Knowledge Base.
  2. Rerank those 20 candidates, keeping the top 5 by relevance score.
  3. Generate a response using those 5 documents as context — a much smaller and more precise context window than passing all 20.

The filtering ratio — retrieve 20, keep 5 — is where the precision improvement comes from. If you retrieve 5 and keep 5, there is no filtering happening and the reranker provides no benefit over direct vector retrieval. A 3:1 to 5:1 ratio between retrieval count and kept results is a reasonable starting point for most corpora.

The API lives in bedrock-agent-runtime, not bedrock-runtime

The first thing that breaks every new user of Bedrock Reranking: the RerankCommand is in @aws-sdk/client-bedrock-agent-runtime, not in @aws-sdk/client-bedrock-runtime. If you import from the wrong package, you will find that RerankCommand does not exist there — the error happens at import time with no helpful message pointing to the correct package.

npm install @aws-sdk/client-bedrock-agent-runtime

Import from this package, using BedrockAgentRuntimeClient as the client:

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

// Create once at module level — do NOT create inside tool handlers
const agentRuntimeClient = new BedrockAgentRuntimeClient({
  region: process.env.AWS_REGION ?? "us-east-1",
});

Create the client once at module initialization. Creating a new client inside each tool handler call wastes time on credential resolution and connection setup — it adds 50–150ms per call that is entirely avoidable.

The double-colon ARN format

The second thing that trips up almost every developer: the model ARN format for Bedrock Reranking uses a double colon before foundation-model. This is not a typo in the documentation. Bedrock foundation model ARNs follow this pattern because there is no account ID in the ARN for public foundation models — the account segment is empty, producing arn:aws:bedrock:REGION::foundation-model/MODEL_ID. Using a single colon here returns an AccessDeniedException or ValidationException depending on the region, neither of which mentions the ARN format problem in its error message.

// Amazon Rerank 1 — English-optimized, simplest to use
const AMAZON_RERANK_ARN =
  "arn:aws:bedrock:us-east-1::foundation-model/amazon.rerank-v1:0";
//                           ^^-- double colon here

// Cohere Rerank v3 Multilingual — 100+ languages
const COHERE_RERANK_ARN =
  "arn:aws:bedrock:us-east-1::foundation-model/cohere.rerank-v3-5:0";

// Build ARN dynamically from the client's configured region
function buildRerankArn(region: string, modelId: string): string {
  return `arn:aws:bedrock:${region}::foundation-model/${modelId}`;
}

const region = process.env.AWS_REGION ?? "us-east-1";
const rerankArn = buildRerankArn(region, "amazon.rerank-v1:0");

The dynamic builder is the safest pattern for multi-region deployments. It derives the region from the environment at startup, keeping ARN and client region in sync automatically.

Minimal inline reranking: the complete working pattern

Inline document reranking is the right source type when your candidate documents come from any retrieval system outside Bedrock Knowledge Bases: your own vector store, a full-text search index, a SQL query result, or any assembled list of text passages. You pass the document text directly in the request body — Bedrock scores each one against the query without storing it.

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

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

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

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

interface Document {
  id: string;
  content: string;
}

async function rerankDocuments(
  query: string,
  documents: Document[],
  topN: number = 5
): Promise<Array<{ document: Document; score: number }>> {
  // Guard: empty sources array throws ValidationException, not returns []
  if (documents.length === 0) return [];

  // Guard: filter empty text before the API call
  const validDocs = documents.filter((d) => d.content.trim().length > 0);
  if (validDocs.length === 0) return [];

  // Guard: numberOfResults must not exceed sources count
  const safeTopN = Math.min(topN, validDocs.length);

  const response = await agentRuntimeClient.send(
    new RerankCommand({
      rerankingConfiguration: {
        type: "BEDROCK_RERANKING_MODEL",
        bedrockRerankingConfiguration: {
          modelConfiguration: { modelArn: AMAZON_RERANK_ARN },
          numberOfResults: safeTopN,
        },
      },
      sources: validDocs.map((doc) => ({
        type: "INLINE",
        inlineDocumentSource: {
          type: "TEXT",
          textDocument: { text: doc.content },
        },
      })),
      query: {
        type: "TEXT",
        textQuery: { text: query },
      },
    })
  );

  // results are pre-sorted descending — results[0] is most relevant
  return (response.rerankingResults ?? []).map((result) => ({
    document: validDocs[result.index!],
    score: result.relevanceScore ?? 0,
  }));
}

server.tool(
  "search_docs",
  { query: z.string().describe("Search query") },
  async ({ query }) => {
    const candidates: Document[] = await fetchCandidates(query, 20);
    const reranked = await rerankDocuments(query, candidates, 5);

    if (reranked.length === 0) {
      return { content: [{ type: "text", text: "No relevant documents found." }] };
    }

    const topDocs = reranked
      .map((r) => `[score=${r.score.toFixed(3)}] ${r.document.content}`)
      .join("\n\n---\n\n");

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

async function fetchCandidates(query: string, limit: number): Promise<Document[]> {
  // Replace with your vector store retrieval
  return [];
}

Three validation guards are embedded in the function. All three prevent ValidationException causes that are easy to hit in production when retrieval returns edge-case results:

Response structure: index, score, sort order

The RerankResponse structure is simple but has three important behaviors to understand:

// Safe response parsing
const results = response.rerankingResults ?? [];
// Always default to [] — rerankingResults can be undefined

for (const result of results) {
  const originalDoc = documents[result.index!]; // map back using index
  const score = result.relevanceScore ?? 0;     // 0.0 to 1.0
}

// results are ALREADY sorted descending by relevanceScore
// results[0] is always the most relevant document
// Do NOT sort them again

First: rerankingResults can be undefined if no documents score above an internal threshold, so always default to an empty array with ?? []. Second: results are pre-sorted descending — sorting them again is a no-op but wastes cycles; if you observe results appearing unsorted, the issue is in a post-processing step, not the API response. Third: numberOfResults caps how many results are returned — if you pass 20 documents and set numberOfResults: 5, you get exactly 5 results (fewer if fewer than 5 score above the minimum internal threshold). Omitting numberOfResults returns all source documents reranked — useful when you want to apply your own threshold logic, but means you are paying to score every document.

Threshold filtering: quality gating beyond numberOfResults

The numberOfResults parameter controls quantity. Threshold filtering on relevanceScore controls quality. These two work together: set numberOfResults to a reasonable top-N, then filter the results to remove documents below a minimum score. This is more reliable than relying on numberOfResults alone — when overall corpus relevance is poor, numberOfResults: 5 will still return 5 results even if none of them are genuinely relevant.

const THRESHOLD_STRICT = 0.7;      // high confidence — only clearly relevant
const THRESHOLD_NORMAL = 0.3;      // balanced — some borderline included
const THRESHOLD_PERMISSIVE = 0.1;  // low bar — almost everything passes

type ThresholdMode = "strict" | "normal" | "permissive";

function applyThreshold<T extends { score: number }>(
  results: T[],
  mode: ThresholdMode
): T[] {
  const threshold = { strict: 0.7, normal: 0.3, permissive: 0.1 }[mode];
  const filtered = results.filter((r) => r.score >= threshold);

  // Always return at least 1 result — an empty-handed tool response is
  // worse than a borderline result the LLM can qualify
  if (filtered.length === 0 && results.length > 0) {
    return [results[0]];
  }

  return filtered;
}

Use "strict" (threshold 0.7) for factual question-answering tools where only clearly on-topic documents should enter the context window. Use "normal" (threshold 0.3) for search tools where some borderline results are acceptable. Use "permissive" (threshold 0.1) for exploratory queries where the caller wants to see the full retrieved set.

The fallback that always returns at least one result prevents the calling LLM from receiving an unhelpful empty response. The best single result — even if below the strict threshold — is usually better than a generic "no results" message, because the LLM can still reason about partial information and qualify its answer accordingly.

Start with 0.1 on representative queries to see the full distribution of scores on your corpus, then tighten the threshold to cut obvious irrelevances while keeping genuinely borderline documents. The right threshold is corpus-specific — there is no universal value.

JSON inline sources: reranking structured documents

When your documents have multiple text fields (title, body, summary) that all contribute to relevance, the JSON inline source type lets the reranker read all fields together rather than a concatenated string. This is most beneficial when title is a strong relevance signal separate from body — a title match is weighted appropriately because it appears as a named field.

interface StructuredDoc {
  id: string;
  title: string;
  body: string;
  section: string;
}

const response = await agentRuntimeClient.send(
  new RerankCommand({
    rerankingConfiguration: {
      type: "BEDROCK_RERANKING_MODEL",
      bedrockRerankingConfiguration: {
        modelConfiguration: { modelArn: AMAZON_RERANK_ARN },
        numberOfResults: Math.min(5, docs.length),
      },
    },
    sources: docs.map((doc) => ({
      type: "INLINE",
      inlineDocumentSource: {
        type: "JSON",
        jsonDocument: {
          data: {
            title: doc.title,
            body: doc.body,
            section: doc.section,
            // Flatten arrays to comma-separated strings
            // The reranker tokenizes JSON as text — arrays don't score well
          },
        },
      },
    })),
    query: { type: "TEXT", textQuery: { text: query } },
  })
);

When using JSON documents, flatten nested structures and arrays to top-level string fields before passing to the API. Arrays like tags: ["auth", "security"] are best passed as tags: "auth, security" — the model tokenizes JSON as text, and JSON arrays may score as opaque noise rather than content.

The metadataConfiguration option controls which JSON fields the reranker scores. With selectionMode: "SELECTIVE" you can include only title and body for scoring while still carrying url, author, and date in the response payload — those travel with the document but do not influence the relevance score calculation. This prevents query terms that happen to match metadata values (a query for "john" matching an author named "John Smith") from elevating irrelevant documents.

Merging multiple retrieval sources with inline reranking

When your MCP server federates multiple retrieval systems — a vector store, BM25 full-text index, and a Bedrock Knowledge Base — their similarity scores are incomparable. Each system uses a different scoring metric, so a score of 0.8 from a cosine-similarity vector store is not comparable to a score of 15 from a BM25 ranker. Inline reranking normalizes across retrieval systems by scoring all candidates against the same query using a single cross-encoder model.

interface SearchResult {
  id: string;
  source: "vector" | "bm25" | "kb";
  text: string;
}

async function hybridSearchWithRerank(query: string): Promise<SearchResult[]> {
  // Run all three retrievals concurrently
  const [vectorResults, bm25Results, kbResults] = await Promise.all([
    vectorSearch(query, 10),
    bm25Search(query, 10),
    kbSearch(query, 10),
  ]);

  // Merge and deduplicate by content prefix
  const seen = new Set<string>();
  const candidates: SearchResult[] = [];

  for (const r of [...vectorResults, ...bm25Results, ...kbResults]) {
    const key = r.text.slice(0, 100); // rough dedup by text prefix
    if (!seen.has(key)) {
      seen.add(key);
      candidates.push(r);
    }
  }

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

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

  return (response.rerankingResults ?? []).map((r) => ({
    ...candidates[r.index!],
  }));
}

Running the three retrievals with Promise.all means total retrieval latency is bounded by the slowest retriever, not the sum. The reranking API call then adds latency sequentially on top of the parallel retrieval phase — a reasonable trade-off given the material precision improvement. For production use, replace the first-100-character deduplication key with a SHA256 hash of the full text to avoid false positives from documents with identical prefixes.

Knowledge Base source type: combined retrieve + rerank

When all your documents live in a single Bedrock Knowledge Base, the KNOWLEDGE_BASE source type lets you retrieve and rerank in one RerankCommand call rather than chaining a separate RetrieveCommand followed by an inline reranking call. This reduces round-trips from two API calls to one and simplifies error handling in MCP tool handlers.

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";

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

server.tool(
  "search_knowledge_base",
  { query: z.string().describe("Search query") },
  async ({ query }) => {
    const response = await agentRuntimeClient.send(
      new RerankCommand({
        rerankingConfiguration: {
          type: "BEDROCK_RERANKING_MODEL",
          bedrockRerankingConfiguration: {
            modelConfiguration: { modelArn: AMAZON_RERANK_ARN },
            numberOfResults: 5, // keep 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
                    overrideSearchType: "HYBRID", // BM25 + semantic
                  },
                },
              },
            },
          },
        ],
        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);
        const doc = (r as Record<string, unknown>).document as Record<string, unknown> | undefined;
        const text = doc?.text as string ?? JSON.stringify(r).slice(0, 500);
        return `[${i + 1}] score=${score}\n${text}`;
      })
      .join("\n\n---\n\n");

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

The critical parameters: numberOfResults: 20 in vectorSearchConfiguration (retrieval count) versus numberOfResults: 5 in bedrockRerankingConfiguration (kept count after reranking). The 4:1 ratio is the precision improvement mechanism. If both are set to 5, the reranker is selecting from 5 documents and there is no filtering benefit.

Adding overrideSearchType: "HYBRID" enables BM25 keyword matching alongside semantic vector search. Hybrid retrieval and reranking complement each other well: hybrid retrieval improves recall (fewer relevant documents missed in the initial 20), and reranking improves precision (better ranking within the retrieved set). Using both together produces higher quality final context windows than either technique alone.

Full RAG pipeline: retrieve → rerank → generate

The complete pattern for an MCP tool that implements the full retrieve-rerank-generate pipeline. This version uses the Knowledge Base source type for the retrieval + reranking step, then generates with 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,
          },
        },
        sources: [{
          type: "KNOWLEDGE_BASE",
          knowledgeBaseSource: {
            retrieve: {
              knowledgeBaseId: KB_ID,
              retrievalQuery: { text: question },
              retrievalConfiguration: {
                vectorSearchConfiguration: {
                  numberOfResults: 25,
                  overrideSearchType: "HYBRID",
                },
              },
            },
          },
        }],
        query: { type: "TEXT", textQuery: { text: question } },
      })
    );

    const results = rerankResponse.rerankingResults ?? [];
    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 doc = (r as Record<string, unknown>).document as Record<string, unknown> | undefined;
        const text = doc?.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 }] };
  }
);

The min_score parameter — exposed as a tool input — lets the calling agent adjust how strict the relevance filter is at runtime. 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. This is a useful design pattern for MCP tools where the calling agent has context about query difficulty that the tool handler does not.

Model selection: Cohere Rerank v3 vs Amazon Rerank 1

Bedrock Reranking offers two foundation models. For most MCP server use cases on English-language corpora, Amazon Rerank 1 is the simpler starting point. Cohere Rerank v3 Multilingual has two distinct advantages that justify its additional configuration complexity.

CriterionAmazon Rerank 1Cohere Rerank v3
Model IDamazon.rerank-v1:0cohere.rerank-v3-5:0
Language supportEnglish-optimized100+ languages, cross-lingual
Extra parametersNone requiredmax_chunks_per_doc available
Latency (20 docs × 500 tokens)~250ms p50, ~600ms p95~300ms p50, ~700ms p95
Config complexityMinimaladditionalModelRequestFields

Use Amazon Rerank 1 when your corpus is English-only, documents are pre-chunked (500–1000 tokens), and you want minimal configuration. It performs particularly well on domain-specific English text — technical documentation, code comments, support tickets.

Use Cohere Rerank v3 Multilingual when queries or documents span multiple languages (a French query against Spanish documents scores correctly without any translation preprocessing), or when you have long multi-page documents where the max_chunks_per_doc parameter gives you control over how the model internally segments documents before scoring.

async function rerankWithCohere(
  query: string,
  documents: Array<{ id: string; text: string }>,
  topN: number = 5,
  maxChunksPerDoc: number = 10
) {
  const COHERE_RERANK_ARN =
    "arn:aws:bedrock:us-east-1::foundation-model/cohere.rerank-v3-5:0";

  const response = await agentRuntimeClient.send(
    new RerankCommand({
      rerankingConfiguration: {
        type: "BEDROCK_RERANKING_MODEL",
        bedrockRerankingConfiguration: {
          modelConfiguration: {
            modelArn: COHERE_RERANK_ARN,
            additionalModelRequestFields: {
              max_chunks_per_doc: maxChunksPerDoc,
            },
          },
          numberOfResults: Math.min(topN, documents.length),
        },
      },
      sources: documents.map((doc) => ({
        type: "INLINE",
        inlineDocumentSource: {
          type: "TEXT",
          textDocument: { text: doc.text },
        },
      })),
      query: { type: "TEXT", textQuery: { text: query } },
    })
  );

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

Setting max_chunks_per_doc to 1 treats each document as a single scoring unit (fast, but misses relevant passages in long documents). Setting it to 20–30 allows Cohere to find relevant passages deep in multi-page documents but increases scoring time proportionally. For pre-chunked 500-token documents, the default is fine. For full-page or multi-page documents, increase it to 20 or 30.

One important caveat: a relevance score of 0.6 from Amazon Rerank 1 is not equivalent to a score of 0.6 from Cohere Rerank v3 — the two models use different internal calibrations. Never compare raw scores across models or apply the same threshold without recalibration. Run a calibration pass on 50–100 representative query-document pairs to find the equivalent threshold before switching models in production.

Language-adaptive model routing

For MCP servers deployed to global audiences, a lightweight language detection step before reranking lets you route to Amazon Rerank 1 for English queries (simpler, marginally faster) and Cohere Rerank v3 for non-English queries (better multilingual quality):

function isLikelyEnglish(text: string): boolean {
  // >95% ASCII characters is a reasonable proxy for English-only text
  const asciiCount = [...text].filter((c) => c.charCodeAt(0) < 128).length;
  return asciiCount / text.length > 0.95;
}

async function adaptiveRerank(
  query: string,
  documents: Array<{ id: string; text: string }>,
  topN: number = 5
) {
  const region = process.env.AWS_REGION ?? "us-east-1";
  const modelId = isLikelyEnglish(query)
    ? "amazon.rerank-v1:0"
    : "cohere.rerank-v3-5:0";
  const modelArn = `arn:aws:bedrock:${region}::foundation-model/${modelId}`;

  const response = await agentRuntimeClient.send(
    new RerankCommand({
      rerankingConfiguration: {
        type: "BEDROCK_RERANKING_MODEL",
        bedrockRerankingConfiguration: {
          modelConfiguration: { modelArn },
          numberOfResults: Math.min(topN, documents.length),
        },
      },
      sources: documents.map((doc) => ({
        type: "INLINE",
        inlineDocumentSource: { type: "TEXT", textDocument: { text: doc.text } },
      })),
      query: { type: "TEXT", textQuery: { text: query } },
    })
  );

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

The result includes modelUsed so you can log which model handled each request — useful for debugging scoring discrepancies. For production language detection, replace the ASCII-ratio heuristic with a dedicated library or Bedrock's translation API to identify the language before routing.

Error handling and retry logic

Bedrock Reranking throws the same exception types as other Bedrock APIs. The ones most likely to appear in production MCP server tools:

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

async function rerankWithRetry(
  query: string,
  documents: Document[],
  topN: number = 5,
  maxRetries: number = 3
): Promise<Array<{ document: Document; score: number }>> {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const response = await agentRuntimeClient.send(
        new RerankCommand({
          rerankingConfiguration: {
            type: "BEDROCK_RERANKING_MODEL",
            bedrockRerankingConfiguration: {
              modelConfiguration: { modelArn: AMAZON_RERANK_ARN },
              numberOfResults: Math.min(topN, documents.length),
            },
          },
          sources: documents.map((doc) => ({
            type: "INLINE",
            inlineDocumentSource: { type: "TEXT", textDocument: { text: doc.content } },
          })),
          query: { type: "TEXT", textQuery: { text: query } },
        })
      );

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

    } catch (err) {
      if (err instanceof ThrottlingException && attempt < maxRetries - 1) {
        // Exponential backoff: 500ms, 1000ms, 2000ms
        await new Promise((r) => setTimeout(r, 500 * Math.pow(2, attempt)));
        continue;
      }
      if (err instanceof ValidationException) {
        // Log — it won't fix itself on retry
        console.error("Bedrock Reranking ValidationException:", err.message);
        return [];
      }
      if (err instanceof ResourceNotFoundException) {
        // KB or model not found — permanent error
        console.error("Resource not found:", err.message);
        return [];
      }
      if (err instanceof AccessDeniedException) {
        // Missing bedrock:Rerank or bedrock:Retrieve permission
        console.error("Access denied — check IAM bedrock:Rerank policy:", err.message);
        return [];
      }
      throw err; // Unknown error — propagate
    }
  }
  return [];
}

ThrottlingException is the most common transient error — reranking models have lower throughput quotas than generation models because they are compute-intensive. If your MCP server receives concurrent reranking requests, consider a request queue with a semaphore to cap concurrency. Returning an empty array on ValidationException and AccessDeniedException is appropriate for most tool handlers because the tool can still return a result using unreranked candidates as fallback — a hard throw would surface the error to the LLM client, which typically cannot recover.

IAM permissions

The reranking API requires bedrock:Rerank — a distinct action from bedrock:InvokeModel. If your MCP server also uses Knowledge Base source type for reranking, you additionally need bedrock:Retrieve on the Knowledge Base resource. If you use both Cohere and Amazon Rerank 1 (via adaptive routing), include both model ARNs in the resource list:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["bedrock:Rerank"],
      "Resource": [
        "arn:aws:bedrock:us-east-1::foundation-model/amazon.rerank-v1:0",
        "arn:aws:bedrock:us-east-1::foundation-model/cohere.rerank-v3-5:0"
      ]
    },
    {
      "Effect": "Allow",
      "Action": ["bedrock:Retrieve"],
      "Resource": ["arn:aws:bedrock:us-east-1:ACCOUNT_ID:knowledge-base/KB_ID"]
    }
  ]
}

Missing bedrock:Rerank returns an AccessDeniedException with the message "is not authorized to perform: bedrock:Rerank". Missing bedrock:Retrieve for a Knowledge Base source returns an AccessDeniedException for the Knowledge Base resource. Both are distinct from the bedrock:InvokeModel permission required for ConverseCommand — add all three to whatever role your MCP server's Lambda or ECS task assumes.

Also note: Cohere Rerank v3 may require activating Cohere model access in the Bedrock Model Access console in some regions. If Cohere Rerank v3 returns AccessDeniedException even with correct IAM policies, check Bedrock console → Model access → Cohere models for that region.

Consolidated production gotchas

The following gotchas are drawn from across all four Bedrock Reranking arc pages. Each one silently breaks a real deployment.

1. Wrong package — bedrock-runtime has no RerankCommand

RerankCommand lives in @aws-sdk/client-bedrock-agent-runtime. Importing from @aws-sdk/client-bedrock-runtime (the generation package) gives a runtime "command not found" error at import time.

2. Single colon in ARN triggers AccessDeniedException

The correct ARN format is arn:aws:bedrock:REGION::foundation-model/MODEL_ID — double colon before foundation-model because there is no account ID for public foundation models. Single colon returns an AccessDeniedException or ValidationException with no mention of the ARN format.

3. Empty sources array throws, not returns []

Calling RerankCommand with sources: [] returns a ValidationException immediately. Add a guard: if (documents.length === 0) return []; before the API call.

4. Empty text string throws, not skips

Unlike vector stores that silently skip empty documents, Bedrock Reranking throws ValidationException for any source entry where textDocument.text is an empty string or only whitespace. Filter before the call: const validDocs = docs.filter(d => d.text.trim().length > 0);

5. numberOfResults > sources count throws

Setting numberOfResults: 10 when you pass 5 documents causes a ValidationException. Always cap: numberOfResults: Math.min(topN, documents.length).

6. Results are pre-sorted — do not sort them again

The API returns results in descending score order. results[0] is always the most relevant. A second sort is a no-op but wastes cycles. If results appear unsorted, the issue is in a post-processing step.

7. Scores are not portable between models

A relevance score of 0.6 from Amazon Rerank 1 is not the same as 0.6 from Cohere Rerank v3. Switching models without recalibrating thresholds may silently filter out relevant results. Recalibrate thresholds on representative queries when switching models.

8. additionalModelRequestFields silently ignored by Amazon Rerank 1

Amazon Rerank 1 does not recognize max_chunks_per_doc or other Cohere-specific fields. The API does not throw — it silently ignores unrecognized fields. Always validate that model-specific parameters are intentional for the model in use.

9. KNOWLEDGE_BASE and INLINE sources cannot be mixed

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

10. Retrieval-to-reranking ratio must be > 1 to get any benefit

Retrieving 5 and reranking to 5 provides no filtering benefit. Retrieve at minimum 3× the number of results you want to keep. The 3:1 to 5:1 ratio is where the precision improvement comes from. If both numberOfResults values are equal, the reranker is reranking but not filtering, and you are paying for a reranking call with no quality improvement over direct retrieval.

Further reading

Monitor your RAG MCP tools with AliveMCP

AliveMCP monitors MCP server endpoints for uptime, latency, and error rates. When a reranking-heavy tool handler starts returning elevated latency, persistent empty results, or AccessDeniedException errors, AliveMCP surfaces the issue before it silently degrades agent quality.

Start free monitoring