Nirmitee.io
From HL7v2 Event to Agent Action: Building Trigger-Based Clinical Automation

From HL7v2 Event to Agent Action: Building Trigger-Based Clinical Automation

March 17, 2026
15 min read
Written by
Dinesh Thorat
Dinesh Thorat

Digital Growth Lead

Writes about healthcare technology, interoperability, and AI-driven transformation across modern care systems.

Every 2.4 seconds, a US hospital generates an HL7v2 event that could trigger a clinical AI agent. An ADT^A01 fires when a patient crosses the emergency department threshold. An ORU^R01 arrives the moment a critical lab result clears the analyzer. An ADT^A03 signals the discharge that should have started a cascade of follow-up scheduling, medication reconciliation, and care transition coordination 30 minutes earlier.

These HL7v2 events are not just data updates. They are the natural trigger points for autonomous clinical workflows. This guide covers the architecture for turning raw HL7v2 events into agent-driven clinical automation: event routing, context enrichment, agent reasoning, and clinical action — with production patterns using Mirth Connect, Apache Kafka, and purpose-built agent orchestrators.

HL7v2 event-driven agent pipeline from EHR through Kafka to clinical AI agents

The Event-Driven Advantage for Clinical AI

Most healthcare AI systems are request-response: a clinician opens a patient chart, the system runs a risk model, the result appears in a widget. This misses the 90% of clinical opportunities that happen between chart opens. A patient's lactate doubles at 2 AM. A medication order conflicts with a newly resulted allergy panel. A discharge happens without scheduling the mandatory 7-day follow-up.

Event-driven architecture flips the model. Instead of waiting for a human to ask a question, agents listen for HL7v2 events and act autonomously within defined authority boundaries. The result is clinical automation that operates at the speed of hospital operations, not the speed of chart review.

The numbers support this approach. According to Deloitte's 2026 healthcare AI survey, 82% of early adopters are prioritizing multi-agent solutions that coordinate work across care delivery and back-office operations. Event-driven agent architectures are how those multi-agent systems actually work in production.

The Six HL7v2 Events Every Agent Architecture Must Handle

HL7v2 trigger event matrix showing clinical meaning and agent opportunities

Not all HL7v2 events warrant agent attention. Here are the six that drive the most clinical value:

EventTriggerClinical SignalAgent OpportunityVolume (400-bed)
ADT^A01Patient admissionNew patient in systemRisk scoring, bed allocation, care team assembly50-80/day
ADT^A02Patient transferUnit changeHandoff checklist, receiving unit prep, medication review30-50/day
ADT^A03Patient dischargeCare transitionDischarge summary, follow-up scheduling, med reconciliation40-70/day
ADT^A08Patient updateDemographics or insurance changeInsurance verification, consent refresh, demographics sync200-400/day
ORU^R01Lab/observation resultClinical data availableCritical value alerting, trend analysis, sepsis screening500-2000/day
ORM^O01New order placedClinical decision madeDrug interaction check, duplicate order detection, cost optimization300-800/day

Combined, these six events generate 1,100-3,400 agent-actionable signals per day in a typical 400-bed hospital. Each one is a missed opportunity if your AI operates only in request-response mode.

Architecture: From HL7v2 Event to Agent Action

The end-to-end pipeline has four stages: event ingestion, event routing, context enrichment, and agent execution. Here is how each stage works.

Stage 1: Event Ingestion via Mirth Connect

Mirth Connect channel configuration for HL7v2 event-driven agent architecture

Mirth Connect (or Rhapsody, Ensemble, or any HL7 integration engine) sits at the ingestion layer. It receives HL7v2 messages via MLLP from the hospital's ADT system, lab system, and order entry system. The integration engine handles:

  • Message validation: Confirm the message parses correctly and contains required segments
  • Deduplication: Hospital systems sometimes send the same message twice. Use MSH-10 (Message Control ID) for dedup.
  • Priority classification: ORU^R01 with OBX-8=HH (critical high) gets priority routing. ADT^A08 (patient update) goes to the standard queue.
  • ACK generation: Send HL7v2 ACK back to the sending system immediately. The agent pipeline is asynchronous — the sending system should not wait for agent processing.

Stage 2: Event Routing via Apache Kafka

Event routing architecture showing content-based routing from HL7v2 events to Kafka topics

Mirth Connect publishes validated messages to Apache Kafka topics. Topic design matters for agent performance:

# Kafka topic design for clinical event routing
# Pattern: clinical.{domain}.{priority}

# ADT events
clinical.adt.standard        # ADT^A01, A02, A03, A08
clinical.adt.critical        # ADT^A01 with trauma flag

# Lab results
clinical.labs.routine        # Normal results (OBX-8 = N)
clinical.labs.abnormal       # Abnormal results (OBX-8 = H, L, A)
clinical.labs.critical       # Critical results (OBX-8 = HH, LL)

# Orders
clinical.orders.new          # ORM^O01 (new orders)
clinical.orders.cancel       # ORM^O01 with ORC-1 = CA

# Dead letter queue
clinical.dlq                 # Messages that failed processing

This topic structure enables different agent consumer groups to subscribe to exactly the events they care about. The sepsis screening agent subscribes to clinical.labs.critical and clinical.labs.abnormal. The discharge planning agent subscribes to clinical.adt.standard and filters for ADT^A03. This pattern prevents a noisy event stream from overwhelming agents that only care about specific triggers.

Stage 3: Context Enrichment

A raw HL7v2 event contains only the data from that specific transaction. An ADT^A01 tells you a patient was admitted, but your risk-scoring agent needs the patient's prior admissions, active medications, recent lab trends, and social determinant data to generate a meaningful risk score.

The context enrichment layer sits between Kafka and the agent, pulling additional data from:

  • Patient data cache: Redis or similar in-memory store with recent patient demographics, active problems, and medication lists. Updated by prior HL7v2 events.
  • FHIR server: For historical data — prior encounters, longitudinal lab trends, care plans. Yes, you use FHIR here even though the trigger was v2. The FHIR server is your longitudinal data store; v2 events are your real-time trigger stream.
  • External APIs: Insurance verification, social determinant data, medication database for interaction checking

Context enrichment typically adds 20-50ms to the pipeline but transforms a sparse event into a rich clinical context that enables meaningful agent reasoning.

Stage 4: Agent Execution

The enriched event reaches the agent orchestrator, which routes to the appropriate agent(s) based on event type and clinical context. Multiple agents can process the same event in parallel — an ADT^A01 triggers both the risk-scoring agent and the bed management agent simultaneously.

Agent outputs fall into four categories:

  1. Alerts: Page the attending physician, send a secure message, trigger a code team response
  2. Orders: Submit a lab order (with physician authorization), schedule an appointment, request a consult
  3. Documentation: Generate a discharge summary draft, create a care plan update, write a handoff note
  4. Workflow triggers: Start a discharge protocol, initiate a transfer checklist, trigger insurance pre-authorization

Real Workflow: Sepsis Detection on Critical Lab Results

Sepsis detection workflow from ORU^R01 critical lab event to clinical action

Here is a complete workflow, from HL7v2 event to clinical action, for the highest-value use case in event-driven clinical AI:

Trigger: ORU^R01 arrives with OBX results for WBC (18.2, flag HH), Lactate (4.1, flag HH), and Creatinine (2.8, flag H).

Routing: Mirth Connect classifies this as critical (two HH flags) and publishes to clinical.labs.critical.

Enrichment: The context builder pulls from Redis: patient was admitted 6 hours ago via ADT^A01, admission diagnosis is pneumonia, current medications include IV antibiotics. From the FHIR server: patient had a prior sepsis episode 8 months ago.

Agent reasoning: The sepsis screening agent calculates a qSOFA score of 3 (altered mentation from prior vitals, respiratory rate 24, systolic BP 95). Combined with the lab results and sepsis history, the risk score is 0.94.

Action dispatch:

  • Page the attending physician with structured alert: "Sepsis risk HIGH (0.94) for patient [MRN]. qSOFA 3, WBC 18.2, Lactate 4.1. Prior sepsis episode 8mo ago."
  • Recommend blood culture order (queued for physician approval per Tier 3 bounded autonomy)
  • Start fluid resuscitation protocol timer (30-minute window per Surviving Sepsis Campaign guidelines)
  • Log complete audit trail with HIPAA-compliant logging

Total latency: Event receipt to physician page: 12 seconds. Compare this to the 45-90 minute average for manual critical value notification reported in hospital quality metrics.

Real Workflow: Discharge Planning on ADT^A03

Discharge planning automation workflow triggered by ADT^A03 event

Discharge is where event-driven agents deliver the most operational value. A typical hospital discharge involves 15-20 discrete tasks, most of which can be automated or accelerated by agents:

Trigger: ADT^A03 for patient John Smith, MRN 123456, length of stay 4 days, admission diagnosis: heart failure exacerbation.

Parallel agent execution:

  • Documentation Agent: Generates discharge summary draft from encounter notes, pulls problem list, medication changes, pending lab results. Creates a structured document aligned with USCDI v3 data elements.
  • Scheduling Agent: Books a 7-day follow-up with the patient's cardiologist (or PCP if cardiology unavailable within 7 days). Checks the patient's insurance network for in-network providers. Arranges home health nurse visit for day 3.
  • Medication Agent: Reconciles inpatient medications against the patient's home medication list. Flags new medications that need patient education. Generates a patient-friendly medication schedule. Checks RxNorm mappings for generic alternatives if cost is a concern.

Output: A complete discharge packet ready for physician review in under 3 minutes, compared to the 45-minute average for manual discharge preparation. Research shows this pattern reduces discharge delay by 47 minutes per patient and decreases 30-day readmission rates by 12-18%.

Implementation: Kafka Consumer to Agent Orchestrator

# event_agent_orchestrator.py
# Kafka consumer that routes clinical events to agents

import json
from kafka import KafkaConsumer
from context_enrichment import enrich_event
from agents import SepsisAgent, DischargeAgent, BedManagementAgent

AGENT_REGISTRY = {
    "ADT": {
        "A01": [SepsisAgent, BedManagementAgent],
        "A03": [DischargeAgent],
    },
    "ORU": {
        "R01": [SepsisAgent],
    },
}

class EventOrchestrator:
    def __init__(self):
        self.consumer = KafkaConsumer(
            'clinical.adt.standard',
            'clinical.labs.critical',
            'clinical.labs.abnormal',
            bootstrap_servers='kafka:9092',
            group_id='agent-orchestrator',
            value_deserializer=lambda m: json.loads(m.decode('utf-8')),
            auto_offset_reset='latest',
            enable_auto_commit=False,
        )

    def run(self):
        for message in self.consumer:
            event = message.value
            msg_type = event.get("message_type")
            trigger = event.get("trigger_event")

            # Get agents for this event type
            agents = AGENT_REGISTRY.get(msg_type, {}).get(trigger, [])
            if not agents:
                self.consumer.commit()
                continue

            # Enrich with patient context
            enriched = enrich_event(event)

            # Execute agents in parallel
            results = []
            for agent_cls in agents:
                agent = agent_cls()
                result = agent.process(enriched)
                results.append(result)

            # Dispatch actions from all agents
            for result in results:
                self.dispatch_actions(result)

            self.consumer.commit()

    def dispatch_actions(self, result):
        for action in result.get("actions", []):
            if action["type"] == "alert":
                self.send_alert(action)
            elif action["type"] == "order":
                self.queue_order(action)
            elif action["type"] == "document":
                self.create_document(action)

Error Handling and Dead Letter Queues

Clinical event pipelines cannot silently drop messages. Every failed message must be preserved and investigated. Implement a three-tier error handling strategy:

  1. Retry with backoff: Transient failures (database timeout, API rate limit) get 3 retries with exponential backoff. Most clinical systems experience brief outages that resolve within seconds.
  2. Dead letter queue: After 3 retries, the message moves to clinical.dlq with error metadata. A dedicated monitoring process alerts the on-call team when DLQ depth exceeds thresholds.
  3. Poison pill isolation: Messages that cause agent crashes (malformed HL7v2, unexpected data types) are isolated with full stack traces. These indicate either upstream data quality issues or parser bugs that need immediate fixes.

Monitor DLQ depth as a clinical quality metric. A growing DLQ means patients are not getting agent-driven care that they should be receiving. Treat it with the same urgency as a system outage.

Performance Targets and Monitoring

Event-driven clinical agents must meet strict latency SLAs because delayed clinical actions have patient safety implications. Use OpenTelemetry to instrument every stage:

Pipeline Stagep50 Targetp95 Targetp99 Target
MLLP receipt to Kafka publish5ms15ms50ms
Kafka to agent consumer10ms30ms100ms
Context enrichment20ms50ms150ms
Agent reasoning50ms200ms500ms
Action dispatch10ms30ms100ms
End-to-end95ms325ms900ms

Build a monitoring dashboard that tracks these latencies in real time. Set SLOs based on clinical impact: a sepsis alert that takes 5 seconds instead of 12 seconds is meaningfully better for patient outcomes.

Getting Started with Nirmitee

At Nirmitee, we architect and build event-driven clinical AI pipelines that turn your existing HL7v2 message infrastructure into an intelligent automation platform. Our teams have deep expertise in Mirth Connect configuration, Kafka topic design for clinical workloads, and building AI agents that operate within bounded autonomy frameworks.

Whether you need a single-agent sepsis screening pipeline or a multi-agent discharge automation system, we can design, build, and deploy it against your existing HL7v2 infrastructure.

Talk to our clinical AI engineering team about event-driven agent architectures.

Related reading

Frequently Asked Questions

What is trigger-based clinical automation with HL7v2 events?

Trigger-based clinical automation uses HL7v2 events — admissions, discharges, lab results, new orders — as the activation points for autonomous AI agents instead of waiting for a clinician to open a chart. A US hospital generates an HL7v2 event every 2.4 seconds, and agents listen for these events and act within defined authority boundaries. The pipeline has four stages: event ingestion via an integration engine like Mirth Connect, routing through Apache Kafka, context enrichment, and agent execution.

Which HL7v2 events should clinical AI agents listen for?

Six events drive the most clinical value: ADT^A01 (admission — risk scoring, care team assembly), ADT^A02 (transfer — handoff checklists), ADT^A03 (discharge — follow-up scheduling, medication reconciliation), ADT^A08 (patient update — insurance verification), ORU^R01 (lab results — critical value alerting, sepsis screening, at 500-2,000 per day the highest volume), and ORM^O01 (new orders — drug interaction and duplicate order checks). Combined, these generate 1,100-3,400 agent-actionable signals per day in a typical 400-bed hospital.

Why is event-driven architecture better than request-response for clinical AI?

Request-response AI only runs when a clinician opens a chart, missing roughly 90% of clinical opportunities that happen between chart opens — a lactate doubling at 2 AM, a medication order conflicting with a new allergy panel, a discharge without the mandatory 7-day follow-up. Event-driven agents react at the speed of hospital operations. Per Deloitte's 2026 healthcare AI survey, 82% of early adopters are prioritizing multi-agent solutions, and event-driven architectures are how those systems work in production.

How does context enrichment work in an HL7v2 agent pipeline?

Context enrichment sits between Kafka and the agent, transforming a sparse HL7v2 event into rich clinical context. An ADT^A01 only says a patient was admitted; a risk-scoring agent also needs prior admissions, active medications, lab trends, and social determinants. The enrichment layer pulls from a Redis patient data cache updated by prior events, a FHIR server for longitudinal history, and external APIs for insurance and drug interaction data. It typically adds just 20-50ms to the pipeline.

How do you build an event-driven clinical automation pipeline with Mirth Connect and Kafka?

Use Mirth Connect at ingestion to validate messages, deduplicate on MSH-10, classify priority (critical labs route ahead of demographic updates), and send immediate ACKs so the pipeline stays asynchronous. Publish to Kafka topics structured so each agent consumer group subscribes only to relevant events — the sepsis agent to critical labs, the discharge planner to ADT^A03. Then enrich context and route to agents that emit alerts, orders, documentation drafts, or workflow triggers. Nirmitee's healthcare engineering teams build these production pipelines for hospitals.

Share