Guide · Amazon HealthLake · FHIR Search

Amazon HealthLake FHIR Search for MCP Servers — SearchWithPost, Search Parameters, Bundle Pagination

FHIR search is how healthcare AI agents answer clinical questions: which lab results has this patient had in the last three months, what active diagnoses are on record, which medications were prescribed during this encounter. Amazon HealthLake supports standard FHIR R4 search parameters with two HTTP entry points — SearchWithGet and SearchWithPost — and returns results as FHIR Bundle resources with pagination tokens. This guide covers the full picture for MCP server tool handlers: why SearchWithPost is mandatory in production, how to parse the Bundle response and filter entry modes, how to follow the _page-token pagination link to retrieve all matching resources, the standard search parameters for Patient, Observation, Condition, and MedicationRequest, and practical patterns for clinical timeline queries using date range operators.

TL;DR

Use SearchWithPost for all production queries — POST to /{ResourceType}/_search with the body as application/x-www-form-urlencoded to avoid PHI in URL query strings. Bundle response: iterate entry[].resource after filtering for entry[].search.mode === 'match' to exclude included and outcome entries. Pagination: extract the _page-token value from the next link URL in bundle.link and add it as a parameter in the subsequent request — keep all original search parameters and add the token. Default _count is 10; maximum is 100 per page in HealthLake. The SearchWithPost Content-Type is application/x-www-form-urlencoded, not application/fhir+json — SigV4 signing must use the URL-encoded body for the content hash.

SearchWithPost vs SearchWithGet

FHIR defines two equivalent ways to issue a search request. Both accept the same search parameters and return identical Bundle responses. The choice between them matters for security and operational reasons, not functionality.

SearchWithGet appends search parameters to the URL as a query string: GET /r4/Patient?family=Smith&birthdate=1990-01-15. This is the most natural form for FHIR and matches how HTTP GET requests conventionally work. For exploration and debugging it is convenient — you can test it directly in a browser or with curl. The problem is that query strings appear in HTTP server access logs, proxy logs, CDN logs, and browser history. For health data, patient names, dates of birth, and medical record numbers in URL query strings are a PHI exposure risk. Under HIPAA, access logs containing PHI must be treated as PHI themselves — handled with appropriate controls, audit trails, and retention policies. Query string PHI dramatically increases your log management burden.

SearchWithPost sends the same parameters in the HTTP request body: POST /r4/Patient/_search with body family=Smith&birthdate=1990-01-15 and Content-Type: application/x-www-form-urlencoded. The body does not appear in standard access log formats. Additionally, POST bodies have no length limit, which matters for complex queries with many search parameters or long identifier lists. The URL path /_search suffix distinguishes a search POST from a resource creation POST to the same resource type path.

Use SearchWithPost in every production MCP server tool handler. Use SearchWithGet only for ad-hoc debugging in development environments where you are certain no real PHI is present.

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

const signer = new SignatureV4({
  service: 'healthlake',
  region: process.env.AWS_REGION!,
  credentials: fromNodeProviderChain(),
  sha256: Sha256,
});

// SearchWithPost — PHI-safe FHIR search
async function searchFHIR(
  datastoreEndpoint: string,
  resourceType: string,
  params: Record<string, string | string[]>
): Promise<FHIRBundle> {
  const url = new URL(`${datastoreEndpoint}/${resourceType}/_search`);

  // Build URL-encoded body — URLSearchParams handles repeated keys correctly
  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();

  const request = {
    method: 'POST',
    protocol: 'https:' as const,
    hostname: url.hostname,
    path: url.pathname,
    headers: {
      // SearchWithPost requires application/x-www-form-urlencoded — NOT application/fhir+json
      'content-type': 'application/x-www-form-urlencoded',
      host: url.hostname,
      'content-length': String(Buffer.byteLength(bodyStr)),
    },
    body: bodyStr,
  };

  const signed = await signer.sign(request);

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

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

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

The critical detail in the signing: Content-Type must be application/x-www-form-urlencoded in the headers object passed to signer.sign() — not application/fhir+json as used for resource CRUD operations. SigV4 includes the Content-Type header in the signed string, so if the Content-Type you sign differs from the one you send in the actual request, HealthLake returns HTTP 403 with a "SignatureDoesNotMatch" error.

Bundle response structure and parsing

All FHIR search responses are returned as Bundle resources with type: 'searchset'. The Bundle contains a total count, pagination links, and an entry array where each element has a resource and a search object indicating how that resource appeared in the results.

interface FHIRBundle {
  resourceType: 'Bundle';
  type: 'searchset';
  total: number;  // total matching resources — may be approximate for large datasets
  link: Array<{
    relation: 'self' | 'next' | 'previous' | 'first' | 'last';
    url: string;
  }>;
  entry?: Array<{
    resource: FHIRResource;
    search: {
      mode: 'match' | 'include' | 'outcome';
      score?: number;
    };
  }>;
}

// Parse a Bundle response and extract matching resources
function extractMatches<T extends FHIRResource>(bundle: FHIRBundle): T[] {
  return (bundle.entry ?? [])
    .filter(entry => entry.search.mode === 'match')
    .map(entry => entry.resource as T);
}

// Extract included resources (from _include / _revinclude)
function extractIncludes<T extends FHIRResource>(
  bundle: FHIRBundle,
  resourceType: string
): T[] {
  return (bundle.entry ?? [])
    .filter(entry => entry.search.mode === 'include' && entry.resource.resourceType === resourceType)
    .map(entry => entry.resource as T);
}

The search.mode field on each entry tells you why that resource appears in the Bundle:

Always filter by mode === 'match' when you want only the resources you searched for. Failing to filter means included resources from _include queries appear mixed in with direct matches, and the resource types will differ — leading to type assertion failures or incorrect processing downstream.

The total field deserves careful treatment. For small datasets, it is exact. For large data stores with many matching resources, HealthLake may return an approximate count. Do not use bundle.total for precise reporting or as a stop condition — use the absence of a next link to determine when you have exhausted all pages.

Pagination with _page-token

When a search returns more results than the page size (default 10, maximum 100), the Bundle includes a next link in the link array. The token for the next page is embedded as a query parameter named _page-token in that link URL. To retrieve the next page, repeat the search with all original parameters plus the _page-token value.

HealthLake pagination tokens are opaque, URL-safe strings. They are time-limited — do not store them in databases or pass them between user sessions. If a token expires, re-execute the search from the first page. For MCP tool handlers, pagination tokens should only live for the duration of a single tool invocation.

// Extract _page-token from the 'next' link in a Bundle
function extractNextPageToken(bundle: FHIRBundle): string | null {
  const nextLink = bundle.link?.find(l => l.relation === 'next');
  if (!nextLink) return null;

  const nextUrl = new URL(nextLink.url);
  return nextUrl.searchParams.get('_page-token');
}

// Async generator: yields one page of match resources at a time
async function* searchAllPages(
  datastoreEndpoint: string,
  resourceType: string,
  params: Record<string, string | string[]>,
  pageSize = 50
): AsyncGenerator<FHIRResource[]> {
  let currentParams: Record<string, string | string[]> = {
    ...params,
    _count: String(pageSize),
  };

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

    if (matches.length > 0) yield matches;

    const nextToken = extractNextPageToken(bundle);
    if (!nextToken) break;

    // Keep original search filters, add token for next page
    currentParams = { ...params, _count: String(pageSize), '_page-token': nextToken };
  }
}

// Collect all matching resources across all pages (use with care for large result sets)
async function searchAll(
  datastoreEndpoint: string,
  resourceType: string,
  params: Record<string, string | string[]>
): Promise<FHIRResource[]> {
  const all: FHIRResource[] = [];
  for await (const page of searchAllPages(datastoreEndpoint, resourceType, params)) {
    all.push(...page);
  }
  return all;
}

For MCP tool handlers, prefer the streaming async generator pattern over collecting all results at once. Clinical data sets can be large — a patient with a 20-year care history may have thousands of Observation resources. Collecting all of them into memory before returning defeats the purpose of pagination and risks running out of memory or exceeding MCP tool response size limits. Instead, return the first page with a continuation token that the LLM can pass in a follow-up tool call.

Search parameters: universal parameters

FHIR defines a set of search parameters that apply to all resource types. These parameters use the underscore prefix convention (_id, _lastUpdated, etc.) and work consistently across Patient, Observation, Condition, and every other resource type.

Parameter Meaning Example Notes
_id Resource logical ID _id=abc123def456 Equivalent to a direct GET — use GET /{type}/{id} for single resource reads
_lastUpdated When the resource was last modified in HealthLake _lastUpdated=gt2024-01-01 Use for change-feed style queries: "what changed since last sync"
_count Page size _count=50 Default 10, maximum 100 in HealthLake — always set explicitly
_page-token Pagination continuation token _page-token=abc...xyz Opaque, time-limited — extract from bundle.link[?relation=='next'].url
_sort Sort order _sort=-date Prefix with - for descending; HealthLake supports sorting on a subset of parameters
_include Include referenced resources in results _include=Observation:subject Include the Patient referenced by each Observation match
_revinclude Include resources that reference matched resources _revinclude=Observation:encounter Include all Observations referencing matched Encounters

Search parameters: Patient

Patient search is the entry point for most clinical queries — you typically search for a patient by demographic identifiers, then use the returned patient ID to search for their clinical data. HealthLake supports the core Patient search parameters from the FHIR R4 specification.

Parameter Meaning Example Notes
family Family (last) name family=Smith Case-insensitive in HealthLake; partial match depends on configuration
given Given (first) name given=John Matches any given name in the name array
name Any part of any name name=Smith Searches across family and given names simultaneously
birthdate Date of birth birthdate=1990-01-15 Exact match; supports date prefix operators (lt, gt, etc.)
gender Administrative gender gender=male Values: male, female, other, unknown
identifier External identifier (MRN, SSN, etc.) identifier=MRN-00123 Can include system: identifier=http://hospital.example.com/mrn|MRN-00123
address Any address field address=Boston Searches city, state, line, and postal code
// Find a patient by MRN
const patientBundle = await searchFHIR(
  datastoreEndpoint,
  'Patient',
  {
    identifier: 'http://hospital.example.com/mrn|MRN-00123',
    _count: '1',
  }
);

const patients = extractMatches(patientBundle);
if (patients.length === 0) throw new Error('Patient not found');
const patientId = patients[0].id;

Search parameters: Observation

Observation search is the workhorse for clinical data retrieval — lab values, vital signs, and clinical findings are all Observation resources. The code parameter with LOINC codes is the primary way to retrieve specific test types.

Parameter Meaning Example Notes
subject Patient reference (full) subject=Patient/abc123 Include resource type prefix
patient Patient shorthand (ID only) patient=abc123 Alias for subject that accepts bare patient ID
date Effective date/time of the observation date=ge2024-01-01 Use multiple values for ranges: date=ge2024-01-01 AND date=le2024-12-31
code LOINC or SNOMED code code=8867-4 LOINC: 8867-4 (heart rate), 8310-5 (body temp), 2160-0 (creatinine), 2345-7 (glucose)
category Broad category category=vital-signs Values: vital-signs, laboratory, imaging, social-history, survey
status Observation status status=final Values: registered, preliminary, final, amended, cancelled
value-quantity Numeric result value value-quantity=gt100 Useful for finding abnormal values above/below thresholds
encounter Associated encounter encounter=Encounter/xyz789 Retrieve all observations from a specific visit

Search parameters: Condition and MedicationRequest

Condition resources represent diagnoses and problems. MedicationRequest resources represent prescriptions and medication orders. Both use the subject or patient parameter to scope results to a specific patient.

Resource Parameter Meaning Example
Condition subject Patient reference subject=Patient/abc123
Condition clinical-status Current status of the problem clinical-status=active (also: recurrence, relapse, inactive, remission, resolved)
Condition code SNOMED CT or ICD-10-CM code code=73211009 (type 2 diabetes mellitus), code=44054006 (also type 2 diabetes, alternate SNOMED)
Condition onset-date When the condition started onset-date=ge2020-01-01
Condition category Problem-list vs encounter-diagnosis category=problem-list-item
MedicationRequest subject Patient reference subject=Patient/abc123
MedicationRequest status Current prescription status status=active (also: on-hold, cancelled, completed, stopped)
MedicationRequest medication RxNorm medication code medication=860975 (metformin 500mg tab)
MedicationRequest authoredon Date the prescription was written authoredon=ge2024-01-01
MedicationRequest intent Purpose of the request intent=order (also: proposal, plan, instance-order)

Date range queries

FHIR date search parameters support comparison operators using a two-character prefix. This is the standard mechanism for querying observations within a date range, finding conditions that onset before or after a date, and paginating through time-ordered clinical events. The operators apply to any date or dateTime parameter.

Operator Meaning Example
eq Equal (default when no operator) date=eq2024-06-15 or date=2024-06-15
ne Not equal date=ne2024-06-15
lt Less than (before) date=lt2024-01-01
le Less than or equal date=le2024-12-31
gt Greater than (after) date=gt2024-01-01
ge Greater than or equal date=ge2024-01-01

Date ranges require two separate parameter values for the same parameter name, both specifying a bound. When URL-encoding, repeat the key: date=ge2024-01-01&date=le2024-12-31. FHIR semantics treat multiple values for the same search parameter as AND conditions for date parameters. Use URLSearchParams.append() rather than set() to add multiple values for the same key without overwriting.

// Date range for Observations in Q1 2024
const obsBundle = await searchFHIR(
  datastoreEndpoint,
  'Observation',
  {
    patient: patientId,
    date: ['ge2024-01-01', 'le2024-03-31'],  // array for repeated key
    category: 'laboratory',
    status: 'final',
    _count: '50',
    _sort: '-date',
  }
);

// The URLSearchParams inside searchFHIR handles array values by appending:
// patient=abc123&date=ge2024-01-01&date=le2024-03-31&category=laboratory&status=final&_count=50&_sort=-date

Date formats: use YYYY-MM-DD for date-only values, or YYYY-MM-DDThh:mm:ssZ for date-time values. HealthLake stores Observation effectiveDateTime values with time components when they were created with time precision — searching with a date-only value like ge2024-01-01 matches any dateTime on or after midnight UTC of that date.

Subject reference formats and cross-resource chaining

The subject and patient parameters on Observation, Condition, MedicationRequest, and Encounter accept patient references in slightly different formats depending on which parameter you use.

subject expects a full FHIR reference including the resource type: subject=Patient/abc123. The Patient/ prefix is required. Sending a bare ID like subject=abc123 without the resource type prefix may return zero results or an error — the behavior is undefined when the resource type is omitted from a reference search parameter.

patient is an alias parameter defined on Observation, Condition, and several other resource types as a convenience. It accepts the bare patient ID without the resource type prefix: patient=abc123. Using patient is marginally more convenient for the common case but provides no functional difference — it resolves to the same underlying reference search.

Cross-resource search chaining uses dot notation to traverse references. For example, Observation?subject.family=Smith searches for Observations where the referenced Patient resource has family=Smith. HealthLake supports a subset of FHIR chaining; not all chained parameters are supported. Where chaining is not supported, do the lookup in two steps: first search for the Patient by name, then search for Observations using the returned patient ID.

// Two-step lookup (more reliable than chaining)
// Step 1: find the patient
const patientBundle = await searchFHIR(datastoreEndpoint, 'Patient', {
  family: 'Smith',
  given: 'John',
  birthdate: '1990-01-15',
  _count: '5',
});
const patients = extractMatches(patientBundle);
if (patients.length === 0) throw new Error('Patient not found');

// Step 2: find their observations
const obsBundle = await searchFHIR(datastoreEndpoint, 'Observation', {
  patient: patients[0].id,  // bare ID, using the 'patient' alias
  code: '8867-4',           // LOINC: heart rate
  date: ['ge2024-01-01', 'le2024-12-31'],
  status: 'final',
  _sort: '-date',
  _count: '20',
});

_include and _revinclude: multi-resource queries in one request

The _include and _revinclude parameters reduce the number of round trips needed to fetch related resources. They are especially useful for clinical summary views where you need a primary resource and all associated data in a single query.

_include=Observation:subject tells HealthLake: for each matching Observation, also include the Patient referenced by the subject field. The included Patient resources appear in the Bundle with search.mode: 'include'. This avoids a separate lookup for the patient when you already have observation IDs.

_revinclude=Observation:encounter tells HealthLake: for each matching Encounter, also include all Observation resources that reference that Encounter in their encounter field. This is a "reverse" include — instead of following outgoing references from the matched resource, you follow incoming references to it.

// Get an Encounter and all its Observations in one request
const bundle = await searchFHIR(datastoreEndpoint, 'Encounter', {
  patient: patientId,
  date: ['ge2024-06-01', 'le2024-06-30'],
  status: 'finished',
  _revinclude: 'Observation:encounter',
  _count: '10',
});

const encounters = extractMatches(bundle);
const observations = extractIncludes(bundle, 'Observation');

console.log(`Found ${encounters.length} encounters with ${observations.length} total observations`);

// Map observations back to their encounters
const obsByEncounter = new Map<string, FHIRResource[]>();
for (const obs of observations) {
  const encounterRef = (obs as Record<string, any>).encounter?.reference;
  if (encounterRef) {
    const encId = encounterRef.split('/').pop()!;
    if (!obsByEncounter.has(encId)) obsByEncounter.set(encId, []);
    obsByEncounter.get(encId)!.push(obs);
  }
}

MCP tool handler: get_patient_observations

This practical example shows a complete MCP tool handler for retrieving a patient's observations by LOINC code and optional date range — a common building block for clinical timeline views, lab trend analysis, and vital sign monitoring agents.

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

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

const datastoreEndpoint = process.env.HEALTHLAKE_ENDPOINT!;

server.tool(
  'get_patient_observations',
  'Retrieve FHIR Observation resources for a patient, optionally filtered by LOINC code and date range.',
  {
    patient_id: z.string().describe(
      'The FHIR logical ID of the Patient resource (UUID from HealthLake)'
    ),
    loinc_code: z.string().optional().describe(
      'LOINC code to filter by, e.g. "8867-4" for heart rate, "2160-0" for creatinine'
    ),
    start_date: z.string().optional().describe(
      'Earliest observation date, inclusive, in YYYY-MM-DD format'
    ),
    end_date: z.string().optional().describe(
      'Latest observation date, inclusive, in YYYY-MM-DD format'
    ),
    category: z.enum(['vital-signs', 'laboratory', 'imaging', 'social-history']).optional().describe(
      'Broad observation category to filter by'
    ),
    page_size: z.number().min(1).max(100).default(20).describe(
      'Number of results per page (1-100, default 20)'
    ),
    page_token: z.string().optional().describe(
      'Pagination token from a previous call to continue fetching results'
    ),
  },
  async ({ patient_id, loinc_code, start_date, end_date, category, page_size, page_token }) => {
    const params: Record<string, string | string[]> = {
      patient: patient_id,
      status: 'final',
      _count: String(page_size),
      _sort: '-date',  // newest first
    };

    if (loinc_code) params.code = loinc_code;
    if (category) params.category = category;

    // Date range: array values become repeated URL-encoded keys
    const dateFilters: string[] = [];
    if (start_date) dateFilters.push(`ge${start_date}`);
    if (end_date) dateFilters.push(`le${end_date}`);
    if (dateFilters.length > 0) params.date = dateFilters;

    // Pagination: add token if continuing a previous search
    if (page_token) params['_page-token'] = page_token;

    const bundle = await searchFHIR(datastoreEndpoint, 'Observation', params);
    const observations = extractMatches(bundle);
    const nextToken = extractNextPageToken(bundle);

    return {
      content: [{
        type: 'text',
        text: JSON.stringify({
          total: bundle.total,
          count: observations.length,
          next_page_token: nextToken,
          observations: observations.map(obs => ({
            id: obs.id,
            code: (obs as Record<string, any>).code?.coding?.[0],
            value: (obs as Record<string, any>).valueQuantity,
            effectiveDateTime: (obs as Record<string, any>).effectiveDateTime,
            status: (obs as Record<string, any>).status,
          })),
        }, null, 2)
      }]
    };
  }
);

server.tool(
  'get_patient_conditions',
  'Retrieve active FHIR Condition resources (diagnoses) for a patient.',
  {
    patient_id: z.string().describe('The FHIR logical ID of the Patient resource'),
    clinical_status: z.enum(['active', 'recurrence', 'relapse', 'inactive', 'remission', 'resolved'])
      .default('active')
      .describe('Filter conditions by clinical status'),
    page_size: z.number().min(1).max(100).default(20),
  },
  async ({ patient_id, clinical_status, page_size }) => {
    const bundle = await searchFHIR(datastoreEndpoint, 'Condition', {
      subject: `Patient/${patient_id}`,
      'clinical-status': clinical_status,
      _count: String(page_size),
      _sort: '-onset-date',
    });

    const conditions = extractMatches(bundle);

    return {
      content: [{
        type: 'text',
        text: JSON.stringify({
          total: bundle.total,
          conditions: conditions.map(cond => ({
            id: cond.id,
            code: (cond as Record<string, any>).code?.coding?.[0],
            clinicalStatus: (cond as Record<string, any>).clinicalStatus?.coding?.[0]?.code,
            onsetDateTime: (cond as Record<string, any>).onsetDateTime,
          })),
        }, null, 2)
      }]
    };
  }
);

The next_page_token in the response lets the LLM continue pagination in a follow-up tool call by passing it back as the page_token argument. This pattern keeps individual tool calls within response size limits while allowing the agent to retrieve complete data sets across multiple calls when needed.

Common gotchas and production errors

Error Cause Fix
Search returns zero results despite known-matching resources _count was not set and defaulted to 10, but all matches happened to be on later pages; or the subject reference used bare ID without resource type prefix (subject=abc123 instead of subject=Patient/abc123) Always set _count explicitly; use full references for subject (e.g. Patient/abc123) or the patient alias for bare IDs
HTTP 403 SignatureDoesNotMatch on SearchWithPost Content-Type in the signed request was application/fhir+json (copied from CRUD helper) instead of application/x-www-form-urlencoded Use a separate signing path for search requests that sets content-type: application/x-www-form-urlencoded before calling signer.sign()
bundle.total is lower than actual result count across all pages HealthLake may return an approximate total for large data stores — this is documented FHIR behavior Do not use bundle.total for precise counts; paginate to completion and count retrieved resources instead
Pagination token expired between calls _page-token values are time-limited and expire if not used promptly Do not store page tokens across MCP sessions or in databases; re-execute the search from the beginning if the token expires. Return the token to the caller for immediate use only.
Date range with two date values only applies one bound URLSearchParams.set('date', 'ge2024-01-01') then .set('date', 'le2024-12-31') — the second call overwrites the first Use URLSearchParams.append() for the second date value, or pass date as an array and use append in a loop
Included resources missing from results when using _include Filtering entries with mode === 'match' only — included resources have mode === 'include' and are excluded Use separate filter passes: extractMatches() for primary results and extractIncludes() for referenced resources
SearchWithPost to /Patient (without /_search) returns 400 or creates a resource POST to /Patient is the FHIR create operation — not search. The /_search suffix is required for SearchWithPost. Always append /_search to the resource type path for SearchWithPost: POST to /Patient/_search not /Patient

One additional note on FHIR search performance in HealthLake: searches on _id and direct reference parameters (patient, subject) are fast because they use internal indexing. Full-text string searches on name or address are slower and should be used sparingly in production MCP tools with high call rates. For patient lookup in production, prefer identifier search by MRN over name-based search — MRNs are precise identifiers that return at most one result, while name searches may return many candidates and require disambiguation logic.