Amazon Bedrock · InvokeDataAutomationAsyncCommand, CreateBlueprintCommand, GetDataAutomationStatusCommand, job_manifest.json · 2026-11-28 · Amazon Bedrock Data Automation arc
Amazon Bedrock Data Automation for MCP Servers: Async Invocation, Blueprints, Document Processing, and Output Parsing
Four BDA deep-dive pages synthesised into a complete production playbook for MCP server developers — BDA overview (InvokeDataAutomationAsyncCommand from @aws-sdk/client-bedrock-data-automation-runtime submits a job and returns an invocationArn immediately with no synchronous option; GetDataAutomationStatusCommand polls until status === "Success"; two separate SDK packages where the runtime package handles invocations and the control-plane package handles blueprints — using the wrong client raises UnknownOperation; S3 output bucket requires a bucket policy granting bedrock.amazonaws.com write access via service principal not your task role — the most common first-deployment failure surface; dataAutomationProfileArn selects the extraction model; ClientError is not retryable without fixing the root cause, ServiceError is retryable; two-tool MCP pattern submit + poll to avoid blocking the agent loop), BDA blueprints (custom field extraction uses CreateBlueprintCommand from the control-plane package; schema field is a JSON string — pass JSON.stringify(schemaObject) or face an immediate ValidationException; inferenceType of "explicit" for stated values and "generative" for inferred values; field description quality drives extraction accuracy more than any other factor; UpdateBlueprintCommand replaces the entire schema — always read with GetBlueprintCommand first, merge changes, then write back; CreateBlueprintVersionCommand promotes to an immutable LIVE snapshot; blueprintVersion is a string not a number; always pin blueprintVersion explicitly in production invocations; DeleteBlueprintCommand destroys all versions with no confirmation), BDA document processing (seven supported formats: PDF up to 150 MB, DOCX/XLSX/XLS up to 50 MB, CSV/HTML/TXT up to 10 MB; input S3 bucket must be in the same region as the BDA runtime endpoint or every job returns ClientError; standard output includes text, Markdown, tables, key-value pairs, figures, and summary; image-based PDFs are OCR-processed — quality depends on scan resolution; XLSX multi-sheet workbooks produce one page entry per sheet; tables are cell-indexed not row-indexed — reconstruct the 2D grid yourself; key-value pair keys are raw document labels, not normalized to any schema; Markdown output is better than plain text for LLM downstream use), and BDA output parsing (outputConfiguration.s3Uri in the status response is a prefix not a file path — navigate via job_manifest.json at the prefix root to find the exact S3 key; custom blueprint output lives in custom_output/document_output.json and every field is wrapped with a .value key and a confidence score; confidence below 0.7 indicates uncertain extraction; cache results in S3 keyed by content hash to avoid paying per-page charges for the same document twice; EventBridge notifications replace polling for high-volume deployments). Fourteen consolidated production gotchas at the end.
Why Bedrock Data Automation belongs in your MCP server toolkit
An MCP server operating in a document-rich environment — processing uploaded invoices, extracting fields from medical records, parsing contract clauses for a legal workflow — needs a managed service that can handle unstructured content reliably without requiring a custom fine-tuned model. Amazon Bedrock Data Automation fills that role: it takes a file from S3, runs foundation model extraction internally, and writes structured JSON back to S3. The calling code deals only with S3 URIs and a polling loop.
The service has a reputation for a steep onboarding gradient because its failure modes are unusual. Errors that surface as immediate SDK exceptions during ConverseCommand calls — wrong IAM, missing parameters — instead surface as ClientError on a job status poll, 10–90 seconds after submission. The output is split across two SDK packages, two S3 files, and a manifest that must be navigated to find the actual data. Blueprints require a schema argument that is a JSON string not a JSON object, and version promotion uses a string-typed version identifier that breaks anyone who compares it numerically.
This guide covers all four dimensions of BDA integration in production-ready depth: the core async invocation contract, custom extraction blueprints, document-type-specific processing, and output parsing. It ends with fourteen production gotchas consolidated from across all four topic areas.
Part 1: The Async Invocation Contract
BDA has no synchronous invocation path. InvokeDataAutomationAsyncCommand always returns an invocationArn immediately — the actual extraction runs asynchronously. Any code that expects a result from the invocation call itself will not work. The only way to get output is to poll GetDataAutomationStatusCommand until status === "Success", then read the output from S3.
The two-package SDK split
BDA uses two separate AWS SDK packages that are not interchangeable. 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) handles blueprints (custom extraction schemas). Using the control-plane client to submit a job raises UnknownOperation immediately — a confusing error because the client type looks similar. Install both packages and instantiate them separately at startup.
import {
BedrockDataAutomationClient, // control-plane: blueprints only
CreateBlueprintCommand,
GetBlueprintCommand,
} from '@aws-sdk/client-bedrock-data-automation';
import {
BedrockDataAutomationRuntimeClient, // runtime: invocations and polling
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',
});
Submitting a job
InvokeDataAutomationAsyncCommand requires three fields: inputConfiguration.s3Uri pointing to the source file, outputConfiguration.s3Uri pointing to an S3 prefix where BDA writes results, and dataAutomationProfileArn selecting which foundation model powers the extraction. The optional clientToken provides idempotency — the same token within a one-hour window returns the same invocationArn without submitting a duplicate job.
const PROFILE_ARN =
'arn:aws:bedrock:us-east-1::data-automation-profile/anthropic.claude-3-haiku-20240307-v1:0';
const OUTPUT_BUCKET = process.env.BDA_OUTPUT_BUCKET!;
async function submitJob(inputS3Uri: string, jobId: string): Promise<string> {
const response = await runtime.send(new InvokeDataAutomationAsyncCommand({
inputConfiguration: { s3Uri: inputS3Uri },
outputConfiguration: { s3Uri: `s3://${OUTPUT_BUCKET}/bda-output/${jobId}/` },
dataAutomationProfileArn: PROFILE_ARN,
clientToken: `job-${jobId}`,
}));
if (!response.invocationArn) {
throw new Error('BDA did not return an invocationArn');
}
return response.invocationArn;
}
Profile ARNs follow the pattern arn:aws:bedrock:REGION::data-automation-profile/MODEL_ID (note the double-colon — no account ID segment). For higher-accuracy extraction on complex documents, use a Claude 3.5 Sonnet profile: arn:aws:bedrock:us-east-1::data-automation-profile/anthropic.claude-3-5-sonnet-20241022-v2:0. Profile availability varies by region — use the ARN from the BDA documentation for your specific deployment region. Do not confuse data automation profile ARNs with cross-region inference profile ARNs from the Bedrock inference profiles feature — they are different resources.
Polling for completion
GetDataAutomationStatusCommand takes an invocationArn and returns the current status. Status values: Created (queued), InProgress (running), Success (done), ServiceError (AWS-side failure — retryable), ClientError (configuration problem — not retryable without fixing the root cause). Poll at 5-second intervals; most small-to-medium documents complete within 10–60 seconds.
async function waitForJob(
invocationArn: string,
timeoutMs = 300_000,
pollIntervalMs = 5_000,
): Promise<string> {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
const response = await runtime.send(
new GetDataAutomationStatusCommand({ invocationArn })
);
switch (response.status) {
case 'Success': {
const outputUri = response.outputConfiguration?.s3Uri;
if (!outputUri) throw new Error('Success status but no output S3 URI');
return outputUri;
}
case 'ClientError':
throw new Error(
`BDA ClientError (not retryable): ${response.errorType} — ${response.errorMessage}`
);
case 'ServiceError':
throw new Error(
`BDA ServiceError (retryable): ${response.errorType} — ${response.errorMessage}`
);
default:
await new Promise(r => setTimeout(r, pollIntervalMs));
}
}
throw new Error(`BDA job timed out after ${timeoutMs}ms: ${invocationArn}`);
}
The S3 bucket policy requirement
BDA writes output using the Bedrock service principal (bedrock.amazonaws.com), not your IAM task role. Your task role's s3:PutObject permission alone is insufficient — the output bucket must have a resource-based bucket policy granting the Bedrock service principal write access. Missing this policy surfaces as a ClientError on the job status after several seconds of apparent progress, not as an SDK exception during InvokeDataAutomationAsyncCommand. This delay is why the missing policy is the most common first-deployment failure mode: developers test the invocation call, see it succeed, and only discover the problem when the first poll returns ClientError.
// Required on the output S3 bucket
{
"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" }
}
}]
}
The aws:SourceAccount condition prevents the bucket from being used as an exfiltration target by other AWS accounts' BDA jobs. Always include it. The IAM policy on your task role separately needs s3:GetObject and s3:ListBucket on the output bucket to read back results — the bucket policy granting Bedrock write access does not grant your application role read access.
Two-tool MCP pattern for long-running jobs
BDA jobs take 10–120 seconds for most documents. Blocking the agent loop inside a single tool call for that duration produces poor user experience and ties up MCP server resources. The production pattern is two tools: one to submit the job and return the invocationArn as a job ID, and a second to check status and return results when complete. The agent can call the second tool multiple times if the job is still running.
// 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 process' },
},
required: ['s3_uri'],
},
async execute({ s3_uri }) {
const jobId = randomUUID();
const invocationArn = await submitJob(s3_uri, jobId);
return { job_id: invocationArn, status: 'submitted' };
}
}
// Tool 2: get_extraction_result
{
name: 'get_extraction_result',
description: 'Check status of a document extraction job. Returns 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 fetchAndParseOutput(statusResp.outputConfiguration!.s3Uri!);
return { status: 'complete', data: output };
}
if (statusResp.status === 'ClientError' || statusResp.status === 'ServiceError') {
return { status: 'failed', error: `${statusResp.errorType}: ${statusResp.errorMessage}` };
}
return { status: statusResp.status.toLowerCase() }; // 'created' or 'inprogress'
}
}
Part 2: Custom Blueprints — Defining Exactly What to Extract
Without a blueprint, BDA runs standard extraction: it returns all document text, tables, form fields, figures, and a summary. Standard extraction is the right choice for general document parsing where you want everything. Blueprints are for domain-specific extraction — when you need specific named fields from documents of a known type. An invoice blueprint extracts invoice_number, vendor_name, line_items, and total_amount. A medical note blueprint extracts diagnosis_codes, prescribed_medications, and follow_up_date. BDA applies the blueprint's JSON schema to the document and returns the extracted fields under a custom_output key alongside (or instead of) standard output.
CreateBlueprintCommand — the schema-as-string gotcha
Blueprints live in the control-plane package. CreateBlueprintCommand requires blueprintName (unique per account+region), type ('DOCUMENT' or 'IMAGE'), and schema. The schema field is a JSON string, not a JSON object. Pass JSON.stringify(schemaObject) — passing a raw object raises an immediate ValidationException: schema must be a string. This is the most disorienting blueprint gotcha because every other AWS SDK command accepts structured objects, not serialized strings.
import {
BedrockDataAutomationClient,
CreateBlueprintCommand,
} from '@aws-sdk/client-bedrock-data-automation';
const invoiceSchema = {
description: 'Extract structured fields from vendor invoices',
type: 'object',
properties: {
invoice_number: {
type: 'string',
description: 'Unique invoice identifier. Usually labeled "Invoice #", "Invoice No.", or "Reference". Return null if not found.',
inferenceType: 'explicit',
},
vendor_name: {
type: 'string',
description: 'Name of the company or person issuing the invoice',
inferenceType: 'explicit',
},
invoice_date: {
type: 'string',
description: 'Date the invoice was issued in ISO 8601 format (YYYY-MM-DD)',
inferenceType: 'explicit',
},
total_amount: {
type: 'number',
description: 'Final total amount due as a numeric value without currency symbols or commas. Example: 1250.00 not "$1,250.00". Return 0 if undeterminable.',
inferenceType: 'explicit',
},
line_items: {
type: 'array',
description: 'Individual line items on the invoice',
items: {
type: 'object',
properties: {
description: { type: 'string', description: 'Product or service description' },
quantity: { type: 'number', description: 'Quantity ordered or hours worked' },
unit_price: { type: 'number', description: 'Price per unit or hourly rate' },
total: { type: 'number', description: 'Line item total (quantity × unit_price)' },
},
},
},
payment_terms: {
type: 'string',
description: 'Payment terms stated on invoice (e.g. "Net 30", "Due on receipt")',
inferenceType: 'generative', // may require inference from document context
},
},
};
const response = await controlPlane.send(new CreateBlueprintCommand({
blueprintName: 'invoice-extraction-v1',
type: 'DOCUMENT',
blueprintStage: 'DEVELOPMENT', // always start in DEVELOPMENT
schema: JSON.stringify(invoiceSchema), // MUST be JSON.stringify() — not the raw object
clientToken: 'create-invoice-blueprint-v1',
}));
const blueprintArn = response.blueprint!.blueprintArn!;
// arn:aws:bedrock:us-east-1:123456789012:data-automation-blueprint/BLUEPRINT_ID
// Persist this ARN — needed for all subsequent operations
inferenceType and field descriptions
The inferenceType property on each field controls how BDA finds the value. 'explicit' tells BDA the value is directly stated somewhere in the document. 'generative' tells BDA it may need to synthesize or infer the value from document context. When in doubt, start with 'explicit' — it produces more reliable, verifiable extractions and avoids hallucinated values for missing fields.
The description field is the highest-leverage part of schema design. BDA uses field descriptions to match schema properties against document content. A vague description like "Invoice number" produces inconsistent results. A precise description that specifies the expected format, what to return when missing, and alternative phrasings the field might appear under produces consistent results across varied invoice layouts. For numeric fields, always specify that the value should be a numeric value without currency symbols or commas — BDA will otherwise sometimes return "$1,250.00" as a string for a field declared as type: 'number'.
DEVELOPMENT → LIVE lifecycle
Blueprints start in DEVELOPMENT stage. DEVELOPMENT blueprints can be attached to invocations during development, but they are blocked in production invocations (those using production data automation profile ARNs). To use a blueprint in production, call CreateBlueprintVersionCommand to create an immutable LIVE snapshot. The snapshot gets a numeric string version: "1", "2", etc. The version is a string, not a number — the same gotcha as Bedrock Guardrails versioning.
import { CreateBlueprintVersionCommand } from '@aws-sdk/client-bedrock-data-automation';
const promoteResp = await controlPlane.send(new CreateBlueprintVersionCommand({
blueprintArn,
clientToken: `promote-${blueprintArn.split('/').pop()}-${Date.now()}`,
}));
const version = promoteResp.blueprint!.blueprintVersion!;
// version is a string — e.g. "1", "2"
// Guard against accidental numeric comparison:
if (typeof version !== 'string') {
throw new Error(`Unexpected: blueprintVersion type is ${typeof version}`);
}
console.log(`Blueprint promoted to LIVE version: ${version}`);
In production invocations, always pin the specific version via blueprintVersion. Do not rely on blueprintStage: 'LIVE' alone — that always picks up the most recently promoted version and silently changes extraction behavior when you promote a new version without a deployment gate.
// Production invocation with pinned blueprint version
const response = await runtime.send(new InvokeDataAutomationAsyncCommand({
inputConfiguration: { s3Uri: inputS3Uri },
outputConfiguration: { s3Uri: `s3://${OUTPUT_BUCKET}/output/${jobId}/` },
dataAutomationProfileArn: PROFILE_ARN,
blueprintConfiguration: {
blueprints: [
{
blueprintArn: process.env.BDA_BLUEPRINT_ARN!,
blueprintVersion: process.env.BDA_BLUEPRINT_VERSION!, // "2" — string from env
// Never: blueprintStage: 'LIVE' — picks up latest without deployment gate
// Never: blueprintStage: 'DEVELOPMENT' — blocked in production
},
],
},
clientToken: `extract-${jobId}`,
}));
Updating blueprints — full replacement, not partial patch
UpdateBlueprintCommand replaces the entire blueprint schema. Omitting a property that existed before silently deletes it. Always read the current schema with GetBlueprintCommand first, merge your changes programmatically, then write back the full updated schema. The GetBlueprintCommand response's blueprint.schema field is a JSON string — call JSON.parse() before merging.
async function addFieldToBlueprint(
blueprintArn: string,
newField: string,
fieldSchema: object,
): Promise<void> {
// 1. Read current schema — ALWAYS do this before updating
const getResp = await controlPlane.send(new GetBlueprintCommand({
blueprintArn,
blueprintStage: 'DEVELOPMENT',
}));
const currentSchema = JSON.parse(getResp.blueprint!.schema!); // schema is a string
// 2. Merge new field
currentSchema.properties = {
...currentSchema.properties,
[newField]: fieldSchema,
};
// 3. Write back the full updated schema — still must be JSON.stringify()
await controlPlane.send(new UpdateBlueprintCommand({
blueprintArn,
schema: JSON.stringify(currentSchema),
}));
}
UpdateBlueprintCommand always targets DEVELOPMENT — you cannot update an existing LIVE version. After updating and testing DEVELOPMENT, call CreateBlueprintVersionCommand again to create a new LIVE snapshot with an incremented version number. For DeleteBlueprintCommand: it destroys the blueprint and all versions with no confirmation prompt and no recycle bin. Restrict the IAM action bedrock:DeleteBlueprint to deployment pipeline roles only — application and MCP server task roles should have only bedrock:GetBlueprint and bedrock:ListBlueprints.
Part 3: Document Processing — Formats, Regions, Tables, and Forms
BDA supports seven document formats. Knowing the limits, the extraction characteristics, and the common failure patterns for each format is what makes the difference between a document processing MCP tool that works in demos and one that handles real-world documents reliably.
Supported formats and limits
| Format | Extension | Max Size | Key Notes |
|---|---|---|---|
| 150 MB | Text PDFs and scanned (image-based) PDFs both supported; 100-page max | ||
| Word | .docx | 50 MB | Embedded images, tables, and tracked changes all processed |
| Excel | .xlsx / .xls | 50 MB | Multi-sheet workbooks: one page output per sheet |
| CSV | .csv | 10 MB | Tabular; output as a single-table document |
| HTML | .html | 10 MB | Rendered HTML; <table> elements extracted as tables |
| Plain text | .txt | 10 MB | UTF-8; treated as single-page document |
For PDFs longer than 100 pages, split into 100-page segments and submit separate invocations. BDA determines document type from file content, not extension — a PDF saved as .txt is still processed as a PDF — but naming files with the correct extension avoids edge cases in BDA's content-detection step.
The same-region S3 requirement
The input S3 URI must point to a bucket in the same AWS region as your BDA runtime endpoint. Cross-region input produces a ClientError on the job status with an error message that often says "AccessDenied" rather than explaining the region mismatch. This is the most surprising document processing gotcha because the error message does not name the actual problem. If your application stores documents in a different region, copy them to a staging bucket in the BDA deployment region before submitting.
const BDA_REGION = process.env.AWS_REGION ?? 'us-east-1';
const STAGING_BUCKET = process.env.BDA_STAGING_BUCKET!; // in BDA_REGION
async function stageForBda(sourceS3Uri: string, destKey: string): Promise<string> {
const source = new URL(sourceS3Uri.replace('s3://', 'https://'));
const sourceBucket = source.hostname;
const sourceKey = source.pathname.replace(/^\//, '');
// If source bucket is known to be in a different region, copy to staging
const sourceS3 = new S3Client({ region: 'us-west-2' }); // or detect at runtime
await sourceS3.send(new CopyObjectCommand({
Bucket: STAGING_BUCKET,
Key: destKey,
CopySource: `${sourceBucket}/${sourceKey}`,
}));
return `s3://${STAGING_BUCKET}/${destKey}`;
}
Standard output components
Without a blueprint, BDA produces a structured output JSON with the following components for every document:
- Document text (
document.representation.text) — Full extracted text as a plain string. - Markdown representation (
document.representation.markdown) — The same content formatted as Markdown with headers, lists, and table syntax. Prefer this over plain text when feeding content to a foundation model — Markdown preserves table structure and section context that the LLM uses for reasoning. - Tables (
document.tables) — Each table as a cell-indexed array. Tables that span multiple pages are merged into a single table object. - Key-value pairs (
document.key_value_pairs) — Form fields and labeled data like "Invoice Date: 2024-01-15". - Figures (
document.figures) — Text descriptions of charts, graphs, and embedded images. BDA describes figure content in text — it does not return image bytes. - Summary (
document.summary) — LLM-generated document summary. - Pages (
document.pages) — Per-page breakdown containing the page's portion of text, tables, and key-value pairs.
Extracting tables — the cell-indexed gotcha
BDA table output is not a row array. It is a flat cells array where each cell has row_index and column_index. Row 0 is typically the header row. You must reconstruct the 2D grid yourself. This catches developers who check the BDA output format documentation but skip the cells section and assume a row-based structure.
interface BdaTableCell {
row_index: number;
column_index: number;
content: string | null;
is_header?: boolean;
}
function reconstructTable(cells: BdaTableCell[]): {
headers: string[];
rows: Array<Array<string | null>>;
} {
const maxRow = Math.max(...cells.map(c => c.row_index));
const maxCol = Math.max(...cells.map(c => c.column_index));
// Build 2D grid
const grid: Array<Array<string | null>> = Array.from(
{ length: maxRow + 1 },
() => Array(maxCol + 1).fill(null)
);
for (const cell of cells) {
grid[cell.row_index][cell.column_index] = cell.content ?? null;
}
const headers = grid[0]?.map(h => h ?? '') ?? [];
const rows = grid.slice(1);
return { headers, rows };
}
// Convert to keyed objects
function tableToObjects(
cells: BdaTableCell[]
): Array<Record<string, string | null>> {
const { headers, rows } = reconstructTable(cells);
return rows.map(row =>
Object.fromEntries(headers.map((h, i) => [h, row[i] ?? null]))
);
}
Key-value pair extraction
BDA identifies field-label patterns and extracts them as key-value pairs with a confidence score. Each pair has a key.content (e.g. "Invoice Date") and value.content (e.g. "January 15, 2024"). The keys are raw document labels — not normalized to any schema. "Invoice #", "INV NO", and "Reference Number" might all appear as separate keys across different invoice layouts when they represent the same field. For high-reliability production use, attach a custom blueprint to normalize field names, or implement a post-processing normalization step. Filter by confidence >= 0.7 for production — low-confidence pairs often indicate ambiguous layout where BDA was uncertain about which label belongs to which value.
function extractFormFields(
documentOutput: { document?: { key_value_pairs?: Array<{
key: { content?: string };
value: { content?: string };
confidence?: number;
}> } },
minConfidence = 0.7,
): Record<string, string> {
const fields: Record<string, string> = {};
for (const kvp of documentOutput.document?.key_value_pairs ?? []) {
if ((kvp.confidence ?? 1.0) < minConfidence) continue;
const key = kvp.key?.content?.trim();
const value = kvp.value?.content?.trim();
if (key && value) {
// Normalize key: lowercase, whitespace to underscore, strip non-alphanumeric
const normalizedKey = key
.toLowerCase()
.replace(/\s+/g, '_')
.replace(/[^a-z0-9_]/g, '');
fields[normalizedKey] = value;
}
}
return fields;
}
Image-based PDFs and XLSX multi-sheet workbooks
Scanned PDFs without selectable text are processed via OCR — BDA applies orientation correction, deskew, and contrast normalization before running OCR. Quality is good for high-resolution scans (300+ DPI) but degrades significantly below 150 DPI. The output format is identical to text PDF output; BDA does not explicitly indicate whether OCR was applied. For mission-critical OCR on scanned documents with low scan quality, evaluate Amazon Textract, which provides per-character confidence scores and geometric bounding-box information. See Textract for MCP servers for the Textract approach.
Excel workbooks with multiple sheets produce one page entry per sheet in the output — not separate invocations. Each sheet's page_index (0-based) maps to sheet order in the original workbook. If you need to apply different blueprints to different sheets, split the workbook into separate single-sheet XLSX files before submitting.
Part 4: Output Parsing — Manifests, Standard Fields, Custom Fields, and Caching
BDA output is not a single JSON file at a known path. It is a directory of files under the S3 prefix you specified, with a manifest file at the root that maps to the actual output files. The outputConfiguration.s3Uri in the status response is that prefix — it does not point to the extracted JSON. Getting this wrong produces a 404 from S3 when you try to read the results.
Navigating job_manifest.json
Always read job_manifest.json at the prefix root first. The manifest's output_metadata[0].segment_metadata[0] entry contains standard_output_path and (if a blueprint was attached) custom_output_path — these are the full S3 keys of the respective output files, relative to the bucket root.
interface BdaManifest {
output_metadata: Array<{
segment_metadata: Array<{
asset_type: 'DOCUMENT' | 'IMAGE' | 'AUDIO' | 'VIDEO';
standard_output_path?: string; // S3 key of standard_output/document_output.json
custom_output_path?: string; // S3 key of custom_output/document_output.json
asset_metadata_path?: string; // S3 key of metadata/asset_metadata.json
}>;
}>;
}
const s3 = new S3Client({ region: process.env.AWS_REGION! });
function parseS3Uri(uri: string): { bucket: string; prefix: string } {
const url = new URL(uri.replace('s3://', 'https://'));
return {
bucket: url.hostname,
prefix: url.pathname.replace(/^\//, ''),
};
}
async function s3GetJson(bucket: string, key: string): Promise<unknown> {
const response = await s3.send(new GetObjectCommand({ Bucket: bucket, Key: key }));
return JSON.parse(await response.Body!.transformToString('utf-8'));
}
async function readOutputFiles(outputS3Uri: string): Promise<{
standard: unknown;
custom?: unknown;
}> {
const { bucket, prefix } = parseS3Uri(outputS3Uri);
// 1. Read manifest at prefix root
const manifest = await s3GetJson(bucket, `${prefix}job_manifest.json`) as BdaManifest;
const segment = manifest.output_metadata?.[0]?.segment_metadata?.[0];
if (!segment) {
throw new Error('Manifest missing output_metadata[0].segment_metadata[0]');
}
// 2. Read standard output
const standard = segment.standard_output_path
? await s3GetJson(bucket, segment.standard_output_path)
: null;
// 3. Read custom output if blueprint was attached
const custom = segment.custom_output_path
? await s3GetJson(bucket, segment.custom_output_path)
: undefined;
return { standard, custom };
}
Standard output JSON structure
The standard output JSON follows a consistent schema regardless of document type:
interface BdaStandardOutput {
metadata: {
content_type: string; // "application/pdf", "application/docx", etc.
document_class: {
type: string; // "INVOICE", "CONTRACT", "RECEIPT", etc.
confidence?: number;
};
total_pages: number;
};
document: {
statistics: {
pages: number;
tables: number;
figures: number;
key_value_pairs: number;
};
representation: {
text: string; // Full plain text
markdown: string; // Markdown with headers, tables, lists
};
summary: string;
pages: BdaPage[];
tables: BdaTableOutput[]; // All tables across all pages
key_value_pairs: BdaKvPair[];
figures: BdaFigure[];
};
}
Custom blueprint output — the .value wrapper
Custom blueprint output lives in custom_output/document_output.json. The structure is different from standard output: each field you defined in the blueprint schema appears as an object with a value key (the extracted content) and a confidence score. The wrapping is consistent — even scalar string fields are wrapped. Never read output.invoice_number directly; always read output.invoice_number.value. For array fields (line items), the top-level array element is wrapped with .value, and each sub-field inside the array objects is also individually wrapped.
// Custom output shape for the invoice blueprint:
// {
// "metadata": { "blueprint_name": "invoice-extraction-v1", "blueprint_version": "2" },
// "output": {
// "invoice_number": { "value": "INV-2024-001", "confidence": 0.98 },
// "total_amount": { "value": 4250.00, "confidence": 0.97 },
// "line_items": {
// "value": [
// {
// "description": { "value": "Consulting services", "confidence": 0.94 },
// "quantity": { "value": 10, "confidence": 0.99 },
// "unit_price": { "value": 300.0, "confidence": 0.98 },
// "total": { "value": 3000.0, "confidence": 0.96 }
// }
// ]
// }
// }
// }
function extractCustomFields(
customOutput: { output?: Record<string, { value: unknown; confidence?: number }> },
minConfidence = 0.7,
): Record<string, unknown> {
const result: Record<string, unknown> = {};
for (const [fieldName, fieldData] of Object.entries(customOutput.output ?? {})) {
const confidence = fieldData.confidence ?? 1.0;
if (confidence < minConfidence) {
console.warn(`Low confidence for field '${fieldName}': ${confidence.toFixed(2)}`);
continue;
}
const rawValue = fieldData.value;
if (Array.isArray(rawValue)) {
// Array fields: unwrap each sub-field inside each item
result[fieldName] = rawValue.map(item => {
const row: Record<string, unknown> = {};
for (const [subKey, subData] of Object.entries(item ?? {})) {
row[subKey] = (subData as { value: unknown })?.value ?? null;
}
return row;
});
} else {
result[fieldName] = rawValue;
}
}
return result;
}
Feeding BDA Markdown to Bedrock Converse for downstream reasoning
A powerful MCP server pattern: use BDA to extract and structure a document, then pass the Markdown representation to a Claude model for downstream reasoning — answering questions about the document, verifying extracted fields, or generating a custom summary. The Markdown output from BDA preserves table structure as pipe-separated syntax, section headers, and list formatting in a way that Claude processes accurately. Plain text from representation.text flattens this structure and reduces LLM reasoning quality on complex multi-section documents.
import { BedrockRuntimeClient, ConverseCommand } from '@aws-sdk/client-bedrock-runtime';
const bedrock = new BedrockRuntimeClient({ region: process.env.AWS_REGION! });
async function askAboutDocument(
standardOutput: BdaStandardOutput,
question: string,
): Promise<string> {
const markdown = standardOutput.document.representation.markdown;
const response = await bedrock.send(new ConverseCommand({
modelId: 'anthropic.claude-3-5-haiku-20241022',
messages: [{
role: 'user',
content: [{
type: 'text',
text: `Document content:\n\n---\n${markdown}\n---\n\nQuestion: ${question}`,
}],
}],
inferenceConfig: { maxTokens: 1024 },
}));
const content = response.output?.message?.content?.[0];
if (content?.type === 'text') return content.text;
throw new Error('Unexpected Converse response shape');
}
Caching to avoid repeated per-page charges
BDA charges per page processed. The same document analyzed five times across five agent sessions costs 5× the extraction fee. Cache extraction results in S3 keyed by a hash derived from the input document's S3 ETag — a stable content fingerprint for non-multipart uploads. Before submitting a new BDA job, check the cache. This pattern also eliminates 10–90 seconds of polling latency for repeat document accesses.
import { createHash } from 'node:crypto';
const CACHE_BUCKET = process.env.BDA_CACHE_BUCKET!;
const CACHE_TTL_DAYS = 30;
async function hashDocument(bucket: string, key: string): Promise<string> {
const head = await s3.send(new HeadObjectCommand({ Bucket: bucket, Key: key }));
const etag = head.ETag?.replace(/"/g, '') ?? '';
return createHash('sha256').update(`${bucket}/${key}:${etag}`).digest('hex').slice(0, 16);
}
async function getCache(cacheKey: string): Promise<unknown | null> {
try {
const response = await s3.send(new GetObjectCommand({
Bucket: CACHE_BUCKET,
Key: `bda-cache/${cacheKey}.json`,
}));
const entry: { extracted_at: string; output: unknown } =
JSON.parse(await response.Body!.transformToString('utf-8'));
const ageMs = Date.now() - new Date(entry.extracted_at).getTime();
if (ageMs > CACHE_TTL_DAYS * 86_400_000) return null;
return entry.output;
} catch (err: unknown) {
if ((err as { name?: string }).name === 'NoSuchKey') return null;
throw err;
}
}
export async function extractWithCache(s3Uri: string): Promise<unknown> {
const { bucket, key } = parseS3Uri(s3Uri);
const cacheKey = await hashDocument(bucket, key);
const cached = await getCache(cacheKey);
if (cached) return cached;
const output = await runFullBdaExtraction(s3Uri);
await s3.send(new PutObjectCommand({
Bucket: CACHE_BUCKET,
Key: `bda-cache/${cacheKey}.json`,
Body: JSON.stringify({ extracted_at: new Date().toISOString(), output }),
ContentType: 'application/json',
}));
return output;
}
ClientError vs ServiceError — the retry decision
BDA job failures fall into two categories that require different handling. ClientError means the job failed because of a problem with the input or configuration — retrying immediately produces the same error. ServiceError means AWS infrastructure experienced a transient failure — retrying with exponential backoff is appropriate. The errorType and errorMessage fields on the failed job status give the specific root cause for ClientError:
- AccessDenied — output bucket policy missing for
bedrock.amazonaws.comservice principal - RegionMismatch — input S3 bucket is in a different region than BDA runtime
- InvalidInput — file is corrupted, password-protected, or in an unsupported format
- FileSizeLimitExceeded — input file exceeds the per-format size limit
- PageCountLimitExceeded — PDF exceeds 100-page limit
- InvalidProfile — dataAutomationProfileArn is wrong or not available in region
- BlueprintNotFound — blueprint ARN was deleted; BDA validates blueprint existence at job start
Consolidated production gotchas
- Always async — no synchronous option.
InvokeDataAutomationAsyncCommandreturns immediately with aninvocationArn. There is noInvokeDataAutomationSyncCommand. Any code path that expects extracted data from the invocation call itself will not work. Plan for the async lifecycle from the start. - Control-plane vs runtime package split. Blueprint CRUD (
CreateBlueprintCommand,UpdateBlueprintCommand,CreateBlueprintVersionCommand) lives in@aws-sdk/client-bedrock-data-automation. Job submission and status polling (InvokeDataAutomationAsyncCommand,GetDataAutomationStatusCommand) lives in@aws-sdk/client-bedrock-data-automation-runtime. Using the wrong client raisesUnknownOperation. - S3 output bucket policy required for Bedrock service principal. BDA writes output as
bedrock.amazonaws.com, not your IAM role. Your task role'ss3:PutObjectalone is insufficient. The output bucket must have a resource-based bucket policy granting the Bedrock service principal write access with anaws:SourceAccountcondition. Missing this policy surfaces asClientErroron the job, not an SDK exception during invocation submission. - Input bucket must be in the same region as BDA runtime. Cross-region input produces a
ClientErrorwith an error message that often says "AccessDenied" rather than explaining the region mismatch. Stage documents to a bucket in the BDA deployment region before submitting. - Blueprint schema must be a JSON string. The
schemafield inCreateBlueprintCommandandUpdateBlueprintCommandtakes astring. PassJSON.stringify(schemaObject). Passing a raw object raisesValidationException: schema must be a string. - UpdateBlueprintCommand is a full replacement. Omitting a property silently deletes it. Always read the current schema with
GetBlueprintCommand, merge changes, then write back the entire schema. Theblueprint.schemafield in the get response is a string —JSON.parse()before merging. - blueprintVersion is a string not a number.
CreateBlueprintVersionCommandreturns version"1","2", etc. Never compare versions numerically (version > 1does not work as expected in TypeScript/JavaScript). Use string comparison orparseInt(version, 10)explicitly when ordering. - Always pin blueprintVersion in production. Using
blueprintStage: 'LIVE'without a version picks up the most recently promoted version and silently changes extraction behavior when you promote a new blueprint version without a deployment gate. SetBDA_BLUEPRINT_VERSIONin your environment variables and update it as part of a controlled deployment. - Tables are cell-indexed, not row-indexed. BDA table output is a flat
cellsarray withrow_indexandcolumn_indexper cell. There is no pre-built row array. Row 0 is typically the header row. Reconstruct the 2D grid yourself before accessing data by column name. - Custom blueprint output fields are wrapped — access .value. Every field in custom output is
{ value: "...", confidence: 0.95 }. Never readoutput.invoice_numberdirectly — readoutput.invoice_number.value. For array fields, each element's sub-fields are also individually wrapped. - outputConfiguration.s3Uri is a prefix, not a file path. Navigate via
job_manifest.jsonat the prefix root to find exact S3 keys forstandard_output/document_output.jsonandcustom_output/document_output.json. Hardcoding the subdirectory path will break on BDA version updates. - Markdown output beats plain text for LLM downstream use. When feeding BDA output to a foundation model via Bedrock Converse, use
representation.markdownnotrepresentation.text. Markdown preserves table structure as pipe-separated syntax and section headers as heading markers — context that models use for accurate reasoning. Plain text flattens this structure. - XLSX sheets map to pages, not to separate documents. A multi-sheet workbook is a single BDA job. Each sheet appears as a separate
pagein the output with its own tables and text. If you need sheet-level jobs (to apply different blueprints to different sheets), split the workbook first. - Cache extraction results to avoid repeated per-page charges. BDA charges per page processed. Use the S3 object ETag as a stable content fingerprint to build a cache key. Check the cache before submitting a new BDA job. For MCP server deployments where the same documents may be queried repeatedly across different agent sessions, this is a significant cost lever.
Putting it together — a production document extraction MCP server
The complete BDA integration for a production MCP server combines all four parts: the two-package SDK setup, the two-tool (submit + poll) agent pattern, same-region staging, blueprint attachment with pinned version, manifest-based output navigation, and cache-first result retrieval. The following sketch shows how these pieces connect:
// Startup: initialize clients
const controlPlane = new BedrockDataAutomationClient({ region: AWS_REGION });
const runtime = new BedrockDataAutomationRuntimeClient({ region: AWS_REGION });
const s3 = new S3Client({ region: AWS_REGION });
// Tool 1: submit_document_extraction
// - Stages document if cross-region
// - Submits BDA job with blueprint (optional)
// - Returns invocation ARN as job_id
// Tool 2: get_extraction_result
// - Polls GetDataAutomationStatusCommand
// - On Success: reads manifest, fetches standard + custom output
// - Unwraps .value from custom fields
// - Builds normalized result object
// - Saves to S3 cache keyed by input document ETag hash
// - Returns structured extraction result
// Blueprint management (CI/CD, not runtime):
// 1. UpdateBlueprintCommand after read-merge-write cycle
// 2. CreateBlueprintVersionCommand to promote DEVELOPMENT → LIVE
// 3. Update BDA_BLUEPRINT_VERSION env var in deployment config
// 4. Never use blueprintStage: 'LIVE' in runtime invocations
AliveMCP monitors the uptime and health of MCP servers that expose document extraction tools — including BDA-backed endpoints. If your MCP server exposes document processing tools, claim your listing to get instant alerts when extraction latency spikes above your SLA threshold or when BDA ServiceError rates increase. See AliveMCP plans for details.