Guide · Amazon Bedrock · Reranking

MCP Server Bedrock Reranking — Inline Documents, TEXT and JSON sources, threshold filtering

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 a manually assembled list of passages. You pass the document text directly in the RerankCommand request body under inlineDocumentSource, and Bedrock scores each one against the query without storing it. Two inline document types are available: TEXT for plain string content and JSON for structured key-value data where the reranker can use multiple fields. Three constraints matter in practice: empty document text causes a ValidationException — unlike most APIs, Bedrock Reranking will not silently skip empty documents; numberOfResults must not exceed the source count — requesting 10 results from 5 documents throws immediately; and long documents are automatically chunked by the reranker, but you can control chunking behavior via additionalModelRequestFields for the Cohere model, which affects scoring when a single document contains multiple relevant passages. For the overview of RerankCommand structure see Bedrock Reranking overview; for Knowledge Base source type see reranking KB results.

TL;DR

Set type: "INLINE" for each source entry and provide text under inlineDocumentSource.textDocument.text. Guard against empty text — it throws. Cap numberOfResults to Math.min(topN, documents.length). Filter results by relevanceScore threshold after the call; don't rely on numberOfResults alone for quality filtering.

TEXT source: basic inline reranking

The TEXT inline source type is the most direct: each source has a textDocument with a single text field. The reranker scores the full text against the query. Use this for passages, paragraphs, document chunks, search results — any content that is naturally represented as a string:

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

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

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

interface TextDoc {
  id: string;
  text: string;
  metadata?: Record<string, unknown>;
}

async function rerankText(
  query: string,
  docs: TextDoc[],
  topN: number = 5
): Promise<Array<TextDoc & { score: number }>> {
  if (docs.length === 0) return [];

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

  const safeTopN = Math.min(topN, validDocs.length);

  const response = await client.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.text,
          },
        },
      })),
      query: {
        type: "TEXT",
        textQuery: { text: query },
      },
    })
  );

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

The two guards — filtering empty text and capping safeTopN — prevent the two most common ValidationException causes. The spread ...validDocs[r.index!] preserves the original document metadata alongside the score, so the caller gets enriched result objects without needing to do a secondary lookup.

JSON source: reranking structured documents

The JSON inline source type passes a structured key-value object instead of a plain string. The reranker receives the full JSON structure and uses all fields when scoring relevance. This is useful when your documents have multiple text fields (title, body, summary) that all contribute to relevance, or when you want to include numeric or categorical metadata that might help the model differentiate documents:

interface StructuredDoc {
  id: string;
  title: string;
  body: string;
  section: string;
  tags: string[];
}

async function rerankStructured(
  query: string,
  docs: StructuredDoc[],
  topN: number = 5
): Promise<Array<{ doc: StructuredDoc; score: number }>> {
  if (docs.length === 0) return [];

  const safeTopN = Math.min(topN, docs.length);

  const response = await client.send(
    new RerankCommand({
      rerankingConfiguration: {
        type: "BEDROCK_RERANKING_MODEL",
        bedrockRerankingConfiguration: {
          modelConfiguration: { modelArn: AMAZON_RERANK_ARN },
          numberOfResults: safeTopN,
        },
      },
      sources: docs.map((doc) => ({
        type: "INLINE",
        inlineDocumentSource: {
          type: "JSON",
          jsonDocument: {
            data: {
              title: doc.title,
              body: doc.body,
              section: doc.section,
              tags: doc.tags.join(", "),
            },
          },
        },
      })),
      query: {
        type: "TEXT",
        textQuery: { text: query },
      },
    })
  );

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

When using JSON documents, all values should be serializable to strings or simple types — the reranker treats the JSON as textual content. Arrays like tags are best flattened to a comma-separated string rather than passed as a JSON array, which the model may treat as opaque noise. The JSON type 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 rather than being buried in a concatenated string.

If you have documents with both a short summary and long body, consider whether to pass both fields (more information for the model) or just the body (avoids duplicate signal). For most corpora, passing both is better — the title + summary fields give the cross-encoder model fast relevance signals before it processes the full body.

Handling long documents and chunking

Bedrock Reranking accepts documents up to a maximum length per source (the exact limit depends on the model). When a document exceeds this limit, the reranker scores based on the beginning of the document and may miss relevant passages in the second half. The standard mitigation in production RAG systems is to chunk documents before retrieval — your vector store should already hold ~512-token chunks rather than full pages — but if you find yourself reranking long documents, there are two approaches:

// Approach 1: Pre-chunk before reranking
function chunkText(text: string, chunkSize: number = 1000, overlap: number = 100): string[] {
  const chunks: string[] = [];
  let start = 0;
  while (start < text.length) {
    const end = Math.min(start + chunkSize, text.length);
    chunks.push(text.slice(start, end));
    start = end - overlap;
    if (start >= text.length) break;
  }
  return chunks;
}

// Expand long docs into multiple chunks, track origin
interface ChunkedDoc {
  originalId: string;
  chunkIndex: number;
  text: string;
}

function expandToChuks(docs: TextDoc[]): ChunkedDoc[] {
  const result: ChunkedDoc[] = [];
  for (const doc of docs) {
    if (doc.text.length <= 1000) {
      result.push({ originalId: doc.id, chunkIndex: 0, text: doc.text });
    } else {
      const chunks = chunkText(doc.text, 1000, 100);
      chunks.forEach((chunk, i) =>
        result.push({ originalId: doc.id, chunkIndex: i, text: chunk })
      );
    }
  }
  return result;
}

// After reranking, deduplicate by originalId — keep the best-scoring chunk per doc
function deduplicateByOrigin(
  results: Array<ChunkedDoc & { score: number }>
): Array<ChunkedDoc & { score: number }> {
  const best = new Map<string, ChunkedDoc & { score: number }>();
  for (const r of results) {
    const existing = best.get(r.originalId);
    if (!existing || r.score > existing.score) {
      best.set(r.originalId, r);
    }
  }
  return [...best.values()].sort((a, b) => b.score - a.score);
}

Pre-chunking before reranking converts one long document into multiple candidate chunks that each have an independent relevance score. After reranking, deduplicate by original document ID, keeping the highest-scoring chunk. This surfaces the best passage per document rather than scoring the whole document as a unit.

For the Cohere Rerank v3 model specifically, the additionalModelRequestFields parameter supports a max_chunks_per_doc option that controls how Cohere's model internally splits long documents. See Cohere vs Amazon Rerank 1 for details on this model-specific field.

Threshold filtering strategies

The numberOfResults parameter controls quantity — how many top results to return. Threshold filtering controls quality — only return results above a minimum relevance score. The two work together: set numberOfResults to retrieve a reasonable top-N, then apply a threshold to remove low-relevance documents from that set. This is more reliable than relying on numberOfResults alone, which can include low-quality results when overall corpus relevance is poor:

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: THRESHOLD_STRICT,
    normal: THRESHOLD_NORMAL,
    permissive: THRESHOLD_PERMISSIVE,
  }[mode];

  const filtered = results.filter((r) => r.score >= threshold);

  // Always return at least 1 result if the caller requested results at all
  // This prevents empty-handed tool responses on borderline queries
  if (filtered.length === 0 && results.length > 0) {
    return [results[0]]; // return best result even if below threshold
  }

  return filtered;
}

// In an MCP tool handler: use "strict" for factual QA, "normal" for search
server.tool(
  "factual_lookup",
  { question: z.string() },
  async ({ question }) => {
    const candidates = await fetchCandidates(question, 20);
    if (candidates.length === 0) {
      return { content: [{ type: "text", text: "No candidates found." }] };
    }

    const reranked = await rerankText(question, candidates, 10);
    const filtered = applyThreshold(reranked, "strict");

    return {
      content: [{
        type: "text",
        text: filtered.map((r) =>
          `[score=${r.score.toFixed(3)}]\n${r.text}`
        ).join("\n\n---\n\n"),
      }],
    };
  }
);

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.

Merging results from multiple retrieval sources

A common MCP server architecture runs multiple retrieval systems in parallel and merges their outputs before generation. Each retrieval system uses its own similarity metric (cosine similarity, BM25, dense retrieval), so their scores are not directly comparable. Reranking the merged list is the standard way to normalize across retrieval systems:

interface SearchResult {
  id: string;
  source: "vector" | "bm25" | "kb";
  text: string;
  originalScore: number; // not used for reranking — just for logging
}

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 into a single candidate list
  // Deduplicate by content hash to avoid rescoring identical documents
  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 [];

  // Rerank the merged list as inline documents
  const safeTopN = Math.min(5, candidates.length);
  const response = await client.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!],
    originalScore: r.relevanceScore ?? 0,
  }));
}

// Stubs — replace with real retrieval implementations
async function vectorSearch(query: string, limit: number): Promise<SearchResult[]> { return []; }
async function bm25Search(query: string, limit: number): Promise<SearchResult[]> { return []; }
async function kbSearch(query: string, limit: number): Promise<SearchResult[]> { return []; }

The rough deduplication using the first 100 characters as a key is intentionally simple — it catches exact duplicates that often appear when multiple retrieval systems index the same underlying corpus. For more robust deduplication in production, use a content hash of the full text, but keep it fast since deduplication runs on every query.

Running the three retrievals with Promise.all means the total latency is bounded by the slowest retriever, not the sum. For a typical MCP tool handler, this means the reranking API call adds latency sequentially on top of a parallel retrieval phase — a reasonable trade-off given that the reranking step significantly improves answer quality.

Handling very large candidate sets with batching

The Bedrock Reranking API has a maximum number of inline sources per call. When your retrieval system returns hundreds of candidates — for example, a full-text search over a large corpus returning the top 100 — you may need to batch the reranking across multiple calls or use a two-stage approach:

const MAX_SOURCES_PER_CALL = 100; // conservative safe limit
const STAGE_ONE_TOP_N = 20;       // top-20 from each batch
const STAGE_TWO_TOP_N = 5;        // final top-5

async function twoStageRerank(
  query: string,
  docs: TextDoc[]
): Promise<Array<TextDoc & { score: number }>> {
  if (docs.length === 0) return [];

  // Stage 1: batch rerank the full set, keep top-N per batch
  const batches: TextDoc[][] = [];
  for (let i = 0; i < docs.length; i += MAX_SOURCES_PER_CALL) {
    batches.push(docs.slice(i, i + MAX_SOURCES_PER_CALL));
  }

  const stage1Results = await Promise.all(
    batches.map((batch) => rerankText(query, batch, STAGE_ONE_TOP_N))
  );

  // Flatten stage 1 results
  const stage1Flat = stage1Results.flat();
  if (stage1Flat.length === 0) return [];

  // Stage 2: rerank the best candidates from all batches
  const safeTopN = Math.min(STAGE_TWO_TOP_N, stage1Flat.length);
  const stage2Response = await client.send(
    new RerankCommand({
      rerankingConfiguration: {
        type: "BEDROCK_RERANKING_MODEL",
        bedrockRerankingConfiguration: {
          modelConfiguration: { modelArn: AMAZON_RERANK_ARN },
          numberOfResults: safeTopN,
        },
      },
      sources: stage1Flat.map((doc) => ({
        type: "INLINE",
        inlineDocumentSource: {
          type: "TEXT",
          textDocument: { text: doc.text },
        },
      })),
      query: { type: "TEXT", textQuery: { text: query } },
    })
  );

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

Two-stage reranking adds one extra API call but handles arbitrarily large candidate sets. Stage 1 runs batches in parallel with Promise.all, so the latency is bounded by the slowest batch, not the number of batches. For MCP tool handlers where the query arrives infrequently (not on every agent turn), two-stage reranking is a good trade-off between result quality and API cost.

Caching reranking results

Unlike generation model calls, reranking results for the same (query, document set) are deterministic — the same input always produces the same output. This makes them safe to cache with a short TTL if your document corpus changes infrequently:

import crypto from "node:crypto";

interface CacheEntry {
  results: Array<{ id: string; score: number; text: string }>;
  cachedAt: number;
}

const rerankCache = new Map<string, CacheEntry>();
const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes

function cacheKey(query: string, docIds: string[]): string {
  const payload = JSON.stringify({ query, ids: docIds.sort() });
  return crypto.createHash("sha256").update(payload).digest("hex").slice(0, 16);
}

async function rerankWithCache(
  query: string,
  docs: TextDoc[],
  topN: number = 5
): Promise<Array<TextDoc & { score: number }>> {
  const key = cacheKey(query, docs.map((d) => d.id));
  const cached = rerankCache.get(key);

  if (cached && Date.now() - cached.cachedAt < CACHE_TTL_MS) {
    return cached.results.map((r) => ({
      id: r.id,
      text: r.text,
      score: r.score,
    }));
  }

  const results = await rerankText(query, docs, topN);

  rerankCache.set(key, {
    results: results.map((r) => ({ id: r.id, text: r.text, score: r.score })),
    cachedAt: Date.now(),
  });

  return results;
}

The cache key includes both the query and the sorted document IDs, so it invalidates correctly when the document set changes (new documents retrieved) or when the query changes. A 5-minute TTL is appropriate for MCP servers where the same user might follow up on a query within a conversation window — the second query in a conversation about the same topic often hits the cache, cutting latency for the follow-up turn.

Keep the in-process cache bounded using an LRU strategy if your MCP server handles many distinct queries — an unbounded Map will grow without limit in a long-running process.

Production gotchas

Empty text strings throw, not skip

Unlike vector stores that silently skip empty documents, Bedrock Reranking throws a ValidationException for any source entry where textDocument.text is an empty string or only whitespace. Always filter before passing to the API:

const validDocs = docs.filter((d) => d.text.trim().length > 0);

numberOfResults defaults to all results when omitted

Omitting numberOfResults returns all source documents reranked — not just a default top-5. This is useful when you want to apply your own threshold logic, but it means you're paying to score every document. If you only need the top 5, set numberOfResults: 5 explicitly and avoid scoring the other 15.

Results are pre-sorted — do not sort them again

The API returns results in descending score order. results[0] is always the most relevant. Many developers sort the results a second time out of habit, which 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.

Scores are not normalized across different models

A score of 0.6 from Amazon Rerank 1 is not the same as a score of 0.6 from Cohere Rerank v3 — the two models are calibrated differently. If you switch models without adjusting your threshold, you may filter out results that the new model scores lower even though they are equally relevant. Recalibrate thresholds on representative queries when switching models.

JSON document values must be strings or simple types

The jsonDocument.data object is passed as a JSON structure to the reranker, but deeply nested objects or arrays may not score as expected — the model tokenizes the JSON text. Flatten nested structures to top-level string fields before passing as JSON sources. Numbers and booleans are accepted but treated as their string representations for scoring purposes.

Monitor your reranking MCP tools with AliveMCP

AliveMCP monitors MCP server endpoints and surfaces latency spikes in tools that include reranking API calls, so you can catch performance regressions in multi-stage RAG pipelines before they reach users.

Start free monitoring