Guide · Amazon Bedrock · Data Extraction

Bedrock Data Automation Output Parsing — JSON Structure, S3 Key Pattern, and MCP Tool Integration

Amazon Bedrock Data Automation writes results to S3 as a job manifest plus one or more modality-specific JSON files — but the outputConfiguration.s3Uri in the status response is a prefix, not a file path, and the exact key of the output JSON requires either reading the manifest or knowing BDA's key-naming convention. The most common parsing failure: constructing the output key path incorrectly and hitting a 404 from S3, or reading the manifest but not understanding the nested output_metadata → segment_metadata path to the actual file location. Beyond output file navigation, four topics dominate BDA output work: distinguishing standard output fields from custom blueprint output fields, feeding extracted Markdown to Bedrock Converse for downstream LLM analysis, handling job failures with the right retry strategy, and building a durable MCP tool that caches results to avoid re-running expensive extraction jobs. For the BDA invocation pattern see BDA overview; for custom blueprint design see BDA blueprints; for document-type-specific extraction see BDA document processing.

TL;DR

BDA output lands in the S3 prefix you specified plus a job-specific subdirectory. Read job_manifest.json at the prefix root to find the exact S3 keys of output files. For standard document extraction, the main file is document_output.json. Custom blueprint fields appear under document.custom_output (or a blueprint-specific key). Standard fields appear under document.representation, document.tables, and document.key_value_pairs.

Output S3 structure — manifest and data files

When BDA completes a job, it writes files to the output S3 prefix you provided in the invocation. The files are written to a subdirectory under that prefix — the subdirectory name is derived from the job ID embedded in the invocationArn. The output layout looks like this:

s3://my-output-bucket/bda-output/my-job-prefix/
  job_manifest.json                      ← always present, describes all output files
  0/                                      ← per-input-file directory (index 0 for first file)
    standard_output/
      document_output.json               ← main standard extraction output
    custom_output/
      document_output.json               ← custom blueprint output (if blueprint attached)
    metadata/
      asset_metadata.json                ← file type, page count, processing stats

The job_manifest.json at the prefix root is the authoritative map to all output files. Never hardcode the subdirectory path — the structure can change between BDA version updates. Always read the manifest first.

import { S3Client, GetObjectCommand } from '@aws-sdk/client-s3';

const s3 = new S3Client({ region: process.env.AWS_REGION! });

interface BdaOutputManifest {
  output_metadata: Array<{
    segment_metadata: Array<{
      asset_id: string;
      asset_type: 'DOCUMENT' | 'IMAGE' | 'AUDIO' | 'VIDEO';
      input_key: string;        // S3 key of the input file
      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
    }>;
  }>;
}

async function readManifest(outputS3Uri: string): Promise<BdaOutputManifest> {
  const { bucket, prefix } = parseS3Uri(outputS3Uri);
  const manifestKey = `${prefix}job_manifest.json`;

  const response = await s3.send(new GetObjectCommand({
    Bucket: bucket,
    Key: manifestKey,
  }));
  const text = await response.Body!.transformToString('utf-8');
  return JSON.parse(text);
}

function parseS3Uri(uri: string): { bucket: string; prefix: string } {
  const url = new URL(uri.replace('s3://', 'https://'));
  return {
    bucket: url.hostname,
    prefix: url.pathname.replace(/^\//, ''),
  };
}

// Traverse manifest to find output file keys
async function getOutputFilePaths(outputS3Uri: string): Promise<{
  standardOutputKey?: string;
  customOutputKey?: string;
  assetMetadataKey?: string;
  bucket: string;
}> {
  const manifest = await readManifest(outputS3Uri);
  const { bucket } = parseS3Uri(outputS3Uri);

  const segment = manifest.output_metadata?.[0]?.segment_metadata?.[0];
  if (!segment) {
    throw new Error('BDA manifest missing expected output_metadata[0].segment_metadata[0]');
  }

  return {
    standardOutputKey: segment.standard_output_path,
    customOutputKey: segment.custom_output_path,
    assetMetadataKey: segment.asset_metadata_path,
    bucket,
  };
}

Standard output JSON schema

The standard output JSON (standard_output/document_output.json) follows a consistent schema regardless of document type. The root-level structure:

// Full standard output JSON schema (TypeScript interface)
interface BdaStandardOutput {
  metadata: {
    content_type: string;         // MIME type: "application/pdf", "application/docx", etc.
    document_class: {
      type: string;               // BDA's classification: "INVOICE", "CONTRACT", "RECEIPT", etc.
      confidence?: number;        // 0.0–1.0 classification confidence
    };
    total_pages: number;
    file_size_bytes?: number;
  };
  document: {
    statistics: {
      pages: number;
      tables: number;
      figures: number;
      key_value_pairs: number;
      words?: number;
    };
    representation: {
      text: string;               // Full plain text of the document
      markdown: string;           // Markdown-formatted version with headers, tables, lists
    };
    summary: string;              // LLM-generated document summary
    pages: BdaPage[];             // Per-page breakdown
    tables: BdaTableOutput[];     // All tables across all pages (merged if multi-page table)
    key_value_pairs: BdaKvPair[]; // Form fields and labeled data
    figures: BdaFigure[];         // Figure and chart descriptions
  };
}

interface BdaPage {
  page_index: number;             // 0-based
  representation: {
    text: string;
    markdown: string;
  };
  tables: BdaTableOutput[];
  key_value_pairs: BdaKvPair[];
  figures: BdaFigure[];
  summary?: string;               // Page-level summary (may not be present for all page types)
}

interface BdaTableOutput {
  title?: string;
  page_index?: number;
  cells: BdaTableCell[];
  footnotes?: string[];
}

interface BdaTableCell {
  row_index: number;
  column_index: number;
  content: string | null;
  row_span?: number;
  column_span?: number;
  is_header?: boolean;
  confidence?: number;
}

interface BdaKvPair {
  key: { content: string; confidence?: number; bounding_box?: BdaBoundingBox };
  value: { content: string; confidence?: number; bounding_box?: BdaBoundingBox };
  confidence?: number;
}

interface BdaFigure {
  content: string;                // Text description of the figure
  page_index?: number;
  figure_type?: string;           // "CHART", "DIAGRAM", "PHOTO", etc.
}

interface BdaBoundingBox {
  left: number;                   // 0.0–1.0 (fraction of page width)
  top: number;                    // 0.0–1.0 (fraction of page height)
  width: number;
  height: number;
}

Custom blueprint output — the custom_output key

When a blueprint is attached to a BDA invocation, the extracted fields appear in the custom output file (custom_output/document_output.json). The structure is different from standard output — it contains a top-level matched_fields or output object whose shape mirrors the blueprint schema you defined.

// Custom output JSON for an invoice blueprint
// (from custom_output/document_output.json)
{
  "metadata": {
    "content_type": "application/pdf",
    "blueprint_name": "invoice-extraction-v1",
    "blueprint_version": "2"
  },
  "output": {
    // Top-level keys match the properties you defined in the blueprint schema
    "invoice_number": {
      "value": "INV-2024-001",
      "confidence": 0.98,
      "bounding_box": { "page_index": 0, "left": 0.72, "top": 0.08, "width": 0.15, "height": 0.03 }
    },
    "vendor_name": {
      "value": "Acme Supplies Inc.",
      "confidence": 0.95
    },
    "invoice_date": {
      "value": "2024-01-15",
      "confidence": 0.99
    },
    "total_amount": {
      "value": 4250.00,     // numeric type preserved from schema definition
      "confidence": 0.97
    },
    "line_items": {
      "value": [
        {
          "description": { "value": "Consulting services - January 2024", "confidence": 0.94 },
          "quantity": { "value": 10, "confidence": 0.99 },
          "unit_price": { "value": 300.0, "confidence": 0.98 },
          "total": { "value": 3000.0, "confidence": 0.96 }
        },
        {
          "description": { "value": "Software license - annual", "confidence": 0.95 },
          "quantity": { "value": 1, "confidence": 1.0 },
          "unit_price": { "value": 1250.0, "confidence": 0.99 },
          "total": { "value": 1250.0, "confidence": 0.99 }
        }
      ]
    }
  }
}

Each extracted field is wrapped in an object with a value key (the extracted content) and a confidence score. This wrapping is consistent — even scalar string values are wrapped. When reading custom output, always access field.value, not the field directly.

function extractCustomFields(customOutput: BdaCustomOutput): Record<string, unknown> {
  const result: Record<string, unknown> = {};
  const fields = customOutput.output ?? {};

  for (const [fieldName, fieldData] of Object.entries(fields)) {
    if (fieldData === null || fieldData === undefined) continue;

    // Check confidence threshold
    const confidence = (fieldData as { confidence?: number }).confidence ?? 1.0;
    if (confidence < 0.7) {
      console.warn(`Low confidence for field ${fieldName}: ${confidence}`);
      continue;
    }

    const rawValue = (fieldData as { value: unknown }).value;

    // Handle arrays of objects (line items, etc.)
    if (Array.isArray(rawValue)) {
      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;
}

// Example usage for invoice extraction:
// {
//   invoice_number: "INV-2024-001",
//   vendor_name: "Acme Supplies Inc.",
//   invoice_date: "2024-01-15",
//   total_amount: 4250.0,
//   line_items: [
//     { description: "Consulting services - January 2024", quantity: 10, unit_price: 300.0, total: 3000.0 },
//     { description: "Software license - annual", quantity: 1, unit_price: 1250.0, total: 1250.0 },
//   ]
// }

Feeding BDA Markdown output to Bedrock Converse

A powerful pattern for MCP servers: use BDA to extract and structure a document, then pass the Markdown representation to a foundation model for downstream reasoning (answering questions about the document, verifying extracted fields, generating summaries with specific formatting). The Markdown output from BDA preserves table structure, headers, and lists in a format that Claude and other Bedrock models process well.

import {
  BedrockRuntimeClient,
  ConverseCommand,
  type ContentBlock,
} from '@aws-sdk/client-bedrock-runtime';

const bedrock = new BedrockRuntimeClient({ region: process.env.AWS_REGION! });

async function askAboutDocument(
  documentOutput: BdaStandardOutput,
  question: string,
): Promise<string> {
  const markdown = documentOutput.document.representation.markdown;

  const messages = [
    {
      role: 'user' as const,
      content: [
        {
          type: 'text' as const,
          text: `The following is a document extracted from a business file. Use it to answer the question at the end.\n\n---\n${markdown}\n---\n\nQuestion: ${question}`,
        },
      ] satisfies ContentBlock[],
    },
  ];

  const response = await bedrock.send(new ConverseCommand({
    modelId: 'anthropic.claude-3-5-haiku-20241022',
    messages,
    inferenceConfig: { maxTokens: 1024 },
  }));

  const text = response.output?.message?.content?.[0];
  if (text?.type === 'text') return text.text;
  throw new Error('Unexpected Converse response shape');
}

// MCP tool: ask_document_question
// 1. analyzeDocumentTool() — runs BDA, gets markdown
// 2. askAboutDocument() — passes markdown to Claude, asks question
// This pattern combines BDA's structured extraction with LLM reasoning
//
// Example agent call:
//   ask_document_question(s3_uri="s3://bucket/invoices/inv-001.pdf",
//                         question="What is the payment due date?")
//   → "The invoice is due on February 14, 2024 (Net 30 from January 15, 2024)."

Error handling — ClientError vs ServiceError

BDA job failures fall into two categories with different retry strategies. ClientError means the job failed because of a problem with the input, configuration, or permissions — retrying without fixing the root cause will produce the same error. ServiceError means AWS infrastructure experienced a transient failure — retrying with exponential backoff is appropriate.

interface BdaFailureInfo {
  invocationArn: string;
  status: 'ClientError' | 'ServiceError';
  errorType: string;
  errorMessage: string;
  retryable: boolean;
  debugHint: string;
}

function classifyJobFailure(statusResp: {
  status: string;
  errorType?: string;
  errorMessage?: string;
  invocationArn?: string;
}): BdaFailureInfo {
  const errorType = statusResp.errorType ?? 'UnknownError';
  const errorMessage = statusResp.errorMessage ?? 'No error message';
  const isClientError = statusResp.status === 'ClientError';

  // Map common error types to debug hints
  const hints: Record<string, string> = {
    'AccessDenied': 'Check S3 bucket policy grants bedrock.amazonaws.com write access on output bucket',
    'NoSuchKey': 'Input S3 object does not exist — verify s3_uri is correct',
    'NoSuchBucket': 'Input or output S3 bucket does not exist',
    'InvalidInput': 'Unsupported file format or file is corrupted',
    'FileSizeLimitExceeded': 'Input file exceeds BDA size limit — split into smaller chunks',
    'PageCountLimitExceeded': 'PDF exceeds 100-page limit — split into 100-page segments',
    'InvalidProfile': 'dataAutomationProfileArn is invalid or not available in this region',
    'BlueprintNotFound': 'Blueprint ARN does not exist or was deleted',
    'RegionMismatch': 'Input S3 bucket is in a different region than the BDA runtime endpoint',
  };

  return {
    invocationArn: statusResp.invocationArn ?? 'unknown',
    status: statusResp.status as 'ClientError' | 'ServiceError',
    errorType,
    errorMessage,
    retryable: !isClientError,  // ServiceError is retryable; ClientError is not
    debugHint: hints[errorType] ?? 'Check BDA job logs in CloudWatch for detailed error',
  };
}

// Retry policy for ServiceError
async function invokeWithRetry(
  submitFn: () => Promise<string>,
  maxAttempts = 3,
): Promise<string> {
  let lastError: Error | null = null;

  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await submitFn();
    } catch (err) {
      lastError = err as Error;
      if (attempt < maxAttempts) {
        const delay = Math.min(2 ** attempt * 1000, 30_000);  // exponential backoff, cap 30s
        await new Promise(r => setTimeout(r, delay + Math.random() * 1000));
      }
    }
  }

  throw lastError!;
}

Common ClientError causes and fixes

Caching BDA results to avoid re-extraction

BDA charges per page processed. For MCP servers where the same document may be analyzed multiple times across different agent sessions, cache the extracted output in S3 keyed by a hash of the input document. Before submitting a new BDA job, check whether the cache key already exists in S3.

import { S3Client, HeadObjectCommand, GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3';
import { createHash } from 'node:crypto';

const s3 = new S3Client({ region: process.env.AWS_REGION! });
const CACHE_BUCKET = process.env.BDA_CACHE_BUCKET!;
const CACHE_TTL_DAYS = 30;

interface CacheEntry {
  extracted_at: string;
  source_s3_uri: string;
  output: unknown;
}

async function hashS3Object(bucket: string, key: string): Promise<string> {
  // Use S3 ETag (MD5 for non-multipart uploads) as a stable content hash
  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 getCachedExtraction(cacheKey: string): Promise<CacheEntry | null> {
  try {
    const response = await s3.send(new GetObjectCommand({
      Bucket: CACHE_BUCKET,
      Key: `bda-cache/${cacheKey}.json`,
    }));
    const entry: CacheEntry = JSON.parse(await response.Body!.transformToString('utf-8'));

    // Check TTL
    const ageMs = Date.now() - new Date(entry.extracted_at).getTime();
    if (ageMs > CACHE_TTL_DAYS * 24 * 60 * 60 * 1000) return null;

    return entry;
  } catch (err: unknown) {
    if ((err as { name?: string }).name === 'NoSuchKey') return null;
    throw err;
  }
}

async function setCachedExtraction(
  cacheKey: string,
  sourceUri: string,
  output: unknown,
): Promise<void> {
  const entry: CacheEntry = {
    extracted_at: new Date().toISOString(),
    source_s3_uri: sourceUri,
    output,
  };
  await s3.send(new PutObjectCommand({
    Bucket: CACHE_BUCKET,
    Key: `bda-cache/${cacheKey}.json`,
    Body: JSON.stringify(entry),
    ContentType: 'application/json',
  }));
}

// Cached extraction wrapper
export async function extractWithCache(s3Uri: string): Promise<unknown> {
  const { bucket, key } = parseS3Uri(s3Uri);
  const cacheKey = await hashS3Object(bucket, key);

  const cached = await getCachedExtraction(cacheKey);
  if (cached) {
    console.log(`BDA cache hit for ${s3Uri} (key=${cacheKey})`);
    return cached.output;
  }

  const output = await runBdaExtraction(s3Uri);
  await setCachedExtraction(cacheKey, s3Uri, output);
  return output;
}

EventBridge-driven result processing for high-volume MCP servers

For MCP server deployments that process hundreds or thousands of documents per day, the polling loop does not scale well — holding a polling loop open per job exhausts Lambda concurrency and wastes request budget. Use EventBridge notifications to process completions through an SQS queue instead.

// EventBridge rule configuration (CDK):
// Match BDA completion events and route to your SQS queue
//
// EventPattern:
// {
//   "source": ["aws.bedrock-data-automation"],
//   "detail-type": ["Bedrock Data Automation Job State Change"],
//   "detail": {
//     "status": ["Success", "ClientError", "ServiceError"]
//   }
// }

// Lambda handler for SQS-delivered BDA completion events
interface BdaEventDetail {
  invocationArn: string;
  status: 'Success' | 'ClientError' | 'ServiceError';
  errorType?: string;
  errorMessage?: string;
  outputConfiguration?: { s3Uri: string };
}

export async function handleBdaCompletion(event: { Records: Array<{body: string}> }): Promise<void> {
  for (const record of event.Records) {
    const snsOrEventBridgeWrapper = JSON.parse(record.body);
    const detail: BdaEventDetail = snsOrEventBridgeWrapper.detail;

    if (detail.status === 'Success') {
      const outputUri = detail.outputConfiguration?.s3Uri;
      if (!outputUri) {
        console.error('Success event missing outputConfiguration.s3Uri', detail);
        continue;
      }

      try {
        const output = await parseDocumentOutput(outputUri);
        await saveProcessedResult(detail.invocationArn, output);
        console.log(`Processed BDA result for ${detail.invocationArn}`);
      } catch (err) {
        console.error(`Failed to process BDA result for ${detail.invocationArn}:`, err);
        throw err;  // Let SQS retry if processing fails
      }
    } else {
      const failure = classifyJobFailure(detail);
      console.error(`BDA job failed:`, JSON.stringify(failure));

      if (failure.retryable) {
        // Could re-submit the original job, but need to look up original input from DynamoDB
        await scheduleRetry(detail.invocationArn);
      } else {
        // ClientError — alert and move to DLQ
        await alertOnPermanentFailure(detail);
      }
    }
  }
}

Key gotchas