Guide · Amazon Bedrock · Knowledge Base Retrieval

Amazon Bedrock RetrieveAndGenerate for MCP Servers — Citations, sessionId Memory, and Guardrails

RetrieveAndGenerateCommand performs retrieval and LLM generation in a single Bedrock API call, returning a natural-language answer grounded in your knowledge base along with structured citations for every source chunk used. For MCP servers that expose question-answering over internal documentation, this is cleaner than calling RetrieveCommand and then passing chunks to a second ConverseCommand — the retrieval context, model selection, and system prompt are all wired inside Bedrock. The two most common gotchas are using a short model ID instead of a full model ARN (throws ValidationException: modelArn is not a valid ARN — you cannot pass anthropic.claude-3-5-sonnet-20241022-v2:0; you must pass a full ARN or cross-region inference profile ID in ARN form) and misunderstanding session expiry (sessions expire after 1 hour of inactivity; a resumed session after expiry starts fresh without error). This guide covers ModelArn formatting, citation extraction, multi-turn sessionId patterns, guardrail embedding, and promptTemplate customization. For search mode selection, see Hybrid Search. For metadata attribute filters, see Metadata Filtering. For data source sync, see Data Sources.

TL;DR

Pass modelArn: "arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-3-5-sonnet-20241022-v2:0" (full ARN, not short ID). Use sessionId from the response for follow-up questions. Extract citations from output.text references and citations[].retrievedReferences[].location. Sessions expire 1 hour after last use — handle re-creation transparently. Use guardrailConfiguration to wrap guardrails around both retrieval context and generated response.

RetrieveAndGenerate vs Retrieve + Converse

RetrieveAndGenerateCommand is a convenience API that combines retrieval and generation. The tradeoffs versus calling RetrieveCommand followed by ConverseCommand separately:

DimensionRetrieveAndGenerateRetrieve + Converse (manual RAG)
Number of API calls12 (or more if reranking)
Citation structureReturned in response — no parsing neededMust be constructed manually from chunk content
Multi-turn memoryBuilt-in via sessionIdMust manage conversation history array manually
Retrieval controlLimited — only numberOfResults and filter exposedFull control over overrideSearchType, scoring, reranking
System promptPartial — only via promptTemplate wrapperFull system parameter in ConverseCommand
StreamingNot supported as of late 2026Full streaming via ConverseStreamCommand
GuardrailsBuilt-in via guardrailConfigurationMust wire via ConverseCommand guardrailConfig

Use RetrieveAndGenerate when you want citations and multi-turn conversation and can live without streaming. Use manual RAG when you need fine-grained retrieval control, streaming output, or a complex system prompt that cannot be expressed as a template suffix.

Basic RetrieveAndGenerateCommand call

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

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

const KNOWLEDGE_BASE_ID = process.env.BEDROCK_KB_ID!;
// Full foundation model ARN — NOT a short model ID
const MODEL_ARN =
  "arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-3-5-sonnet-20241022-v2:0";

export interface RagResponse {
  answer: string;
  sessionId: string;
  citations: Array<{
    generatedText: string;
    sources: Array<{ text: string; uri: string }>;
  }>;
}

export async function askKnowledgeBase(
  question: string,
  sessionId?: string,
): Promise<RagResponse> {
  const input: RetrieveAndGenerateCommandInput = {
    input: { text: question },
    retrieveAndGenerateConfiguration: {
      type: "KNOWLEDGE_BASE",
      knowledgeBaseConfiguration: {
        knowledgeBaseId: KNOWLEDGE_BASE_ID,
        modelArn: MODEL_ARN,
        retrievalConfiguration: {
          vectorSearchConfiguration: {
            numberOfResults: 10,
            overrideSearchType: "HYBRID",
          },
        },
        generationConfiguration: {
          inferenceConfig: {
            textInferenceConfig: {
              maxTokens: 1024,
              temperature: 0.0,
              topP: 0.9,
            },
          },
        },
      },
    },
    sessionId, // undefined on first call, then pass back the returned sessionId
  };

  const response = await client.send(new RetrieveAndGenerateCommand(input));

  const citations = (response.citations ?? []).map((c) => ({
    generatedText: c.generatedResponsePart?.textResponsePart?.text ?? "",
    sources: (c.retrievedReferences ?? []).map((ref) => ({
      text: ref.content?.text ?? "",
      uri:
        ref.location?.s3Location?.uri ??
        ref.location?.webLocation?.url ??
        "",
    })),
  }));

  return {
    answer: response.output?.text ?? "",
    sessionId: response.sessionId ?? "",
    citations,
  };
}

ModelArn — the most common ValidationException

The modelArn field requires a full ARN string. The three valid formats are:

Passing a bare model ID like anthropic.claude-3-5-sonnet-20241022-v2:0 throws ValidationException: 1 validation error detected: Value at 'retrieveAndGenerateConfiguration.knowledgeBaseConfiguration.modelArn' failed to satisfy constraint: Member must satisfy regular expression pattern. The error message is clear but only encountered at runtime — there is no compile-time enforcement. Use a constant with the full ARN and test it in development before deploying.

Multi-turn conversation with sessionId

When you pass sessionId from one call into the next, Bedrock maintains conversation context — previous questions and answers inform the retrieval query for the follow-up. This is critical for conversational use cases where follow-up questions like "what about the retry behavior?" refer back to a previous question about Bedrock throttling.

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

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

// In-memory session store — replace with Redis or DynamoDB for multi-instance MCP servers
const sessionStore = new Map<string, string>(); // conversationId → bedrockSessionId

server.tool(
  "ask_docs",
  {
    question: z.string().describe("Question to answer from documentation"),
    conversation_id: z
      .string()
      .optional()
      .describe("Conversation ID for follow-up questions; omit for new conversation"),
  },
  async ({ question, conversation_id }) => {
    const bedrockSessionId = conversation_id
      ? sessionStore.get(conversation_id)
      : undefined;

    let result: RagResponse;
    try {
      result = await askKnowledgeBase(question, bedrockSessionId);
    } catch (err: unknown) {
      // Session expired (1 hour inactivity) — start fresh
      if (
        err instanceof Error &&
        err.name === "ResourceNotFoundException" &&
        bedrockSessionId !== undefined
      ) {
        if (conversation_id) sessionStore.delete(conversation_id);
        result = await askKnowledgeBase(question, undefined);
      } else {
        throw err;
      }
    }

    // Persist the Bedrock session ID under the caller's conversation_id
    if (conversation_id) {
      sessionStore.set(conversation_id, result.sessionId);
    }

    // Format answer with citations
    let output = result.answer;
    if (result.citations.length > 0) {
      const sourceUris = [
        ...new Set(
          result.citations.flatMap((c) => c.sources.map((s) => s.uri).filter(Boolean)),
        ),
      ];
      if (sourceUris.length > 0) {
        output += "\n\nSources:\n" + sourceUris.map((u) => `- ${u}`).join("\n");
      }
    }

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

Session expiry behavior

Bedrock sessions expire after 1 hour of inactivity. If you pass an expired sessionId, the API throws ResourceNotFoundException with a message about the session not being found — the same exception thrown for an invalid knowledge base ID. The code above handles this transparently by catching the error and retrying without a session ID. Without this handler, an expired session will surface as an unhandled exception in production, breaking conversations that resume after an idle period.

Custom system prompt via promptTemplate

generationConfiguration.promptTemplate.textPromptTemplate lets you wrap a custom system-level instruction around the retrieved context. Bedrock substitutes $search_results$ with the retrieved chunks and passes the resulting text as the system prompt to the generation model:

generationConfiguration: {
  promptTemplate: {
    textPromptTemplate: `You are a helpful assistant for the Platform Engineering team.
Answer questions using only the following documentation excerpts.
If the documentation does not contain enough information to answer confidently, say so explicitly.
Do not speculate or use external knowledge beyond what is provided.

$search_results$`,
  },
  inferenceConfig: {
    textInferenceConfig: {
      maxTokens: 1024,
      temperature: 0.0,
    },
  },
},

The $search_results$ placeholder is required — omitting it throws ValidationException. The template cannot be used to add user-turn instructions; it only wraps the system context. If you need to inject user-specific instructions per request (e.g., the caller's permission level), use manual RAG with ConverseCommand instead, where the full system parameter and the message array are both controllable.

Embedding guardrails in RetrieveAndGenerate

Guardrails apply to both the retrieved context (pre-generation) and the model output (post-generation). The guardrailConfiguration field takes a guardrail ARN and version:

knowledgeBaseConfiguration: {
  knowledgeBaseId: KNOWLEDGE_BASE_ID,
  modelArn: MODEL_ARN,
  generationConfiguration: {
    guardrailConfiguration: {
      guardrailId: "abc123",          // from CreateGuardrail response
      guardrailVersion: "DRAFT",      // or a version number string like "1"
    },
    inferenceConfig: {
      textInferenceConfig: { maxTokens: 1024, temperature: 0.0 },
    },
  },
},

When a guardrail blocks a response, the output text is replaced with the guardrail's configured blocked message and the response includes guardrailAction: "INTERVENED" in the guardrail trace. If guardrailAction is "INTERVENED", the output.text will contain the guardrail's fallback message rather than a generated answer — check for this before surfacing the response to users. The IAM policy for the execution role must include bedrock:ApplyGuardrail on the guardrail ARN.

Extracting and surfacing citations

The citations array in the response maps generated text spans back to their source chunks. Each citation entry contains the generatedResponsePart.textResponsePart.text (the sentence or phrase in the answer) and an array of retrievedReferences (the source chunks that grounded it):

function formatCitations(citations: RagResponse["citations"]): string {
  const sourceMap = new Map<string, number>();
  let refIndex = 1;
  const lines: string[] = [];

  for (const citation of citations) {
    for (const source of citation.sources) {
      if (source.uri && !sourceMap.has(source.uri)) {
        sourceMap.set(source.uri, refIndex++);
      }
    }
  }

  for (const [uri, idx] of sourceMap) {
    lines.push(`[${idx}] ${uri}`);
  }

  return lines.length > 0 ? "\n\nSources:\n" + lines.join("\n") : "";
}

Citations are valuable in MCP tool responses because they let the calling agent (and ultimately the end user) verify claims against primary sources. For compliance-sensitive use cases — HR policy, legal documentation, security runbooks — including citations is not optional.

Monitoring RetrieveAndGenerate with AliveMCP

RetrieveAndGenerate calls are slower than pure retrieve calls because they include an LLM generation step. Latency spikes on this tool surface as slow MCP tool responses that stall the calling agent. AliveMCP monitors p50, p95, and p99 latency for each MCP tool, so you can distinguish between retrieval slowness (OpenSearch latency) and generation slowness (Bedrock model capacity). A p99 latency increase with no p50 change is typically a cross-region inference routing event; a uniform latency increase on all percentiles indicates corpus growth requiring a larger numberOfResults cut-down.

Related pages in this arc

For guardrail creation, see Bedrock Guardrails for MCP Servers. For the foundational knowledge base overview, see Bedrock Knowledge Base for MCP Servers.