-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
944 lines (821 loc) · 36.6 KB
/
Copy pathmain.py
File metadata and controls
944 lines (821 loc) · 36.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
"""
AuthBridge MCP Server
The Prior Authorization Liberation Agent
An open-standards MCP server that automates healthcare prior authorization
using FHIR R4 patient data, structured payer criteria, and LLM-powered
clinical reasoning.
Updated: 16+ Drug Database | CMS-0057-F Compliance | FHIR Citation Trail
"""
from starlette.middleware.base import BaseHTTPMiddleware
from tools.letter_tools import generate_patient_summary as _generate_patient_summary
from tools.letter_tools import verify_pa_letter as _verify_pa_letter
from tools.letter_tools import draft_appeal_letter as _draft_appeal_letter
from tools.letter_tools import draft_pa_letter as _draft_pa_letter
from tools.criteria_tools import ingest_payer_policy as _ingest_payer_policy
from tools.criteria_tools import score_clinical_match as _score_clinical_match
from tools.criteria_tools import lookup_pa_criteria as _lookup_pa_criteria
from tools.criteria_tools import _generate_reasoning_trace
from tools.fhir_tools import fetch_patient_context as _fetch_patient_context
from tools.fhir_tools import SMART_FHIR_BASE
import os
import logging
import re
import asyncio
import json
from typing import Optional, Dict, Any, List
from mcp.server.fastmcp import FastMCP
from dotenv import load_dotenv
from collections import defaultdict
import time
_metrics = {
"total_pa_letters": 0,
"total_appeals": 0,
"total_verifications": 0,
"urgent_cases": 0,
"approve_count": 0,
"start_time": time.time()
}
def _validate_patient_id(patient_id: str) -> str:
# Allow alphanumeric, hyphens, underscores, and periods (standard FHIR ID format)
if not re.match(r'^[a-zA-Z0-9\-_.]{1,64}$', patient_id):
raise ValueError(f"Invalid patient_id format: {patient_id}")
return patient_id
def _ensure_json_serializable(obj: Any) -> Any:
"""Ensure object is JSON serializable, convert None to empty strings where appropriate"""
if obj is None:
return ""
elif isinstance(obj, dict):
return {k: _ensure_json_serializable(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [_ensure_json_serializable(item) for item in obj]
elif hasattr(obj, '__dict__'):
# Convert objects with __dict__ to their string representation
return str(obj)
else:
return obj
# Load environment variables
load_dotenv()
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s"
)
logger = logging.getLogger("authbridge")
# Import tool implementations
# ─── Initialize FastMCP Server ───────────────────────────────────────────────
mcp = FastMCP(
name="AuthBridge",
instructions="FHIR-native prior authorization agent. Reads patient FHIR records, matches payer criteria, scores evidence, and drafts complete PA letters and appeals."
)
FHIR_EXTENSION = {
"ai.promptopinion/fhir-context": {
"scopes": [
{"name": "patient/Patient.rs", "required": True},
{"name": "patient/Condition.rs", "required": True},
{"name": "patient/MedicationRequest.rs"},
{"name": "patient/MedicationStatement.rs"},
{"name": "patient/Observation.rs"},
{"name": "patient/Procedure.rs"},
{"name": "patient/AllergyIntolerance.rs"},
]
}
}
class FHIRExtensionMiddleware:
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
await self.app(scope, receive, send)
return
# Skip middleware for SSE and streaming endpoints
path = scope.get("path", "")
if path.startswith("/sse") or path.startswith("/messages/"):
await self.app(scope, receive, send)
return
async def send_wrapper(message):
# Only try to modify response body, pass through everything else
if message["type"] == "http.response.body":
body = message.get("body", b"")
try:
# Skip empty bodies and SSE data
if body and not body.startswith(b"data:"):
data = json.loads(body)
# Check if this is an initialize response
if (isinstance(data, dict) and
data.get("result", {}).get("serverInfo") is not None):
caps = data["result"].setdefault(
"capabilities", {})
caps.setdefault("extensions", {}).update(
FHIR_EXTENSION)
body = json.dumps(data).encode()
message = {**message, "body": body}
except (json.JSONDecodeError, UnicodeDecodeError, ValueError):
pass # Not JSON, send as-is
await send(message)
await self.app(scope, receive, send_wrapper)
# ─── Tool Registrations ───────────────────────────────────────────────────────
@mcp.tool()
async def fetch_patient_context(
patient_id: str,
fhir_base_url: Optional[str] = None
) -> dict:
"""
Returns:
Structured dict with patient_info, conditions, active_medications,
medication_history, observations, procedures, allergies, fetch_errors.
"""
patient_id = _validate_patient_id(patient_id)
logger.info(f"Fetching FHIR context for patient: {patient_id}")
result = await _fetch_patient_context(patient_id, fhir_base_url)
return result
@mcp.tool()
async def lookup_pa_criteria(
drug_name: str,
indication: Optional[str] = None
) -> dict:
"""
Looks up clinical PA requirements. Covers 16+ major therapeutic drugs.
"""
logger.info(f"Looking up PA criteria for: {drug_name}")
result = await _lookup_pa_criteria(drug_name, indication)
return result
@mcp.tool()
async def score_clinical_match(
patient_context: dict,
pa_criteria: dict
) -> dict:
"""
Analyzes patient record against PA criteria using clinical reasoning.
Includes CMS-0057-F urgency detection and FHIR evidence citations.
"""
logger.info(f"Scoring PA match for {pa_criteria.get('drug_name')}")
result = await _score_clinical_match(patient_context, pa_criteria)
if result.get("urgency", {}).get("is_urgent"):
_metrics["urgent_cases"] += 1
if result.get("score", 0) >= 80 or str(result.get("recommendation", "")).upper() == "APPROVE":
_metrics["approve_count"] += 1
return result
@mcp.tool()
async def draft_pa_letter(
drug_name: str,
pa_criteria: dict,
match_result: dict,
patient_context: dict,
prescriber_name: Optional[str] = None,
prescriber_npi: Optional[str] = None,
prescriber_specialty: Optional[str] = None,
prescriber_phone: Optional[str] = None,
practice_name: Optional[str] = None
) -> dict:
"""
Drafts a justification letter with urgency headers and FHIR evidence trail.
"""
logger.info(f"Drafting PA letter for: {drug_name}")
_metrics["total_pa_letters"] += 1
result = await _draft_pa_letter(
drug_name, pa_criteria, match_result, patient_context,
prescriber_name, prescriber_npi, prescriber_specialty,
prescriber_phone, practice_name
)
return result
@mcp.tool()
async def draft_appeal_letter(
drug_name: str,
denial_reason: str,
pa_criteria: dict,
patient_context: dict,
prescriber_name: Optional[str] = None,
prescriber_npi: Optional[str] = None,
prescriber_specialty: Optional[str] = None,
prescriber_phone: Optional[str] = None,
practice_name: Optional[str] = None,
denial_date: Optional[str] = None,
reference_number: Optional[str] = None
) -> dict:
"""
Drafts a formal appeal letter rebuttal with guideline citations.
"""
logger.info(f"Drafting appeal for: {drug_name}")
_metrics["total_appeals"] += 1
result = await _draft_appeal_letter(
drug_name, denial_reason, pa_criteria, patient_context,
prescriber_name, prescriber_npi, prescriber_specialty,
prescriber_phone, practice_name, denial_date, reference_number
)
return result
@mcp.tool()
async def ingest_payer_policy(
policy_text: str,
payer_name: str = "Unknown Payer"
) -> dict:
"""
Ingests unstructured payer policy text, extracts structured PA criteria using an LLM,
and dynamically updates the payer_criteria.json database.
"""
logger.info(f"Ingesting new payer policy for {payer_name}")
result = await _ingest_payer_policy(policy_text, payer_name)
return result
@mcp.tool()
async def verify_pa_letter(
letter: str,
patient_context: dict,
match_result: dict
) -> dict:
"""
Audits a generated PA letter against the FHIR evidence trail.
Flags any clinical claim that cannot be traced to a source FHIR resource.
Implements AI self-verification to prevent hallucination before physician review.
"""
_metrics["total_verifications"] += 1
return await _verify_pa_letter(letter, patient_context, match_result)
@mcp.tool()
async def generate_patient_summary(
drug_name: str,
match_result: dict,
patient_context: dict,
pa_criteria: dict
) -> dict:
"""
Generates a plain-language PA status summary for the patient.
No clinical jargon, no ICD codes. Designed for patient portal delivery.
"""
return await _generate_patient_summary(drug_name, match_result, patient_context, pa_criteria)
@mcp.tool()
async def run_full_pa_workflow(
patient_id: str,
drug_name: str,
prescriber_name: str = "",
prescriber_npi: str = "",
prescriber_specialty: str = "",
prescriber_phone: str = "",
practice_name: str = "",
payer: str = ""
) -> dict:
"""
Runs the complete AuthBridge prior authorization workflow in a single call.
Fetches FHIR patient context, looks up payer criteria, scores clinical evidence,
drafts the PA justification letter, verifies it, and generates a patient summary.
Returns the complete output including score, letter, urgency flag, and evidence trail.
Use this for the full end-to-end PA automation workflow.
Args:
patient_id: FHIR patient resource ID
drug_name: Generic or brand name of drug requiring PA
prescriber_name: Full name of prescribing physician (optional)
prescriber_npi: Prescriber NPI number (optional)
prescriber_specialty: Medical specialty (optional)
prescriber_phone: Direct phone for peer-to-peer review (optional)
practice_name: Practice or health system name (optional)
"""
try:
if not patient_id or not patient_id.strip():
return {"error": "patient_id is required", "status": "missing_input"}
if not drug_name or not drug_name.strip():
return {"error": "drug_name is required", "status": "missing_input"}
_validate_patient_id(patient_id)
logger.info(
f"Running full PA workflow: patient={patient_id}, drug={drug_name}")
# Step 1: FHIR
patient_context = await _fetch_patient_context(patient_id)
# Step 2: Criteria
pa_criteria = await _lookup_pa_criteria(drug_name, payer=payer or None)
# Step 3: Score
match_result = await _score_clinical_match(patient_context, pa_criteria)
# Step 4: Letter
letter_result = await _draft_pa_letter(
drug_name=pa_criteria.get("drug_name", drug_name),
pa_criteria=pa_criteria,
match_result=match_result,
patient_context=patient_context,
prescriber_name=prescriber_name,
prescriber_npi=prescriber_npi,
prescriber_specialty=prescriber_specialty,
prescriber_phone=prescriber_phone,
practice_name=practice_name
)
# Step 5: Verify
verify_result = {}
if letter_result.get("success") and letter_result.get("letter"):
try:
verify_result = await _verify_pa_letter(
letter=letter_result["letter"],
patient_context=patient_context,
match_result=match_result
)
except Exception as e:
verify_result = {"error": str(e)}
# Step 6: Patient summary
summary_result = {}
try:
summary_result = await _generate_patient_summary(
drug_name=pa_criteria.get("drug_name", drug_name),
match_result=match_result,
patient_context=patient_context,
pa_criteria=pa_criteria
)
except Exception as e:
summary_result = {"error": str(e)}
urgency = match_result.get("urgency", {})
_metrics["total_pa_letters"] += 1
if urgency.get("is_urgent"):
_metrics["urgent_cases"] += 1
if match_result.get("recommendation") in ("APPROVE", "LIKELY_APPROVE"):
_metrics["approve_count"] += 1
result = {
"patient": patient_context.get("patient_info", {}).get("name", "Unknown"),
"drug": pa_criteria.get("drug_name", drug_name),
"score": match_result.get("score", 0),
"recommendation": match_result.get("recommendation", "UNKNOWN"),
"evidence_strength": match_result.get("evidence_strength", "UNKNOWN"),
"is_urgent": urgency.get("is_urgent", False),
"urgency_reason": urgency.get("urgency_reason", ""),
"cms_timeline": urgency.get("cms_timeline", ""),
"matched_criteria": match_result.get("matched_criteria", []),
"missing_criteria": match_result.get("missing_criteria", []),
"step_therapy_evidence": match_result.get("step_therapy_evidence", []),
"fhir_evidence_trail": match_result.get("fhir_evidence_trail", []),
"clinical_summary": match_result.get("clinical_summary", ""),
"letter": letter_result.get("letter", ""),
"letter_word_count": letter_result.get("word_count", 0),
"verification": verify_result,
"patient_summary": summary_result.get("summary", ""),
"patient_next_step": summary_result.get("next_step", ""),
"hallucination_risk": verify_result.get("hallucination_risk", "UNKNOWN"),
"reasoning_trace": (await _generate_reasoning_trace(patient_context, pa_criteria, match_result)).get("reasoning_trace", ""),
"workflow_steps_completed": 6
}
# Ensure JSON serializable
serializable_result = _ensure_json_serializable(result)
# Test serialization
json.dumps(serializable_result)
logger.info(
f"Successfully created result for PA workflow: patient={patient_id}, drug={drug_name}")
return serializable_result
except Exception as e:
logger.error(f"Error creating PA workflow result: {e}")
return {
"error": str(e),
"success": False,
"patient": patient_context.get("patient_info", {}).get("name", "Unknown"),
"drug": pa_criteria.get("drug_name", drug_name),
"workflow_steps_completed": 0
}
@mcp.tool()
async def run_full_appeal_workflow(
patient_id: str,
drug_name: str,
denial_reason: str,
prescriber_name: str = "",
prescriber_npi: str = "",
prescriber_specialty: str = "",
prescriber_phone: str = "",
practice_name: str = "",
payer: str = ""
) -> dict:
"""
Runs the complete appeal letter workflow in a single call.
Fetches FHIR patient context, looks up payer criteria, then drafts a formal appeal.
"""
try:
if not patient_id or not patient_id.strip():
return {"error": "patient_id is required", "status": "missing_input"}
if not drug_name or not drug_name.strip():
return {"error": "drug_name is required", "status": "missing_input"}
if not denial_reason or not denial_reason.strip():
return {"error": "denial_reason is required", "status": "missing_input"}
_validate_patient_id(patient_id)
patient_context = await _fetch_patient_context(patient_id)
pa_criteria = await _lookup_pa_criteria(drug_name, payer=payer or None)
appeal_result = await _draft_appeal_letter(
drug_name=drug_name,
denial_reason=denial_reason,
patient_context=patient_context,
pa_criteria=pa_criteria,
prescriber_name=prescriber_name,
prescriber_npi=prescriber_npi,
prescriber_specialty=prescriber_specialty,
prescriber_phone=prescriber_phone,
practice_name=practice_name
)
logger.info(
f"Successfully created result for appeal workflow: patient={patient_id}, drug={drug_name}")
# Ensure JSON serializable
serializable_result = _ensure_json_serializable(appeal_result)
# Test serialization
json.dumps(serializable_result)
return serializable_result
except Exception as e:
logger.error(f"Error creating appeal workflow result: {e}")
return {
"error": str(e),
"success": False,
"patient": patient_context.get("patient_info", {}).get("name", "Unknown"),
"drug": drug_name,
"denial_reason": denial_reason,
"workflow_steps_completed": 0
}
@mcp.tool()
async def simulate_pa_lifecycle(
patient_id: str,
drug_name: str,
prescriber_name: str = "",
prescriber_npi: str = "",
prescriber_specialty: str = "",
prescriber_phone: str = "",
practice_name: str = "",
denial_reason: str = "",
payer: str = ""
) -> dict:
"""
Simulates the complete PA lifecycle from submission to final resolution.
Returns a timeline of events showing the full prior authorization journey.
"""
try:
_validate_patient_id(patient_id)
timeline = []
# Day 0: Initial PA submission
timeline.append({
"day": 0,
"event": "PA submitted",
"status": "pending",
"description": f"Prior authorization request submitted for {drug_name}"
})
# Run the full PA workflow
pa_result = await run_full_pa_workflow(
patient_id=patient_id,
drug_name=drug_name,
prescriber_name=prescriber_name,
prescriber_npi=prescriber_npi,
prescriber_specialty=prescriber_specialty,
prescriber_phone=prescriber_phone,
practice_name=practice_name,
payer=payer
)
# Day 1: Decision based on scoring
if pa_result.get("recommendation") in ["APPROVE", "LIKELY_APPROVE"]:
timeline.append({
"day": 1,
"event": "Approved - criteria met",
"status": "approved",
"description": f"PA for {drug_name} approved without delay"
})
final_outcome = "approved"
else:
timeline.append({
"day": 1,
"event": f"Denied - {pa_result.get('missing_criteria', ['criteria not met'])[0] if pa_result.get('missing_criteria') else 'criteria not met'}",
"status": "denied",
"description": f"PA for {drug_name} denied"
})
# Day 1: Appeal generation (if denied)
if denial_reason:
appeal_result = await run_full_appeal_workflow(
patient_id=patient_id,
drug_name=drug_name,
denial_reason=denial_reason,
prescriber_name=prescriber_name,
prescriber_npi=prescriber_npi,
prescriber_specialty=prescriber_specialty,
prescriber_phone=prescriber_phone,
practice_name=practice_name,
payer=payer
)
timeline.append({
"day": 1,
"event": "Appeal generated and submitted",
"status": "appealed",
"description": f"Formal appeal letter generated for {drug_name}"
})
# Day 3: Final resolution (peer review)
timeline.append({
"day": 3,
"event": "Peer review completed",
"status": "resolved",
"description": f"Peer-to-peer review conducted for {drug_name} request"
})
final_outcome = "approved_after_appeal" if denial_reason else "approved"
return {
"patient": pa_result.get("patient", "Unknown"),
"drug": drug_name,
"timeline": timeline,
"final_outcome": final_outcome,
"pa_score": pa_result.get("score", 0),
"pa_recommendation": pa_result.get("recommendation", "UNKNOWN"),
"workflow_steps_completed": len(timeline)
}
except Exception as e:
logger.error(f"Error simulating PA lifecycle: {e}")
return {"error": str(e), "success": False}
async def _single_pa_score(pid: str, drug_name: str) -> dict:
pid = _validate_patient_id(pid)
ctx = await _fetch_patient_context(pid)
crit = await _lookup_pa_criteria(drug_name)
res = await _score_clinical_match(ctx, crit)
res["patient_id"] = pid
return res
@mcp.tool()
async def batch_pa_check(patient_ids: List[str], drug_name: str) -> dict:
"""
Runs PA eligibility scoring for multiple patients simultaneously.
Returns ranked results with scores and urgency flags.
Demonstrates population-level PA workflow automation.
"""
logger.info(
f"Running batch PA check for {len(patient_ids)} patients on {drug_name}")
sem = asyncio.Semaphore(3)
async def _sem_score(pid: str):
async with sem:
# Rate limit protection for downstream APIs
await asyncio.sleep(0.5)
return await _single_pa_score(pid, drug_name)
tasks = [_sem_score(pid) for pid in patient_ids[:5]]
results = await asyncio.gather(*tasks, return_exceptions=True)
return {
"drug": drug_name,
"patients_evaluated": len(patient_ids),
"results": sorted(
[r for r in results if isinstance(r, dict)],
key=lambda x: x.get("score", 0),
reverse=True
)
}
# Keep the public MCP surface small and registry-friendly. The lower-level
# functions remain available to the Python app, but hosted MCP registries such
# as Prompt Opinion only need the single-call workflows below.
PUBLIC_MCP_TOOLS = {
"run_full_pa_workflow",
"run_full_appeal_workflow",
"simulate_pa_lifecycle",
}
for _tool_name in list(mcp._tool_manager._tools.keys()):
if _tool_name not in PUBLIC_MCP_TOOLS:
mcp.remove_tool(_tool_name)
# Patch MCP server to include FHIR extension in initialize response
def _patch_mcp_capabilities():
"""Ensure FHIR extension is included in MCP server capabilities"""
try:
# Access the internal MCP server
if hasattr(mcp, '_mcp_server'):
server = mcp._mcp_server
# Patch the create_initialization_options method
original_create_init_options = server.create_initialization_options
def patched_create_init_options(*args, **kwargs):
init_opts = original_create_init_options(*args, **kwargs)
# Add FHIR extension to capabilities
if hasattr(init_opts, 'capabilities'):
if not hasattr(init_opts.capabilities, 'extensions'):
init_opts.capabilities.extensions = {}
init_opts.capabilities.extensions.update(FHIR_EXTENSION)
return init_opts
server.create_initialization_options = patched_create_init_options
logger.info("Patched MCP server to include FHIR extension")
except Exception as e:
logger.warning(f"Could not patch MCP capabilities: {e}")
_patch_mcp_capabilities()
# ─── Server Entry Point ───────────────────────────────────────────────────────
if __name__ == "__main__":
import uvicorn
from mcp.server.sse import SseServerTransport
from starlette.applications import Starlette
from starlette.routing import Route, Mount
from starlette.responses import JSONResponse, HTMLResponse, FileResponse
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
from slowapi.middleware import SlowAPIMiddleware
limiter = Limiter(key_func=get_remote_address)
port = int(os.environ.get("PORT", 10000))
host = os.environ.get("HOST", "0.0.0.0")
logger.info("AuthBridge MCP Server starting with SMART on FHIR integration")
logger.info(f"FHIR Base: {SMART_FHIR_BASE}")
logger.info(f"Clinical tools: gpt-4o | Utility tools: gpt-4o-mini")
logger.info("Payer criteria sourced from CMS LCD database")
logger.info(f"Starting AuthBridge MCP Server on {host}:{port}")
# Initialize SSE transport
sse = SseServerTransport("/messages/")
async def health(request):
return JSONResponse({"status": "ok", "service": "authbridge", "mcp": "sse"})
async def mcp_tools_debug(request):
tools = await mcp.list_tools()
return JSONResponse({
"status": "ok",
"count": len(tools),
"tools": [
{
"name": tool.name,
"description": tool.description,
"inputSchema": tool.inputSchema,
}
for tool in tools
],
})
async def serve_index(request):
return FileResponse("index.html")
async def dashboard(request):
uptime_hours = (time.time() - _metrics["start_time"]) / 3600
# conservative 1h manual PA baseline per completed workflow
hours_saved = _metrics["total_pa_letters"] * 1
dollars_saved = hours_saved * 150 # $150/h physician time
baseline_stats = {
"avg_manual_pa_hours": 1,
"avg_physician_hourly": 150,
"treatment_abandonment_rate": 0.25,
"cms_urgent_response_hours": 72
}
# Static math for impact case
# Assuming 1 PA per day per physician, 20 working days/month
monthly_pas = 10 * 20
proj_hours_saved = monthly_pas * baseline_stats["avg_manual_pa_hours"]
proj_dollars_saved = proj_hours_saved * \
baseline_stats["avg_physician_hourly"]
html = f"""<!DOCTYPE html>
<html>
<head><title>AuthBridge — Status</title>
<style>
body {{ font-family: system-ui; background: #f8fafc; color: #1e293b; padding: 40px; }}
h1 {{ color: #0f766e; }}
.grid {{ display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin: 24px 0; }}
.card {{ background: white; border: 1px solid #e2e8f0; border-radius: 12px; padding: 24px; }}
.num {{ font-size: 36px; font-weight: 800; color: #0f766e; }}
.label {{ color: #64748b; font-size: 13px; margin-top: 4px; }}
.badge {{ display: inline-block; background: #d1fae5; color: #065f46;
padding: 4px 12px; border-radius: 99px; font-size: 12px; font-weight: 600; }}
.impact-card {{ background: #0f766e; color: white; border-radius: 12px; padding: 24px; margin-top: 32px; }}
.impact-card h2 {{ font-size: 20px; margin-top: 0; }}
.impact-card p {{ opacity: 0.9; line-height: 1.5; }}
</style>
</head>
<body>
<h1>AuthBridge <span class="badge">● Live</span></h1>
<p>FHIR-native Prior Authorization Intelligence Agent · MCP + A2A + FHIR R4</p>
<div class="grid">
<div class="card"><div class="num">{_metrics['total_pa_letters']}</div><div class="label">PA Letters Generated</div></div>
<div class="card"><div class="num">{_metrics['total_appeals']}</div><div class="label">Appeal Letters Generated</div></div>
<div class="card"><div class="num">{_metrics['urgent_cases']}</div><div class="label">Urgent Cases Flagged for Expedited Review</div></div>
<div class="card"><div class="num">{hours_saved:.0f}h</div><div class="label">Estimated Physician Hours Saved</div></div>
<div class="card"><div class="num">${dollars_saved:,.0f}</div><div class="label">Estimated Administrative Cost Saved</div></div>
<div class="card"><div class="num">{uptime_hours:.1f}h</div><div class="label">Server Uptime</div></div>
</div>
<div class="impact-card">
<h2>The Population Health Impact</h2>
<p><strong>Even before processing live calls, the static math is transformative:</strong><br>
If 10 physicians used AuthBridge daily (1 PA/day, 20 days/month), the clinic reduces manual chart review and drafting work by an estimated <strong>{proj_hours_saved:,.0f} hours</strong> and <strong>${proj_dollars_saved:,.0f}</strong> in administrative cost per month.</p>
<p style="font-size:12px;opacity:0.8;">Regulatory note: CMS-0057-F establishes FHIR prior authorization API and decision-timeframe requirements for covered items and services; the current medication PA demo uses the same interoperability pattern but remains a synthetic demonstration.</p>
</div>
<p style="color:#94a3b8;font-size:12px;margin-top:24px;">MCP endpoint: /sse · Health: /health</p>
</body>
</html>"""
return HTMLResponse(html)
class SSEHandler:
async def __call__(self, scope, receive, send):
# Correctly wire FastMCP's internal server to the SSE transport
try:
async with sse.connect_sse(
scope, receive, send
) as streams:
await mcp._mcp_server.run(
streams[0], streams[1],
mcp._mcp_server.create_initialization_options()
)
except Exception as e:
logger.error(f"SSE connection error: {e}")
handle_sse = SSEHandler()
handle_sse.__name__ = "handle_sse"
handle_sse.__module__ = __name__
@limiter.limit("50/minute")
async def run_pa_api(request):
# Request size limit 1MB
if int(request.headers.get("content-length", 0)) > 1024 * 1024:
return JSONResponse({"error": "Payload too large. Max 1MB."}, status_code=413)
try:
body = await request.json()
except:
return JSONResponse({"error": "Invalid JSON payload"}, status_code=400)
patient_id = body.get("patient_id")
drug_name = body.get("drug_name")
if not patient_id or not drug_name:
return JSONResponse({"error": "Missing patient_id or drug_name"}, status_code=400)
try:
t0 = time.time()
result = await run_full_pa_workflow(
patient_id=patient_id,
drug_name=drug_name,
prescriber_name=body.get("prescriber_name"),
prescriber_npi=body.get("prescriber_npi"),
prescriber_specialty=body.get("prescriber_specialty"),
prescriber_phone=body.get("prescriber_phone"),
practice_name=body.get("practice_name"),
payer=body.get("payer")
)
elapsed_seconds = round(time.time() - t0, 2)
evidence_count = len(result.get("fhir_evidence_trail", []))
result["elapsed_seconds"] = elapsed_seconds
result["impact_metrics"] = {
"manual_pa_minutes_baseline": 60,
"automation_seconds": elapsed_seconds,
"estimated_minutes_saved": max(0, round(60 - (elapsed_seconds / 60), 1)),
"evidence_resources": evidence_count,
"verification_status": result.get("verification", {}).get("overall_verdict", "UNKNOWN")
}
result["safety_controls"] = [
"Synthetic or de-identified data only in this demo",
"Strict patient ID validation before FHIR access",
"FHIR evidence trail attached to clinical claims",
"AI self-audit runs before clinician review",
"Clinician attestation required before submission"
]
result["regulatory_note"] = (
"CMS-0057-F supports the FHIR prior authorization direction for covered items and services; "
"this medication PA demo is a synthetic workflow prototype and does not claim live payer submission."
)
return JSONResponse(result)
except Exception as e:
logger.error(f"API Error: {e}")
return JSONResponse({"error": str(e)}, status_code=500)
@limiter.limit("50/minute")
async def run_appeal_api(request):
# Request size limit 1MB
if int(request.headers.get("content-length", 0)) > 1024 * 1024:
return JSONResponse({"error": "Payload too large. Max 1MB."}, status_code=413)
try:
body = await request.json()
except:
return JSONResponse({"error": "Invalid JSON payload"}, status_code=400)
patient_id = body.get("patient_id")
drug_name = body.get("drug_name")
denial_reason = body.get("denial_reason")
if not patient_id or not drug_name or not denial_reason:
return JSONResponse({"error": "Missing patient_id, drug_name, or denial_reason"}, status_code=400)
try:
result = await run_full_appeal_workflow(
patient_id=patient_id,
drug_name=drug_name,
denial_reason=denial_reason,
prescriber_name=body.get("prescriber_name"),
prescriber_npi=body.get("prescriber_npi"),
prescriber_specialty=body.get("prescriber_specialty"),
prescriber_phone=body.get("prescriber_phone"),
practice_name=body.get("practice_name"),
payer=body.get("payer")
)
return JSONResponse(result)
except Exception as e:
logger.error(f"Appeal API Error: {e}")
return JSONResponse({"error": str(e)}, status_code=500)
@limiter.limit("50/minute")
async def run_pa_lifecycle_api(request):
# Request size limit 1MB
if int(request.headers.get("content-length", 0)) > 1024 * 1024:
return JSONResponse({"error": "Payload too large. Max 1MB."}, status_code=413)
try:
body = await request.json()
except:
return JSONResponse({"error": "Invalid JSON payload"}, status_code=400)
patient_id = body.get("patient_id")
drug_name = body.get("drug_name")
prescriber_name = body.get("prescriber_name")
prescriber_npi = body.get("prescriber_npi")
prescriber_specialty = body.get("prescriber_specialty")
prescriber_phone = body.get("prescriber_phone")
practice_name = body.get("practice_name")
denial_reason = body.get("denial_reason")
payer = body.get("payer")
if not patient_id or not drug_name:
return JSONResponse({"error": "Missing patient_id or drug_name"}, status_code=400)
try:
result = await simulate_pa_lifecycle(
patient_id=patient_id,
drug_name=drug_name,
prescriber_name=prescriber_name,
prescriber_npi=prescriber_npi,
prescriber_specialty=prescriber_specialty,
prescriber_phone=prescriber_phone,
practice_name=practice_name,
denial_reason=denial_reason,
payer=payer
)
return JSONResponse(result)
except Exception as e:
logger.error(f"Lifecycle API Error: {e}")
return JSONResponse({"error": str(e)}, status_code=500)
starlette_app = Starlette(
routes=[
Route("/", endpoint=serve_index),
Route("/dashboard", endpoint=dashboard),
Route("/api/run-pa", endpoint=run_pa_api, methods=["POST"]),
Route("/api/run-appeal",
endpoint=run_appeal_api, methods=["POST"]),
Route("/api/run-pa-lifecycle",
endpoint=run_pa_lifecycle_api, methods=["POST"]),
Route("/health", endpoint=health),
Route("/mcp/tools", endpoint=mcp_tools_debug),
Route("/sse", endpoint=handle_sse),
Mount("/messages/", app=sse.handle_post_message),
]
)
starlette_app.state.limiter = limiter
starlette_app.add_exception_handler(
RateLimitExceeded, _rate_limit_exceeded_handler)
starlette_app.add_middleware(SlowAPIMiddleware)
starlette_app.add_middleware(FHIRExtensionMiddleware)
logger.info(f"AuthBridge MCP listening at http://{host}:{port}/sse")
uvicorn.run(starlette_app, host=host, port=port)