Guide · Amazon HealthLake · Bulk Import & Export
Amazon HealthLake Bulk Import and Export for MCP Servers — StartFHIRImportJob, NDJSON, S3 Integration
Bulk import and export are the two operations that move entire FHIR datasets in and out of Amazon HealthLake, and both are asynchronous S3-based jobs that require a dedicated IAM data access role separate from your MCP server's own role. StartFHIRImportJobCommand reads NDJSON files from an S3 prefix, validates each line as a FHIR R4 resource, and writes an error report back to S3 if any resources fail validation. StartFHIRExportJobCommand snapshots the entire data store to NDJSON files split by resource type. Neither job completes synchronously — your MCP server must poll DescribeFHIRImportJobCommand or DescribeFHIRExportJobCommand until the terminal state arrives. This guide covers the NDJSON format rules that trip up most implementations, the IAM trust policy that the data access role requires, the iam:PassRole permission your MCP server must have, handling COMPLETED_WITH_ERRORS, and the KMS configuration that affects both data store and output bucket encryption.
TL;DR
StartFHIRImportJobCommand reads NDJSON from S3 — one FHIR resource JSON per line, UTF-8 encoded. It requires a dataAccessRoleArn that is a separate IAM role with principal healthlake.amazonaws.com in its trust policy, not your MCP server's own role. Poll DescribeFHIRImportJobCommand every 15 seconds until jobStatus reaches COMPLETED, COMPLETED_WITH_ERRORS, or FAILED. COMPLETED_WITH_ERRORS means some resources failed FHIR validation — an error NDJSON file is written to your output S3 prefix but successfully imported resources are not rolled back. Your MCP server role needs healthlake:StartFHIRImportJob and iam:PassRole on the data access role ARN — missing iam:PassRole is the most common AccessDeniedException for this call.
Why bulk import matters for MCP servers
Most FHIR MCP servers start with the question: how does data get into the data store in the first place? The FHIR REST API lets you create individual resources one at a time with CreateFHIRResourceCommand, but this approach breaks down at scale. Creating 50,000 Patient records one HTTP call at a time is slow, expensive, and subject to per-second rate limits.
Bulk import with StartFHIRImportJobCommand is the right path for four common scenarios: initial data load from an EHR export (Epic, Cerner, or any system producing HL7 FHIR R4 bundles); migrating from an existing FHIR server where you can export NDJSON via the FHIR Bulk Data specification; loading synthetic patient data generated by Synthea for development and testing environments; and fulfilling HIPAA data portability workflows where a patient or payer requests all records in a standard format and you need to load a provided export.
Bulk export with StartFHIRExportJobCommand serves the inverse use cases: creating a point-in-time snapshot for analytics pipelines, training ML models on FHIR-structured data, fulfilling regulatory data portability requests, or creating a backup before a migration. The exported NDJSON files are split by resource type, making them directly consumable by tools like AWS Glue, Amazon Athena, or any pipeline that processes one resource type at a time.
NDJSON input format requirements
NDJSON (newline-delimited JSON) is deceptively simple but has several rules that cause silent import failures or validation errors if violated. Each line in the file must be a complete, self-contained JSON object representing a single FHIR R4 resource. There is no array wrapper and no commas between lines. Here is a minimal valid NDJSON file containing three different resource types:
{"resourceType":"Patient","id":"patient-001","name":[{"family":"Smith","given":["John"]}],"birthDate":"1980-05-15","gender":"male"}
{"resourceType":"Observation","id":"obs-001","status":"final","code":{"coding":[{"system":"http://loinc.org","code":"8867-4"}]},"subject":{"reference":"Patient/patient-001"},"valueQuantity":{"value":72,"unit":"beats/minute"}}
{"resourceType":"Condition","id":"cond-001","clinicalStatus":{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/condition-clinical","code":"active"}]},"code":{"coding":[{"system":"http://snomed.info/sct","code":"73211009","display":"Diabetes mellitus"}]},"subject":{"reference":"Patient/patient-001"}}
The rules that matter most in practice:
resourceType is required on every line. HealthLake uses this field to determine which FHIR validation rules to apply and which resource collection to write to. A line missing resourceType will fail with a schema validation error and appear in the error output file.
id is optional — but understand PUT semantics. If you omit id, HealthLake generates a UUID and creates the resource. If you include id, HealthLake behaves like a FHIR PUT operation for that resource: if a resource with the same type and ID already exists in the data store, it is overwritten. This is usually what you want for initial loads and migrations, but be aware that re-importing the same NDJSON file a second time will update all existing resources rather than creating duplicates.
UTF-8 encoding is mandatory. Windows-generated NDJSON files sometimes use UTF-16 or include a BOM (byte order mark). Files with CRLF line endings generally work, but certain unicode characters in CRLF files can cause line-boundary parsing errors. If your import pipeline runs on Windows, explicitly encode NDJSON output as UTF-8 without BOM.
File organization and size limits. HealthLake reads all files matching the S3 prefix you provide in inputDataConfig.s3Uri. Files can use .ndjson or .json extensions — HealthLake reads both. Each individual file has a 10 GB size limit. For large datasets, split into multiple files at the same prefix. There is no requirement to organize by resource type; a single file can contain a mix of Patients, Observations, Conditions, and any other resource types.
References between resources. Import does not validate referential integrity. A Condition that references Patient/patient-001 will import successfully even if Patient/patient-001 does not exist in the data store yet. After the import completes, the reference will work correctly if the referenced resource was imported in the same job or was already present. If the referenced resource was not imported, searches by reference will simply return no results rather than throwing an error.
Starting an import job with StartFHIRImportJobCommand
The import command takes five meaningful parameters: a human-readable job name, the data store ID, the S3 input location, the S3 output location for the error report, and the data access role ARN. The clientToken field provides idempotency — if you submit two requests with the same token, only one job is created:
import { HealthLakeClient, StartFHIRImportJobCommand, DescribeFHIRImportJobCommand } from '@aws-sdk/client-healthlake';
const client = new HealthLakeClient({ region: 'us-east-1' });
const { jobId } = await client.send(new StartFHIRImportJobCommand({
jobName: `import-${Date.now()}`,
datastoreId: process.env.HEALTHLAKE_DATASTORE_ID,
inputDataConfig: {
s3Uri: 's3://my-fhir-bucket/imports/batch-01/', // trailing slash = prefix
},
jobOutputDataConfig: {
s3Configuration: {
s3Uri: 's3://my-fhir-bucket/import-output/batch-01/',
kmsKeyId: process.env.KMS_KEY_ARN, // optional, uses S3 default if omitted
},
},
dataAccessRoleArn: process.env.HEALTHLAKE_DATA_ACCESS_ROLE_ARN,
clientToken: `import-${Date.now()}-${Math.random()}`, // idempotency key
}));
console.log('Import job started:', jobId);
The s3Uri trailing slash is important. s3://my-fhir-bucket/imports/batch-01/ tells HealthLake to read all objects whose key starts with imports/batch-01/. Without the trailing slash, s3://my-fhir-bucket/imports/batch-01 reads objects whose key starts with the literal string imports/batch-01, which will also match imports/batch-010, imports/batch-01-retry, and anything else sharing that prefix. Use a trailing slash to scope to a specific folder.
The job returns a jobId immediately — this is a UUID that you will use to poll for status. The import itself runs asynchronously in the HealthLake service and may take anywhere from a few minutes to several hours depending on the volume of data.
Polling for job completion
The import job moves through states: SUBMITTED (accepted, not yet started), IN_PROGRESS (actively processing), and then one of three terminal states: COMPLETED, COMPLETED_WITH_ERRORS, or FAILED. Poll every 15 seconds for small jobs and every 60 seconds for large multi-file imports to avoid unnecessary API calls:
type ImportJobStatus = 'SUBMITTED' | 'IN_PROGRESS' | 'COMPLETED' | 'COMPLETED_WITH_ERRORS' | 'FAILED';
async function waitForImportJob(
datastoreId: string,
jobId: string,
pollIntervalMs = 15_000
): Promise<{ status: ImportJobStatus; outputS3Uri?: string }> {
while (true) {
const { jobProperties } = await client.send(
new DescribeFHIRImportJobCommand({ datastoreId, jobId })
);
const { jobStatus, jobOutputDataConfig, message } = jobProperties!;
if (jobStatus === 'COMPLETED') {
return { status: 'COMPLETED', outputS3Uri: jobOutputDataConfig?.s3Configuration?.s3Uri };
}
if (jobStatus === 'COMPLETED_WITH_ERRORS') {
console.warn('Import completed with errors — check output S3 prefix for error file');
return { status: 'COMPLETED_WITH_ERRORS', outputS3Uri: jobOutputDataConfig?.s3Configuration?.s3Uri };
}
if (jobStatus === 'FAILED') {
throw new Error(`Import job ${jobId} failed: ${message}`);
}
// SUBMITTED or IN_PROGRESS — keep polling
await new Promise(resolve => setTimeout(resolve, pollIntervalMs));
}
}
An important note about FAILED vs COMPLETED_WITH_ERRORS: a FAILED job means the entire job could not run — most commonly because HealthLake could not access the S3 input prefix (IAM permissions on the data access role), could not write to the output prefix, or encountered a critical internal error. A COMPLETED_WITH_ERRORS job ran successfully but some individual resources failed FHIR validation — the job itself completed and all valid resources were imported.
For MCP server implementations that need to surface job status to AI agents, the job metadata is retained for 90 days. Use ListFHIRImportJobsCommand with a Filter.jobStatus filter to find all FAILED jobs for a given data store if you need to audit failures across multiple import sessions.
Handling COMPLETED_WITH_ERRORS
When an import job finishes with status COMPLETED_WITH_ERRORS, HealthLake has written an error report file to the output S3 prefix you specified in jobOutputDataConfig. The error report is a JSON file (not NDJSON) that lists each failed resource with an error code and a human-readable description.
Errors in this report fall into three categories. First, invalid FHIR R4 schema: a required field was missing, a code binding was invalid, or a value had the wrong data type. For example, a Patient resource missing resourceType or an Observation with a malformed valueQuantity unit. Second, duplicate resource IDs in conflict mode: if you have configured the data store to reject duplicates rather than overwrite them, any resource whose ID already exists will fail here. Third, unsupported FHIR resource types: HealthLake supports a specific subset of FHIR R4 resource types; importing a resource type outside that set will produce an error entry.
To retrieve and process the error file, download it from S3 using the standard AWS SDK and parse the JSON structure to identify which resources need correction:
import { S3Client, GetObjectCommand } from '@aws-sdk/client-s3';
const s3 = new S3Client({ region: 'us-east-1' });
async function getImportErrors(errorS3Uri: string): Promise<any[]> {
// errorS3Uri looks like: s3://my-bucket/import-output/batch-01/
// The actual error file has a generated key under that prefix
// List objects first to find the error file key
const url = new URL(errorS3Uri.replace('s3://', 'https://'));
const bucket = url.hostname;
const prefix = url.pathname.slice(1);
const { Body } = await s3.send(new GetObjectCommand({
Bucket: bucket,
Key: `${prefix}error-output.json`, // HealthLake writes to this key
}));
const content = await Body!.transformToString('utf-8');
const errorReport = JSON.parse(content);
return errorReport.errors ?? [];
}
Import is not transactional. Resources that passed validation and were written to the data store before a later resource failed are not rolled back. If your NDJSON file contains 10,000 resources and 50 fail validation, 9,950 resources are in the data store. This is generally the correct behavior for bulk healthcare data operations — you want maximum successful throughput with a clear audit trail of what failed — but it means your re-import strategy should address only the failed resources, not the entire dataset.
Starting an export job with StartFHIRExportJobCommand
The export command snapshots the entire data store at the moment the job starts. Resources added during the export are not included — the snapshot is consistent to the job start time. The output is written as NDJSON files to your S3 prefix, organized by resource type (one file per type or multiple files for large resource collections):
import { StartFHIRExportJobCommand, DescribeFHIRExportJobCommand } from '@aws-sdk/client-healthlake';
const { jobId } = await client.send(new StartFHIRExportJobCommand({
datastoreId: process.env.HEALTHLAKE_DATASTORE_ID,
outputDataConfig: {
s3Configuration: {
s3Uri: 's3://my-fhir-bucket/exports/full-export-20261119/',
kmsKeyId: process.env.KMS_KEY_ARN,
},
},
dataAccessRoleArn: process.env.HEALTHLAKE_DATA_ACCESS_ROLE_ARN,
clientToken: `export-${Date.now()}`,
}));
console.log('Export job started:', jobId);
The export job status polling follows the same pattern as import, using DescribeFHIRExportJobCommand with the same terminal states: COMPLETED, COMPLETED_WITH_ERRORS, and FAILED. For export jobs, COMPLETED_WITH_ERRORS is rare and typically indicates that specific resources could not be serialized — in practice most export jobs either complete cleanly or fail entirely.
The exported files are structured for direct consumption by analytics pipelines. Each file is named with the resource type, making it straightforward to point AWS Glue crawlers or Athena external tables at specific resource type prefixes. A data store containing Patients, Observations, Conditions, and MedicationRequests will produce output like:
exports/full-export-20261119/Patient.ndjson
exports/full-export-20261119/Observation.ndjson
exports/full-export-20261119/Condition.ndjson
exports/full-export-20261119/MedicationRequest.ndjson
For large data stores, a single resource type file may be split into numbered parts: Observation-1.ndjson, Observation-2.ndjson, and so on. Analytics pipelines should use prefix matching rather than expecting specific filenames.
IAM data access role configuration
The dataAccessRoleArn parameter in both import and export commands refers to an IAM role that the HealthLake service assumes — not a role your application directly uses. The trust policy for this role must allow healthlake.amazonaws.com to call sts:AssumeRole:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "healthlake.amazonaws.com" },
"Action": "sts:AssumeRole"
}
]
}
The role's permission policy needs S3 access scoped to the specific buckets and prefixes you use for import input and export output, plus KMS access if you encrypt the output bucket:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:ListBucket"],
"Resource": [
"arn:aws:s3:::my-fhir-bucket",
"arn:aws:s3:::my-fhir-bucket/imports/*"
]
},
{
"Effect": "Allow",
"Action": ["s3:PutObject"],
"Resource": "arn:aws:s3:::my-fhir-bucket/import-output/*"
},
{
"Effect": "Allow",
"Action": ["kms:GenerateDataKey", "kms:Decrypt"],
"Resource": "arn:aws:kms:us-east-1:123456789:key/abc-123"
}
]
}
Notice that import needs s3:GetObject and s3:ListBucket on the input prefix, and s3:PutObject on the output prefix (for writing the error report). Export needs s3:PutObject on the output prefix. If you use the same role for both import and export jobs, the policy needs both s3:GetObject and s3:PutObject access on the relevant prefixes.
The s3:ListBucket permission on the bucket (not the prefix) is needed in addition to s3:GetObject on the prefix because HealthLake performs a LIST operation to enumerate all NDJSON files matching your input prefix before beginning the read phase.
MCP server role permissions for import and export
Your MCP server's own IAM role needs two distinct permission sets for import and export operations. The first is the set of healthlake: management actions to start and monitor jobs. The second is iam:PassRole on the data access role ARN — this is the permission that allows your MCP server to hand the data access role to the HealthLake service when starting a job:
{
"Effect": "Allow",
"Action": [
"healthlake:StartFHIRImportJob",
"healthlake:DescribeFHIRImportJob",
"healthlake:ListFHIRImportJobs",
"healthlake:StartFHIRExportJob",
"healthlake:DescribeFHIRExportJob",
"healthlake:ListFHIRExportJobs"
],
"Resource": "arn:aws:healthlake:us-east-1:123456789:datastore/*"
},
{
"Effect": "Allow",
"Action": "iam:PassRole",
"Resource": "arn:aws:iam::123456789:role/healthlake-data-access-role"
}
iam:PassRole is the most common source of AccessDeniedException for StartFHIRImportJob and StartFHIRExportJob. When you receive an AccessDeniedException on these calls, check two things first: does the MCP server role have iam:PassRole on the data access role ARN, and does the data access role trust policy allow healthlake.amazonaws.com? One of these two is usually the culprit.
Scope the iam:PassRole resource to the specific data access role ARN rather than using a wildcard. This prevents the MCP server role from being able to pass any role to any AWS service — it can only pass the specific HealthLake data access role to HealthLake.
MCP tool handler for import job status
An MCP server tool that checks import job status is useful for AI agents that need to monitor long-running data operations. The tool takes a job ID and returns structured status information including the output S3 prefix where error files can be found:
server.tool('check_healthlake_import_status', {
job_id: z.string(),
}, async ({ job_id }) => {
const { jobProperties } = await client.send(new DescribeFHIRImportJobCommand({
datastoreId: process.env.HEALTHLAKE_DATASTORE_ID!,
jobId: job_id,
}));
return {
content: [{
type: 'text',
text: JSON.stringify({
status: jobProperties?.jobStatus,
startedAt: jobProperties?.submitTime,
endedAt: jobProperties?.endTime,
outputPrefix: jobProperties?.jobOutputDataConfig?.s3Configuration?.s3Uri,
}, null, 2)
}]
};
});
For complete MCP server workflows involving import, consider exposing three tools: start_healthlake_import (starts the job and returns the job ID), check_healthlake_import_status (checks a specific job), and list_healthlake_import_jobs (lists recent jobs with optional status filter). This lets an AI agent start an import, then come back and check on it in a later turn without needing to store the job ID in its context indefinitely — it can re-discover in-progress jobs via the list tool.
KMS encryption for import and export
HealthLake encryption operates at two levels that are configured independently and cannot be changed after the fact for data store encryption.
Data store encryption is set at creation time via sseConfiguration.kmsEncryptionConfig in CreateFHIRDatastoreCommand. You choose between cmkType: 'AWS_OWNED_KMS_KEY' (default, AWS manages the key, no additional cost) and cmkType: 'CUSTOMER_MANAGED_KMS_KEY' (your own KMS key, with kmsKeyId pointing to the key ARN). Once a data store is created, its encryption configuration cannot be changed. If you need to migrate from AWS-owned to CMK encryption, you must create a new data store, export from the old one, and import into the new one.
Export output encryption is configured per job via the kmsKeyId in the s3Configuration block of StartFHIRExportJobCommand. If you omit kmsKeyId, the output bucket's default encryption applies. For HIPAA workloads, specifying an explicit KMS key for export output is recommended to maintain key control independent of bucket defaults.
For CMK-encrypted data stores, the KMS key policy must grant healthlake.amazonaws.com the necessary actions. Add this statement to your KMS key policy:
{
"Effect": "Allow",
"Principal": { "Service": "healthlake.amazonaws.com" },
"Action": [
"kms:DescribeKey",
"kms:GenerateDataKey",
"kms:Decrypt"
],
"Resource": "*"
}
For export output encryption using a CMK, the data access role (not the HealthLake service principal directly) needs kms:GenerateDataKey and kms:Decrypt on the KMS key. This is why the data access role's permission policy includes the KMS actions in addition to the S3 actions.
Common gotchas and production checklist
iam:PassRole is the most common AccessDeniedException cause. When StartFHIRImportJob or StartFHIRExportJob returns AccessDeniedException, check iam:PassRole before anything else. The error message does not always call out PassRole explicitly — it may surface as a generic access denied on the import or export action itself.
S3 prefix trailing slash behavior. s3://bucket/imports/ (with trailing slash) is a prefix matching all objects under the imports/ folder. Without the trailing slash, s3://bucket/imports is treated as a prefix that matches any key starting with imports, including imports-old/, imports-v2/, and so on. Always use a trailing slash when you mean a specific folder prefix.
NDJSON line endings. Windows CRLF line endings generally work, but certain Unicode characters in CRLF files can cause line-boundary parsing issues. If you're generating NDJSON on Windows or receiving exports from Windows-based EHR systems, normalize to LF line endings before uploading to S3.
Import is not transactional. COMPLETED_WITH_ERRORS does not roll back the resources that were imported successfully. If you re-import after fixing validation errors in the failed resources, you will end up with duplicates if the originally successful resources used server-generated IDs (no id field). For imports where you control the NDJSON, always include explicit id fields so re-imports result in updates rather than duplicates.
Job metadata retention is 90 days. DescribeFHIRImportJobCommand and ListFHIRImportJobsCommand return job records for 90 days after job creation. After that, the records are purged. If your MCP server exposes job status tools, make sure the tool handles the case where a job ID is no longer in the HealthLake job list — the most likely explanation after 90 days is expiration rather than a bug.
Export snapshot semantics. The export captures the data store state at the moment the job starts. Resources added, modified, or deleted during the export run are not reflected in the output. For compliance snapshots, record the export job's submitTime from the describe response as the official snapshot timestamp.
Job concurrency limits. HealthLake limits the number of concurrent import and export jobs per data store. If you are running multiple parallel import jobs (e.g., loading several independent datasets simultaneously), check the current service quota and request an increase if needed before hitting the limit in production.