Guide · Amazon S3 · Multipart Upload · Large Files · MCP Server Tools
S3 Multipart Upload for MCP Servers — Large File Uploads, Concurrent Parts, Presigned Parts
S3's single PutObject call works fine up to about 100 MB, but anything larger benefits from multipart upload: split the file into 5 MB – 5 GB parts, upload them concurrently, then assemble at S3. Multipart upload recovers individual failed parts without restarting the whole transfer, saturates available bandwidth with parallel network I/O, and is the only way to upload objects larger than 5 GB in a single request. MCP server tools that handle model weights, training datasets, video exports, audit log archives, or large CSV exports all need multipart upload. This guide covers the three-phase API (CreateMultipartUpload → UploadPart × N → CompleteMultipartUpload), concurrent part uploads with controlled parallelism, presigned part URLs so browser clients upload directly, abort and cleanup on failure, and resume patterns using the ListParts API.
TL;DR
Use multipart upload for files > 100 MB. Minimum part size is 5 MB (except the last part). Call CreateMultipartUpload first to get an UploadId. Upload each part with UploadPart, collecting the ETag from each response. Finish with CompleteMultipartUpload passing all ETags in part-number order. Always abort with AbortMultipartUpload on failure — incomplete uploads incur storage charges until aborted. For client-side uploads, generate presigned URLs per part with getSignedUrl(UploadPartCommand). Use an S3 lifecycle rule with AbortIncompleteMultipartUploads as a safety net for abandoned uploads.
When to use multipart upload
AWS documentation recommends multipart upload for files larger than 100 MB. It is required for files larger than 5 GB. Beyond the size requirement, multipart upload provides several practical benefits for MCP server tools:
- Fault tolerance: A failed part can be retried individually. With
PutObject, a network hiccup at 90% completion means restarting from zero. - Throughput: Parts upload in parallel, saturating available bandwidth. A 1 GB file uploaded in 20 × 50 MB concurrent parts is roughly 20× faster than a serial upload on a fast connection.
- Progress reporting: You can report upload progress part-by-part to the calling agent or user.
- Memory efficiency: You can stream parts from disk or a readable stream without loading the entire file into memory.
| File size | Recommended approach | Notes |
|---|---|---|
| < 5 MB | PutObject | Simpler; multipart minimum part size is 5 MB anyway |
| 5 MB – 100 MB | Either | Multipart adds overhead for little gain at this range |
| 100 MB – 5 GB | Multipart upload | Fault tolerance + speed benefit clear |
| > 5 GB | Multipart upload required | PutObject rejects with EntityTooLarge |
Three-phase API: Create → Upload → Complete
Multipart upload is a three-phase protocol. Phase 1 creates the upload and returns an UploadId. Phase 2 uploads individual parts, each returning an ETag. Phase 3 assembles the parts by passing the ordered ETag list back to S3.
import {
S3Client,
CreateMultipartUploadCommand,
UploadPartCommand,
CompleteMultipartUploadCommand,
AbortMultipartUploadCommand,
} from '@aws-sdk/client-s3';
import { createReadStream, statSync } from 'fs';
const s3 = new S3Client({ region: 'us-east-1' });
const PART_SIZE = 50 * 1024 * 1024; // 50 MB per part (must be >= 5 MB except last)
async function uploadLargeFile(bucket: string, key: string, filePath: string) {
const fileSize = statSync(filePath).size;
const numParts = Math.ceil(fileSize / PART_SIZE);
// --- Phase 1: Create the multipart upload ---
const { UploadId } = await s3.send(
new CreateMultipartUploadCommand({
Bucket: bucket,
Key: key,
ContentType: 'application/octet-stream',
// Set metadata and storage class here — cannot change after creation
StorageClass: 'STANDARD_IA',
ServerSideEncryption: 'aws:kms',
})
);
if (!UploadId) throw new Error('CreateMultipartUpload returned no UploadId');
const completedParts: { ETag: string; PartNumber: number }[] = [];
try {
// --- Phase 2: Upload parts ---
for (let partNumber = 1; partNumber <= numParts; partNumber++) {
const start = (partNumber - 1) * PART_SIZE;
const end = Math.min(start + PART_SIZE, fileSize);
const partSize = end - start;
const partStream = createReadStream(filePath, { start, end: end - 1 });
const { ETag } = await s3.send(
new UploadPartCommand({
Bucket: bucket,
Key: key,
UploadId,
PartNumber: partNumber, // 1-indexed, 1 to 10,000
Body: partStream,
ContentLength: partSize, // required when body is a stream
})
);
if (!ETag) throw new Error(`Part ${partNumber} returned no ETag`);
completedParts.push({ ETag, PartNumber: partNumber });
console.log(`Uploaded part ${partNumber}/${numParts}`);
}
// --- Phase 3: Complete the upload ---
const { Location } = await s3.send(
new CompleteMultipartUploadCommand({
Bucket: bucket,
Key: key,
UploadId,
MultipartUpload: {
Parts: completedParts.sort((a, b) => a.PartNumber - b.PartNumber),
},
})
);
return Location; // https://bucket.s3.amazonaws.com/key
} catch (err) {
// --- Always abort on any failure ---
await s3.send(new AbortMultipartUploadCommand({ Bucket: bucket, Key: key, UploadId }));
throw err;
}
}
The ETag returned by each UploadPart is an MD5 hash of the part bytes, surrounded by double quotes (e.g. "abc123..."). Store it exactly as returned — including the quotes. CompleteMultipartUpload will reject with InvalidPart if the ETags don't match what S3 computed.
Concurrent part uploads
Serial uploads leave available bandwidth unused. For large files, uploading 4–8 parts concurrently typically provides the best throughput without overwhelming the host network interface or hitting S3 rate limits. Use a semaphore to cap concurrent uploads.
import PQueue from 'p-queue'; // or implement your own semaphore
async function uploadLargeFileConcurrent(
bucket: string,
key: string,
filePath: string,
concurrency = 5
) {
const fileSize = statSync(filePath).size;
const numParts = Math.ceil(fileSize / PART_SIZE);
const { UploadId } = await s3.send(
new CreateMultipartUploadCommand({ Bucket: bucket, Key: key })
);
if (!UploadId) throw new Error('no UploadId');
const completedParts: { ETag: string; PartNumber: number }[] = [];
const queue = new PQueue({ concurrency });
const errors: Error[] = [];
for (let partNumber = 1; partNumber <= numParts; partNumber++) {
const pn = partNumber; // capture for closure
queue.add(async () => {
if (errors.length > 0) return; // bail on first error
const start = (pn - 1) * PART_SIZE;
const end = Math.min(start + PART_SIZE, fileSize);
try {
const { ETag } = await s3.send(
new UploadPartCommand({
Bucket: bucket,
Key: key,
UploadId,
PartNumber: pn,
Body: createReadStream(filePath, { start, end: end - 1 }),
ContentLength: end - start,
})
);
if (!ETag) throw new Error(`Part ${pn} returned no ETag`);
completedParts.push({ ETag, PartNumber: pn });
} catch (err) {
errors.push(err as Error);
}
});
}
await queue.onIdle();
if (errors.length > 0) {
await s3.send(new AbortMultipartUploadCommand({ Bucket: bucket, Key: key, UploadId }));
throw errors[0];
}
await s3.send(
new CompleteMultipartUploadCommand({
Bucket: bucket,
Key: key,
UploadId,
MultipartUpload: {
Parts: completedParts.sort((a, b) => a.PartNumber - b.PartNumber),
},
})
);
}
Concurrency guidance: 4–8 concurrent parts is a sweet spot for most network conditions. Avoid going above 20 — S3 may throttle your uploads and return SlowDown (HTTP 503), and high concurrency can exhaust file descriptors if each part opens a new read stream.
Presigned URLs for client-side multipart upload
When a browser or external client needs to upload a large file directly to S3 — bypassing your MCP server — your server generates presigned URLs for each part. The client uploads each part to its URL, sends the ETags back to your server, and your server calls CompleteMultipartUpload. This keeps large binary data off your server's network path.
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
interface PresignedPartUrl {
partNumber: number;
url: string;
}
// Called by MCP tool: initiate_upload
async function initiateMultipartUpload(bucket: string, key: string, numParts: number) {
const { UploadId } = await s3.send(
new CreateMultipartUploadCommand({ Bucket: bucket, Key: key })
);
if (!UploadId) throw new Error('no UploadId');
// Generate one presigned URL per part (expires in 1 hour)
const presignedUrls: PresignedPartUrl[] = await Promise.all(
Array.from({ length: numParts }, (_, i) => i + 1).map(async (partNumber) => {
const url = await getSignedUrl(
s3,
new UploadPartCommand({ Bucket: bucket, Key: key, UploadId, PartNumber: partNumber }),
{ expiresIn: 3600 }
);
return { partNumber, url };
})
);
// Return UploadId + presigned URLs to the client
// Client uploads each part via PUT to the URL and collects ETags from response headers
return { uploadId: UploadId, parts: presignedUrls };
}
// Called by MCP tool: complete_upload
async function completeMultipartUpload(
bucket: string,
key: string,
uploadId: string,
parts: { partNumber: number; etag: string }[]
) {
await s3.send(
new CompleteMultipartUploadCommand({
Bucket: bucket,
Key: key,
UploadId: uploadId,
MultipartUpload: {
Parts: parts
.sort((a, b) => a.partNumber - b.partNumber)
.map((p) => ({ PartNumber: p.partNumber, ETag: p.etag })),
},
})
);
}
The client extracts the ETag from the ETag response header of each part's PUT request. If the client uses fetch, note that browsers may block access to the ETag header on cross-origin responses unless S3 CORS is configured to expose it: ExposeHeaders: ['ETag'].
Abort and cleanup on failure
Incomplete multipart uploads — uploads started but never completed or aborted — accumulate storage costs silently. S3 bills you for each uploaded part even if the upload was never completed. Always abort on failure in your error handler, and add a lifecycle rule as a safety net for abandoned uploads.
// Safety net: lifecycle rule to abort abandoned multipart uploads after 7 days
import { PutBucketLifecycleConfigurationCommand } from '@aws-sdk/client-s3';
await s3.send(
new PutBucketLifecycleConfigurationCommand({
Bucket: 'your-bucket',
LifecycleConfiguration: {
Rules: [
{
ID: 'abort-incomplete-multipart-uploads',
Status: 'Enabled',
Filter: { Prefix: '' }, // apply to all objects
AbortIncompleteMultipartUploads: {
DaysAfterInitiation: 7,
},
},
],
},
})
);
To list in-flight multipart uploads (useful for debugging or manual cleanup):
import { ListMultipartUploadsCommand } from '@aws-sdk/client-s3';
const { Uploads } = await s3.send(
new ListMultipartUploadsCommand({ Bucket: 'your-bucket' })
);
for (const upload of Uploads ?? []) {
console.log(upload.Key, upload.UploadId, upload.Initiated);
// abort if older than your threshold
const ageMs = Date.now() - new Date(upload.Initiated!).getTime();
if (ageMs > 24 * 60 * 60 * 1000) {
await s3.send(new AbortMultipartUploadCommand({
Bucket: 'your-bucket',
Key: upload.Key!,
UploadId: upload.UploadId!,
}));
}
}
Resume an interrupted upload with ListParts
If your MCP server crashes mid-upload, you can resume by listing the already-uploaded parts and skipping them. This avoids re-uploading data you already paid to transfer.
import { ListPartsCommand } from '@aws-sdk/client-s3';
async function resumeOrUpload(bucket: string, key: string, uploadId: string, filePath: string) {
const fileSize = statSync(filePath).size;
const numParts = Math.ceil(fileSize / PART_SIZE);
// List parts already uploaded for this UploadId
const { Parts: existingParts = [] } = await s3.send(
new ListPartsCommand({ Bucket: bucket, Key: key, UploadId: uploadId })
);
const uploadedPartNumbers = new Set(existingParts.map((p) => p.PartNumber!));
const completedParts = existingParts.map((p) => ({
ETag: p.ETag!,
PartNumber: p.PartNumber!,
}));
for (let partNumber = 1; partNumber <= numParts; partNumber++) {
if (uploadedPartNumbers.has(partNumber)) {
console.log(`Skipping already-uploaded part ${partNumber}`);
continue;
}
const start = (partNumber - 1) * PART_SIZE;
const end = Math.min(start + PART_SIZE, fileSize);
const { ETag } = await s3.send(
new UploadPartCommand({
Bucket: bucket,
Key: key,
UploadId: uploadId,
PartNumber: partNumber,
Body: createReadStream(filePath, { start, end: end - 1 }),
ContentLength: end - start,
})
);
completedParts.push({ ETag: ETag!, PartNumber: partNumber });
}
await s3.send(
new CompleteMultipartUploadCommand({
Bucket: bucket,
Key: key,
UploadId: uploadId,
MultipartUpload: { Parts: completedParts.sort((a, b) => a.PartNumber - b.PartNumber) },
})
);
}
Persist the UploadId (and optionally a part manifest) to a database or the file system between upload sessions. The UploadId is valid for 7 days after the last activity. After 7 days of inactivity S3 expires the upload and ListParts will return NoSuchUpload.
Using the high-level Upload helper
The AWS SDK v3 ships a high-level Upload class in @aws-sdk/lib-storage that handles part splitting, concurrent uploads, retries, and abort on failure automatically. Use it when you don't need fine-grained control over part management.
import { Upload } from '@aws-sdk/lib-storage';
import { createReadStream } from 'fs';
const upload = new Upload({
client: s3,
params: {
Bucket: 'your-bucket',
Key: 'large-file.bin',
Body: createReadStream('/path/to/large-file.bin'),
},
queueSize: 4, // concurrent part uploads
partSize: 50 * 1024 * 1024, // 50 MB per part
leavePartsOnError: false, // abort on failure (default)
});
// Progress events
upload.on('httpUploadProgress', (progress) => {
const pct = Math.round((progress.loaded! / progress.total!) * 100);
console.log(`Upload progress: ${pct}%`);
});
await upload.done();
The @aws-sdk/lib-storage package is a first-party AWS helper and is production-safe. For MCP server tools that upload files as a secondary concern, use the Upload helper. Use the low-level API when you need presigned part URLs for client-side uploads, need to implement pause/resume, or need to report per-part status to callers.
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
EntityTooSmall | Part smaller than 5 MB (except last part) | Increase PART_SIZE constant; note the 5 MB minimum applies to all parts except the final one |
EntityTooLarge on PutObject | File > 5 GB uploaded with single PutObject | Switch to multipart upload — required above 5 GB |
InvalidPart | ETag in CompleteMultipartUpload doesn't match what S3 stored | Pass ETags exactly as returned (with surrounding quotes); ensure parts list is sorted by PartNumber |
NoSuchUpload | UploadId expired (7 days inactivity) or never created | Start a new multipart upload; add lifecycle rule for auto-abort |
TooManyParts | More than 10,000 parts | Increase part size to fit within 10,000-part limit: Math.ceil(fileSize / 10000) |
| ETag missing from CORS response | Browser can't read ETag header on cross-origin presigned part upload | Add ExposeHeaders: ['ETag'] to S3 bucket CORS configuration |
| Orphaned incomplete uploads billing | Crash before abort, abandoned uploads | Add AbortIncompleteMultipartUploads lifecycle rule; always abort in catch |
ContentLength required error | Streaming body without length in SDK v3 | Always pass ContentLength: partSize when Body is a stream, not a Buffer |
Related guides
- S3 for MCP servers: buckets, IAM, versioning, encryption
- S3 presigned URLs: temporary GET/PUT access, expiry, security
- S3 lifecycle policies: transition to cheaper storage tiers, expiry rules
- S3 event notifications: trigger Lambda or SQS on object create/delete
- S3 access points: per-workload access control policies