> ## Documentation Index
> Fetch the complete documentation index at: https://docs.corti.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Retrieve patient data

> Build a schema tool that requests EHR data for the current patient by resource type, hands the fetch to the client, and answers from the records that come back.

The clinician asks a patient-specific question. The agent emits a structured request naming the kinds of record it needs, yields, and answers from the records the client fetches back. If the answer depends on the *current* patient's electronic health record (EHR), retrieve.

![Retrieve flow: the clinician asks a patient question, the agent requests the relevant EHR data, the client fetches the records, and the agent answers grounded in the returned data.](https://mintcdn.com/corti/OdqulwjO6Fo6Jlod/images/recipes-retrieve-light.svg?fit=max\&auto=format\&n=OdqulwjO6Fo6Jlod\&q=85\&s=b208c0e607b716ab9b007e8c5769078a)

A retrieve takes two runs: the agent requests data, the client fetches it, and the agent answers from what comes back.

This page builds on [Build a schema tool](https://docs.corti.ai/agentic/cookbook/extract.md#build-a-schema-tool), which explains the five fields of the connector body, `additionalProperties: false`, `required`, `const`, `enum`, `transition`, and how to attach a tool to your agent. What is new here: a `requests` array, `anyOf` branches selected by `resourceType`, per-branch search parameters that are all optional, and the `input_required` transition that hands the fetch to the client.

## Build the retrieve tool

The target: the clinician asks "Does the patient have hypertension?" and the agent emits one request that names every resource type it needs, with any search parameters, then waits for the client to fetch the records.

### 1. Wrap the requests in an array

One question often needs several kinds of data, such as the problem list, lab values, and medication. So the schema's only top-level field is a `requests` array, and the agent fills every request in one call:

```json theme={null}
"requests": {
  "type": "array", "minItems": 1,
  "items": { ... }
}
```

With `requests` in `required`, `minItems: 1` means the agent can never emit an empty request. The agent should also ask for each resource type at most once per call, but `uniqueItems` compares whole items, so two `Condition` requests with different search parameters would both pass it. That rule goes in the `description` instead: "Emit at least one request, at most one per resource type."

### 2. Make each request one of several branches with anyOf

Resource types do not all take the same search parameters. Observations narrow by category and date, conditions narrow by category, and flags (alerts on the patient's record) take no parameters at all. So `items` is an `anyOf`: a list of branches, each a complete object schema for a group of resource types that share the same search parameters.

```json theme={null}
"items": {
  "anyOf": [
    { "type": "object", "additionalProperties": false, "required": ["resourceType"], "properties": { ... } },
    { "type": "object", "additionalProperties": false, "required": ["resourceType"], "properties": { ... } }
  ]
}
```

A request is valid if it matches any one branch. Each branch is closed and requires `resourceType`, so a request always says what it asks for and carries only the search parameters its branch defines. This page groups 13 resource types into 7 branches by their search parameters.

### 3. Select the branch with the resource type

A branch that covers one resource type pins it with a `const`. A branch that covers several resource types with the same search parameters lists them in an `enum`:

```json theme={null}
"resourceType": { "const": "Condition" }
```

```json theme={null}
"resourceType": { "enum": ["Procedure", "Appointment"] }
```

No resource type appears in more than one branch, so `resourceType` acts as a discriminator: a request can match only one branch, and `anyOf` behaves like `oneOf` here. Grouping by search parameters keeps the body short, because the resource types in a branch share one definition.

### 4. Give each branch its own search parameters

Each branch lists its search parameters directly on the request, next to `resourceType`, and leaves them out of `required`. Every parameter is optional, and an omitted parameter means no restriction:

```json theme={null}
"properties": {
  "resourceType": { "enum": ["Procedure", "Appointment"] },
  "date": {
    "type": "object", "additionalProperties": false,
    "properties": {
      "ge": { "type": "string" },
      "le": { "type": "string" }
    }
  }
}
```

A branch whose resource types take no search parameters has only `resourceType` in its `properties`, so the agent cannot attach a parameter to a `Flag` request. Parameters whose accepted values your source system defines, such as `type` on `DocumentReference`, stay free-form strings until you know the full set:

```json theme={null}
"type": { "type": "array", "items": { "type": "string" } }
```

A date range is one object: `ge` means on or after, and `le` means on or before. The client converts it to the query your EHR expects.

### 5. Yield with input\_required

The agent cannot answer until the client has fetched the records, so the tool ends the run in `input_required`, not `complete`:

```json theme={null}
"transition": "input_required"
```

The framework enforces the transition. The task is not finished: the client's next message on the same `contextId` resumes it, as described in [Task lifecycle](https://docs.corti.ai/agentic/task-lifecycle.md).

## The full body

Retrieve needs no registry connector. Attach this one schema tool to your agent.

```json expandable theme={null}
{
  "type": "schema",
  "name": "retrieve_patient_data",
  "description": "Request the current patient's EHR data by resource type and search parameters. Omit any search parameter to mean no restriction. Ends this run: the client returns the records in a new message. Emit at least one request, at most one per resource type.",
  "schema": {
    "type": "object",
    "additionalProperties": false,
    "required": ["requests"],
    "properties": {
      "requests": {
        "type": "array", "minItems": 1,
        "items": {
          "anyOf": [
            {
              "type": "object", "additionalProperties": false, "required": ["resourceType"],
              "properties": {
                "resourceType": { "enum": ["AllergyIntolerance", "Flag", "MedicationStatement", "Patient", "ServiceRequest", "Task"] }
              }
            },
            {
              "type": "object", "additionalProperties": false, "required": ["resourceType"],
              "properties": {
                "resourceType": { "const": "DocumentReference" },
                "category": { "type": "array", "items": { "type": "string" }, "description": "Document categories, such as clinical-note." },
                "type": { "type": "array", "items": { "type": "string" }, "description": "Document types defined by the source system." },
                "date": {
                  "type": "object", "additionalProperties": false,
                  "description": "Date range. ge: on or after. le: on or before. A date or date-time, such as 2026-01-01.",
                  "properties": { "ge": { "type": "string" }, "le": { "type": "string" } }
                },
                "_id": { "type": "array", "items": { "type": "string" }, "description": "Document IDs from the source system." },
                "_summary": { "enum": ["true", "false"], "description": "\"false\" returns content. Omit for metadata only." }
              }
            },
            {
              "type": "object", "additionalProperties": false, "required": ["resourceType"],
              "properties": {
                "resourceType": { "const": "QuestionnaireResponse" },
                "authored": {
                  "type": "object", "additionalProperties": false,
                  "description": "When the form was filled in. ge: on or after. le: on or before. A date or date-time, such as 2026-01-01.",
                  "properties": { "ge": { "type": "string" }, "le": { "type": "string" } }
                },
                "questionnaire": { "type": "array", "items": { "type": "string" }, "description": "The forms to return, as identifiers from the source system." },
                "_id": { "type": "array", "items": { "type": "string" }, "description": "Form response IDs from the source system." },
                "_summary": { "enum": ["true", "false"], "description": "\"false\" returns content. Omit for metadata only." }
              }
            },
            {
              "type": "object", "additionalProperties": false, "required": ["resourceType"],
              "properties": {
                "resourceType": { "const": "Observation" },
                "category": {
                  "type": "array",
                  "items": { "enum": ["laboratory", "vital-signs", "social-history", "imaging", "procedure", "survey", "exam", "therapy", "activity"] }
                },
                "date": {
                  "type": "object", "additionalProperties": false,
                  "description": "Date range. ge: on or after. le: on or before. A date or date-time, such as 2026-01-01.",
                  "properties": { "ge": { "type": "string" }, "le": { "type": "string" } }
                }
              }
            },
            {
              "type": "object", "additionalProperties": false, "required": ["resourceType"],
              "properties": {
                "resourceType": { "enum": ["Procedure", "Appointment"] },
                "date": {
                  "type": "object", "additionalProperties": false,
                  "description": "Date range. ge: on or after. le: on or before. A date or date-time, such as 2026-01-01.",
                  "properties": { "ge": { "type": "string" }, "le": { "type": "string" } }
                }
              }
            },
            {
              "type": "object", "additionalProperties": false, "required": ["resourceType"],
              "properties": {
                "resourceType": { "const": "Condition" },
                "category": {
                  "type": "array",
                  "items": { "enum": ["problem-list-item", "encounter-diagnosis"] },
                  "description": "problem-list-item: the patient's ongoing problem list. encounter-diagnosis: diagnoses recorded for a visit or stay."
                }
              }
            },
            {
              "type": "object", "additionalProperties": false, "required": ["resourceType"],
              "properties": {
                "resourceType": { "const": "Encounter" },
                "status": {
                  "type": "array",
                  "items": { "enum": ["planned", "arrived", "triaged", "in-progress", "onleave", "finished", "cancelled"] },
                  "description": "in-progress: the current stay. Omit for the full stay history."
                },
                "date": {
                  "type": "object", "additionalProperties": false,
                  "description": "Date range. ge: on or after. le: on or before. A date or date-time, such as 2026-01-01.",
                  "properties": { "ge": { "type": "string" }, "le": { "type": "string" } }
                },
                "_include": {
                  "type": "array",
                  "items": { "enum": ["Encounter:diagnosis"] },
                  "description": "Add it to also get the stay's coded diagnoses and procedures. The Encounter lists each one with its use and rank."
                }
              }
            }
          ]
        }
      }
    }
  },
  "transition": "input_required"
}
```

| Field | Type | Required | Description |
| - | - | - | - |
| `requests` | array, at least one item | yes | One request per resource type the agent needs. The `description` limits it to at most one per resource type |
| `requests[].resourceType` | `const` or `enum`, per branch | yes | The resource type to search. It selects the branch the request matches |
| Search parameters, such as `requests[].category` and `requests[].date` | per branch | no | The search parameters for that branch, set directly on the request. Every parameter is optional, and an omitted parameter means no restriction. Branch 1 has none |

The right-hand column is the pattern: map each branch to the equivalent read surface in your EHR.

| Branch | Resource types | What it retrieves | Search parameters | What yours would be |
| - | - | - | - | - |
| 1 | `AllergyIntolerance`, `Flag`, `MedicationStatement`, `Patient`, `ServiceRequest`, `Task` | In order: allergies and intolerances, alerts, current medication, patient details, existing orders and their status, reminders and follow-ups | none | Your unfiltered feeds: the reads that take no arguments beyond the patient |
| 2 | `DocumentReference` | Clinical notes and documents, such as course notes, discharge letters, referral letters, and scanned reports | `category`, `type`, `date`, `_id`, `_summary` | Your note and document repositories, however many you expose |
| 3 | `QuestionnaireResponse` | Filled clinical forms, such as assessments and checklists | `authored`, `questionnaire`, `_id`, `_summary` | Your form repository |
| 4 | `Observation` | Lab results, vital signs, and other measurements and findings | `category`, `date` | Your lab and observation reads |
| 5 | `Procedure`, `Appointment` | Surgical and other procedure history, appointments | `date` | Your dated-event reads |
| 6 | `Condition` | The problem list and the diagnoses recorded for each visit | `category` | Your problem list |
| 7 | `Encounter` | Hospital stays and visits, and optionally each stay's coded diagnoses and procedures | `status`, `date`, `_include` | Your patient administration source and your case-coding or billing view |

An encounter is one visit or hospital stay. `status: ["in-progress"]` returns the current stay, and no `status` returns the stay history. Add `_include: ["Encounter:diagnosis"]` and the stay's coded diagnoses and procedures come back with it. The Encounter lists each one with its use (such as admission or discharge diagnosis) and rank. Together they are the data a Diagnosis-Related Group (DRG) billing view reads.

> [accordion] Search parameters by branch
>
> | Parameter | Branch | Type | Values |
> | - | - | - | - |
> | `category` | 2 | array of strings | Free-form, defined by your source system, such as `clinical-note` |
> | `type` | 2 | array of strings | Free-form document types, defined by your source system |
> | `date`\* | 2, 4, 5, 7 | object `{ ge, le }`, both optional | `ge` is on or after, `le` is on or before, each a date or date-time such as `2026-01-01` |
> | `_id` | 2, 3 | array of strings | Record IDs from your source system |
> | `_summary` | 2, 3 | enum | `"true"` returns metadata only. `"false"` returns content. The client treats an omitted `_summary` as `"true"` |
> | `authored`\* | 3 | object `{ ge, le }`, both optional | When the form was filled in. Same syntax as `date` |
> | `questionnaire` | 3 | array of strings | The forms to return, as identifiers from your source system |
> | `category` | 4 | array of enum | `laboratory`, `vital-signs`, `social-history`, `imaging`, `procedure`, `survey`, `exam`, `therapy`, `activity` |
> | `category` | 6 | array of enum | `problem-list-item` (the ongoing problem list), `encounter-diagnosis` (diagnoses recorded for a visit or stay) |
> | `status` | 7 | array of enum | `planned`, `arrived`, `triaged`, `in-progress`, `onleave`, `finished`, `cancelled` |
> | `_include` | 7 | array of enum | `Encounter:diagnosis`: also returns the stay's coded diagnoses and procedures. The Encounter lists each one with its use and rank |
>
> \* Differs slightly from [FHIR R4](https://docs.corti.ai/agentic/cookbook/overview#based-on-fhir-r4), where a simpler field is easier for the agent to fill.

## Point the system prompt at the tool

The schema tool defines what the agent can request. The system prompt routes each question to it. This is the minimal prompt for retrieve:

```text theme={null}
Role: answer patient-specific clinical questions, for clinicians, from the patient's EHR.

You have one tool: retrieve_patient_data. It requests EHR data by resource type and search parameter.

Route each request:
- asks about this patient        -> retrieve_patient_data
- does not mention this patient  -> say you answer patient questions from the record only
- unclear                        -> ask one question, then stop
```

Add [the rules every flow shares](https://docs.corti.ai/agentic/cookbook/overview#write-the-system-prompt). Retrieve is the flow likeliest to break the rule against requesting data again once it has arrived: when the records come back, the agent must answer from them, not request the same resource types again.

> [accordion] Run it: flow, example, and the client's apply-step
>
> The agent handles a retrieve in two runs: it emits a request, then answers from what comes back. The system prompt and the tool's description produce this sequence.
>
> 1. **Clinician asks**: "Does the patient have hypertension?"
> 2. **Emit request**: the agent names one or more resource types and any search parameters, and ends the run in `input_required`.
> 3. **Client fetches EHR**: the client resolves each request against the EHR's read API.
> 4. **Data arrives**: the client sends the records back as a new message on the same `contextId`, carrying a data part. See [Using data parts for structured context](https://docs.corti.ai/agentic/guides/send-message.md#using-data-parts-for-structured-context) for the data-part shape. The task is in `input_required`, not finished, so that message resumes it. See [Task lifecycle](https://docs.corti.ai/agentic/task-lifecycle.md).
> 5. **Answer**: the agent grounds every claim in the returned data and answers in prose.
>
> For "Does the patient have hypertension?", the agent emits one request per resource type it needs, in a single call:
>
> ```json theme={null}
> {
>   "requests": [
>     { "resourceType": "Condition", "category": ["problem-list-item"] },
>     { "resourceType": "Observation", "category": ["laboratory", "vital-signs"] },
>     { "resourceType": "MedicationStatement" },
>     { "resourceType": "Encounter", "status": ["in-progress"], "_include": ["Encounter:diagnosis"] }
>   ]
> }
> ```
>
> `MedicationStatement` has no search parameters, so the client returns all current medication. The `Encounter` request asks for the current stay and its coded diagnoses and procedures. Because the `transition` is `input_required`, this call ends the run.
>
> The apply-step is yours. Map each request to your EHR's read API, scoped to the current patient, then fetch the records and return them in a new message on the same `contextId`. If answers come back hedged or empty, check what the client sends back as the data part before adding prompt rules.

## Adapt it

* Keep one retrieve connector for all your resource types. One connector with every branch is easier for the agent to route to and more token-efficient than several.
* Remove the resource types and search parameters your EHR does not support, using the "What yours would be" column in the branch table.
* Replace the free-form `category` and `type` strings on `DocumentReference`, and the `questionnaire` strings, with your own `enum` once you know your system's full set. A closed `enum` makes the schema a complete menu of what the agent may emit.
* If a new resource type takes the same search parameters as an existing branch, add it to that branch's `resourceType` enum. If it takes different parameters, add a new branch to the `anyOf`.
* The `transition` stays `input_required`, because the agent always waits for the client to fetch the data.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.