Skip to content

Connect AdvancedMD to AI Agents: Automate Bulk Patient Data Workflows

Uday Gajavalli Uday Gajavalli 10 min read AI & Agents
TrutoFor teams building AI agents

Give your AI agent AdvancedMD tools.

A complete technical guide to connecting AdvancedMD to AI agents. We cover bypassing FHIR schema complexities, handling asynchronous bulk data exports, and building framework-agnostic agent loops to automate complex clinical workflows safely.

In this guide

  1. 01Initialize the LLM
  2. 02Fetch AdvancedMD Tools via Truto
  3. 03Bind Tools to the Agent
  4. 04Execute the Agent Loop and Handle 429s

The guide

Learn how to connect AdvancedMD to AI agents using Truto's /tools endpoint. Build autonomous workflows for FHIR data, bulk exports, and clinical records.

You want to connect AdvancedMD to an AI agent so your system can autonomously query FHIR records, trigger bulk data exports, extract care plans, and compile clinical summaries based on historical patient context. Here is exactly how to do it using Truto's /tools endpoint and SDK, bypassing the need to build a custom EHR integration from scratch.

Giving a Large Language Model (LLM) read and write access to your AdvancedMD instance is an engineering headache. You either spend weeks building, hosting, and maintaining a custom connector that handles FHIR specifications and asynchronous polling, or you use a managed infrastructure layer that handles the boilerplate for you. If your team uses ChatGPT, check out our guide on connecting AdvancedMD to ChatGPT, or if you are building on Anthropic's models, read our guide on connecting AdvancedMD to Claude. For developers building custom autonomous workflows, you need a programmatic way to fetch these tools and bind them to your agent framework.

This guide breaks down exactly how to fetch AI-ready tools for AdvancedMD, bind them natively to an LLM using frameworks like LangChain, LangGraph, CrewAI, or the Vercel AI SDK, and execute complex clinical workflows. For a deeper look at the architecture behind this approach, refer to our research on Architecting AI Agents: LangGraph, LangChain, and the SaaS Integration Bottleneck.

The Engineering Reality of the AdvancedMD API

Giving an LLM access to external data sounds simple in a prototype. You write a Node.js function that makes a fetch request and wrap it in an @tool decorator. In production against complex clinical systems like AdvancedMD, this approach collapses.

AdvancedMD's API introduces several specific integration challenges that break standard REST assumptions. If you hardcode these interactions into your agent, you will spend your sprints writing defensive integration code instead of improving your model's reasoning.

The FHIR R4 Schema Trap

AdvancedMD utilizes the Fast Healthcare Interoperability Resources (FHIR) R4 standard. Standard LLMs are trained to expect flat, intuitive JSON objects. When an agent wants to read a patient's care plan, it naturally expects a flat object like {"patient_id": "123", "plan": "physical therapy"}.

AdvancedMD will return a deeply nested FHIR Bundle. The actual payload sits under multiple arrays and wrappers, typically structured as entry [].resource. Pushing raw FHIR JSON into an LLM context window is dangerous for two reasons: it consumes massive amounts of tokens for structural boilerplate, and it actively encourages hallucinations. The LLM will often invent FHIR resource types or misinterpret the nested arrays when trying to generate a payload to send back.

Asynchronous Bulk Data Exports

Healthcare integration rarely happens one record at a time. AdvancedMD provides a Bulk FHIR connection for population-level data extraction. This is not a simple GET request. It is a complex asynchronous state machine.

To run a bulk export, your system must:

  1. Send a GET request with specific headers (Prefer: respond-async and OfficeKey) to start the job.
  2. Receive an HTTP 202 Accepted response containing a groupId and jobId.
  3. Repeatedly poll a status endpoint using those IDs.
  4. Handle intermediate 202 statuses ("In progress").
  5. Eventually receive a 200 OK with a manifest containing URLs for the output files.
  6. Download and parse the resulting NDJSON (application/fhir+ndjson) files.

An LLM cannot reliably orchestrate this 6-step asynchronous loop on its own. It will hallucinate polling intervals, invent file URLs, or completely forget the jobId halfway through the process.

Contextual Token Isolation

AdvancedMD enforces strict data isolation based on the authentication context. A token generated for a patient only allows reading that specific patient's data. A provider token assumes the context of the patient selected at sign-in. If your agent is operating in a multi-tenant environment, cross-contamination of token scopes will lead to immediate HTTP 403 Forbidden errors, or worse, returning the wrong patient's clinical history to the prompt.

Why a Unified Tool Layer Matters for Agent Safety

Before writing a line of integration code, decide what layer your agent talks to. This choice determines how safe your production system will be.

Direct API tools (one tool per raw AdvancedMD endpoint) look convenient but they push provider quirks into the LLM's context. The model has to remember that bulk exports require NDJSON, that FHIR payloads are wrapped in Bundles, and that the agent must parse entry [].resource. Every one of those quirks is a hallucination waiting to happen.

Truto's Proxy API abstraction collapses AdvancedMD behind a standardized schema. Your agent sees deterministic, pre-configured tools. That gives you four concrete safety wins:

  1. Smaller attack surface for hallucination. The LLM only ever chooses from a stable list of function names with predictable parameters. It never invents FHIR Bundle schemas or hallucinates NDJSON parsing logic.
  2. Deterministic input validation. Every tool has a strict JSON schema. Invalid arguments are rejected before they hit the AdvancedMD API, so a broken tool call fails fast instead of generating a confusing FHIR validation error.
  3. Isolated state management. The complex asynchronous polling for bulk exports can be abstracted away from the LLM's immediate reasoning loop, keeping the context window clean.
  4. Standardized rate limiting. AdvancedMD has strict rate limits. When you hit a limit, AdvancedMD returns an HTTP 429. Truto does not retry, throttle, or absorb these errors. Instead, Truto normalizes the upstream rate limit information into standardized IETF headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset). This allows your agent framework to implement deterministic backoff logic based on explicit reset times, rather than having the LLM guess when to retry.

Hero Tools for AdvancedMD

Truto provides a comprehensive suite of tools for AdvancedMD by mapping its FHIR endpoints to Proxy APIs. By calling Truto's /integrated-account/<id>/tools endpoint, you instantly equip your agent with these capabilities.

Here are the highest-leverage tools available for AdvancedMD workflows.

Start Bulk Data Export Job

create_a_advanced_md_bulk_export

Initiates an asynchronous export of a patient Group's data. This tool abstracts the initial request setup, ensuring the correct headers (Prefer: respond-async) are passed. It returns the critical groupId and jobId needed to track the export.

"We need to run a population health analysis. Start a bulk data export job for group ID 'diabetics-cohort-2026'. Give me the job ID so we can track it."

Check Bulk Export Status

advanced_md_bulk_export_jobs_lookup

Checks the status of a running bulk export. This tool handles the HTTP 202 ("In progress") and HTTP 200 ("Done") states, ultimately returning the manifest with output file URLs once the job completes.

"Check the status of bulk export job ID 'job-987' for group 'diabetics-cohort-2026'. If it is done, give me the URLs to the NDJSON files."

Read Patient Records

get_single_advanced_md_patient_by_id

Retrieves a specific Patient resource based on the FHIR resource ID. This handles the complex token scoping automatically, ensuring the agent only accesses data permitted by the active integration token.

"Fetch the full demographic and contact profile for patient ID 'pt-5542'."

Search Care Plans

list_all_advanced_md_care_plans

Searches a set of CarePlans based on filter criteria. This is crucial for agents assisting in care coordination, allowing them to pull active treatment plans and instructions.

"Find all active care plans for patient ID 'pt-5542' categorized under 'cardiology'."

Search Diagnostic Reports

list_all_advanced_md_diagnostic_reports

Retrieves DiagnosticReports (such as lab results or imaging studies) based on filter criteria. The tool automatically manages the FHIR Bundle pagination using the next link.

"Pull the most recent diagnostic reports and lab results for patient ID 'pt-5542' from the last 30 days."

Search Document References

list_all_advanced_md_fetched_document_references

Executes the US Core $docref operation to retrieve a patient's documents (e.g., C-CDA files) as DocumentReferences within a specific date range.

"Fetch all clinical document references, including discharge summaries and C-CDAs, for patient ID 'pt-5542' between January 1st and March 1st."

For the complete inventory of AdvancedMD tools and their precise JSON schemas, refer to the AdvancedMD integration page.

Workflows in Action

When you bind these tools to a reasoning engine like Claude 3.5 Sonnet or GPT-4o, the agent can autonomously navigate complex clinical operations. Here are two real-world examples.

Workflow 1: Pre-Encounter Clinical Briefing

Physicians spend hours reviewing charts before appointments. An agent can completely automate the compilation of a pre-encounter briefing by chaining AdvancedMD tools.

"Patient pt-5542 has an appointment tomorrow. Compile a briefing containing their active care plans, any diagnostic reports from the last month, and their known allergies."

  1. The agent calls get_single_advanced_md_patient_by_id to verify the patient's identity and basic demographics.
  2. The agent calls list_all_advanced_md_care_plans passing patient=pt-5542 to retrieve ongoing treatments.
  3. The agent calls list_all_advanced_md_diagnostic_reports to find recent lab work.
  4. The agent calls list_all_advanced_md_allergy_intolerances to pull safety alerts.
  5. The agent synthesizes this nested JSON data into a clean, human-readable markdown briefing for the physician.

Workflow 2: Asynchronous Population Health Export

A healthcare data engineering team needs to export cohorts for a predictive modeling pipeline without manually babysitting the AdvancedMD async endpoints.

"Start a bulk data export for the 'cardiology-risk' group. Monitor the job until it completes, then return the manifest URLs so our data pipeline can download the NDJSON files."

  1. The agent calls create_a_advanced_md_bulk_export passing the target group_id. It receives a 202 Accepted with a jobId.
  2. The agent uses its internal reasoning loop to wait, then calls advanced_md_bulk_export_jobs_lookup.
  3. Receiving an "In progress" status, the agent waits and loops again.
  4. Once advanced_md_bulk_export_jobs_lookup returns a 200 OK, the agent parses the returned manifest and hands the output file URLs back to the user.
sequenceDiagram
    participant User
    participant Agent
    participant Truto
    participant AdvancedMD as "AdvancedMD API"

    User->>Agent: "Export cohort 'cardiology-risk'"
    Agent->>Truto: Call create_a_advanced_md_bulk_export
    Truto->>AdvancedMD: GET /v1/r4/Group/{id}/$export
    AdvancedMD-->>Truto: 202 Accepted {jobId: 123}
    Truto-->>Agent: Returns jobId 123
    
    loop Polling
        Agent->>Truto: Call advanced_md_bulk_export_jobs_lookup(jobId: 123)
        Truto->>AdvancedMD: GET /v1/fhir-bulk/status
        AdvancedMD-->>Truto: 202 {status: "In progress"}
        Truto-->>Agent: Status: In progress
        Note over Agent: Agent waits before retrying
    end
    
    Agent->>Truto: Call advanced_md_bulk_export_jobs_lookup(jobId: 123)
    Truto->>AdvancedMD: GET /v1/fhir-bulk/status
    AdvancedMD-->>Truto: 200 OK {manifest: {urls: [...]}}
    Truto-->>Agent: Returns Manifest
    Agent-->>User: "Export complete. URLs: [...]"

Building Multi-Step Workflows

To build these workflows in code, you need an execution loop that fetches tools from Truto, binds them to your LLM, and handles execution errors - specifically rate limits.

Because AdvancedMD enforces strict rate limiting on API requests, your agent will inevitably encounter HTTP 429 Too Many Requests errors during heavy operations like fetching paginated DocumentReferences. Truto explicitly does not retry, throttle, or apply backoff on rate limit errors. Truto passes the 429 error directly to the caller, while normalizing the upstream headers into standard IETF format (ratelimit-limit, ratelimit-remaining, ratelimit-reset).

It is the caller's responsibility to read the ratelimit-reset header and pause execution.

Here is a complete, framework-agnostic architectural approach using LangChain.js and the truto-langchainjs-toolset.

import { TrutoToolManager } from 'truto-langchainjs-toolset';
import { ChatOpenAI } from '@langchain/openai';
import { AgentExecutor, createToolCallingAgent } from 'langchain/agents';
import { ChatPromptTemplate } from '@langchain/core/prompts';
 
async function runAdvancedMDAgent(prompt: string, integratedAccountId: string) {
    // 1. Initialize the LLM
    const llm = new ChatOpenAI({
        modelName: 'gpt-4o',
        temperature: 0,
    });
 
    // 2. Fetch AdvancedMD tools from Truto's /tools endpoint via the SDK
    const toolManager = new TrutoToolManager({
        apiKey: process.env.TRUTO_API_KEY
    });
    
    const tools = await toolManager.getTools(integratedAccountId);
 
    // 3. Bind the tools to the LLM
    const promptTemplate = ChatPromptTemplate.fromMessages([
        ["system", "You are a clinical data assistant. You retrieve FHIR records and orchestrate bulk data exports from AdvancedMD. If a tool returns a 429 error indicating a rate limit, inform the user that the system is pausing, and use the provided reset time to wait before retrying."],
        ["human", "{input}"],
        ["placeholder", "{agent_scratchpad}"],
    ]);
 
    const agent = createToolCallingAgent({
        llm,
        tools,
        prompt: promptTemplate,
    });
 
    const executor = new AgentExecutor({
        agent,
        tools,
        maxIterations: 10, // Prevent infinite loops during bulk polling
        handleParsingErrors: true,
    });
 
    // 4. Execute the workflow
    try {
        console.log(`Executing prompt: ${prompt}`);
        const result = await executor.invoke({ input: prompt });
        console.log("Agent Response:", result.output);
    } catch (error: any) {
        // Explicit handling for HTTP 429 Rate Limits passed through by Truto
        if (error.response && error.response.status === 429) {
            const resetTime = error.response.headers['ratelimit-reset'];
            console.error(`Rate limit exceeded. Truto passed a 429. Reset time: ${resetTime}`);
            // Implement your system-level sleep/retry queue here based on resetTime
        } else {
            console.error("Workflow failed:", error);
        }
    }
}
 
// Example execution
const ADVANCED_MD_ACCOUNT_ID = "truto_acc_12345abcde";
runAdvancedMDAgent(
    "Fetch active care plans and recent diagnostic reports for patient pt-5542.",
    ADVANCED_MD_ACCOUNT_ID
);

The Architecture Behind the Code

  1. Dynamic Tool Fetching: The TrutoToolManager queries Truto's /integrated-account/<id>/tools endpoint. If you update a tool description in the Truto UI to give the LLM better instructions for the AdvancedMD schema, the SDK picks it up immediately. No code redeployment required.
  2. Tool Binding: Frameworks like LangChain map the JSON schemas provided by Truto directly into the LLM's native function-calling format.
  3. Agent Executor Loop: The AgentExecutor acts as the cognitive loop. If the LLM decides it needs to fetch a patient, it emits a tool call. The executor runs the underlying Truto Proxy API call, catches the JSON response, and feeds it back into the LLM's context window.
  4. Fail-Fast Safety: If the LLM attempts to send an invalid FHIR query (e.g., passing an integer when AdvancedMD requires a string ID), Truto rejects the request before it leaves your infrastructure. The executor feeds the validation error back to the LLM, which can self-correct on the next iteration.

Getting Started

Writing defensive code to handle FHIR schemas, nested Bundles, and asynchronous polling logic is not how you build a competitive AI product. By leveraging a unified tool layer, your engineering team can focus on agentic reasoning and clinical accuracy, rather than reverse-engineering the AdvancedMD API documentation.

Truto provides a dedicated /tools endpoint that auto-generates function-calling schemas for AdvancedMD and over 200 other enterprise APIs, complete with unified rate limit headers and zero-data-retention security.

Two ways to put AdvancedMD to work

Truto

For product teams

Give your agent AdvancedMD tools

Your customers connect their own AdvancedMD accounts. Your product gets one API and MCP tools for AdvancedMD, through Truto.

FAQ

Does Truto automatically retry AdvancedMD API requests if they fail due to rate limits?
No. Truto does not retry, throttle, or apply backoff on rate limit errors. When AdvancedMD returns an HTTP 429, Truto passes that error directly to the caller and normalizes the upstream rate limit information into standard IETF headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset). The caller is responsible for implementing retry and backoff logic.
Can I use frameworks other than LangChain to connect AdvancedMD to my AI agent?
Yes. Truto's /tools endpoint provides standardized JSON descriptions and schemas for all API methods. These schemas can be bound to any modern LLM framework that supports function calling, including LangGraph, CrewAI, Vercel AI SDK, and custom architectures.
How does Truto handle AdvancedMD's FHIR R4 schema complexity?
Truto maps AdvancedMD's complex FHIR endpoints into standardized Proxy APIs. By defining strict JSON schemas for the inputs and managing tasks like pagination automatically, Truto prevents the LLM from hallucinating deep nested structures or invalid FHIR resource parameters.
Does Truto support AdvancedMD's Bulk Data Export operations?
Yes. Truto provides tools to start bulk data export jobs, lookup job status, and handle the asynchronous polling required to retrieve the final NDJSON output manifests.
AdvancedMD AdvancedMDAI agent tools Get a sandbox

More from our Blog