Guide · Amazon Bedrock Flows

MCP Server Bedrock Flows — CreateFlow, PrepareFlow, InvokeFlow, flow aliases

Amazon Bedrock Flows lets you define multi-step AI pipelines as directed graphs and invoke them from an MCP server tool with a single API call. Instead of writing orchestration logic in your MCP server — calling the model, checking conditions, looping over results, calling Lambda, re-prompting — you define the entire workflow as a Bedrock Flow once and invoke it from MCP with InvokeFlowCommand. The flow handles conditional branching, fan-out/fan-in iteration, Knowledge Base retrieval, and prompt chaining. This guide covers the five things that matter in production: the two-SDK split between management and runtime, the CreateFlow + PrepareFlow lifecycle (a flow cannot be invoked until prepared), the streaming response format from InvokeFlowCommand, flow versioning and aliases (the DRAFT alias is not safe for production), and the IAM execution role the flow uses to call your Lambda, models, and Knowledge Bases.

TL;DR

Use @aws-sdk/client-bedrock-agent for management (CreateFlow, PrepareFlow, CreateFlowAlias) and @aws-sdk/client-bedrock-agent-runtime for invocation (InvokeFlowCommand). Every flow must be prepared before it can be invoked — PrepareFlowCommand validates the graph and creates a runnable snapshot. The DRAFT alias always points to the last prepared state; create versioned aliases for production. InvokeFlowCommand returns a streaming response — drain it and collect flowOutputEvent events to get the result. Pass input data as inputs[0].content.document (not a raw string — it must be wrapped in the document envelope).

When to use Bedrock Flows in an MCP server

Bedrock Flows is the right choice when your MCP tool needs to execute a fixed pipeline that combines multiple AI operations — model calls, conditionals, Knowledge Base retrievals, Lambda side effects — and you want that logic managed as infrastructure rather than coded in your MCP server. The flow is defined once in AWS, versioned, and invoked by name. Your MCP server becomes a thin proxy: map tool arguments to flow inputs, invoke, return the result.

Use caseBedrock FlowsConverse loop in MCP server
Fixed pipeline (classify → retrieve → generate)Define as flow graph, invoke onceMust code each step manually
Conditional routing based on model outputConditionNode handles branchingMust parse model output and branch in code
Fan-out processing of arraysIteratorNode + CollectorNodeMust loop and aggregate in code
Prompt versioning independent of serverPrompt ARN in PromptNode — update prompt, re-preparePrompts embedded in server code
Ad-hoc tool calls (dynamic tool list)Not supported — flow tools are staticMCP tools/list works normally
Low-latency, tight loopsHigher overhead per invocationLower — direct model calls

Two-SDK architecture: management vs runtime

Bedrock Flows uses the same SDK split as Bedrock Agents. The management SDK creates, edits, prepares, and versions flows. The runtime SDK invokes them. Import them separately:

// Management — create, edit, prepare, version, alias
import {
  BedrockAgentClient,
  CreateFlowCommand,
  PrepareFlowCommand,
  CreateFlowVersionCommand,
  CreateFlowAliasCommand,
  UpdateFlowAliasCommand,
} from '@aws-sdk/client-bedrock-agent';

// Runtime — invoke only
import {
  BedrockAgentRuntimeClient,
  InvokeFlowCommand,
} from '@aws-sdk/client-bedrock-agent-runtime';

const mgmt = new BedrockAgentClient({ region: 'us-east-1' });
const runtime = new BedrockAgentRuntimeClient({ region: 'us-east-1' });

The BedrockAgentClient endpoint is bedrock-agent.us-east-1.amazonaws.com; the runtime is bedrock-agent-runtime.us-east-1.amazonaws.com. Both clients accept the same credential chain. If you are only invoking flows (not managing them), you only need the runtime client.

CreateFlow: defining the flow graph

A flow is a directed graph of nodes and connections. CreateFlowCommand requires three fields: name (unique in account+region), executionRoleArn (the IAM role the flow assumes when it calls models, Lambda, S3, or Knowledge Bases), and definition (the graph itself).

Every valid flow graph must have exactly one node of type Input and exactly one node of type Output. All other nodes are optional. The minimum possible flow is Input → Prompt → Output:

import { CreateFlowCommand } from '@aws-sdk/client-bedrock-agent';

const flow = await mgmt.send(new CreateFlowCommand({
  name: 'mcp-summarization-flow',
  description: 'Summarizes a document passed from an MCP tool',
  executionRoleArn: 'arn:aws:iam::123456789012:role/BedrockFlowsExecutionRole',
  definition: {
    nodes: [
      {
        name: 'FlowInputNode',
        type: 'Input',
        outputs: [
          { name: 'document', type: 'String' }
        ],
      },
      {
        name: 'SummarizationPrompt',
        type: 'Prompt',
        configuration: {
          prompt: {
            sourceConfiguration: {
              resource: {
                // ARN of a saved Bedrock Prompt (created separately)
                promptArn: 'arn:aws:bedrock:us-east-1:123456789012:prompt/ABCDEF1234',
              },
            },
          },
        },
        inputs: [
          {
            name: 'document',          // must match prompt template variable
            type: 'String',
            expression: '$.data',      // JSONata path into the upstream output
          },
        ],
        outputs: [
          { name: 'modelCompletion', type: 'String' },
        ],
      },
      {
        name: 'FlowOutputNode',
        type: 'Output',
        inputs: [
          {
            name: 'document',
            type: 'String',
            expression: '$.data',
          },
        ],
      },
    ],
    connections: [
      {
        name: 'InputToPrompt',
        source: 'FlowInputNode',
        target: 'SummarizationPrompt',
        type: 'Data',
        configuration: {
          data: {
            sourceOutput: 'document',
            targetInput: 'document',
          },
        },
      },
      {
        name: 'PromptToOutput',
        source: 'SummarizationPrompt',
        target: 'FlowOutputNode',
        type: 'Data',
        configuration: {
          data: {
            sourceOutput: 'modelCompletion',
            targetInput: 'document',
          },
        },
      },
    ],
  },
}));

const flowId = flow.id!;
console.log('Flow created:', flowId);

Key details in the CreateFlow definition:

PrepareFlow: the mandatory pre-invocation step

PrepareFlowCommand validates the flow graph (checks all connections resolve, all types match) and compiles a runnable snapshot. A flow cannot be invoked until it has been prepared at least once. After any edit via UpdateFlowCommand, you must call PrepareFlowCommand again before the edits take effect for invocation — the DRAFT alias always points to the most recently prepared state, not the most recently saved state.

import { PrepareFlowCommand, GetFlowCommand } from '@aws-sdk/client-bedrock-agent';

await mgmt.send(new PrepareFlowCommand({ flowIdentifier: flowId }));

// PrepareFlow is asynchronous — poll until status is PREPARED
async function waitForPrepared(flowId: string, maxWaitMs = 60_000): Promise {
  const start = Date.now();
  while (Date.now() - start < maxWaitMs) {
    const { status } = await mgmt.send(new GetFlowCommand({ flowIdentifier: flowId }));
    if (status === 'Prepared') return;
    if (status === 'Failed') throw new Error(`Flow ${flowId} preparation failed`);
    await new Promise(r => setTimeout(r, 2000));
  }
  throw new Error(`Timed out waiting for flow ${flowId} to prepare`);
}

await waitForPrepared(flowId);

Possible status values from GetFlowCommand: NotPrepared, Preparing, Prepared, Failed. A flow in Failed status typically has a type mismatch in a connection, a missing Prompt resource, or an IAM permission error. Check the validations array in the GetFlow response for detailed error messages.

Preparation time depends on flow complexity: simple 3-node flows typically prepare in 2–5 seconds; complex flows with many nodes take 10–30 seconds. Build the prepare poll into your CI/CD pipeline so deploys do not leave flows in Preparing state when your MCP server routes traffic to them.

InvokeFlow: streaming response and event types

Like InvokeAgentCommand, InvokeFlowCommand returns a streaming response. There is no synchronous variant. The response has a responseStream async iterable that emits typed events until the flow completes or errors.

import { InvokeFlowCommand } from '@aws-sdk/client-bedrock-agent-runtime';

async function invokeFlow(
  flowId: string,
  flowAliasId: string,
  inputDocument: unknown,
): Promise {
  const response = await runtime.send(new InvokeFlowCommand({
    flowIdentifier: flowId,
    flowAliasIdentifier: flowAliasId,
    inputs: [
      {
        content: {
          document: inputDocument,  // string, number, boolean, object, or array
        },
        nodeName: 'FlowInputNode',      // the Input node's name in your definition
        nodeOutputName: 'document',     // always 'document' for Input nodes
      },
    ],
  }));

  if (!response.responseStream) {
    throw new Error('No response stream from InvokeFlow');
  }

  const outputChunks: string[] = [];

  for await (const event of response.responseStream) {
    if ('flowOutputEvent' in event) {
      // The final output from the Output node
      const content = event.flowOutputEvent?.content;
      if (content?.document !== undefined) {
        outputChunks.push(String(content.document));
      }
    } else if ('flowCompletionEvent' in event) {
      // Flow finished — completionReason: 'SUCCESS' | 'INPUT_REQUIRED'
      const reason = event.flowCompletionEvent?.completionReason;
      if (reason !== 'SUCCESS') {
        throw new Error(`Flow completed with reason: ${reason}`);
      }
    } else if ('flowTraceEvent' in event) {
      // Debug trace — log in development; skip in production
      if (process.env.NODE_ENV !== 'production') {
        console.debug('Flow trace:', JSON.stringify(event.flowTraceEvent, null, 2));
      }
    }
  }

  return outputChunks.join('');
}

Event type reference:

Event keyWhen emittedKey fields
flowOutputEventWhen the Output node receives its final valuecontent.document — the flow's output value; nodeName — the Output node name
flowCompletionEventAt stream endcompletionReason: SUCCESS or INPUT_REQUIRED
flowTraceEventOnce per node execution (if trace enabled)trace.node.nodeType, trace.node.nodeName, trace.node.inputs, trace.node.outputs
accessDeniedExceptionFlow role missing permissionmessage names the resource and permission
validationExceptionInput type mismatchmessage describes the type error
throttlingExceptionRate limit hit on model call inside flowRetry with exponential backoff

The inputs[].content.document field accepts any JSON-serializable value. If your flow's Input node expects a String, pass a string. If it expects an Object, pass a plain object — the SDK will serialize it. Do not JSON-stringify and then pass the string unless your flow explicitly expects a JSON string — this is a common mistake that causes the PromptNode to receive escaped JSON rather than a structured object.

Flow versioning and aliases

Bedrock Flows has the same version/alias model as Lambda. Versions are immutable integer snapshots. Aliases are mutable pointers to one or two versions with optional traffic weights. The DRAFT alias is a special built-in alias that always points to the most recent prepared state — do not use it in production because a developer re-preparing a flow mid-deploy will immediately change what DRAFT points to.

import {
  CreateFlowVersionCommand,
  CreateFlowAliasCommand,
  UpdateFlowAliasCommand,
} from '@aws-sdk/client-bedrock-agent';

// 1. Create an immutable version snapshot
const version = await mgmt.send(new CreateFlowVersionCommand({
  flowIdentifier: flowId,
  description: 'v3 — added ConditionNode for language routing',
}));
const versionNumber = version.version!;  // e.g. '3' (string, not integer)

// 2. Create a production alias pointing to this version
const alias = await mgmt.send(new CreateFlowAliasCommand({
  flowIdentifier: flowId,
  name: 'production',
  description: 'Production traffic',
  routingConfiguration: [
    { flowVersion: versionNumber, flowVersionWeight: 1.0 },
  ],
}));
const aliasId = alias.id!;

// 3. For A/B testing: split traffic 90/10 between v3 and v4
await mgmt.send(new UpdateFlowAliasCommand({
  flowIdentifier: flowId,
  aliasIdentifier: aliasId,
  routingConfiguration: [
    { flowVersion: '3', flowVersionWeight: 0.9 },
    { flowVersion: '4', flowVersionWeight: 0.1 },
  ],
}));

Alias IDs look like ABCDEF1234. Version numbers are strings like '1', '2'. The DRAFT alias ID is the literal string TSTALIASID (the word TEST, not an actual alias you created). Store the aliasId from CreateFlowAliasCommand in your MCP server config — do not hardcode version numbers or use the DRAFT string.

Your MCP server's invoke call uses both the flow ID and the alias ID:

// In your MCP tool handler
const result = await invokeFlow(
  process.env.FLOW_ID!,       // from state.json or env
  process.env.FLOW_ALIAS_ID!, // production alias, not DRAFT
  toolArgs.documentText,
);

IAM execution role

The executionRoleArn in CreateFlowCommand is the role Bedrock Flows assumes when it executes your flow. It must trust bedrock.amazonaws.com and have permissions for every resource used by your flow nodes:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "Service": "bedrock.amazonaws.com" },
      "Action": "sts:AssumeRole",
      "Condition": {
        "StringEquals": {
          "aws:SourceAccount": "123456789012"
        },
        "ArnLike": {
          "aws:SourceArn": "arn:aws:bedrock:us-east-1:123456789012:flow/*"
        }
      }
    }
  ]
}

Permission policy for a flow that uses PromptNodes, LambdaFunctionNodes, and KnowledgeBaseNodes:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"],
      "Resource": "arn:aws:bedrock:us-east-1::foundation-model/*"
    },
    {
      "Effect": "Allow",
      "Action": "bedrock:GetPrompt",
      "Resource": "arn:aws:bedrock:us-east-1:123456789012:prompt/*"
    },
    {
      "Effect": "Allow",
      "Action": "bedrock:Retrieve",
      "Resource": "arn:aws:bedrock:us-east-1:123456789012:knowledge-base/*"
    },
    {
      "Effect": "Allow",
      "Action": "lambda:InvokeFunction",
      "Resource": "arn:aws:lambda:us-east-1:123456789012:function:my-flow-action"
    }
  ]
}

The aws:SourceArn condition in the trust policy is recommended by AWS to prevent confused deputy attacks — it restricts which flows can assume this role. Without it, any Bedrock Flow in your account (including those created by third-party apps with Bedrock access) could assume the role.

MCP tool handler: full wiring

A complete MCP server tool handler that wraps a Bedrock Flow:

import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { BedrockAgentRuntimeClient, InvokeFlowCommand } from '@aws-sdk/client-bedrock-agent-runtime';
import { z } from 'zod';

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

const server = new McpServer({ name: 'my-flow-server', version: '1.0.0' });

server.tool(
  'summarize_document',
  'Summarize a document using the managed Bedrock summarization flow',
  {
    text: z.string().min(1).describe('Document text to summarize'),
    style: z.enum(['bullet_points', 'paragraph']).default('paragraph'),
  },
  async ({ text, style }) => {
    const response = await runtime.send(new InvokeFlowCommand({
      flowIdentifier: process.env.FLOW_ID!,
      flowAliasIdentifier: process.env.FLOW_ALIAS_ID!,
      inputs: [
        {
          content: { document: { text, style } },
          nodeName: 'FlowInputNode',
          nodeOutputName: 'document',
        },
      ],
    }));

    if (!response.responseStream) {
      throw new Error('Empty response stream from Bedrock Flow');
    }

    let summary = '';
    for await (const event of response.responseStream) {
      if ('flowOutputEvent' in event) {
        summary = String(event.flowOutputEvent?.content?.document ?? '');
      } else if ('flowCompletionEvent' in event) {
        const reason = event.flowCompletionEvent?.completionReason;
        if (reason !== 'SUCCESS') throw new Error(`Flow failed: ${reason}`);
      }
    }

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

Common failure modes

ErrorCauseFix
ResourceNotFoundException on InvokeFlow Flow ID or alias ID does not exist in the region the runtime client is pointed at Verify region matches between management and runtime clients; check the alias was created for this flow
ConflictException on PrepareFlow Another prepare is in progress Wait for the in-progress prepare to finish before calling PrepareFlow again
Flow status stuck at Preparing Validation failure that doesn't surface as a synchronous error Call GetFlowCommand and inspect validations[].details — look for type mismatches or missing prompt ARNs
flowOutputEvent never received Flow exited via a ConditionNode branch that leads to a path with no Output node connection Ensure all branches of your ConditionNode eventually connect to the Output node — add an explicit "default" condition branch
AccessDeniedException in stream event Execution role missing permission for one of the flow's resources Check message for the specific resource ARN; add the permission to the execution role policy
Output is an escaped JSON string instead of an object inputs[0].content.document was passed as JSON.stringify(obj) instead of the raw object Pass the object directly; the SDK serializes it
ValidationException: Input node output 'xyz' does not exist inputs[].nodeOutputName doesn't match a defined output name on the Input node Use 'document' — the standard output name for Input nodes