Skip to content

Connect Tebra to AI Agents: Sync Medical Summaries and Clinical FHIR

Nachi Raman Nachi Raman 9 min read AI & Agents
TrutoFor teams building AI agents

Give your AI agent Tebra tools.

Connecting Tebra to AI agents requires navigating complex FHIR R4 search constraints and dual APIs. This guide shows how to fetch Tebra tools programmatically and bind them to your agent framework.

In this guide

  1. 01Analyze the Tebra API Architecture
  2. 02Fetch Tools via Truto
  3. 03Bind Tools to the LLM
  4. 04Implement Rate Limit Backoff
  5. 05Execute Clinical Workflows

The guide

Learn how to connect Tebra to AI agents using Truto's tools endpoint to autonomously orchestrate FHIR R4 records, clinical summaries, and patient data.

You want to connect Tebra to an AI agent so your system can autonomously fetch patient demographics, analyze recent medical encounters, summarize clinical notes, and monitor medication requests. Here is exactly how to do it using Truto's /tools endpoint and SDK, bypassing the massive technical debt of building and maintaining a custom Electronic Health Record (EHR) integration from scratch.

Giving a Large Language Model (LLM) read and write access to clinical data requires strict adherence to schemas and error handling. If your team uses ChatGPT, check out our guide on connecting Tebra to ChatGPT, or if you are building on Anthropic's models, read our guide on connecting Tebra to Claude. For developers building custom autonomous workflows within internal apps or products, you need a programmatic way to fetch these tools and bind them directly to your agent framework.

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

The Engineering Reality of the Tebra API

Connecting an AI agent to an external system is primarily an exercise in state management and schema enforcement. When that external system is a healthcare API holding protected health information (PHI), the margin for error drops to zero. You cannot afford an agent hallucinating query parameters or misinterpreting authentication contexts.

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

The Dual API Paradigm

Tebra does not expose a single, uniform API. Instead, it offers two distinct paradigms: the FHIR R4 (US Core / USCDI v1) API and the Clinical REST API.

The FHIR R4 API requires specific logical IDs for reading resources and enforces strict parameter requirements for searching. The Clinical REST API, however, is heavily dependent on the context of the API key itself. In the Clinical REST endpoints, the patient is fixed by the API key - no patient ID is passed in the URL path. If your LLM attempts to use a standard CRUD approach, it will mix these contexts, attempting to pass FHIR IDs into Clinical REST endpoints, resulting in immediate failures.

Strict FHIR Search Requirements

Standard LLMs are trained to expect intuitive, open-ended search endpoints. When an agent wants to find a patient, it naturally attempts to send a basic payload or query string like ?query=John+Doe.

Tebra's FHIR R4 search endpoints reject this. The Patient search endpoint requires specific parameter combinations. You cannot simply hit the endpoint empty to get a list. You must send at least one of _id, identifier, name, birthdate with name, or gender with name. If the agent does not construct this exact combination, the API returns an error. Pushing this validation logic into the LLM prompt consumes valuable context window space and increases the likelihood of hallucination.

Base64 Encoded Clinical Summaries

Extracting comprehensive clinical data often relies on the C-CDA 2.1 summary document (Common Clinical Data Set). However, the API does not return this summary as clean, parsed JSON text. The content field of the document reference is Base64 encoded. If an agent calls the endpoint and attempts to summarize the raw output, it will ingest a massive block of encoded text, entirely destroying its context window and failing the task. The agent layer must know to either decode this payload or utilize a proxy layer that manages data normalization.

Unified Tools: Abstracting the Integration Layer

Rather than forcing the LLM to learn the intricacies of Tebra's US Core FHIR profiles and Clinical REST authentication quirks, a unified tool layer abstracts these endpoints into stable, descriptive JSON schemas.

Truto maps Tebra's endpoints into resources and methods, converting them into Proxy APIs. These Proxy APIs handle the query parameter processing, schema normalization, and authentication headers. By calling Truto's /integrated-account/<id>/tools endpoint, you retrieve an array of pre-configured tools with strict schemas that your LLM can safely invoke.

Factual Note on Rate Limits and Truto

When building autonomous agents, rate limiting is a critical concern because agents can loop rapidly. It is important to understand exactly how Truto handles this: Truto does not retry, throttle, or apply backoff on rate limit errors.

When Tebra's upstream API returns an HTTP 429 Too Many Requests, Truto passes that error directly back to the caller. However, Truto does normalize the upstream rate limit information into standardized headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset) per the IETF specification. The caller - your agent framework - is entirely responsible for reading these headers, pausing execution, and applying retry or backoff logic. Do not expect the proxy layer to silently absorb rate limit failures.

Hero Tools for Tebra

Truto provides a comprehensive suite of tools for Tebra, covering both the FHIR R4 and Clinical REST APIs. Below are the highest-leverage operations for building clinical AI agents. We recommend exposing only the specific tools your agent needs to accomplish its designated task to reduce the attack surface for hallucinations.

List All Tebra Patients (FHIR)

This tool enables the agent to search for patient records using the FHIR R4 standard. Because the schema enforces the required query parameters, the agent is structurally guided to provide the correct demographic combinations (like name and birthdate) to successfully execute the search.

"Find the FHIR logical ID for a male patient named Robert Smith born on 1965-04-12."

Get Single Tebra Clinical Summary

This tool retrieves the C-CDA 2.1 summary document for the patient associated with the active clinical API key. This is the single most valuable tool for preparing agents to summarize a patient's entire medical history, provided your execution environment handles the Base64 decoding of the content field.

"Retrieve the complete clinical summary document for this account and summarize the patient's active health concerns."

List All Tebra Encounters (FHIR)

This tool queries the FHIR Encounter resource to find matching visit records for a specific patient. It is essential for workflows that need to isolate notes or diagnostics to a specific date of service or visit type.

"Fetch all encounters for patient ID 84729 that occurred in the last six months and list the participating practitioners."

List All Tebra Observations (FHIR)

This tool pulls vital signs, laboratory results, and smoking status records. It returns the FHIR Observation resource, mapping specific LOINC codes and value quantities. Agents use this to track biometric trends over time.

"Pull all recent blood pressure observations for patient ID 39481 and flag any readings where the systolic pressure exceeds 140."

List All Tebra Clinical Medical Allergies

Using the Clinical REST API, this tool directly pulls the medication allergies for the API key patient. It returns structured data including the RxNorm code, allergen, reaction, and severity, which is critical for pre-visit screening tasks.

"Check the clinical medical allergies list for this patient and identify any severe reactions to penicillin or related antibiotics."

List All Tebra Medication Requests (FHIR)

This tool queries active and historical prescriptions and medication requests. It returns the dosage instructions and medication concepts, allowing the agent to perform automated medication reconciliation against newly proposed care plans.

"Retrieve all active medication requests for patient ID 99281 and list the dosage instructions for their current hypertension medications."

For the complete tool inventory and detailed parameter schemas, visit the Tebra integration page.

Workflows in Action

Building an AI agent is about chaining these tools together to accomplish complex, multi-step operations. Here is how specific personas utilize these tools in real-world scenarios.

Scenario 1: Pre-Visit Clinical Summary Prep

Medical assistants and clinicians spend significant time reviewing charts before a patient arrives. An AI agent can autonomously compile a pre-visit brief by synthesizing historical FHIR records.

"Prepare a pre-visit summary for Jane Doe, born 1980-08-15. Check her latest vital signs and active medication requests."

Execution Steps:

  1. The agent calls list_all_tebra_patients passing name="Jane Doe" and birthdate="1980-08-15" to retrieve the FHIR logical ID.
  2. Using the retrieved ID, the agent calls list_all_tebra_observations to pull recent vital signs, filtering the returned JSON for the latest weight and blood pressure.
  3. The agent calls list_all_tebra_medication_requests to pull active prescriptions.
  4. Output: The agent returns a concise, formatted markdown summary to the clinician's dashboard, highlighting the patient's current vitals and active medication list, saving the clinician 10 minutes of chart review.

Scenario 2: Chronic Care Compliance Auditing

Care coordinators need to monitor patients with chronic conditions to ensure they are keeping up with lab work and care plan directives. An agent can automate this audit across a patient cohort.

"Review the care plan for patient ID 48291. Check if they have had a diagnostic report for HbA1c in the last 90 days."

Execution Steps:

  1. The agent calls get_single_tebra_care_plan_by_id to verify the active care protocols and intents for the patient.
  2. The agent calls list_all_tebra_diagnostic_reports using the patient ID to fetch recent laboratory results.
  3. The agent analyzes the returned searchset Bundle, specifically looking for the relevant LOINC codes associated with the care plan.
  4. Output: If the diagnostic report is missing or outdated, the agent generates a draft SMS or email reminder for the care coordinator to review and send to the patient.

Building Multi-Step Workflows

To build a resilient AI agent, you must handle the orchestration of these tools in code. Standard agent loops - like those built with LangGraph or the Vercel AI SDK - execute a continuous cycle of reasoning and action.

Because Truto passes upstream HTTP 429 errors directly down to you, your agent execution loop must be aware of API rate limits. If the agent fires too many FHIR search requests in sequence, Tebra will rate limit the connection. Your code must intercept the tool execution failure, read the ratelimit-reset header, pause, and retry.

Below is a conceptual architecture diagram showing how a multi-step agent loop interacts with Truto and Tebra, including rate limit handling.

sequenceDiagram
    participant App as Your App
    participant Agent as AI Agent
    participant Truto as Truto Proxy
    participant Tebra as Tebra API

    App->>Agent: "Summarize recent encounters for patient 123"
    Agent->>Truto: GET /integrated-account/<id>/tools
    Truto-->>Agent: Returns JSON schemas for tools
    Note over Agent: Agent reasoning phase
    Agent->>Truto: Execute: list_all_tebra_encounters(patient=123)
    Truto->>Tebra: GET /Encounter?patient=123
    Tebra-->>Truto: 200 OK (Searchset Bundle)
    Truto-->>Agent: Returns Encounter JSON
    Note over Agent: Agent reasoning phase
    Agent->>Truto: Execute: get_single_tebra_observation_by_id(id=456)
    Truto->>Tebra: GET /Observation/456
    Tebra-->>Truto: 429 Too Many Requests
    Truto-->>Agent: 429 Error <br> ratelimit-reset: 10
    Note over Agent: App framework pauses for 10 seconds
    Agent->>Truto: Retry: get_single_tebra_observation_by_id(id=456)
    Truto->>Tebra: GET /Observation/456
    Tebra-->>Truto: 200 OK (Observation JSON)
    Truto-->>Agent: Returns Observation JSON
    Agent-->>App: Final clinical summary generated

Here is how you implement this programmatic fetching and binding using TypeScript and a framework like LangChain. Notice how we utilize the /tools endpoint to automatically bind the Tebra resources to the model.

import { ChatOpenAI } from "@langchain/openai";
import { AgentExecutor, createToolCallingAgent } from "langchain/agents";
import { ChatPromptTemplate } from "@langchain/core/prompts";
 
// 1. Fetch tools dynamically from Truto's proxy layer
async function fetchTebraTools(accountId: string, trutoApiKey: string) {
  const response = await fetch(`https://api.truto.one/integrated-account/${accountId}/tools`, {
    headers: {
      Authorization: `Bearer ${trutoApiKey}`
    }
  });
  
  if (!response.ok) {
    throw new Error("Failed to fetch Tebra tools");
  }
  
  const toolsData = await response.json();
  // In a production environment, you would map these JSON schemas 
  // into the specific Tool classes required by your framework (e.g., DynamicTool).
  return toolsData.tools;
}
 
async function runClinicalAgent(accountId: string, trutoApiKey: string) {
  // Fetch the normalized Tebra tools
  const tebraTools = await fetchTebraTools(accountId, trutoApiKey);
  
  const llm = new ChatOpenAI({
    modelName: "gpt-4-turbo-preview",
    temperature: 0,
  });
 
  // 2. Bind the tools to the LLM
  const llmWithTools = llm.bindTools(tebraTools);
 
  const prompt = ChatPromptTemplate.fromMessages([
    ["system", "You are a clinical assistant. Use the provided tools to query patient data safely. If a tool fails due to a rate limit (HTTP 429), you must inform the system to wait."],
    ["placeholder", "{chat_history}"],
    ["human", "{input}"],
    ["placeholder", "{agent_scratchpad}"],
  ]);
 
  const agent = createToolCallingAgent({
    llm: llmWithTools,
    tools: tebraTools,
    prompt,
  });
 
  const agentExecutor = new AgentExecutor({
    agent,
    tools: tebraTools,
    // Framework-level configuration for retries should be implemented here
    // to catch Truto's direct passthrough of 429 errors.
  });
 
  // 3. Execute the workflow
  const result = await agentExecutor.invoke({
    input: "Check the active medication requests for patient ID 88392 and summarize the current dosages.",
  });
 
  console.log(result.output);
}

By relying on the unified tool definitions, your agent code remains entirely decoupled from the underlying complexities of the FHIR specification. If Tebra updates their API, or if you decide to connect a different EHR system tomorrow, the agent logic remains intact. You only interact with the normalized proxy endpoints.

Moving to Production

Connecting an AI agent to an EHR like Tebra is a high-stakes engineering task. Writing point-to-point integration code forces your team to manage complex FHIR R4 search semantics, handle dual-API authentication contexts, and write custom schemas for the LLM to understand.

By leveraging a unified integration architecture, you collapse these complexities into a set of stable, predictable JSON schemas that agents natively understand. You retain full control over workflow orchestration, prompt engineering, and rate limit backoff strategies, without drowning your engineering team in healthcare integration boilerplate.

Two ways to put Tebra to work

Truto

For product teams

Give your agent Tebra tools

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

FAQ

How does Truto handle Tebra API rate limits?
Truto does not retry, throttle, or apply backoff on rate limit errors. When Tebra returns an HTTP 429, Truto passes that error directly to the caller, normalizing the rate limit information into standard headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset). Your application or agent framework is responsible for handling the retry and backoff logic.
What is the difference between Tebra's FHIR APIs and Clinical REST APIs?
Tebra exposes two different API paradigms. The FHIR R4 APIs allow you to search and read specific resources (like Patient or Encounter) using standard FHIR logical IDs. The Clinical REST APIs operate under a context fixed to the user who owns the API key, meaning no patient ID is passed in the request path.
Can I use these Tebra tools with any AI framework?
Yes. Truto's /tools endpoint returns standard JSON schemas describing the proxy API endpoints. These can be bound to any modern LLM framework, including LangChain, LangGraph, CrewAI, or the Vercel AI SDK, using standard tool-calling methods like .bindTools().
Tebra TebraAI agent tools Get a sandbox

More from our Blog

PII Redaction for MCP: Stop Leaking SaaS Data to LLMs
Security/Guides/AI & Agents

PII Redaction for MCP: Stop Leaking SaaS Data to LLMs

Architectural patterns for redacting PII and standardizing ATS data from Greenhouse, Lever, and Workday before it reaches LLMs via MCP - with code examples, field-level decision matrices, and compliance checklists.

Yuvraj Muley Yuvraj Muley · · 33 min read