Guide · Amazon Bedrock Agents · Return Control Pattern
Bedrock Agents Return Control for MCP Servers — Tool Call Routing, ReturnControlPayload, and Result Submission
Bedrock Agents' RETURN_CONTROL executor mode stops agent orchestration mid-flight and passes tool call details back to the calling application, which executes the tool and re-submits the result. This is the inverse of a Lambda action group: instead of Bedrock invoking your Lambda, your application receives the tool call parameters and executes them in-process. For MCP server developers, return control is the natural bridge between Bedrock Agents and an MCP tool router — the agent decides what tool to call, Bedrock packages the tool invocation and sends it to your server, your MCP server executes it via the appropriate MCP tool, and the result flows back to continue the agent's reasoning chain.
TL;DR
Create an action group with actionGroupExecutor: { customControl: 'RETURN_CONTROL' } and define the tool schemas in functionSchema.functions. When the agent decides to call a tool, InvokeAgentCommand returns a returnControl event with invocationId and invocationInputs (a list of tool calls). Execute each tool call in your application, then re-invoke with the same sessionId, passing sessionState.invocationId and sessionState.returnControlInvocationResults containing the results. The agent continues orchestration with the tool results injected. Critical: all tool calls in a single invocationInputs batch must be submitted together in one re-invocation — do not submit partial results.
Why RETURN_CONTROL instead of Lambda action groups
Lambda action groups are the standard Bedrock Agents tool execution model: the agent calls a Lambda function, the function runs, and the result is returned. This works well for tools with fixed implementations that do not depend on application-side state.
Return control is preferable when:
- Tools require application-side state: Database connections, authenticated HTTP sessions, in-memory caches, or user context that is expensive to reconstruct inside Lambda cold starts.
- Tool routing is dynamic: An MCP server that discovers available tools at runtime (from connected MCP servers) cannot statically define Lambda handlers for each tool. With return control, the application decides how to route each tool call at execution time.
- Latency matters for the first call: Lambda cold starts add 100–1,000ms to the first tool invocation. With return control, the execution happens in your already-running application server.
- Tool definitions change frequently: Adding a new MCP server means new tools are available. With Lambda action groups, adding tools requires updating the action group schema and re-preparing the agent. With return control, you update only the action group schema (which still requires re-preparation), but the execution routing is handled in your application without Lambda deployment changes.
Return control adds application-side complexity: your server must handle the returnControl event, dispatch the tool call, and manage the re-invocation lifecycle. For simple, stateless tools, Lambda action groups are easier to operate. Use return control when the tool execution genuinely belongs in your application.
Configuring a RETURN_CONTROL action group
Create the action group with customControl: 'RETURN_CONTROL' in the executor. Define tool schemas using the function-based format — each function in functionSchema.functions becomes a tool the agent can invoke via return control.
import {
BedrockAgentClient,
CreateAgentActionGroupCommand
} from "@aws-sdk/client-bedrock-agent";
const client = new BedrockAgentClient({ region: "us-east-1" });
await client.send(new CreateAgentActionGroupCommand({
agentId: "YOURAGENTID",
agentVersion: "DRAFT",
actionGroupName: "MCPTools",
description: "Tools provided by connected MCP servers",
actionGroupExecutor: {
customControl: "RETURN_CONTROL" // No Lambda; execution returns to caller
},
functionSchema: {
functions: [
{
name: "readFile",
description: "Read the contents of a file at the given path",
parameters: {
path: {
type: "string",
description: "Absolute or relative path to the file",
required: true
},
encoding: {
type: "string",
description: "File encoding: utf8, base64, or hex",
required: false
}
}
},
{
name: "runQuery",
description: "Execute a read-only SQL query and return results as JSON",
parameters: {
sql: {
type: "string",
description: "SQL SELECT statement to execute",
required: true
},
database: {
type: "string",
description: "Database name to query against",
required: true
}
}
},
{
name: "searchWeb",
description: "Search the web for recent information on a topic",
parameters: {
query: {
type: "string",
description: "Search query string",
required: true
},
maxResults: {
type: "integer",
description: "Maximum number of results to return (1-10)",
required: false
}
}
}
]
}
}));
// Re-prepare the agent after adding the action group
await client.send(new PrepareAgentCommand({
agentId: "YOURAGENTID"
}));
Handling the ReturnControlPayload in the response stream
When the agent decides to call a return-control tool, the InvokeAgentCommand response stream emits a returnControl event instead of a chunk event. The returnControl event carries the invocationId and a list of invocationInputs.
import {
BedrockAgentRuntimeClient,
InvokeAgentCommand
} from "@aws-sdk/client-bedrock-agent-runtime";
const runtime = new BedrockAgentRuntimeClient({ region: "us-east-1" });
async function invokeAgent(sessionId: string, inputText: string): Promise<string> {
const response = await runtime.send(new InvokeAgentCommand({
agentId: process.env.BEDROCK_AGENT_ID!,
agentAliasId: process.env.BEDROCK_AGENT_ALIAS_ID!,
sessionId,
inputText
}));
let finalAnswer = "";
let returnControlEvent: any = null;
for await (const event of response.completion) {
if (event.chunk?.bytes) {
// Normal text chunk — accumulate the answer
finalAnswer += new TextDecoder().decode(event.chunk.bytes);
} else if (event.returnControl) {
// Agent wants to call a tool — capture the return control payload
returnControlEvent = event.returnControl;
break; // Stop consuming the stream; we need to execute tools first
}
}
if (returnControlEvent) {
// Execute the tools and re-invoke the agent with results
return await handleReturnControl(sessionId, returnControlEvent);
}
return finalAnswer;
}
The returnControl event structure:
// Shape of event.returnControl
{
invocationId: "inv-abc123def456", // Must be echoed back in re-invocation
invocationInputs: [
{
functionInvocationInput: {
actionGroup: "MCPTools",
function: "runQuery",
parameters: [
{ name: "sql", type: "string", value: "SELECT * FROM orders LIMIT 5" },
{ name: "database", type: "string", value: "ecommerce" }
]
}
}
// Multiple entries here when the agent calls tools in parallel
]
}
Executing tools and submitting results
Execute each tool call in invocationInputs and collect results, then re-invoke the agent in a single call with all results bundled together. The re-invocation uses the same sessionId and sets sessionState.invocationId and sessionState.returnControlInvocationResults.
async function handleReturnControl(sessionId: string, returnControl: any): Promise<string> {
const { invocationId, invocationInputs } = returnControl;
// Execute all tool calls (possibly in parallel)
const results = await Promise.all(
invocationInputs.map(async (input: any) => {
const { actionGroup, function: fnName, parameters } = input.functionInvocationInput;
// Convert Bedrock's [{name, type, value}] format to plain object
const args = Object.fromEntries(
(parameters || []).map((p: any) => [p.name, p.value])
);
// Route to MCP server or local tool
const toolResult = await executeTool(fnName, args);
return {
functionResult: {
actionGroup,
function: fnName,
responseBody: {
TEXT: { body: typeof toolResult === "string" ? toolResult : JSON.stringify(toolResult) }
}
}
};
})
);
// Re-invoke the agent with all tool results
const response = await runtime.send(new InvokeAgentCommand({
agentId: process.env.BEDROCK_AGENT_ID!,
agentAliasId: process.env.BEDROCK_AGENT_ALIAS_ID!,
sessionId,
inputText: "", // Empty — continuation is driven by tool results
sessionState: {
invocationId, // Echo the same invocationId from the returnControl event
returnControlInvocationResults: results
}
}));
// Consume the new response — may trigger additional tool calls
let answer = "";
let nextReturnControl: any = null;
for await (const event of response.completion) {
if (event.chunk?.bytes) {
answer += new TextDecoder().decode(event.chunk.bytes);
} else if (event.returnControl) {
nextReturnControl = event.returnControl;
break;
}
}
// Handle chained tool calls recursively (agent may call tools multiple times)
if (nextReturnControl) {
return await handleReturnControl(sessionId, nextReturnControl);
}
return answer;
}
Chained tool calls are common — the agent may call a tool, receive results, decide it needs another tool call based on those results, and emit another returnControl event. The recursive pattern above handles this naturally. Set a maximum recursion depth (e.g., 10 tool call rounds) to prevent infinite loops in case of a buggy agent instruction.
Routing tool calls to MCP servers
The executeTool function in the pattern above is where the MCP routing logic lives. For a Bedrock Agent fronting multiple MCP servers, maintain a registry that maps tool names to their source MCP server:
// Tool registry: maps Bedrock tool name → MCP server + tool name
const toolRegistry: Record<string, { server: MCPClient; mcpToolName: string }> = {};
// Populate registry from connected MCP servers at startup
async function buildToolRegistry(mcpServers: MCPClient[]) {
for (const server of mcpServers) {
const { tools } = await server.listTools();
for (const tool of tools) {
// Namespace tool names by server to avoid collisions
const bedrockToolName = `${server.name}_${tool.name}`;
toolRegistry[bedrockToolName] = { server, mcpToolName: tool.name };
}
}
}
async function executeTool(functionName: string, args: Record<string, any>): Promise<string> {
const registration = toolRegistry[functionName];
if (!registration) {
return JSON.stringify({ error: `Unknown tool: ${functionName}` });
}
const { server, mcpToolName } = registration;
const result = await server.callTool(mcpToolName, args);
// Convert MCP content array to string for Bedrock's TEXT response format
return result.content
.filter((c: any) => c.type === "text")
.map((c: any) => c.text)
.join("\n");
}
When the MCP server's tool list changes (new server connected, server disconnected), rebuild the tool registry and update the Bedrock Agent's action group schema to match. This requires calling UpdateAgentActionGroupCommand with the new functionSchema.functions and re-preparing the agent. The return control pattern makes the execution-side update invisible to Bedrock — only the schema declaration needs updating.
Parallel tool calls and batching behavior
When the foundation model decides to call multiple tools simultaneously (a common pattern in Claude 3.5 Sonnet and Opus), invocationInputs contains multiple entries. The critical rule: all results in a batch must be submitted together in a single re-invocation. Submitting a partial set of results (some tools executed, others not) will cause Bedrock to return an error.
// WRONG: submitting results for each tool call separately
for (const input of invocationInputs) {
const result = await executeTool(input.functionInvocationInput.function, ...);
// This will fail — partial results not accepted
await runtime.send(new InvokeAgentCommand({
sessionState: { invocationId, returnControlInvocationResults: [result] }
}));
}
// CORRECT: execute all tools, then submit all results together
const allResults = await Promise.all(
invocationInputs.map(input => executeToolCall(input))
);
await runtime.send(new InvokeAgentCommand({
sessionState: { invocationId, returnControlInvocationResults: allResults }
}));
If one tool call in a batch fails (e.g., the MCP server returns an error), still submit a result for it — use the error message as the body in the response. The agent will incorporate the error into its reasoning and can decide to retry, ask for clarification, or continue with partial results. Never silently omit a failed tool call result from the batch.
Comparison: RETURN_CONTROL vs Lambda action groups
| Attribute | RETURN_CONTROL | Lambda action group |
|---|---|---|
| Tool execution location | Calling application | AWS Lambda function |
| Cold-start latency | None (in-process) | 100–1,000ms on cold start |
| Application-side state access | Yes — same process context | No — Lambda is stateless (can use ElastiCache/RDS) |
| Dynamic tool routing | Yes — routing logic is in-application | No — Lambda handler is static |
| Schema update requires re-preparation? | Yes | Yes |
| Works when application is offline | No — Bedrock waits for caller re-invocation | Yes — Lambda is independently available |
| Parallel tool call handling | Caller is responsible for executing all and re-submitting | Bedrock handles multiple Lambda invocations |
| Best for | MCP server proxies, authenticated sessions, dynamic tool registries | Stateless tools, event-driven architectures, background tasks |
Timeout and session management
When a returnControl event is emitted, Bedrock pauses the agent's orchestration and waits for the calling application to re-invoke with results. If the application does not re-invoke within the session's idle TTL (idleSessionTTLInSeconds), the session expires and the return control state is lost. The next invocation on that sessionId starts a new orchestration turn — the pending tool call is abandoned.
Design your tool execution to complete within the session TTL. For long-running tools (database queries that may take minutes, file operations on large files), set a generous idleSessionTTLInSeconds on the agent (up to 3,600 seconds / 1 hour). Alternatively, implement tool call timeouts in your application and return a "tool timed out after X seconds" error result if the tool does not complete in time — this keeps the session alive and lets the agent decide how to proceed.