Guide · Amazon Redshift · COPY Command · Bulk Loading · MCP Server Tools

Redshift COPY Command for MCP Servers — Bulk Load from S3, IAM Role, Error Handling

The Redshift COPY command is the fastest way to load data into Redshift tables: it parallelizes across Redshift compute nodes, pushes predicate filtering to the S3 tier, and handles Parquet, CSV, JSON, and several other formats natively. For MCP server tools that ingest datasets — user uploads, pipeline outputs, batch exports from other systems — COPY is 10–100× faster than row-by-row INSERTs. The challenge is that COPY doesn't execute synchronously like a SELECT: it's an async operation managed through the Redshift Data API, it requires an IAM role attached to the Redshift resource (not the caller), and when rows fail validation, the error details are buried in the STL_LOAD_ERRORS system table rather than returned in the API response. This guide covers IAM role setup, the complete COPY syntax for each supported format, manifest files for precise file lists, error handling and diagnostics, and best practices for MCP data-ingestion tools.

TL;DR

COPY requires an IAM role attached to the Redshift cluster/namespace with S3 read access and trust principal redshift.amazonaws.com. Run COPY via the Redshift Data API using ExecuteStatementCommand; it completes when DescribeStatementCommand returns FINISHED. After completion, always check STL_LOAD_ERRORS — COPY can partially succeed, loading valid rows while silently skipping invalid ones if you use the MAXERROR option. Use a manifest JSON file in S3 to specify exactly which files to load; without a manifest, COPY loads all objects with the given S3 prefix, which can include files from previous loads if you don't clean up. For Parquet, skip the format options entirely — just specify the S3 path and IAM role; Parquet schema is auto-detected.

IAM role for COPY — attached to the cluster, not the caller

The most common first-time mistake with COPY is trying to use the caller's IAM credentials to access S3. COPY does not use the IAM principal that called the Data API. Instead, Redshift assumes a role that is attached to the cluster (provisioned) or namespace (Serverless) at the time of COPY execution. The caller's IAM policy only needs Data API permissions; S3 access is entirely through the attached role.

# Step 1: Create the COPY IAM role with Redshift trust
aws iam create-role \
  --role-name RedshiftCopyRole \
  --assume-role-policy-document '{
    "Version": "2012-10-17",
    "Statement": [{
      "Effect": "Allow",
      "Principal": { "Service": "redshift.amazonaws.com" },
      "Action": "sts:AssumeRole"
    }]
  }'

# Step 2: Grant S3 read access on the data bucket
aws iam put-role-policy \
  --role-name RedshiftCopyRole \
  --policy-name S3ReadAccess \
  --policy-document '{
    "Version": "2012-10-17",
    "Statement": [{
      "Effect": "Allow",
      "Action": ["s3:GetObject", "s3:ListBucket"],
      "Resource": [
        "arn:aws:s3:::my-ingest-bucket",
        "arn:aws:s3:::my-ingest-bucket/*"
      ]
    }]
  }'

# Step 3a: Attach to provisioned cluster
aws redshift modify-cluster-iam-roles \
  --cluster-identifier my-cluster \
  --add-iam-roles arn:aws:iam::123456789012:role/RedshiftCopyRole

# Step 3b: For Serverless, include in CreateNamespaceCommand.iamRoles[]
# or UpdateNamespaceCommand if adding after creation

The role ARN is referenced directly in the COPY statement text as IAM_ROLE 'arn:aws:iam::123456789012:role/RedshiftCopyRole'. Using the alias IAM_ROLE default uses the first attached role alphabetically — always specify the full ARN explicitly to avoid surprising behavior when multiple roles are attached.

COPY syntax and execution via the Data API

COPY runs as a standard SQL statement through the Data API. The statement is long-running (seconds to minutes depending on data volume), so the Data API's async pattern — submit and poll — is exactly the right model.

import {
  RedshiftDataClient,
  ExecuteStatementCommand,
  DescribeStatementCommand,
  GetStatementResultCommand,
  StatusString,
} from "@aws-sdk/client-redshift-data";

const rsData = new RedshiftDataClient({ region: "us-east-1" });

async function runCopy(params: {
  table: string;
  s3Path: string;       // s3://bucket/prefix/ or s3://bucket/prefix/manifest.json
  iamRoleArn: string;
  format: "parquet" | "csv" | "json";
  options?: string;     // additional COPY options
  workgroupName?: string;
  clusterIdentifier?: string;
  database: string;
}) {
  const formatClause = buildFormatClause(params.format, params.options);

  const copySql = [
    `COPY ${params.table}`,
    `FROM '${params.s3Path}'`,
    `IAM_ROLE '${params.iamRoleArn}'`,
    formatClause,
    "REGION 'us-east-1'",
    "STATUPDATE OFF",    // skip automatic stats update on small loads
    "COMPUPDATE OFF",    // skip automatic compression analysis on repeated loads
  ].filter(Boolean).join("\n");

  const cmd: ExecuteStatementCommand = new ExecuteStatementCommand({
    ...(params.workgroupName ? { WorkgroupName: params.workgroupName } : { ClusterIdentifier: params.clusterIdentifier }),
    Database: params.database,
    Sql: copySql,
  });

  const { Id: statementId } = await rsData.send(cmd);

  // Poll until terminal state — COPY can run for minutes
  for (let i = 0; i < 180; i++) {
    const { Status, Error: err, HasResultSet } = await rsData.send(
      new DescribeStatementCommand({ Id: statementId! })
    );

    if (Status === StatusString.FINISHED) return statementId!;
    if (Status === StatusString.FAILED) {
      throw new Error(`COPY failed: ${err}`);
    }
    if (Status === StatusString.ABORTED) {
      throw new Error("COPY aborted");
    }
    await new Promise(r => setTimeout(r, 5_000));  // poll every 5 seconds
  }
  throw new Error("COPY timed out after 15 minutes");
}

function buildFormatClause(format: string, extra?: string): string {
  switch (format) {
    case "parquet": return "FORMAT AS PARQUET";
    case "csv":     return `CSV IGNOREHEADER 1 QUOTE '\"' DELIMITER ',' ${extra ?? ""}`;
    case "json":    return `JSON 'auto ignorecase' ${extra ?? ""}`;
    default:        throw new Error(`Unsupported format: ${format}`);
  }
}

STATUPDATE OFF and COMPUPDATE OFF are important performance flags for repeated programmatic loads. ANALYZE (statistics update) and compression analysis add significant overhead to each COPY run; for automated pipelines that load frequently, run ANALYZE tablename separately on a maintenance schedule rather than on every load.

Format-specific COPY options

Parquet — the simplest option

Parquet schema is auto-detected by Redshift. The COPY statement needs only the format keyword, S3 path, and IAM role. Column names in the Parquet file must match Redshift column names (case-insensitive). No delimiter, quote character, or header options needed:

COPY sales FROM 's3://ingest-bucket/sales/2026-11-12/'
IAM_ROLE 'arn:aws:iam::123456789012:role/RedshiftCopyRole'
FORMAT AS PARQUET
REGION 'us-east-1';

CSV — common gotchas

CSV loading has several pitfalls: header row handling, quoting behavior, delimiter choice, and NULL representation:

COPY customers FROM 's3://ingest-bucket/customers/batch-20261112.csv'
IAM_ROLE 'arn:aws:iam::123456789012:role/RedshiftCopyRole'
CSV                     -- enables CSV mode (handles embedded commas inside quotes)
IGNOREHEADER 1          -- skip the first header row; without this, header is loaded as data
QUOTE '"'               -- quote character for fields containing the delimiter
DELIMITER ','           -- redundant with CSV mode default but explicit is safer
NULL AS '\N'            -- treat \N as SQL NULL; default treats empty string as NULL for VARCHAR
DATEFORMAT 'YYYY-MM-DD' -- prevent ambiguity on date columns
TIMEFORMAT 'YYYY-MM-DD HH:MI:SS'
TRIMBLANKS              -- trim leading/trailing whitespace from VARCHAR values
ENCODING UTF8
REGION 'us-east-1';

JSON — auto-mapping and path files

JSON COPY has two mapping modes: JSON 'auto' maps JSON keys to column names (case-sensitive by default), and JSON 'auto ignorecase' matches case-insensitively. For custom key-to-column mapping, provide a JSONPaths file in S3:

-- JSONPaths file (s3://ingest-bucket/paths/events.jsonpaths):
-- { "jsonpaths": ["$.event_id", "$.user_id", "$.event_type", "$.ts"] }

COPY events (event_id, user_id, event_type, event_at)
FROM 's3://ingest-bucket/events/raw/'
IAM_ROLE 'arn:aws:iam::123456789012:role/RedshiftCopyRole'
JSON 's3://ingest-bucket/paths/events.jsonpaths'
REGION 'us-east-1';

-- Ndjson (newline-delimited JSON, one object per line) — the default for JSON COPY
-- For JSON arrays (array of objects), not natively supported; transform before loading

JSON COPY expects newline-delimited JSON (one JSON object per line), not JSON arrays. If your source produces JSON arrays, you must flatten them to NDJSON before loading. Kinesis Firehose's Lambda transformation is a common pre-processing step for this conversion.

Manifest files — precise file control

Without a manifest, COPY loads every S3 object with the given prefix — including files from previous loads, partial writes, or unintended objects. For production pipelines, always use a manifest that explicitly lists the files to load. This prevents double-loading and handles the case where multiple producers write to the same prefix concurrently.

// Generate and upload a manifest before each COPY run
async function createAndUploadManifest(
  s3Client: S3Client,
  bucket: string,
  manifestKey: string,
  fileKeys: string[]
): Promise<string> {
  const manifest = {
    entries: fileKeys.map(key => ({
      url: `s3://${bucket}/${key}`,
      mandatory: true,  // fail COPY if this file is missing (default: false)
    })),
  };

  await s3Client.send(new PutObjectCommand({
    Bucket: bucket,
    Key: manifestKey,
    Body: JSON.stringify(manifest),
    ContentType: "application/json",
  }));

  return `s3://${bucket}/${manifestKey}`;
}

// COPY with manifest
const manifestS3Url = await createAndUploadManifest(
  s3Client,
  "ingest-bucket",
  "manifests/batch-20261112T150000Z.json",
  ["data/2026-11-12/part-0001.parquet", "data/2026-11-12/part-0002.parquet"]
);

const copySql = `
  COPY sales
  FROM '${manifestS3Url}'
  IAM_ROLE 'arn:aws:iam::123456789012:role/RedshiftCopyRole'
  FORMAT AS PARQUET
  MANIFEST                -- tells COPY to treat the S3 path as a manifest, not a prefix
  REGION 'us-east-1'
`;

When mandatory: true is set for an entry, COPY fails immediately if any mandatory file is missing from S3. Without mandatory: true, missing files are silently skipped. Use mandatory: true for data integrity in production pipelines.

Error handling — STL_LOAD_ERRORS

COPY has two error behaviors controlled by the MAXERROR option. By default (MAXERROR 0), any row that fails validation causes the entire COPY to fail. With MAXERROR N, COPY continues loading valid rows and skips invalid ones up to N errors, then succeeds if the threshold isn't exceeded. The skipped rows and their error reasons are stored in STL_LOAD_ERRORS.

-- COPY with error tolerance (logs failures, doesn't fail the entire load)
COPY events
FROM 's3://ingest-bucket/events/'
IAM_ROLE 'arn:aws:iam::123456789012:role/RedshiftCopyRole'
FORMAT AS PARQUET
MAXERROR 100       -- tolerate up to 100 row errors; fail if more
REGION 'us-east-1';
// After COPY completes (even when FINISHED), check for load errors
async function checkLoadErrors(
  statementId: string,
  workgroupOrCluster: { WorkgroupName?: string; ClusterIdentifier?: string },
  database: string
) {
  // The load_error_detail session variable is set after each COPY
  // Query STL_LOAD_ERRORS to get per-row error details
  const errorQueryId = await executeAndWait({
    ...workgroupOrCluster,
    Database: database,
    Sql: `
      SELECT
        starttime,
        filename,
        line_number,
        colname,
        type,
        col_length,
        position,
        raw_line,
        raw_field_value,
        err_code,
        err_reason
      FROM STL_LOAD_ERRORS
      WHERE session = pg_backend_pid()
        AND starttime >= DATEADD(minutes, -5, GETDATE())
      ORDER BY starttime DESC
      LIMIT 100
    `,
  });

  const { rows } = await fetchAllPages(errorQueryId);
  return rows;
}

// Always call after COPY, even on success:
const loadErrors = await checkLoadErrors(statementId, { WorkgroupName: "analytics-wg" }, "analytics");
if (loadErrors.length > 0) {
  console.warn(`COPY completed with ${loadErrors.length} row errors:`, loadErrors[0]);
}

STL_LOAD_ERRORS is a Redshift system view only accessible through direct cluster connections or the Data API — it is not exposed through Redshift's public monitoring APIs. Each row contains the raw input data (raw_line), the specific field that failed (raw_field_value, colname), and a human-readable error reason (err_reason). Common errors: type mismatch (string where integer expected), value too long for VARCHAR(N), date format mismatch, encoding issues.

COPY options reference table

OptionPurposeRecommended default
COMPUPDATE OFFSkip compression encoding analysisON for first load of a table; OFF for subsequent loads
STATUPDATE OFFSkip automatic ANALYZE after loadON for infrequent loads; OFF for frequent small loads
MAXERROR NTolerate up to N row errors before failing0 for critical data; 100 for log data with known noise
TRUNCATECOLUMNSSilently truncate values longer than column lengthAvoid — use MAXERROR + investigate errors instead
MANIFESTTreat S3 path as a manifest JSON fileAlways in production to prevent double-loading
IGNOREHEADER 1Skip first row (header) in CSV filesAlways for CSV files with header rows
TIMEFORMAT 'epochsecs'Parse Unix epoch seconds as TIMESTAMPUseful for event data stored as epoch integers
ESCAPEEnable backslash escape sequences in CSVUse only with CSV; incompatible with CSV mode's quote handling
FILLRECORDFill missing trailing columns with NULL/defaultAvoid — surfaces schema drift; fail and investigate instead
NOLOADValidate files without loading; dry-run modeUse to validate a new data source before first production load

UNLOAD — the reverse operation

UNLOAD exports Redshift query results to S3 in Parquet, CSV, or other formats. For MCP tools that need to export large result sets (too large for the Data API's 100 MB cache limit), UNLOAD is the right approach:

UNLOAD ('SELECT * FROM sales WHERE sale_date BETWEEN ''2026-11-01'' AND ''2026-11-07''')
TO 's3://export-bucket/sales-weekly-export/'
IAM_ROLE 'arn:aws:iam::123456789012:role/RedshiftCopyRole'
FORMAT AS PARQUET
PARALLEL ON       -- write multiple files for parallel downstream reads
MAXFILESIZE 256 MB
ALLOWOVERWRITE;   -- overwrite existing files at the prefix

UNLOAD writes multiple files in parallel by default (one per slice/node). Use PARALLEL OFF to write a single file; use MAXFILESIZE to control per-file sizes for downstream S3 processing. The output location always gets a manifest file (prefix/manifest) listing all written files, which can be passed directly to a subsequent COPY command in another system.

Related guides