Guide · Amazon S3 · Presigned URLs · Temporary Access · MCP Server Tools

S3 Presigned URLs for MCP Servers — Temporary GET/PUT Access, Expiry, Security

Presigned URLs are time-limited, cryptographically signed URLs that grant temporary access to a specific S3 object — without exposing your AWS credentials or making the bucket public. MCP server tools use presigned GET URLs to give calling agents or users temporary read access to private files (reports, exports, generated assets), and presigned PUT URLs so clients can upload files directly to S3 without routing large binary payloads through your server. This guide covers generating presigned GET and PUT URLs with @aws-sdk/s3-request-presigner, expiry limits, IAM constraints that affect presigned URL validity, CORS configuration for browser uploads, security pitfalls to avoid, and patterns for validating what clients actually uploaded.

TL;DR

Use getSignedUrl(s3, new GetObjectCommand({...}), { expiresIn: N }) for temporary read access. Use getSignedUrl(s3, new PutObjectCommand({...}), { expiresIn: N }) for client-direct uploads. Maximum expiry is 7 days (604800 seconds) for IAM user credentials; for assumed-role (Lambda, ECS) credentials the expiry is capped at the role session duration (typically 1 hour). Never log or cache presigned URLs — anyone who obtains one can use it. Always validate uploaded content (size, type) separately after upload; ContentType in the presigned PUT URL is a header hint the client can override.

Generating presigned GET URLs

A presigned GET URL allows anyone with the URL to download the specified object until the URL expires. Use it when an agent or user needs temporary access to a private file — a generated report, a data export, a model artifact — without granting them IAM credentials.

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

const s3 = new S3Client({ region: 'us-east-1' });

// MCP tool: get_download_url
async function getDownloadUrl(bucket: string, key: string): Promise {
  const url = await getSignedUrl(
    s3,
    new GetObjectCommand({
      Bucket: bucket,
      Key: key,
      // Optional: override response headers on download
      ResponseContentDisposition: 'attachment; filename="report.csv"',
      ResponseContentType: 'text/csv',
    }),
    { expiresIn: 3600 } // 1 hour
  );
  return url;
}

The ResponseContentDisposition and ResponseContentType overrides in the GetObjectCommand are embedded in the signature. The browser will use these headers when the user opens the link, overriding whatever Content-Disposition was set when the object was uploaded. This is useful for forcing downloads (attachment) vs inline display (inline).

Downloading directly from a presigned GET URL

// From a Lambda or external service using the presigned URL
const response = await fetch(presignedUrl);
if (!response.ok) throw new Error(`Download failed: ${response.status}`);
const content = await response.arrayBuffer();
// Process content...

Generating presigned PUT URLs

A presigned PUT URL lets a client upload a file directly to S3 without routing the data through your MCP server. The client makes an HTTP PUT request to the URL with the file as the body. Your server never touches the file bytes — only the signed URL metadata.

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

// MCP tool: get_upload_url
async function getUploadUrl(
  bucket: string,
  key: string,
  contentType: string
): Promise {
  const url = await getSignedUrl(
    s3,
    new PutObjectCommand({
      Bucket: bucket,
      Key: key,
      ContentType: contentType, // Client MUST send matching Content-Type header
      // Enforce size limit via policy (see below) — not enforced by presigned URL alone
    }),
    { expiresIn: 900 } // 15 minutes — keep PUT URLs short-lived
  );
  return url;
}

// Client-side usage (browser or external service):
// fetch(uploadUrl, {
//   method: 'PUT',
//   headers: { 'Content-Type': contentType },
//   body: file
// });

Important: The ContentType in the PutObjectCommand is embedded in the signature. If the client sends a different Content-Type header, S3 returns SignatureDoesNotMatch. Instruct your client to use exactly the content type your server specified when generating the URL.

Expiry limits and credential type constraints

The maximum expiry depends on the type of AWS credentials used to sign the URL. This is the most common source of confusion with presigned URLs.

Credential typeMax expiryNotes
IAM user long-term credentials (aws_access_key_id)7 days (604800s)Avoid in production — long-term credentials are a security risk
IAM role via AssumeRole (Lambda, ECS, EC2 instance profile)Role session durationDefault session = 1 hour; maximum = 12 hours; URL invalid after session expires even if expiresIn was longer
Federated/web identity credentialsSession duration of the assumed roleSame constraint as AssumeRole

The critical pitfall: if your Lambda function uses a 1-hour session token and you generate a presigned URL with expiresIn: 86400 (24 hours), the URL will stop working after 1 hour — when the underlying session expires. The URL's listed expiry time is a maximum, not a guarantee.

// To get longer-lived presigned URLs from Lambda/ECS:
// 1. Create a dedicated IAM user with S3-only permissions (use long-term credentials)
// 2. OR increase the role session duration in the IAM role trust policy (max 12h)
// 3. OR generate the presigned URL server-side from a long-lived signing service

// Example: use a separate client with longer-lived credentials for presigning
import { fromIni } from '@aws-sdk/credential-providers';

const presigningClient = new S3Client({
  region: 'us-east-1',
  credentials: fromIni({ profile: 's3-presign-role' }),
  // This role has sessionDuration: 43200 (12 hours) in its trust policy
});

CORS configuration for browser uploads

When a browser uploads a file via a presigned PUT URL, it makes a cross-origin request. S3 CORS must explicitly allow the origin, method, and headers used in the upload. Without CORS, the browser's preflight OPTIONS request fails and the upload never starts.

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

await s3.send(
  new PutBucketCorsCommand({
    Bucket: 'your-bucket',
    CORSConfiguration: {
      CORSRules: [
        {
          AllowedOrigins: ['https://your-app.com'],  // never use '*' for PUT
          AllowedMethods: ['GET', 'PUT', 'HEAD'],
          AllowedHeaders: ['*'],
          ExposeHeaders: ['ETag'],  // required for multipart upload ETags
          MaxAgeSeconds: 3600,
        },
      ],
    },
  })
);

Never set AllowedOrigins: ['*'] for PUT operations — it allows any website to upload to your bucket using a presigned URL you generated. Restrict to your known origins. For GET-only downloads where you don't care about the calling origin, * is acceptable if the bucket already enforces IAM-based authorization through the presigned URL mechanism.

Enforcing upload constraints with conditions

Presigned PUT URLs alone don't enforce file size limits or content type validation — the client can upload anything within the URL's validity window. Use S3 POST policy conditions for stricter enforcement, or validate after upload.

// Post-upload validation: check the uploaded object's metadata
import { HeadObjectCommand } from '@aws-sdk/client-s3';

async function validateUpload(
  bucket: string,
  key: string,
  expectedContentType: string,
  maxSizeBytes: number
) {
  let head;
  try {
    head = await s3.send(new HeadObjectCommand({ Bucket: bucket, Key: key }));
  } catch (err: any) {
    if (err.name === 'NotFound') throw new Error('File was not uploaded');
    throw err;
  }

  const actualType = head.ContentType ?? '';
  if (!actualType.startsWith(expectedContentType)) {
    // Delete the invalid upload
    await s3.send(new DeleteObjectCommand({ Bucket: bucket, Key: key }));
    throw new Error(`Invalid content type: ${actualType}`);
  }

  const size = head.ContentLength ?? 0;
  if (size > maxSizeBytes) {
    await s3.send(new DeleteObjectCommand({ Bucket: bucket, Key: key }));
    throw new Error(`File too large: ${size} bytes (max ${maxSizeBytes})`);
  }

  return { size, contentType: actualType };
}

An alternative is S3 POST policies (using createPresignedPost from @aws-sdk/s3-presigned-post), which embed conditions directly in the signed policy: ['content-length-range', 0, maxBytes] and ['eq', '$Content-Type', 'image/jpeg']. S3 rejects uploads that violate conditions before accepting any bytes, which is more efficient for large-file abuse prevention.

import { createPresignedPost } from '@aws-sdk/s3-presigned-post';

const { url, fields } = await createPresignedPost(s3, {
  Bucket: 'your-bucket',
  Key: key,
  Conditions: [
    ['content-length-range', 1, 10 * 1024 * 1024], // 1 byte to 10 MB
    ['eq', '$Content-Type', 'image/jpeg'],
  ],
  Fields: { 'Content-Type': 'image/jpeg' },
  Expires: 300, // 5 minutes
});

// Client must POST a multipart/form-data with these fields + the file
// Unlike PUT presigned URLs, POST policy uses form submission, not raw PUT

Security patterns

// Enforce SSE-KMS on client-direct PUT upload
const url = await getSignedUrl(
  s3,
  new PutObjectCommand({
    Bucket: bucket,
    Key: key,
    ContentType: 'image/jpeg',
    ServerSideEncryption: 'aws:kms',
    SSEKMSKeyId: 'arn:aws:kms:us-east-1:123456789012:key/mrk-...',
  }),
  { expiresIn: 900 }
);
// Client must include x-amz-server-side-encryption: aws:kms header
// or S3 rejects with SignatureDoesNotMatch

Common errors and fixes

ErrorCauseFix
SignatureDoesNotMatchClient sent a header or query param that wasn't in the signed request (Content-Type mismatch, extra headers)Send exactly the headers used to generate the presigned URL; don't add extra headers
AccessDenied before expiryRole session expired before the URL's listed expiryEnsure URL expiry ≤ remaining role session duration; use longer-lived signing credentials
AccessDenied immediatelySigning IAM principal doesn't have s3:GetObject or s3:PutObject permissionAdd required permission to the signing role; presigned URL inherits the signer's permissions at request time
CORS preflight failsAllowedOrigins, AllowedMethods, or AllowedHeaders don't match client requestAdd the client origin and method to CORS; allow Content-Type and x-amz-* headers
URL works for first user, fails for othersPresigned URL is single-use by design? (No — it's multi-use until expiry)Actually a credential expiry issue — multiple users triggered requests after session expired
InvalidArgument: Expires must be less than...Requested expiry exceeds credential session durationReduce expiresIn to match session duration

Related guides