Guide · Amazon Bedrock · Inline Agents · Knowledge Bases
MCP Server Bedrock Inline Agents — Knowledge Base Associations, Retrieval Config
Bedrock Inline Agents can retrieve from Knowledge Bases during orchestration without a pre-built agent configuration — you attach KBs per invocation via the knowledgeBases array. When an inline agent has a Knowledge Base association, the agent can autonomously decide to retrieve from it when answering a question, just as a pre-built agent would. The difference is that the KB ID and retrieval settings are passed at call time, so the same MCP tool handler can query different KBs for different users, tenants, or request types. Three configuration fields matter most: knowledgeBaseId (the KB's ARN or ID), description (the agent uses this to decide when to retrieve from this KB), and retrievalConfiguration.vectorSearchConfiguration (controls how many results to fetch and whether to use hybrid or semantic search). Two constraints catch authors off-guard: attaching a KB to an inline agent requires both bedrock:Retrieve and bedrock:InvokeInlineAgent IAM permissions; and the KB's retrieval results are injected into the agent's context automatically — unlike return-of-control action groups, KB retrieval does NOT produce a ReturnControlPayload chunk, so your streaming loop does not need to handle it specially. For the core inline agent setup see inline agents overview; for action groups that complement KB retrieval see inline action groups; for standalone KB retrieval without agents see Bedrock Knowledge Base — retrieve and generate.
TL;DR
Add a knowledgeBases array to InvokeInlineAgentCommand. Each entry needs knowledgeBaseId, description, and optionally retrievalConfiguration.vectorSearchConfiguration to control result count and search type. The agent retrieves from the KB automatically — your streaming code handles only PayloadPart (response text) and optionally ReturnControlPayload (action groups). No special handling for KB retrieval chunks.
Attaching a Knowledge Base to an inline agent
The knowledgeBases field on InvokeInlineAgentCommand takes an array of KnowledgeBase objects. Each object specifies the KB to retrieve from and how the agent should retrieve:
import {
BedrockAgentRuntimeClient,
InvokeInlineAgentCommand,
KnowledgeBase,
} from "@aws-sdk/client-bedrock-agent-runtime";
const agentRuntimeClient = new BedrockAgentRuntimeClient({ region: "us-east-1" });
const FOUNDATION_MODEL = "amazon.nova-lite-v1:0";
// Knowledge Base ID from Bedrock console (a string like "ABCDE12345")
const KB_ID = process.env.BEDROCK_KB_ID!;
const kbAssociation: KnowledgeBase = {
knowledgeBaseId: KB_ID,
description:
"Contains MCP server documentation, API references, and integration guides. " +
"Use this for questions about MCP protocol, server configuration, and tool schemas.",
retrievalConfiguration: {
vectorSearchConfiguration: {
numberOfResults: 5, // how many chunks to retrieve per query
},
},
};
async function invokeWithKB(
sessionId: string,
instruction: string,
userQuery: string
): Promise<string> {
const command = new InvokeInlineAgentCommand({
sessionId,
foundationModel: FOUNDATION_MODEL,
instruction,
inputText: userQuery,
knowledgeBases: [kbAssociation],
enableTrace: false,
});
const result = await agentRuntimeClient.send(command);
let response = "";
for await (const chunk of result.completion) {
if (chunk.chunk?.bytes) {
response += new TextDecoder().decode(chunk.chunk.bytes);
}
}
return response;
}
The description field is critical — the agent uses it to decide whether to retrieve from this KB for a given query. Write it as a factual description of what information the KB contains and when the agent should use it. Vague descriptions like "contains documents" lead to under-retrieval. Specific descriptions like the example above help the agent correctly identify when the KB is relevant.
Per-tenant Knowledge Base routing
Inline agents make it straightforward to route each invocation to a different KB based on user context. This is impossible with pre-built agents (a fixed alias always uses the same KB configuration) but natural with inline agents:
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
const server = new McpServer({ name: "kb-agent-server", version: "1.0.0" });
// Tenant-to-KB mapping — load from config or database in production
const tenantKBs: Record<string, string> = {
"acme-corp": process.env.KB_ID_ACME!,
"globex-inc": process.env.KB_ID_GLOBEX!,
"default": process.env.KB_ID_DEFAULT!,
};
server.tool(
"tenant_aware_query",
{
session_id: z.string(),
tenant_id: z.string().describe("Tenant identifier for KB routing"),
query: z.string(),
},
async ({ session_id, tenant_id, query }) => {
const kbId = tenantKBs[tenant_id] ?? tenantKBs["default"];
const kb: KnowledgeBase = {
knowledgeBaseId: kbId,
description:
`Contains documentation and policies specific to tenant ${tenant_id}. ` +
"Use this Knowledge Base to answer questions about the tenant's configuration, policies, and data.",
retrievalConfiguration: {
vectorSearchConfiguration: { numberOfResults: 5 },
},
};
const instruction =
`You are a helpful assistant for ${tenant_id}. Answer questions using the provided Knowledge Base. ` +
"Be precise and cite the documentation when answering factual questions.";
const response = await agentRuntimeClient.send(
new InvokeInlineAgentCommand({
sessionId: session_id,
foundationModel: FOUNDATION_MODEL,
instruction,
inputText: query,
knowledgeBases: [kb],
})
);
let text = "";
for await (const chunk of response.completion) {
if (chunk.chunk?.bytes) text += new TextDecoder().decode(chunk.chunk.bytes);
}
return { content: [{ type: "text", text }] };
}
);
When routing tenants to different KBs, make sure the IAM role that runs the MCP server has bedrock:Retrieve permission for all KB ARNs it might access. If a KB ID is invalid or the IAM policy is missing for a specific KB, the agent returns a DependencyFailedException during the stream — not a pre-flight validation error.
Hybrid search configuration
By default, Bedrock KB retrieval uses semantic vector search. You can override this to use hybrid search (semantic + keyword BM25) on KBs that support it (OpenSearch Service and OpenSearch Serverless vector stores). Hybrid search typically improves precision on queries that contain specific product names, error codes, or other exact-match terms:
import { SearchType } from "@aws-sdk/client-bedrock-agent-runtime";
const hybridKB: KnowledgeBase = {
knowledgeBaseId: KB_ID,
description:
"Technical documentation including error codes, API method names, and configuration keys. " +
"Use for precise lookups involving specific identifiers or error messages.",
retrievalConfiguration: {
vectorSearchConfiguration: {
numberOfResults: 8,
overrideSearchType: SearchType.HYBRID, // "HYBRID" | "SEMANTIC"
},
},
};
const command = new InvokeInlineAgentCommand({
sessionId,
foundationModel: FOUNDATION_MODEL,
instruction,
inputText: userQuery,
knowledgeBases: [hybridKB],
});
Not all Bedrock KB backing stores support hybrid search. As of late 2026, hybrid search is available for OpenSearch Serverless and OpenSearch Service vector store types. Aurora PostgreSQL (pgvector) backing stores support only semantic search. If you request hybrid search on a KB that doesn't support it, the API returns a ValidationException rather than silently falling back to semantic search, so test this configuration explicitly after changing KB backing stores.
Metadata attribute filters
When a Knowledge Base's documents have metadata attributes (set during ingestion), you can filter the retrieval to only consider documents matching specific metadata conditions. This is useful for scoping retrieval to a document version, a product tier, or a date range:
import {
RetrievalFilter,
FilterAttribute,
} from "@aws-sdk/client-bedrock-agent-runtime";
function buildKBWithFilter(kbId: string, productTier: string): KnowledgeBase {
const tierFilter: RetrievalFilter = {
equals: {
key: "product_tier",
value: { stringValue: productTier },
},
};
return {
knowledgeBaseId: kbId,
description:
`Product documentation for the ${productTier} tier. ` +
"Use this for questions about features and limits available to this subscription tier.",
retrievalConfiguration: {
vectorSearchConfiguration: {
numberOfResults: 5,
filter: tierFilter,
},
},
};
}
server.tool(
"tier_scoped_query",
{
session_id: z.string(),
query: z.string(),
tier: z.enum(["free", "pro", "enterprise"]),
},
async ({ session_id, query, tier }) => {
const instruction =
"You are a support assistant. Answer questions based on the user's subscription tier documentation.";
const kb = buildKBWithFilter(KB_ID, tier);
const result = await agentRuntimeClient.send(
new InvokeInlineAgentCommand({
sessionId: session_id,
foundationModel: FOUNDATION_MODEL,
instruction,
inputText: query,
knowledgeBases: [kb],
})
);
let text = "";
for await (const chunk of result.completion) {
if (chunk.chunk?.bytes) text += new TextDecoder().decode(chunk.chunk.bytes);
}
return { content: [{ type: "text", text }] };
}
);
The filter field supports a full set of filter operators: equals, notEquals, greaterThan, greaterThanOrEquals, lessThan, lessThanOrEquals, in, notIn, startsWith, listContains, and logical operators andAll / orAll for composing multiple conditions. Metadata key names and value types must match what was set during document ingestion — a mismatch returns no results rather than an error. For the full filter operator reference see Bedrock KB metadata filtering.
Multiple Knowledge Bases per invocation
An inline agent can retrieve from multiple KBs in the same invocation. The agent decides which KB to query based on each KB's description and the user's query. This is useful when different aspects of a question require different document collections:
const docsKB: KnowledgeBase = {
knowledgeBaseId: process.env.KB_ID_DOCS!,
description:
"Official MCP server product documentation: installation, configuration, API reference. " +
"Use for how-to questions about product features.",
retrievalConfiguration: {
vectorSearchConfiguration: { numberOfResults: 5 },
},
};
const troubleshootingKB: KnowledgeBase = {
knowledgeBaseId: process.env.KB_ID_TROUBLESHOOT!,
description:
"Known issues, error codes, and troubleshooting guides. " +
"Use when the user describes an error message or unexpected behavior.",
retrievalConfiguration: {
vectorSearchConfiguration: {
numberOfResults: 5,
overrideSearchType: SearchType.HYBRID, // good for error code lookups
},
},
};
const changelogKB: KnowledgeBase = {
knowledgeBaseId: process.env.KB_ID_CHANGELOG!,
description:
"Product changelog and release notes. " +
"Use when the user asks about recent changes, what's new in a version, or when a feature was added.",
retrievalConfiguration: {
vectorSearchConfiguration: { numberOfResults: 3 },
},
};
const command = new InvokeInlineAgentCommand({
sessionId,
foundationModel: FOUNDATION_MODEL,
instruction:
"You are a knowledgeable MCP server support assistant with access to product docs, " +
"troubleshooting guides, and release notes. Use the appropriate Knowledge Base for each question.",
inputText: userQuery,
knowledgeBases: [docsKB, troubleshootingKB, changelogKB],
});
When using multiple KBs, write descriptions that clearly differentiate them so the agent picks the right one. If two KBs have similar descriptions, the agent may retrieve from the wrong one or query both when only one is needed, increasing latency. Test multi-KB routing by sending queries you expect to hit each KB and enabling trace (enableTrace: true) to verify which KB the agent actually queries for each question.
Combining Knowledge Bases with action groups
Inline agents support combining KB associations and action groups in the same invocation. This is a powerful pattern for MCP servers: the agent can retrieve background context from a KB and also call tools to fetch live data, then synthesize both sources in its response:
import { AgentActionGroup } from "@aws-sdk/client-bedrock-agent-runtime";
const liveDataActionGroup: AgentActionGroup = {
actionGroupName: "live_monitoring",
description: "Fetches real-time server status and recent alert data.",
actionGroupExecutor: { customControl: "RETURN_CONTROL" },
functionSchema: {
functions: [
{
name: "get_current_status",
description: "Returns live uptime status for a named MCP server.",
parameters: {
server_name: { type: "string", description: "Server name.", required: true },
},
},
],
},
};
const documentationKB: KnowledgeBase = {
knowledgeBaseId: process.env.KB_ID_DOCS!,
description:
"Product documentation for MCP server configuration and troubleshooting. " +
"Use to explain what a status code means or how to resolve a known issue.",
retrievalConfiguration: {
vectorSearchConfiguration: { numberOfResults: 4 },
},
};
// Agent can retrieve from KB for context AND call tools for live data
const hybridAgentCommand = new InvokeInlineAgentCommand({
sessionId,
foundationModel: FOUNDATION_MODEL,
instruction:
"You are a monitoring assistant. Use live tools to fetch real-time data " +
"and the documentation KB to explain what results mean and how to resolve issues.",
inputText: userQuery,
actionGroups: [liveDataActionGroup],
knowledgeBases: [documentationKB],
});
When combining KBs and action groups, the agent orchestrates both transparently — it may retrieve from the KB first to understand the context, then call a tool to get live data, then synthesize the final response. Your stream handler needs to handle both ReturnControlPayload chunks (for action group tool calls) and PayloadPart chunks (for the final response). KB retrieval is fully transparent — no special chunk type for KB results. For the complete stream handling code that covers all chunk types including ReturnControlPayload, see inline agents streaming.
IAM permissions for KB-enabled inline agents
Attaching a Knowledge Base to an inline agent invocation requires the calling role to have bedrock:Retrieve permission for the specific KB ARN, in addition to bedrock:InvokeInlineAgent:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["bedrock:InvokeInlineAgent"],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"],
"Resource": [
"arn:aws:bedrock:us-east-1::foundation-model/amazon.nova-lite-v1:0"
]
},
{
"Effect": "Allow",
"Action": ["bedrock:Retrieve"],
"Resource": [
"arn:aws:bedrock:us-east-1:123456789012:knowledge-base/ABCDE12345",
"arn:aws:bedrock:us-east-1:123456789012:knowledge-base/FGHIJ67890"
]
}
]
}
Use least-privilege for bedrock:Retrieve: list only the specific KB ARNs your MCP server legitimately needs to access. If you use a wildcard resource ("Resource": "*" for Retrieve), any KB accessible to the account becomes queryable from your MCP server, which may violate data isolation requirements in multi-tenant deployments.
Cross-account KB access
If the Knowledge Base lives in a different AWS account from your MCP server, the KB's resource policy must grant bedrock:Retrieve to the MCP server's role ARN, and the MCP server's IAM policy must list the cross-account KB ARN explicitly. Cross-account KB access does not work with wildcard ARN policies on either side.
numberOfResults tuning
The vectorSearchConfiguration.numberOfResults field controls how many document chunks the KB retriever returns. These chunks are injected into the agent's context window before each orchestration step. Retrieving too many chunks wastes context window space; retrieving too few may miss relevant information:
// Tuning guide based on KB document type:
// Short, dense documents (FAQs, reference entries): 5–8 results
const faqKB: KnowledgeBase = {
knowledgeBaseId: KB_ID,
description: "FAQ entries about MCP server configuration.",
retrievalConfiguration: {
vectorSearchConfiguration: { numberOfResults: 5 },
},
};
// Long-form documentation (guides, tutorials): 3–5 results
// Each chunk is larger, so fewer results fill the same context budget
const guideKB: KnowledgeBase = {
knowledgeBaseId: KB_ID,
description: "Long-form setup guides and tutorials.",
retrievalConfiguration: {
vectorSearchConfiguration: { numberOfResults: 4 },
},
};
// Code snippets and API reference (high precision needed): 10–15 results
// Many small relevant chunks may need to be combined
const apiRefKB: KnowledgeBase = {
knowledgeBaseId: KB_ID,
description: "API reference with code examples.",
retrievalConfiguration: {
vectorSearchConfiguration: {
numberOfResults: 12,
overrideSearchType: SearchType.HYBRID, // improves method name matching
},
},
};
The practical upper bound for numberOfResults is determined by the foundation model's context window and how many tokens each retrieved chunk consumes. With Amazon Nova Lite (amazon.nova-lite-v1:0), setting numberOfResults above 20 for long-form documents is unlikely to improve answer quality and may cause the agent to miss important context in its own orchestration history. Start with 5 and increase only if the agent consistently gives incomplete answers on complex multi-part questions.
KB retrieval in trace events
Enabling trace (enableTrace: true) reveals KB retrieval details as TracePart chunks in the stream. The trace shows which KB the agent queried, what search query it used, and which chunks it retrieved. This is invaluable for debugging why the agent gave a wrong or incomplete answer:
async function invokeWithKBTrace(
sessionId: string,
instruction: string,
query: string,
kb: KnowledgeBase
): Promise<{ response: string; kbQueries: string[] }> {
const result = await agentRuntimeClient.send(
new InvokeInlineAgentCommand({
sessionId,
foundationModel: FOUNDATION_MODEL,
instruction,
inputText: query,
knowledgeBases: [kb],
enableTrace: true,
})
);
let response = "";
const kbQueries: string[] = [];
for await (const chunk of result.completion) {
if (chunk.chunk?.bytes) {
response += new TextDecoder().decode(chunk.chunk.bytes);
}
if (chunk.trace?.trace?.orchestrationTrace?.observation?.knowledgeBaseLookupOutput) {
const lookupOutput = chunk.trace.trace.orchestrationTrace.observation.knowledgeBaseLookupOutput;
kbQueries.push(JSON.stringify({
retrievedReferenceCount: lookupOutput.retrievedReferences?.length ?? 0,
// Each reference has content.text (the retrieved chunk) and location (S3 or web URL)
firstReference: lookupOutput.retrievedReferences?.[0]?.content?.text?.slice(0, 200),
}));
}
}
return { response, kbQueries };
}
The trace path chunk.trace.trace.orchestrationTrace.observation.knowledgeBaseLookupOutput reveals what the agent retrieved. If the retrieved chunks don't match your expectation, the problem is usually either the KB's chunking configuration (chunks too large or too small during ingestion), a mismatch between the agent's search query and how the documents are written, or the wrong numberOfResults value. All three are easier to diagnose with trace enabled than by guessing from the final response alone.
Monitor your Bedrock Inline Agent MCP tools with AliveMCP
AliveMCP monitors MCP server endpoints for uptime and latency. When a KB-enabled inline agent tool handler starts timing out due to retrieval failures or elevated Knowledge Base query latency, AliveMCP alerts you before it impacts downstream agents.
Start free monitoring