Guide · Amazon Bedrock · Inline Agents

MCP Server Amazon Bedrock Inline Agents — InvokeInlineAgentCommand, dynamic instructions, ephemeral agents

Amazon Bedrock Inline Agents let MCP server tools spin up an AI agent on demand — with custom instructions, tools, and Knowledge Bases — without pre-creating anything in the Bedrock console. The API lives in @aws-sdk/client-bedrock-agent-runtime and exports InvokeInlineAgentCommand. Unlike the regular InvokeAgentCommand that requires a stable agentId and agentAliasId, inline agents define everything at invocation time: the foundation model to use, the system instruction that shapes the agent's behavior, optional action groups (tool schemas the agent can call), and optional Knowledge Base associations. This makes inline agents ideal for MCP server architectures where the agent's scope must be determined dynamically — for example, when a tool handler receives a user query and needs to spawn a task-specific sub-agent rather than routing all requests through a single pre-built agent. Three constraints are frequently overlooked: the response is an async iterable stream you must consume chunk by chunk (not a single resolved promise); the sessionId must be stable across turns to maintain conversation history; and inline agent sessions are billed per token like all Bedrock inference — there is no flat session fee, but multi-turn sessions accumulate input tokens from the full conversation history on each turn. For action groups see inline action groups; for Knowledge Base associations see inline KB associations; for streaming handling see inline agents streaming.

TL;DR

Import InvokeInlineAgentCommand from @aws-sdk/client-bedrock-agent-runtime. Pass sessionId, foundationModel, instruction (system prompt), and inputText (user message). Consume the completion async iterable and collect PayloadPart chunks into the agent's text response. No agentId or console setup required.

Inline agents vs pre-built agents: when to use each

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 Bases, then deploy an agent alias. Every invocation references that alias by ID. Inline agents (via InvokeInlineAgentCommand) skip the console step entirely — the caller passes all configuration per-request.

Use pre-built agents when the agent's configuration is stable across requests — for example, a customer support agent that always reads from the same Knowledge Base and always calls the same Lambda tools. Use inline agents when the configuration varies per-call:

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 the function execution and passes the result back.

Package and client setup

Inline agents use the same package as regular Bedrock Agents and Reranking — 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,
  InvokeInlineAgentCommandInput,
} from "@aws-sdk/client-bedrock-agent-runtime";

// Create once at module level
const agentRuntimeClient = new BedrockAgentRuntimeClient({
  region: process.env.AWS_REGION ?? "us-east-1",
});

// Supported foundation models for inline agents (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
// - anthropic.claude-3-sonnet-20240229-v1:0
// Use model IDs, NOT full ARNs (unlike reranking models)
const FOUNDATION_MODEL = process.env.BEDROCK_INLINE_AGENT_MODEL ?? "amazon.nova-lite-v1:0";

An important 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:... ARN. Passing an ARN here produces a ValidationException. Only the model IDs for models enabled in your Bedrock Model Access settings will work — if the model is not enabled, the API returns a ResourceNotFoundException.

Minimal inline agent invocation

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. The agent uses only the foundation model — no action groups or Knowledge Bases:

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import {
  BedrockAgentRuntimeClient,
  InvokeInlineAgentCommand,
} 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: "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);

  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 to investigate"),
    session_id: z.string().describe("Session ID for multi-turn conversation"),
    focus: z.string().optional().describe("Optional focus area for the research"),
  },
  async ({ topic, session_id, focus }) => {
    const instruction = focus
      ? `You are a research assistant specializing in ${focus}. Provide detailed, accurate information with specific examples. Always cite key concepts and explain trade-offs.`
      : "You are a thorough research assistant. Provide detailed, accurate information with specific examples and clear structure.";

    const response = await invokeInlineAgent(
      session_id,
      instruction,
      `Research the following topic in depth: ${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 and determines its persona, constraints, and behavior; inputText is the current user message; foundationModel is the model ID. The response's completion property is an async iterable — you must iterate it to get the response text. Each chunk has a chunk.bytes field (a Uint8Array) containing a fragment of the UTF-8 encoded response.

Session management for multi-turn conversations

The sessionId is the key to multi-turn conversations with an inline agent. 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:

import { randomUUID } from "node:crypto";

// In-memory session store — replace with Redis or DynamoDB in production
const activeSessions = new Map<string, { createdAt: number; instruction: string }>();
const SESSION_TTL_MS = 30 * 60 * 1000; // 30 minutes

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

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

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

server.tool(
  "chat_with_agent",
  {
    user_id: z.string().describe("Stable user identifier for session continuity"),
    message: z.string().describe("User's message to the agent"),
    agent_role: z.enum(["analyst", "writer", "coder"]).default("analyst"),
  },
  async ({ user_id, message, agent_role }) => {
    const instructions = {
      analyst: "You are a data analyst. Focus on quantitative insights, patterns, and evidence-based conclusions.",
      writer:  "You are a skilled technical writer. Prioritize clarity, conciseness, and well-structured prose.",
      coder:   "You are an expert software engineer. Provide working code examples with TypeScript. Explain design decisions.",
    };

    const sessionId = getOrCreateSession(user_id, instructions[agent_role]);

    const response = await invokeInlineAgent(
      sessionId,
      instructions[agent_role],
      message
    );

    return {
      content: [{
        type: "text",
        text: JSON.stringify({ sessionId, response }),
      }],
    };
  }
);

// End session explicitly when done
server.tool(
  "end_agent_session",
  { session_id: z.string() },
  async ({ session_id }) => {
    await agentRuntimeClient.send(new InvokeInlineAgentCommand({
      sessionId: session_id,
      foundationModel: FOUNDATION_MODEL,
      instruction: "", // instruction is required even for end-session calls
      inputText: "",
      endSession: true, // signals Bedrock to close the session
    }));

    return { content: [{ type: "text", text: "Session ended." }] };
  }
);

Three session management caveats: First, Bedrock enforces a session idle timeout — sessions without activity for 25 minutes are automatically closed server-side regardless of endSession. After that, using the same sessionId starts a fresh conversation with no history. Second, the instruction field is processed on the first turn and stored; subsequent turns in the same session use the stored instruction. If you pass a different instruction on a later turn, the behavior is undefined — treat the instruction as immutable for the session lifetime. Third, there is no server-side API to list active sessions — you must track sessions in your own store if you want to manage them explicitly.

Dynamic instruction generation

The main advantage of inline agents over pre-built agents is that the instruction can be computed at invocation time from request parameters, user context, or configuration. This pattern is very natural for MCP tool handlers:

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 as appropriate.");
  }

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

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

server.tool(
  "run_specialized_agent",
  {
    role: z.string().describe("Agent role description"),
    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 ~2,000 tokens) eat into the model's effective context window for the conversation. The practical limit is 4,000 characters for the instruction — above that, consider whether some constraints belong in the first user message rather than the system prompt.

Passing session state via inlineSessionState

The inlineSessionState parameter lets you inject structured data into the session that the agent can reference in its responses. This is useful for passing user context, configuration values, or return-of-control results (see inline action groups for the full return-of-control pattern):

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

interface UserContext {
  userId: string;
  plan: "free" | "pro" | "enterprise";
  serverCount: number;
  timezone: string;
}

async function invokeWithContext(
  sessionId: string,
  instruction: string,
  userMessage: string,
  userContext: UserContext
): Promise<string> {
  const sessionState: InlineSessionState = {
    sessionAttributes: {
      // Key-value pairs injected as context into the agent's prompt
      userId: userContext.userId,
      plan: userContext.plan,
      serverCount: String(userContext.serverCount),
      timezone: userContext.timezone,
    },
    promptSessionAttributes: {
      // Injected into the prompt template directly (if using prompt override)
      currentDate: new Date().toISOString().split("T")[0],
    },
  };

  const command = new InvokeInlineAgentCommand({
    sessionId,
    foundationModel: FOUNDATION_MODEL,
    instruction: instruction + "\n\nUser context is available in session attributes.",
    inputText: userMessage,
    inlineSessionState: sessionState,
    endSession: false,
    enableTrace: false,
  });

  const response = await agentRuntimeClient.send(command);
  let text = "";
  for await (const chunk of response.completion) {
    if (chunk.chunk?.bytes) text += new TextDecoder().decode(chunk.chunk.bytes);
  }
  return text;
}

server.tool(
  "agent_with_context",
  {
    session_id: z.string(),
    query: z.string(),
    user_id: z.string(),
    plan: z.enum(["free", "pro", "enterprise"]),
    server_count: z.number().int().min(0),
    timezone: z.string().default("UTC"),
  },
  async ({ session_id, query, user_id, plan, server_count, timezone }) => {
    const instruction =
      "You are a helpful assistant for AliveMCP users. Help them manage their MCP server monitoring. " +
      "Tailor advice to the user's plan and server count.";

    const text = await invokeWithContext(session_id, instruction, query, {
      userId: user_id,
      plan,
      serverCount: server_count,
      timezone,
    });

    return { content: [{ type: "text", text }] };
  }
);

sessionAttributes are string-to-string key-value pairs passed to the agent as part of the prompt context. They are available to the agent but not included literally in the user message. promptSessionAttributes are injected directly into prompt templates when using prompt override configurations. For most inline agent use cases without Lambda-backed prompts, sessionAttributes is the right field.

Enabling orchestration trace

Setting enableTrace: true causes the agent to emit TracePart chunks alongside the response text. These trace events reveal the agent's orchestration steps — which tools it considered calling, what intermediate reasoning it performed, and which Knowledge Base retrievals it made. Traces are essential for debugging unexpected agent behavior in development:

async function invokeWithTrace(
  sessionId: string,
  instruction: string,
  inputText: string
): Promise<{ response: string; traceEvents: string[] }> {
  const command = new InvokeInlineAgentCommand({
    sessionId,
    foundationModel: FOUNDATION_MODEL,
    instruction,
    inputText,
    enableTrace: true,  // emit TracePart chunks
  });

  const result = await agentRuntimeClient.send(command);
  let response = "";
  const traceEvents: string[] = [];

  for await (const chunk of result.completion) {
    if (chunk.chunk?.bytes) {
      // PayloadPart — actual response text
      response += new TextDecoder().decode(chunk.chunk.bytes);
    } else if (chunk.trace) {
      // TracePart — orchestration trace event
      const traceStr = JSON.stringify(chunk.trace, null, 2);
      traceEvents.push(traceStr);
    }
  }

  return { response, traceEvents };
}

// Development-only tool that exposes trace events
server.tool(
  "debug_agent",
  {
    session_id: z.string(),
    instruction: z.string(),
    query: z.string(),
  },
  async ({ session_id, instruction, query }) => {
    const { response, traceEvents } = await invokeWithTrace(
      session_id,
      instruction,
      query
    );

    return {
      content: [{
        type: "text",
        text: JSON.stringify({
          response,
          traceEventCount: traceEvents.length,
          traces: traceEvents,
        }, null, 2),
      }],
    };
  }
);

In production, disable trace (enableTrace: false) to reduce response latency and avoid emitting internal agent reasoning to callers. Use it only in staging environments or when debugging a specific agent behavior. The trace chunks are interleaved with PayloadPart chunks in the stream — your consumer code must distinguish between chunk.chunk?.bytes (response text) and chunk.trace (trace data).

IAM permissions for inline agents

Inline agent invocations require a distinct IAM action from regular Bedrock model 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",
        "arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-3-haiku-20240307-v1:0"
      ]
    }
  ]
}

bedrock:InvokeInlineAgent is an Agents-specific IAM action — it is separate from bedrock:InvokeAgent (pre-built agents) and bedrock:InvokeModel (Converse API). If you also attach Knowledge Bases to inline agents, add bedrock:Retrieve and bedrock:RetrieveAndGenerate for the specific Knowledge Base ARNs. The model ARNs for inline agents use the same double-colon format as reranking: arn:aws:bedrock:REGION::foundation-model/MODEL_ID.

Trust policy for Lambda execution role

If your MCP server runs in Lambda, the execution role needs the trust relationship for Lambda and the above inline agent permissions. If it runs in ECS/Fargate, attach the policy to the task role instead:

# For ECS task role
aws iam create-policy \
  --policy-name AliveMCPInlineAgentPolicy \
  --policy-document file://inline-agent-policy.json

aws iam attach-role-policy \
  --role-name alivemcp-ecs-task-role \
  --policy-arn arn:aws:iam::123456789012:policy/AliveMCPInlineAgentPolicy

Error handling patterns

Inline agent invocations can fail with several exception types. The critical one is DependencyFailedException, which wraps failures from the underlying foundation model call and from Knowledge Base retrievals:

import {
  DependencyFailedException,
  ThrottlingException,
  ValidationException,
  ServiceQuotaExceededException,
} from "@aws-sdk/client-bedrock-agent-runtime";

async function invokeInlineAgentSafe(
  sessionId: string,
  instruction: string,
  inputText: string,
  maxRetries = 2
): Promise<string> {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      const command = new InvokeInlineAgentCommand({
        sessionId,
        foundationModel: FOUNDATION_MODEL,
        instruction,
        inputText,
        enableTrace: false,
      });

      const result = await agentRuntimeClient.send(command);
      let text = "";

      for await (const chunk of result.completion) {
        if (chunk.chunk?.bytes) {
          text += new TextDecoder().decode(chunk.chunk.bytes);
        }
        // Stream-level errors arrive as typed chunks too
        if (chunk.internalServerException) {
          throw new Error(`Agent stream error: ${chunk.internalServerException.message}`);
        }
        if (chunk.dependencyFailedException) {
          throw new DependencyFailedException({
            message: chunk.dependencyFailedException.message ?? "Dependency failed",
            $metadata: {},
          });
        }
      }

      return text;
    } catch (err) {
      if (err instanceof ThrottlingException && attempt < maxRetries) {
        await new Promise((r) => setTimeout(r, 1000 * Math.pow(2, attempt)));
        continue;
      }
      if (err instanceof ServiceQuotaExceededException) {
        return "Agent service quota exceeded. Please try again later.";
      }
      if (err instanceof ValidationException) {
        // Log but don't retry — validation errors are deterministic
        console.error("Inline agent ValidationException:", err.message);
        return "Agent configuration error. Please check the session parameters.";
      }
      throw err;
    }
  }
  return "";
}

An important subtlety: errors can arrive both as thrown exceptions (before the stream starts) and as typed chunks within the completion stream. internalServerException and dependencyFailedException are stream-level errors that arrive as chunks after some successful chunks, so you must check for them inside the for await loop — not just in the outer try/catch. For comprehensive stream handling including ReturnControlPayload for action group execution see streaming response handling.

Concurrency and rate limits

Each InvokeInlineAgentCommand call that enables trace or uses action groups runs multiple underlying foundation model calls (one per orchestration step). A single user-visible agent turn can consume 3–10 underlying model invocations depending on how many tools the agent considers calling. This amplification means that inline agents consume Bedrock model TPS (transactions per second) faster than direct ConverseCommand calls at the same user-request rate.

import PQueue from "p-queue";

// Limit concurrent inline agent sessions to avoid Bedrock TPS throttling
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(
      () => invokeInlineAgentSafe(session_id, instruction, query)
    );
    return { content: [{ type: "text", text: response ?? "" }] };
  }
);

The p-queue pattern caps concurrent in-flight agent requests. 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.

Monitor your Bedrock Inline Agent MCP tools with AliveMCP

AliveMCP monitors MCP server endpoints for uptime, latency spikes, and error rates. When a Bedrock Inline Agent tool handler starts returning DependencyFailedExceptions or elevated latency from multi-step orchestration, AliveMCP alerts you before it impacts downstream agents.

Start free monitoring