Blog · Amazon Bedrock Flows · Production Guide

Amazon Bedrock Flows for MCP Servers: Graph Pipelines, Node Type Gotchas, RAG Chains, and Production Deployment

Amazon Bedrock Flows lets you define multi-step AI pipelines as directed graphs and invoke them from an MCP server with a single API call. Instead of writing orchestration logic inside your MCP server — calling the model, checking conditions, looping over results, calling Lambda, re-prompting — you define the entire workflow in AWS once and reduce your MCP tool handler to a thin proxy: map tool arguments to flow inputs, invoke, return the result. This guide synthesises the full Bedrock Flows stack from first principles to production: the two-SDK architecture, the PrepareFlow lifecycle (the most common silent failure point), the nine node types with their type contracts and reserved input names, retrieval-augmented generation chains via KnowledgeBaseNode, StorageNode caching patterns, and the four-step CI/CD deploy sequence that separates working deployments from flows that silently serve stale logic.

When Bedrock Flows is the right tool for an MCP server

The core trade-off is orchestration-in-code versus orchestration-as-infrastructure. MCP server tools that implement their own multi-step pipeline — classify input, retrieve context, generate response, format output — are correct but brittle: pipeline logic is entangled with transport code, prompts are hardcoded in your server, and changing a step requires a full redeploy. Bedrock Flows moves the pipeline definition into AWS as a versioned, graph-structured resource. Your MCP server gains two things: prompt versioning independent of server deploys (a Bedrock Prompt ARN in a PromptNode can be updated without touching your server code), and built-in infrastructure for conditional routing, fan-out processing, Knowledge Base retrieval, and S3 caching that you do not have to implement yourself.

The tradeoff has real costs. Bedrock Flows has higher per-invocation latency than a direct ConverseCommand call — the managed pipeline layer adds overhead that is worth it for complex multi-node flows but wasteful for a single model call. The flow tool list is static: you cannot dynamically provide tools inside a flow the way you can in a standard Converse session with a tool list. And the deployment lifecycle is more involved than Lambda's — a four-step sequence replaces the two-step update-and-invoke of InvokeAgentCommand. Understand these costs before choosing Flows over a direct Bedrock Converse loop in your MCP server.

ScenarioPrefer Bedrock FlowsPrefer direct Converse in MCP
Fixed classify → retrieve → generate pipelineDefine as flow graph, invoke onceOverkill for 2–3 steps
Conditional routing on model outputConditionNode handles branchingSimple if/else in code
Fan-out: process each item in a listIteratorNode + CollectorNodePromise.all in MCP tool handler
Prompt versioning independent of server deploysPrompt ARN in PromptNode — update prompt, re-prepareRequires server redeploy
Dynamic tool list during conversationNot supported — flow tools are staticMCP tools/list works normally
Latency-critical single model callAvoid — pipeline overhead adds latencyDirect ConverseCommand preferred

The two-SDK split: management versus runtime

Bedrock Flows uses the same SDK split as Bedrock Agents. All management operations — creating flows, preparing them, versioning, alias management — go through @aws-sdk/client-bedrock-agent. All invocations go through @aws-sdk/client-bedrock-agent-runtime. These are distinct npm packages with distinct endpoints and distinct IAM namespaces. Using the wrong client for an operation produces an error that is easy to mistake for a permissions problem:

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

// Runtime SDK — 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' });

Both clients accept the same credential chain. The management endpoint is bedrock-agent.us-east-1.amazonaws.com; the runtime endpoint is bedrock-agent-runtime.us-east-1.amazonaws.com. If your MCP server only invokes existing flows — it does not create or manage them — you need only the runtime client. Keep the management client in a separate deploy script or CDK stack, not in your server's hot path.

The PrepareFlow lifecycle: the silent failure most teams hit first

This is the most common source of confusion with Bedrock Flows: a flow cannot be invoked until it has been explicitly prepared, and every edit requires a re-prepare before the changes take effect. The DRAFT alias always points to the most recently prepared state, not the most recently saved state. If you call UpdateFlowCommand and then immediately invoke via the DRAFT alias, you are invoking the previous version of the flow. No error is raised. The flow just behaves differently from what you saved.

PrepareFlowCommand validates the graph — checking that all connections resolve, all type signatures match, all referenced Prompt ARNs and Knowledge Base IDs exist in the region — and compiles a runnable snapshot. The operation is asynchronous: the API call returns immediately but the flow transitions through Preparing before reaching Prepared. You must poll GetFlowCommand until the status changes:

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

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

async function waitForPrepared(flowId: string, maxWaitMs = 60_000): Promise<void> {
  const start = Date.now();
  while (Date.now() - start < maxWaitMs) {
    const { status, validations } = await mgmt.send(
      new GetFlowCommand({ flowIdentifier: flowId })
    );
    if (status === 'Prepared') return;
    if (status === 'Failed') {
      throw new Error(
        `Flow preparation failed:\n${JSON.stringify(validations, null, 2)}`
      );
    }
    await new Promise(r => setTimeout(r, 2000));
  }
  throw new Error(`Timed out waiting for flow ${flowId} to prepare`);
}

await waitForPrepared(flowId);

Possible status values: NotPrepared (created or edited, never prepared), Preparing (in progress), Prepared (valid and invocable), Failed (validation error — inspect validations[] for the specific node and connection that failed). Simple three-node flows typically prepare in 2–5 seconds; complex flows with many nodes take 10–30 seconds. Build the prepare poll into every CI/CD deploy step — never create a version from an unprepared state.

The state machine only applies to the DRAFT working copy. Once you create an immutable version snapshot with CreateFlowVersionCommand, that snapshot is always in an equivalent of Prepared state. This is why the deployment workflow involves creating a version: it freezes the prepared state so alias routing is stable regardless of future edits.

See the core Bedrock Flows guide for the full CreateFlow + PrepareFlow lifecycle with connection syntax and IAM execution role configuration.

Node types: the contracts that cause silent failures

Bedrock Flows has nine node types. The overview is quick; the gotchas take longer. See the full node types reference for SDK definitions and all failure mode tables. Here are the contracts that cause problems in production.

PromptNode: modelCompletion is always a String

PromptNode calls a Bedrock foundation model and returns its completion. The output name is always modelCompletion and the type is always String — regardless of how you configure the model or what it returns. If you need structured JSON from the model, you get a string containing JSON. Use a LambdaFunctionNode downstream to JSON.parse it and return a typed object to subsequent nodes.

Use a saved Bedrock Prompt ARN (not an inline template) for production flows. The Prompt ARN lets you version prompts independently of the flow: update the prompt text, increment the prompt version, update the ARN in the flow, re-prepare. Your MCP server never redeploys. For development iteration, inline templates are fine. For production, the ARN-based approach separates prompt engineering from server engineering.

// Production: reference a saved Bedrock Prompt by ARN
const promptNode = {
  name: 'SummarizationPrompt',
  type: 'Prompt',
  configuration: {
    prompt: {
      sourceConfiguration: {
        resource: {
          promptArn: 'arn:aws:bedrock:us-east-1:123456789012:prompt/ABCDEF1234',
          // Append :3 to pin to a specific prompt version
        },
      },
    },
  },
  inputs: [
    { name: 'document', type: 'String', expression: '$.data' },
  ],
  outputs: [
    { name: 'modelCompletion', type: 'String' },
  ],
};

ConditionNode: JSONata not JSONPath, default branch mandatory, and Conditional connections

ConditionNode is the most common source of hard-to-debug silent failures. Three independent rules must all be followed:

Rule 1: Expressions are JSONata, not JSONPath or JMESPath. The reference to the upstream value is $.data, not $ or @. Comparisons use == and !=. String literals use single quotes inside the double-quoted expression string. Numeric comparisons use > and <. Field access on an Object-typed input is $.data.fieldName. Getting this wrong causes the condition to never match — a valid expression that evaluates to false for all inputs.

Rule 2: The default condition must be the last item in the conditions array. If no condition matches and there is no default, the flow emits flowCompletionEvent with completionReason: 'INPUT_REQUIRED' and no flowOutputEvent. Your MCP tool receives no output and no explicit error. The fix is straightforward — add a condition with no expression as the last item — but the failure mode is subtle because the flow itself appears to complete successfully.

Rule 3: Connections from a ConditionNode must use type: 'Conditional', not 'Data'. Using the wrong connection type causes a ValidationException at PrepareFlow that names the connection. This one at least fails loudly.

const conditionNode = {
  name: 'LanguageRouter',
  type: 'Condition',
  configuration: {
    condition: {
      conditions: [
        { name: 'isEnglish', expression: "$.data == 'en'" },  // JSONata
        { name: 'isFrench',  expression: "$.data == 'fr'" },
        { name: 'default' },  // Must be last — no expression
      ],
    },
  },
  inputs: [
    { name: 'languageCode', type: 'String', expression: '$.data' },
  ],
  // Outputs are auto-generated from condition names
};

// Connections out of ConditionNode use 'Conditional' not 'Data'
const connection = {
  name: 'ToEnglishBranch',
  source: 'LanguageRouter',
  target: 'EnglishPrompt',
  type: 'Conditional',                    // Not 'Data'
  configuration: {
    conditional: { condition: 'isEnglish' },
  },
};

IteratorNode and CollectorNode: reserved input names are non-negotiable

IteratorNode takes an Array-typed input and emits each element individually. CollectorNode is the complementary accumulator — it receives one result per element and merges them back into an Array. The reserved names are enforced by the API and cause PrepareFlow validation errors if violated:

// Fan-out: summarize each document in a list independently
const iteratorNode = {
  name: 'DocumentIterator',
  type: 'Iterator',
  inputs: [
    { name: 'array', type: 'Array', expression: '$.data' },  // 'array' is mandatory
  ],
  outputs: [
    { name: 'arrayItem', type: 'String' },
    { name: 'arraySize', type: 'Number' },
  ],
};

const collectorNode = {
  name: 'SummaryCollector',
  type: 'Collector',
  inputs: [
    { name: 'arrayItem', type: 'String', expression: '$.data' },  // 'arrayItem' is mandatory
  ],
  outputs: [
    { name: 'collectedArray', type: 'Array' },
  ],
};

The fan-out pattern for MCP tools that process a list of items: FlowInput → IteratorNode → PromptNode (invoked once per element) → CollectorNode → FlowOutput. The PromptNode is called N times, once for each element, and all results are aggregated by CollectorNode into an Array that the Output node emits as a single flowOutputEvent.

Using IteratorNode without a CollectorNode is valid when you want streaming: the flow emits one flowOutputEvent per element and one flowCompletionEvent at the end. This is useful when the MCP tool needs to yield incremental results rather than waiting for the full array. IteratorNode flattens exactly one array level — if your input is a nested array, use a LambdaFunctionNode to flatten it before the Iterator.

LambdaFunctionNode: inputs arrive as an array, return type must match declaration

LambdaFunctionNode invokes an AWS Lambda function synchronously. All node inputs are passed as a JSON event with an inputs array; the Lambda's return value becomes the functionResponse output. The Lambda must return a value whose type matches what you declared in the node's output — if you declare type: 'String' and Lambda returns an object, the flow emits a type error. When you need type conversion between nodes (Number to String, Object to String), a trivial Lambda is the correct solution: Bedrock Flows is strictly typed and does not auto-coerce.

// Lambda handler receives this shape
interface BedrockFlowLambdaEvent {
  node: { name: string; type: string; outputs: Array<{ name: string; type: string }> };
  inputs: Array<{ name: string; type: string; value: unknown }>;
}

export async function handler(event: BedrockFlowLambdaEvent) {
  const summary = event.inputs.find(i => i.name === 'summary')?.value as string;
  const metadata = event.inputs.find(i => i.name === 'metadata')?.value as Record<string, unknown>;
  return `# ${metadata.title}\n\n${summary}`;  // return type must match declared output type
}

KnowledgeBaseNode: two modes with different output shapes

KnowledgeBaseNode is the RAG primitive in Bedrock Flows. Its behavior — and output shape — changes based on whether you include a modelArn in the configuration. This is a common source of confusion because the output name (outputText) is the same in both modes but represents different data.

Retrieval-only mode (no modelArn): The node retrieves document chunks from the Knowledge Base and returns them as a single concatenated String in outputText. No generation is performed. Use this when you want to inject retrieved context into your own PromptNode — it gives you full control over the generation model, system prompt, temperature, and output format.

Retrieve-and-generate mode (with modelArn): The node runs a full retrieve-and-generate pass internally using the specified foundation model and returns the generated answer in outputText. The generation uses Bedrock's default RAG system prompt. Use this when you want the simplest possible RAG result without prompt engineering.

The recommended RAG pattern for MCP servers is retrieval-only plus a downstream PromptNode. This wires the retrieved context and the original user question as separate template variables — giving you a grounded answer with a custom prompt:

// Recommended: retrieval-only KB + custom PromptNode for RAG
//
// Flow input → KBRetrieval (chunks) + FlowInput (question)
//          ↓                           ↓
//       context variable          question variable
//          ↘                          ↙
//           QAGeneration (PromptNode) → FlowOutput
//
// KBRetrieval outputs 'outputText' (String: concatenated chunks)
// QAGeneration inputs 'context' from KBRetrieval + 'question' from FlowInput
// Two separate connections into QAGeneration from two upstream nodes

One important constraint: you cannot override numberOfResults in the KnowledgeBaseNode definition — it uses whatever retrieval count is configured on the Knowledge Base resource itself. Set the retrieval count on the KB before creating the flow. For multi-domain routing — routing queries to different KBs based on content type — combine a ConditionNode with separate KnowledgeBaseNodes per domain and re-converge at a shared PromptNode. See the KnowledgeBase and StorageNode guide for the full multi-KB routing pattern and IAM configuration.

StorageNode: S3 caching with three hard constraints

StorageNode reads from or writes to an S3 object. It is useful for caching expensive intermediate results — such as KB retrieval chunks for a high-traffic flow — so that subsequent invocations skip the retrieval step for identical queries. Three constraints trip teams up in production:

Constraint 1: The objectKey must be a full object key, not a prefix. 'cache/' will fail — it must be 'cache/results.json' or similar. The node does not compute keys dynamically from input data. If you need a runtime-computed key (e.g., a hash of the query), use a LambdaFunctionNode before the StorageNode to do the S3 operation directly with a computed key.

Constraint 2: The body output is always a String. Even if you stored a JSON object, StorageNode returns the raw bytes as a String. Use a LambdaFunctionNode downstream to JSON.parse it if you need an Object-typed value for downstream nodes.

Constraint 3: A get on a non-existent key causes an internalServerException in the response stream. StorageNode does not gracefully return null on a cache miss — it throws. The correct pattern for cache-miss handling: use a LambdaFunctionNode before the StorageNode to call HeadObjectCommand and check existence, then route via a ConditionNode on the cache-hit/miss result. The LambdaFunctionNode before the cache read does the HeadObject check; on cache hit it routes to StorageNode read; on cache miss it routes to the KB retrieval path, which then writes the result to the cache via a separate StorageNode write.

// Cache-miss safe pattern
// LambdaCacheCheck (HeadObject → { hit: bool, cacheKey }) →
//   ConditionNode on $.data.hit →
//     cacheHit branch → StorageNode read → PromptNode
//     cacheMiss branch → KBRetrieval → LambdaCacheWrite (PutObject) → PromptNode

The execution role for a flow with both KnowledgeBaseNode and StorageNode needs four permissions: bedrock:Retrieve on the KB ARN, bedrock:InvokeModel on the foundation model ARN, and s3:GetObject + s3:PutObject scoped to the specific bucket prefix — not s3:* on the whole bucket.

InvokeFlowCommand: streaming response and error events in the stream

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. Three events matter for MCP tool handlers:

Critically, error conditions are reported as stream events, not as thrown exceptions. accessDeniedException, throttlingException, and internalServerException all appear as event keys in the stream. A robust MCP tool handler must check for these inside the stream loop, not just catch exceptions from the outer runtime.send() call:

async function invokeFlowSafe(
  flowId: string,
  aliasId: string,
  input: unknown,
): Promise<{ ok: true; output: string } | { ok: false; error: string; retryable: boolean }> {
  try {
    const response = await runtime.send(new InvokeFlowCommand({
      flowIdentifier: flowId,
      flowAliasIdentifier: aliasId,
      inputs: [
        { content: { document: input }, nodeName: 'FlowInputNode', nodeOutputName: 'document' },
      ],
      enableTrace: process.env.NODE_ENV !== 'production',
    }));

    if (!response.responseStream) {
      return { ok: false, error: 'No response stream', retryable: false };
    }

    let output = '';

    for await (const event of response.responseStream) {
      if ('flowOutputEvent' in event) {
        output = String(event.flowOutputEvent?.content?.document ?? '');
      } else if ('flowCompletionEvent' in event) {
        const reason = event.flowCompletionEvent?.completionReason;
        if (reason !== 'SUCCESS') {
          return { ok: false, error: `Flow ended with: ${reason}`, retryable: false };
        }
      } else if ('throttlingException' in event) {
        return { ok: false, error: 'Throttled — retry with backoff', retryable: true };
      } else if ('accessDeniedException' in event) {
        return { ok: false, error: `Access denied: ${event.accessDeniedException?.message}`, retryable: false };
      } else if ('internalServerException' in event) {
        return { ok: false, error: `Internal error: ${event.internalServerException?.message}`, retryable: true };
      } else if ('validationException' in event) {
        return { ok: false, error: `Validation: ${event.validationException?.message}`, retryable: false };
      }
    }

    return { ok: true, output };

  } catch (err) {
    return { ok: false, error: String(err), retryable: false };
  }
}

One common serialization mistake: inputs[0].content.document accepts any JSON-serializable value — string, number, boolean, object, array. The SDK serializes it. Do not JSON.stringify before passing. If your flow's Input node expects an Object and you pass JSON.stringify(obj), the PromptNode receives escaped JSON as a string literal rather than a structured object — the prompt template renders a JSON blob instead of your fields.

Flow versioning and aliases: why DRAFT is not safe for production

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 — its internal alias ID is the literal string TSTALIASID.

Using DRAFT in production is dangerous for the same reason that Lambda's $LATEST is dangerous: a developer re-preparing a flow mid-deploy immediately changes what DRAFT points to. If your MCP server holds the DRAFT alias ID and an engineer prepares a half-finished flow update, production traffic immediately hits the broken version. Create a versioned alias after every prepare and store that alias ID in your MCP server config:

// 1. Create an immutable version from the prepared flow
const version = await mgmt.send(new CreateFlowVersionCommand({
  flowIdentifier: flowId,
  description: 'v3 — 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',
  routingConfiguration: [{ flowVersion: versionNumber, flowVersionWeight: 1.0 }],
}));

// Store alias.id! — this is what your MCP server uses
// process.env.FLOW_ALIAS_ID = alias.id!

For safe rollouts, use traffic splitting: route 5% of invocations to the new version, monitor CloudWatch error rates, then promote fully. Weights must sum to 1.0 and you can split between at most two versions. For conversational MCP flows where session consistency matters, avoid splits — a user may hit different flow behavior on consecutive calls.

The four-step CI/CD deploy sequence

This is the most significant operational difference between Bedrock Flows and Lambda. Lambda deployment is two steps: upload code, optionally update alias. Bedrock Flows deployment is four steps, in order, with a mandatory async poll between steps two and three:

  1. UpdateFlowCommand — save the new graph definition to the DRAFT working copy
  2. PrepareFlowCommand — trigger async validation and compilation
  3. Poll GetFlowCommand until status === 'Prepared' — do not proceed before this
  4. CreateFlowVersionCommand — create an immutable snapshot of the prepared state
  5. UpdateFlowAliasCommand — point your production alias at the new version

Skipping step three (the poll) causes a silent failure: CreateFlowVersionCommand creates a snapshot of the previous prepared state if the new prepare hasn't finished yet. You end up with a version that doesn't reflect your edits, with no error from the API. The deploy script below makes the poll non-optional:

#!/bin/bash
# deploy-flow.sh
set -euo pipefail
FLOW_ID="${BEDROCK_FLOW_ID:?must be set}"
ALIAS_ID="${BEDROCK_FLOW_ALIAS_ID:?must be set}"
REGION="${AWS_REGION:-us-east-1}"

echo "Step 1/4: Preparing flow..."
aws bedrock-agent prepare-flow --flow-identifier "$FLOW_ID" --region "$REGION"

echo "Step 2/4: Polling until Prepared..."
for i in $(seq 1 40); do
  STATUS=$(aws bedrock-agent get-flow --flow-identifier "$FLOW_ID" \
    --region "$REGION" --query 'status' --output text)
  echo "  status: $STATUS (attempt $i)"
  if [[ "$STATUS" == "Prepared" ]]; then break; fi
  if [[ "$STATUS" == "Failed" ]]; then
    echo "FAILED — validations:"
    aws bedrock-agent get-flow --flow-identifier "$FLOW_ID" --region "$REGION" --query 'validations'
    exit 1
  fi
  sleep 5
done
[[ "$STATUS" != "Prepared" ]] && { echo "Timed out"; exit 1; }

echo "Step 3/4: Creating immutable version..."
VERSION=$(aws bedrock-agent create-flow-version \
  --flow-identifier "$FLOW_ID" \
  --description "CI deploy $(git rev-parse --short HEAD)" \
  --region "$REGION" --query 'version' --output text)
echo "  version: $VERSION"

echo "Step 4/4: Updating alias to v$VERSION..."
aws bedrock-agent update-flow-alias \
  --flow-identifier "$FLOW_ID" --alias-identifier "$ALIAS_ID" \
  --routing-configuration "[{\"flowVersion\":\"$VERSION\",\"flowVersionWeight\":1.0}]" \
  --region "$REGION"

echo "Done. Alias $ALIAS_ID → version $VERSION"

Maintain the flow definition as a JSON file in version control. Use update-flow to sync it to AWS before preparing. This makes flow changes reviewable in pull requests alongside the MCP server code that invokes them. See the Bedrock Flows deployment guide for the full trace event debugging workflow and flow version cleanup script.

IAM: execution role versus caller role

Bedrock Flows uses two distinct IAM principals. The caller role (your MCP server's Lambda or ECS task role) needs bedrock:InvokeFlow on the flow ARN. The execution role (specified in executionRoleArn when creating the flow) is what the flow itself assumes when it calls models, Lambda, Knowledge Bases, and S3.

The execution role trust policy must allow bedrock.amazonaws.com to assume it. Add an aws:SourceArn condition scoped to your flow ARNs to prevent confused deputy attacks — without it, any Bedrock Flow in your account can assume the role:

// Trust policy for the flow execution role
{
  "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 with PromptNodes, KnowledgeBaseNode, LambdaFunctionNode, and StorageNode: bedrock:InvokeModel and bedrock:InvokeModelWithResponseStream on the foundation models, bedrock:GetPrompt on the Prompt ARNs, bedrock:Retrieve on the Knowledge Base ARNs, lambda:InvokeFunction on the Lambda ARNs, and s3:GetObject + s3:PutObject on the specific S3 key paths. Use resource-level scoping, not wildcards — the execution role has broad trust and a wildcard bedrock:InvokeModel on * allows the flow to call any model in the account.

Seven production gotchas consolidated

GotchaSymptomFix
Edit flow without re-preparing DRAFT alias invokes previous version; no error Always PrepareFlowCommand + poll after every UpdateFlowCommand; never create a version before status === 'Prepared'
ConditionNode missing default branch flowCompletionEvent.completionReason: 'INPUT_REQUIRED'; no output received Add a condition with no expression as the last item in conditions[]
ConditionNode outbound connections using type: 'Data' PrepareFlow fails with ValidationException: connection type mismatch Use type: 'Conditional' for all ConditionNode outbound connections
IteratorNode input not named 'array' PrepareFlow validation error on the Iterator node Rename the input to exactly 'array'
CollectorNode input not named 'arrayItem' PrepareFlow validation error on the Collector node Rename the input to exactly 'arrayItem'
StorageNode read on non-existent S3 key internalServerException in stream on cache miss Use LambdaFunctionNode + HeadObjectCommand before StorageNode; route via ConditionNode on hit/miss
Passing JSON.stringify(obj) as flow input document PromptNode receives escaped JSON string instead of structured object; model output is malformed Pass the raw object; the SDK serializes it. Only pass a string if the Input node expects String type

MCP tool handler: full wiring pattern

A complete MCP server tool handler that wraps a Bedrock Flow as a production-safe tool, handling in-stream error events and returning structured MCP responses:

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(
  'analyze_document',
  'Classify, retrieve relevant context, and generate a grounded answer using the managed pipeline',
  {
    text: z.string().min(1).describe('Document or question text'),
    domain: z.enum(['technical', 'hr', 'product']).default('technical'),
  },
  async ({ text, domain }) => {
    const response = await runtime.send(new InvokeFlowCommand({
      flowIdentifier: process.env.FLOW_ID!,
      flowAliasIdentifier: process.env.FLOW_ALIAS_ID!,
      inputs: [
        {
          content: { document: { text, domain } },  // Object input, not JSON string
          nodeName: 'FlowInputNode',
          nodeOutputName: 'document',
        },
      ],
      enableTrace: process.env.NODE_ENV !== 'production',
    }));

    if (!response.responseStream) {
      return { content: [{ type: 'text', text: 'Error: empty response stream' }], isError: true };
    }

    let output = '';

    for await (const event of response.responseStream) {
      if ('flowOutputEvent' in event) {
        output = String(event.flowOutputEvent?.content?.document ?? '');
      } else if ('flowCompletionEvent' in event) {
        const reason = event.flowCompletionEvent?.completionReason;
        if (reason !== 'SUCCESS') {
          return {
            content: [{ type: 'text', text: `Flow ended: ${reason}` }],
            isError: true,
          };
        }
      } else if ('throttlingException' in event) {
        return { content: [{ type: 'text', text: 'Throttled — retry shortly' }], isError: true };
      } else if ('accessDeniedException' in event) {
        return { content: [{ type: 'text', text: `Access denied: ${event.accessDeniedException?.message}` }], isError: true };
      } else if ('internalServerException' in event) {
        return { content: [{ type: 'text', text: `Internal error: ${event.internalServerException?.message}` }], isError: true };
      }
    }

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

Deployment checklist

CheckHow to verify
Flow status is Prepared before creating versionGetFlowCommand → flow.status === 'Prepared'
No validation errors in flowGetFlowCommand → flow.validations[] empty or all PASSED
Version exists before updating aliasListFlowVersionsCommand shows new version
Alias routing points to new versionGetFlowAliasCommand → routingConfiguration[].flowVersion
Test invocation via DRAFT alias passesCall InvokeFlowCommand with TSTALIASID and known test input before version creation
MCP server env vars updated if flow was recreatedCheck FLOW_ID and FLOW_ALIAS_ID in server config; redeploy if changed
CloudWatch error rate stable post-deployWatch InvocationErrors metric (namespace AWS/Bedrock/Flows) for 5 minutes after alias update

Further reading