Guide · Amazon Bedrock · Reranking

MCP Server Amazon Bedrock Reranking — RerankCommand, model selection, response parsing

Amazon Bedrock Reranking lets MCP server tools post-process a list of retrieved documents and score them against a user query before passing them to a generation model. The API lives in @aws-sdk/client-bedrock-agent-runtime — not in bedrock-runtime — and exports a single RerankCommand that accepts either inline documents you supply directly or Knowledge Base sources that Bedrock retrieves for you. Two reranking models are available: Cohere Rerank v3 Multilingual (cohere.rerank-v3-5:0) for multi-language corpora and Amazon Rerank 1 (amazon.rerank-v1:0) for English workloads. Three constraints catch MCP server authors off-guard: the API is in bedrock-agent-runtime, not bedrock-runtime, so using the wrong client returns a confusing "command not found" error at import time; the model ARN format requires a double colon before the resource segment (arn:aws:bedrock:REGION::foundation-model/MODEL_ID), not the single colon used in most other Bedrock ARNs; and numberOfResults controls how many top-ranked documents are returned in the response — if you omit it, the API returns all input documents reranked, which can be expensive when the caller only needs the top 5. For integration with Bedrock Knowledge Bases see reranking KB results; for inline document scoring patterns see inline reranking; for Cohere vs Amazon model trade-offs see model selection.

TL;DR

Import RerankCommand from @aws-sdk/client-bedrock-agent-runtime. Pass your documents as sources with type: "INLINE", your query in query.textQuery.text, and pick a model via its full ARN in rerankingConfiguration.bedrockRerankingConfiguration.modelConfiguration.modelArn. Set numberOfResults to limit how many top results come back. Each result in rerankingResults has an index (position in your original sources array) and a relevanceScore (0.0–1.0, higher is better).

Why reranking matters in MCP server RAG tools

Retrieval from a vector database or Bedrock Knowledge Base returns documents ranked by embedding similarity — a semantic distance metric that works well on average but fails on precise factual queries where keyword overlap matters as much as semantic proximity. A reranker scores each candidate document against the actual query using a cross-encoder model: it reads query and document together, not as independent embeddings, which produces more accurate relevance scores at the cost of a separate API call. In a typical MCP tool handler the pattern is:

  1. Retrieve the top-20 (or top-50) candidates from your vector store or 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 retrieve-rerank-generate pipeline is well-established in production RAG systems. Bedrock Reranking makes it available as a managed API call without requiring you to run a separate reranker model on EC2 or Lambda, which simplifies the operational surface of MCP servers considerably.

Client setup and package

Bedrock Reranking is part of the Amazon Bedrock Agent Runtime, not the Bedrock Runtime that hosts ConverseCommand and InvokeModelCommand. Install the correct package:

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

The BedrockAgentRuntimeClient is the right client. If you accidentally import from @aws-sdk/client-bedrock-runtime you will find that RerankCommand does not exist there — it only exists in bedrock-agent-runtime. Create the client once and reuse it across MCP tool calls:

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",
});

// Model ARNs — note the double-colon before "foundation-model"
const COHERE_RERANK_ARN =
  "arn:aws:bedrock:us-east-1::foundation-model/cohere.rerank-v3-5:0";
const AMAZON_RERANK_ARN =
  "arn:aws:bedrock:us-east-1::foundation-model/amazon.rerank-v1:0";

The double colon (::) in the ARN is not a typo. Bedrock foundation model ARNs follow this pattern because there is no account ID in the resource 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 a ValidationException depending on the region, which is confusing to debug.

Minimal inline reranking example

The most direct use case: you have a list of text documents (retrieved from any source) and you want to rerank them against a user query. Each document becomes an inline source with type: "INLINE" and an inlineDocumentSource containing the text:

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 }>> {
  const response = await agentRuntimeClient.send(
    new RerankCommand({
      rerankingConfiguration: {
        type: "BEDROCK_RERANKING_MODEL",
        bedrockRerankingConfiguration: {
          modelConfiguration: {
            modelArn: AMAZON_RERANK_ARN,
          },
          numberOfResults: topN,
        },
      },
      sources: documents.map((doc) => ({
        type: "INLINE",
        inlineDocumentSource: {
          type: "TEXT",
          textDocument: {
            text: doc.content,
          },
        },
      })),
      query: {
        type: "TEXT",
        textQuery: {
          text: query,
        },
      },
    })
  );

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

server.tool(
  "search_docs",
  { query: z.string().describe("Search query") },
  async ({ query }) => {
    // In production, retrieve candidates from your vector store
    const candidates: Document[] = await fetchCandidates(query, 20);

    const reranked = await rerankDocuments(query, candidates, 5);

    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 [];
}

The key pieces: sources maps your documents to inline source objects, rerankingResults in the response has each result's index (position in your original sources array) and relevanceScore. The results arrive pre-sorted — the highest score is first. You map result.index back to the original document to get content alongside the score.

Response structure in detail

Understanding the response schema prevents the most common parsing mistakes. The RerankResponse contains:

interface RerankResponse {
  rerankingResults: Array<{
    index: number;         // 0-based position in the input sources array
    relevanceScore: number; // 0.0 to 1.0 — higher is more relevant
  }>;
  nextToken?: string;      // set when there are more results (pagination)
}

// Safe parsing pattern
const results = response.rerankingResults ?? [];

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

  console.log(`score=${score.toFixed(4)} id=${originalDoc.id}`);
}

// results are already sorted descending by relevanceScore
// results[0] is always the most relevant document

Three things to note: First, rerankingResults can be undefined if no documents score above an internal threshold, so always default to an empty array with ?? []. Second, results are already sorted descending — you do not need to sort them yourself. 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 threshold). If you omit numberOfResults, all 20 documents come back reranked, which is useful when you want to apply your own threshold logic after the fact.

Pagination via nextToken applies only when input sources number in the hundreds. For the typical RAG use case of 10–50 candidate documents, all results fit in a single response.

Relevance score threshold filtering

The relevanceScore is a float between 0.0 and 1.0, but unlike cosine similarity from a vector store, it reflects actual relevance to the query as estimated by the cross-encoder model. Scores above ~0.5 generally indicate genuine relevance; scores below ~0.1 indicate the document is unlikely to help answer the query. A threshold filter prevents irrelevant documents from polluting the generation context:

const MIN_RELEVANCE_SCORE = 0.3;

async function rerankWithThreshold(
  query: string,
  documents: Document[],
  topN: number = 10,
  minScore: number = MIN_RELEVANCE_SCORE
): Promise<Array<{ document: Document; score: number }>> {
  if (documents.length === 0) return [];

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

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

// Usage in MCP tool handler
server.tool(
  "precise_search",
  { query: z.string() },
  async ({ query }) => {
    const candidates = await fetchCandidates(query, 20);
    const relevant = await rerankWithThreshold(query, candidates);

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

    return {
      content: [{
        type: "text",
        text: relevant.map((r) => r.document.content).join("\n\n---\n\n"),
      }],
    };
  }
);

Setting minScore to 0.3 is a reasonable starting point, but the right threshold depends on your corpus and query distribution. Start with 0.1 to see the full distribution of scores on representative queries, then tighten the threshold to cut obvious irrelevances while keeping genuinely borderline documents.

Model ARNs and regional availability

Both reranking models are accessed via full ARNs. The ARN region must match the region of your BedrockAgentRuntimeClient. As of late 2026, the Bedrock Reranking API is available in us-east-1, us-west-2, eu-west-1, and ap-northeast-1 — not in all Bedrock regions:

// Amazon Rerank 1 — English-optimized
const AMAZON_RERANK_ARN_USE1 =
  "arn:aws:bedrock:us-east-1::foundation-model/amazon.rerank-v1:0";
const AMAZON_RERANK_ARN_USW2 =
  "arn:aws:bedrock:us-west-2::foundation-model/amazon.rerank-v1:0";

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

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

// At startup, derive the ARN from your configured region
const region = process.env.AWS_REGION ?? "us-east-1";
const rerankArn = buildRerankArn(region, "amazon.rerank-v1:0");

The dynamic ARN builder is especially useful when deploying the same MCP server in multiple regions — you read AWS_REGION from the environment and construct the ARN at startup rather than hardcoding it. If your deployed region does not support Bedrock Reranking, the API returns a ResourceNotFoundException for the model ARN. For model selection guidance see Cohere vs Amazon Rerank 1 model selection.

Error handling and retries

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 } 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: topN,
            },
          },
          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 the validation error — it won't fix itself on retry
        console.error("Bedrock Reranking ValidationException:", err.message);
        return [];
      }
      throw err;
    }
  }
  return [];
}

// Common ValidationException causes:
// 1. ARN format wrong (single colon instead of double)
// 2. Document text is empty string
// 3. Sources array is empty
// 4. numberOfResults > number of sources
// 5. Model not available in this region

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 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.

Using both source types: when to pick inline vs Knowledge Base

The reranking API supports two source types for a single call:

You cannot mix INLINE and KNOWLEDGE_BASE sources in the same RerankCommand call — all entries in the sources array must use the same type. If you need to merge results from multiple sources (a KB plus a custom vector store), retrieve from each separately, merge the lists, then pass the merged list as inline documents to a final reranking call:

// Merge results from two sources, then rerank together
const kbResults = await retrieveFromKnowledgeBase(query, 10);
const vectorResults = await retrieveFromVectorStore(query, 10);

const allCandidates: Document[] = [
  ...kbResults.map((r) => ({ id: `kb-${r.id}`, content: r.text })),
  ...vectorResults.map((r) => ({ id: `vec-${r.id}`, content: r.content })),
];

// Rerank the merged 20 candidates as inline documents
const reranked = await rerankDocuments(query, allCandidates, 5);

This two-retrieval then inline-rerank pattern is a common design for MCP servers that federate multiple knowledge sources — the reranker acts as a final arbitration layer that normalizes scores across the two retrieval systems.

Integration with MCP tool metadata

When a reranking step is embedded in an MCP tool handler, it is worth surfacing the relevance scores in the tool response metadata so the calling LLM can use them for downstream decisions — for example, to decide whether retrieved context is reliable enough to cite:

server.tool(
  "search_with_scores",
  {
    query: z.string(),
    min_score: z.number().min(0).max(1).default(0.2),
  },
  async ({ query, min_score }) => {
    const candidates = await fetchCandidates(query, 20);
    const reranked = await rerankDocuments(query, candidates, 10);

    const filtered = reranked.filter((r) => r.score >= min_score);

    if (filtered.length === 0) {
      return {
        content: [{
          type: "text",
          text: JSON.stringify({
            query,
            results: [],
            message: "No documents met the minimum relevance threshold.",
          }),
        }],
      };
    }

    return {
      content: [{
        type: "text",
        text: JSON.stringify({
          query,
          results: filtered.map((r) => ({
            id: r.document.id,
            relevanceScore: r.score,
            content: r.document.content,
          })),
        }),
      }],
    };
  }
);

Returning structured JSON (rather than plain text) lets the calling LLM or agent parse the scores and decide how to use the results — for example, citing only documents above 0.7 and hedging on those between 0.3 and 0.7. The min_score parameter lets the LLM client tune the threshold per-call based on query confidence.

Production gotchas

Empty sources array throws ValidationException

Calling RerankCommand with an empty sources array returns a ValidationException immediately. Add a guard before the API call:

if (documents.length === 0) {
  return []; // skip the API call entirely
}

This is easy to miss when your retrieval step returns zero results for unusual queries. Without the guard, an empty retrieval propagates into a reranking exception instead of returning an empty result set.

numberOfResults must not exceed sources count

Setting numberOfResults: 10 when you pass only 5 documents causes a ValidationException. Either cap numberOfResults dynamically or omit it to get back all documents:

const topN = Math.min(5, documents.length);

new RerankCommand({
  rerankingConfiguration: {
    type: "BEDROCK_RERANKING_MODEL",
    bedrockRerankingConfiguration: {
      modelConfiguration: { modelArn: AMAZON_RERANK_ARN },
      numberOfResults: topN,  // safe — always <= documents.length
    },
  },
  sources: documents.map(/* ... */),
  query: { type: "TEXT", textQuery: { text: query } },
});

reranking adds ~200–500ms latency

The reranking model runs inference on each (query, document) pair, which takes noticeably longer than a vector similarity lookup. For latency-sensitive MCP tools, run the vector retrieval and cache warming in parallel with other work before calling the reranker. If the tool's total latency budget is tight, consider reranking only the top-10 candidates rather than top-20 or top-50 — the latency scales roughly linearly with the number of source documents.

Bedrock Agent Runtime requires different IAM permissions

The reranking API is in Bedrock Agent Runtime, not Bedrock Runtime. The IAM action to allow is bedrock:Rerank, separate from bedrock:InvokeModel:

{
  "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"
  ]
}

Missing this permission returns an AccessDeniedException with the message "is not authorized to perform: bedrock:Rerank". Add it to whatever role your MCP server's Lambda or ECS task assumes.

Monitor your RAG MCP tools with AliveMCP

AliveMCP monitors MCP server endpoints for uptime, latency spikes, and error rates. When a reranking-heavy tool handler starts returning elevated latency or errors, AliveMCP alerts you before it impacts downstream agents.

Start free monitoring