Skip to content
ankitlade12Public

About

LoopGuard — A2A/MCP healthcare agent that closes the loop on AI-generated clinical recommendations

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

LoopGuard — Healthcare Workflow Safety Layer

Python 3.12+ FastAPI MCP Anthropic Claude FHIR R4 SHARP-on-MCP Render License: MIT

Healthcare agents shouldn't just make recommendations. They should make sure someone owns the next step. LoopGuard does not generate clinical advice. It closes the loop after someone else does.

LoopGuard is an A2A/MCP healthcare agent that turns every AI-generated clinical recommendation into a trackable, FHIR-grounded Handoff Contract, monitors FHIR resources to verify whether the loop actually closed, and escalates when a patient is at risk of falling through the cracks. It is the workflow-safety primitive other healthcare agents call after they create a recommendation.

Quick Highlights

  • Three primitives only — Handoff Contract, Closure Check, Audit Receipt. Not a diagnosis engine, not a chatbot, not another note generator.
  • Seven MCP tools — published on the Prompt Opinion Marketplace; every other healthcare agent on the platform can compose with them.
  • Hybrid AI + deterministic rules — Claude extracts the obligation from free-text; transparent rules over FHIR resources verify closure.
  • Live SMART-on-FHIR path wired — when SHARP context (X-FHIR-Server-URL + X-FHIR-Access-Token + X-Patient-ID) is present, LoopGuard fetches Patient/{id}/$everything via httpx; otherwise falls back to synthetic bundles. Same closure rules either way.
  • Three patient scenarios end-to-end — lung nodule (Appointment-based closure), hyperkalemia (Task-based closure), postpartum HTN (Communication-based closure). All with full red→green bundles.
  • SHARP-on-MCP compliant — ai.promptopinion/fhir-context capability declared at initialize with 8 SMART scopes, patient/Patient.rs required.
  • Synthetic data only for the demo — every fixture carries the FHIR v3-ActReason / HTEST tag. Zero real PHI in code, fixtures, or video.
  • 120 tests, mypy strict, ruff clean — including 11 dedicated tests for the live FHIR path using httpx.MockTransport.

Live Deployment

Service URL Notes
MCP endpoint https://loopguard.onrender.com/mcp Streamable HTTP, requires X-LoopGuard-API-Key header
Health check https://loopguard.onrender.com/health Returns {"status":"ok","version":"0.1.0","env":"prod","mcp_auth":"configured"}
Marketplace listing Prompt Opinion Marketplace Studio → MCP Servers Status: Published; auto-introspected to 7 tools

Render free tier; auto-deploys on push to main. Sleeps after ~15 min idle (cold start ~30–60s), so pre-warm with a curl /health before any latency-sensitive use.

Architecture Overview

High-Level Workflow

graph LR
    subgraph "STEP 1: RECOMMENDATION ARRIVES"
        UA["Upstream agent<br/>(Radiology / Discharge /<br/>Lab Review / etc.)"] --> REC["Free-text recommendation<br/>+ patient_id<br/>+ evidence refs"]
    end

    subgraph "STEP 2: OBLIGATION EXTRACTION"
        REC --> EX["Claude messages.parse()<br/>structured output"]
        EX --> HC["HandoffContract<br/>(Pydantic-validated)"]
        HC --> ST["Contract Store<br/>+ history event"]
    end

    subgraph "STEP 3: CLOSURE CHECK"
        ST --> RB["resolve_bundle()<br/>SHARP ctx? live FHIR<br/>else synthetic"]
        RB --> CC["Deterministic Checker<br/>walks FHIR resources<br/>resolves closure rules"]
        CC --> CR["ClosureCheckResult<br/>loop_status<br/>missing_events<br/>risk_level"]
    end

    subgraph "STEP 4: AUDIT + ESCALATE"
        CR --> D{Closed?}
        D -->|No, overdue| ESC["escalate_open_loop<br/>route to Care Coordinator"]
        D -->|Yes| AR["AuditReceipt<br/>append-only<br/>actual_closure recorded"]
        ESC --> AR
    end

    style UA fill:#e1f5ff
    style HC fill:#fff4e1
    style CR fill:#fce4ec
    style AR fill:#c8e6c9
    style ESC fill:#ffcdd2
Loading

System Architecture

graph TB
    PO["PROMPT OPINION LAUNCHPAD<br/>LoopGuard Demo Agent<br/>(LLM picks tools from plain English)"]

    subgraph "MCP TOOL LAYER (FastMCP)"
        T1["create_handoff_contract"]
        T2["check_loop_status"]
        T3["find_missing_closure_events"]
        T4["escalate_open_loop"]
        T5["generate_loop_audit_receipt"]
        T6["list_open_loops_for_patient"]
        T7["get_contract_history"]
    end

    subgraph "API LAYER (FastAPI)"
        MW["McpAuthMiddleware<br/>X-LoopGuard-API-Key<br/>+ SHARP X-FHIR-* parser"]
        SC["SHARP capability<br/>injected at initialize"]
        RR["REST routes<br/>contracts / status /<br/>escalate / audit_receipt"]
    end

    subgraph "CORE SERVICES"
        EX["Obligation Extractor<br/>Claude messages.parse()"]
        CK["Closure Checker<br/>deterministic FHIR rules"]
        AU["Audit Receipt Builder<br/>append-only"]
        CS["Contract Store<br/>(in-memory + history)"]
    end

    subgraph "FHIR LAYER"
        RS["resolve_bundle()<br/>dispatcher"]
        SY["FHIRBundleReader<br/>synthetic_bundles/*.json<br/>HTEST-tagged"]
        LV["LiveFHIRClient<br/>httpx GET<br/>Patient/{id}/$everything"]
    end

    EXT["ANTHROPIC API<br/>claude-sonnet-4-6"]
    EHR["External FHIR server<br/>(Epic / Cerner / SMART<br/>sandbox — opt-in via SHARP)"]

    PO -->|Streamable HTTP /mcp| MW
    MW --> SC
    MW --> T1
    MW --> T2
    MW --> T3
    MW --> T4
    MW --> T5
    MW --> T6
    MW --> T7

    T1 --> EX
    T2 --> CK
    T3 --> CK
    T4 --> CS
    T5 --> AU
    T6 --> CS
    T7 --> CS

    EX --> EXT
    EX --> CS
    CK --> RS
    CK --> CS
    AU --> CS

    RS --> SY
    RS --> LV
    LV -.->|when SHARP ctx present| EHR

    RR -.->|same business logic| EX
    RR -.-> CK
    RR -.-> AU

    style PO fill:#e1f5ff,stroke:#0288d1,stroke-width:2px
    style EX fill:#fff4e1,stroke:#f57c00,stroke-width:2px
    style CK fill:#c8e6c9,stroke:#388e3c,stroke-width:2px
    style AU fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px
    style EXT fill:#ffe0b2,stroke:#e64a19,stroke-width:2px
    style EHR fill:#ffe0b2,stroke:#e64a19,stroke-width:2px
Loading

Tech Stack

Layer Technology Purpose
Runtime Python 3.12 (async) All FastAPI handlers + I/O are async def
Web framework FastAPI 0.115+ Parent ASGI app; serves both REST routes and MCP at /mcp
MCP server mcp Python SDK 1.27 (FastMCP) Streamable HTTP transport; 7 LoopGuard tools
AI engine Anthropic Claude (messages.parse()) Pydantic-validated structured output for obligation extraction
Validation Pydantic v2 + pydantic-settings Every boundary contract (HTTP / LLM / FHIR / store)
FHIR (synthetic) JSON fixtures in backend/fhir/synthetic_bundles/ HTEST-tagged R4 Bundles
FHIR (live) httpx async client Patient/{id}/$everything via SHARP-injected bearer
Storage In-memory dict + history list Demo-scoped; production target is Postgres
Lint / Type ruff + ruff-format + mypy strict Pre-commit gated on every commit
Testing pytest + pytest-asyncio (120 tests) unit / integration / contract tiers
Deploy Render free tier (auto-deploy from main) One web service serves REST + MCP
Package mgmt uv Reproducible installs from pyproject.toml

The Problem

Healthcare's number-one source of preventable harm isn't a wrong diagnosis — it's the moment after a doctor says "follow up on this in two weeks" and nobody actually does. The data is brutal:

  • 7–8% of abnormal cancer-screening results have inadequate follow-up; up to 36% for some test types.
  • "Failure to follow up on diagnostic findings" is the #1 most common allegation in primary-care malpractice claims.
  • The Joint Commission identifies "communication breakdowns" and "failure to follow up on diagnostic results" as leading causes of preventable patient harm.
  • 25–30% of patients discharged from EDs with abnormal findings have no documented follow-up plan booked before they leave.

When a doctor says "needs cardiology follow-up in 7 days," that follow-up actually happens about 75% of the time. The other 25% — the open loops — are where patients sometimes die. AI agents are about to make this dramatically worse, generating clinical recommendations at 10× the volume while human capacity to track them stays constant.

The Solution

LoopGuard is the workflow-safety layer that sits between recommendation and closure:

  • Obligations are quantified as typed Handoff Contracts with closure conditions, owner, due date, and escalation plan
  • Closure is verified deterministically against FHIR resources — no LLM judgment in the safety path
  • The audit receipt is visible — every receipt records what was recommended, what was checked, what was missing, and what was escalated, even before the loop closes
  • Three independent safety checkpoints — at extraction (Pydantic validates structure), at closure check (rules walk FHIR), and at audit (append-only history)

The Mathematical Core

Risk-Level Scoring (transparent rules, no black-box model)

Risk level is a deterministic function of loop_status, days_open, missing FHIR resource count, and clinical-trigger type:

Input Contribution
loop_status == "closed" risk_level = low (terminal)
clinical_trigger.type ∈ {abnormal_imaging_result, critical_lab_value, postpartum_follow_up} +1 to high-risk weight
days_overdue > 0 +1 to high-risk weight
Missing Appointment for specialty obligation +1 to high-risk weight
Missing Communication for patient outreach obligation +1 to high-risk weight

The mapping is: weight ≥ 2 → high; weight 1 → medium; weight 0 → low.

Closure-Check Decision Matrix

Closure conditions resolved Days vs. due loop_status
All resolved (Appointment / Task / Communication present + matching) any closed
Some resolved, within due window days_open ≤ due_in_days open_pending
Not all resolved, past due window days_open > due_in_days open_risk

Audit Receipt Decision

loop_status Escalated? Receipt records
closed (any) actual_closure ∈ FHIR resource refs that satisfied each condition
open_risk / open_pending yes escalation_history[], escalated: true, no actual_closure
open_risk / open_pending no missing_events[], status preserved, no actual_closure

Features

Seven MCP Tools

# Tool Purpose
1 create_handoff_contract Convert free-text recommendation → typed HandoffContract via Claude messages.parse()
2 check_loop_status Walk FHIR resources, resolve closure conditions, return loop_status + transparent risk score
3 find_missing_closure_events Thin gap-analysis slice — just loop_status + missing_events + risk_level
4 escalate_open_loop Route unresolved obligation to a downstream agent / human role; mark contract escalated
5 generate_loop_audit_receipt Emit defensible record: source agent, trigger evidence, expected closure, actual closure, escalation flag
6 list_open_loops_for_patient Patient-scoped queue — every contract whose latest status is not closed
7 get_contract_history Full chain-of-custody — created → every status_checked → escalated, oldest first

Three Patient Scenarios (full red→green)

Scenario Patient Trigger Closure shape
Suspicious lung nodule synthetic-patient-123 abnormal_imaging_result Appointment + Communication
Critical hyperkalemia synthetic-patient-456 critical_lab_value Task + Communication
Postpartum hypertension synthetic-patient-987 postpartum_follow_up Appointment + Communication

Each scenario has paired *_open and *_closed FHIR bundles; the same deterministic checker resolves all three closure shapes.

Defense in Depth — Three Safety Checkpoints

Checkpoint What it catches
At extraction Pydantic v2 with extra="forbid" rejects unstructured / hallucinated obligations; retry with stricter framing on first invalid JSON
At closure check Substring matches don't count — Appointment.specialty == "pulmonology" AND Appointment.status == "booked" both required
At audit receipt Append-only _history event log per contract: created → status_checked (with loop_status) → escalated

Quick Start

Prerequisites

  • Python 3.12 + uv
  • An Anthropic API key (or leave blank for offline tests via MockLLMClient)

Installation

# Clone and install
git clone https://github.com/ankitlade12/loopguard.git
cd loopguard
uv sync --extra dev
uv run pre-commit install

# Configure environment
cp .env.example .env
# Edit .env and set ANTHROPIC_API_KEY (and LOOPGUARD_API_KEY for the MCP auth gate)

Run Locally

# FastAPI + MCP server on :8000
uv run uvicorn backend.app:app --reload

# Smoke-test
curl http://localhost:8000/health
# {"status":"ok","version":"0.1.0","env":"dev","mcp_auth":"configured"}

The MCP endpoint is at http://localhost:8000/mcp (Streamable HTTP).

Reproducible Testing

# Full suite (120 tests, ~150ms)
uv run pytest -q

# Just the unit tier
uv run pytest -m unit -q

# Lint + type-check (matches the pre-commit gate)
uv run ruff check backend/ && uv run ruff format --check backend/ && uv run mypy backend/

# Smoke-test the live deployed server
curl https://loopguard.onrender.com/health

# Stress-test the SHARP capability declaration
curl -sL -X POST https://loopguard.onrender.com/mcp \
  -H "Content-Type: application/json" \
  -H "Accept: application/json,text/event-stream" \
  -H "X-LoopGuard-API-Key: $LOOPGUARD_API_KEY" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"check","version":"1.0"}}}'

# Wipe the in-memory contract store between demo rehearsals (idempotent, API-key gated)
curl -X POST https://loopguard.onrender.com/admin/reset \
  -H "X-LoopGuard-API-Key: $LOOPGUARD_API_KEY"

Demo Flow

The canonical demo runs as a 7-beat dialogue inside the Prompt Opinion Launchpad, paste each prompt in turn into the LoopGuard Demo Agent. Prompts are deliberately plain English — the LLM picks the right MCP tool. We never name an MCP tool in the prompt; the LLM routes to one of the seven based on intent.

1. Patient synthetic-patient-123 had a CT chest today showing a suspicious pulmonary
   nodule. Radiology recommends pulmonology follow-up within 14 days. Track this.
   Source agent: Radiology Follow-Up Agent.
   Evidence: DiagnosticReport/ct-chest-001.

2. It's been 21 days since we logged the lung-nodule case. Has anything actually
   happened? Check against the open bundle.

3. Show me everything still outstanding for synthetic-patient-123.

4. Hand off the lung-nodule case to a care coordinator. High priority.

5. The pulmonology appointment got booked and the patient was contacted.
   Re-check the lung-nodule loop against the closed bundle.

6. Walk me through everything that's happened with the lung-nodule contract —
   the full chain of custody.

7. I need the formal audit record for the lung-nodule contract.

The visual punch is at step 5 — the same deterministic checker, same code path, same FHIR-bundle structure, only the bundle contents differ between open and closed. The loop_status flips red → green, risk drops to low, the audit receipt now carries actual_closure: "Appointment/pulm-appointment-001".

Tool-Call Sequence

sequenceDiagram
    participant User
    participant DemoAgent as LoopGuard Demo Agent
    participant LoopGuard as LoopGuard MCP Server
    participant Claude

    User->>DemoAgent: "Patient synthetic-patient-123<br/>had a CT chest..."
    DemoAgent->>LoopGuard: create_handoff_contract
    LoopGuard->>Claude: messages.parse() with HandoffContract schema
    Claude-->>LoopGuard: { obligation, closure_conditions, escalation }
    LoopGuard-->>DemoAgent: HandoffContract (contract_id)

    User->>DemoAgent: "21 days later — has anything happened?"
    DemoAgent->>LoopGuard: check_loop_status(bundle="open", days=21)
    LoopGuard->>LoopGuard: walk FHIR, resolve closure rules
    LoopGuard-->>DemoAgent: loop_status: open_risk, risk: high

    User->>DemoAgent: "Show me everything outstanding..."
    DemoAgent->>LoopGuard: list_open_loops_for_patient
    LoopGuard-->>DemoAgent: [contract_id]

    User->>DemoAgent: "Hand off to care coordinator..."
    DemoAgent->>LoopGuard: escalate_open_loop
    LoopGuard-->>DemoAgent: escalation_status: sent

    User->>DemoAgent: "Re-check against closed bundle"
    DemoAgent->>LoopGuard: check_loop_status(bundle="closed")
    LoopGuard-->>DemoAgent: loop_status: closed, risk: low ✅

    User->>DemoAgent: "Walk me through the history..."
    DemoAgent->>LoopGuard: get_contract_history
    LoopGuard-->>DemoAgent: [created, status_checked,<br/>escalated, status_checked]

    User->>DemoAgent: "I need the audit record"
    DemoAgent->>LoopGuard: generate_loop_audit_receipt
    LoopGuard-->>DemoAgent: { status: closed,<br/>escalated: true,<br/>actual_closure: ... }
Loading

Project Structure

loopguard/
├── backend/
│   ├── app.py                          # FastAPI app + lifespan + MCP mount
│   ├── config.py                       # pydantic-settings
│   ├── routes/
│   │   ├── contracts.py                # POST /api/contracts, GET /api/contracts/{id}
│   │   ├── status.py                   # GET /api/contracts/{id}/status
│   │   ├── escalate.py                 # POST /api/contracts/{id}/escalate
│   │   ├── audit_receipt.py            # GET /api/contracts/{id}/audit-receipt
│   │   └── admin.py                    # POST /admin/reset — wipe demo state between runs
│   ├── mcp/
│   │   ├── server.py                   # FastMCP server with 7 tools
│   │   ├── auth.py                     # API-key middleware
│   │   ├── fhir_headers.py             # SHARP X-FHIR-* parser → ContextVar
│   │   └── sharp_capability.py         # ai.promptopinion/fhir-context advert
│   ├── contracts/
│   │   ├── schema.py                   # HandoffContract, ClosureCheckResult, AuditReceipt
│   │   ├── store.py                    # in-memory store + per-contract history
│   │   ├── extractor.py                # Claude messages.parse() obligation extractor
│   │   ├── checker.py                  # deterministic FHIR closure rules + risk scoring
│   │   └── audit_receipt.py            # append-only receipt builder
│   ├── fhir/
│   │   ├── client.py                   # FHIRBundleReader + resolve_bundle dispatcher
│   │   ├── live_client.py              # LiveFHIRClient (httpx + SHARP bearer)
│   │   ├── resources.py                # typed Pydantic shapes for the FHIR subset
│   │   └── synthetic_bundles/          # HTEST-tagged R4 Bundles
│   ├── agents/                         # reserved for Phase 6 A2A (not yet wired)
│   └── tests/                          # 120 tests across unit / integration / contract
├── scripts/                            # bundle loaders + type-gen utilities
├── pyproject.toml                      # Python deps + tool config
├── Makefile                            # setup / test / lint / dev
├── render.yaml                         # Render service config
├── Dockerfile                          # Render build target
└── .env.example                        # ANTHROPIC_API_KEY, LOOPGUARD_API_KEY, etc.

Configuration

# .env file
ANTHROPIC_API_KEY=                                # Required for live Claude path
LLM_MODEL=claude-sonnet-4-6                       # Default model
LOOPGUARD_API_KEY=                                # Required for /mcp auth gate
LOOPGUARD_API_KEY_HEADER_NAME=X-LoopGuard-API-Key # Custom header for the MCP auth
LOG_LEVEL=INFO
LOOPGUARD_ENV=dev                                 # dev | prod

In production (Render), ANTHROPIC_API_KEY and LOOPGUARD_API_KEY are configured as environment variables on the service — never baked into the image. The Render service auto-deploys on every push to main.

Hackathon Innovation

Why LoopGuard Stands Out

  1. Workflow safety, not generation. Most healthcare AI hackathon entries generate something — summaries, prior-auths, triage advice. LoopGuard sits between a recommendation and its closure. We're the audit layer the others can compose with.

  2. Hybrid AI + deterministic rules. The LLM does what regex can't (categorical mapping from English to FHIR-grounded structure). The closure checker does what an LLM shouldn't (deterministic, defensible reads of FHIR resources with a transparent risk-scoring table). The AI never decides whether a loop is open.

  3. Visible audit receipt. Every receipt records what was recommended, what was checked, what was missing, and what was escalated, even before the loop closes. That makes the workflow-safety claim verifiable post-hoc — a property most LLM-only systems can't offer.

  4. Live SMART-on-FHIR ready in code. Synthetic data for the demo (per the no-PHI rule), but the LiveFHIRClient is wired and unit-tested. Real-EHR deployments come online with zero LoopGuard code changes — only environment configuration.

  5. Complementary, not competitive. AlarmIQ generates ICU alarm triage. TinyDx generates rare-disease differentials. Pharmacovigil generates adverse-event reports. None of them verify what happens after their recommendation. LoopGuard is the horizontal MCP primitive that makes every other healthcare AI agent on Prompt Opinion accountable through one integration.

The Gap We Fill

Capability Typical clinical AI agent LoopGuard
Output A recommendation A trackable obligation + closure verification
Decision authority Yes (clinical judgment) None (workflow accountability only)
Persistence Stateless reply Append-only audit history per contract
FHIR integration Optional context Closure conditions defined as FHIR resource shapes
Failure mode Silent / not surfaced Visible: open_risk + missing_events[] + escalation

Future Enhancements

  • Postgres + audit-log retention — the in-memory store is hackathon-scoped; Pydantic models are serialization-ready, so this is substitution, not rewrite
  • A2A agent chain — Radiology Follow-Up Agent → LoopGuard Agent → Scheduler Agent → Care Coordinator Agent → Patient Communication Agent. The MCP tool layer underneath stays unchanged.
  • Real escalation routing — Epic InBasket / Slack / Teams / pager / SMS adapters; the escalate_open_loop tool's interface stays the same, only the routing target changes
  • More obligation patterns — chronic disease management, medication reconciliation, post-procedural monitoring. Mostly prompt engineering + golden-test additions on top of the existing extractor.
  • HIPAA + compliance infrastructure — vendor BAA, encryption-at-rest, role-based access, audit-log retention. Standard healthcare-SaaS work that doesn't change the LoopGuard primitive.

License

MIT — chosen for maximum permissiveness; the Agents Assemble hackathon does not mandate a specific license.


Built for the Agents Assemble hackathon — The Healthcare AI Endgame (Devpost, deadline 2026-05-11). Submission path: MCP Server published to the Prompt Opinion Marketplace.

"LoopGuard closes the gap between AI recommendation and real clinical action."

About

LoopGuard — A2A/MCP healthcare agent that closes the loop on AI-generated clinical recommendations

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages