After connection
Read the session result, list a patient's connections, and listen for record events.
Open in
Show prompt text
You are an AI coding agent helping integrate Medblocks Patient Access into the codebase that is currently open. Treat the live Medblocks docs and generated API reference as the source of truth. If you are running inside a local repo that contains openapi/medblocks.json, read it too. Do not rely on endpoint names, SDK calls, response fields, or code snippets from memory. Before changing code, read the current docs directly. - Patient Access overview https://medblocks.com/docs/patient-access/overview - Find connections https://medblocks.com/docs/patient-access/find-connections - Create patients https://medblocks.com/docs/patient-access/create-patients - Create a patient session https://medblocks.com/docs/patient-access/create-patient-session - Medblocks-hosted page https://medblocks.com/docs/patient-access/create-patient-session/medblocks-hosted-page - Your own UI https://medblocks.com/docs/patient-access/create-patient-session/your-own-ui - Handle the return https://medblocks.com/docs/patient-access/handle-the-return - After connection https://medblocks.com/docs/patient-access/after-connection - Get the data https://medblocks.com/docs/patient-access/get-the-data - API conventions https://medblocks.com/docs/reference/conventions - API reference https://medblocks.com/docs/reference/api Use the page I copied this from as the immediate task context, then use the rest of the Build pages to understand the full flow. Work in this order. 1. Inspect this codebase first. Identify the app framework, server boundary, environment variable pattern, existing API client pattern, current patient or user identity model, logging style, and test runner. 2. Read the generated API reference before naming any route, field, enum, header, error code, or SDK method. If your tool has local filesystem access and this repo has openapi/medblocks.json, read that too. If the docs and reference disagree, stop and ask the user which source to follow. 3. Decide whether this app should use the Medblocks-hosted page, your own UI, or both. Ask the user if the answer is not obvious from the product. 4. Keep the Medblocks API key server-side. Never expose it through public environment variable prefixes, frontend bundles, browser logs, or client-side fetches. 5. Implement the smallest complete path for the selected page. Follow existing project conventions for file locations, naming, validation, errors, loading states, and tests. 6. After a patient returns from authorization, verify the result from the server using the latest documented Patient Access status flow. Do not trust query string values as the final source of truth. 7. Preserve Medblocks request IDs and documented error details in logs and server responses where safe. Avoid logging PHI unless this codebase already has an approved pattern. 8. Run the relevant type checks and tests before reporting done. If a live smoke test needs credentials the repo does not have, explain the exact manual smoke test steps. If any required detail is missing, ask concise questions before writing code. In a healthcare integration, a correct pause is better than an incorrect assumption.
After your return page has parsed patient_id and patient_session_id, confirm the outcome on your server. A patient session finishing is not the same as a connection going active, and a connection going active is not the same as records being ready. This page covers all three, the authoritative reads on your server and the events that save you from polling for them.
Read the session
Call mb.patientSession.retrieve(id) on your server with the patient_session_id you read from the return. It gives you the session and its connections, one per facility the patient tried in that session.
import { mb } from "./medblocks";
const session = await mb.patientSession.retrieve(patientSessionId);
const active = (session.connections ?? []).filter((c) => c.status === "active");
const connected = active.length > 0;A session can be complete and still have connected nothing, for example if the patient changed their mind at the portal. So the session lifecycle answers whether the patient finished, and the connection status answers whether records flow. The real success signal is a connection going active, not the session being complete. Act on the connection.
// session.status is the patient's progress, not the result.
// connections[].status decides whether records flow.
const failed = (session.connections ?? []).filter((c) => c.status === "failed");
const lapsed = (session.connections ?? []).filter((c) => c.status === "refresh_failed");A refresh_failed connection worked before but its access lapsed, so prompt the patient to reconnect. Authorization explains why access lapses.
idstringrequiredPatient session id (ps_*).
Read the patient’s connections
A session shows one trip. To see everything a patient has connected across every session, read the patient. mb.patients.retrieve(id) returns the patient with a connections array, each entry carrying a connection_id and a status, including failed attempts so you can surface them.
import { mb } from "./medblocks";
const patient = await mb.patients.retrieve("user_42");
const live = patient.connections.filter((c) => c.status === "active");Those entries name the facility by ID, not by its display name or logo. The getConnections helper does that lookup for you and hands back fully rendered facilities, ready to drop into a UI. It skips failed connections, since they carry no data.
import { mb } from "./medblocks";
const facilities = await mb.patients.getConnections("user_42", { hydrate: true });
for (const facility of facilities) {
console.log(facility.name, facility.logo_url, facility.fhir_base_url);
}idstringrequiredYour patient_id from Patient creation or Session upsert.
Disconnect a connection
Sometimes a patient asks you to stop pulling from a source, or you no longer need one they linked. mb.patients.disconnectConnection(id, connectionId) removes your organization’s access to one of the patient’s linked sources using the connection_id you read above. Stored tokens are revoked once no other workspace still uses them, and the call returns a tombstone confirming the disconnect.
import { mb } from "./medblocks";
const result = await mb.patients.disconnectConnection("user_42", "conn_01J9YR9N3X4VZ6P2K5RH7M3LMP");
console.log(result.id, result.disconnected);idstringrequiredYour patient_id from Patient creation or Session upsert.
connection_idstringrequiredThe conn_ connection id from the patient's connections[].
A patient’s session history
A patient is not limited to one session. They reconnect when access lapses, add another hospital later, or retry after a failed attempt. mb.patients.listPatientSessions(id) lists every session a patient has had, most recent first, which is what you want for a “past connections” view or a support screen.
import { mb } from "./medblocks";
const page = await mb.patients.listPatientSessions("user_42", { limit: 50 });
for (const session of page.data) {
console.log(session.id, session.status);
}The result is cursor-paginated. Await it for the first page, or iterate it to walk them all.
idstringrequiredYour patient_id from Patient creation or Session upsert.
Listen to events
Reading the session tells you where things stand at one moment. But records arrive in the background after the patient has moved on, and access can lapse weeks later, so polling for either is wasteful and slow. Subscribe to events instead. Medblocks posts to your server the moment something settles.
Four events matter here.
patient_session.completed. The patient finished a session. Update your connected UI and kick off whatever should happen next.records.sync.completed. A background pull settled and new records are ready to read. Trigger downstream processing here rather than guessing when the data has landed.records.sync.failed. A background pull errored. Surface it or page your on-call team.connection.token_refresh_failed. A connection’s access lapsed. Prompt the patient to reconnect to resume the pull.
The full payload for each is in the event catalog, and the webhooks quickstart walks you through a receiver that verifies signatures so you can trust what arrives. Build the receiver there, then handle these four events.
Common errors
| Code | Meaning |
|---|---|
resource_not_found | No patient or session matches the ID you retrieved, or it belongs to another organization. |
bad_request | A query parameter is malformed, such as a limit outside the allowed range. |
missing_api_key | The Authorization header is missing from your server’s request. |
invalid_api_key | The key is invalid or does not belong to your organization. |
Read the full envelope and code list in Errors.
