Guide · Amazon Bedrock · Inline Agents · Streaming
MCP Server Bedrock Inline Agents — Streaming Response, PayloadPart, ReturnControlPayload, Trace
The InvokeInlineAgentCommand response does not resolve to a completed string — it resolves to an async iterable stream that you must consume chunk by chunk to retrieve the agent's response. The completion property on the response is an AsyncIterable<ResponseStream> where each yielded value is a discriminated union: a PayloadPart containing a fragment of the agent's response text, a ReturnControlPayload signaling that the agent wants to call an action group tool, a TracePart with orchestration trace data (only when enableTrace: true), or one of several stream-level error types. Four mistakes dominate MCP server bug reports for inline agents: not consuming the stream at all (the agent runs but you get no response); not checking for stream-level error chunks inside the for await loop (errors are silently dropped); breaking out of the stream on ReturnControlPayload but forgetting that partial text may have been emitted before the tool-call chunk; and not handling the case where completion itself is undefined (this happens when the HTTP connection drops before the stream starts). For the base inline agent setup see inline agents overview; for how to handle return-of-control from action groups see inline action groups; for Knowledge Base associations see inline KB associations.
TL;DR
Iterate response.completion with for await. Collect chunk.chunk?.bytes (decode with TextDecoder) for response text. Break on chunk.returnControl to handle tool calls. Check chunk.internalServerException and chunk.dependencyFailedException in every iteration. If enableTrace: true, skip chunk.trace for the response but log it for debugging. Never await the entire stream outside the loop.
The completion stream structure
The InvokeInlineAgentResponse type exposes a completion field typed as AsyncIterable<ResponseStream>. The ResponseStream union type has the following members, each mutually exclusive within a single chunk object:
// ResponseStream union — only one field is set per chunk
interface ResponseStream {
// Agent's response text — present during final answer generation
chunk?: {
bytes?: Uint8Array; // UTF-8 encoded text fragment
attribution?: Attribution; // source citations (if KB used)
};
// Agent requests a tool call — present when action group fires
returnControl?: ReturnControlPayload;
// Orchestration trace event — only when enableTrace: true
trace?: {
agentId?: string;
agentVersion?: string;
sessionId?: string;
trace?: AgentTrace; // deep nested object with orchestration details
};
// Stream-level errors — can appear after successful PayloadPart chunks
internalServerException?: { message?: string };
dependencyFailedException?: { message?: string; resourceName?: string };
badGatewayException?: { message?: string; resourceName?: string };
accessDeniedException?: { message?: string };
resourceNotFoundException?: { message?: string; resourceName?: string };
serviceQuotaExceededException?: { message?: string };
throttlingException?: { message?: string };
validationException?: { message?: string };
conflictException?: { message?: string };
}
The critical distinction: stream-level errors are delivered as typed fields in the chunk object — they are not JavaScript exceptions thrown by the 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 explicitly check for each error type (or at least the most common ones) in every loop iteration.
Complete production stream consumer
A production-grade stream consumer that handles all chunk types and both pre-flight and stream-level errors:
import {
BedrockAgentRuntimeClient,
InvokeInlineAgentCommand,
ReturnControlPayload,
} from "@aws-sdk/client-bedrock-agent-runtime";
const agentRuntimeClient = new BedrockAgentRuntimeClient({ region: "us-east-1" });
export type StreamResult =
| { type: "response"; text: string }
| { type: "tool_call"; payload: ReturnControlPayload }
| { type: "error"; code: string; message: string };
export async function consumeInlineAgentStream(
sessionId: string,
foundationModel: string,
instruction: string,
inputText: string,
options?: {
enableTrace?: boolean;
onTrace?: (trace: unknown) => void;
}
): Promise<StreamResult> {
let command: InvokeInlineAgentCommand;
try {
command = new InvokeInlineAgentCommand({
sessionId,
foundationModel,
instruction,
inputText,
enableTrace: options?.enableTrace ?? false,
});
} catch (err) {
return { type: "error", code: "COMMAND_BUILD_FAILED", message: String(err) };
}
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) {
// Response text
if (chunk.chunk?.bytes) {
responseText += new TextDecoder().decode(chunk.chunk.bytes);
}
// Tool call — return early to let the caller handle it
if (chunk.returnControl) {
return { type: "tool_call", payload: chunk.returnControl };
}
// Trace events (dev/debug only)
if (chunk.trace && options?.onTrace) {
options.onTrace(chunk.trace);
}
// Stream-level errors — check most common first
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" };
}
if (chunk.validationException) {
return { type: "error", code: "VALIDATION", message: chunk.validationException.message ?? "Validation error" };
}
}
} catch (streamErr: unknown) {
// This catches network-level errors during stream iteration
const e = streamErr as { message?: string };
return { type: "error", code: "STREAM_READ_ERROR", message: e.message ?? String(streamErr) };
}
return { type: "response", text: responseText };
}
This function returns a discriminated union that lets the caller handle each case explicitly. The tool_call result exits the stream early — the caller is responsible for executing the tool and resuming with a follow-up invocation (see action groups for the full return-of-control loop). Note the outer try/catch around the for await loop — network drops and HTTP errors during stream iteration throw JavaScript exceptions (not stream-level error chunks), so you need both the in-loop error checks and the outer catch.
Collecting partial text before a tool call
The agent may emit partial response text before a ReturnControlPayload chunk. For example, an agent might output "Let me check that for you..." before invoking a tool. If your MCP tool handler returns the agent's final response to the client, you need to decide what to do with this partial text:
type AgentStreamOutcome =
| { kind: "final"; text: string }
| { kind: "tool_call"; preText: string; payload: ReturnControlPayload }
| { kind: "error"; code: string; message: string };
async function consumeStream(
command: InvokeInlineAgentCommand
): Promise<AgentStreamOutcome> {
const result = await agentRuntimeClient.send(command);
if (!result.completion) {
return { kind: "error", code: "NO_STREAM", message: "completion stream was undefined" };
}
let accumulatedText = "";
for await (const chunk of result.completion) {
if (chunk.chunk?.bytes) {
accumulatedText += new TextDecoder().decode(chunk.chunk.bytes);
}
if (chunk.returnControl) {
// Return both the pre-tool partial text and the tool call payload
return { kind: "tool_call", preText: accumulatedText, payload: chunk.returnControl };
}
if (chunk.internalServerException || chunk.dependencyFailedException) {
const err = chunk.internalServerException ?? chunk.dependencyFailedException;
return { kind: "error", code: "STREAM_ERROR", message: err?.message ?? "Stream error" };
}
}
return { kind: "final", text: accumulatedText };
}
// In a return-of-control loop, discard preText from tool-call turns
// since it's the agent's internal reasoning, not the final answer
async function runAgentLoop(
sessionId: string,
instruction: string,
initialInput: string
): Promise<string> {
let inputText = initialInput;
let sessionState = undefined;
for (let i = 0; i < 10; i++) {
const command = new InvokeInlineAgentCommand({
sessionId,
foundationModel: "amazon.nova-lite-v1:0",
instruction,
inputText,
inlineSessionState: sessionState,
});
const outcome = await consumeStream(command);
if (outcome.kind === "final") return outcome.text;
if (outcome.kind === "error") {
throw new Error(`${outcome.code}: ${outcome.message}`);
}
// Handle tool call — execute and resume
const { payload } = outcome;
const invocationResults = await executeToolCallsFromPayload(payload);
sessionState = {
returnControlInvocationResults: invocationResults,
invocationId: payload.invocationId,
};
inputText = ""; // empty on follow-up after return-of-control
}
return "Max iterations reached.";
}
// Placeholder — implement with your actual tool dispatch logic
async function executeToolCallsFromPayload(payload: ReturnControlPayload) {
return (payload.invocationInputs ?? [])
.filter((i) => i.functionInvocationInput)
.map((i) => ({
functionResult: {
actionGroup: i.functionInvocationInput!.actionGroup!,
function: i.functionInvocationInput!.function!,
responseBody: { TEXT: { body: JSON.stringify({ result: "placeholder" }) } },
},
}));
}
The preText field 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 and the agent emits a final stream outcome with no pending ReturnControlPayload.
Source citations from Knowledge Base retrieval
When a Knowledge Base is attached and the agent retrieves documents, the PayloadPart chunks include attribution data alongside the response text. The chunk.chunk.attribution.citations array lists which retrieved document chunks contributed to each text fragment:
interface Citation {
generatedResponsePart?: {
textResponsePart?: {
text?: string; // text fragment this citation applies to
span?: { start: number; end: number }; // character range in full response
};
};
retrievedReferences?: Array<{
content?: { text?: string }; // the retrieved document chunk
location?: {
type?: string; // "S3" | "WEB" | "CONFLUENCE" | ...
s3Location?: { uri?: string };
webLocation?: { url?: string };
};
metadata?: Record<string, unknown>;
}>;
}
async function consumeWithCitations(
command: InvokeInlineAgentCommand
): Promise<{ text: string; citations: Citation[] }> {
const result = await agentRuntimeClient.send(command);
let text = "";
const citations: Citation[] = [];
for await (const chunk of result.completion) {
if (chunk.chunk?.bytes) {
text += new TextDecoder().decode(chunk.chunk.bytes);
}
if (chunk.chunk?.attribution?.citations) {
citations.push(...chunk.chunk.attribution.citations);
}
if (chunk.internalServerException || chunk.dependencyFailedException) break;
}
return { text, citations };
}
// Format citations for inclusion in MCP tool response
function formatCitations(citations: Citation[]): string {
const sources = new Set<string>();
for (const citation of citations) {
for (const ref of citation.retrievedReferences ?? []) {
const loc = ref.location;
if (loc?.s3Location?.uri) sources.add(loc.s3Location.uri);
if (loc?.webLocation?.url) sources.add(loc.webLocation.url);
}
}
if (sources.size === 0) return "";
return "\n\nSources:\n" + [...sources].map((s) => `- ${s}`).join("\n");
}
Citations are delivered inline with the text chunks — a single response can have multiple citation entries spanning different parts of the text. If your MCP tool needs to surface document sources alongside the agent's answer (for transparency or compliance), collect citations in the stream loop and append them after the response text.
Streaming to MCP clients with progressive delivery
MCP tools return content after the handler resolves — there is no built-in streaming protocol for tool results in the base MCP spec. This means you must fully collect the agent's response before returning it from the tool handler. However, for multi-turn interactions you can implement pseudo-streaming by returning incremental JSON objects with partial results and asking the client to call the tool again with a continuation token:
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
const server = new McpServer({ name: "streaming-agent-server", version: "1.0.0" });
// Map from session_id to in-progress response chunks
const responseBuffers = new Map<string, string[]>();
server.tool(
"agent_query",
{
session_id: z.string(),
query: z.string(),
instruction: z.string(),
},
async ({ session_id, query, instruction }) => {
// Fully collect the response before returning (MCP tool constraint)
const command = new InvokeInlineAgentCommand({
sessionId: session_id,
foundationModel: "amazon.nova-lite-v1:0",
instruction,
inputText: query,
enableTrace: false,
});
const result = await agentRuntimeClient.send(command);
if (!result.completion) {
return { content: [{ type: "text", text: "Error: no completion stream." }] };
}
let text = "";
let errorMessage = "";
for await (const chunk of result.completion) {
if (chunk.chunk?.bytes) {
text += new TextDecoder().decode(chunk.chunk.bytes);
}
if (chunk.internalServerException) {
errorMessage = chunk.internalServerException.message ?? "Internal server error";
break;
}
if (chunk.dependencyFailedException) {
errorMessage = chunk.dependencyFailedException.message ?? "Dependency failed";
break;
}
if (chunk.throttlingException) {
errorMessage = "Request throttled. Please retry.";
break;
}
}
if (errorMessage) {
return { content: [{ type: "text", text: `Error: ${errorMessage}` }] };
}
return { content: [{ type: "text", text }] };
}
);
For long-running agent responses (agents with many tool calls or long documents to summarize), the total latency from InvokeInlineAgentCommand dispatch to final PayloadPart can exceed 30 seconds. Set appropriate timeouts in your MCP server framework — the default HTTP timeout in most Node.js HTTP servers is 30 seconds, which may kill long agent runs. Increase the socket timeout on your HTTP server or use a streaming transport that keeps the connection open.
Timeout and abort handling
Long-running inline agent streams can be aborted using the standard AbortController pattern. This is important for MCP servers that need to enforce response time budgets 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 command = new InvokeInlineAgentCommand({
sessionId,
foundationModel: "amazon.nova-lite-v1:0",
instruction,
inputText,
});
const result = await agentRuntimeClient.send(command, {
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. The query may require more time to process.";
}
throw err;
} finally {
clearTimeout(timer);
}
}
When the abort signal fires, Bedrock stops sending new chunks and the stream iteration exits on the next iteration. Any partial text collected before the abort is returned — if you need a complete response or nothing, check whether controller.signal.aborted is true before returning the accumulated text and return an error message instead.
Deduplicating stream iterations for concurrent callers
If multiple MCP clients call the same tool with the same session ID concurrently, they would each start their own InvokeInlineAgentCommand for the same session, which creates conflicting session state. Use an in-progress map to deduplicate concurrent requests for the same session:
const inProgressAgentCalls = new Map<string, Promise<string>>();
async function invokeDeduped(
sessionId: string,
instruction: string,
inputText: string
): Promise<string> {
const existing = inProgressAgentCalls.get(sessionId);
if (existing) {
// Wait for the in-progress call to complete, then start a new one
await existing.catch(() => {});
}
const promise = invokeWithTimeout(sessionId, instruction, inputText);
inProgressAgentCalls.set(sessionId, promise);
try {
return await promise;
} finally {
// Remove only if this exact promise is still the registered one
if (inProgressAgentCalls.get(sessionId) === promise) {
inProgressAgentCalls.delete(sessionId);
}
}
}
The deduplication strategy here serializes calls to the same session — when a second call arrives while the first is still running, it waits for the first to finish before starting. This avoids session state conflicts at the cost of serializing concurrent requests for the same session. If your use case requires true concurrent agent calls, use separate session IDs per caller.
Extracting session-ended status
The inline agent stream does not emit an explicit "session ended" chunk. The session ends when endSession: true is set on the last invocation and the stream completes normally. To confirm a session was successfully ended, check that the stream iterated to completion without errors after the endSession call:
async function endSession(sessionId: string): Promise<boolean> {
try {
const result = await agentRuntimeClient.send(
new InvokeInlineAgentCommand({
sessionId,
foundationModel: "amazon.nova-lite-v1:0",
instruction: "Session ending.",
inputText: "",
endSession: true,
})
);
// Drain the stream to confirm clean completion
if (result.completion) {
for await (const chunk of result.completion) {
if (chunk.internalServerException || chunk.dependencyFailedException) {
return false; // session end failed
}
}
}
return true;
} catch {
return false;
}
}
// Tool that explicitly ends a session
server.tool(
"end_session",
{ session_id: z.string() },
async ({ session_id }) => {
const ended = await endSession(session_id);
return {
content: [{
type: "text",
text: ended
? `Session ${session_id} ended successfully.`
: `Failed to end session ${session_id}. It may have already expired.`,
}],
};
}
);
Sessions that are ended explicitly via endSession: true stop accruing costs for session storage on Bedrock's side. For short-lived MCP tool interactions where you don't expect follow-up turns, ending sessions explicitly is good hygiene. If you don't, Bedrock automatically expires idle sessions after 25 minutes of inactivity — but calling a closed session ID in a follow-up turn silently starts a fresh session rather than returning an error, so you lose conversation history without warning.
Monitor your Bedrock Inline Agent MCP tools with AliveMCP
AliveMCP monitors MCP server endpoints for uptime and latency. When inline agent streaming latency spikes — from long orchestration chains or throttled model calls — AliveMCP catches it and alerts you before it cascades into tool timeouts for your users.
Start free monitoring