Guide · AWS DataSync · Data Transfer

AWS DataSync for MCP Servers — Migrate and Sync Data Between S3, EFS, and FSx

AWS DataSync is a fully managed data transfer service that moves files between on-premises storage, Amazon S3, Amazon EFS, and all four Amazon FSx variants at up to 10 Gbps per agent. Unlike aws s3 sync or rsync, DataSync handles POSIX metadata preservation, bandwidth throttling, task scheduling, verification, and CloudWatch metrics out of the box. For MCP server deployments, DataSync solves three recurring problems: populating a new EFS or FSx file system with existing data faster than a manual copy, synchronizing on-premises tool libraries into AWS on a schedule, and replicating S3 artifacts across accounts or regions as part of a disaster-recovery pipeline. This guide covers the core DataSync JavaScript SDK commands, the task-execution lifecycle, and the common patterns MCP server teams reach for.

TL;DR

DataSync transfers happen in three steps: (1) create a location for each endpoint (S3, EFS, FSx, NFS agent), (2) create a task that pairs a source and destination location with transfer options, (3) start a task execution and poll it until it reaches SUCCESS or ERROR. Pricing is $0.0125 per GB transferred — the total gigabytes moved, not connection time. The minimum IAM permission set for running DataSync from an MCP tool is datasync:CreateTask, datasync:StartTaskExecution, datasync:DescribeTaskExecution, plus the IAM permissions your chosen location type requires (S3 passrole, EFS client mount, etc.).

When MCP servers use DataSync

DataSync is not a file system mount — it is a transfer job. MCP server code typically invokes DataSync in four scenarios:

  1. Initial EFS or FSx population — You have a large dataset in S3 (ML models, reference files, tool binaries) and you need it pre-loaded into an EFS file system or FSx for Lustre before your first container starts. DataSync does this in parallel at network speed rather than streaming through your application container.
  2. On-premises NFS to EFS migration — Your MCP server currently reads from an NFS mount in a datacenter. You install a DataSync agent on-premises, create an NFS source location, and DataSync syncs into EFS over AWS Direct Connect or VPN — with POSIX permissions preserved.
  3. Cross-account or cross-region S3 replication — S3 Cross-Region Replication handles new objects automatically, but DataSync handles existing objects that predate the replication rule, or one-time cross-account copies where you cannot attach a replication role to the source account.
  4. Scheduled differential sync — DataSync tasks can be scheduled (via CloudWatch Events / EventBridge) to run nightly or hourly. Each execution does a differential transfer — only files changed since the previous successful execution are re-transferred.

Install the DataSync SDK client

npm install @aws-sdk/client-datasync

The DataSync client is regional — you specify the region where your DataSync task will run, which is typically the region where your destination storage lives.

import {
  DataSyncClient,
  CreateLocationS3Command,
  CreateLocationEfsCommand,
  CreateTaskCommand,
  StartTaskExecutionCommand,
  DescribeTaskExecutionCommand,
  CancelTaskExecutionCommand,
  ListTaskExecutionsCommand,
  DeleteTaskCommand,
} from "@aws-sdk/client-datasync";

const datasync = new DataSyncClient({ region: "us-east-1" });

Core concepts: locations, tasks, and task executions

DataSync has a strict three-layer model:

Resource What it represents Lifecycle
Location An endpoint: an S3 bucket prefix, EFS file system + path, FSx file system, or on-premises NFS/SMB server Created once, reused across many tasks. ARN: arn:aws:datasync:region:account:location/loc-xxxxxxxx
Task A named transfer configuration: source location → destination location, with options (verify mode, bandwidth throttle, filters, metadata flags) Created once; can be executed many times. ARN: arn:aws:datasync:region:account:task/task-xxxxxxxx
Task execution One run of a task. Each start produces a new task execution ARN. Ephemeral — transitions through QUEUED → LAUNCHING → PREPARING → TRANSFERRING → VERIFYING → SUCCESS/ERROR. ARN: arn:aws:datasync:region:account:task/task-xxx/execution/exec-xxx

A common mistake is to confuse the task ARN and the task execution ARN. CancelTaskExecutionCommand takes the execution ARN — not the task ARN. DescribeTaskExecutionCommand also takes the execution ARN. Only StartTaskExecutionCommand and DeleteTaskCommand take the task ARN.

Creating an S3 location

Each S3 location points to a bucket (and optional prefix). DataSync assumes an IAM role to access the bucket — you must pass a BucketAccessRoleArn and add DataSync as a trusted principal in that role's trust policy.

// 1. Create an S3 source location
const s3Loc = await datasync.send(new CreateLocationS3Command({
  S3BucketArn: "arn:aws:s3:::my-mcp-artifacts",
  Subdirectory: "/models/",           // only sync this prefix
  S3StorageClass: "STANDARD",
  S3Config: {
    BucketAccessRoleArn: "arn:aws:iam::123456789012:role/datasync-s3-access",
  },
}));
console.log(s3Loc.LocationArn); // arn:aws:datasync:...:location/loc-...

The trust policy on datasync-s3-access must allow DataSync to assume it:

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "Service": "datasync.amazonaws.com" },
    "Action": "sts:AssumeRole",
    "Condition": {
      "StringEquals": { "aws:SourceAccount": "123456789012" },
      "ArnLike": { "aws:SourceArn": "arn:aws:datasync:us-east-1:123456789012:*" }
    }
  }]
}

The role permissions need s3:GetObject, s3:PutObject, s3:DeleteObject, s3:ListBucket, and s3:GetBucketLocation on the target bucket. See the DataSync with S3 deep dive for the full IAM policy, storage class selection, and filter patterns.

Creating an EFS destination location

// 2. Create an EFS destination location
const efsLoc = await datasync.send(new CreateLocationEfsCommand({
  EfsFilesystemArn: "arn:aws:elasticfilesystem:us-east-1:123456789012:file-system/fs-0abc123",
  Ec2Config: {
    SubnetArn: "arn:aws:ec2:us-east-1:123456789012:subnet/subnet-0def456",
    SecurityGroupArns: [
      "arn:aws:ec2:us-east-1:123456789012:security-group/sg-datasync-eni",
    ],
  },
  Subdirectory: "/models/",
  InTransitEncryption: "TLS1_2",
  // Optional: restrict to an EFS access point
  // AccessPointArn: "arn:aws:elasticfilesystem:...:access-point/fsap-xxx",
  // FileSystemAccessRoleArn: "arn:aws:iam::...:role/datasync-efs-iam-auth",
}));
console.log(efsLoc.LocationArn);

DataSync creates an ENI inside subnet-0def456 using sg-datasync-eni. That security group must have an outbound rule allowing TCP 2049 to the EFS security group. See the DataSync with EFS guide for the full security group chain and cross-region replication pattern.

Creating a task

A task pairs a source and destination location with transfer options. Options are fixed at task creation time but can be overridden per execution via StartTaskExecutionCommand.OverrideOptions.

// 3. Create a task: S3 → EFS
const task = await datasync.send(new CreateTaskCommand({
  SourceLocationArn: s3Loc.LocationArn,
  DestinationLocationArn: efsLoc.LocationArn,
  Name: "mcp-models-s3-to-efs",
  Options: {
    // Verify every transferred file by checksum
    VerifyMode: "ONLY_FILES_TRANSFERRED",
    // Don't re-transfer files that already exist and have the same mtime+size
    OverwriteMode: "ALWAYS",
    // Preserve POSIX metadata from S3 object metadata headers
    Atime: "BEST_EFFORT",
    Mtime: "PRESERVE",
    Uid: "INT_VALUE",   // preserve numeric UID from object metadata (s3-mcp-uid header)
    Gid: "INT_VALUE",   // preserve numeric GID
    PosixPermissions: "PRESERVE",
    // Log every transferred file to CloudWatch
    LogLevel: "TRANSFER",
    // Throttle to 100 MB/s to avoid starving production traffic
    BytesPerSecond: 104857600,
    // Allow multiple executions to queue if one is running
    TaskQueueing: "ENABLED",
  },
  CloudWatchLogGroupArn: "arn:aws:logs:us-east-1:123456789012:log-group:/datasync/mcp-models",
  Tags: [{ Key: "project", Value: "mcp-server" }],
}));
console.log(task.TaskArn); // arn:aws:datasync:...:task/task-...

Starting and polling a task execution

Use StartTaskExecutionCommand to kick off a transfer. The returned TaskExecutionArn — not the task ARN — is what you pass to all execution-level operations.

// 4. Start the task execution
const exec = await datasync.send(new StartTaskExecutionCommand({
  TaskArn: task.TaskArn,
  // Optional: per-execution filter override
  // Includes: [{ FilterType: "SIMPLE_PATTERN", Value: "*.onnx|*.gguf" }],
  // Optional: per-execution option overrides
  // OverrideOptions: { BytesPerSecond: -1 }, // unlimited for this run
}));
const execArn = exec.TaskExecutionArn;

// 5. Poll until terminal state
async function waitForExecution(execArn: string, intervalMs = 15_000): Promise {
  const terminalStates = new Set(["SUCCESS", "ERROR"]);
  for (;;) {
    const result = await datasync.send(new DescribeTaskExecutionCommand({
      TaskExecutionArn: execArn,
    }));

    const status = result.Status!;
    console.log(`[${new Date().toISOString()}] status=${status} `
      + `files=${result.FilesTransferred ?? 0} `
      + `bytes=${result.BytesTransferred ?? 0} `
      + `errors=${result.FilesDeleted ?? 0}`
    );

    if (terminalStates.has(status)) {
      if (status === "ERROR") {
        throw new Error(
          `DataSync execution failed: ${result.TaskExecutionArn}`
        );
      }
      return;
    }
    await new Promise(r => setTimeout(r, intervalMs));
  }
}

Task execution status lifecycle

Understanding the status sequence helps you decide when to alarm and when to wait:

Status What's happening Typical duration
QUEUED Execution is waiting for a previous execution on the same task to finish (TaskQueueing: ENABLED) Until the prior execution completes
LAUNCHING DataSync is provisioning transfer workers in your VPC 5–60 seconds
PREPARING DataSync is scanning the source and destination to build the differential file list Seconds to minutes; proportional to file count, not data size
TRANSFERRING Files are being moved; BytesTransferred and FilesTransferred increment Proportional to data volume and bandwidth
VERIFYING DataSync is computing checksums on transferred files at the destination (only when VerifyMode != NONE) Roughly 10–30% of transfer time
SUCCESS All files transferred and verified Terminal
ERROR Transfer failed — check result.Errors array and CloudWatch log group for per-file errors Terminal

Important: DataSync does not automatically retry on ERROR. Your MCP tool must call StartTaskExecutionCommand again after diagnosing the error. Check result.FilesTransferred vs result.FilesSkipped vs result.FilesVerificationFailed to triage before retrying.

Cancelling a running execution

// Cancel the execution (use the execution ARN, not the task ARN)
await datasync.send(new CancelTaskExecutionCommand({
  TaskExecutionArn: execArn,
}));

Cancellation transitions the execution to ERROR within about 30 seconds. Files already transferred to the destination remain — DataSync does not roll back on cancel. If you need atomicity (all-or-nothing), place the destination in a staging prefix and rename it after SUCCESS.

Scheduling DataSync tasks with EventBridge

DataSync has a built-in task schedule (cron syntax in CreateTaskCommand.Schedule.ScheduleExpression), but triggering via EventBridge gives you more control — you can pass override filters, correlate with other pipeline events, and get per-execution CloudWatch events.

// EventBridge rule: run the DataSync task nightly at 02:00 UTC
// (This example uses the AWS CLI — equivalent SDK calls exist)
// aws events put-rule --name datasync-nightly-models \
//   --schedule-expression "cron(0 2 * * ? *)" \
//   --state ENABLED
//
// aws events put-targets --rule datasync-nightly-models \
//   --targets '[{
//     "Id": "StartDataSyncTask",
//     "Arn": "arn:aws:events:us-east-1:123456789012:datasync:task/task-xxx",
//     "RoleArn": "arn:aws:iam::123456789012:role/eventbridge-datasync-invoke"
//   }]'
//
// The IAM role needs: datasync:StartTaskExecution on the task ARN.

Alternatively, an MCP tool that schedules DataSync executions needs only the datasync:StartTaskExecution permission — the task configuration (source, destination, options) is already baked into the task resource.

DataSync vs alternatives

Method Best for Limitations Cost model
DataSync Large (100 GB+) one-time migrations; NFS/SMB to AWS; cross-account S3 copy; EFS/FSx population Minimum task setup overhead; no support for SFTP endpoints (use Transfer Family instead) $0.0125 / GB transferred
aws s3 sync Simple S3 → S3 same-region copies in a script No POSIX metadata; runs from EC2/Lambda (counts as data transfer cost from that compute) Compute cost (Lambda/EC2) + S3 request fees
S3 Cross-Region Replication Continuous replication of new S3 objects across regions Does not replicate pre-existing objects; same-account only unless you use Cross-Account CRR config S3 replication data transfer rate (~$0.02/GB) + S3 replication PUT fees
EFS Replication Continuous disaster-recovery EFS replica in another region Read-only replica; RPO ~hours; cannot select a subset of the file system EFS storage rate for replica + data transfer
rsync / rclone Developer laptops, small data, simple scripts No managed monitoring; runs from your compute; single-threaded rsync is slow for millions of small files Compute cost only

IAM policy for running DataSync from an MCP tool

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DataSyncOperations",
      "Effect": "Allow",
      "Action": [
        "datasync:CreateLocationS3",
        "datasync:CreateLocationEfs",
        "datasync:CreateLocationFsxLustre",
        "datasync:CreateLocationFsxOpenZfs",
        "datasync:CreateTask",
        "datasync:StartTaskExecution",
        "datasync:DescribeTaskExecution",
        "datasync:CancelTaskExecution",
        "datasync:ListTaskExecutions",
        "datasync:DescribeTask",
        "datasync:DeleteTask",
        "datasync:ListLocations",
        "datasync:DescribeLocationS3",
        "datasync:DescribeLocationEfs"
      ],
      "Resource": "*"
    },
    {
      "Sid": "PassRoleToDataSync",
      "Effect": "Allow",
      "Action": "iam:PassRole",
      "Resource": "arn:aws:iam::123456789012:role/datasync-s3-access",
      "Condition": {
        "StringEquals": { "iam:PassedToService": "datasync.amazonaws.com" }
      }
    }
  ]
}

The iam:PassRole permission is required only when creating an S3 location that specifies a BucketAccessRoleArn. EFS and FSx locations with TLS use the caller's own credentials (via FileSystemAccessRoleArn), which also requires a PassRole for that role.

Common errors and fixes

Error Root cause Fix
InvalidRequestException: The source S3 bucket is not accessible BucketAccessRoleArn trust policy missing datasync.amazonaws.com as principal, or aws:SourceAccount condition doesn't match Add "Service": "datasync.amazonaws.com" to trust policy with aws:SourceAccount condition matching your account ID
Task execution stuck in LAUNCHING for >5 minutes DataSync cannot create an ENI in the specified subnet — VPC resource limits or subnet has no available IPs Check ec2:DescribeNetworkInterfaces for stale DataSync ENIs; ensure subnet has free IPs
Task execution stuck in PREPARING for >30 minutes Source has millions of small files — DataSync takes O(file count) time to build the diff list Use IncludeFilters to limit scope, or split into multiple tasks by prefix
InvalidRequestException: TaskExecutionArn not found Passing the task ARN to DescribeTaskExecutionCommand instead of the execution ARN Use the ARN from StartTaskExecutionCommand.TaskExecutionArn, which contains /execution/exec-
InvalidRequestException: Cannot start task while another execution is running A previous execution is still running and TaskQueueing: DISABLED Either set TaskQueueing: ENABLED or cancel the current execution before starting a new one

Monitoring DataSync with CloudWatch

DataSync emits execution-level metrics to the AWS/DataSync namespace. The most useful ones for MCP server pipelines:

Metric Unit What to alarm on
BytesTransferred Bytes Alert if zero for >10 minutes during an expected transfer — indicates a stall
FilesTransferred Count Useful for progress estimation; compare against PREPARING-phase file count
FilesVerificationFailed Count Alert if >0 — indicates destination write corruption or checksum mismatch
FilesSkipped Count Files not transferred because they matched exclude filters or already existed

DataSync also emits task execution events to EventBridge on state changes. Subscribe to {"source": ["aws.datasync"], "detail-type": ["DataSync Task Execution State Change"]} to trigger downstream workflows when a transfer completes.

Related guides