Guide · Amazon S3 · Batch Operations · Bulk Processing · MCP Server Tools

S3 Batch Operations for MCP Servers — Bulk Processing, Inventory, Lambda Transform

MCP server tools often need to process large numbers of S3 objects at once: convert a bucket of raw uploads to a standardized format, re-encrypt objects with a new KMS key, restore thousands of Glacier objects before an analytics run, or apply a metadata tag to objects matching a certain pattern. Writing a pagination loop with ListObjectsV2 + per-object worker threads gets the job done but takes days to build correctly with error handling, retries, and progress reporting. S3 Batch Operations is a managed service that takes a manifest of objects (from S3 Inventory or a CSV you provide), parallelizes work across AWS infrastructure at billions-of-objects scale, writes per-object success/failure reports, and handles retries — without you managing any workers. This guide covers creating batch jobs from the SDK, the Lambda invoke pattern, IAM requirements, job monitoring, completion reports, and common errors.

TL;DR

S3 Batch Operations processes a manifest of object keys and applies one operation to each: S3PutObjectCopy, S3InitiateRestoreObject, LambdaInvoke, S3PutObjectTagging, S3PutObjectAcl, or S3DeleteObjectTagging. Create a job with CreateJobCommand; set ConfirmationRequired: false to auto-start. The IAM role needs s3:GetObject on source, s3:PutObject on destination, and lambda:InvokeFunction for Lambda jobs. The manifest can be a CSV (bucket,key per line) or an S3 Inventory report. Write job completion reports to a separate S3 prefix for auditing. Each Lambda invocation receives a payload of one object at a time and must return { resultCode: 'Succeeded' | 'TemporaryFailure' | 'PermanentFailure', resultString: ... }.

When to use S3 Batch Operations

Use caseApproachNotes
Process < 1,000 objectsListObjectsV2 + manual loopBatch Operations has per-job overhead not worth it at this scale
Bulk copy to new bucket/regionBatch S3PutObjectCopyPreserves metadata; can change encryption key, storage class
Bulk Lambda processing (resize, transcode, extract)Batch LambdaInvokeLambda is invoked once per object; concurrency managed by Batch
Restore Glacier objects in bulkBatch S3InitiateRestoreObjectSchedules restore for all matched objects at once
Apply tags/ACL at scaleBatch S3PutObjectTagging / S3PutObjectAclUseful for data classification or access policy migration
Re-encrypt with new KMS keyBatch S3PutObjectCopy with new encryption paramsCopy object to same key with new SSE-KMS key ID

Creating a batch job from a CSV manifest

The simplest manifest is a CSV file you upload to S3 with one row per object: bucket,key (optionally with a version ID third column). No header row.

// 1. Upload your manifest CSV to S3
// manifest.csv content:
// your-bucket,uploads/file1.jpg
// your-bucket,uploads/file2.jpg
// your-bucket,uploads/file3.jpg

import {
  S3ControlClient,
  CreateJobCommand,
  DescribeJobCommand,
} from '@aws-sdk/client-s3-control';
import { GetCallerIdentityCommand, STSClient } from '@aws-sdk/client-sts';

const s3control = new S3ControlClient({ region: 'us-east-1' });
const sts = new STSClient({ region: 'us-east-1' });

// Get account ID (required by S3 Control API)
const { Account: accountId } = await sts.send(new GetCallerIdentityCommand({}));

const { JobId } = await s3control.send(
  new CreateJobCommand({
    AccountId: accountId!,
    ConfirmationRequired: false, // auto-start the job
    Priority: 10, // 1 (lowest) to 2147483647 (highest)
    RoleArn: 'arn:aws:iam::123456789012:role/s3-batch-job-role',

    // The manifest describing which objects to process
    Manifest: {
      Spec: {
        Format: 'S3BatchOperations_CSV_20180820', // CSV format without header
        Fields: ['Bucket', 'Key'], // columns in your CSV
      },
      Location: {
        ObjectArn: 'arn:aws:s3:::manifest-bucket/manifest.csv',
        ETag: 'abc123', // ETag of the manifest CSV object — prevents stale manifests
      },
    },

    // The operation to perform on each object
    Operation: {
      LambdaInvoke: {
        FunctionArn: 'arn:aws:lambda:us-east-1:123456789012:function:process-s3-object',
        InvocationSchemaVersion: '2.0', // use 2.0 for new jobs
      },
    },

    // Where to write the completion report
    Report: {
      Bucket: 'arn:aws:s3:::report-bucket',
      Prefix: 'batch-reports/',
      Format: 'Report_CSV_20180820',
      Enabled: true,
      ReportScope: 'FailedTasksOnly', // or 'AllTasks' for full audit trail
    },

    // Idempotency token — prevents duplicate jobs if you retry CreateJob
    ClientRequestToken: `batch-job-${Date.now()}`,
  })
);

The ETag field in Manifest.Location is required and prevents the job from using a stale or accidentally replaced manifest file. Get the ETag from HeadObjectCommand after uploading your manifest CSV.

Lambda handler for LambdaInvoke operations

When using LambdaInvoke, S3 Batch Operations calls your Lambda function once per object in the manifest. Your function receives the bucket and key, processes the object, and returns a result code. The result code determines whether Batch Operations retries the object or marks it as failed.

// Lambda function: process-s3-object
// Runtime: Node.js 22.x
import { S3Client, GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3';

const s3 = new S3Client({});

interface BatchTaskResult {
  taskId: string;
  resultCode: 'Succeeded' | 'TemporaryFailure' | 'PermanentFailure';
  resultString: string;
}

interface BatchEvent {
  invocationSchemaVersion: string;
  invocationId: string;
  job: { id: string };
  tasks: Array<{
    taskId: string;
    s3Key: string;
    s3VersionId: string | null;
    s3BucketArn: string;
  }>;
}

export async function handler(event: BatchEvent): Promise<{ invocationSchemaVersion: string; treatMissingKeysAs: string; invocationId: string; results: BatchTaskResult[] }> {
  const results: BatchTaskResult[] = [];

  for (const task of event.tasks) {
    const bucket = task.s3BucketArn.split(':::')[1];
    const key = task.s3Key;

    try {
      // Get the object
      const { Body, ContentType } = await s3.send(
        new GetObjectCommand({ Bucket: bucket, Key: key })
      );

      const bytes = await Body!.transformToByteArray();

      // Process the object (example: add a metadata tag by re-uploading)
      await s3.send(
        new PutObjectCommand({
          Bucket: 'processed-bucket',
          Key: key,
          Body: bytes,
          ContentType,
          Metadata: { processed: 'true', processedAt: new Date().toISOString() },
        })
      );

      results.push({
        taskId: task.taskId,
        resultCode: 'Succeeded',
        resultString: `Processed ${key}`,
      });
    } catch (err: any) {
      // TemporaryFailure = Batch will retry; PermanentFailure = skip
      const isTransient = err.name === 'ThrottlingException' || err.name === 'ServiceUnavailable';
      results.push({
        taskId: task.taskId,
        resultCode: isTransient ? 'TemporaryFailure' : 'PermanentFailure',
        resultString: `Error: ${err.message}`,
      });
    }
  }

  return {
    invocationSchemaVersion: event.invocationSchemaVersion,
    treatMissingKeysAs: 'PermanentFailure', // or 'Succeeded' to skip missing keys
    invocationId: event.invocationId,
    results,
  };
}

TemporaryFailure tells Batch Operations to retry the object (up to the job's retry configuration). PermanentFailure marks the object as failed without retrying and writes it to the failure report. Use TemporaryFailure for transient errors (throttling, network) and PermanentFailure for unrecoverable errors (corrupt data, missing dependency).

IAM role requirements

The batch job role needs several permissions. The most common mistake is missing s3:GetObject on the manifest bucket or forgetting to add the S3 Batch Operations service as a trust principal.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ReadManifest",
      "Effect": "Allow",
      "Action": ["s3:GetObject", "s3:GetObjectVersion"],
      "Resource": "arn:aws:s3:::manifest-bucket/*"
    },
    {
      "Sid": "WriteReport",
      "Effect": "Allow",
      "Action": ["s3:PutObject"],
      "Resource": "arn:aws:s3:::report-bucket/batch-reports/*"
    },
    {
      "Sid": "ReadSourceObjects",
      "Effect": "Allow",
      "Action": ["s3:GetObject", "s3:GetObjectVersion"],
      "Resource": "arn:aws:s3:::your-bucket/*"
    },
    {
      "Sid": "InvokeLambda",
      "Effect": "Allow",
      "Action": ["lambda:InvokeFunction"],
      "Resource": "arn:aws:lambda:us-east-1:123456789012:function:process-s3-object"
    }
  ]
}

// Trust policy — must trust batchoperations.s3.amazonaws.com
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "Service": "batchoperations.s3.amazonaws.com" },
      "Action": "sts:AssumeRole"
    }
  ]
}

Monitoring job status

Batch jobs go through several states. Poll DescribeJobCommand until the job reaches Complete, Failed, or Cancelled.

async function waitForBatchJob(accountId: string, jobId: string) {
  const terminalStates = new Set(['Complete', 'Failed', 'Cancelled', 'Completing']);

  while (true) {
    const { Job } = await s3control.send(
      new DescribeJobCommand({ AccountId: accountId, JobId: jobId })
    );

    const status = Job?.Status;
    const progress = Job?.ProgressSummary;

    console.log(`Status: ${status}, Succeeded: ${progress?.NumberOfTasksSucceeded}, ` +
      `Failed: ${progress?.NumberOfTasksFailed}, Total: ${progress?.TotalNumberOfTasks}`);

    if (terminalStates.has(status ?? '')) {
      return Job;
    }

    await new Promise((resolve) => setTimeout(resolve, 10000)); // poll every 10s
  }
}

// Job states: New → Preparing → Suspended (awaiting confirmation) →
//             Active → Completing → Complete
//          or: Active → Pausing → Paused → Active
//          or: Active → Cancelling → Cancelled
//          or: Active → Failing → Failed

For long-running jobs (millions of objects), use EventBridge rather than polling. Batch Operations emits job state change events to aws.s3 that you can route to Lambda or SQS.

Using S3 Inventory as manifest

Instead of building a CSV manually, configure S3 Inventory to generate weekly or daily CSV reports of all objects in a bucket. Reference the inventory report directly in your batch job manifest.

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

// Configure inventory (runs daily, outputs CSV to report bucket)
await s3.send(
  new PutBucketInventoryConfigurationCommand({
    Bucket: 'your-bucket',
    Id: 'daily-full-inventory',
    InventoryConfiguration: {
      Id: 'daily-full-inventory',
      IsEnabled: true,
      Destination: {
        S3BucketDestination: {
          Bucket: 'arn:aws:s3:::report-bucket',
          Prefix: 'inventory/',
          Format: 'CSV',
        },
      },
      Schedule: { Frequency: 'Daily' },
      IncludedObjectVersions: 'Current', // or 'All' for versioned buckets
      OptionalFields: ['Size', 'StorageClass', 'LastModifiedDate', 'ETag'],
    },
  })
);

// When creating a Batch job from inventory, use format S3InventoryReport_CSV_20161130
// and point Manifest.Location to the manifest.json file S3 Inventory generates
// (not the data CSV — the manifest.json that lists all the data CSV files)

Common errors and fixes

ErrorCauseFix
InvalidManifestETag in job request doesn't match current manifest object ETagFetch ETag via HeadObjectCommand immediately before CreateJobCommand
AccessDenied creating jobCaller missing s3:CreateJob permission or batch role missing trust policyAdd s3:CreateJob to caller; add batchoperations.s3.amazonaws.com trust to role
Job stuck in SuspendedConfirmationRequired: true (the default)Set ConfirmationRequired: false in CreateJobCommand or call UpdateJobStatusCommand to confirm
Lambda returns 200 but tasks marked failedLambda response missing required fields or resultCode not one of three valid valuesEnsure Lambda returns exactly { invocationSchemaVersion, treatMissingKeysAs, invocationId, results: [{taskId, resultCode, resultString}] }
All tasks fail with AccessDeniedBatch role doesn't have s3:GetObject on source bucketAdd s3:GetObject and s3:GetObjectVersion to batch role for source bucket ARN
Lambda not invokedBatch role missing lambda:InvokeFunction, or Lambda resource policy doesn't allow Batch service principalAdd lambda:InvokeFunction to batch role; add resource-based policy on Lambda allowing batchoperations.s3.amazonaws.com
Job report emptyReport.Enabled: false or ReportScope: 'FailedTasksOnly' with no failuresSet ReportScope: 'AllTasks' to get a full audit trail

Related guides