Guide · Amazon Bedrock · Data Extraction
Amazon Bedrock Data Automation for MCP Servers — InvokeDataAutomationAsyncCommand, Polling, and S3 Output
Amazon Bedrock Data Automation (BDA) extracts structured data from documents, images, audio, and video — but every invocation is asynchronous, every result lands in S3, and the control-plane and runtime operations live in separate SDK packages. The most common failure mode for MCP server developers: calling InvokeDataAutomationAsyncCommand and expecting a synchronous result, or omitting the IAM permissions that allow Bedrock to write output to your S3 bucket. Beyond the async pattern, four topics dominate BDA integration work: selecting the right data automation profile ARN, writing a correct polling loop with GetDataAutomationStatusCommand, reading output files from S3, and distinguishing ClientError from ServiceError for retry decisions. For custom field extraction with user-defined schemas see BDA blueprints; for document-specific patterns (PDF, DOCX, tables) see BDA document processing; for output JSON structure and parsing see BDA output parsing.
TL;DR
BDA always runs async. Submit a job with InvokeDataAutomationAsyncCommand from @aws-sdk/client-bedrock-data-automation-runtime, get back an invocationArn, then poll GetDataAutomationStatusCommand until status === "Success". Output lands in the S3 prefix you specified — fetch it with GetObjectCommand. The control-plane package @aws-sdk/client-bedrock-data-automation is for blueprints only; invocations always use the runtime package.
- BDA blueprints — custom extraction schemas, CreateBlueprintCommand, DEVELOPMENT/LIVE stages
- BDA document processing — PDF/DOCX extraction, standard output, tables and forms
- BDA output parsing — output JSON structure, S3 key pattern, MCP tool integration
- Bedrock Converse API — foundation model calls for MCP tools
- Bedrock Agents — multi-step agentic workflows
What Amazon Bedrock Data Automation is
Amazon Bedrock Data Automation is a managed extraction service that uses foundation models to convert unstructured content into structured JSON output. You provide an S3 URI pointing to a document (PDF, DOCX, XLSX, CSV, HTML, TXT), image (JPEG, PNG, TIFF), audio (MP3, WAV), or video (MP4, MOV), and BDA returns structured data including extracted text, identified tables, form fields (key-value pairs), figures, and summaries. For custom field extraction — invoice line items, medical record fields, contract clauses — you attach a blueprint that defines the JSON schema of the output you want.
BDA is designed for high-volume document processing workloads where low-latency response is not required. Jobs typically take 10–120 seconds depending on document size and modality. This makes BDA a good fit for MCP server tools that process uploaded files, run background document analysis, or build vector search pipelines — not for interactive real-time workflows where the user is waiting.
The service integrates with two separate AWS SDK packages. The runtime package (@aws-sdk/client-bedrock-data-automation-runtime) handles job submission and status polling. The control-plane package (@aws-sdk/client-bedrock-data-automation) manages blueprints (custom extraction schemas). Many developers try to use the control-plane client for invocations and hit an immediate UnknownOperation error — the packages are not interchangeable.
// Two separate packages — not interchangeable
import {
BedrockDataAutomationClient,
CreateBlueprintCommand,
GetBlueprintCommand,
ListBlueprintsCommand,
} from '@aws-sdk/client-bedrock-data-automation';
import {
BedrockDataAutomationRuntimeClient,
InvokeDataAutomationAsyncCommand,
GetDataAutomationStatusCommand,
} from '@aws-sdk/client-bedrock-data-automation-runtime';
const controlPlane = new BedrockDataAutomationClient({
region: process.env.AWS_REGION ?? 'us-east-1',
});
const runtime = new BedrockDataAutomationRuntimeClient({
region: process.env.AWS_REGION ?? 'us-east-1',
});
Data automation profiles — selecting the right foundation model
Every BDA invocation requires a dataAutomationProfileArn that specifies which foundation model powers the extraction. AWS provides standard profiles per region; you do not create these — they are AWS-managed resources identified by a double-colon ARN format (no account ID segment, similar to Bedrock foundation model ARNs).
Standard profiles follow the ARN pattern:
arn:aws:bedrock:REGION::data-automation-profile/MODEL_ID
For us-east-1, the most commonly used standard profile targets Claude 3 Haiku for cost-effective extraction:
const STANDARD_PROFILE_ARN =
'arn:aws:bedrock:us-east-1::data-automation-profile/anthropic.claude-3-haiku-20240307-v1:0';
For higher-accuracy extraction on complex documents (dense tables, handwriting, nested structures), use a Claude 3.5 Sonnet profile:
const HIGH_ACCURACY_PROFILE_ARN =
'arn:aws:bedrock:us-east-1::data-automation-profile/anthropic.claude-3-5-sonnet-20241022-v2:0';
Profile ARN availability varies by region. The safest approach is to hardcode the region-specific ARN from the BDA documentation for your deployment region rather than constructing it at runtime. The dataAutomationProfileArn is a required field — omitting it raises a ValidationException before any extraction work begins.
A common confusion: the data automation profile ARN is different from a Bedrock inference profile ARN. The inference profile (from cross-region inference profiles) routes traffic across regions for quota management. The data automation profile selects which model powers the extraction job. These are not interchangeable in InvokeDataAutomationAsyncCommand.
InvokeDataAutomationAsyncCommand — full parameter reference
InvokeDataAutomationAsyncCommand submits a job to BDA and immediately returns an invocationArn. The actual extraction happens asynchronously — the return of invocationArn means the job was accepted and queued, not completed.
import {
BedrockDataAutomationRuntimeClient,
InvokeDataAutomationAsyncCommand,
type InvokeDataAutomationAsyncCommandInput,
} from '@aws-sdk/client-bedrock-data-automation-runtime';
const runtime = new BedrockDataAutomationRuntimeClient({
region: process.env.AWS_REGION ?? 'us-east-1',
});
const PROFILE_ARN = process.env.BDA_PROFILE_ARN!;
const OUTPUT_BUCKET = process.env.BDA_OUTPUT_BUCKET!;
async function submitExtractionJob(
inputS3Uri: string,
jobPrefix: string,
): Promise<string> {
const input: InvokeDataAutomationAsyncCommandInput = {
inputConfiguration: {
s3Uri: inputS3Uri, // e.g. "s3://my-docs-bucket/uploads/invoice-2024-001.pdf"
},
outputConfiguration: {
s3Uri: `s3://${OUTPUT_BUCKET}/bda-output/${jobPrefix}/`,
},
dataAutomationProfileArn: PROFILE_ARN,
// clientToken ensures idempotency within a 1-hour window
// Use a deterministic ID (e.g. document hash) to safely retry on network failure
clientToken: `job-${jobPrefix}-${Date.now()}`,
// Optional: attach custom extraction blueprint
// blueprintConfiguration: {
// blueprints: [{ blueprintArn: BLUEPRINT_ARN, blueprintStage: 'LIVE' }]
// },
// Optional: EventBridge notification instead of polling
// notificationConfiguration: {
// eventBridgeConfiguration: { eventBridgeEnabled: true }
// },
};
const response = await runtime.send(new InvokeDataAutomationAsyncCommand(input));
// response.invocationArn is the job identifier — persist this for status polling
// Format: arn:aws:bedrock:REGION:ACCOUNT_ID:data-automation-invocation/JOB_ID
if (!response.invocationArn) {
throw new Error('BDA invocation did not return an invocationArn');
}
return response.invocationArn;
}
Input S3 URI requirements
The input S3 URI must point to a single file (not a prefix). The bucket must be in the same AWS region as the BDA runtime endpoint you are calling. BDA reads from the bucket using the caller's IAM credentials — the service does not assume a separate role for reading input. Your Lambda or ECS task role must have s3:GetObject on the input object.
The output S3 URI is a prefix (ending in /) where BDA writes result files. BDA needs s3:PutObject and s3:GetBucketLocation on this bucket. The key difference from reading: BDA writes output using the Bedrock service principal (bedrock.amazonaws.com), not your task role. You must add a bucket policy granting Bedrock write access — omitting this causes a ClientError on the job, not an SDK-level exception during InvokeDataAutomationAsyncCommand.
// S3 bucket policy required on output bucket — without this BDA job will fail
// with status=ClientError and errorType containing "AccessDenied"
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowBDAOutputWrite",
"Effect": "Allow",
"Principal": { "Service": "bedrock.amazonaws.com" },
"Action": ["s3:PutObject", "s3:GetObject"],
"Resource": "arn:aws:s3:::MY-OUTPUT-BUCKET/bda-output/*",
"Condition": {
"StringEquals": { "aws:SourceAccount": "MY-ACCOUNT-ID" }
}
}
]
}
Polling with GetDataAutomationStatusCommand
GetDataAutomationStatusCommand takes an invocationArn and returns the current job status. Possible status values: Created (accepted but not yet running), InProgress (actively processing), Success (completed), ServiceError (AWS-side failure — retryable), ClientError (configuration error — not retryable without fixing the underlying cause). Never retry a ClientError in a tight loop — fix the root cause first (IAM, S3 policy, unsupported file format, oversized input).
import {
BedrockDataAutomationRuntimeClient,
GetDataAutomationStatusCommand,
type GetDataAutomationStatusCommandOutput,
} from '@aws-sdk/client-bedrock-data-automation-runtime';
interface JobResult {
outputS3Uri: string;
durationMs: number;
}
async function waitForJob(
runtime: BedrockDataAutomationRuntimeClient,
invocationArn: string,
timeoutMs = 300_000, // 5-minute default timeout
pollIntervalMs = 5_000,
): Promise<JobResult> {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
const response: GetDataAutomationStatusCommandOutput = await runtime.send(
new GetDataAutomationStatusCommand({ invocationArn })
);
switch (response.status) {
case 'Success': {
const outputUri = response.outputConfiguration?.s3Uri;
if (!outputUri) {
throw new Error(`BDA job succeeded but returned no outputConfiguration.s3Uri`);
}
return { outputS3Uri: outputUri, durationMs: Date.now() - start };
}
case 'ClientError': {
// Configuration problem — no point retrying
throw new Error(
`BDA job failed with ClientError: ${response.errorType} — ${response.errorMessage}`
);
}
case 'ServiceError': {
// AWS-side error — log and throw, let caller decide on retry
throw new Error(
`BDA job failed with ServiceError: ${response.errorType} — ${response.errorMessage}`
);
}
case 'Created':
case 'InProgress':
default: {
// Still running — wait and poll again
await sleep(pollIntervalMs);
break;
}
}
}
throw new Error(
`BDA job ${invocationArn} did not complete within ${timeoutMs}ms`
);
}
function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
Polling interval guidance
For small documents (1–5 pages, PDF under 500 KB), jobs typically complete in 10–30 seconds. For large multi-page documents or spreadsheets with many tables, expect 60–180 seconds. For audio/video, 1–10 minutes depending on duration. Start polling after 5 seconds and use a 5–10 second interval — polling more frequently wastes API calls and does not speed up the job.
BDA does not support job cancellation — once submitted, a job runs to completion. For MCP server tools with user-visible latency, build your tool to return a job ticket (the invocationArn) immediately and have a separate check_extraction_job tool that the agent can call to poll for completion. This prevents blocking the agent loop on a long-running extraction job.
// Two-tool pattern for MCP servers: submit + poll
// Tool 1: submit_document_extraction
{
name: 'submit_document_extraction',
description: 'Start extracting structured data from a document in S3. Returns a job ID.',
inputSchema: {
type: 'object',
properties: {
s3_uri: { type: 'string', description: 'S3 URI of the document to extract' },
},
required: ['s3_uri'],
},
async execute({ s3_uri }) {
const invocationArn = await submitExtractionJob(s3_uri, generateJobId());
return { job_id: invocationArn, status: 'submitted' };
}
}
// Tool 2: get_extraction_result
{
name: 'get_extraction_result',
description: 'Check the status of a document extraction job and return results when complete.',
inputSchema: {
type: 'object',
properties: {
job_id: { type: 'string', description: 'The job_id returned by submit_document_extraction' },
},
required: ['job_id'],
},
async execute({ job_id }) {
const statusResp = await runtime.send(
new GetDataAutomationStatusCommand({ invocationArn: job_id })
);
if (statusResp.status === 'Success') {
const output = await fetchOutputFromS3(statusResp.outputConfiguration!.s3Uri!);
return { status: 'complete', data: output };
}
return { status: statusResp.status.toLowerCase() }; // 'created', 'inprogress', 'clienterror', 'serviceerror'
}
}
Reading output from S3
When a job completes, the outputConfiguration.s3Uri in the status response points to the S3 prefix where BDA wrote the result files. BDA always writes a manifest file (job_manifest.json) at the prefix root that lists every output file and its modality type. For a document invocation, the manifest points to a single document_output.json containing the extracted content.
import { S3Client, GetObjectCommand, ListObjectsV2Command } from '@aws-sdk/client-s3';
const s3 = new S3Client({ region: process.env.AWS_REGION ?? 'us-east-1' });
async function fetchBdaOutput(outputS3Uri: string): Promise<unknown> {
// Parse the S3 URI
const url = new URL(outputS3Uri.replace('s3://', 'https://'));
const bucket = url.hostname;
const prefix = url.pathname.replace(/^\//, '');
// Read the manifest first to find output file keys
const manifestKey = `${prefix}job_manifest.json`;
const manifestText = await s3GetText(bucket, manifestKey);
const manifest = JSON.parse(manifestText) as BdaManifest;
// For document invocations, find the document output file
const docOutput = manifest.output_metadata?.find(
(m: OutputMetadataEntry) => m.segment_metadata?.[0]?.asset_type === 'DOCUMENT'
);
if (!docOutput) {
// Fall back: list all files in prefix and find the JSON output
const listing = await s3.send(new ListObjectsV2Command({ Bucket: bucket, Prefix: prefix }));
const jsonKey = listing.Contents?.find(
obj => obj.Key?.endsWith('.json') && !obj.Key.endsWith('manifest.json')
)?.Key;
if (!jsonKey) throw new Error(`No JSON output found in BDA output prefix: ${prefix}`);
return JSON.parse(await s3GetText(bucket, jsonKey));
}
const outputKey = docOutput.segment_metadata[0].standard_output_path;
return JSON.parse(await s3GetText(bucket, outputKey));
}
async function s3GetText(bucket: string, key: string): Promise<string> {
const response = await s3.send(new GetObjectCommand({ Bucket: bucket, Key: key }));
if (!response.Body) throw new Error(`Empty S3 response for s3://${bucket}/${key}`);
return response.Body.transformToString('utf-8');
}
Your task role needs s3:GetObject and s3:ListBucket on the output bucket to read back results. The same bucket policy granting Bedrock write access (from the previous section) does not automatically grant your application role read access — both grants are needed independently.
EventBridge notification instead of polling
For high-volume or long-running jobs, replace the polling loop with EventBridge notifications. Set notificationConfiguration.eventBridgeConfiguration.eventBridgeEnabled = true in the invocation request, then configure an EventBridge rule that routes BDA completion events to your handler (Lambda, SQS, or EventBridge Pipes).
// Submit with EventBridge notifications enabled
const response = await runtime.send(new InvokeDataAutomationAsyncCommand({
inputConfiguration: { s3Uri: inputS3Uri },
outputConfiguration: { s3Uri: `s3://${OUTPUT_BUCKET}/bda-output/${jobId}/` },
dataAutomationProfileArn: PROFILE_ARN,
notificationConfiguration: {
eventBridgeConfiguration: { eventBridgeEnabled: true },
},
clientToken: `job-${jobId}`,
}));
// EventBridge event shape (source: "aws.bedrock-data-automation"):
// {
// "source": "aws.bedrock-data-automation",
// "detail-type": "Bedrock Data Automation Job State Change",
// "detail": {
// "invocationArn": "arn:aws:bedrock:us-east-1:123456789012:data-automation-invocation/...",
// "status": "Success", // or "ClientError" / "ServiceError"
// "outputConfiguration": {
// "s3Uri": "s3://bucket/bda-output/job-123/"
// }
// }
// }
EventBridge notification is especially valuable when processing large batches of documents — you can submit thousands of jobs concurrently and process completions through an SQS queue rather than maintaining thousands of open polling loops. See EventBridge patterns and SQS tool queues for queue-based processing patterns.
IAM permissions summary
BDA integration requires permissions on three distinct layers: the Bedrock action itself, S3 read on input, and S3 write on output (via bucket policy). Missing any one of these produces failures that look different — an IAM action denial on the Bedrock call surface as an immediate SDK exception; missing S3 write for output produces a ClientError on the job status after several seconds of apparent progress.
// IAM policy for the MCP server task/Lambda role
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "BDAInvoke",
"Effect": "Allow",
"Action": [
"bedrock:InvokeDataAutomationAsync",
"bedrock:GetDataAutomationStatus"
],
"Resource": "*"
},
{
"Sid": "InputS3Read",
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:HeadObject"],
"Resource": "arn:aws:s3:::MY-INPUT-BUCKET/*"
},
{
"Sid": "OutputS3Read",
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:ListBucket"],
"Resource": [
"arn:aws:s3:::MY-OUTPUT-BUCKET",
"arn:aws:s3:::MY-OUTPUT-BUCKET/*"
]
},
{
"Sid": "BlueprintRead", // Only needed if using custom blueprints
"Effect": "Allow",
"Action": ["bedrock:GetBlueprint", "bedrock:ListBlueprints"],
"Resource": "*"
}
]
}
Complete MCP tool: extract_document
The following example wraps the full BDA invocation + polling flow into a single MCP tool. For production, prefer the two-tool (submit + poll) pattern described earlier to avoid blocking the agent loop on long jobs — but this single-tool version works well for quick prototyping or when the calling agent can tolerate 30–120 second tool call latency.
import {
BedrockDataAutomationRuntimeClient,
InvokeDataAutomationAsyncCommand,
GetDataAutomationStatusCommand,
} from '@aws-sdk/client-bedrock-data-automation-runtime';
import { S3Client, GetObjectCommand } from '@aws-sdk/client-s3';
import { randomUUID } from 'node:crypto';
const runtime = new BedrockDataAutomationRuntimeClient({ region: process.env.AWS_REGION! });
const s3 = new S3Client({ region: process.env.AWS_REGION! });
const PROFILE_ARN = process.env.BDA_PROFILE_ARN!;
const OUTPUT_BUCKET = process.env.BDA_OUTPUT_BUCKET!;
export async function extractDocumentTool(input: { s3_uri: string }): Promise<unknown> {
const jobId = randomUUID();
const outputPrefix = `bda-output/${jobId}/`;
// 1. Submit job
const submitResp = await runtime.send(new InvokeDataAutomationAsyncCommand({
inputConfiguration: { s3Uri: input.s3_uri },
outputConfiguration: { s3Uri: `s3://${OUTPUT_BUCKET}/${outputPrefix}` },
dataAutomationProfileArn: PROFILE_ARN,
clientToken: `mcp-extract-${jobId}`,
}));
const invocationArn = submitResp.invocationArn!;
// 2. Poll for completion (5s intervals, 3-minute timeout)
const startMs = Date.now();
while (Date.now() - startMs < 180_000) {
await new Promise(r => setTimeout(r, 5_000));
const statusResp = await runtime.send(
new GetDataAutomationStatusCommand({ invocationArn })
);
if (statusResp.status === 'Success') {
// 3. Fetch output from S3
const outputUri = statusResp.outputConfiguration!.s3Uri!;
const url = new URL(outputUri.replace('s3://', 'https://'));
const bucket = url.hostname;
const prefix = url.pathname.replace(/^\//, '');
const outputResp = await s3.send(new GetObjectCommand({
Bucket: bucket,
Key: `${prefix}document_output.json`,
}));
const text = await outputResp.Body!.transformToString('utf-8');
return JSON.parse(text);
}
if (statusResp.status === 'ClientError' || statusResp.status === 'ServiceError') {
throw new Error(
`BDA extraction failed (${statusResp.status}): ${statusResp.errorMessage}`
);
}
// status is 'Created' or 'InProgress' — continue polling
}
throw new Error(`BDA extraction timed out after 3 minutes for job ${invocationArn}`);
}
Key gotchas
- Always async — no synchronous option.
InvokeDataAutomationAsyncCommandreturns immediately with aninvocationArn. There is noInvokeDataAutomationSyncCommand. Any MCP tool that calls BDA must handle the async lifecycle. - Control-plane vs runtime package split. Blueprint CRUD uses
BedrockDataAutomationClientfrom@aws-sdk/client-bedrock-data-automation. Job submission and polling useBedrockDataAutomationRuntimeClientfrom@aws-sdk/client-bedrock-data-automation-runtime. Using the wrong client for either operation returnsUnknownOperation. - S3 bucket policy required for output. BDA writes output as the Bedrock service principal, not as your IAM role. Your task role's
s3:PutObjectpermission alone is insufficient. The output bucket must have a bucket policy grantingbedrock.amazonaws.comwrite access withaws:SourceAccountcondition. Failure surface:ClientErroron the job, not an exception duringInvokeDataAutomationAsyncCommand. - Input bucket must be in the same region. BDA reads input using the same region endpoint as the runtime client. Cross-region input S3 URIs result in a
ClientErrorwith an access or geography error message. Uses3.copyObjectto stage the file into the same region if your source bucket is different. - ClientError is not retryable without fixing the cause. Distinguish
ClientError(IAM, S3 policy, unsupported format, file size limit) fromServiceError(AWS-side, transient). Retrying aClientErrorin a loop wastes time and money — log theerrorTypeanderrorMessagefields to understand the root cause. - Output S3 URI in status response vs output prefix in invocation. The
outputConfiguration.s3UriinGetDataAutomationStatusCommandresponse is the same prefix you specified — it does not give you the exact key of the output file. You must list the prefix or know the BDA file naming convention (job_manifest.jsonat root, modality-specific JSON files at subpaths). - clientToken window is 1 hour. If you retry with the same
clientTokenwithin one hour, BDA returns the sameinvocationArnwithout submitting a duplicate job. After one hour, the same token creates a new job. Use a deterministic token (e.g., SHA-256 of the input S3 URI + timestamp truncated to hour) to get safe idempotency without duplicate charges.