Amazon Bedrock · InvokeInlineAgentCommand, Action Groups, Knowledge Bases & Streaming · 2026-11-26 · Bedrock Inline Agents arc

Amazon Bedrock Inline Agents for MCP Servers: A Complete Playbook

Four Bedrock Inline Agents arc pages synthesised into a complete production playbook for MCP server developers — covering the core InvokeInlineAgentCommand API (which lives in bedrock-agent-runtime, needs a plain model ID not an ARN, and maintains session state server-side across turns), return-of-control action groups (the only executor type inline agents support — no Lambda ARN; full loop with invocationId echo and empty inputText on follow-ups), per-call Knowledge Base associations (tenant-routed KB IDs, hybrid search for OpenSearch, metadata filters, combining KB + action groups in one invocation), and streaming response handling (the completion async iterable, the full ResponseStream union, stream-level errors as typed chunks not JS exceptions, AbortController timeouts, session deduplication). Ten production gotchas consolidated at the end.

Why inline agents over pre-built agents for MCP servers

Amazon Bedrock offers two ways to run an AI agent. Pre-built agents (via InvokeAgentCommand) are configured once in the Bedrock console or via CloudFormation/CDK: you define the system instruction, foundation model, action groups backed by Lambda functions, and Knowledge Base associations, then deploy an agent alias. Every invocation references that alias by its stable agentId and agentAliasId. Inline agents (via InvokeInlineAgentCommand) skip the console step entirely — the caller passes all configuration per-request.

MCP servers are fundamentally request-driven: each tool call arrives with its own parameters, context, and potentially different authorization scope. That request shape maps naturally to inline agents because:

The tradeoff: inline agents cannot use Bedrock-managed agent memory across sessions (the persistent memory feature requires a pre-built agent alias), and they cannot use Lambda-backed action groups directly — inline action groups use the return-of-control pattern where the calling code handles function execution. For MCP servers this is not a limitation in practice, because the tool execution logic already exists in the server process.

Package, client, and the foundationModel field that breaks everyone

Like the Reranking and Agents APIs, inline agents live in the Amazon Bedrock Agent Runtime SDK — not the Bedrock Runtime SDK used for ConverseCommand:

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

Create the client once at module initialization. Creating a new client per MCP tool call wastes time on credential resolution and connection setup:

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

const agentRuntimeClient = new BedrockAgentRuntimeClient({
  region: process.env.AWS_REGION ?? "us-east-1",
});

// Use plain model IDs — NOT full ARNs
const FOUNDATION_MODEL = process.env.BEDROCK_INLINE_AGENT_MODEL ?? "amazon.nova-lite-v1:0";

The critical difference from the Reranking API: foundationModel takes a plain model ID string (e.g., "amazon.nova-lite-v1:0"), not a full arn:aws:bedrock:REGION::foundation-model/MODEL_ID ARN. If you pass an ARN here, Bedrock returns a ValidationException immediately with no other indication of what is wrong. The reranking API requires ARNs; the inline agents API requires plain model IDs. The same SDK package, different rules for the model identifier. Models supported as of late 2026: amazon.nova-pro-v1:0, amazon.nova-lite-v1:0, anthropic.claude-3-5-sonnet-20241022-v2:0, anthropic.claude-3-haiku-20240307-v1:0. If the model is not enabled in your Bedrock Model Access settings, the API returns a ResourceNotFoundException.

The minimal invocation pattern

The simplest pattern: a single-turn invocation that sends a user message, collects the agent's text response, and returns it from an MCP tool handler. No action groups, no Knowledge Bases — just the foundation model with a custom instruction:

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

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

async function invokeInlineAgent(
  sessionId: string,
  instruction: string,
  userMessage: string
): Promise<string> {
  const command = new InvokeInlineAgentCommand({
    sessionId,
    foundationModel: FOUNDATION_MODEL,
    instruction,       // system-level prompt defining agent behavior
    inputText: userMessage,
    endSession: false, // keep session alive for follow-up turns
    enableTrace: false,
  });

  const response = await agentRuntimeClient.send(command);

  // completion is an AsyncIterable — iterate chunk by chunk
  if (!response.completion) return "";
  let fullResponse = "";
  for await (const chunk of response.completion) {
    if (chunk.chunk?.bytes) {
      fullResponse += new TextDecoder().decode(chunk.chunk.bytes);
    }
  }
  return fullResponse;
}

server.tool(
  "research_topic",
  {
    topic: z.string().describe("Research topic"),
    session_id: z.string().describe("Session ID for multi-turn continuity"),
    focus: z.string().optional(),
  },
  async ({ topic, session_id, focus }) => {
    const instruction = focus
      ? `You are a research assistant specializing in ${focus}. Provide detailed, accurate information with specific examples.`
      : "You are a thorough research assistant. Provide accurate information with clear structure.";

    const response = await invokeInlineAgent(session_id, instruction, `Research: ${topic}`);
    return { content: [{ type: "text", text: response }] };
  }
);

The core fields: sessionId is a string you generate and manage (a UUID works well); instruction is the agent's system prompt; inputText is the current user message; foundationModel is the plain model ID. The completion property is an async iterable — you must iterate it to get the response text. Each chunk has a chunk.bytes field containing a Uint8Array fragment of the UTF-8 encoded response. If you await response.completion without iterating, you get a stream object reference back, not a string — a subtle bug that produces no error at all.

Session management — the three invariants

The sessionId is the key to multi-turn conversations. Amazon Bedrock maintains conversation history server-side for the duration of the session. On each subsequent call with the same sessionId, the agent sees the full prior conversation and can answer follow-up questions. Three invariants you must respect:

Invariant 1: Session idle TTL is 25 minutes. Sessions without activity for 25 minutes are automatically closed server-side. After that, using the same sessionId starts a fresh conversation with no history — but Bedrock does not return an error. The session silently resets. If your MCP tool handler tracks sessions in memory, reconcile your TTL with Bedrock's: if your in-memory record says a session is active but Bedrock closed it at 25 minutes, the agent will start fresh without warning. The 25-minute number is frequently misquoted as 30 minutes in AWS documentation examples — 25 minutes is the actual enforced limit.

Invariant 2: The instruction is immutable after the first turn. The instruction field is processed on the first turn and stored server-side for the session. Subsequent turns in the same session use the stored instruction. If you pass a different instruction on a later turn in the same session, the behavior is undefined — the agent may ignore the new instruction entirely. Treat the instruction as locked for the lifetime of a session. If the agent's system prompt needs to change, end the session and start a new one with the new instruction.

Invariant 3: There is no server-side API to list active sessions. You must track sessions in your own store. An in-memory Map works for single-process MCP servers; for multi-process or serverless deployments, use Redis or DynamoDB to maintain session state across instances:

import { randomUUID } from "node:crypto";

const activeSessions = new Map<string, { createdAt: number; instruction: string }>();
const SESSION_TTL_MS = 24 * 60 * 1000; // 24 minutes — slightly under Bedrock's 25min limit

function getOrCreateSession(userId: string, instruction: string): string {
  const existing = activeSessions.get(userId);
  const now = Date.now();

  if (existing && now - existing.createdAt < SESSION_TTL_MS) {
    return userId; // userId doubles as sessionId here
  }

  const sessionId = `${userId}-${randomUUID()}`;
  activeSessions.set(userId, { createdAt: now, instruction });
  return sessionId;
}

Setting your local TTL to 24 minutes (slightly under Bedrock's 25) ensures your session store never references a session that Bedrock has already expired. The slight discrepancy creates a grace window where you proactively create a new session before Bedrock resets the old one.

Dynamic instructions — the killer feature for MCP servers

The main advantage of inline agents is that the instruction can be computed at invocation time from request parameters, user context, or configuration. This is natural for MCP tool handlers that serve multiple users with different roles or tenants with different requirements:

interface AgentConfig {
  role: string;
  constraints: string[];
  outputFormat: "markdown" | "json" | "plain";
  language?: string;
}

function buildInstruction(config: AgentConfig): string {
  const lines: string[] = [`You are ${config.role}.`];

  if (config.constraints.length > 0) {
    lines.push("Constraints:");
    for (const c of config.constraints) {
      lines.push(`- ${c}`);
    }
  }

  if (config.outputFormat === "json") {
    lines.push("Always respond with valid JSON. No prose outside the JSON object.");
  } else if (config.outputFormat === "markdown") {
    lines.push("Format your response in clean Markdown with headers, lists, and code blocks.");
  }

  if (config.language) {
    lines.push(`Always respond in ${config.language}.`);
  }

  return lines.join("\n");
}

server.tool(
  "run_specialized_agent",
  {
    role: z.string(),
    constraints: z.array(z.string()).default([]),
    output_format: z.enum(["markdown", "json", "plain"]).default("markdown"),
    language: z.string().optional(),
    session_id: z.string(),
    query: z.string(),
  },
  async ({ role, constraints, output_format, language, session_id, query }) => {
    const instruction = buildInstruction({ role, constraints, outputFormat: output_format, language });
    const response = await invokeInlineAgent(session_id, instruction, query);
    return { content: [{ type: "text", text: response }] };
  }
);

When building instructions dynamically, keep them concise. Very long instructions — over roughly 2,000 tokens — eat into the model's effective context window for the conversation. The practical limit is around 4,000 characters for the instruction field. If you have more constraints than that, consider whether some belong in the first user message rather than the system prompt. The instruction informs the agent's overall behavior; per-turn context is better placed in inputText.

Action groups with return-of-control — the full loop

Bedrock Inline Agents support giving the agent a set of function schemas it can call — but unlike pre-built agents that can call Lambda directly, inline agents only support the return-of-control executor. When the agent decides to call a tool, the stream emits a ReturnControlPayload chunk containing the function name and arguments. Your MCP server code receives this payload, executes the tool locally, and sends the result back in a follow-up invocation:

import {
  AgentActionGroup,
  InlineSessionState,
  ReturnControlPayload,
} from "@aws-sdk/client-bedrock-agent-runtime";

// Define function schemas at invocation time
const monitoringActionGroup: AgentActionGroup = {
  actionGroupName: "monitoring_tools",
  description: "Tools for checking MCP server status and retrieving monitoring data.",
  actionGroupExecutor: {
    customControl: "RETURN_CONTROL", // the only valid executor for inline agents
  },
  functionSchema: {
    functions: [
      {
        name: "get_server_status",
        description: "Returns the current uptime status of a named MCP server endpoint.",
        parameters: {
          server_name: { type: "string", description: "The MCP server name.", required: true },
        },
      },
      {
        name: "get_uptime_percentage",
        description: "Returns uptime percentage for a server over a time range.",
        parameters: {
          server_name: { type: "string", description: "The MCP server name.", required: true },
          days: { type: "integer", description: "Number of past days. Defaults to 30.", required: false },
        },
      },
    ],
  },
};

// Return-of-control invocation loop
async function runAgentWithTools(
  sessionId: string,
  instruction: string,
  initialInput: string,
  actionGroups: AgentActionGroup[]
): Promise<string> {
  let inputText = initialInput;
  let sessionState: InlineSessionState | undefined;
  const MAX_TOOL_CALLS = 10; // prevent infinite loops

  for (let iteration = 0; iteration < MAX_TOOL_CALLS; iteration++) {
    const command = new InvokeInlineAgentCommand({
      sessionId,
      foundationModel: FOUNDATION_MODEL,
      instruction,
      inputText,
      actionGroups,
      inlineSessionState: sessionState,
      enableTrace: false,
    });

    const result = await agentRuntimeClient.send(command);
    let responseText = "";
    let returnControl: ReturnControlPayload | undefined;

    for await (const chunk of result.completion ?? []) {
      if (chunk.chunk?.bytes) {
        responseText += new TextDecoder().decode(chunk.chunk.bytes);
      }
      if (chunk.returnControl) {
        returnControl = chunk.returnControl;
        break; // stop consuming the stream — handle tool call first
      }
      if (chunk.internalServerException || chunk.dependencyFailedException) {
        const err = chunk.internalServerException ?? chunk.dependencyFailedException;
        throw new Error(`Stream error: ${err?.message}`);
      }
    }

    // If no tool call, the agent has finished — return the response
    if (!returnControl) return responseText;

    // Execute the requested tool call(s) and prepare follow-up
    const invocationResults = [];
    for (const input of returnControl.invocationInputs ?? []) {
      if (!input.functionInvocationInput) continue;
      const fi = input.functionInvocationInput;
      const toolResult = await executeToolLocally(fi.function!, fi.parameters ?? []);
      invocationResults.push({
        functionResult: {
          actionGroup: fi.actionGroup ?? "",
          function: fi.function!,
          responseBody: { TEXT: { body: toolResult } },
        },
      });
    }

    // Echo invocationId back — required for the agent to correlate the result
    sessionState = {
      returnControlInvocationResults: invocationResults,
      invocationId: returnControl.invocationId,
    };

    // Follow-up after return-of-control MUST have empty inputText
    inputText = "";
  }

  return "Agent reached maximum tool call iterations.";
}

Four things catch MCP server authors off-guard in this loop:

  1. The follow-up inputText must be empty string (""). After a return-of-control turn, the agent treats the tool result in returnControlInvocationResults as the continuation. A non-empty inputText alongside a return-of-control result creates an ambiguous turn that the agent handles inconsistently — sometimes ignoring the tool result, sometimes producing a doubled response.
  2. The invocationId must be echoed back. It correlates the tool result with the specific tool-call request the agent issued. Omitting it causes the agent to lose track of which tool call it was waiting on.
  3. All parameter values arrive as strings, regardless of declared type. If you declared a parameter as type: "integer", the value still arrives as the string "5". Parse numeric and boolean parameters explicitly in your tool execution code.
  4. The actionGroups definition must be passed on every follow-up invocation. Inline agents do not persist the action group schema server-side — it must be re-sent on each call in the loop, identical to the original definition.

Parameter parsing from ReturnControlPayload

Because all parameter values arrive as strings, a type-safe parser is worth extracting into a utility:

function parseToolParameters(
  parameters: Array<{ name?: string; type?: string; value?: string }>
): Record<string, string | number | boolean> {
  const result: Record<string, string | number | boolean> = {};
  for (const p of parameters) {
    if (!p.name || p.value === undefined) continue;
    switch (p.type) {
      case "integer": result[p.name] = parseInt(p.value, 10); break;
      case "number":  result[p.name] = parseFloat(p.value); break;
      case "boolean": result[p.name] = p.value === "true"; break;
      default:        result[p.name] = p.value;
    }
  }
  return result;
}

async function executeToolLocally(
  functionName: string,
  parameters: Array<{ name?: string; type?: string; value?: string }>
): Promise<string> {
  const args = parseToolParameters(parameters);
  switch (functionName) {
    case "get_server_status":
      return getServerStatus(args.server_name as string);
    case "get_uptime_percentage":
      return getUptimePercentage(args.server_name as string, (args.days as number) ?? 30);
    default:
      return JSON.stringify({ error: `Unknown function: ${functionName}` });
  }
}

Return informative error JSON rather than throwing exceptions when a function is not found or required parameters are missing. The agent reads the error body, understands what went wrong, and may try a different approach on the next turn. Throwing an exception instead tears down the entire runAgentWithTools call and the user gets no response at all.

To disable the agent's default ability to ask clarifying questions (which can interrupt tool-use flows in MCP servers), include a disable action group for AMAZON.UserInput:

const userInputDisableGroup: AgentActionGroup = {
  actionGroupName: "UserInputActionGroup",
  parentActionGroupSignature: "AMAZON.UserInput",
  actionGroupState: "DISABLED",
};

// Pass alongside your functional action groups
actionGroups: [monitoringActionGroup, userInputDisableGroup]

By default, Bedrock Agents can emit a clarifying question mid-orchestration. For MCP server use cases where the calling LLM client expects a tool response, disabling this ensures the agent always produces a final answer. If the agent genuinely cannot complete the task, it says so in its final response rather than generating a stream-breaking clarification request.

Knowledge Base associations — per-call routing

Inline agents can retrieve from Bedrock Knowledge Bases during orchestration without a pre-built agent configuration. You attach KBs per invocation via the knowledgeBases array. Unlike action groups, KB retrieval does not produce a ReturnControlPayload chunk — the agent queries the KB autonomously during orchestration and the retrieved chunks are injected into its context automatically. Your streaming code does not need to handle KB retrieval specially:

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

const kbAssociation: KnowledgeBase = {
  knowledgeBaseId: process.env.BEDROCK_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,
    },
  },
};

const command = new InvokeInlineAgentCommand({
  sessionId,
  foundationModel: FOUNDATION_MODEL,
  instruction: "You are a helpful support assistant. Answer questions using the documentation Knowledge Base.",
  inputText: userQuery,
  knowledgeBases: [kbAssociation],
});

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 one above help the agent correctly identify when the KB is relevant to the question.

The key capability that inline agents unlock: per-tenant KB routing. Pre-built agents have a fixed KB configuration per alias; inline agents let you route each invocation to a different KB based on user context:

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(),
    query: z.string(),
  },
  async ({ session_id, tenant_id, query }) => {
    const kbId = tenantKBs[tenant_id] ?? tenantKBs["default"];
    const kb: KnowledgeBase = {
      knowledgeBaseId: kbId,
      description: `Contains documentation specific to tenant ${tenant_id}.`,
      retrievalConfiguration: { vectorSearchConfiguration: { numberOfResults: 5 } },
    };

    const result = await agentRuntimeClient.send(
      new InvokeInlineAgentCommand({
        sessionId: session_id,
        foundationModel: FOUNDATION_MODEL,
        instruction: `You are a support assistant for ${tenant_id}.`,
        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 }] };
  }
);

Hybrid search and metadata filters for KB retrieval

By default, Bedrock KB retrieval uses semantic vector search. For KBs backed by OpenSearch Service or OpenSearch Serverless, you can override this to use hybrid search (semantic + keyword BM25), which improves precision on queries containing specific product names, error codes, or other exact-match terms:

const hybridKB: KnowledgeBase = {
  knowledgeBaseId: KB_ID,
  description: "Technical documentation including error codes and API method names.",
  retrievalConfiguration: {
    vectorSearchConfiguration: {
      numberOfResults: 8,
      overrideSearchType: SearchType.HYBRID, // "HYBRID" | "SEMANTIC"
    },
  },
};

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 — this is the kind of failure that only appears in production after you migrate to a different KB backing store.

When a Knowledge Base's documents have metadata attributes set during ingestion, you can filter retrieval to only consider matching documents:

import { RetrievalFilter } 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.`,
    retrievalConfiguration: {
      vectorSearchConfiguration: {
        numberOfResults: 5,
        filter: tierFilter,
      },
    },
  };
}

The filter operators available: equals, notEquals, greaterThan, greaterThanOrEquals, lessThan, lessThanOrEquals, in, notIn, startsWith, listContains, and logical operators andAll / orAll. Metadata key names and value types must exactly match what was set during document ingestion — a mismatch returns no results rather than an error, so a typo in the filter key name will silently produce empty retrieval.

Combining Knowledge Bases with action groups

Inline agents support combining KB associations and action groups in the same invocation. The agent can retrieve background context from a KB and also call tools to fetch live data, then synthesize both sources in its response — a powerful pattern for MCP servers that need to blend static documentation with dynamic operational data:

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

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 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 — there is no special chunk type for KB results. This means the full return-of-control loop from the action groups section works unchanged when you add KBs — just add the knowledgeBases field to each InvokeInlineAgentCommand in the loop.

The streaming response — ResponseStream union in full

The InvokeInlineAgentResponse.completion field is typed as AsyncIterable<ResponseStream>. The ResponseStream union has several members, and the two most important failure modes both relate to it: not consuming it at all, and not checking for stream-level errors inside the loop:

// ResponseStream union — only one field is set per chunk
interface ResponseStream {
  chunk?: {
    bytes?: Uint8Array;        // UTF-8 encoded text fragment
    attribution?: Attribution; // source citations (if KB used)
  };
  returnControl?: ReturnControlPayload;         // action group tool call
  trace?: { trace?: AgentTrace; ... };          // only when enableTrace: true
  // Stream-level errors — these are NOT thrown JS exceptions
  internalServerException?: { message?: string };
  dependencyFailedException?: { message?: string; resourceName?: string };
  badGatewayException?: { message?: string; resourceName?: string };
  accessDeniedException?: { message?: string };
  serviceQuotaExceededException?: { message?: string };
  throttlingException?: { message?: string };
  validationException?: { message?: string };
}

The critical distinction: stream-level errors are delivered as typed fields in the chunk object — they are not JavaScript exceptions thrown by stream iteration. If you iterate the stream with just if (chunk.chunk?.bytes) and ignore all other fields, errors arrive silently and your code returns an empty string with no indication of what went wrong. You must check for each error type in every loop iteration.

A production-grade stream consumer that handles all chunk types:

export type StreamResult =
  | { type: "response"; text: string }
  | { type: "tool_call"; preText: string; payload: ReturnControlPayload }
  | { type: "error"; code: string; message: string };

export async function consumeInlineAgentStream(
  command: InvokeInlineAgentCommand,
  onTrace?: (trace: unknown) => void
): Promise<StreamResult> {
  let result: Awaited<ReturnType<typeof agentRuntimeClient.send>>;
  try {
    result = await agentRuntimeClient.send(command);
  } catch (err: unknown) {
    const e = err as { name?: string; message?: string };
    return { type: "error", code: e.name ?? "INVOKE_FAILED", message: e.message ?? String(err) };
  }

  if (!result.completion) {
    return { type: "error", code: "NO_STREAM", message: "completion stream was undefined" };
  }

  let responseText = "";

  try {
    for await (const chunk of result.completion) {
      if (chunk.chunk?.bytes) {
        responseText += new TextDecoder().decode(chunk.chunk.bytes);
      }
      if (chunk.returnControl) {
        return { type: "tool_call", preText: responseText, payload: chunk.returnControl };
      }
      if (chunk.trace && onTrace) onTrace(chunk.trace);
      if (chunk.throttlingException)
        return { type: "error", code: "THROTTLING", message: chunk.throttlingException.message ?? "Throttled" };
      if (chunk.dependencyFailedException)
        return { type: "error", code: "DEPENDENCY_FAILED", message: chunk.dependencyFailedException.message ?? "Dependency failed" };
      if (chunk.internalServerException)
        return { type: "error", code: "INTERNAL_SERVER_ERROR", message: chunk.internalServerException.message ?? "Internal error" };
      if (chunk.serviceQuotaExceededException)
        return { type: "error", code: "QUOTA_EXCEEDED", message: chunk.serviceQuotaExceededException.message ?? "Quota exceeded" };
      if (chunk.accessDeniedException)
        return { type: "error", code: "ACCESS_DENIED", message: chunk.accessDeniedException.message ?? "Access denied" };
    }
  } catch (streamErr: unknown) {
    const e = streamErr as { message?: string };
    return { type: "error", code: "STREAM_READ_ERROR", message: e.message ?? String(streamErr) };
  }

  return { type: "response", text: responseText };
}

The outer try/catch around the for await loop is necessary because network drops and HTTP-level errors during stream iteration throw JavaScript exceptions (not stream-level error chunks) — you need both the in-loop error checks and the outer catch. The preText field in the tool_call result captures any text the agent emits before the tool call. For most agents in a return-of-control flow this is empty or contains internal reasoning text that you don't want to surface to the end user. The final answer only comes after all tool calls complete.

Timeout and concurrency controls

Long-running inline agent streams — agents with many tool calls, long documents to summarize, or slow Knowledge Base retrievals — can take 30 seconds or more from dispatch to final response. The standard AbortController pattern enforces a time budget per tool call:

async function invokeWithTimeout(
  sessionId: string,
  instruction: string,
  inputText: string,
  timeoutMs: number = 25_000
): Promise<string> {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), timeoutMs);

  try {
    const result = await agentRuntimeClient.send(
      new InvokeInlineAgentCommand({ sessionId, foundationModel: FOUNDATION_MODEL, instruction, inputText }),
      { abortSignal: controller.signal }
    );

    if (!result.completion) return "";
    let text = "";
    for await (const chunk of result.completion) {
      if (controller.signal.aborted) break;
      if (chunk.chunk?.bytes) text += new TextDecoder().decode(chunk.chunk.bytes);
      if (chunk.internalServerException || chunk.dependencyFailedException) break;
    }
    return text;
  } catch (err: unknown) {
    const e = err as { name?: string };
    if (e.name === "AbortError") return "Agent response timed out.";
    throw err;
  } finally {
    clearTimeout(timer);
  }
}

For concurrency: each InvokeInlineAgentCommand with action groups or trace enabled can trigger 3–10 underlying foundation model invocations per user-visible agent turn. This amplification means inline agents consume Bedrock model TPS faster than direct ConverseCommand calls at the same user-request rate. Use p-queue to cap concurrent in-flight agent requests:

import PQueue from "p-queue";

const agentQueue = new PQueue({ concurrency: 5 });

server.tool(
  "queued_agent",
  { session_id: z.string(), instruction: z.string(), query: z.string() },
  async ({ session_id, instruction, query }) => {
    const response = await agentQueue.add(
      () => invokeWithTimeout(session_id, instruction, query)
    );
    return { content: [{ type: "text", text: response ?? "" }] };
  }
);

Set concurrency based on your Bedrock TPS quota for the foundation model. If your quota is 50 TPS and each agent turn uses up to 5 underlying model calls, limit concurrent agent sessions to 10 to stay safely under quota. For models with lower quotas — Anthropic Claude models on Bedrock often start at 10–20 TPS — reduce concurrency accordingly.

IAM permissions — three distinct actions

Inline agent invocations require a distinct IAM action from both regular Bedrock model invocations and pre-built agent invocations. The minimum policy for an MCP server that calls inline agents:

{
  "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",
        "arn:aws:bedrock:us-east-1::foundation-model/amazon.nova-pro-v1:0"
      ]
    }
  ]
}

bedrock:InvokeInlineAgent is distinct from both bedrock:InvokeAgent (pre-built agents) and bedrock:InvokeModel (Converse API). All three are needed if you use all three APIs. A role that has only bedrock:InvokeModel will get an AccessDeniedException on inline agent calls despite being able to call ConverseCommand successfully from the same code.

If you attach Knowledge Bases to inline agents, add bedrock:Retrieve for the specific KB ARNs. Use least-privilege: list only the specific KB ARNs your MCP server legitimately needs to access rather than wildcarding the resource:

{
  "Effect": "Allow",
  "Action": ["bedrock:Retrieve"],
  "Resource": [
    "arn:aws:bedrock:us-east-1:123456789012:knowledge-base/ABCDE12345"
  ]
}

A wildcard "Resource": "*" for bedrock:Retrieve makes any KB accessible to the account queryable from your MCP server — a data isolation violation in multi-tenant deployments where different tenants should only be able to retrieve from their own KB.

10 production gotchas — consolidated

These are the mistakes extracted from across all four Inline Agents arc pages. Each one silently fails in a way that is hard to diagnose without knowing what to look for.

  1. foundationModel takes a plain model ID, not an ARN. Passing arn:aws:bedrock:us-east-1::foundation-model/amazon.nova-lite-v1:0 produces a ValidationException. The reranking API requires ARNs; the inline agents API requires plain IDs like amazon.nova-lite-v1:0. Both come from the same SDK package, same client. Mixing the conventions is a constant source of confusion.
  2. The package is bedrock-agent-runtime, not bedrock-runtime. InvokeInlineAgentCommand does not exist in @aws-sdk/client-bedrock-runtime. Same mistake that trips up Reranking and regular Agents users — the naming is non-obvious.
  3. bedrock:InvokeInlineAgent is a separate IAM action. A role with bedrock:InvokeModel and bedrock:InvokeAgent does not have bedrock:InvokeInlineAgent. All three must be granted explicitly. AccessDeniedException on inline agent calls while ConverseCommand works fine is almost always this.
  4. completion is an async iterable — iterate it, do not await it. await response.completion returns the stream object, not a string. The model ran and produced a response, but your code returned the stream reference. No error is thrown. This is the most common inline agents bug in MCP server code.
  5. completion can be undefined. This happens when the HTTP connection drops before the stream starts. Check if (!result.completion) before the for await loop — iterating undefined throws a TypeError that is easy to confuse with an Bedrock API error.
  6. Stream-level errors are typed chunks, not JS exceptions. internalServerException, dependencyFailedException, and throttlingException arrive as fields on the chunk object inside the stream. If you don't check for them in every loop iteration, they are silently dropped and the response is whatever partial text collected before the error chunk.
  7. The session instruction is immutable after the first turn. Passing a different instruction on a later turn in the same session produces undefined behavior — the agent may ignore the new instruction or behave inconsistently. Treat the instruction as locked for the session lifetime. To change instructions, end the session and create a new one.
  8. Session idle TTL is 25 minutes, not 30. Sessions without activity for 25 minutes are silently reset by Bedrock — the same sessionId starts a fresh conversation with no history and no error. Set your local session store TTL to 24 minutes to proactively create a new session before Bedrock expires the old one.
  9. Follow-up after return-of-control MUST have inputText: "". A non-empty inputText alongside returnControlInvocationResults creates an ambiguous turn. The agent behavior is inconsistent — it may ignore the tool result, repeat the tool call, or produce garbled output. This always manifests as "the agent ignores my tool results."
  10. Hybrid search ValidationException on Aurora pgvector KBs. Requesting SearchType.HYBRID on a Knowledge Base backed by Aurora PostgreSQL (pgvector) returns a ValidationException rather than silently falling back to semantic search. If you migrate a KB's backing store from OpenSearch to pgvector, hybrid search configuration must also be updated — it will not silently degrade to semantic search.

Monitor your Bedrock Inline Agent MCP tools with AliveMCP

AliveMCP monitors MCP server endpoints for uptime, latency spikes, and error rates. When an inline agent tool handler starts producing elevated latency from long orchestration chains or throttled model calls — or when a return-of-control loop starts timing out silently — AliveMCP catches it and alerts you before it cascades into tool timeouts for your users. Free tier covers every public MCP endpoint in the registry with 90-day uptime history.

Start free monitoring