Spaces:
Sleeping
Sleeping
frabbani commited on
Commit ·
76f86e6
1
Parent(s): e616494
Add graph based workflow ui filtering to agent_v2......
Browse files- agent_v2.py +93 -38
- server.py +71 -1
- tools.py +1089 -546
agent_v2.py
CHANGED
|
@@ -197,12 +197,14 @@ def get_relevant_categories(question: str, manifest: Dict = None) -> Set[str]:
|
|
| 197 |
return relevant
|
| 198 |
|
| 199 |
|
| 200 |
-
def get_filtered_tools_description(categories: Set[str]) -> str:
|
| 201 |
"""
|
| 202 |
Generate tool descriptions for only the specified categories.
|
| 203 |
-
This significantly reduces token usage in the planning prompt.
|
| 204 |
|
| 205 |
-
|
|
|
|
|
|
|
|
|
|
| 206 |
"""
|
| 207 |
# Map categories to tool name patterns
|
| 208 |
CATEGORY_TOOL_PATTERNS = {
|
|
@@ -215,57 +217,110 @@ def get_filtered_tools_description(categories: Set[str]) -> str:
|
|
| 215 |
'meta': ['search_tools', 'get_tool_schema', 'list_tool']
|
| 216 |
}
|
| 217 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
# Build list of patterns to match
|
| 219 |
patterns_to_match = []
|
| 220 |
for cat in categories:
|
| 221 |
patterns_to_match.extend(CATEGORY_TOOL_PATTERNS.get(cat, []))
|
| 222 |
|
| 223 |
-
# Try to use get_tools_description with categories if it supports it
|
| 224 |
-
try:
|
| 225 |
-
# Check if get_tools_description accepts categories parameter
|
| 226 |
-
import inspect
|
| 227 |
-
sig = inspect.signature(get_tools_description)
|
| 228 |
-
if 'categories' in sig.parameters:
|
| 229 |
-
return get_tools_description(categories=list(categories))
|
| 230 |
-
except:
|
| 231 |
-
pass
|
| 232 |
-
|
| 233 |
-
# Fallback: Filter the TOOLS list based on patterns
|
| 234 |
if not patterns_to_match:
|
| 235 |
-
|
| 236 |
-
return get_tools_description()
|
| 237 |
|
| 238 |
-
#
|
| 239 |
-
|
| 240 |
-
|
| 241 |
|
| 242 |
-
# Parse the tools description and filter
|
| 243 |
-
# TOOLS is a list of MCP schema dicts
|
| 244 |
-
lines = ["Available tools:\n"]
|
| 245 |
for tool in TOOLS:
|
| 246 |
tool_name = tool.get('name', '')
|
| 247 |
-
tool_desc = tool.get('description', '')
|
| 248 |
|
| 249 |
-
#
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
params = tool.get('inputSchema', {}).get('properties', {})
|
| 254 |
-
params_str = ", ".join([
|
| 255 |
-
|
| 256 |
-
for name, info in params.items()
|
| 257 |
-
])
|
| 258 |
-
lines.append(f"- {tool_name}: {tool_desc}")
|
| 259 |
if params_str:
|
| 260 |
-
lines.append(f"
|
| 261 |
-
|
| 262 |
-
filtered_tools.append(tool_name)
|
| 263 |
|
| 264 |
-
|
| 265 |
-
if not filtered_tools:
|
| 266 |
return get_tools_description()
|
| 267 |
|
| 268 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 269 |
def extract_json(text: str) -> Optional[Dict]:
|
| 270 |
"""Extract JSON from text, handling various formats."""
|
| 271 |
# Try to find JSON in code blocks
|
|
|
|
| 197 |
return relevant
|
| 198 |
|
| 199 |
|
| 200 |
+
def get_filtered_tools_description(categories: Set[str], condensed: bool = True) -> str:
|
| 201 |
"""
|
| 202 |
Generate tool descriptions for only the specified categories.
|
|
|
|
| 203 |
|
| 204 |
+
Args:
|
| 205 |
+
categories: Set of category names to include
|
| 206 |
+
condensed: If True, use minimal descriptions with valid values inline
|
| 207 |
+
This reduces tokens from ~800 to ~300 for typical queries
|
| 208 |
"""
|
| 209 |
# Map categories to tool name patterns
|
| 210 |
CATEGORY_TOOL_PATTERNS = {
|
|
|
|
| 217 |
'meta': ['search_tools', 'get_tool_schema', 'list_tool']
|
| 218 |
}
|
| 219 |
|
| 220 |
+
# CONDENSED TOOL INFO with valid values inline
|
| 221 |
+
# This prevents LLM errors by showing exactly what values are accepted
|
| 222 |
+
TOOL_CONDENSED_INFO = {
|
| 223 |
+
'get_vital_chart_data': {
|
| 224 |
+
'desc': 'Get vital signs chart data for visualization',
|
| 225 |
+
'params': 'vital_type (MUST be one of: blood_pressure, blood_pressure_systolic, blood_pressure_diastolic, heart_rate, temperature, weight, height, bmi, respiratory_rate, oxygen_saturation), days (default 30)'
|
| 226 |
+
},
|
| 227 |
+
'get_lab_chart_data': {
|
| 228 |
+
'desc': 'Get lab results chart data for visualization',
|
| 229 |
+
'params': 'lab_type (MUST be one of: a1c, glucose, cholesterol, kidney), periods (default 4)'
|
| 230 |
+
},
|
| 231 |
+
'compare_before_after_treatment': {
|
| 232 |
+
'desc': 'Compare health metrics before/after starting a medication',
|
| 233 |
+
'params': 'medication_name (exact medication name), metric_type (MUST be one of: blood_pressure, heart_rate, weight, a1c, glucose, cholesterol)'
|
| 234 |
+
},
|
| 235 |
+
'analyze_vital_trend': {
|
| 236 |
+
'desc': 'Analyze trends in vital signs over time',
|
| 237 |
+
'params': 'vital_type (same options as get_vital_chart_data), days (default 30)'
|
| 238 |
+
},
|
| 239 |
+
'get_medications': {
|
| 240 |
+
'desc': 'Get patient medications',
|
| 241 |
+
'params': 'status (optional: active, stopped, or omit for all)'
|
| 242 |
+
},
|
| 243 |
+
'get_conditions': {
|
| 244 |
+
'desc': 'Get patient medical conditions/diagnoses',
|
| 245 |
+
'params': 'status (optional: active, resolved, or omit for all)'
|
| 246 |
+
},
|
| 247 |
+
'get_allergies': {
|
| 248 |
+
'desc': 'Get patient allergies',
|
| 249 |
+
'params': 'none required'
|
| 250 |
+
},
|
| 251 |
+
'get_recent_vitals': {
|
| 252 |
+
'desc': 'Get recent vital sign readings',
|
| 253 |
+
'params': 'days (default 30), vital_type (optional, same options as charts)'
|
| 254 |
+
},
|
| 255 |
+
'get_lab_results': {
|
| 256 |
+
'desc': 'Get recent lab test results',
|
| 257 |
+
'params': 'days (default 90)'
|
| 258 |
+
},
|
| 259 |
+
'get_immunizations': {
|
| 260 |
+
'desc': 'Get patient immunization/vaccination history',
|
| 261 |
+
'params': 'none required'
|
| 262 |
+
},
|
| 263 |
+
'get_encounters': {
|
| 264 |
+
'desc': 'Get patient healthcare visits/encounters',
|
| 265 |
+
'params': 'limit (default 10)'
|
| 266 |
+
},
|
| 267 |
+
'get_patient_summary': {
|
| 268 |
+
'desc': 'Get overview of all patient data',
|
| 269 |
+
'params': 'none required'
|
| 270 |
+
},
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
# Build list of patterns to match
|
| 274 |
patterns_to_match = []
|
| 275 |
for cat in categories:
|
| 276 |
patterns_to_match.extend(CATEGORY_TOOL_PATTERNS.get(cat, []))
|
| 277 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
if not patterns_to_match:
|
| 279 |
+
patterns_to_match = None # Include all
|
|
|
|
| 280 |
|
| 281 |
+
# Build tool descriptions
|
| 282 |
+
lines = ["Available tools (always include patient_id in args):\n"]
|
| 283 |
+
included_tools = []
|
| 284 |
|
|
|
|
|
|
|
|
|
|
| 285 |
for tool in TOOLS:
|
| 286 |
tool_name = tool.get('name', '')
|
|
|
|
| 287 |
|
| 288 |
+
# Skip meta tools in planning
|
| 289 |
+
if tool_name in ['search_tools', 'get_tool_schema', 'list_tool_categories']:
|
| 290 |
+
continue
|
| 291 |
+
|
| 292 |
+
# Check if tool matches any pattern (or include all if no patterns)
|
| 293 |
+
if patterns_to_match:
|
| 294 |
+
matches = any(pattern in tool_name.lower() for pattern in patterns_to_match)
|
| 295 |
+
if not matches:
|
| 296 |
+
continue
|
| 297 |
+
|
| 298 |
+
included_tools.append(tool_name)
|
| 299 |
+
|
| 300 |
+
if condensed and tool_name in TOOL_CONDENSED_INFO:
|
| 301 |
+
# Use condensed format with valid values
|
| 302 |
+
info = TOOL_CONDENSED_INFO[tool_name]
|
| 303 |
+
lines.append(f"• {tool_name}: {info['desc']}")
|
| 304 |
+
lines.append(f" Args: {info['params']}")
|
| 305 |
+
else:
|
| 306 |
+
# Fallback to full description
|
| 307 |
+
tool_desc = tool.get('description', '')
|
| 308 |
params = tool.get('inputSchema', {}).get('properties', {})
|
| 309 |
+
params_str = ", ".join([f"{name}" for name in params.keys() if name != 'patient_id'])
|
| 310 |
+
lines.append(f"• {tool_name}: {tool_desc}")
|
|
|
|
|
|
|
|
|
|
| 311 |
if params_str:
|
| 312 |
+
lines.append(f" Args: {params_str}")
|
| 313 |
+
lines.append("")
|
|
|
|
| 314 |
|
| 315 |
+
if not included_tools:
|
|
|
|
| 316 |
return get_tools_description()
|
| 317 |
|
| 318 |
+
# Add token count estimate for logging
|
| 319 |
+
result = "\n".join(lines)
|
| 320 |
+
print(f"[TOOL SEARCH] Providing {len(included_tools)} tools (~{len(result.split())} tokens)")
|
| 321 |
+
|
| 322 |
+
return result
|
| 323 |
+
|
| 324 |
def extract_json(text: str) -> Optional[Dict]:
|
| 325 |
"""Extract JSON from text, handling various formats."""
|
| 326 |
# Try to find JSON in code blocks
|
server.py
CHANGED
|
@@ -396,6 +396,76 @@ async def health_check():
|
|
| 396 |
"database": db_status,
|
| 397 |
"llama_url": LLAMA_SERVER_URL
|
| 398 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
# ============================================================================
|
| 400 |
# Agent endpoint (v2 with discovery, planning, fact extraction)
|
| 401 |
# ============================================================================
|
|
@@ -1031,4 +1101,4 @@ if __name__ == "__main__":
|
|
| 1031 |
print(f"Starting server on port {port}...")
|
| 1032 |
print(f"LLM Backend: {LLAMA_SERVER_URL}")
|
| 1033 |
print(f"HeAR Backend: {HEAR_SERVER_URL or 'Not configured'}")
|
| 1034 |
-
uvicorn.run(app, host="0.0.0.0", port=port)
|
|
|
|
| 396 |
"database": db_status,
|
| 397 |
"llama_url": LLAMA_SERVER_URL
|
| 398 |
}
|
| 399 |
+
|
| 400 |
+
# ============================================================================
|
| 401 |
+
# MCP (Model Context Protocol) Endpoints
|
| 402 |
+
# ============================================================================
|
| 403 |
+
from tools import mcp_interface
|
| 404 |
+
|
| 405 |
+
@app.post("/mcp/initialize")
|
| 406 |
+
async def mcp_initialize(request: dict = None):
|
| 407 |
+
"""MCP Initialize - Return server capabilities."""
|
| 408 |
+
return mcp_interface.get_server_info()
|
| 409 |
+
|
| 410 |
+
@app.post("/mcp/tools/list")
|
| 411 |
+
async def mcp_list_tools():
|
| 412 |
+
"""MCP List Tools - Return available tools in MCP format."""
|
| 413 |
+
return mcp_interface.list_tools()
|
| 414 |
+
|
| 415 |
+
@app.post("/mcp/tools/call")
|
| 416 |
+
async def mcp_call_tool(request: dict):
|
| 417 |
+
"""MCP Call Tool - Execute a tool and return result."""
|
| 418 |
+
name = request.get("name")
|
| 419 |
+
arguments = request.get("arguments", {})
|
| 420 |
+
return mcp_interface.call_tool(name, arguments)
|
| 421 |
+
|
| 422 |
+
@app.get("/api/mcp/status")
|
| 423 |
+
async def mcp_status():
|
| 424 |
+
"""Get MCP status including connected external servers."""
|
| 425 |
+
return {
|
| 426 |
+
"protocol_version": mcp_interface.PROTOCOL_VERSION,
|
| 427 |
+
"local_tools": len(mcp_interface.registry.get_all()),
|
| 428 |
+
"external_tools": len(mcp_interface.external_tools),
|
| 429 |
+
"connected_servers": mcp_interface.list_connected_servers()
|
| 430 |
+
}
|
| 431 |
+
|
| 432 |
+
@app.post("/api/mcp/connect")
|
| 433 |
+
async def mcp_connect_server(request: dict):
|
| 434 |
+
"""Connect to an external MCP server and discover its tools."""
|
| 435 |
+
server_url = request.get("server_url")
|
| 436 |
+
server_name = request.get("server_name")
|
| 437 |
+
if not server_url:
|
| 438 |
+
return {"success": False, "error": "server_url required"}
|
| 439 |
+
return mcp_interface.connect_server(server_url, server_name)
|
| 440 |
+
|
| 441 |
+
@app.post("/api/mcp/disconnect")
|
| 442 |
+
async def mcp_disconnect_server(request: dict):
|
| 443 |
+
"""Disconnect from an external MCP server."""
|
| 444 |
+
server_url = request.get("server_url")
|
| 445 |
+
if not server_url:
|
| 446 |
+
return {"success": False, "error": "server_url required"}
|
| 447 |
+
success = mcp_interface.disconnect_server(server_url)
|
| 448 |
+
return {"success": success}
|
| 449 |
+
|
| 450 |
+
@app.post("/api/mcp/register-tool")
|
| 451 |
+
async def mcp_register_tool(request: dict):
|
| 452 |
+
"""Manually register an external tool without full MCP server."""
|
| 453 |
+
name = request.get("name")
|
| 454 |
+
description = request.get("description")
|
| 455 |
+
parameters = request.get("parameters", {"type": "object", "properties": {}})
|
| 456 |
+
handler_url = request.get("handler_url")
|
| 457 |
+
|
| 458 |
+
if not all([name, description, handler_url]):
|
| 459 |
+
return {"success": False, "error": "name, description, and handler_url required"}
|
| 460 |
+
|
| 461 |
+
success = mcp_interface.register_tool_manually(name, description, parameters, handler_url)
|
| 462 |
+
return {"success": success, "tool_name": name}
|
| 463 |
+
|
| 464 |
+
@app.get("/api/mcp/tools")
|
| 465 |
+
async def mcp_get_all_tools():
|
| 466 |
+
"""Get all tools (local + external) in MCP format."""
|
| 467 |
+
return {"tools": mcp_interface.get_all_tools()}
|
| 468 |
+
|
| 469 |
# ============================================================================
|
| 470 |
# Agent endpoint (v2 with discovery, planning, fact extraction)
|
| 471 |
# ============================================================================
|
|
|
|
| 1101 |
print(f"Starting server on port {port}...")
|
| 1102 |
print(f"LLM Backend: {LLAMA_SERVER_URL}")
|
| 1103 |
print(f"HeAR Backend: {HEAR_SERVER_URL or 'Not configured'}")
|
| 1104 |
+
uvicorn.run(app, host="0.0.0.0", port=port)
|
tools.py
CHANGED
|
@@ -1,138 +1,593 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
Health data tools for the MedGemma agent.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
These tools allow the LLM to query specific data rather than
|
| 5 |
loading everything into context at once.
|
| 6 |
"""
|
| 7 |
import sqlite3
|
|
|
|
|
|
|
| 8 |
from datetime import datetime, timedelta
|
| 9 |
-
from typing import Optional
|
|
|
|
| 10 |
import os
|
|
|
|
|
|
|
| 11 |
DB_PATH = os.getenv("DB_PATH", "data/fhir.db")
|
|
|
|
| 12 |
def get_db():
|
| 13 |
"""Get database connection."""
|
| 14 |
conn = sqlite3.connect(DB_PATH)
|
| 15 |
conn.row_factory = sqlite3.Row
|
| 16 |
return conn
|
| 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 |
-
"days": "(Optional) Number of days to analyze. Default is 30."
|
| 88 |
-
}
|
| 89 |
-
},
|
| 90 |
-
{
|
| 91 |
-
"name": "get_vital_chart_data",
|
| 92 |
-
"description": "Get vital sign data formatted for generating a LINE chart/graph. USE THIS TOOL (not get_recent_vitals) whenever the user wants to: see, show, display, visualize, or graph any vital sign; view trends over time; or asks for a chart. Returns data that renders as a visual chart.",
|
| 93 |
-
"parameters": {
|
| 94 |
-
"patient_id": "The patient's ID",
|
| 95 |
-
"vital_type": "The vital to chart: 'blood_pressure', 'heart_rate', 'weight', 'temperature', 'respiratory_rate', 'oxygen_saturation'",
|
| 96 |
-
"days": "(Optional) Number of days to include. Default is 30."
|
| 97 |
-
}
|
| 98 |
-
},
|
| 99 |
-
{
|
| 100 |
-
"name": "get_lab_chart_data",
|
| 101 |
-
"description": "Get laboratory results formatted for a BAR chart. Use this when user wants to compare lab values, see lab history as a chart, or visualize lab trends. Good for: cholesterol comparison, A1c history, glucose trends, kidney function over time.",
|
| 102 |
-
"parameters": {
|
| 103 |
-
"patient_id": "The patient's ID",
|
| 104 |
-
"lab_type": "The lab to chart: 'cholesterol' (shows Total, HDL, LDL, Triglycerides), 'a1c', 'glucose', 'kidney' (Creatinine, eGFR), 'all_latest' (comparison of recent labs)",
|
| 105 |
-
"periods": "(Optional) Number of time periods to show. Default is 4."
|
| 106 |
}
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
"
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
}
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
}
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
lines = ["Available tools:\n"]
|
| 130 |
-
for tool in
|
| 131 |
-
lines.append(
|
| 132 |
-
|
| 133 |
-
|
| 134 |
return "\n".join(lines)
|
| 135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
def get_patient_summary(patient_id: str) -> str:
|
| 137 |
"""Get a summary of available health data."""
|
| 138 |
conn = get_db()
|
|
@@ -141,6 +596,7 @@ def get_patient_summary(patient_id: str) -> str:
|
|
| 141 |
patient = cursor.fetchone()
|
| 142 |
if not patient:
|
| 143 |
return "Patient not found."
|
|
|
|
| 144 |
counts = {}
|
| 145 |
for table in ['conditions', 'medications', 'observations', 'allergies', 'encounters', 'immunizations', 'procedures']:
|
| 146 |
try:
|
|
@@ -148,27 +604,33 @@ def get_patient_summary(patient_id: str) -> str:
|
|
| 148 |
counts[table] = cursor.fetchone()[0]
|
| 149 |
except:
|
| 150 |
counts[table] = 0
|
|
|
|
| 151 |
cursor = conn.execute(
|
| 152 |
"SELECT display, clinical_status FROM conditions WHERE patient_id = ? LIMIT 10",
|
| 153 |
(patient_id,)
|
| 154 |
)
|
| 155 |
conditions = [f"{row['display']} ({row['clinical_status']})" for row in cursor.fetchall()]
|
|
|
|
| 156 |
cursor = conn.execute(
|
| 157 |
"SELECT display FROM medications WHERE patient_id = ? AND status = 'active' LIMIT 10",
|
| 158 |
(patient_id,)
|
| 159 |
)
|
| 160 |
medications = [row['display'] for row in cursor.fetchall()]
|
|
|
|
| 161 |
cursor = conn.execute("""
|
| 162 |
SELECT MIN(effective_date) as earliest, MAX(effective_date) as latest
|
| 163 |
FROM observations WHERE patient_id = ?
|
| 164 |
""", (patient_id,))
|
| 165 |
obs_range = cursor.fetchone()
|
|
|
|
| 166 |
birth = datetime.strptime(patient["birth_date"], "%Y-%m-%d")
|
| 167 |
age = (datetime.now() - birth).days // 365
|
|
|
|
| 168 |
summary = f"""Patient Summary:
|
| 169 |
- Name: {patient['given_name']} {patient['family_name']}
|
| 170 |
- Age: {age} years old
|
| 171 |
- Gender: {patient['gender']}
|
|
|
|
| 172 |
Available Data:
|
| 173 |
- Conditions: {counts['conditions']} records
|
| 174 |
- Medications: {counts['medications']} records
|
|
@@ -176,13 +638,27 @@ Available Data:
|
|
| 176 |
- Allergies: {counts['allergies']} records
|
| 177 |
- Encounters: {counts['encounters']} records
|
| 178 |
- Immunizations: {counts['immunizations']} records
|
|
|
|
| 179 |
Conditions: {', '.join(conditions) if conditions else 'None recorded'}
|
|
|
|
| 180 |
Active Medications: {', '.join(medications) if medications else 'None'}
|
|
|
|
| 181 |
Observation date range: {obs_range['earliest'][:10] if obs_range['earliest'] else 'N/A'} to {obs_range['latest'][:10] if obs_range['latest'] else 'N/A'}
|
| 182 |
"""
|
| 183 |
return summary
|
| 184 |
finally:
|
| 185 |
conn.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
def get_conditions(patient_id: str, status: Optional[str] = None) -> str:
|
| 187 |
"""Get patient conditions."""
|
| 188 |
conn = get_db()
|
|
@@ -199,17 +675,31 @@ def get_conditions(patient_id: str, status: Optional[str] = None) -> str:
|
|
| 199 |
FROM conditions WHERE patient_id = ?
|
| 200 |
ORDER BY onset_date DESC
|
| 201 |
""", (patient_id,))
|
|
|
|
| 202 |
conditions = cursor.fetchall()
|
| 203 |
if not conditions:
|
| 204 |
return "No conditions found."
|
|
|
|
| 205 |
lines = ["Conditions:\n"]
|
| 206 |
for c in conditions:
|
| 207 |
onset = c['onset_date'][:10] if c['onset_date'] else 'Unknown'
|
| 208 |
end = f" (resolved: {c['abatement_date'][:10]})" if c['abatement_date'] else ""
|
| 209 |
lines.append(f"- {c['display']} [{c['clinical_status']}] - since {onset}{end}")
|
|
|
|
| 210 |
return "\n".join(lines)
|
| 211 |
finally:
|
| 212 |
conn.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
def get_medications(patient_id: str, status: Optional[str] = None) -> str:
|
| 214 |
"""Get patient medications."""
|
| 215 |
conn = get_db()
|
|
@@ -226,12 +716,11 @@ def get_medications(patient_id: str, status: Optional[str] = None) -> str:
|
|
| 226 |
FROM medications WHERE patient_id = ?
|
| 227 |
ORDER BY start_date DESC
|
| 228 |
""", (patient_id,))
|
|
|
|
| 229 |
medications = cursor.fetchall()
|
| 230 |
if not medications:
|
| 231 |
-
# Debug: check what patient_ids exist
|
| 232 |
-
cursor = conn.execute("SELECT DISTINCT patient_id FROM medications LIMIT 5")
|
| 233 |
-
existing_ids = [row[0] for row in cursor.fetchall()]
|
| 234 |
return "No medications found."
|
|
|
|
| 235 |
lines = ["Medications:\n"]
|
| 236 |
for m in medications:
|
| 237 |
dosage = m['dosage_text'] or 'No dosage specified'
|
|
@@ -240,9 +729,20 @@ def get_medications(patient_id: str, status: Optional[str] = None) -> str:
|
|
| 240 |
lines.append(f"- {m['display']} [{m['status']}]")
|
| 241 |
lines.append(f" Dosage: {dosage}{route}")
|
| 242 |
lines.append(f" Started: {start}")
|
|
|
|
| 243 |
return "\n".join(lines)
|
| 244 |
finally:
|
| 245 |
conn.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
def get_allergies(patient_id: str) -> str:
|
| 247 |
"""Get patient allergies."""
|
| 248 |
conn = get_db()
|
|
@@ -251,9 +751,11 @@ def get_allergies(patient_id: str) -> str:
|
|
| 251 |
SELECT substance, reaction_display, reaction_severity, criticality, category
|
| 252 |
FROM allergies WHERE patient_id = ?
|
| 253 |
""", (patient_id,))
|
|
|
|
| 254 |
allergies = cursor.fetchall()
|
| 255 |
if not allergies:
|
| 256 |
return "No known allergies."
|
|
|
|
| 257 |
lines = ["Allergies:\n"]
|
| 258 |
for a in allergies:
|
| 259 |
severity = a['reaction_severity'] or a['criticality'] or 'Unknown severity'
|
|
@@ -262,27 +764,28 @@ def get_allergies(patient_id: str) -> str:
|
|
| 262 |
lines.append(f"- {a['substance']} ({category})")
|
| 263 |
lines.append(f" Reaction: {reaction}")
|
| 264 |
lines.append(f" Severity: {severity}")
|
|
|
|
| 265 |
return "\n".join(lines)
|
| 266 |
finally:
|
| 267 |
conn.close()
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
}
|
| 281 |
def get_recent_vitals(patient_id: str, days: int = 30, vital_type: Optional[str] = None) -> str:
|
| 282 |
"""Get recent vital signs."""
|
| 283 |
conn = get_db()
|
| 284 |
try:
|
| 285 |
cutoff = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
|
|
|
|
| 286 |
if vital_type and vital_type in VITAL_CODES:
|
| 287 |
codes = VITAL_CODES[vital_type]
|
| 288 |
placeholders = ','.join(['?' for _ in codes])
|
|
@@ -302,9 +805,11 @@ def get_recent_vitals(patient_id: str, days: int = 30, vital_type: Optional[str]
|
|
| 302 |
ORDER BY effective_date DESC
|
| 303 |
LIMIT 50
|
| 304 |
""", (patient_id, cutoff))
|
|
|
|
| 305 |
vitals = cursor.fetchall()
|
| 306 |
if not vitals:
|
| 307 |
return f"No vital signs found in the last {days} days."
|
|
|
|
| 308 |
lines = [f"Vital Signs (last {days} days):\n"]
|
| 309 |
by_type = {}
|
| 310 |
for v in vitals:
|
|
@@ -312,6 +817,7 @@ def get_recent_vitals(patient_id: str, days: int = 30, vital_type: Optional[str]
|
|
| 312 |
if display not in by_type:
|
| 313 |
by_type[display] = []
|
| 314 |
by_type[display].append(v)
|
|
|
|
| 315 |
for display, readings in by_type.items():
|
| 316 |
lines.append(f"\n{display}:")
|
| 317 |
for r in readings[:5]:
|
|
@@ -319,14 +825,27 @@ def get_recent_vitals(patient_id: str, days: int = 30, vital_type: Optional[str]
|
|
| 319 |
value = r['value_quantity']
|
| 320 |
unit = r['value_unit'] or ''
|
| 321 |
lines.append(f" {date}: {value} {unit}")
|
|
|
|
| 322 |
return "\n".join(lines)
|
| 323 |
finally:
|
| 324 |
conn.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 325 |
def get_lab_results(patient_id: str, days: int = 90) -> str:
|
| 326 |
"""Get laboratory results."""
|
| 327 |
conn = get_db()
|
| 328 |
try:
|
| 329 |
cutoff = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
|
|
|
|
| 330 |
cursor = conn.execute("""
|
| 331 |
SELECT display, value_quantity, value_unit, value_string,
|
| 332 |
effective_date, interpretation
|
|
@@ -335,9 +854,11 @@ def get_lab_results(patient_id: str, days: int = 90) -> str:
|
|
| 335 |
ORDER BY effective_date DESC
|
| 336 |
LIMIT 50
|
| 337 |
""", (patient_id, cutoff))
|
|
|
|
| 338 |
labs = cursor.fetchall()
|
| 339 |
if not labs:
|
| 340 |
return f"No lab results found in the last {days} days."
|
|
|
|
| 341 |
lines = [f"Lab Results (last {days} days):\n"]
|
| 342 |
for lab in labs:
|
| 343 |
date = lab['effective_date'][:10] if lab['effective_date'] else 'Unknown'
|
|
@@ -345,9 +866,21 @@ def get_lab_results(patient_id: str, days: int = 90) -> str:
|
|
| 345 |
unit = lab['value_unit'] or ''
|
| 346 |
interp = f" [{lab['interpretation']}]" if lab['interpretation'] else ""
|
| 347 |
lines.append(f"- {lab['display']}: {value} {unit}{interp} ({date})")
|
|
|
|
| 348 |
return "\n".join(lines)
|
| 349 |
finally:
|
| 350 |
conn.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 351 |
def get_encounters(patient_id: str, limit: int = 10) -> str:
|
| 352 |
"""Get healthcare encounters."""
|
| 353 |
conn = get_db()
|
|
@@ -359,9 +892,11 @@ def get_encounters(patient_id: str, limit: int = 10) -> str:
|
|
| 359 |
ORDER BY period_start DESC
|
| 360 |
LIMIT ?
|
| 361 |
""", (patient_id, limit))
|
|
|
|
| 362 |
encounters = cursor.fetchall()
|
| 363 |
if not encounters:
|
| 364 |
return "No encounters found."
|
|
|
|
| 365 |
lines = [f"Healthcare Encounters (last {limit}):\n"]
|
| 366 |
for e in encounters:
|
| 367 |
date = e['period_start'][:10] if e['period_start'] else 'Unknown'
|
|
@@ -369,9 +904,20 @@ def get_encounters(patient_id: str, limit: int = 10) -> str:
|
|
| 369 |
reason = e['reason_display'] or 'No reason specified'
|
| 370 |
lines.append(f"- {date}: {enc_type}")
|
| 371 |
lines.append(f" Reason: {reason}")
|
|
|
|
| 372 |
return "\n".join(lines)
|
| 373 |
finally:
|
| 374 |
conn.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 375 |
def get_immunizations(patient_id: str) -> str:
|
| 376 |
"""Get immunization history."""
|
| 377 |
conn = get_db()
|
|
@@ -381,25 +927,42 @@ def get_immunizations(patient_id: str) -> str:
|
|
| 381 |
FROM immunizations WHERE patient_id = ?
|
| 382 |
ORDER BY occurrence_date DESC
|
| 383 |
""", (patient_id,))
|
|
|
|
| 384 |
immunizations = cursor.fetchall()
|
| 385 |
if not immunizations:
|
| 386 |
return "No immunization records found."
|
|
|
|
| 387 |
lines = ["Immunizations:\n"]
|
| 388 |
for i in immunizations:
|
| 389 |
date = i['occurrence_date'][:10] if i['occurrence_date'] else 'Unknown'
|
| 390 |
lines.append(f"- {i['vaccine_display']} ({date}) [{i['status']}]")
|
|
|
|
| 391 |
return "\n".join(lines)
|
| 392 |
finally:
|
| 393 |
conn.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 394 |
def analyze_vital_trend(patient_id: str, vital_type: str, days: int = 30) -> str:
|
| 395 |
"""Analyze trends in vital signs."""
|
| 396 |
conn = get_db()
|
| 397 |
try:
|
| 398 |
if vital_type not in VITAL_CODES:
|
| 399 |
return f"Unknown vital type: {vital_type}. Available: {', '.join(VITAL_CODES.keys())}"
|
|
|
|
| 400 |
codes = VITAL_CODES[vital_type]
|
| 401 |
cutoff = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
|
| 402 |
placeholders = ','.join(['?' for _ in codes])
|
|
|
|
| 403 |
cursor = conn.execute(f"""
|
| 404 |
SELECT value_quantity, effective_date
|
| 405 |
FROM observations
|
|
@@ -407,18 +970,23 @@ def analyze_vital_trend(patient_id: str, vital_type: str, days: int = 30) -> str
|
|
| 407 |
AND effective_date >= ? AND value_quantity IS NOT NULL
|
| 408 |
ORDER BY effective_date ASC
|
| 409 |
""", [patient_id] + codes + [cutoff])
|
|
|
|
| 410 |
readings = cursor.fetchall()
|
| 411 |
if not readings:
|
| 412 |
return f"No {vital_type} readings found in the last {days} days."
|
|
|
|
| 413 |
values = [r['value_quantity'] for r in readings]
|
| 414 |
dates = [r['effective_date'][:10] for r in readings]
|
|
|
|
| 415 |
avg_val = sum(values) / len(values)
|
| 416 |
min_val = min(values)
|
| 417 |
max_val = max(values)
|
|
|
|
| 418 |
if len(values) >= 3:
|
| 419 |
first_third = sum(values[:len(values)//3]) / (len(values)//3)
|
| 420 |
last_third = sum(values[-len(values)//3:]) / (len(values)//3)
|
| 421 |
diff_pct = ((last_third - first_third) / first_third) * 100 if first_third != 0 else 0
|
|
|
|
| 422 |
if diff_pct > 5:
|
| 423 |
trend = f"INCREASING (up {diff_pct:.1f}%)"
|
| 424 |
elif diff_pct < -5:
|
|
@@ -427,27 +995,42 @@ def analyze_vital_trend(patient_id: str, vital_type: str, days: int = 30) -> str
|
|
| 427 |
trend = "STABLE"
|
| 428 |
else:
|
| 429 |
trend = "Not enough data for trend"
|
|
|
|
| 430 |
return f"""{vital_type.replace('_', ' ').title()} Analysis (last {days} days):
|
|
|
|
| 431 |
Readings: {len(values)}
|
| 432 |
Date range: {dates[0]} to {dates[-1]}
|
|
|
|
| 433 |
Statistics:
|
| 434 |
- Average: {avg_val:.1f}
|
| 435 |
- Minimum: {min_val:.1f}
|
| 436 |
- Maximum: {max_val:.1f}
|
|
|
|
| 437 |
Trend: {trend}
|
|
|
|
| 438 |
Recent values: {', '.join([str(v) for v in values[-5:]])}
|
| 439 |
"""
|
| 440 |
finally:
|
| 441 |
conn.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 442 |
def get_vital_chart_data(patient_id: str, vital_type: str, days: int = 30) -> str:
|
| 443 |
"""
|
| 444 |
Get vital sign data formatted for charting.
|
| 445 |
Returns JSON that can be used to render a chart.
|
| 446 |
-
Includes pre-computed statistics (min, max, avg, count) for accurate LLM reporting.
|
| 447 |
"""
|
| 448 |
-
import json as json_module
|
| 449 |
-
import statistics as stats_module
|
| 450 |
-
|
| 451 |
def compute_stats(values):
|
| 452 |
"""Compute statistics for a list of values."""
|
| 453 |
if not values:
|
|
@@ -464,14 +1047,14 @@ def get_vital_chart_data(patient_id: str, vital_type: str, days: int = 30) -> st
|
|
| 464 |
try:
|
| 465 |
if vital_type not in VITAL_CODES:
|
| 466 |
return json_module.dumps({"error": f"Unknown vital type: {vital_type}. Available: {', '.join(VITAL_CODES.keys())}"})
|
|
|
|
| 467 |
codes = VITAL_CODES[vital_type]
|
| 468 |
cutoff = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
|
| 469 |
-
placeholders = ','.join(['?' for _ in codes])
|
| 470 |
|
| 471 |
# For blood pressure, we need both systolic and diastolic
|
| 472 |
if vital_type == 'blood_pressure':
|
| 473 |
# Get systolic
|
| 474 |
-
cursor = conn.execute(
|
| 475 |
SELECT value_quantity, effective_date
|
| 476 |
FROM observations
|
| 477 |
WHERE patient_id = ? AND code = '8480-6'
|
|
@@ -483,7 +1066,7 @@ def get_vital_chart_data(patient_id: str, vital_type: str, days: int = 30) -> st
|
|
| 483 |
systolic_values = [r['value_quantity'] for r in systolic_rows]
|
| 484 |
|
| 485 |
# Get diastolic
|
| 486 |
-
cursor = conn.execute(
|
| 487 |
SELECT value_quantity, effective_date
|
| 488 |
FROM observations
|
| 489 |
WHERE patient_id = ? AND code = '8462-4'
|
|
@@ -497,11 +1080,9 @@ def get_vital_chart_data(patient_id: str, vital_type: str, days: int = 30) -> st
|
|
| 497 |
if not systolic and not diastolic:
|
| 498 |
return json_module.dumps({"error": "No blood pressure data found"})
|
| 499 |
|
| 500 |
-
# Compute statistics
|
| 501 |
systolic_stats = compute_stats(systolic_values)
|
| 502 |
diastolic_stats = compute_stats(diastolic_values)
|
| 503 |
|
| 504 |
-
# Put summary FIRST so LLM sees it prominently
|
| 505 |
summary_text = (
|
| 506 |
f"STATISTICS (use these exact values): "
|
| 507 |
f"Total readings: {systolic_stats['count']}. "
|
|
@@ -510,7 +1091,7 @@ def get_vital_chart_data(patient_id: str, vital_type: str, days: int = 30) -> st
|
|
| 510 |
)
|
| 511 |
|
| 512 |
return json_module.dumps({
|
| 513 |
-
"summary": summary_text,
|
| 514 |
"chart_type": "blood_pressure",
|
| 515 |
"title": f"Blood Pressure (Last {days} Days)",
|
| 516 |
"statistics": {
|
|
@@ -523,6 +1104,7 @@ def get_vital_chart_data(patient_id: str, vital_type: str, days: int = 30) -> st
|
|
| 523 |
]
|
| 524 |
})
|
| 525 |
else:
|
|
|
|
| 526 |
cursor = conn.execute(f"""
|
| 527 |
SELECT value_quantity, value_unit, effective_date, display
|
| 528 |
FROM observations
|
|
@@ -530,6 +1112,7 @@ def get_vital_chart_data(patient_id: str, vital_type: str, days: int = 30) -> st
|
|
| 530 |
AND effective_date >= ? AND value_quantity IS NOT NULL
|
| 531 |
ORDER BY effective_date ASC
|
| 532 |
""", [patient_id] + codes + [cutoff])
|
|
|
|
| 533 |
readings = cursor.fetchall()
|
| 534 |
if not readings:
|
| 535 |
return json_module.dumps({"error": f"No {vital_type} data found"})
|
|
@@ -539,10 +1122,8 @@ def get_vital_chart_data(patient_id: str, vital_type: str, days: int = 30) -> st
|
|
| 539 |
unit = readings[0]['value_unit'] if readings else ''
|
| 540 |
display = readings[0]['display'] if readings else vital_type
|
| 541 |
|
| 542 |
-
# Compute statistics
|
| 543 |
vital_stats = compute_stats(values)
|
| 544 |
|
| 545 |
-
# Put summary FIRST so LLM sees it prominently
|
| 546 |
summary_text = (
|
| 547 |
f"STATISTICS (use these exact values): "
|
| 548 |
f"Total readings: {vital_stats['count']}. "
|
|
@@ -550,7 +1131,7 @@ def get_vital_chart_data(patient_id: str, vital_type: str, days: int = 30) -> st
|
|
| 550 |
)
|
| 551 |
|
| 552 |
return json_module.dumps({
|
| 553 |
-
"summary": summary_text,
|
| 554 |
"chart_type": "line",
|
| 555 |
"title": f"{display} (Last {days} Days)",
|
| 556 |
"unit": unit,
|
|
@@ -561,31 +1142,25 @@ def get_vital_chart_data(patient_id: str, vital_type: str, days: int = 30) -> st
|
|
| 561 |
})
|
| 562 |
finally:
|
| 563 |
conn.close()
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
(
|
| 571 |
-
('
|
| 572 |
-
(
|
| 573 |
],
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
}
|
| 579 |
def get_lab_chart_data(patient_id: str, lab_type: str, periods: int = 4) -> str:
|
| 580 |
-
"""
|
| 581 |
-
Get lab results formatted for a BAR chart.
|
| 582 |
-
Shows comparison of lab values over time.
|
| 583 |
-
"""
|
| 584 |
-
import json as json_module
|
| 585 |
conn = get_db()
|
| 586 |
try:
|
| 587 |
if lab_type == 'all_latest':
|
| 588 |
-
# Get most recent value for each common lab
|
| 589 |
labs_to_show = [
|
| 590 |
('4548-4', 'HbA1c'),
|
| 591 |
('2093-3', 'Total Chol'),
|
|
@@ -598,153 +1173,70 @@ def get_lab_chart_data(patient_id: str, lab_type: str, periods: int = 4) -> str:
|
|
| 598 |
for code, label in labs_to_show:
|
| 599 |
cursor = conn.execute("""
|
| 600 |
SELECT value_quantity FROM observations
|
| 601 |
-
WHERE patient_id = ? AND code = ?
|
| 602 |
ORDER BY effective_date DESC LIMIT 1
|
| 603 |
""", (patient_id, code))
|
| 604 |
row = cursor.fetchone()
|
| 605 |
-
if row
|
| 606 |
data.append({"label": label, "value": row['value_quantity']})
|
|
|
|
| 607 |
if not data:
|
| 608 |
return json_module.dumps({"error": "No lab data found"})
|
| 609 |
-
return json_module.dumps({
|
| 610 |
-
"chart_type": "bar",
|
| 611 |
-
"title": "Latest Lab Results Comparison",
|
| 612 |
-
"datasets": [{"data": data, "color": "#667eea"}]
|
| 613 |
-
})
|
| 614 |
-
elif lab_type == 'cholesterol':
|
| 615 |
-
# Get cholesterol panel over time - grouped bar chart
|
| 616 |
-
datasets = []
|
| 617 |
-
colors = ['#e74c3c', '#27ae60', '#f39c12', '#9b59b6']
|
| 618 |
-
for i, (code, name, unit) in enumerate(LAB_CODES['cholesterol']):
|
| 619 |
-
cursor = conn.execute("""
|
| 620 |
-
SELECT value_quantity, effective_date FROM observations
|
| 621 |
-
WHERE patient_id = ? AND code = ?
|
| 622 |
-
ORDER BY effective_date DESC LIMIT ?
|
| 623 |
-
""", (patient_id, code, periods))
|
| 624 |
-
rows = cursor.fetchall()
|
| 625 |
-
if rows:
|
| 626 |
-
data = [{"date": r['effective_date'][:10], "value": r['value_quantity']}
|
| 627 |
-
for r in reversed(rows)]
|
| 628 |
-
datasets.append({
|
| 629 |
-
"label": name,
|
| 630 |
-
"data": data,
|
| 631 |
-
"color": colors[i]
|
| 632 |
-
})
|
| 633 |
-
if not datasets:
|
| 634 |
-
return json_module.dumps({"error": "No cholesterol data found"})
|
| 635 |
-
|
| 636 |
-
# Compute statistics for each cholesterol type
|
| 637 |
-
import statistics as stats_module
|
| 638 |
-
stats_summary = {}
|
| 639 |
-
summary_parts = []
|
| 640 |
-
for ds in datasets:
|
| 641 |
-
values = [d['value'] for d in ds['data']]
|
| 642 |
-
if values:
|
| 643 |
-
stats_summary[ds['label']] = {
|
| 644 |
-
"count": len(values),
|
| 645 |
-
"min": round(min(values), 1),
|
| 646 |
-
"max": round(max(values), 1),
|
| 647 |
-
"avg": round(stats_module.mean(values), 1),
|
| 648 |
-
"latest": round(values[-1], 1)
|
| 649 |
-
}
|
| 650 |
-
summary_parts.append(f"{ds['label']}: latest={stats_summary[ds['label']]['latest']} mg/dL")
|
| 651 |
-
|
| 652 |
-
summary_text = f"STATISTICS (use these exact values): {'; '.join(summary_parts)}."
|
| 653 |
|
| 654 |
return json_module.dumps({
|
| 655 |
-
"
|
| 656 |
-
"
|
| 657 |
-
"
|
| 658 |
-
"unit": "mg/dL",
|
| 659 |
-
"statistics": stats_summary,
|
| 660 |
-
"datasets": datasets
|
| 661 |
})
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
|
|
|
|
|
|
|
|
|
| 667 |
cursor = conn.execute("""
|
| 668 |
SELECT value_quantity, effective_date FROM observations
|
| 669 |
-
WHERE patient_id = ? AND code = ?
|
| 670 |
ORDER BY effective_date DESC LIMIT ?
|
| 671 |
""", (patient_id, code, periods))
|
| 672 |
rows = cursor.fetchall()
|
| 673 |
-
if not rows:
|
| 674 |
-
return json_module.dumps({"error": f"No {lab_type} data found"})
|
| 675 |
-
data = [{"date": r['effective_date'][:10], "value": r['value_quantity']}
|
| 676 |
-
for r in reversed(rows)]
|
| 677 |
-
values = [r['value_quantity'] for r in rows]
|
| 678 |
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
return json_module.dumps({
|
| 696 |
-
"summary": summary_text, # PUT FIRST
|
| 697 |
-
"chart_type": "bar",
|
| 698 |
-
"title": f"{name} History",
|
| 699 |
-
"unit": unit,
|
| 700 |
-
"statistics": lab_stats,
|
| 701 |
-
"datasets": [{"label": name, "data": data, "color": "#667eea"}]
|
| 702 |
-
})
|
| 703 |
-
else:
|
| 704 |
-
return json_module.dumps({
|
| 705 |
-
"error": f"Unknown lab type: {lab_type}. Use: cholesterol, a1c, glucose, kidney, all_latest"
|
| 706 |
-
})
|
| 707 |
finally:
|
| 708 |
conn.close()
|
| 709 |
-
|
| 710 |
-
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
|
| 717 |
-
'
|
| 718 |
-
|
| 719 |
-
|
| 720 |
-
|
| 721 |
-
|
| 722 |
-
|
| 723 |
-
'category': 'laboratory',
|
| 724 |
-
'unit': 'mg/dL'
|
| 725 |
-
},
|
| 726 |
-
'glucose': {
|
| 727 |
-
'codes': [('2345-7', 'Fasting Glucose'), ('1558-6', 'Fasting Glucose')],
|
| 728 |
-
'category': 'laboratory',
|
| 729 |
-
'unit': 'mg/dL'
|
| 730 |
-
},
|
| 731 |
-
'weight': {
|
| 732 |
-
'codes': [('29463-7', 'Weight')],
|
| 733 |
-
'category': 'vital-signs',
|
| 734 |
-
'unit': 'lb'
|
| 735 |
-
},
|
| 736 |
-
'heart_rate': {
|
| 737 |
-
'codes': [('8867-4', 'Heart Rate')],
|
| 738 |
-
'category': 'vital-signs',
|
| 739 |
-
'unit': '/min'
|
| 740 |
-
}
|
| 741 |
-
}
|
| 742 |
def compare_before_after_treatment(patient_id: str, medication_name: str, metric_type: str) -> str:
|
| 743 |
-
"""
|
| 744 |
-
Compare health metrics before vs after starting a medication.
|
| 745 |
-
Returns a bar chart showing the comparison.
|
| 746 |
-
"""
|
| 747 |
-
import json as json_module
|
| 748 |
conn = get_db()
|
| 749 |
try:
|
| 750 |
# Find the medication start date
|
|
@@ -752,24 +1244,37 @@ def compare_before_after_treatment(patient_id: str, medication_name: str, metric
|
|
| 752 |
SELECT display, start_date FROM medications
|
| 753 |
WHERE patient_id = ? AND LOWER(display) LIKE ?
|
| 754 |
ORDER BY start_date ASC LIMIT 1
|
| 755 |
-
""", (patient_id, f
|
|
|
|
| 756 |
med_row = cursor.fetchone()
|
| 757 |
if not med_row:
|
| 758 |
-
return json_module.dumps({
|
| 759 |
-
|
| 760 |
-
|
| 761 |
-
|
| 762 |
-
|
| 763 |
-
|
| 764 |
-
|
| 765 |
-
|
| 766 |
-
|
| 767 |
-
|
| 768 |
-
|
| 769 |
-
|
| 770 |
-
|
| 771 |
-
|
| 772 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 773 |
cursor = conn.execute("""
|
| 774 |
SELECT AVG(value_quantity) as avg_val, COUNT(*) as cnt
|
| 775 |
FROM observations
|
|
@@ -777,7 +1282,8 @@ def compare_before_after_treatment(patient_id: str, medication_name: str, metric
|
|
| 777 |
AND value_quantity IS NOT NULL
|
| 778 |
""", (patient_id, code, start_date))
|
| 779 |
before = cursor.fetchone()
|
| 780 |
-
|
|
|
|
| 781 |
cursor = conn.execute("""
|
| 782 |
SELECT AVG(value_quantity) as avg_val, COUNT(*) as cnt
|
| 783 |
FROM observations
|
|
@@ -785,266 +1291,303 @@ def compare_before_after_treatment(patient_id: str, medication_name: str, metric
|
|
| 785 |
AND value_quantity IS NOT NULL
|
| 786 |
""", (patient_id, code, start_date))
|
| 787 |
after = cursor.fetchone()
|
| 788 |
-
|
| 789 |
-
|
| 790 |
-
|
| 791 |
-
|
| 792 |
-
|
| 793 |
-
|
| 794 |
-
|
| 795 |
-
|
| 796 |
-
|
| 797 |
-
|
| 798 |
-
|
| 799 |
-
|
| 800 |
-
'after_count': after['cnt']
|
| 801 |
-
})
|
| 802 |
-
if not results:
|
| 803 |
-
return json_module.dumps({
|
| 804 |
-
"error": f"Not enough {metric_type} data before and after starting {med_name}"
|
| 805 |
-
})
|
| 806 |
-
# Build chart data
|
| 807 |
-
labels = []
|
| 808 |
-
before_data = []
|
| 809 |
-
after_data = []
|
| 810 |
-
for r in results:
|
| 811 |
-
labels.append(r['label'])
|
| 812 |
-
before_data.append(r['before'])
|
| 813 |
-
after_data.append(r['after'])
|
| 814 |
-
# Build summary text
|
| 815 |
-
summary_parts = []
|
| 816 |
-
for r in results:
|
| 817 |
-
direction = "↓" if r['change'] < 0 else "↑" if r['change'] > 0 else "→"
|
| 818 |
-
summary_parts.append(f"{r['label']}: {r['before']} → {r['after']} ({direction} {abs(r['change_pct'])}%)")
|
| 819 |
return json_module.dumps({
|
| 820 |
-
"chart_type": "
|
| 821 |
-
"title": f"{metric_type.
|
| 822 |
-
"
|
| 823 |
-
"
|
| 824 |
-
"
|
| 825 |
-
"labels": labels,
|
| 826 |
"datasets": [
|
| 827 |
-
{"label":
|
| 828 |
-
{"label": "After
|
| 829 |
-
]
|
| 830 |
-
"summary": summary_parts
|
| 831 |
})
|
| 832 |
finally:
|
| 833 |
conn.close()
|
| 834 |
-
# ============================================================================
|
| 835 |
-
# Skin Analysis Tool (uses Derm Foundation + SCIN Classifier via Health Foundation Server)
|
| 836 |
-
# ============================================================================
|
| 837 |
|
| 838 |
-
# Environment variable for the health foundation server
|
| 839 |
-
HEALTH_FOUNDATION_URL = os.getenv("HEALTH_FOUNDATION_URL", "http://localhost:8082")
|
| 840 |
|
| 841 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 842 |
"""
|
| 843 |
-
|
|
|
|
| 844 |
|
| 845 |
-
This
|
| 846 |
-
1.
|
| 847 |
-
2.
|
| 848 |
-
3.
|
| 849 |
-
|
| 850 |
-
5. Returns structured data + LLM prompt for synthesis
|
| 851 |
|
| 852 |
-
|
| 853 |
-
|
| 854 |
-
|
| 855 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 856 |
|
| 857 |
-
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
|
| 861 |
-
|
| 862 |
-
|
|
|
|
|
|
|
|
|
|
| 863 |
|
| 864 |
-
|
| 865 |
-
|
| 866 |
-
if
|
| 867 |
-
|
| 868 |
-
|
| 869 |
-
|
| 870 |
-
|
| 871 |
-
|
| 872 |
-
|
| 873 |
-
|
| 874 |
-
|
| 875 |
-
|
| 876 |
-
|
| 877 |
-
|
| 878 |
-
"
|
| 879 |
-
"
|
| 880 |
}
|
| 881 |
-
|
| 882 |
-
response = client.post(
|
| 883 |
-
f"{HEALTH_FOUNDATION_URL}/analyze/skin/classify",
|
| 884 |
-
files=files,
|
| 885 |
-
data=data,
|
| 886 |
-
headers={"ngrok-skip-browser-warning": "true"}
|
| 887 |
-
)
|
| 888 |
-
|
| 889 |
-
# If classifier not available, fall back to basic embedding analysis
|
| 890 |
-
if response.status_code == 503 or (response.status_code == 200 and "classifier not loaded" in response.text.lower()):
|
| 891 |
-
# Fallback to basic embedding analysis
|
| 892 |
-
files = {"image": ("skin_image.png", image_bytes, "image/png")}
|
| 893 |
-
response = client.post(
|
| 894 |
-
f"{HEALTH_FOUNDATION_URL}/analyze/skin",
|
| 895 |
-
files=files,
|
| 896 |
-
data={"include_embedding": "false"},
|
| 897 |
-
headers={"ngrok-skip-browser-warning": "true"}
|
| 898 |
-
)
|
| 899 |
-
response.raise_for_status()
|
| 900 |
-
result = response.json()
|
| 901 |
-
|
| 902 |
-
if not result.get("success"):
|
| 903 |
-
return json_module.dumps({
|
| 904 |
-
"error": result.get("error", "Analysis failed"),
|
| 905 |
-
"disclaimer": "⚠️ FOR RESEARCH USE ONLY - NOT A DIAGNOSTIC TOOL"
|
| 906 |
-
})
|
| 907 |
-
|
| 908 |
-
# Format basic response
|
| 909 |
-
quality = result.get("image_quality", {})
|
| 910 |
-
return json_module.dumps({
|
| 911 |
-
"status": "success",
|
| 912 |
-
"analysis_type": "embedding_only",
|
| 913 |
-
"model": "Derm Foundation (classifier unavailable)",
|
| 914 |
-
"image_quality_score": quality.get("score", 0),
|
| 915 |
-
"image_quality_notes": quality.get("notes", []),
|
| 916 |
-
"conditions": [],
|
| 917 |
-
"symptoms_detected": [],
|
| 918 |
-
"body_parts_detected": [],
|
| 919 |
-
"user_reported_symptoms": symptoms,
|
| 920 |
-
"llm_synthesis_prompt": (
|
| 921 |
-
f"The skin image was analyzed but the condition classifier is unavailable. "
|
| 922 |
-
f"Image quality score: {quality.get('score', 0)}/100. "
|
| 923 |
-
f"User described: '{symptoms}'. "
|
| 924 |
-
f"Please acknowledge their concern, note that specific condition identification isn't available, "
|
| 925 |
-
f"and recommend they consult a dermatologist for a proper evaluation."
|
| 926 |
-
),
|
| 927 |
-
"summary": "Image processed (embedding only - classifier unavailable)",
|
| 928 |
-
"disclaimer": "⚠️ FOR RESEARCH USE ONLY - NOT A DIAGNOSTIC TOOL"
|
| 929 |
-
})
|
| 930 |
-
|
| 931 |
-
response.raise_for_status()
|
| 932 |
-
result = response.json()
|
| 933 |
|
| 934 |
-
|
| 935 |
-
|
| 936 |
-
|
| 937 |
-
"
|
| 938 |
-
|
|
|
|
| 939 |
|
| 940 |
-
#
|
| 941 |
-
|
| 942 |
-
|
| 943 |
-
|
| 944 |
-
|
| 945 |
-
|
| 946 |
-
|
| 947 |
-
|
| 948 |
-
|
| 949 |
-
|
| 950 |
-
|
| 951 |
-
|
| 952 |
-
|
| 953 |
-
|
| 954 |
-
|
| 955 |
-
|
| 956 |
-
|
| 957 |
-
|
| 958 |
-
|
| 959 |
-
|
| 960 |
-
|
| 961 |
-
|
| 962 |
-
|
| 963 |
-
|
| 964 |
-
|
|
|
|
| 965 |
|
| 966 |
-
|
| 967 |
-
|
| 968 |
-
|
| 969 |
-
|
| 970 |
-
|
| 971 |
|
| 972 |
-
#
|
| 973 |
-
|
| 974 |
-
{"
|
| 975 |
-
|
| 976 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 977 |
|
| 978 |
-
#
|
| 979 |
-
"
|
| 980 |
-
|
| 981 |
-
"body_parts": user_reported.get("body_parts", []),
|
| 982 |
-
"duration": user_reported.get("duration"),
|
| 983 |
-
"raw_description": user_reported.get("raw_text", symptoms)
|
| 984 |
-
},
|
| 985 |
|
| 986 |
-
#
|
| 987 |
-
|
| 988 |
-
|
| 989 |
-
|
| 990 |
-
|
| 991 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 992 |
|
| 993 |
-
#
|
| 994 |
-
|
| 995 |
-
"
|
| 996 |
-
"
|
| 997 |
-
|
|
|
|
| 998 |
|
| 999 |
-
|
| 1000 |
-
"summary": summary,
|
| 1001 |
|
| 1002 |
-
|
| 1003 |
-
|
|
|
|
|
|
|
|
|
|
| 1004 |
|
| 1005 |
-
|
| 1006 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1007 |
|
| 1008 |
-
|
|
|
|
|
|
|
|
|
|
| 1009 |
|
| 1010 |
-
|
| 1011 |
-
|
| 1012 |
-
|
| 1013 |
-
|
| 1014 |
-
|
| 1015 |
-
|
| 1016 |
-
|
| 1017 |
-
|
| 1018 |
-
|
| 1019 |
-
|
| 1020 |
-
|
| 1021 |
-
|
| 1022 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1023 |
|
| 1024 |
|
| 1025 |
-
#
|
| 1026 |
-
|
| 1027 |
-
|
| 1028 |
-
|
| 1029 |
-
|
| 1030 |
-
|
| 1031 |
-
|
| 1032 |
-
|
| 1033 |
-
|
| 1034 |
-
"
|
| 1035 |
-
|
| 1036 |
-
|
| 1037 |
-
|
| 1038 |
-
|
| 1039 |
-
"
|
| 1040 |
-
|
| 1041 |
-
|
| 1042 |
-
|
| 1043 |
-
|
| 1044 |
-
|
| 1045 |
-
|
| 1046 |
-
func = TOOL_FUNCTIONS[tool_name]
|
| 1047 |
-
result = func(**args)
|
| 1048 |
-
return result
|
| 1049 |
-
except Exception as e:
|
| 1050 |
-
return f"Error executing {tool_name}: {str(e)}"
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
Health data tools for the MedGemma agent.
|
| 4 |
+
|
| 5 |
+
Enhanced with:
|
| 6 |
+
1. Dynamic Tool Registry - Tools can be registered/unregistered at runtime
|
| 7 |
+
2. Tool Search - Reduce token usage by searching for relevant tools
|
| 8 |
+
3. MCP Compatibility - Ready for Model Context Protocol integration
|
| 9 |
+
|
| 10 |
These tools allow the LLM to query specific data rather than
|
| 11 |
loading everything into context at once.
|
| 12 |
"""
|
| 13 |
import sqlite3
|
| 14 |
+
import json as json_module
|
| 15 |
+
import statistics as stats_module
|
| 16 |
from datetime import datetime, timedelta
|
| 17 |
+
from typing import Optional, Callable, Dict, Any, List, Set
|
| 18 |
+
from dataclasses import dataclass, field
|
| 19 |
import os
|
| 20 |
+
import re
|
| 21 |
+
|
| 22 |
DB_PATH = os.getenv("DB_PATH", "data/fhir.db")
|
| 23 |
+
|
| 24 |
def get_db():
|
| 25 |
"""Get database connection."""
|
| 26 |
conn = sqlite3.connect(DB_PATH)
|
| 27 |
conn.row_factory = sqlite3.Row
|
| 28 |
return conn
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# =============================================================================
|
| 32 |
+
# DYNAMIC TOOL REGISTRY WITH MCP COMPATIBILITY
|
| 33 |
+
# =============================================================================
|
| 34 |
+
|
| 35 |
+
@dataclass
|
| 36 |
+
class ToolParameter:
|
| 37 |
+
"""Definition of a tool parameter."""
|
| 38 |
+
name: str
|
| 39 |
+
type: str # "string", "integer", "boolean", "array"
|
| 40 |
+
description: str
|
| 41 |
+
required: bool = True
|
| 42 |
+
default: Any = None
|
| 43 |
+
enum: List[str] = None # For constrained values
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@dataclass
|
| 47 |
+
class ToolDefinition:
|
| 48 |
+
"""
|
| 49 |
+
Complete definition of a tool.
|
| 50 |
+
MCP-compatible structure for future integration.
|
| 51 |
+
"""
|
| 52 |
+
name: str
|
| 53 |
+
description: str
|
| 54 |
+
parameters: List[ToolParameter]
|
| 55 |
+
handler: Callable
|
| 56 |
+
category: str = "general"
|
| 57 |
+
requires_patient_id: bool = True
|
| 58 |
+
returns_chart: bool = False
|
| 59 |
+
returns_json: bool = False
|
| 60 |
+
version: str = "1.0.0"
|
| 61 |
+
|
| 62 |
+
# MCP-specific fields
|
| 63 |
+
mcp_compatible: bool = True
|
| 64 |
+
mcp_annotations: Dict[str, Any] = field(default_factory=dict)
|
| 65 |
+
|
| 66 |
+
def to_mcp_schema(self) -> Dict:
|
| 67 |
+
"""Convert to MCP tool schema format."""
|
| 68 |
+
properties = {}
|
| 69 |
+
required = []
|
| 70 |
+
|
| 71 |
+
for param in self.parameters:
|
| 72 |
+
prop = {
|
| 73 |
+
"type": param.type,
|
| 74 |
+
"description": param.description
|
| 75 |
+
}
|
| 76 |
+
if param.enum:
|
| 77 |
+
prop["enum"] = param.enum
|
| 78 |
+
if param.default is not None:
|
| 79 |
+
prop["default"] = param.default
|
| 80 |
+
|
| 81 |
+
properties[param.name] = prop
|
| 82 |
+
if param.required:
|
| 83 |
+
required.append(param.name)
|
| 84 |
+
|
| 85 |
+
return {
|
| 86 |
+
"name": self.name,
|
| 87 |
+
"description": self.description,
|
| 88 |
+
"inputSchema": {
|
| 89 |
+
"type": "object",
|
| 90 |
+
"properties": properties,
|
| 91 |
+
"required": required
|
| 92 |
+
},
|
| 93 |
+
"annotations": {
|
| 94 |
+
"category": self.category,
|
| 95 |
+
"returnsChart": self.returns_chart,
|
| 96 |
+
"version": self.version,
|
| 97 |
+
**self.mcp_annotations
|
| 98 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
}
|
| 100 |
+
|
| 101 |
+
def to_llm_description(self, detail_level: str = "full") -> str:
|
| 102 |
+
"""Generate description for LLM context."""
|
| 103 |
+
if detail_level == "name_only":
|
| 104 |
+
return self.name
|
| 105 |
+
|
| 106 |
+
if detail_level == "brief":
|
| 107 |
+
return f"- {self.name}: {self.description[:80]}..."
|
| 108 |
+
|
| 109 |
+
# Full description
|
| 110 |
+
params_str = ", ".join([
|
| 111 |
+
f"{p.name}: {p.description}" + (" (optional)" if not p.required else "")
|
| 112 |
+
for p in self.parameters
|
| 113 |
+
])
|
| 114 |
+
return f"- {self.name}: {self.description}\n Parameters: {params_str}"
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class DynamicToolRegistry:
|
| 118 |
+
"""
|
| 119 |
+
Dynamic registry for tool management.
|
| 120 |
+
|
| 121 |
+
Features:
|
| 122 |
+
- Runtime tool registration/unregistration
|
| 123 |
+
- Category-based filtering
|
| 124 |
+
- Semantic search for relevant tools
|
| 125 |
+
- MCP-compatible schema generation
|
| 126 |
+
- Context-aware tool selection
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
def __init__(self):
|
| 130 |
+
self._tools: Dict[str, ToolDefinition] = {}
|
| 131 |
+
self._categories: Dict[str, Set[str]] = {}
|
| 132 |
+
self._keyword_index: Dict[str, Set[str]] = {} # keyword -> tool names
|
| 133 |
+
|
| 134 |
+
def register(self,
|
| 135 |
+
name: str,
|
| 136 |
+
description: str,
|
| 137 |
+
parameters: List[ToolParameter],
|
| 138 |
+
category: str = "general",
|
| 139 |
+
requires_patient_id: bool = True,
|
| 140 |
+
returns_chart: bool = False,
|
| 141 |
+
returns_json: bool = False,
|
| 142 |
+
mcp_annotations: Dict = None):
|
| 143 |
+
"""
|
| 144 |
+
Decorator for registering tools dynamically.
|
| 145 |
+
|
| 146 |
+
Usage:
|
| 147 |
+
@registry.register(
|
| 148 |
+
name="get_conditions",
|
| 149 |
+
description="Get patient conditions",
|
| 150 |
+
parameters=[ToolParameter("patient_id", "string", "Patient ID")],
|
| 151 |
+
category="medical_records"
|
| 152 |
+
)
|
| 153 |
+
def get_conditions(patient_id: str) -> str:
|
| 154 |
+
...
|
| 155 |
+
"""
|
| 156 |
+
def decorator(func: Callable) -> Callable:
|
| 157 |
+
tool = ToolDefinition(
|
| 158 |
+
name=name,
|
| 159 |
+
description=description,
|
| 160 |
+
parameters=parameters,
|
| 161 |
+
handler=func,
|
| 162 |
+
category=category,
|
| 163 |
+
requires_patient_id=requires_patient_id,
|
| 164 |
+
returns_chart=returns_chart,
|
| 165 |
+
returns_json=returns_json,
|
| 166 |
+
mcp_annotations=mcp_annotations or {}
|
| 167 |
+
)
|
| 168 |
+
self._register_tool(tool)
|
| 169 |
+
return func
|
| 170 |
+
return decorator
|
| 171 |
+
|
| 172 |
+
def _register_tool(self, tool: ToolDefinition):
|
| 173 |
+
"""Internal method to register a tool and update indices."""
|
| 174 |
+
self._tools[tool.name] = tool
|
| 175 |
+
|
| 176 |
+
# Update category index
|
| 177 |
+
if tool.category not in self._categories:
|
| 178 |
+
self._categories[tool.category] = set()
|
| 179 |
+
self._categories[tool.category].add(tool.name)
|
| 180 |
+
|
| 181 |
+
# Update keyword index for search
|
| 182 |
+
keywords = self._extract_keywords(f"{tool.name} {tool.description}")
|
| 183 |
+
for keyword in keywords:
|
| 184 |
+
if keyword not in self._keyword_index:
|
| 185 |
+
self._keyword_index[keyword] = set()
|
| 186 |
+
self._keyword_index[keyword].add(tool.name)
|
| 187 |
+
|
| 188 |
+
def _extract_keywords(self, text: str) -> Set[str]:
|
| 189 |
+
"""Extract searchable keywords from text."""
|
| 190 |
+
# Lowercase and split
|
| 191 |
+
words = re.findall(r'\b\w+\b', text.lower())
|
| 192 |
+
# Filter stop words
|
| 193 |
+
stop_words = {'the', 'a', 'an', 'is', 'are', 'for', 'to', 'of', 'and', 'or', 'in', 'on', 'with'}
|
| 194 |
+
return {w for w in words if w not in stop_words and len(w) > 2}
|
| 195 |
+
|
| 196 |
+
def unregister(self, name: str) -> bool:
|
| 197 |
+
"""Remove a tool from the registry."""
|
| 198 |
+
if name not in self._tools:
|
| 199 |
+
return False
|
| 200 |
+
|
| 201 |
+
tool = self._tools[name]
|
| 202 |
+
|
| 203 |
+
# Remove from category index
|
| 204 |
+
if tool.category in self._categories:
|
| 205 |
+
self._categories[tool.category].discard(name)
|
| 206 |
+
|
| 207 |
+
# Remove from keyword index
|
| 208 |
+
for keyword_set in self._keyword_index.values():
|
| 209 |
+
keyword_set.discard(name)
|
| 210 |
+
|
| 211 |
+
del self._tools[name]
|
| 212 |
+
return True
|
| 213 |
+
|
| 214 |
+
def get(self, name: str) -> Optional[ToolDefinition]:
|
| 215 |
+
"""Get a specific tool by name."""
|
| 216 |
+
return self._tools.get(name)
|
| 217 |
+
|
| 218 |
+
def get_all(self) -> List[ToolDefinition]:
|
| 219 |
+
"""Get all registered tools."""
|
| 220 |
+
return list(self._tools.values())
|
| 221 |
+
|
| 222 |
+
def get_by_category(self, category: str) -> List[ToolDefinition]:
|
| 223 |
+
"""Get all tools in a category."""
|
| 224 |
+
tool_names = self._categories.get(category, set())
|
| 225 |
+
return [self._tools[name] for name in tool_names]
|
| 226 |
+
|
| 227 |
+
def get_categories(self) -> List[str]:
|
| 228 |
+
"""Get all available categories."""
|
| 229 |
+
return list(self._categories.keys())
|
| 230 |
+
|
| 231 |
+
def search(self, query: str, max_results: int = 5) -> List[ToolDefinition]:
|
| 232 |
+
"""
|
| 233 |
+
Search for tools matching a query.
|
| 234 |
+
Uses keyword matching with relevance scoring.
|
| 235 |
+
"""
|
| 236 |
+
query_keywords = self._extract_keywords(query)
|
| 237 |
+
|
| 238 |
+
# Score each tool by keyword matches
|
| 239 |
+
scores: Dict[str, int] = {}
|
| 240 |
+
for keyword in query_keywords:
|
| 241 |
+
matching_tools = self._keyword_index.get(keyword, set())
|
| 242 |
+
for tool_name in matching_tools:
|
| 243 |
+
scores[tool_name] = scores.get(tool_name, 0) + 1
|
| 244 |
+
|
| 245 |
+
# Also check for exact name matches (higher weight)
|
| 246 |
+
for tool_name in self._tools:
|
| 247 |
+
if query.lower() in tool_name.lower():
|
| 248 |
+
scores[tool_name] = scores.get(tool_name, 0) + 3
|
| 249 |
+
|
| 250 |
+
# Sort by score and return top results
|
| 251 |
+
sorted_tools = sorted(
|
| 252 |
+
[(name, score) for name, score in scores.items()],
|
| 253 |
+
key=lambda x: -x[1]
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
return [self._tools[name] for name, _ in sorted_tools[:max_results]]
|
| 257 |
+
|
| 258 |
+
def get_tools_for_context(self,
|
| 259 |
+
categories: List[str] = None,
|
| 260 |
+
query_keywords: List[str] = None,
|
| 261 |
+
max_tools: int = 10) -> List[ToolDefinition]:
|
| 262 |
+
"""
|
| 263 |
+
Get tools filtered by context.
|
| 264 |
+
Used to reduce token usage by only including relevant tools.
|
| 265 |
+
"""
|
| 266 |
+
if categories:
|
| 267 |
+
tools = []
|
| 268 |
+
for cat in categories:
|
| 269 |
+
tools.extend(self.get_by_category(cat))
|
| 270 |
+
else:
|
| 271 |
+
tools = self.get_all()
|
| 272 |
+
|
| 273 |
+
if query_keywords:
|
| 274 |
+
# Score by relevance
|
| 275 |
+
def relevance_score(tool: ToolDefinition) -> int:
|
| 276 |
+
text = f"{tool.name} {tool.description}".lower()
|
| 277 |
+
return sum(1 for kw in query_keywords if kw.lower() in text)
|
| 278 |
+
|
| 279 |
+
tools = sorted(tools, key=relevance_score, reverse=True)
|
| 280 |
+
|
| 281 |
+
return tools[:max_tools]
|
| 282 |
+
|
| 283 |
+
def execute(self, tool_name: str, args: Dict[str, Any]) -> str:
|
| 284 |
+
"""Execute a tool by name with given arguments."""
|
| 285 |
+
tool = self._tools.get(tool_name)
|
| 286 |
+
if not tool:
|
| 287 |
+
return json_module.dumps({"error": f"Unknown tool: {tool_name}"})
|
| 288 |
+
|
| 289 |
+
try:
|
| 290 |
+
result = tool.handler(**args)
|
| 291 |
+
return result
|
| 292 |
+
except Exception as e:
|
| 293 |
+
return json_module.dumps({"error": f"Error executing {tool_name}: {str(e)}"})
|
| 294 |
+
|
| 295 |
+
# =========================================================================
|
| 296 |
+
# MCP Compatibility Methods
|
| 297 |
+
# =========================================================================
|
| 298 |
+
|
| 299 |
+
def to_mcp_tools_list(self) -> List[Dict]:
|
| 300 |
+
"""Generate MCP-compatible tools list."""
|
| 301 |
+
return [tool.to_mcp_schema() for tool in self._tools.values()]
|
| 302 |
+
|
| 303 |
+
def handle_mcp_tool_call(self, tool_name: str, arguments: Dict) -> Dict:
|
| 304 |
+
"""
|
| 305 |
+
Handle an MCP tool call request.
|
| 306 |
+
Returns MCP-compatible response format.
|
| 307 |
+
"""
|
| 308 |
+
tool = self._tools.get(tool_name)
|
| 309 |
+
if not tool:
|
| 310 |
+
return {
|
| 311 |
+
"isError": True,
|
| 312 |
+
"content": [{"type": "text", "text": f"Unknown tool: {tool_name}"}]
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
try:
|
| 316 |
+
result = tool.handler(**arguments)
|
| 317 |
+
|
| 318 |
+
# Determine content type
|
| 319 |
+
if tool.returns_json:
|
| 320 |
+
try:
|
| 321 |
+
parsed = json_module.loads(result)
|
| 322 |
+
return {
|
| 323 |
+
"content": [{"type": "text", "text": json_module.dumps(parsed, indent=2)}]
|
| 324 |
+
}
|
| 325 |
+
except:
|
| 326 |
+
pass
|
| 327 |
+
|
| 328 |
+
return {
|
| 329 |
+
"content": [{"type": "text", "text": result}]
|
| 330 |
+
}
|
| 331 |
+
except Exception as e:
|
| 332 |
+
return {
|
| 333 |
+
"isError": True,
|
| 334 |
+
"content": [{"type": "text", "text": f"Error: {str(e)}"}]
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
def generate_mcp_server_info(self) -> Dict:
|
| 338 |
+
"""Generate MCP server information."""
|
| 339 |
+
return {
|
| 340 |
+
"name": "medgemma-health-tools",
|
| 341 |
+
"version": "1.0.0",
|
| 342 |
+
"description": "Health data tools for MedGemma medical AI assistant",
|
| 343 |
+
"capabilities": {
|
| 344 |
+
"tools": True,
|
| 345 |
+
"resources": False,
|
| 346 |
+
"prompts": False
|
| 347 |
+
}
|
| 348 |
}
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
# =============================================================================
|
| 352 |
+
# GLOBAL REGISTRY INSTANCE
|
| 353 |
+
# =============================================================================
|
| 354 |
+
|
| 355 |
+
registry = DynamicToolRegistry()
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
# =============================================================================
|
| 359 |
+
# TOOL SEARCH FUNCTIONS (Reduce Token Usage)
|
| 360 |
+
# =============================================================================
|
| 361 |
+
|
| 362 |
+
def search_tools(query: str, category: str = None, max_results: int = 5) -> str:
|
| 363 |
+
"""
|
| 364 |
+
Search for tools matching a query.
|
| 365 |
+
Returns condensed tool info to reduce token usage.
|
| 366 |
+
|
| 367 |
+
This is a META-TOOL that helps the agent find relevant tools
|
| 368 |
+
without loading all tool definitions into context.
|
| 369 |
+
"""
|
| 370 |
+
if category:
|
| 371 |
+
tools = registry.get_by_category(category)
|
| 372 |
+
# Filter by query within category
|
| 373 |
+
query_lower = query.lower()
|
| 374 |
+
tools = [t for t in tools if query_lower in t.name.lower() or query_lower in t.description.lower()]
|
| 375 |
+
else:
|
| 376 |
+
tools = registry.search(query, max_results)
|
| 377 |
+
|
| 378 |
+
if not tools:
|
| 379 |
+
return json_module.dumps({
|
| 380 |
+
"matches": [],
|
| 381 |
+
"hint": "No tools found. Try broader search terms.",
|
| 382 |
+
"available_categories": registry.get_categories()
|
| 383 |
+
})
|
| 384 |
+
|
| 385 |
+
return json_module.dumps({
|
| 386 |
+
"matches": [
|
| 387 |
+
{
|
| 388 |
+
"name": t.name,
|
| 389 |
+
"description": t.description[:100] + "..." if len(t.description) > 100 else t.description,
|
| 390 |
+
"category": t.category,
|
| 391 |
+
"returns_chart": t.returns_chart
|
| 392 |
+
}
|
| 393 |
+
for t in tools[:max_results]
|
| 394 |
+
],
|
| 395 |
+
"hint": "Use GET_TOOL_SCHEMA to get full parameters for a specific tool."
|
| 396 |
+
})
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def get_tool_schema(tool_name: str) -> str:
|
| 400 |
+
"""
|
| 401 |
+
Get the full schema for a specific tool.
|
| 402 |
+
Called on-demand to reduce initial context size.
|
| 403 |
+
"""
|
| 404 |
+
tool = registry.get(tool_name)
|
| 405 |
+
if not tool:
|
| 406 |
+
return json_module.dumps({
|
| 407 |
+
"error": f"Tool '{tool_name}' not found",
|
| 408 |
+
"available_tools": [t.name for t in registry.get_all()]
|
| 409 |
+
})
|
| 410 |
+
|
| 411 |
+
return json_module.dumps({
|
| 412 |
+
"name": tool.name,
|
| 413 |
+
"description": tool.description,
|
| 414 |
+
"parameters": [
|
| 415 |
+
{
|
| 416 |
+
"name": p.name,
|
| 417 |
+
"type": p.type,
|
| 418 |
+
"description": p.description,
|
| 419 |
+
"required": p.required,
|
| 420 |
+
"default": p.default
|
| 421 |
+
}
|
| 422 |
+
for p in tool.parameters
|
| 423 |
+
],
|
| 424 |
+
"category": tool.category,
|
| 425 |
+
"returns_chart": tool.returns_chart,
|
| 426 |
+
"returns_json": tool.returns_json
|
| 427 |
+
})
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def list_tool_categories() -> str:
|
| 431 |
+
"""List all available tool categories with tool counts."""
|
| 432 |
+
categories = {}
|
| 433 |
+
for cat in registry.get_categories():
|
| 434 |
+
tools = registry.get_by_category(cat)
|
| 435 |
+
categories[cat] = {
|
| 436 |
+
"count": len(tools),
|
| 437 |
+
"tools": [t.name for t in tools]
|
| 438 |
}
|
| 439 |
+
return json_module.dumps(categories)
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
# =============================================================================
|
| 443 |
+
# TOOL DESCRIPTIONS GENERATOR (for LLM prompts)
|
| 444 |
+
# =============================================================================
|
| 445 |
+
|
| 446 |
+
def get_tools_description(detail_level: str = "full",
|
| 447 |
+
categories: List[str] = None,
|
| 448 |
+
max_tools: int = None) -> str:
|
| 449 |
+
"""
|
| 450 |
+
Generate a description of available tools for the LLM.
|
| 451 |
+
|
| 452 |
+
Args:
|
| 453 |
+
detail_level: "name_only", "brief", or "full"
|
| 454 |
+
categories: Filter to specific categories
|
| 455 |
+
max_tools: Limit number of tools shown
|
| 456 |
+
"""
|
| 457 |
+
if categories:
|
| 458 |
+
tools = []
|
| 459 |
+
for cat in categories:
|
| 460 |
+
tools.extend(registry.get_by_category(cat))
|
| 461 |
+
else:
|
| 462 |
+
tools = registry.get_all()
|
| 463 |
+
|
| 464 |
+
if max_tools:
|
| 465 |
+
tools = tools[:max_tools]
|
| 466 |
+
|
| 467 |
lines = ["Available tools:\n"]
|
| 468 |
+
for tool in tools:
|
| 469 |
+
lines.append(tool.to_llm_description(detail_level))
|
| 470 |
+
lines.append("")
|
| 471 |
+
|
| 472 |
return "\n".join(lines)
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
def get_condensed_tools_prompt() -> str:
|
| 476 |
+
"""
|
| 477 |
+
Generate a minimal tools prompt that uses search instead of listing all tools.
|
| 478 |
+
This significantly reduces token usage for agents with many tools.
|
| 479 |
+
"""
|
| 480 |
+
return """You have access to health data tools. Instead of all tools being listed here,
|
| 481 |
+
use these META-TOOLS to find what you need:
|
| 482 |
+
|
| 483 |
+
1. SEARCH_TOOLS: {"query": "search term", "category": "optional_category"}
|
| 484 |
+
- Search for relevant tools by keyword
|
| 485 |
+
- Returns tool names and brief descriptions
|
| 486 |
+
|
| 487 |
+
2. GET_TOOL_SCHEMA: {"tool_name": "name"}
|
| 488 |
+
- Get full parameters for a specific tool
|
| 489 |
+
- Call this before using a tool you found via search
|
| 490 |
+
|
| 491 |
+
3. LIST_CATEGORIES: {}
|
| 492 |
+
- See all tool categories: vitals, labs, medications, conditions, charts, analysis
|
| 493 |
+
|
| 494 |
+
WORKFLOW:
|
| 495 |
+
1. Search for relevant tools based on user's question
|
| 496 |
+
2. Get the schema for tools you want to use
|
| 497 |
+
3. Call the tool with proper parameters
|
| 498 |
+
|
| 499 |
+
Tool categories available: """ + ", ".join(registry.get_categories())
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
# =============================================================================
|
| 503 |
+
# VITAL SIGN CODES
|
| 504 |
+
# =============================================================================
|
| 505 |
+
|
| 506 |
+
VITAL_CODES = {
|
| 507 |
+
'blood_pressure': ['8480-6', '8462-4', '85354-9'],
|
| 508 |
+
'blood_pressure_systolic': ['8480-6'],
|
| 509 |
+
'blood_pressure_diastolic': ['8462-4'],
|
| 510 |
+
'heart_rate': ['8867-4'],
|
| 511 |
+
'temperature': ['8310-5', '8331-1'],
|
| 512 |
+
'weight': ['29463-7'],
|
| 513 |
+
'height': ['8302-2'],
|
| 514 |
+
'respiratory_rate': ['9279-1'],
|
| 515 |
+
'oxygen_saturation': ['2708-6', '59408-5'],
|
| 516 |
+
'bmi': ['39156-5']
|
| 517 |
+
}
|
| 518 |
+
|
| 519 |
+
# Lab codes for bar charts
|
| 520 |
+
LAB_CODES = {
|
| 521 |
+
'a1c': [('4548-4', 'HbA1c', '%')],
|
| 522 |
+
'glucose': [('2345-7', 'Fasting Glucose', 'mg/dL'), ('1558-6', 'Fasting Glucose', 'mg/dL')],
|
| 523 |
+
'cholesterol': [
|
| 524 |
+
('2093-3', 'Total Cholesterol', 'mg/dL'),
|
| 525 |
+
('2085-9', 'HDL', 'mg/dL'),
|
| 526 |
+
('13457-7', 'LDL', 'mg/dL'),
|
| 527 |
+
('2571-8', 'Triglycerides', 'mg/dL')
|
| 528 |
+
],
|
| 529 |
+
'kidney': [
|
| 530 |
+
('2160-0', 'Creatinine', 'mg/dL'),
|
| 531 |
+
('33914-3', 'eGFR', 'mL/min')
|
| 532 |
+
]
|
| 533 |
+
}
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
# =============================================================================
|
| 537 |
+
# REGISTERED TOOLS
|
| 538 |
+
# =============================================================================
|
| 539 |
+
|
| 540 |
+
@registry.register(
|
| 541 |
+
name="search_tools",
|
| 542 |
+
description="Search for available tools by keyword. Use this to find relevant tools without loading all tool definitions. Returns tool names and brief descriptions.",
|
| 543 |
+
parameters=[
|
| 544 |
+
ToolParameter("query", "string", "Search keywords (e.g., 'blood pressure', 'medications', 'chart')"),
|
| 545 |
+
ToolParameter("category", "string", "Optional category filter", required=False),
|
| 546 |
+
ToolParameter("max_results", "integer", "Maximum results to return", required=False, default=5)
|
| 547 |
+
],
|
| 548 |
+
category="meta",
|
| 549 |
+
requires_patient_id=False,
|
| 550 |
+
returns_json=True
|
| 551 |
+
)
|
| 552 |
+
def _search_tools(query: str, category: str = None, max_results: int = 5) -> str:
|
| 553 |
+
return search_tools(query, category, max_results)
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
@registry.register(
|
| 557 |
+
name="get_tool_schema",
|
| 558 |
+
description="Get the full parameter schema for a specific tool. Call this after search_tools to get details before using a tool.",
|
| 559 |
+
parameters=[
|
| 560 |
+
ToolParameter("tool_name", "string", "Name of the tool to get schema for")
|
| 561 |
+
],
|
| 562 |
+
category="meta",
|
| 563 |
+
requires_patient_id=False,
|
| 564 |
+
returns_json=True
|
| 565 |
+
)
|
| 566 |
+
def _get_tool_schema(tool_name: str) -> str:
|
| 567 |
+
return get_tool_schema(tool_name)
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
@registry.register(
|
| 571 |
+
name="list_tool_categories",
|
| 572 |
+
description="List all available tool categories and their tools. Useful for understanding what data is accessible.",
|
| 573 |
+
parameters=[],
|
| 574 |
+
category="meta",
|
| 575 |
+
requires_patient_id=False,
|
| 576 |
+
returns_json=True
|
| 577 |
+
)
|
| 578 |
+
def _list_tool_categories() -> str:
|
| 579 |
+
return list_tool_categories()
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
@registry.register(
|
| 583 |
+
name="get_patient_summary",
|
| 584 |
+
description="Get a high-level summary of what health data is available for the patient. Call this first to understand what data exists.",
|
| 585 |
+
parameters=[
|
| 586 |
+
ToolParameter("patient_id", "string", "The patient's ID")
|
| 587 |
+
],
|
| 588 |
+
category="summary",
|
| 589 |
+
requires_patient_id=True
|
| 590 |
+
)
|
| 591 |
def get_patient_summary(patient_id: str) -> str:
|
| 592 |
"""Get a summary of available health data."""
|
| 593 |
conn = get_db()
|
|
|
|
| 596 |
patient = cursor.fetchone()
|
| 597 |
if not patient:
|
| 598 |
return "Patient not found."
|
| 599 |
+
|
| 600 |
counts = {}
|
| 601 |
for table in ['conditions', 'medications', 'observations', 'allergies', 'encounters', 'immunizations', 'procedures']:
|
| 602 |
try:
|
|
|
|
| 604 |
counts[table] = cursor.fetchone()[0]
|
| 605 |
except:
|
| 606 |
counts[table] = 0
|
| 607 |
+
|
| 608 |
cursor = conn.execute(
|
| 609 |
"SELECT display, clinical_status FROM conditions WHERE patient_id = ? LIMIT 10",
|
| 610 |
(patient_id,)
|
| 611 |
)
|
| 612 |
conditions = [f"{row['display']} ({row['clinical_status']})" for row in cursor.fetchall()]
|
| 613 |
+
|
| 614 |
cursor = conn.execute(
|
| 615 |
"SELECT display FROM medications WHERE patient_id = ? AND status = 'active' LIMIT 10",
|
| 616 |
(patient_id,)
|
| 617 |
)
|
| 618 |
medications = [row['display'] for row in cursor.fetchall()]
|
| 619 |
+
|
| 620 |
cursor = conn.execute("""
|
| 621 |
SELECT MIN(effective_date) as earliest, MAX(effective_date) as latest
|
| 622 |
FROM observations WHERE patient_id = ?
|
| 623 |
""", (patient_id,))
|
| 624 |
obs_range = cursor.fetchone()
|
| 625 |
+
|
| 626 |
birth = datetime.strptime(patient["birth_date"], "%Y-%m-%d")
|
| 627 |
age = (datetime.now() - birth).days // 365
|
| 628 |
+
|
| 629 |
summary = f"""Patient Summary:
|
| 630 |
- Name: {patient['given_name']} {patient['family_name']}
|
| 631 |
- Age: {age} years old
|
| 632 |
- Gender: {patient['gender']}
|
| 633 |
+
|
| 634 |
Available Data:
|
| 635 |
- Conditions: {counts['conditions']} records
|
| 636 |
- Medications: {counts['medications']} records
|
|
|
|
| 638 |
- Allergies: {counts['allergies']} records
|
| 639 |
- Encounters: {counts['encounters']} records
|
| 640 |
- Immunizations: {counts['immunizations']} records
|
| 641 |
+
|
| 642 |
Conditions: {', '.join(conditions) if conditions else 'None recorded'}
|
| 643 |
+
|
| 644 |
Active Medications: {', '.join(medications) if medications else 'None'}
|
| 645 |
+
|
| 646 |
Observation date range: {obs_range['earliest'][:10] if obs_range['earliest'] else 'N/A'} to {obs_range['latest'][:10] if obs_range['latest'] else 'N/A'}
|
| 647 |
"""
|
| 648 |
return summary
|
| 649 |
finally:
|
| 650 |
conn.close()
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
@registry.register(
|
| 654 |
+
name="get_conditions",
|
| 655 |
+
description="Get the patient's medical conditions and diagnoses (e.g., diabetes, hypertension, asthma).",
|
| 656 |
+
parameters=[
|
| 657 |
+
ToolParameter("patient_id", "string", "The patient's ID"),
|
| 658 |
+
ToolParameter("status", "string", "Filter by status: 'active', 'resolved', or leave empty for all", required=False)
|
| 659 |
+
],
|
| 660 |
+
category="medical_records"
|
| 661 |
+
)
|
| 662 |
def get_conditions(patient_id: str, status: Optional[str] = None) -> str:
|
| 663 |
"""Get patient conditions."""
|
| 664 |
conn = get_db()
|
|
|
|
| 675 |
FROM conditions WHERE patient_id = ?
|
| 676 |
ORDER BY onset_date DESC
|
| 677 |
""", (patient_id,))
|
| 678 |
+
|
| 679 |
conditions = cursor.fetchall()
|
| 680 |
if not conditions:
|
| 681 |
return "No conditions found."
|
| 682 |
+
|
| 683 |
lines = ["Conditions:\n"]
|
| 684 |
for c in conditions:
|
| 685 |
onset = c['onset_date'][:10] if c['onset_date'] else 'Unknown'
|
| 686 |
end = f" (resolved: {c['abatement_date'][:10]})" if c['abatement_date'] else ""
|
| 687 |
lines.append(f"- {c['display']} [{c['clinical_status']}] - since {onset}{end}")
|
| 688 |
+
|
| 689 |
return "\n".join(lines)
|
| 690 |
finally:
|
| 691 |
conn.close()
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
@registry.register(
|
| 695 |
+
name="get_medications",
|
| 696 |
+
description="Get the patient's medications.",
|
| 697 |
+
parameters=[
|
| 698 |
+
ToolParameter("patient_id", "string", "The patient's ID"),
|
| 699 |
+
ToolParameter("status", "string", "Filter by status: 'active', 'stopped', or leave empty for all", required=False)
|
| 700 |
+
],
|
| 701 |
+
category="medical_records"
|
| 702 |
+
)
|
| 703 |
def get_medications(patient_id: str, status: Optional[str] = None) -> str:
|
| 704 |
"""Get patient medications."""
|
| 705 |
conn = get_db()
|
|
|
|
| 716 |
FROM medications WHERE patient_id = ?
|
| 717 |
ORDER BY start_date DESC
|
| 718 |
""", (patient_id,))
|
| 719 |
+
|
| 720 |
medications = cursor.fetchall()
|
| 721 |
if not medications:
|
|
|
|
|
|
|
|
|
|
| 722 |
return "No medications found."
|
| 723 |
+
|
| 724 |
lines = ["Medications:\n"]
|
| 725 |
for m in medications:
|
| 726 |
dosage = m['dosage_text'] or 'No dosage specified'
|
|
|
|
| 729 |
lines.append(f"- {m['display']} [{m['status']}]")
|
| 730 |
lines.append(f" Dosage: {dosage}{route}")
|
| 731 |
lines.append(f" Started: {start}")
|
| 732 |
+
|
| 733 |
return "\n".join(lines)
|
| 734 |
finally:
|
| 735 |
conn.close()
|
| 736 |
+
|
| 737 |
+
|
| 738 |
+
@registry.register(
|
| 739 |
+
name="get_allergies",
|
| 740 |
+
description="Get the patient's known allergies and adverse reactions.",
|
| 741 |
+
parameters=[
|
| 742 |
+
ToolParameter("patient_id", "string", "The patient's ID")
|
| 743 |
+
],
|
| 744 |
+
category="medical_records"
|
| 745 |
+
)
|
| 746 |
def get_allergies(patient_id: str) -> str:
|
| 747 |
"""Get patient allergies."""
|
| 748 |
conn = get_db()
|
|
|
|
| 751 |
SELECT substance, reaction_display, reaction_severity, criticality, category
|
| 752 |
FROM allergies WHERE patient_id = ?
|
| 753 |
""", (patient_id,))
|
| 754 |
+
|
| 755 |
allergies = cursor.fetchall()
|
| 756 |
if not allergies:
|
| 757 |
return "No known allergies."
|
| 758 |
+
|
| 759 |
lines = ["Allergies:\n"]
|
| 760 |
for a in allergies:
|
| 761 |
severity = a['reaction_severity'] or a['criticality'] or 'Unknown severity'
|
|
|
|
| 764 |
lines.append(f"- {a['substance']} ({category})")
|
| 765 |
lines.append(f" Reaction: {reaction}")
|
| 766 |
lines.append(f" Severity: {severity}")
|
| 767 |
+
|
| 768 |
return "\n".join(lines)
|
| 769 |
finally:
|
| 770 |
conn.close()
|
| 771 |
+
|
| 772 |
+
|
| 773 |
+
@registry.register(
|
| 774 |
+
name="get_recent_vitals",
|
| 775 |
+
description="Get a TEXT SUMMARY of recent vital signs. Use this ONLY for quick text summaries when user does NOT want a chart. For any visual/chart/trend request, use get_vital_chart_data instead.",
|
| 776 |
+
parameters=[
|
| 777 |
+
ToolParameter("patient_id", "string", "The patient's ID"),
|
| 778 |
+
ToolParameter("days", "integer", "Number of days to look back. Default is 30.", required=False, default=30),
|
| 779 |
+
ToolParameter("vital_type", "string", "Specific vital: 'blood_pressure', 'heart_rate', 'temperature', 'weight', 'respiratory_rate', 'oxygen_saturation'", required=False)
|
| 780 |
+
],
|
| 781 |
+
category="vitals"
|
| 782 |
+
)
|
|
|
|
| 783 |
def get_recent_vitals(patient_id: str, days: int = 30, vital_type: Optional[str] = None) -> str:
|
| 784 |
"""Get recent vital signs."""
|
| 785 |
conn = get_db()
|
| 786 |
try:
|
| 787 |
cutoff = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
|
| 788 |
+
|
| 789 |
if vital_type and vital_type in VITAL_CODES:
|
| 790 |
codes = VITAL_CODES[vital_type]
|
| 791 |
placeholders = ','.join(['?' for _ in codes])
|
|
|
|
| 805 |
ORDER BY effective_date DESC
|
| 806 |
LIMIT 50
|
| 807 |
""", (patient_id, cutoff))
|
| 808 |
+
|
| 809 |
vitals = cursor.fetchall()
|
| 810 |
if not vitals:
|
| 811 |
return f"No vital signs found in the last {days} days."
|
| 812 |
+
|
| 813 |
lines = [f"Vital Signs (last {days} days):\n"]
|
| 814 |
by_type = {}
|
| 815 |
for v in vitals:
|
|
|
|
| 817 |
if display not in by_type:
|
| 818 |
by_type[display] = []
|
| 819 |
by_type[display].append(v)
|
| 820 |
+
|
| 821 |
for display, readings in by_type.items():
|
| 822 |
lines.append(f"\n{display}:")
|
| 823 |
for r in readings[:5]:
|
|
|
|
| 825 |
value = r['value_quantity']
|
| 826 |
unit = r['value_unit'] or ''
|
| 827 |
lines.append(f" {date}: {value} {unit}")
|
| 828 |
+
|
| 829 |
return "\n".join(lines)
|
| 830 |
finally:
|
| 831 |
conn.close()
|
| 832 |
+
|
| 833 |
+
|
| 834 |
+
@registry.register(
|
| 835 |
+
name="get_lab_results",
|
| 836 |
+
description="Get the patient's laboratory test results (blood tests, A1c, cholesterol, etc.).",
|
| 837 |
+
parameters=[
|
| 838 |
+
ToolParameter("patient_id", "string", "The patient's ID"),
|
| 839 |
+
ToolParameter("days", "integer", "Number of days to look back. Default is 90.", required=False, default=90)
|
| 840 |
+
],
|
| 841 |
+
category="labs"
|
| 842 |
+
)
|
| 843 |
def get_lab_results(patient_id: str, days: int = 90) -> str:
|
| 844 |
"""Get laboratory results."""
|
| 845 |
conn = get_db()
|
| 846 |
try:
|
| 847 |
cutoff = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
|
| 848 |
+
|
| 849 |
cursor = conn.execute("""
|
| 850 |
SELECT display, value_quantity, value_unit, value_string,
|
| 851 |
effective_date, interpretation
|
|
|
|
| 854 |
ORDER BY effective_date DESC
|
| 855 |
LIMIT 50
|
| 856 |
""", (patient_id, cutoff))
|
| 857 |
+
|
| 858 |
labs = cursor.fetchall()
|
| 859 |
if not labs:
|
| 860 |
return f"No lab results found in the last {days} days."
|
| 861 |
+
|
| 862 |
lines = [f"Lab Results (last {days} days):\n"]
|
| 863 |
for lab in labs:
|
| 864 |
date = lab['effective_date'][:10] if lab['effective_date'] else 'Unknown'
|
|
|
|
| 866 |
unit = lab['value_unit'] or ''
|
| 867 |
interp = f" [{lab['interpretation']}]" if lab['interpretation'] else ""
|
| 868 |
lines.append(f"- {lab['display']}: {value} {unit}{interp} ({date})")
|
| 869 |
+
|
| 870 |
return "\n".join(lines)
|
| 871 |
finally:
|
| 872 |
conn.close()
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
@registry.register(
|
| 876 |
+
name="get_encounters",
|
| 877 |
+
description="Get the patient's healthcare encounters (office visits, hospitalizations, etc.).",
|
| 878 |
+
parameters=[
|
| 879 |
+
ToolParameter("patient_id", "string", "The patient's ID"),
|
| 880 |
+
ToolParameter("limit", "integer", "Maximum number of encounters to return. Default is 10.", required=False, default=10)
|
| 881 |
+
],
|
| 882 |
+
category="medical_records"
|
| 883 |
+
)
|
| 884 |
def get_encounters(patient_id: str, limit: int = 10) -> str:
|
| 885 |
"""Get healthcare encounters."""
|
| 886 |
conn = get_db()
|
|
|
|
| 892 |
ORDER BY period_start DESC
|
| 893 |
LIMIT ?
|
| 894 |
""", (patient_id, limit))
|
| 895 |
+
|
| 896 |
encounters = cursor.fetchall()
|
| 897 |
if not encounters:
|
| 898 |
return "No encounters found."
|
| 899 |
+
|
| 900 |
lines = [f"Healthcare Encounters (last {limit}):\n"]
|
| 901 |
for e in encounters:
|
| 902 |
date = e['period_start'][:10] if e['period_start'] else 'Unknown'
|
|
|
|
| 904 |
reason = e['reason_display'] or 'No reason specified'
|
| 905 |
lines.append(f"- {date}: {enc_type}")
|
| 906 |
lines.append(f" Reason: {reason}")
|
| 907 |
+
|
| 908 |
return "\n".join(lines)
|
| 909 |
finally:
|
| 910 |
conn.close()
|
| 911 |
+
|
| 912 |
+
|
| 913 |
+
@registry.register(
|
| 914 |
+
name="get_immunizations",
|
| 915 |
+
description="Get the patient's immunization/vaccination history.",
|
| 916 |
+
parameters=[
|
| 917 |
+
ToolParameter("patient_id", "string", "The patient's ID")
|
| 918 |
+
],
|
| 919 |
+
category="medical_records"
|
| 920 |
+
)
|
| 921 |
def get_immunizations(patient_id: str) -> str:
|
| 922 |
"""Get immunization history."""
|
| 923 |
conn = get_db()
|
|
|
|
| 927 |
FROM immunizations WHERE patient_id = ?
|
| 928 |
ORDER BY occurrence_date DESC
|
| 929 |
""", (patient_id,))
|
| 930 |
+
|
| 931 |
immunizations = cursor.fetchall()
|
| 932 |
if not immunizations:
|
| 933 |
return "No immunization records found."
|
| 934 |
+
|
| 935 |
lines = ["Immunizations:\n"]
|
| 936 |
for i in immunizations:
|
| 937 |
date = i['occurrence_date'][:10] if i['occurrence_date'] else 'Unknown'
|
| 938 |
lines.append(f"- {i['vaccine_display']} ({date}) [{i['status']}]")
|
| 939 |
+
|
| 940 |
return "\n".join(lines)
|
| 941 |
finally:
|
| 942 |
conn.close()
|
| 943 |
+
|
| 944 |
+
|
| 945 |
+
@registry.register(
|
| 946 |
+
name="analyze_vital_trend",
|
| 947 |
+
description="Analyze trends in a specific vital sign over time. Returns statistics and trend direction.",
|
| 948 |
+
parameters=[
|
| 949 |
+
ToolParameter("patient_id", "string", "The patient's ID"),
|
| 950 |
+
ToolParameter("vital_type", "string", "The vital to analyze: 'blood_pressure_systolic', 'blood_pressure_diastolic', 'heart_rate', 'weight', 'temperature'"),
|
| 951 |
+
ToolParameter("days", "integer", "Number of days to analyze. Default is 30.", required=False, default=30)
|
| 952 |
+
],
|
| 953 |
+
category="analysis"
|
| 954 |
+
)
|
| 955 |
def analyze_vital_trend(patient_id: str, vital_type: str, days: int = 30) -> str:
|
| 956 |
"""Analyze trends in vital signs."""
|
| 957 |
conn = get_db()
|
| 958 |
try:
|
| 959 |
if vital_type not in VITAL_CODES:
|
| 960 |
return f"Unknown vital type: {vital_type}. Available: {', '.join(VITAL_CODES.keys())}"
|
| 961 |
+
|
| 962 |
codes = VITAL_CODES[vital_type]
|
| 963 |
cutoff = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
|
| 964 |
placeholders = ','.join(['?' for _ in codes])
|
| 965 |
+
|
| 966 |
cursor = conn.execute(f"""
|
| 967 |
SELECT value_quantity, effective_date
|
| 968 |
FROM observations
|
|
|
|
| 970 |
AND effective_date >= ? AND value_quantity IS NOT NULL
|
| 971 |
ORDER BY effective_date ASC
|
| 972 |
""", [patient_id] + codes + [cutoff])
|
| 973 |
+
|
| 974 |
readings = cursor.fetchall()
|
| 975 |
if not readings:
|
| 976 |
return f"No {vital_type} readings found in the last {days} days."
|
| 977 |
+
|
| 978 |
values = [r['value_quantity'] for r in readings]
|
| 979 |
dates = [r['effective_date'][:10] for r in readings]
|
| 980 |
+
|
| 981 |
avg_val = sum(values) / len(values)
|
| 982 |
min_val = min(values)
|
| 983 |
max_val = max(values)
|
| 984 |
+
|
| 985 |
if len(values) >= 3:
|
| 986 |
first_third = sum(values[:len(values)//3]) / (len(values)//3)
|
| 987 |
last_third = sum(values[-len(values)//3:]) / (len(values)//3)
|
| 988 |
diff_pct = ((last_third - first_third) / first_third) * 100 if first_third != 0 else 0
|
| 989 |
+
|
| 990 |
if diff_pct > 5:
|
| 991 |
trend = f"INCREASING (up {diff_pct:.1f}%)"
|
| 992 |
elif diff_pct < -5:
|
|
|
|
| 995 |
trend = "STABLE"
|
| 996 |
else:
|
| 997 |
trend = "Not enough data for trend"
|
| 998 |
+
|
| 999 |
return f"""{vital_type.replace('_', ' ').title()} Analysis (last {days} days):
|
| 1000 |
+
|
| 1001 |
Readings: {len(values)}
|
| 1002 |
Date range: {dates[0]} to {dates[-1]}
|
| 1003 |
+
|
| 1004 |
Statistics:
|
| 1005 |
- Average: {avg_val:.1f}
|
| 1006 |
- Minimum: {min_val:.1f}
|
| 1007 |
- Maximum: {max_val:.1f}
|
| 1008 |
+
|
| 1009 |
Trend: {trend}
|
| 1010 |
+
|
| 1011 |
Recent values: {', '.join([str(v) for v in values[-5:]])}
|
| 1012 |
"""
|
| 1013 |
finally:
|
| 1014 |
conn.close()
|
| 1015 |
+
|
| 1016 |
+
|
| 1017 |
+
@registry.register(
|
| 1018 |
+
name="get_vital_chart_data",
|
| 1019 |
+
description="Get vital sign data formatted for generating a LINE chart/graph. USE THIS TOOL (not get_recent_vitals) whenever the user wants to: see, show, display, visualize, or graph any vital sign; view trends over time; or asks for a chart. Returns data that renders as a visual chart.",
|
| 1020 |
+
parameters=[
|
| 1021 |
+
ToolParameter("patient_id", "string", "The patient's ID"),
|
| 1022 |
+
ToolParameter("vital_type", "string", "The vital to chart: 'blood_pressure', 'heart_rate', 'weight', 'temperature', 'respiratory_rate', 'oxygen_saturation'"),
|
| 1023 |
+
ToolParameter("days", "integer", "Number of days to include. Default is 30.", required=False, default=30)
|
| 1024 |
+
],
|
| 1025 |
+
category="charts",
|
| 1026 |
+
returns_chart=True,
|
| 1027 |
+
returns_json=True
|
| 1028 |
+
)
|
| 1029 |
def get_vital_chart_data(patient_id: str, vital_type: str, days: int = 30) -> str:
|
| 1030 |
"""
|
| 1031 |
Get vital sign data formatted for charting.
|
| 1032 |
Returns JSON that can be used to render a chart.
|
|
|
|
| 1033 |
"""
|
|
|
|
|
|
|
|
|
|
| 1034 |
def compute_stats(values):
|
| 1035 |
"""Compute statistics for a list of values."""
|
| 1036 |
if not values:
|
|
|
|
| 1047 |
try:
|
| 1048 |
if vital_type not in VITAL_CODES:
|
| 1049 |
return json_module.dumps({"error": f"Unknown vital type: {vital_type}. Available: {', '.join(VITAL_CODES.keys())}"})
|
| 1050 |
+
|
| 1051 |
codes = VITAL_CODES[vital_type]
|
| 1052 |
cutoff = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
|
|
|
|
| 1053 |
|
| 1054 |
# For blood pressure, we need both systolic and diastolic
|
| 1055 |
if vital_type == 'blood_pressure':
|
| 1056 |
# Get systolic
|
| 1057 |
+
cursor = conn.execute("""
|
| 1058 |
SELECT value_quantity, effective_date
|
| 1059 |
FROM observations
|
| 1060 |
WHERE patient_id = ? AND code = '8480-6'
|
|
|
|
| 1066 |
systolic_values = [r['value_quantity'] for r in systolic_rows]
|
| 1067 |
|
| 1068 |
# Get diastolic
|
| 1069 |
+
cursor = conn.execute("""
|
| 1070 |
SELECT value_quantity, effective_date
|
| 1071 |
FROM observations
|
| 1072 |
WHERE patient_id = ? AND code = '8462-4'
|
|
|
|
| 1080 |
if not systolic and not diastolic:
|
| 1081 |
return json_module.dumps({"error": "No blood pressure data found"})
|
| 1082 |
|
|
|
|
| 1083 |
systolic_stats = compute_stats(systolic_values)
|
| 1084 |
diastolic_stats = compute_stats(diastolic_values)
|
| 1085 |
|
|
|
|
| 1086 |
summary_text = (
|
| 1087 |
f"STATISTICS (use these exact values): "
|
| 1088 |
f"Total readings: {systolic_stats['count']}. "
|
|
|
|
| 1091 |
)
|
| 1092 |
|
| 1093 |
return json_module.dumps({
|
| 1094 |
+
"summary": summary_text,
|
| 1095 |
"chart_type": "blood_pressure",
|
| 1096 |
"title": f"Blood Pressure (Last {days} Days)",
|
| 1097 |
"statistics": {
|
|
|
|
| 1104 |
]
|
| 1105 |
})
|
| 1106 |
else:
|
| 1107 |
+
placeholders = ','.join(['?' for _ in codes])
|
| 1108 |
cursor = conn.execute(f"""
|
| 1109 |
SELECT value_quantity, value_unit, effective_date, display
|
| 1110 |
FROM observations
|
|
|
|
| 1112 |
AND effective_date >= ? AND value_quantity IS NOT NULL
|
| 1113 |
ORDER BY effective_date ASC
|
| 1114 |
""", [patient_id] + codes + [cutoff])
|
| 1115 |
+
|
| 1116 |
readings = cursor.fetchall()
|
| 1117 |
if not readings:
|
| 1118 |
return json_module.dumps({"error": f"No {vital_type} data found"})
|
|
|
|
| 1122 |
unit = readings[0]['value_unit'] if readings else ''
|
| 1123 |
display = readings[0]['display'] if readings else vital_type
|
| 1124 |
|
|
|
|
| 1125 |
vital_stats = compute_stats(values)
|
| 1126 |
|
|
|
|
| 1127 |
summary_text = (
|
| 1128 |
f"STATISTICS (use these exact values): "
|
| 1129 |
f"Total readings: {vital_stats['count']}. "
|
|
|
|
| 1131 |
)
|
| 1132 |
|
| 1133 |
return json_module.dumps({
|
| 1134 |
+
"summary": summary_text,
|
| 1135 |
"chart_type": "line",
|
| 1136 |
"title": f"{display} (Last {days} Days)",
|
| 1137 |
"unit": unit,
|
|
|
|
| 1142 |
})
|
| 1143 |
finally:
|
| 1144 |
conn.close()
|
| 1145 |
+
|
| 1146 |
+
|
| 1147 |
+
@registry.register(
|
| 1148 |
+
name="get_lab_chart_data",
|
| 1149 |
+
description="Get laboratory results formatted for a BAR chart. Use this when user wants to compare lab values, see lab history as a chart, or visualize lab trends. Good for: cholesterol comparison, A1c history, glucose trends, kidney function over time.",
|
| 1150 |
+
parameters=[
|
| 1151 |
+
ToolParameter("patient_id", "string", "The patient's ID"),
|
| 1152 |
+
ToolParameter("lab_type", "string", "The lab to chart: 'cholesterol' (shows Total, HDL, LDL, Triglycerides), 'a1c', 'glucose', 'kidney' (Creatinine, eGFR), 'all_latest' (comparison of recent labs)"),
|
| 1153 |
+
ToolParameter("periods", "integer", "Number of time periods to show. Default is 4.", required=False, default=4)
|
| 1154 |
],
|
| 1155 |
+
category="charts",
|
| 1156 |
+
returns_chart=True,
|
| 1157 |
+
returns_json=True
|
| 1158 |
+
)
|
|
|
|
| 1159 |
def get_lab_chart_data(patient_id: str, lab_type: str, periods: int = 4) -> str:
|
| 1160 |
+
"""Get lab results formatted for a BAR chart."""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1161 |
conn = get_db()
|
| 1162 |
try:
|
| 1163 |
if lab_type == 'all_latest':
|
|
|
|
| 1164 |
labs_to_show = [
|
| 1165 |
('4548-4', 'HbA1c'),
|
| 1166 |
('2093-3', 'Total Chol'),
|
|
|
|
| 1173 |
for code, label in labs_to_show:
|
| 1174 |
cursor = conn.execute("""
|
| 1175 |
SELECT value_quantity FROM observations
|
| 1176 |
+
WHERE patient_id = ? AND code = ? AND value_quantity IS NOT NULL
|
| 1177 |
ORDER BY effective_date DESC LIMIT 1
|
| 1178 |
""", (patient_id, code))
|
| 1179 |
row = cursor.fetchone()
|
| 1180 |
+
if row:
|
| 1181 |
data.append({"label": label, "value": row['value_quantity']})
|
| 1182 |
+
|
| 1183 |
if not data:
|
| 1184 |
return json_module.dumps({"error": "No lab data found"})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1185 |
|
| 1186 |
return json_module.dumps({
|
| 1187 |
+
"chart_type": "bar",
|
| 1188 |
+
"title": "Latest Lab Values",
|
| 1189 |
+
"datasets": [{"label": "Value", "data": data, "color": "#667eea"}]
|
|
|
|
|
|
|
|
|
|
| 1190 |
})
|
| 1191 |
+
|
| 1192 |
+
if lab_type not in LAB_CODES:
|
| 1193 |
+
return json_module.dumps({"error": f"Unknown lab type: {lab_type}. Available: {', '.join(LAB_CODES.keys())}"})
|
| 1194 |
+
|
| 1195 |
+
lab_info = LAB_CODES[lab_type]
|
| 1196 |
+
datasets = []
|
| 1197 |
+
|
| 1198 |
+
for code, label, unit in lab_info:
|
| 1199 |
cursor = conn.execute("""
|
| 1200 |
SELECT value_quantity, effective_date FROM observations
|
| 1201 |
+
WHERE patient_id = ? AND code = ? AND value_quantity IS NOT NULL
|
| 1202 |
ORDER BY effective_date DESC LIMIT ?
|
| 1203 |
""", (patient_id, code, periods))
|
| 1204 |
rows = cursor.fetchall()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1205 |
|
| 1206 |
+
if rows:
|
| 1207 |
+
data = [{"date": r['effective_date'][:10], "value": r['value_quantity']} for r in reversed(rows)]
|
| 1208 |
+
datasets.append({
|
| 1209 |
+
"label": label,
|
| 1210 |
+
"data": data,
|
| 1211 |
+
"unit": unit
|
| 1212 |
+
})
|
| 1213 |
+
|
| 1214 |
+
if not datasets:
|
| 1215 |
+
return json_module.dumps({"error": f"No {lab_type} data found"})
|
| 1216 |
+
|
| 1217 |
+
return json_module.dumps({
|
| 1218 |
+
"chart_type": "bar",
|
| 1219 |
+
"title": f"{lab_type.title()} Results (Last {periods} readings)",
|
| 1220 |
+
"datasets": datasets
|
| 1221 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1222 |
finally:
|
| 1223 |
conn.close()
|
| 1224 |
+
|
| 1225 |
+
|
| 1226 |
+
@registry.register(
|
| 1227 |
+
name="compare_before_after_treatment",
|
| 1228 |
+
description="Compare health metrics BEFORE vs AFTER starting a medication/treatment. Use when user asks about treatment effectiveness, medication impact, or before/after comparisons. Shows a bar chart comparing averages before and after treatment started.",
|
| 1229 |
+
parameters=[
|
| 1230 |
+
ToolParameter("patient_id", "string", "The patient's ID"),
|
| 1231 |
+
ToolParameter("medication_name", "string", "Part of the medication name to search for (e.g., 'metformin', 'lisinopril', 'atorvastatin')"),
|
| 1232 |
+
ToolParameter("metric_type", "string", "What to compare: 'blood_pressure', 'a1c', 'cholesterol', 'glucose', 'weight', 'heart_rate'")
|
| 1233 |
+
],
|
| 1234 |
+
category="analysis",
|
| 1235 |
+
returns_chart=True,
|
| 1236 |
+
returns_json=True
|
| 1237 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1238 |
def compare_before_after_treatment(patient_id: str, medication_name: str, metric_type: str) -> str:
|
| 1239 |
+
"""Compare health metrics before vs after starting a medication."""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1240 |
conn = get_db()
|
| 1241 |
try:
|
| 1242 |
# Find the medication start date
|
|
|
|
| 1244 |
SELECT display, start_date FROM medications
|
| 1245 |
WHERE patient_id = ? AND LOWER(display) LIKE ?
|
| 1246 |
ORDER BY start_date ASC LIMIT 1
|
| 1247 |
+
""", (patient_id, f"%{medication_name.lower()}%"))
|
| 1248 |
+
|
| 1249 |
med_row = cursor.fetchone()
|
| 1250 |
if not med_row:
|
| 1251 |
+
return json_module.dumps({"error": f"No medication found matching '{medication_name}'"})
|
| 1252 |
+
|
| 1253 |
+
med_display = med_row['display']
|
| 1254 |
+
start_date = med_row['start_date'][:10] if med_row['start_date'] else None
|
| 1255 |
+
|
| 1256 |
+
if not start_date:
|
| 1257 |
+
return json_module.dumps({"error": f"No start date found for {med_display}"})
|
| 1258 |
+
|
| 1259 |
+
# Get the appropriate codes for the metric
|
| 1260 |
+
metric_codes = {
|
| 1261 |
+
'blood_pressure': [('8480-6', 'Systolic BP'), ('8462-4', 'Diastolic BP')],
|
| 1262 |
+
'a1c': [('4548-4', 'HbA1c')],
|
| 1263 |
+
'cholesterol': [('2093-3', 'Total Cholesterol'), ('13457-7', 'LDL')],
|
| 1264 |
+
'glucose': [('2345-7', 'Glucose'), ('1558-6', 'Glucose')],
|
| 1265 |
+
'weight': [('29463-7', 'Weight')],
|
| 1266 |
+
'heart_rate': [('8867-4', 'Heart Rate')]
|
| 1267 |
+
}
|
| 1268 |
+
|
| 1269 |
+
if metric_type not in metric_codes:
|
| 1270 |
+
return json_module.dumps({"error": f"Unknown metric type: {metric_type}"})
|
| 1271 |
+
|
| 1272 |
+
codes = metric_codes[metric_type]
|
| 1273 |
+
results = {"before": {}, "after": {}}
|
| 1274 |
+
summary_parts = []
|
| 1275 |
+
|
| 1276 |
+
for code, label in codes:
|
| 1277 |
+
# Get values BEFORE treatment
|
| 1278 |
cursor = conn.execute("""
|
| 1279 |
SELECT AVG(value_quantity) as avg_val, COUNT(*) as cnt
|
| 1280 |
FROM observations
|
|
|
|
| 1282 |
AND value_quantity IS NOT NULL
|
| 1283 |
""", (patient_id, code, start_date))
|
| 1284 |
before = cursor.fetchone()
|
| 1285 |
+
|
| 1286 |
+
# Get values AFTER treatment
|
| 1287 |
cursor = conn.execute("""
|
| 1288 |
SELECT AVG(value_quantity) as avg_val, COUNT(*) as cnt
|
| 1289 |
FROM observations
|
|
|
|
| 1291 |
AND value_quantity IS NOT NULL
|
| 1292 |
""", (patient_id, code, start_date))
|
| 1293 |
after = cursor.fetchone()
|
| 1294 |
+
|
| 1295 |
+
if before['avg_val'] and after['avg_val']:
|
| 1296 |
+
results["before"][label] = round(before['avg_val'], 1)
|
| 1297 |
+
results["after"][label] = round(after['avg_val'], 1)
|
| 1298 |
+
change = after['avg_val'] - before['avg_val']
|
| 1299 |
+
change_pct = (change / before['avg_val']) * 100 if before['avg_val'] else 0
|
| 1300 |
+
direction = "decreased" if change < 0 else "increased"
|
| 1301 |
+
summary_parts.append(f"{label} {direction} from {results['before'][label]} to {results['after'][label]} ({abs(change_pct):.1f}%)")
|
| 1302 |
+
|
| 1303 |
+
if not results["before"]:
|
| 1304 |
+
return json_module.dumps({"error": f"No {metric_type} data found around treatment start date"})
|
| 1305 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1306 |
return json_module.dumps({
|
| 1307 |
+
"chart_type": "comparison",
|
| 1308 |
+
"title": f"{metric_type.title()} Before vs After {med_display}",
|
| 1309 |
+
"medication": med_display,
|
| 1310 |
+
"treatment_start_date": start_date,
|
| 1311 |
+
"summary": summary_parts,
|
|
|
|
| 1312 |
"datasets": [
|
| 1313 |
+
{"label": "Before Treatment", "data": results["before"], "color": "#e74c3c"},
|
| 1314 |
+
{"label": "After Treatment", "data": results["after"], "color": "#27ae60"}
|
| 1315 |
+
]
|
|
|
|
| 1316 |
})
|
| 1317 |
finally:
|
| 1318 |
conn.close()
|
|
|
|
|
|
|
|
|
|
| 1319 |
|
|
|
|
|
|
|
| 1320 |
|
| 1321 |
+
# =============================================================================
|
| 1322 |
+
# BACKWARD COMPATIBILITY - Legacy function mappings
|
| 1323 |
+
# =============================================================================
|
| 1324 |
+
|
| 1325 |
+
# Map old-style tool names to registry
|
| 1326 |
+
TOOL_FUNCTIONS = {
|
| 1327 |
+
"search_tools": _search_tools,
|
| 1328 |
+
"get_tool_schema": _get_tool_schema,
|
| 1329 |
+
"list_tool_categories": _list_tool_categories,
|
| 1330 |
+
"get_patient_summary": get_patient_summary,
|
| 1331 |
+
"get_conditions": get_conditions,
|
| 1332 |
+
"get_medications": get_medications,
|
| 1333 |
+
"get_allergies": get_allergies,
|
| 1334 |
+
"get_recent_vitals": get_recent_vitals,
|
| 1335 |
+
"get_lab_results": get_lab_results,
|
| 1336 |
+
"get_encounters": get_encounters,
|
| 1337 |
+
"get_immunizations": get_immunizations,
|
| 1338 |
+
"analyze_vital_trend": analyze_vital_trend,
|
| 1339 |
+
"get_vital_chart_data": get_vital_chart_data,
|
| 1340 |
+
"get_lab_chart_data": get_lab_chart_data,
|
| 1341 |
+
"compare_before_after_treatment": compare_before_after_treatment,
|
| 1342 |
+
}
|
| 1343 |
+
|
| 1344 |
+
# Legacy TOOLS list for backward compatibility
|
| 1345 |
+
TOOLS = [tool.to_mcp_schema() for tool in registry.get_all()]
|
| 1346 |
+
|
| 1347 |
+
|
| 1348 |
+
def execute_tool(tool_name: str, args: dict) -> str:
|
| 1349 |
+
"""Execute a tool by name with given arguments. (Legacy compatibility)"""
|
| 1350 |
+
return registry.execute(tool_name, args)
|
| 1351 |
+
|
| 1352 |
+
|
| 1353 |
+
# =============================================================================
|
| 1354 |
+
# MCP SERVER INTERFACE (Model Context Protocol)
|
| 1355 |
+
# =============================================================================
|
| 1356 |
+
|
| 1357 |
+
class MCPServerInterface:
|
| 1358 |
"""
|
| 1359 |
+
MCP Server interface for integration with MCP clients.
|
| 1360 |
+
Implements the Model Context Protocol specification.
|
| 1361 |
|
| 1362 |
+
This allows:
|
| 1363 |
+
1. External apps to discover and use our health tools
|
| 1364 |
+
2. Dynamic registration of external MCP tools
|
| 1365 |
+
3. Standard protocol for AI-tool integration
|
| 1366 |
+
"""
|
|
|
|
| 1367 |
|
| 1368 |
+
PROTOCOL_VERSION = "2024-11-05"
|
| 1369 |
+
|
| 1370 |
+
def __init__(self, tool_registry: DynamicToolRegistry):
|
| 1371 |
+
self.registry = tool_registry
|
| 1372 |
+
self.external_tools: Dict[str, Dict] = {} # Tools from external MCP servers
|
| 1373 |
+
self.connected_servers: Dict[str, Dict] = {} # Connected MCP servers
|
| 1374 |
+
|
| 1375 |
+
def get_server_info(self) -> Dict:
|
| 1376 |
+
"""Return MCP server information (initialize response)."""
|
| 1377 |
+
return {
|
| 1378 |
+
"protocolVersion": self.PROTOCOL_VERSION,
|
| 1379 |
+
"serverInfo": {
|
| 1380 |
+
"name": "medgemma-health-tools",
|
| 1381 |
+
"version": "2.0.0"
|
| 1382 |
+
},
|
| 1383 |
+
"capabilities": {
|
| 1384 |
+
"tools": {"listChanged": True},
|
| 1385 |
+
"resources": {},
|
| 1386 |
+
"prompts": {}
|
| 1387 |
+
}
|
| 1388 |
+
}
|
| 1389 |
+
|
| 1390 |
+
def list_tools(self) -> Dict:
|
| 1391 |
+
"""Return list of available tools in MCP format."""
|
| 1392 |
+
tools = []
|
| 1393 |
|
| 1394 |
+
# Add local tools
|
| 1395 |
+
for tool in self.registry.get_all():
|
| 1396 |
+
tools.append(tool.to_mcp_schema())
|
| 1397 |
+
|
| 1398 |
+
# Add external tools
|
| 1399 |
+
for tool_name, tool_info in self.external_tools.items():
|
| 1400 |
+
tools.append(tool_info)
|
| 1401 |
+
|
| 1402 |
+
return {"tools": tools}
|
| 1403 |
|
| 1404 |
+
def call_tool(self, name: str, arguments: Dict) -> Dict:
|
| 1405 |
+
"""Handle MCP tool call."""
|
| 1406 |
+
# Check if it's an external tool
|
| 1407 |
+
if name in self.external_tools:
|
| 1408 |
+
return self._call_external_tool(name, arguments)
|
| 1409 |
+
|
| 1410 |
+
# Otherwise use local registry
|
| 1411 |
+
return self.registry.handle_mcp_tool_call(name, arguments)
|
| 1412 |
+
|
| 1413 |
+
def _call_external_tool(self, name: str, arguments: Dict) -> Dict:
|
| 1414 |
+
"""Call a tool on an external MCP server."""
|
| 1415 |
+
tool_info = self.external_tools.get(name)
|
| 1416 |
+
if not tool_info:
|
| 1417 |
+
return {
|
| 1418 |
+
"isError": True,
|
| 1419 |
+
"content": [{"type": "text", "text": f"External tool not found: {name}"}]
|
| 1420 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1421 |
|
| 1422 |
+
server_url = tool_info.get("_server_url")
|
| 1423 |
+
if not server_url:
|
| 1424 |
+
return {
|
| 1425 |
+
"isError": True,
|
| 1426 |
+
"content": [{"type": "text", "text": f"No server URL for tool: {name}"}]
|
| 1427 |
+
}
|
| 1428 |
|
| 1429 |
+
# Make HTTP request to external MCP server
|
| 1430 |
+
try:
|
| 1431 |
+
import httpx
|
| 1432 |
+
response = httpx.post(
|
| 1433 |
+
f"{server_url}/tools/call",
|
| 1434 |
+
json={"name": name, "arguments": arguments},
|
| 1435 |
+
timeout=30.0
|
| 1436 |
+
)
|
| 1437 |
+
return response.json()
|
| 1438 |
+
except Exception as e:
|
| 1439 |
+
return {
|
| 1440 |
+
"isError": True,
|
| 1441 |
+
"content": [{"type": "text", "text": f"Error calling external tool: {str(e)}"}]
|
| 1442 |
+
}
|
| 1443 |
+
|
| 1444 |
+
# =========================================================================
|
| 1445 |
+
# MCP Client - Connect to external MCP servers
|
| 1446 |
+
# =========================================================================
|
| 1447 |
+
|
| 1448 |
+
def connect_server(self, server_url: str, server_name: str = None) -> Dict:
|
| 1449 |
+
"""
|
| 1450 |
+
Connect to an external MCP server and discover its tools.
|
| 1451 |
+
|
| 1452 |
+
Args:
|
| 1453 |
+
server_url: Base URL of the MCP server
|
| 1454 |
+
server_name: Optional friendly name for the server
|
| 1455 |
|
| 1456 |
+
Returns:
|
| 1457 |
+
Dict with connection status and discovered tools
|
| 1458 |
+
"""
|
| 1459 |
+
try:
|
| 1460 |
+
import httpx
|
| 1461 |
|
| 1462 |
+
# Initialize connection
|
| 1463 |
+
init_response = httpx.post(
|
| 1464 |
+
f"{server_url}/initialize",
|
| 1465 |
+
json={
|
| 1466 |
+
"protocolVersion": self.PROTOCOL_VERSION,
|
| 1467 |
+
"clientInfo": {"name": "medgemma-agent", "version": "2.0.0"},
|
| 1468 |
+
"capabilities": {}
|
| 1469 |
+
},
|
| 1470 |
+
timeout=10.0
|
| 1471 |
+
)
|
| 1472 |
+
server_info = init_response.json()
|
| 1473 |
|
| 1474 |
+
# List available tools
|
| 1475 |
+
tools_response = httpx.post(f"{server_url}/tools/list", timeout=10.0)
|
| 1476 |
+
tools_data = tools_response.json()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1477 |
|
| 1478 |
+
# Register discovered tools
|
| 1479 |
+
discovered_tools = []
|
| 1480 |
+
for tool in tools_data.get("tools", []):
|
| 1481 |
+
tool_name = tool.get("name")
|
| 1482 |
+
# Prefix with server name to avoid conflicts
|
| 1483 |
+
prefixed_name = f"{server_name or 'ext'}_{tool_name}"
|
| 1484 |
+
tool["_original_name"] = tool_name
|
| 1485 |
+
tool["_server_url"] = server_url
|
| 1486 |
+
tool["name"] = prefixed_name
|
| 1487 |
+
self.external_tools[prefixed_name] = tool
|
| 1488 |
+
discovered_tools.append(prefixed_name)
|
| 1489 |
|
| 1490 |
+
# Store connection info
|
| 1491 |
+
self.connected_servers[server_url] = {
|
| 1492 |
+
"name": server_name or server_url,
|
| 1493 |
+
"info": server_info,
|
| 1494 |
+
"tools": discovered_tools
|
| 1495 |
+
}
|
| 1496 |
|
| 1497 |
+
print(f"[MCP] Connected to {server_url}, discovered {len(discovered_tools)} tools")
|
|
|
|
| 1498 |
|
| 1499 |
+
return {
|
| 1500 |
+
"success": True,
|
| 1501 |
+
"server": server_info.get("serverInfo", {}),
|
| 1502 |
+
"tools_discovered": discovered_tools
|
| 1503 |
+
}
|
| 1504 |
|
| 1505 |
+
except Exception as e:
|
| 1506 |
+
print(f"[MCP] Failed to connect to {server_url}: {e}")
|
| 1507 |
+
return {
|
| 1508 |
+
"success": False,
|
| 1509 |
+
"error": str(e)
|
| 1510 |
+
}
|
| 1511 |
+
|
| 1512 |
+
def disconnect_server(self, server_url: str) -> bool:
|
| 1513 |
+
"""Disconnect from an external MCP server and remove its tools."""
|
| 1514 |
+
if server_url not in self.connected_servers:
|
| 1515 |
+
return False
|
| 1516 |
|
| 1517 |
+
# Remove tools from this server
|
| 1518 |
+
server_info = self.connected_servers[server_url]
|
| 1519 |
+
for tool_name in server_info.get("tools", []):
|
| 1520 |
+
self.external_tools.pop(tool_name, None)
|
| 1521 |
|
| 1522 |
+
del self.connected_servers[server_url]
|
| 1523 |
+
print(f"[MCP] Disconnected from {server_url}")
|
| 1524 |
+
return True
|
| 1525 |
+
|
| 1526 |
+
def list_connected_servers(self) -> List[Dict]:
|
| 1527 |
+
"""List all connected MCP servers."""
|
| 1528 |
+
return [
|
| 1529 |
+
{
|
| 1530 |
+
"url": url,
|
| 1531 |
+
"name": info["name"],
|
| 1532 |
+
"tools_count": len(info["tools"])
|
| 1533 |
+
}
|
| 1534 |
+
for url, info in self.connected_servers.items()
|
| 1535 |
+
]
|
| 1536 |
+
|
| 1537 |
+
# =========================================================================
|
| 1538 |
+
# Dynamic Tool Registration
|
| 1539 |
+
# =========================================================================
|
| 1540 |
+
|
| 1541 |
+
def register_tool_manually(self,
|
| 1542 |
+
name: str,
|
| 1543 |
+
description: str,
|
| 1544 |
+
parameters: Dict,
|
| 1545 |
+
handler_url: str) -> bool:
|
| 1546 |
+
"""
|
| 1547 |
+
Manually register an external tool without connecting to a full MCP server.
|
| 1548 |
+
Useful for simple webhook-based tools.
|
| 1549 |
+
|
| 1550 |
+
Args:
|
| 1551 |
+
name: Tool name
|
| 1552 |
+
description: Tool description
|
| 1553 |
+
parameters: JSON Schema for parameters
|
| 1554 |
+
handler_url: URL to POST tool calls to
|
| 1555 |
+
"""
|
| 1556 |
+
self.external_tools[name] = {
|
| 1557 |
+
"name": name,
|
| 1558 |
+
"description": description,
|
| 1559 |
+
"inputSchema": parameters,
|
| 1560 |
+
"_server_url": handler_url.rsplit('/', 1)[0] if '/' in handler_url else handler_url,
|
| 1561 |
+
"_handler_url": handler_url
|
| 1562 |
+
}
|
| 1563 |
+
print(f"[MCP] Registered external tool: {name}")
|
| 1564 |
+
return True
|
| 1565 |
+
|
| 1566 |
+
def get_all_tools(self) -> List[Dict]:
|
| 1567 |
+
"""Get all tools (local + external) in MCP format."""
|
| 1568 |
+
tools = [tool.to_mcp_schema() for tool in self.registry.get_all()]
|
| 1569 |
+
tools.extend(self.external_tools.values())
|
| 1570 |
+
return tools
|
| 1571 |
|
| 1572 |
|
| 1573 |
+
# Create global MCP interface
|
| 1574 |
+
mcp_interface = MCPServerInterface(registry)
|
| 1575 |
+
|
| 1576 |
+
|
| 1577 |
+
# =============================================================================
|
| 1578 |
+
# UTILITY FUNCTIONS
|
| 1579 |
+
# =============================================================================
|
| 1580 |
+
|
| 1581 |
+
def get_tool_names() -> List[str]:
|
| 1582 |
+
"""Get list of all registered tool names."""
|
| 1583 |
+
return [tool.name for tool in registry.get_all()]
|
| 1584 |
+
|
| 1585 |
+
|
| 1586 |
+
def get_chart_tools() -> List[str]:
|
| 1587 |
+
"""Get tools that return chart data."""
|
| 1588 |
+
return [tool.name for tool in registry.get_all() if tool.returns_chart]
|
| 1589 |
+
|
| 1590 |
+
|
| 1591 |
+
def get_tools_by_category(category: str) -> List[str]:
|
| 1592 |
+
"""Get tool names by category."""
|
| 1593 |
+
return [tool.name for tool in registry.get_by_category(category)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|