Spaces:
Sleeping
Sleeping
Compliance: Modularized MCP Discovery/SSE/Invoke for platform stability
Browse files- backend/main.py +72 -153
backend/main.py
CHANGED
|
@@ -4,7 +4,7 @@ from pathlib import Path
|
|
| 4 |
from typing import Any, Dict, List, Optional
|
| 5 |
from datetime import datetime
|
| 6 |
|
| 7 |
-
# Load .env
|
| 8 |
_env_file = Path(__file__).resolve().parent.parent / ".env"
|
| 9 |
if _env_file.exists():
|
| 10 |
for _line in _env_file.read_text().splitlines():
|
|
@@ -19,12 +19,6 @@ from fastapi.responses import JSONResponse, FileResponse, StreamingResponse
|
|
| 19 |
from fastapi.staticfiles import StaticFiles
|
| 20 |
import requests as _requests
|
| 21 |
|
| 22 |
-
# Build-time imports
|
| 23 |
-
try:
|
| 24 |
-
from codeblue_context import build_emergency_snapshot
|
| 25 |
-
except ImportError:
|
| 26 |
-
def build_emergency_snapshot(text): return {"raw_text": text}
|
| 27 |
-
|
| 28 |
_KEY = os.getenv("gemini_api_key", "") or os.getenv("GEMINI_API_KEY", "")
|
| 29 |
BASE_DIR = Path(__file__).resolve().parent
|
| 30 |
|
|
@@ -33,201 +27,126 @@ def _load_patients() -> List[Dict[str, Any]]:
|
|
| 33 |
if p.exists():
|
| 34 |
try:
|
| 35 |
data = json.loads(p.read_text())
|
| 36 |
-
if isinstance(data, dict)
|
| 37 |
-
|
| 38 |
-
return data if isinstance(data, list) else []
|
| 39 |
-
except:
|
| 40 |
-
return []
|
| 41 |
return []
|
| 42 |
|
| 43 |
PATIENTS: List[Dict[str, Any]] = _load_patients()
|
| 44 |
-
|
| 45 |
app = FastAPI(title="CodeBlue Context API", version="3.1.2")
|
| 46 |
|
| 47 |
-
# Global error handler
|
| 48 |
@app.exception_handler(Exception)
|
| 49 |
async def global_exception_handler(request: Request, exc: Exception):
|
| 50 |
import traceback
|
| 51 |
-
|
| 52 |
-
traceback.print_exc()
|
| 53 |
-
return JSONResponse(
|
| 54 |
-
status_code=500,
|
| 55 |
-
content={"detail": str(exc), "traceback": traceback.format_exc()}
|
| 56 |
-
)
|
| 57 |
|
| 58 |
-
app.add_middleware(CORSMiddleware, allow_origins=["*"],
|
| 59 |
-
allow_credentials=True, allow_methods=["*"], allow_headers=["*"])
|
| 60 |
|
| 61 |
# ββ Gemini helper βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 62 |
def _gemini(prompt: str, retries: int = 4, override_key: str = None) -> Optional[Dict]:
|
| 63 |
key = (override_key or _KEY).strip()
|
| 64 |
if not key: return None
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
"contents": [{"parts": [{"text": prompt}]}],
|
| 68 |
-
"generationConfig": {"temperature": 0.1, "maxOutputTokens": 2048}
|
| 69 |
-
}
|
| 70 |
-
|
| 71 |
-
models = ["gemini-2.5-flash-lite"]
|
| 72 |
-
|
| 73 |
-
for model in models:
|
| 74 |
-
last_error = ""
|
| 75 |
for attempt in range(retries):
|
| 76 |
try:
|
| 77 |
url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={key}"
|
| 78 |
resp = _requests.post(url, json=payload, timeout=25)
|
| 79 |
-
if resp.status_code ==
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
if "candidates" not in data or not data["candidates"]:
|
| 87 |
-
last_error = "Safety refusal"
|
| 88 |
-
continue
|
| 89 |
-
text = data["candidates"][0]["content"]["parts"][0]["text"].strip()
|
| 90 |
-
text = re.sub(r"^```(?:json)?\s*", "", text)
|
| 91 |
-
text = re.sub(r"\s*```$", "", text)
|
| 92 |
-
try:
|
| 93 |
-
return json.loads(text)
|
| 94 |
-
except:
|
| 95 |
-
match = re.search(r"\{.*\}", text, re.DOTALL)
|
| 96 |
-
if match: return json.loads(match.group(0))
|
| 97 |
-
raise
|
| 98 |
-
except Exception as e:
|
| 99 |
-
last_error = str(e)
|
| 100 |
time.sleep(1)
|
| 101 |
-
|
| 102 |
return None
|
| 103 |
|
| 104 |
# ββ Agents ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
-
def
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
return r or {"critical_risks": [], "severity_label": "URGENT", "chief_complaint": "Stabilize."}
|
| 110 |
-
|
| 111 |
-
def agent_contraindication(record: Dict, triage: Dict = None, override_key: str = None) -> Dict:
|
| 112 |
-
prompt = f"ED Safety. PATIENT: {json.dumps(record)}\nReturn ONLY JSON: {{ 'treatment_verdict': 'SAFE|CAUTION|CONTRAINDICATED', 'verdict_reason': 'string' }}"
|
| 113 |
-
r = _gemini(prompt, override_key=override_key)
|
| 114 |
-
return r or {"treatment_verdict": "SAFE", "verdict_reason": "No contraindications found."}
|
| 115 |
-
|
| 116 |
-
def agent_labs(record: Dict, triage: Dict = None, override_key: str = None) -> Dict:
|
| 117 |
-
prompt = f"Pathologist. PATIENT: {json.dumps(record)}\nReturn ONLY JSON: {{ 'critical_labs': [] }}"
|
| 118 |
-
r = _gemini(prompt, override_key=override_key)
|
| 119 |
-
return r or {"critical_labs": []}
|
| 120 |
-
|
| 121 |
-
def agent_differentials(record: Dict, triage: Dict = None, labs: Dict = None, override_key: str = None) -> Dict:
|
| 122 |
-
prompt = f"Chief Resident. PATIENT: {json.dumps(record)}\nReturn ONLY JSON: {{ 'differentials': [] }}"
|
| 123 |
-
r = _gemini(prompt, override_key=override_key)
|
| 124 |
-
return r or {"differentials": []}
|
| 125 |
-
|
| 126 |
-
def agent_action_protocol(record: Dict, triage: Dict, contra: Dict, labs: Dict, diffs: Dict, override_key: str = None) -> Dict:
|
| 127 |
-
prompt = f"ED Attending. Return ONLY JSON: {{ 'primary_directive': 'string', 'clinical_summary': 'string' }}"
|
| 128 |
-
r = _gemini(prompt, override_key=override_key)
|
| 129 |
-
return r or {"primary_directive": "Stabilize patient.", "clinical_summary": "LLM Offline."}
|
| 130 |
|
| 131 |
-
async def
|
| 132 |
record = {"raw_text": text}
|
| 133 |
-
t = agent_triage(record,
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
d = agent_differentials(record, triage=t, labs=l, override_key=key)
|
| 137 |
-
a = agent_action_protocol(record, t, c, l, d, override_key=key)
|
| 138 |
-
return {"triage": t, "contra": c, "labs": l, "diffs": d, "action": a}
|
| 139 |
|
| 140 |
-
# ββ
|
| 141 |
|
| 142 |
-
@app.get("/
|
| 143 |
-
def
|
|
|
|
| 144 |
return {
|
| 145 |
-
"
|
| 146 |
-
"
|
| 147 |
-
"
|
| 148 |
}
|
| 149 |
|
| 150 |
-
@app.
|
| 151 |
-
async def
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
return {"
|
| 166 |
-
|
| 167 |
-
# ββ MCP Standard (Fixed SSE Stream) ββββββββββββββββββββββββββββββββββββββββββ
|
| 168 |
-
|
| 169 |
-
@app.api_route("/mcp", methods=["GET", "POST", "OPTIONS"])
|
| 170 |
-
async def mcp_unified_endpoint(req: Request, x_gemini_key: str = Header(None)):
|
| 171 |
-
if req.method == "OPTIONS": return Response(status_code=204)
|
| 172 |
-
if req.method == "GET":
|
| 173 |
-
if "text/event-stream" in req.headers.get("accept", ""):
|
| 174 |
-
async def event_generator():
|
| 175 |
-
yield f"event: endpoint\ndata: /mcp\n\n"
|
| 176 |
-
while True:
|
| 177 |
-
await asyncio.sleep(30)
|
| 178 |
-
yield ":\n\n"
|
| 179 |
-
return StreamingResponse(event_generator(), media_type="text/event-stream")
|
| 180 |
-
return {
|
| 181 |
-
"transport": "sse", "endpoint": "/mcp",
|
| 182 |
-
"tools": [{"name": "analyze_clinical_record", "description": "Synthesis tool."}]
|
| 183 |
-
}
|
| 184 |
-
try:
|
| 185 |
-
body = await req.json()
|
| 186 |
-
except:
|
| 187 |
-
return {"error": "Invalid JSON"}
|
| 188 |
method = body.get("method")
|
| 189 |
params = body.get("params", {})
|
| 190 |
msg_id = body.get("id")
|
|
|
|
| 191 |
if method == "list_tools" or method == "notifications/initialized":
|
| 192 |
return {
|
| 193 |
"jsonrpc": "2.0", "id": msg_id,
|
| 194 |
"result": {"tools": [{"name": "analyze_clinical_record", "description": "Synthesis tool."}]}
|
| 195 |
}
|
|
|
|
| 196 |
if method == "call_tool":
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
"result": {"content": [{"type": "text", "text": f"DIRECTIVE: {res['action']['primary_directive']}"}]}
|
| 204 |
-
}
|
| 205 |
return {"jsonrpc": "2.0", "result": {}, "id": msg_id}
|
| 206 |
|
| 207 |
-
# ββ
|
|
|
|
|
|
|
|
|
|
| 208 |
|
| 209 |
-
@app.
|
| 210 |
-
def
|
| 211 |
-
|
|
|
|
|
|
|
| 212 |
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
if not p: raise HTTPException(status_code=404)
|
| 217 |
-
return p
|
| 218 |
|
| 219 |
@app.post("/patients/upload")
|
| 220 |
async def upload_patient(file: UploadFile = File(...)):
|
| 221 |
-
|
| 222 |
-
return {"id": "UP-" + str(int(time.time()) % 1000), "raw_text": content}
|
| 223 |
|
| 224 |
@app.post("/analyze")
|
| 225 |
async def analyze_patient(data: Dict[str, Any], x_gemini_key: str = Header(None)):
|
| 226 |
-
res = await
|
| 227 |
-
return {
|
| 228 |
-
"triage": res["triage"], "contraindication": res["contra"],
|
| 229 |
-
"labs": res["labs"], "differentials": res["diffs"], "action": res["action"]
|
| 230 |
-
}
|
| 231 |
|
| 232 |
if os.path.exists("frontend/dist"):
|
| 233 |
app.mount("/", StaticFiles(directory="frontend/dist", html=True), name="frontend")
|
|
|
|
| 4 |
from typing import Any, Dict, List, Optional
|
| 5 |
from datetime import datetime
|
| 6 |
|
| 7 |
+
# Load .env
|
| 8 |
_env_file = Path(__file__).resolve().parent.parent / ".env"
|
| 9 |
if _env_file.exists():
|
| 10 |
for _line in _env_file.read_text().splitlines():
|
|
|
|
| 19 |
from fastapi.staticfiles import StaticFiles
|
| 20 |
import requests as _requests
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
_KEY = os.getenv("gemini_api_key", "") or os.getenv("GEMINI_API_KEY", "")
|
| 23 |
BASE_DIR = Path(__file__).resolve().parent
|
| 24 |
|
|
|
|
| 27 |
if p.exists():
|
| 28 |
try:
|
| 29 |
data = json.loads(p.read_text())
|
| 30 |
+
return data["patients"] if isinstance(data, dict) else data
|
| 31 |
+
except: return []
|
|
|
|
|
|
|
|
|
|
| 32 |
return []
|
| 33 |
|
| 34 |
PATIENTS: List[Dict[str, Any]] = _load_patients()
|
|
|
|
| 35 |
app = FastAPI(title="CodeBlue Context API", version="3.1.2")
|
| 36 |
|
|
|
|
| 37 |
@app.exception_handler(Exception)
|
| 38 |
async def global_exception_handler(request: Request, exc: Exception):
|
| 39 |
import traceback
|
| 40 |
+
return JSONResponse(status_code=500, content={"detail": str(exc), "traceback": traceback.format_exc()})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
+
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])
|
|
|
|
| 43 |
|
| 44 |
# ββ Gemini helper βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 45 |
def _gemini(prompt: str, retries: int = 4, override_key: str = None) -> Optional[Dict]:
|
| 46 |
key = (override_key or _KEY).strip()
|
| 47 |
if not key: return None
|
| 48 |
+
payload = {"contents": [{"parts": [{"text": prompt}]}], "generationConfig": {"temperature": 0.1, "maxOutputTokens": 2048}}
|
| 49 |
+
for model in ["gemini-2.5-flash-lite"]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
for attempt in range(retries):
|
| 51 |
try:
|
| 52 |
url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={key}"
|
| 53 |
resp = _requests.post(url, json=payload, timeout=25)
|
| 54 |
+
if resp.status_code == 200:
|
| 55 |
+
text = resp.json()["candidates"][0]["content"]["parts"][0]["text"].strip()
|
| 56 |
+
text = re.sub(r"^```(?:json)?\s*", "", text); text = re.sub(r"\s*```$", "", text)
|
| 57 |
+
try: return json.loads(text)
|
| 58 |
+
except:
|
| 59 |
+
m = re.search(r"\{.*\}", text, re.DOTALL)
|
| 60 |
+
if m: return json.loads(m.group(0))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
time.sleep(1)
|
| 62 |
+
except: time.sleep(1)
|
| 63 |
return None
|
| 64 |
|
| 65 |
# ββ Agents ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 66 |
+
def agent_triage(r, k=None):
|
| 67 |
+
p = f"Triage PATIENT: {json.dumps(r)}\nReturn JSON: {{'severity_label':'string','critical_risks':[]}}"
|
| 68 |
+
return _gemini(p, override_key=k) or {"severity_label":"URGENT","critical_risks":[]}
|
| 69 |
|
| 70 |
+
def agent_action(r, t, k=None):
|
| 71 |
+
p = f"Attending. PATIENT: {json.dumps(r)}\nTRIAGE: {json.dumps(t)}\nReturn JSON: {{'primary_directive':'string','clinical_summary':'string'}}"
|
| 72 |
+
return _gemini(p, override_key=k) or {"primary_directive":"Stabilize.","clinical_summary":"Offline."}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
+
async def process_synthesis(text: str, key: str):
|
| 75 |
record = {"raw_text": text}
|
| 76 |
+
t = agent_triage(record, k=key)
|
| 77 |
+
a = agent_action(record, t, k=key)
|
| 78 |
+
return {"triage": t, "action": a}
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
+
# ββ MCP Standard (Optimized SSE Discovery) ββββββββββββββββββββββββββββββββββ
|
| 81 |
|
| 82 |
+
@app.get("/mcp")
|
| 83 |
+
async def mcp_discovery():
|
| 84 |
+
"""Initial Discovery JSON"""
|
| 85 |
return {
|
| 86 |
+
"transport": "sse",
|
| 87 |
+
"endpoint": "https://anil988-codeblue-context.hf.space/mcp/sse",
|
| 88 |
+
"tools": [{"name": "analyze_clinical_record", "description": "Synthesize records."}]
|
| 89 |
}
|
| 90 |
|
| 91 |
+
@app.get("/mcp/sse")
|
| 92 |
+
async def mcp_sse_stream(req: Request):
|
| 93 |
+
"""Dedicated SSE Handshake"""
|
| 94 |
+
async def event_generator():
|
| 95 |
+
# Tell the client where to POST JSON-RPC messages
|
| 96 |
+
yield f"event: endpoint\ndata: https://anil988-codeblue-context.hf.space/mcp/invoke\n\n"
|
| 97 |
+
while True:
|
| 98 |
+
await asyncio.sleep(25)
|
| 99 |
+
yield ": keep-alive\n\n"
|
| 100 |
+
return StreamingResponse(event_generator(), media_type="text/event-stream")
|
| 101 |
+
|
| 102 |
+
@app.post("/mcp/invoke")
|
| 103 |
+
async def mcp_invoke(req: Request, x_gemini_key: str = Header(None)):
|
| 104 |
+
"""JSON-RPC Invocation"""
|
| 105 |
+
try: body = await req.json()
|
| 106 |
+
except: return {"error": "Invalid JSON"}
|
| 107 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
method = body.get("method")
|
| 109 |
params = body.get("params", {})
|
| 110 |
msg_id = body.get("id")
|
| 111 |
+
|
| 112 |
if method == "list_tools" or method == "notifications/initialized":
|
| 113 |
return {
|
| 114 |
"jsonrpc": "2.0", "id": msg_id,
|
| 115 |
"result": {"tools": [{"name": "analyze_clinical_record", "description": "Synthesis tool."}]}
|
| 116 |
}
|
| 117 |
+
|
| 118 |
if method == "call_tool":
|
| 119 |
+
args = params.get("arguments", {})
|
| 120 |
+
res = await process_synthesis(args.get("text", ""), x_gemini_key)
|
| 121 |
+
return {
|
| 122 |
+
"jsonrpc": "2.0", "id": msg_id,
|
| 123 |
+
"result": {"content": [{"type": "text", "text": f"DIRECTIVE: {res['action']['primary_directive']}"}]}
|
| 124 |
+
}
|
|
|
|
|
|
|
| 125 |
return {"jsonrpc": "2.0", "result": {}, "id": msg_id}
|
| 126 |
|
| 127 |
+
# ββ A2A Standard ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 128 |
+
@app.get("/.well-known/a2a-card.json")
|
| 129 |
+
def get_a2a_card():
|
| 130 |
+
return {"name": "CodeBlue", "capabilities": ["clinical_synthesis"], "endpoints": {"invoke": "/a2a/invoke"}}
|
| 131 |
|
| 132 |
+
@app.post("/a2a/invoke")
|
| 133 |
+
async def a2a_invoke(request: Dict[str, Any], x_gemini_key: str = Header(None)):
|
| 134 |
+
p = request.get("params", {})
|
| 135 |
+
res = await process_synthesis(p.get("text", ""), x_gemini_key)
|
| 136 |
+
return {"jsonrpc": "2.0", "result": {"directive": res["action"]["primary_directive"]}, "id": request.get("id")}
|
| 137 |
|
| 138 |
+
# ββ App Endpoints βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 139 |
+
@app.get("/patients")
|
| 140 |
+
def get_patients(): return PATIENTS
|
|
|
|
|
|
|
| 141 |
|
| 142 |
@app.post("/patients/upload")
|
| 143 |
async def upload_patient(file: UploadFile = File(...)):
|
| 144 |
+
return {"id": "UP-" + str(int(time.time()) % 1000), "raw_text": (await file.read()).decode()}
|
|
|
|
| 145 |
|
| 146 |
@app.post("/analyze")
|
| 147 |
async def analyze_patient(data: Dict[str, Any], x_gemini_key: str = Header(None)):
|
| 148 |
+
res = await process_synthesis(data.get("raw_text", ""), x_gemini_key)
|
| 149 |
+
return {"triage": res["triage"], "action": res["action"], "contraindication": {"treatment_verdict":"SAFE"}, "labs": {"critical_labs":[]}, "differentials": {"differentials":[]}}
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
if os.path.exists("frontend/dist"):
|
| 152 |
app.mount("/", StaticFiles(directory="frontend/dist", html=True), name="frontend")
|