Guide · Amazon Bedrock · Inline Agents · Action Groups
MCP Server Bedrock Inline Agents — Action Groups, Function Schemas, Return-of-Control
Bedrock Inline Agent action groups let you define the tools an agent can call at invocation time, with no Lambda function or console setup required. Instead of routing tool calls through Lambda (as pre-built Bedrock Agents do), inline action groups use the return-of-control pattern: 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 InvokeInlineAgentCommand call with inlineSessionState.returnControlInvocationResults populated. The agent then continues its orchestration with the tool result in context. This pattern is natural for MCP servers because the tool execution logic already exists in the server — there is no need to duplicate it in a Lambda function. Four things catch MCP server authors off-guard: the action group's actionGroupExecutor must be set to { customControl: "RETURN_CONTROL" } (not a Lambda ARN) for inline return-of-control; the stream iteration loop must check for ReturnControlPayload chunks and break out early to process the tool call before resuming; the follow-up invocation must use the same sessionId and the same actionGroups definition; and the invocationId from ReturnControlPayload must be echoed back in the result object. For the base inline agent setup see inline agents overview; for Knowledge Base associations see inline KB associations; for complete stream handling see inline agents streaming.
TL;DR
Add an actionGroups array to InvokeInlineAgentCommand. Each entry has a name, description, and actionGroupExecutor: { customControl: "RETURN_CONTROL" }. Define functions via functionSchema.functions[]. When the stream yields a ReturnControlPayload chunk, run the named function locally and resume by calling InvokeInlineAgentCommand again with inlineSessionState.returnControlInvocationResults containing the result.
How inline action groups differ from pre-built agent action groups
Pre-built Bedrock Agents support two executor types for action groups: a Lambda ARN (Bedrock calls your Lambda function directly when the agent uses the tool) and return-of-control (Bedrock hands the tool call back to the caller). Inline agents only support return-of-control — you cannot specify a Lambda ARN in an inline action group's executor. This is not a limitation in practice for MCP servers because the MCP server process is already the right place to execute tool logic.
The return-of-control flow for an inline agent with action groups:
- Your MCP tool handler sends
InvokeInlineAgentCommandwithactionGroupsdefined. - The agent reads the user message, decides to call one of your defined functions, and emits a
ReturnControlPayloadchunk in the stream. - Your code receives the payload, extracts the function name and arguments, executes the function locally.
- Your code sends a follow-up
InvokeInlineAgentCommandon the same session withinlineSessionState.returnControlInvocationResultscontaining the function result. - The agent incorporates the result and either calls another tool (steps 2–4 repeat) or generates its final response (you receive
PayloadPartchunks).
Defining action groups in the invocation
Action groups are passed in the actionGroups array of InvokeInlineAgentCommand. Each action group has a name, description, and a functionSchema listing the functions the agent can call:
import {
BedrockAgentRuntimeClient,
InvokeInlineAgentCommand,
AgentActionGroup,
FunctionSchema,
} from "@aws-sdk/client-bedrock-agent-runtime";
const agentRuntimeClient = new BedrockAgentRuntimeClient({ region: "us-east-1" });
// Define the action group with function schemas
const monitoringActionGroup: AgentActionGroup = {
actionGroupName: "monitoring_tools",
description: "Tools for checking MCP server status and retrieving monitoring data.",
actionGroupExecutor: {
customControl: "RETURN_CONTROL", // Required 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 name of the MCP server to check.",
required: true,
},
},
},
{
name: "list_recent_alerts",
description: "Returns the most recent downtime alerts for a server.",
parameters: {
server_name: {
type: "string",
description: "The MCP server name.",
required: true,
},
limit: {
type: "integer",
description: "Maximum number of alerts to return. Defaults to 5.",
required: false,
},
},
},
{
name: "get_uptime_percentage",
description: "Returns the 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 to calculate uptime for. Defaults to 30.",
required: false,
},
},
},
],
},
};
The parameters field is a record where each key is a parameter name and each value has type, description, and required. Supported parameter types: "string", "integer", "number", "boolean", "array". There is no nested object type — flatten complex parameters into individual primitives or encode them as strings. The agent uses description fields on both the action group and each function to decide when to call which tool, so write descriptions from the agent's perspective: what does this function return, when should the agent call it.
Full return-of-control invocation loop
Handling return-of-control requires a loop that alternates between streaming the agent response and executing tool calls locally. The loop continues until the agent emits a final text response with no pending tool calls:
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import {
BedrockAgentRuntimeClient,
InvokeInlineAgentCommand,
AgentActionGroup,
InlineSessionState,
ReturnControlPayload,
} from "@aws-sdk/client-bedrock-agent-runtime";
const agentRuntimeClient = new BedrockAgentRuntimeClient({ region: "us-east-1" });
const FOUNDATION_MODEL = "amazon.nova-lite-v1:0";
const server = new McpServer({ name: "monitoring-agent-server", version: "1.0.0" });
// Local implementations of the agent's tools
async function getServerStatus(serverName: string): Promise<string> {
// Replace with real monitoring data lookup
return JSON.stringify({ server: serverName, status: "up", latencyMs: 42 });
}
async function listRecentAlerts(serverName: string, limit = 5): Promise<string> {
return JSON.stringify({ server: serverName, alerts: [], message: "No recent alerts" });
}
async function getUptimePercentage(serverName: string, days = 30): Promise<string> {
return JSON.stringify({ server: serverName, uptimePct: 99.8, days });
}
// Execute a tool call from ReturnControlPayload
async function executeToolCall(
functionName: string,
parameters: Record<string, { type: string; value: string }>
): Promise<string> {
const args = Object.fromEntries(
Object.entries(parameters).map(([k, v]) => [k, v.value])
);
switch (functionName) {
case "get_server_status":
return getServerStatus(args.server_name);
case "list_recent_alerts":
return listRecentAlerts(args.server_name, args.limit ? parseInt(args.limit) : 5);
case "get_uptime_percentage":
return getUptimePercentage(args.server_name, args.days ? parseInt(args.days) : 30);
default:
return JSON.stringify({ error: `Unknown function: ${functionName}` });
}
}
// 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 no tool call, the agent has finished — return the response
if (!returnControl) {
return responseText;
}
// Execute the requested tool call(s)
const invocationResults = [];
for (const input of returnControl.invocationInputs ?? []) {
if (input.functionInvocationInput) {
const fnInput = input.functionInvocationInput;
const functionName = fnInput.function ?? "";
const parameters = fnInput.parameters
? Object.fromEntries(fnInput.parameters.map((p) => [p.name!, { type: p.type!, value: p.value! }]))
: {};
const toolResult = await executeToolCall(functionName, parameters);
invocationResults.push({
functionResult: {
actionGroup: fnInput.actionGroup ?? "",
function: functionName,
responseBody: {
TEXT: { body: toolResult },
},
},
});
}
}
// Prepare session state with tool results for the follow-up invocation
sessionState = {
returnControlInvocationResults: invocationResults,
invocationId: returnControl.invocationId,
};
// On follow-up turns after return-of-control, inputText must be empty string
inputText = "";
}
return "Agent reached maximum tool call iterations without producing a final response.";
}
server.tool(
"agent_monitoring_query",
{
session_id: z.string(),
query: z.string().describe("Natural language query about MCP server monitoring"),
},
async ({ session_id, query }) => {
const instruction =
"You are a monitoring assistant for MCP servers. Use the provided tools to fetch " +
"real-time status and alert data, then give a clear, concise summary to the user. " +
"Always use tools when asked about specific servers rather than guessing.";
const response = await runAgentWithTools(
session_id,
instruction,
query,
[monitoringActionGroup]
);
return { content: [{ type: "text", text: response }] };
}
);
The key insight in this loop: after a tool call, the follow-up InvokeInlineAgentCommand must set inputText to an empty string (""). 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. Also note that invocationId must be set on the sessionState in the follow-up — it correlates the tool result with the specific tool-call request the agent issued.
Multiple action groups
An inline agent invocation can include multiple action groups, each with different functions. The agent selects among all available functions when deciding how to respond. Organize action groups by functional domain to help the agent understand which tools are related:
const dataActionGroup: AgentActionGroup = {
actionGroupName: "data_tools",
description: "Tools for fetching and aggregating monitoring metrics.",
actionGroupExecutor: { customControl: "RETURN_CONTROL" },
functionSchema: {
functions: [
{
name: "get_latency_histogram",
description: "Returns a latency distribution histogram for a server over the past N hours.",
parameters: {
server_name: { type: "string", description: "Server name.", required: true },
hours: { type: "integer", description: "Hours to look back. Default 24.", required: false },
},
},
{
name: "compare_servers",
description: "Returns side-by-side uptime and latency comparison for two servers.",
parameters: {
server_a: { type: "string", description: "First server name.", required: true },
server_b: { type: "string", description: "Second server name.", required: true },
},
},
],
},
};
const notificationActionGroup: AgentActionGroup = {
actionGroupName: "notification_tools",
description: "Tools for managing alert notification settings.",
actionGroupExecutor: { customControl: "RETURN_CONTROL" },
functionSchema: {
functions: [
{
name: "set_alert_threshold",
description: "Updates the downtime alert threshold for a server in seconds.",
parameters: {
server_name: { type: "string", description: "Server name.", required: true },
threshold_seconds: { type: "integer", description: "Threshold in seconds.", required: true },
},
},
],
},
};
// Pass all action groups in a single invocation
const response = await runAgentWithTools(
sessionId,
instruction,
userQuery,
[monitoringActionGroup, dataActionGroup, notificationActionGroup]
);
There is no hard-coded limit on the number of action groups, but the total number of functions across all groups feeds into the model's context window as a tool schema. Very large schemas (20+ functions across multiple groups) can reduce reasoning quality because the model must attend to a large function list while generating its response. If you find the agent making incorrect tool choices with many functions, reduce the set to only the functions relevant to the current task — inline agents make this easy because you define them per-call.
Handling multi-step tool sequences
Agents frequently need to call multiple tools in sequence before producing a final answer — for example, checking server status, then fetching recent alerts for any server that is down, then summarizing the findings. The return-of-control loop handles this automatically as long as you correctly echo back the invocationId and pass the results on each follow-up turn:
// Detailed logging helper for debugging multi-step sequences
async function runAgentWithToolsDebug(
sessionId: string,
instruction: string,
initialInput: string,
actionGroups: AgentActionGroup[]
): Promise<{ response: string; toolCallLog: Array<{ fn: string; args: unknown; result: string }> }> {
let inputText = initialInput;
let sessionState: InlineSessionState | undefined;
const toolCallLog: Array<{ fn: string; args: unknown; result: string }> = [];
for (let i = 0; i < 10; i++) {
const result = await agentRuntimeClient.send(
new InvokeInlineAgentCommand({
sessionId,
foundationModel: FOUNDATION_MODEL,
instruction,
inputText,
actionGroups,
inlineSessionState: sessionState,
enableTrace: false,
})
);
let text = "";
let returnControl: ReturnControlPayload | undefined;
for await (const chunk of result.completion) {
if (chunk.chunk?.bytes) text += new TextDecoder().decode(chunk.chunk.bytes);
if (chunk.returnControl) { returnControl = chunk.returnControl; break; }
}
if (!returnControl) return { response: text, toolCallLog };
const invocationResults = [];
for (const input of returnControl.invocationInputs ?? []) {
const fi = input.functionInvocationInput;
if (!fi) continue;
const params = Object.fromEntries(
(fi.parameters ?? []).map((p) => [p.name!, { type: p.type!, value: p.value! }])
);
const plainArgs = Object.fromEntries(
Object.entries(params).map(([k, v]) => [k, v.value])
);
const toolResult = await executeToolCall(fi.function!, params);
toolCallLog.push({ fn: fi.function!, args: plainArgs, result: toolResult });
invocationResults.push({
functionResult: {
actionGroup: fi.actionGroup ?? "",
function: fi.function!,
responseBody: { TEXT: { body: toolResult } },
},
});
}
sessionState = {
returnControlInvocationResults: invocationResults,
invocationId: returnControl.invocationId,
};
inputText = "";
}
return { response: "Max iterations reached.", toolCallLog };
}
The toolCallLog array makes it easy to audit which tools the agent called and in what order — useful during development to verify the agent is using the right tools for different query patterns. In production, you can omit the log and use the simpler runAgentWithTools from the previous section.
Parameter type handling
All parameter values in ReturnControlPayload arrive as strings regardless of the declared type. If you declared a parameter as type: "integer", the value still arrives as the string "5", not the number 5. Parse numeric and boolean parameters explicitly in your tool execution code:
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;
}
// In executeToolCall, use parseToolParameters instead of manual extraction:
const args = parseToolParameters(fnInput.parameters ?? []);
const serverName = args.server_name as string;
const limit = (args.limit as number) ?? 5;
const days = (args.days as number) ?? 30;
Missing required parameters — the agent should always provide them, but if the model hallucinates a tool call without a required parameter, the value will be undefined. Add a guard before calling the actual tool function: if a required parameter is missing, return an error body to the agent explaining what was missing rather than letting the TypeScript error bubble up. The agent will usually correct itself on the next turn when it sees the error response.
Tool result response body format
The responseBody in functionResult must include at least a TEXT entry with a body string. The agent reads this string as the tool result. For structured data, serialize it as JSON — the agent can parse JSON in its next reasoning step. For errors, return a JSON error object rather than throwing an exception:
// Good: JSON-serialized result the agent can reason about
invocationResults.push({
functionResult: {
actionGroup: fi.actionGroup!,
function: fi.function!,
responseBody: {
TEXT: {
body: JSON.stringify({
success: true,
server: "my-mcp-server",
statusCode: 200,
latencyMs: 42,
}),
},
},
},
});
// Error case — still use TEXT body, not a thrown exception
invocationResults.push({
functionResult: {
actionGroup: fi.actionGroup!,
function: fi.function!,
responseBody: {
TEXT: {
body: JSON.stringify({
success: false,
error: "Server not found in monitoring system",
serverName: fi.parameters?.find((p) => p.name === "server_name")?.value,
}),
},
},
},
});
Returning an informative error body is preferable to letting an exception propagate because it keeps the agent loop running. The agent will read the error body, understand what went wrong, and may try a different approach — for example, listing available servers before retrying with a valid name. If you throw an exception instead, the entire runAgentWithTools call fails and the user gets no response at all.
Disabling an action group
Inline agents support setting parentActionGroupSignature to disable built-in agent capabilities per invocation. The most useful: disabling the agent's default AMAZON.UserInput capability (which allows the agent to ask clarifying questions) forces it to always use the available tools to gather information rather than stopping to ask the user:
// Disable AMAZON.UserInput to prevent agent from asking clarifying questions
const userInputDisableGroup: AgentActionGroup = {
actionGroupName: "UserInputActionGroup",
parentActionGroupSignature: "AMAZON.UserInput",
actionGroupState: "DISABLED",
};
const commandWithDisabledUserInput = new InvokeInlineAgentCommand({
sessionId,
foundationModel: FOUNDATION_MODEL,
instruction,
inputText,
actionGroups: [
monitoringActionGroup,
userInputDisableGroup, // must be included to override default
],
});
By default, Bedrock Agents can emit a clarifying question to the user mid-orchestration. For MCP server use cases where the calling LLM client expects a tool response (not another question), disabling AMAZON.UserInput ensures the agent always produces a final answer. If the agent genuinely cannot complete the task without more information, it will say so in its final response rather than generating a stream-breaking clarification request.
Monitor your Bedrock Inline Agent MCP tools with AliveMCP
AliveMCP monitors MCP server endpoints for uptime and latency. When a return-of-control loop starts timing out or the agent stops producing final responses, AliveMCP catches the latency spike and alerts you before it impacts downstream agents.
Start free monitoring