Blog · Amazon HealthLake · Healthcare AI for MCP Servers

Amazon HealthLake for MCP Servers: FHIR R4, PHI-Safe Search, Bulk Import, and Healthcare IAM

Amazon HealthLake is a FHIR R4-compliant managed data store that eliminates the two most painful parts of building healthcare AI agents: standing up a FHIR server and implementing SigV4-authenticated HTTP calls against it. MCP server tools that need structured access to clinical data — patient demographics, lab results, active diagnoses, medication lists, encounter histories — can query HealthLake directly with standard FHIR search parameters and receive typed JSON resources ready to inject into LLM context. This guide synthesises the full HealthLake stack for MCP server developers: the two-API-layer architecture that every implementation must understand, the SigV4 signing utility for FHIR REST calls, the SearchWithPost pattern that keeps PHI out of access logs, the NDJSON bulk import path with its iam:PassRole gotcha, the non-transactional COMPLETED_WITH_ERRORS semantics, and the Deny-first IAM pattern that protects DeleteFHIRDatastore in production.

When HealthLake is the right tool for an MCP server

Not every healthcare data problem needs HealthLake. The service is purpose-built for FHIR R4 — it shines when your MCP server needs to answer typed clinical questions using standard FHIR search parameters, and it adds complexity when your data is not structured as FHIR resources. Understanding the fit before you start avoids overengineering.

ScenarioHealthLake is the right choiceUse a different approach
Query patient records with FHIR search parametersFHIR search parameters are natively supported — Patient by name/DOB, Observation by LOINC code and date range, Condition by clinical statusRDS + SQL if you have a custom relational schema
Structured clinical data from EHR exportsNDJSON bulk import accepts any FHIR R4 export (Epic, Cerner, Synthea)S3 + Textract if the source is PDFs or HL7 v2 messages
Versioned resource history for auditHealthLake automatically maintains resource version history — read with _history endpointDynamoDB with manual versioning for non-clinical audit trails
HIPAA-covered data with BAA requirementAWS signs a BAA for HealthLake; FHIR resources are PHI-scoped by designAny non-HIPAA-eligible AWS service if your legal team has not evaluated it
Sub-millisecond latency on healthcare lookupsHealthLake is not suitable — FHIR REST adds SigV4 signing overhead on every callDynamoDB or ElastiCache for cached, latency-critical lookups
Free-text clinical notes and unstructured documentsStore the FHIR DocumentReference in HealthLake; store the attachment bytes in S3HealthLake does not store binary blobs inline — only FHIR resource JSON

For MCP server tool arguments, FHIR's typed resource model maps directly to Zod schemas. A get_observations tool takes patient_id, loinc_code, and date range parameters and returns an array of Observation resources. The structured nature of FHIR eliminates the custom serialization logic that makes general healthcare data APIs difficult to surface as MCP tool definitions.

The two-API-layer architecture

Every HealthLake implementation requires two distinct API surfaces, and understanding the boundary between them prevents the most common class of integration errors. Confusing them produces errors that look like permission denials but are actually wrong-client problems.

LayerPackageOperationsContent-TypeAuth
Management (SDK) @aws-sdk/client-healthlake CreateFHIRDatastore, DescribeFHIRDatastore, ListFHIRDatastores, StartFHIRImportJob, StartFHIRExportJob, DescribeFHIRImportJob, DescribeFHIRExportJob Handled by SDK internally Standard SDK credential chain
FHIR REST (HTTP) @smithy/signature-v4 + fetch CRUD and search for all FHIR resource types — Patient, Observation, Condition, MedicationRequest, Encounter, DiagnosticReport, and all others application/fhir+json for CRUD; application/x-www-form-urlencoded for SearchWithPost Manual SigV4 signing on every request

The management API uses standard AWS endpoints (healthlake.us-east-1.amazonaws.com) and is called through the HealthLakeClient. It handles data store lifecycle: creating, describing, and deleting data stores, plus starting and monitoring bulk import and export jobs. The FHIR REST API uses the data store endpoint returned by DescribeFHIRDatastoreCommand — a URL like https://healthlake.us-east-1.amazonaws.com/datastore/{id}/r4 — and requires you to sign every HTTP request manually using SigV4 before issuing it. There is no SDK command that wraps individual FHIR resource operations.

Install both stacks before writing any code:

npm install @aws-sdk/client-healthlake \
  @smithy/signature-v4 \
  @aws-crypto/sha256-js \
  @aws-sdk/credential-providers

See the HealthLake overview guide for the full SDK setup path with TypeScript imports and the management client initialization pattern.

Creating a data store and polling for ACTIVE status

CreateFHIRDatastoreCommand provisions a new FHIR R4 data store. Creation is asynchronous — the command returns a datastoreId immediately while the data store transitions from CREATING to ACTIVE, typically taking one to five minutes. No FHIR REST API calls will succeed until the status is ACTIVE.

import {
  HealthLakeClient,
  CreateFHIRDatastoreCommand,
  DescribeFHIRDatastoreCommand,
  type DatastoreProperties,
} from '@aws-sdk/client-healthlake';

const client = new HealthLakeClient({ region: 'us-east-1' });

// Create with optional SYNTHEA preload for development environments
const { datastoreId } = await client.send(new CreateFHIRDatastoreCommand({
  datastoreName: 'my-clinical-datastore',
  datastoreTypeVersion: 'R4',
  // Remove preloadDataConfig for production datastores containing real PHI
  preloadDataConfig: { preloadDataType: 'SYNTHEA' },
  sseConfiguration: {
    kmsEncryptionConfig: {
      // AWS_OWNED_KMS_KEY: AWS-managed key, no additional KMS charges
      // Use CUSTOMER_MANAGED_KMS_KEY + kmsKeyId for HIPAA BYOK requirements
      cmkType: 'AWS_OWNED_KMS_KEY',
    },
  },
}));

// Poll until ACTIVE, then capture the FHIR endpoint URL
async function waitForDatastoreActive(
  datastoreId: string,
  timeoutMs = 600_000,
  pollIntervalMs = 15_000,
): Promise<DatastoreProperties> {
  const deadline = Date.now() + timeoutMs;

  while (Date.now() < deadline) {
    const { datastoreProperties: props } = await client.send(
      new DescribeFHIRDatastoreCommand({ datastoreId })
    );

    if (!props) throw new Error('No datastoreProperties in response');

    if (props.datastoreStatus === 'ACTIVE') return props;

    if (props.datastoreStatus === 'DELETING' || props.datastoreStatus === 'DELETED') {
      throw new Error(`Datastore entered terminal failed status: ${props.datastoreStatus}`);
    }

    await new Promise(r => setTimeout(r, pollIntervalMs));
  }

  throw new Error(`Datastore did not become ACTIVE within ${timeoutMs / 1000}s`);
}

const props = await waitForDatastoreActive(datastoreId!);
const datastoreEndpoint = props.datastoreEndpoint!;
// e.g. https://healthlake.us-east-1.amazonaws.com/datastore/abc123/r4

Two important details about the endpoint: the datastoreEndpoint field is the canonical FHIR base URL returned by DescribeFHIRDatastoreCommand. While the URL looks constructable from region and ID, always read it from Describe — AWS reserves the right to change the URL format. For MCP servers, persist both datastoreId and datastoreEndpoint in environment variables or AWS Systems Manager Parameter Store rather than re-creating on every deploy. The four possible statuses are CREATING, ACTIVE, DELETING, and DELETED — there is no FAILED state.

SigV4 signing for FHIR REST requests

Every FHIR REST call must be signed with AWS Signature Version 4. The service name for HealthLake is 'healthlake'. Build a reusable signing utility at startup and share it across all tool handlers — do not instantiate SignatureV4 per-request since credential resolution has non-trivial overhead.

import { SignatureV4 } from '@smithy/signature-v4';
import { Sha256 } from '@aws-crypto/sha256-js';
import { fromNodeProviderChain } from '@aws-sdk/credential-providers';

// Build once at module load time, reuse across all requests
const signer = new SignatureV4({
  service: 'healthlake',
  region: process.env.AWS_REGION!,
  credentials: fromNodeProviderChain(),
  sha256: Sha256,
});

async function signedFHIRRequest(
  method: string,
  url: URL,
  contentType: string,
  body?: string,
): Promise<Response> {
  const headers: Record<string, string> = {
    'content-type': contentType,
    host: url.hostname,
  };
  if (body) {
    headers['content-length'] = String(Buffer.byteLength(body));
  }

  const signed = await signer.sign({
    method,
    protocol: 'https:',
    hostname: url.hostname,
    path: url.pathname + (url.search || ''),
    headers,
    body,
  });

  const response = await fetch(url.toString(), {
    method,
    headers: signed.headers as Record<string, string>,
    body,
  });

  return response;
}

Three signing constraints to get right on the first attempt. First, the host header must be in the headers object before signing — SigV4 includes it in the signed string and HealthLake verifies it. Setting it after signing causes a 403 SignatureDoesNotMatch error that looks like a permissions problem. Second, the Content-Type must be identical in the sign call and in the actual fetch headers — the signed string includes Content-Type, so a mismatch between what you signed and what you send produces the same 403. Third, the body passed to the signer and to fetch must be the same string object — do not re-serialize or re-encode between the two calls.

For resource CRUD operations, use content-type: 'application/fhir+json'. For SearchWithPost, use content-type: 'application/x-www-form-urlencoded'. The two operations use different content types and must be signed differently.

FHIR resource CRUD and the 415 gotcha

FHIR resource operations map directly to HTTP methods: POST creates, GET reads, PUT updates, DELETE soft-deletes. The operations are issued against the data store endpoint with the resource type and optional ID in the path. The critical content type for all FHIR resource operations — the one that causes 415 Unsupported Media Type errors if wrong — is application/fhir+json. HealthLake does not accept application/json for FHIR resource operations, even though the bodies are valid JSON.

const FHIR_CT = 'application/fhir+json';

// Create a Patient resource (POST — HealthLake generates a logical ID)
async function createPatient(
  datastoreEndpoint: string,
  patient: FHIRPatient,
): Promise<FHIRPatient> {
  const url = new URL(`${datastoreEndpoint}/Patient`);
  const body = JSON.stringify(patient);

  const response = await signedFHIRRequest('POST', url, FHIR_CT, body);

  if (!response.ok) {
    const err = await response.json();
    throw new Error(`Create Patient failed ${response.status}: ${JSON.stringify(err)}`);
  }

  // Response is the created resource with a server-generated id
  return response.json() as Promise<FHIRPatient>;
}

// Read a Patient by logical ID (GET)
async function readPatient(
  datastoreEndpoint: string,
  patientId: string,
): Promise<FHIRPatient> {
  const url = new URL(`${datastoreEndpoint}/Patient/${patientId}`);
  const response = await signedFHIRRequest('GET', url, FHIR_CT);

  if (response.status === 404) throw new Error(`Patient ${patientId} not found`);
  if (!response.ok) throw new Error(`Read Patient failed: ${response.status}`);

  return response.json() as Promise<FHIRPatient>;
}

// Update a resource (PUT — requires id in body to match path)
async function updatePatient(
  datastoreEndpoint: string,
  patient: FHIRPatient & { id: string },
): Promise<FHIRPatient> {
  const url = new URL(`${datastoreEndpoint}/Patient/${patient.id}`);
  const response = await signedFHIRRequest('PUT', url, FHIR_CT, JSON.stringify(patient));

  if (!response.ok) throw new Error(`Update Patient failed: ${response.status}`);
  return response.json() as Promise<FHIRPatient>;
}

// Delete a resource (DELETE — HealthLake soft-deletes; the resource is tombstoned)
async function deletePatient(
  datastoreEndpoint: string,
  patientId: string,
): Promise<void> {
  const url = new URL(`${datastoreEndpoint}/Patient/${patientId}`);
  const response = await signedFHIRRequest('DELETE', url, FHIR_CT);

  if (!response.ok && response.status !== 404) {
    throw new Error(`Delete Patient failed: ${response.status}`);
  }
}

DELETE in HealthLake is a soft delete — the resource is tombstoned and no longer appears in search results, but its version history is preserved. A GET to the specific resource ID after deletion returns a 410 Gone response with an OperationOutcome body. If you need hard deletion to meet data retention requirements, that requires a support request to AWS or a data store deletion and recreation. Plan your data lifecycle accordingly.

See the HealthLake overview and FHIR CRUD guide for the full table of FHIR resource types HealthLake supports, including MedicationRequest, Encounter, DiagnosticReport, and the resource-specific validation rules that cause 400 Bad Request errors.

SearchWithPost: the PHI-safe query pattern

FHIR defines two equivalent ways to issue a search: SearchWithGet appends parameters to the URL query string (GET /Patient?family=Smith&birthdate=1990-01-15) and SearchWithPost sends them in the request body (POST /Patient/_search with URL-encoded body). They return identical Bundle responses. The choice matters for security, not functionality.

Query strings appear in HTTP access logs, proxy logs, CDN logs, load balancer request logs, and browser history. Patient names, dates of birth, medical record numbers, and LOINC codes embedded in URL query strings constitute PHI in those logs. Under HIPAA, any log file containing PHI must be treated as PHI itself — controlled access, audit trail, retention policy, BAA with the logging vendor. SearchWithPost moves PHI into the request body, which does not appear in standard access log formats.

// SearchWithPost — PHI stays in the body, not the URL
async function searchFHIR(
  datastoreEndpoint: string,
  resourceType: string,
  params: Record<string, string | string[]>,
): Promise<FHIRBundle> {
  // /_search suffix distinguishes search POST from resource creation POST
  const url = new URL(`${datastoreEndpoint}/${resourceType}/_search`);

  // URLSearchParams correctly handles repeated keys (_include, multiple codes, etc.)
  const urlParams = new URLSearchParams();
  for (const [key, value] of Object.entries(params)) {
    if (Array.isArray(value)) {
      for (const v of value) urlParams.append(key, v);
    } else {
      urlParams.set(key, value);
    }
  }
  const bodyStr = urlParams.toString();

  // Content-Type for SearchWithPost is application/x-www-form-urlencoded — NOT application/fhir+json
  // The signer must receive this exact content-type or the signature will mismatch
  const response = await signedFHIRRequest(
    'POST', url, 'application/x-www-form-urlencoded', bodyStr
  );

  if (!response.ok) {
    const error = await response.json();
    throw new Error(`FHIR search ${resourceType} failed ${response.status}: ${JSON.stringify(error)}`);
  }

  return response.json() as Promise<FHIRBundle>;
}

The critical point: SearchWithPost uses Content-Type: application/x-www-form-urlencoded, not application/fhir+json. This content type must be in the headers object given to the SigV4 signer. If you sign with application/fhir+json and then send with application/x-www-form-urlencoded (or vice versa), you get HTTP 403 SignatureDoesNotMatch. The /_search suffix in the URL path is what tells HealthLake this is a search POST rather than a resource creation POST to the same resource type endpoint.

See the HealthLake FHIR search guide for the full SearchWithPost implementation, all search parameter tables, date range operators, and the _include/_revinclude patterns for multi-resource queries.

Bundle parsing and async generator pagination

All FHIR search responses are Bundle resources with type: 'searchset'. Each entry has a resource and a search.mode field — always filter by mode === 'match' to get only the resources that directly matched your search parameters. Entries with mode === 'include' are resources pulled in by _include or _revinclude; mode === 'outcome' is an OperationOutcome warning about that entry.

function extractMatches<T>(bundle: FHIRBundle): T[] {
  return (bundle.entry ?? [])
    .filter(e => e.search.mode === 'match')
    .map(e => e.resource as T);
}

// Extract the _page-token from the 'next' link in the Bundle
function nextPageToken(bundle: FHIRBundle): string | null {
  const nextLink = bundle.link?.find(l => l.relation === 'next');
  if (!nextLink) return null;
  return new URL(nextLink.url).searchParams.get('_page-token');
}

// Async generator: yields one array of match resources per page
async function* allPages<T>(
  datastoreEndpoint: string,
  resourceType: string,
  params: Record<string, string | string[]>,
): AsyncGenerator<T[]> {
  let currentParams = { ...params };

  while (true) {
    const bundle = await searchFHIR(datastoreEndpoint, resourceType, currentParams);
    const matches = extractMatches<T>(bundle);

    if (matches.length > 0) yield matches;

    const token = nextPageToken(bundle);
    if (!token) break;

    // Keep all original search parameters and add the pagination token
    currentParams = { ...params, '_page-token': token };
  }
}

// MCP tool handler example: collect all Observations for a patient
const observations: FHIRObservation[] = [];
for await (const page of allPages<FHIRObservation>(
  datastoreEndpoint,
  'Observation',
  { patient: patientId, code: loincCode, date: ['ge2026-01-01', 'le2026-11-19'], _count: '50' }
)) {
  observations.push(...page);
}

Pagination tokens in HealthLake are opaque, time-limited, URL-safe strings. Do not store them in databases or pass them between MCP tool invocations. If a token expires before you use it, restart from the first page. The _count parameter controls page size — default is 10, maximum is 100. For MCP tool handlers that need all matching resources regardless of count, the async generator pattern above handles pagination transparently without exposing the token management to the calling code.

The total field in the Bundle may be approximate for large data stores. Do not use it as a stop condition or for precise reporting — use the absence of a next link (detected by nextPageToken returning null) to know you have exhausted all pages.

FHIR search parameter reference

HealthLake supports the standard FHIR R4 search parameter set for each resource type. The table below covers the parameters most commonly used in MCP tool handlers for the four core resource types. Date parameters accept comparison operators: ge (≥), le (≤), gt (>), lt (<), eq (=), ne (≠). Pass multiple values for the same parameter as an array to get OR semantics (code: ['8867-4', '8480-6']).

ResourceParameterExample valueMatches
Patient_idpatient-001Patient with specific logical ID
PatientfamilySmithFamily name (case-insensitive prefix match)
PatientgivenJohnGiven name
Patientbirthdate1980-05-15Exact birth date
Patientgendermalemale | female | other | unknown
PatientidentifierMRN|12345Identifier by system | value
Observationpatientpatient-001Observations for a specific patient
Observationcodehttp://loinc.org|8867-4LOINC-coded observation type
Observationdatege2026-01-01Effective date/time range
ObservationcategorylaboratoryCategory code (laboratory, vital-signs, etc.)
ObservationstatusfinalObservation status (registered, preliminary, final, amended)
Conditionpatientpatient-001Conditions for a specific patient
Conditionclinical-statusactiveactive | recurrence | relapse | inactive | remission | resolved
Conditioncodehttp://snomed.info/sct|73211009SNOMED CT or ICD-10 diagnosis code
Conditiononset-datege2024-01-01Onset date range
MedicationRequestpatientpatient-001Prescriptions for a specific patient
MedicationRequeststatusactiveactive | on-hold | cancelled | completed | entered-in-error | stopped | draft | unknown
MedicationRequestintentorderproposal | plan | order | original-order | reflex-order | filler-order | instance-order | option

Subject reference formats require care. HealthLake accepts bare IDs (patient: 'patient-001') and full relative references (patient: 'Patient/patient-001') interchangeably for most search parameters. Use bare IDs for simplicity in MCP tool handlers. Cross-resource queries using _include require the full reference format: '_include': 'Observation:patient' pulls the referenced Patient resource into the same Bundle alongside the Observation results.

Bulk import: NDJSON format and StartFHIRImportJobCommand

Bulk import is the right path for initial data loads, EHR migrations, Synthea synthetic data, and HIPAA data portability workflows. The FHIR REST API's one-at-a-time create operations break down at scale — 50,000 Patient records via individual POST calls hits rate limits and takes hours. StartFHIRImportJobCommand reads NDJSON files from an S3 prefix and processes the entire dataset in parallel.

NDJSON (newline-delimited JSON) has four rules that cause silent failures or validation errors when violated. First: one resource per line, no trailing commas, no array wrapper. Each line is a complete self-contained JSON object. Second: resourceType is required on every line — HealthLake uses it to dispatch to the right FHIR validator. A line without resourceType fails and appears in the error output file. Third: use UTF-8 encoding without BOM. Windows pipelines using UTF-16 or adding a BOM will cause character-level parsing failures. Fourth: the S3 prefix URI must have a trailing slash — s3://bucket/imports/batch-01/ scopes to that folder prefix; without the trailing slash, imports/batch-010 and imports/batch-01-retry would also match.

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: {
    // Trailing slash = prefix; without it, overlapping key names can match
    s3Uri: 's3://my-fhir-bucket/imports/batch-01/',
  },
  jobOutputDataConfig: {
    s3Configuration: {
      s3Uri: 's3://my-fhir-bucket/import-errors/batch-01/',
      kmsKeyId: process.env.KMS_KEY_ARN,  // optional; uses S3 default SSE if omitted
    },
  },
  // This is the SEPARATE data access role, not your MCP server's own IAM role
  dataAccessRoleArn: process.env.HEALTHLAKE_DATA_ACCESS_ROLE_ARN!,
  clientToken: `import-batch-01-${Date.now()}`,  // idempotency key
}));

The iam:PassRole gotcha for import and export

The most common AccessDeniedException when calling StartFHIRImportJob or StartFHIRExportJob is a missing iam:PassRole permission — not a missing healthlake:StartFHIRImportJob permission. The two look identical in the error message but require different fixes.

Here is what happens internally: when your MCP server calls StartFHIRImportJobCommand, it passes the dataAccessRoleArn in the request. The HealthLake service then calls sts:AssumeRole on that ARN to get credentials for reading your S3 input prefix. Before HealthLake can do that, IAM verifies that your MCP server role has permission to "pass" the data access role to the HealthLake service. That permission is iam:PassRole. Without it, the call fails with AccessDeniedException before HealthLake even tries to assume the data access role.

// MCP server role policy — must include iam:PassRole on the data access role ARN
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "HealthLakeManagement",
      "Effect": "Allow",
      "Action": [
        "healthlake:DescribeFHIRDatastore",
        "healthlake:ListFHIRDatastores",
        "healthlake:StartFHIRImportJob",
        "healthlake:DescribeFHIRImportJob",
        "healthlake:ListFHIRImportJobs",
        "healthlake:StartFHIRExportJob",
        "healthlake:DescribeFHIRExportJob",
        "healthlake:ListFHIRExportJobs"
      ],
      "Resource": "arn:aws:healthlake:us-east-1:123456789012:datastore/abc123"
    },
    {
      "Sid": "PassDataAccessRole",
      "Effect": "Allow",
      "Action": "iam:PassRole",
      "Resource": "arn:aws:iam::123456789012:role/HealthLakeDataAccessRole",
      "Condition": {
        "StringEquals": {
          "iam:PassedToService": "healthlake.amazonaws.com"
        }
      }
    }
  ]
}

The iam:PassedToService condition is not strictly required but adds an important defense: it ensures this PassRole permission can only be used to pass the role to HealthLake, not to any other AWS service. Without the condition, the same statement could be exploited to pass the data access role to Lambda or EC2, which would grant unintended access to the S3 buckets the data access role can reach.

The data access role itself requires a trust policy with healthlake.amazonaws.com as the principal — not your account root or your MCP server role. HealthLake is the entity assuming this role, not your application code:

// Data access role trust policy — HealthLake service assumes this role for S3 I/O
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "Service": "healthlake.amazonaws.com" },
      "Action": "sts:AssumeRole",
      "Condition": {
        "StringEquals": {
          // Confused deputy protection: scope to your account
          "aws:SourceAccount": "123456789012",
          // Scope to your specific data store
          "aws:SourceArn": "arn:aws:healthlake:us-east-1:123456789012:datastore/abc123"
        }
      }
    }
  ]
}

The aws:SourceAccount and aws:SourceArn conditions in the trust policy implement confused deputy protection. Without them, any HealthLake data store in any AWS account could assume your data access role if it somehow obtained the ARN. With the conditions, only HealthLake jobs running in your account with your specific data store ARN can assume the role.

See the HealthLake bulk import and export guide for the complete data access role permissions, error file parsing, the COMPLETED_WITH_ERRORS handling pattern, and the KMS configuration for export output encryption.

COMPLETED_WITH_ERRORS: non-transactional semantics

HealthLake import jobs are non-transactional. When a job reaches COMPLETED_WITH_ERRORS, some resources were imported successfully and some failed FHIR validation — but the successful ones are not rolled back. The data store is in a partially-loaded state. This is by design for large datasets where failing one malformed resource should not discard 50,000 valid ones, but it means your MCP server must handle this case explicitly.

async function waitForImportJob(
  datastoreId: string,
  jobId: string,
): Promise<{ status: string; 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') {
      // Successful resources ARE in the data store — this is not a rollback
      // Parse the error NDJSON at outputS3Uri to find which resources failed
      const outputUri = jobOutputDataConfig?.s3Configuration?.s3Uri;
      console.warn(`Import ${jobId} completed with errors — check ${outputUri} for error file`);
      return { status: 'COMPLETED_WITH_ERRORS', outputS3Uri: outputUri };
    }

    if (jobStatus === 'FAILED') {
      // FAILED means the job itself could not run — check message for infrastructure errors
      throw new Error(`Import job ${jobId} failed: ${message}`);
    }

    // SUBMITTED or IN_PROGRESS — keep polling
    await new Promise(r => setTimeout(r, 15_000));
  }
}

The error output at the S3 output prefix is itself an NDJSON file — each line is a JSON object with the failed resource and the validation error that caused the failure. Parse it to identify which resources need correction and re-import. Common causes of validation failures: missing required fields (resourceType, status on Observation, clinicalStatus on Condition), invalid code system URLs (HealthLake validates that LOINC codes match the LOINC URL format), and id values containing characters that are invalid in FHIR logical IDs (only alphanumeric, hyphens, dots, and underscores are allowed).

IAM: the Deny-first DeleteFHIRDatastore pattern

HealthLake IAM has two surfaces (covered above), but the single most important policy decision for production deployments is adding an explicit Deny for healthlake:DeleteFHIRDatastore. This action permanently deletes the data store and all FHIR resources in it. There is no soft delete, no recycle bin, no recovery. Once issued, the command cannot be undone.

// Production MCP server role policy — Deny DeleteFHIRDatastore unconditionally
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "HealthLakeOperations",
      "Effect": "Allow",
      "Action": [
        "healthlake:DescribeFHIRDatastore",
        "healthlake:ListFHIRDatastores",
        "healthlake:StartFHIRImportJob",
        "healthlake:DescribeFHIRImportJob",
        "healthlake:ListFHIRImportJobs",
        "healthlake:StartFHIRExportJob",
        "healthlake:DescribeFHIRExportJob",
        "healthlake:ListFHIRExportJobs",
        "healthlake:TagResource",
        "healthlake:ListTagsForResource"
      ],
      "Resource": "arn:aws:healthlake:us-east-1:123456789012:datastore/abc123"
    },
    {
      "Sid": "NeverDeleteDatastore",
      "Effect": "Deny",
      "Action": "healthlake:DeleteFHIRDatastore",
      "Resource": "*"
    }
  ]
}

The Deny statement uses "Resource": "*" and has no conditions — it overrides any Allow that might exist in this or any other policy attached to the role. IAM explicit Deny always wins over explicit Allow. Even if a role has healthlake:* granted elsewhere, the explicit Deny in a Service Control Policy or identity-based policy blocks the delete. Apply this Deny to every role that could reach HealthLake in production: MCP server roles, CI/CD pipeline roles, administrator roles that are also used for operational tasks.

Scope all Allow statements to specific data store ARNs using the HealthLake ARN format: arn:aws:healthlake:{region}:{accountId}:datastore/{datastoreId}. The healthlake:ListFHIRDatastores, healthlake:ListFHIRImportJobs, and healthlake:ListFHIRExportJobs actions require "Resource": "*" in the Allow statement because they are not resource-scoped. Keep those in a separate statement from the data-store-scoped actions.

See the HealthLake IAM guide for the complete management action reference table, the read-only vs write policy templates, and the ABAC pattern for multi-environment isolation using resource tags.

HIPAA compliance: CloudTrail data events for FHIR access

HealthLake is a HIPAA-eligible service. If your data store contains PHI, you need a Business Associate Agreement with AWS before storing any real patient data. Beyond the BAA, HIPAA requires audit logging for all PHI access — including every FHIR REST API read and write your MCP server issues.

CloudTrail management events (enabled by default for all AWS accounts) capture management API calls: CreateFHIRDatastore, StartFHIRImportJob, DeleteFHIRDatastore. They do not capture FHIR REST API calls — the GET, POST, PUT, and DELETE requests your MCP server issues to the data store endpoint. For HIPAA, you need CloudTrail data events enabled for HealthLake to capture those FHIR access events.

Enable data events in your CloudTrail trail configuration by adding a data resource for HealthLake:

// CloudTrail trail configuration for HIPAA FHIR access logging
// Use AWS CDK, CloudFormation, or CLI — the console does not expose HealthLake data events
aws cloudtrail put-event-selectors \
  --trail-name my-hipaa-trail \
  --advanced-event-selectors '[
    {
      "Name": "HealthLakeDataEvents",
      "FieldSelectors": [
        { "Field": "eventCategory", "Equals": ["Data"] },
        { "Field": "resources.type", "Equals": ["AWS::HealthLake::FHIRDatastore"] },
        {
          "Field": "resources.ARN",
          "StartsWith": ["arn:aws:healthlake:us-east-1:123456789012:datastore/abc123"]
        }
      ]
    }
  ]'

CloudTrail data events for HealthLake are charged per event (approximately $0.10 per 100,000 events). For MCP servers making frequent FHIR calls, this cost can add up. Scope the data event selector to specific data store ARNs rather than using a wildcard to avoid capturing events from development or staging data stores that contain only synthetic Synthea data.

Add a CloudWatch metric filter and alarm for DeleteFHIRDatastore calls against your production data store, even if you have a Deny policy on the role — the alarm catches attempts made by any identity, including root or break-glass roles that bypass the Deny:

// CloudWatch alarm for DeleteFHIRDatastore in CloudTrail
// Metric filter pattern — matches DeleteFHIRDatastore in management events
{ ($.eventSource = "healthlake.amazonaws.com") &&
  ($.eventName = "DeleteFHIRDatastore") &&
  ($.requestParameters.datastoreId = "abc123") }

See the HealthLake IAM and HIPAA guide for the complete CloudTrail data events configuration, the DeleteFHIRResource CloudWatch alarm filter pattern for individual resource deletions, and the KMS key policy structure required for CMK-encrypted data stores.

Full MCP tool handler: get_patient_clinical_summary

This example synthesizes the full stack — SigV4 signing, SearchWithPost, Bundle parsing, and async pagination — into a single get_patient_clinical_summary tool that returns a structured summary of a patient's active conditions and recent lab results. The tool is designed to be called with a patient logical ID and returns the data in a format ready for LLM context injection.

import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';

const server = new McpServer({ name: 'healthlake-mcp', version: '1.0.0' });

server.tool(
  'get_patient_clinical_summary',
  {
    patient_id: z.string().describe('Patient logical ID in the HealthLake data store'),
    days_back: z.number().default(90).describe('How many days of observations to include'),
  },
  async ({ patient_id, days_back }) => {
    const datastoreEndpoint = process.env.HEALTHLAKE_DATASTORE_ENDPOINT!;

    // Compute date range for observations
    const sinceDate = new Date(Date.now() - days_back * 24 * 3600 * 1000)
      .toISOString().split('T')[0];

    // Run all three searches concurrently — independent queries, no ordering dependency
    const [patientBundle, conditionBundle, labBundle] = await Promise.all([
      // Read patient demographics via search (not direct read) to get consistent Bundle format
      searchFHIR(datastoreEndpoint, 'Patient', {
        _id: patient_id,
      }),
      // Active diagnoses
      searchFHIR(datastoreEndpoint, 'Condition', {
        patient: patient_id,
        'clinical-status': 'active',
        _count: '50',
      }),
      // Recent lab observations — vitals and labs by category
      searchFHIR(datastoreEndpoint, 'Observation', {
        patient: patient_id,
        category: ['laboratory', 'vital-signs'],
        date: [`ge${sinceDate}`],
        _sort: '-date',   // most recent first
        _count: '100',
      }),
    ]);

    const patients = extractMatches<FHIRPatient>(patientBundle);
    const patient = patients[0];
    if (!patient) {
      return { content: [{ type: 'text', text: `Patient ${patient_id} not found` }] };
    }

    const conditions = extractMatches<FHIRCondition>(conditionBundle);
    const observations = extractMatches<FHIRObservation>(labBundle);

    // Format for LLM context — structured text, not raw FHIR JSON
    const name = patient.name?.[0]
      ? `${patient.name[0].given?.join(' ')} ${patient.name[0].family}`
      : patient_id;

    const conditionLines = conditions.map(c =>
      `- ${c.code?.coding?.[0]?.display ?? c.code?.text ?? 'unknown'} (${c.code?.coding?.[0]?.code})`
    ).join('\n');

    const obsLines = observations.slice(0, 20).map(o => {
      const code = o.code?.coding?.[0]?.display ?? o.code?.text ?? 'unknown';
      const value = o.valueQuantity
        ? `${o.valueQuantity.value} ${o.valueQuantity.unit}`
        : o.valueString ?? 'no value';
      const date = o.effectiveDateTime?.split('T')[0] ?? 'unknown date';
      return `- ${code}: ${value} (${date})`;
    }).join('\n');

    const summary = [
      `Patient: ${name}`,
      `DOB: ${patient.birthDate ?? 'unknown'}`,
      `Gender: ${patient.gender ?? 'unknown'}`,
      '',
      `Active Conditions (${conditions.length}):`,
      conditionLines || '  (none)',
      '',
      `Recent Lab/Vital Results (last ${days_back} days, up to 20 shown):`,
      obsLines || '  (none)',
    ].join('\n');

    return { content: [{ type: 'text', text: summary }] };
  }
);

The Promise.all pattern is important for latency: the patient, condition, and observation searches are independent queries. Running them concurrently cuts total latency to roughly the slowest single query rather than the sum of three sequential queries. For MCP tool handlers that need to aggregate multiple FHIR resource types, concurrent searches are the standard approach.

Production gotchas consolidated

Across all four HealthLake guides — overview and CRUD, FHIR search, bulk import/export, and IAM and HIPAA — these are the gotchas that come up most in production integrations:

Error / SymptomRoot causeFix
HTTP 415 Unsupported Media Type on FHIR resource operations Content-Type: application/json instead of application/fhir+json Use application/fhir+json for all FHIR CRUD operations
HTTP 403 SignatureDoesNotMatch on SearchWithPost Signed with application/fhir+json but sent with application/x-www-form-urlencoded Pass application/x-www-form-urlencoded in both the signer headers and the fetch headers
HTTP 403 AccessDeniedException calling StartFHIRImportJob Missing iam:PassRole on the data access role ARN Add iam:PassRole with iam:PassedToService: healthlake.amazonaws.com condition to MCP server role
FHIR REST calls fail with endpoint not found immediately after CreateFHIRDatastore Data store still in CREATING state — endpoint does not exist yet Poll DescribeFHIRDatastoreCommand until datastoreStatus === 'ACTIVE' before any FHIR calls
SearchWithPost returns no results but SearchWithGet works Missing _search suffix in POST URL path (/Patient instead of /Patient/_search) Always append /_search to the resource type path for SearchWithPost
Bundle contains unexpected non-matching resources Not filtering entry array by search.mode === 'match' — includes and outcomes are mixed in Always filter entry array by mode before processing resources
Import job reads files from wrong prefix / picks up unintended files Missing trailing slash on s3Uri — batch-01 matches batch-010, batch-01-retry Always end S3 prefix URIs with a trailing slash: s3://bucket/imports/batch-01/
Import resources missing from data store with no error logged resourceType missing from NDJSON lines — silent skip Validate NDJSON before upload: every line must have resourceType
Data access role trust policy rejected — HealthLake cannot assume role Trust policy lists wrong principal — application role instead of healthlake.amazonaws.com Set "Service": "healthlake.amazonaws.com" as principal in trust policy
FHIR DELETE does not remove resource from search results HealthLake DELETE is a soft delete — resource is tombstoned, not physically removed Soft delete is FHIR-spec behavior; plan data lifecycle accordingly or contact AWS support for hard deletion
Pagination stops early — not all resources returned Stopping on empty bundle.total or zero entries instead of checking for next link absence Use absence of next link as the pagination stop condition, not total or entry count
HIPAA audit log missing FHIR access events CloudTrail management events enabled but data events not configured for HealthLake Enable CloudTrail data events for AWS::HealthLake::FHIRDatastore resource type

Deployment checklist