|
| 1 | +"""Async client for BioMCP MCP server. |
| 2 | +
|
| 3 | +Connects to a BioMCP HTTP sidecar and queries drug interaction data |
| 4 | +from DrugBank via MyChem.info. |
| 5 | +""" |
| 6 | + |
| 7 | +import json |
| 8 | +import logging |
| 9 | +import os |
| 10 | +import shlex |
| 11 | +import time |
| 12 | +from contextlib import AbstractAsyncContextManager |
| 13 | + |
| 14 | +import httpx |
| 15 | +from mcp import ClientSession |
| 16 | +from mcp.client.streamable_http import streamable_http_client |
| 17 | + |
| 18 | +logger = logging.getLogger(__name__) |
| 19 | + |
| 20 | +BIOMCP_BASE_URL = os.environ.get("BIOMCP_URL", "http://biomcp:8080/mcp").rsplit("/mcp", 1)[0] |
| 21 | +BIOMCP_URL = f"{BIOMCP_BASE_URL}/mcp" |
| 22 | + |
| 23 | +_session: ClientSession | None = None |
| 24 | +_streams: AbstractAsyncContextManager | None = None |
| 25 | +_tool_name: str = "biomcp" # discovered at connect() via list_tools() |
| 26 | + |
| 27 | +# Simple TTL cache: {key: (value, expiry_timestamp)} |
| 28 | +_cache: dict[str, tuple[object, float]] = {} |
| 29 | +_CACHE_TTL = 86400 # 24 hours |
| 30 | + |
| 31 | + |
| 32 | +class BioMCPUnavailableError(Exception): |
| 33 | + """Raised when BioMCP sidecar is unreachable or returns an error.""" |
| 34 | + |
| 35 | + |
| 36 | +def _cache_get(key: str) -> object | None: |
| 37 | + if key in _cache: |
| 38 | + value, expiry = _cache[key] |
| 39 | + if time.time() < expiry: |
| 40 | + return value |
| 41 | + del _cache[key] |
| 42 | + return None |
| 43 | + |
| 44 | + |
| 45 | +def _cache_set(key: str, value: object) -> None: |
| 46 | + _cache[key] = (value, time.time() + _CACHE_TTL) |
| 47 | + |
| 48 | + |
| 49 | +async def connect() -> None: |
| 50 | + """Establish MCP session with the BioMCP sidecar. |
| 51 | +
|
| 52 | + Silently degrades to _session=None on failure (graceful degradation). |
| 53 | + Callers should handle BioMCPUnavailableError raised by get_interactions(). |
| 54 | + """ |
| 55 | + global _session, _streams, _tool_name |
| 56 | + try: |
| 57 | + _streams = streamable_http_client(BIOMCP_URL) |
| 58 | + read_stream, write_stream, _ = await _streams.__aenter__() |
| 59 | + try: |
| 60 | + _session = ClientSession(read_stream, write_stream) |
| 61 | + await _session.__aenter__() |
| 62 | + await _session.initialize() |
| 63 | + # Discover the actual tool name — versions ≤0.8.14 use "shell", |
| 64 | + # ≥0.8.15 use "biomcp". Fall back to default if neither is found. |
| 65 | + tools = await _session.list_tools() |
| 66 | + names = {t.name for t in tools.tools} |
| 67 | + if "biomcp" in names: |
| 68 | + _tool_name = "biomcp" |
| 69 | + elif "shell" in names: |
| 70 | + _tool_name = "shell" |
| 71 | + logger.warning("BioMCP tool named 'shell' (pre-0.8.15); upgrade for 'biomcp'") |
| 72 | + else: |
| 73 | + logger.warning("Unexpected BioMCP tool names: %s; defaulting to 'biomcp'", names) |
| 74 | + logger.info("Connected to BioMCP at %s (tool=%s)", BIOMCP_URL, _tool_name) |
| 75 | + except Exception: |
| 76 | + # Clean up transport if session init fails |
| 77 | + await _streams.__aexit__(None, None, None) |
| 78 | + raise |
| 79 | + except Exception: |
| 80 | + logger.warning("Failed to connect to BioMCP at %s", BIOMCP_URL, exc_info=True) |
| 81 | + _session = None |
| 82 | + _streams = None |
| 83 | + |
| 84 | + |
| 85 | +async def close() -> None: |
| 86 | + """Close the MCP session.""" |
| 87 | + global _session, _streams |
| 88 | + try: |
| 89 | + if _session is not None: |
| 90 | + try: |
| 91 | + await _session.__aexit__(None, None, None) |
| 92 | + except Exception: |
| 93 | + pass |
| 94 | + _session = None |
| 95 | + finally: |
| 96 | + if _streams is not None: |
| 97 | + try: |
| 98 | + await _streams.__aexit__(None, None, None) |
| 99 | + except Exception: |
| 100 | + pass |
| 101 | + _streams = None |
| 102 | + |
| 103 | + |
| 104 | +async def health_check() -> bool: |
| 105 | + """Check if BioMCP sidecar is reachable and MCP session is active.""" |
| 106 | + if _session is None: |
| 107 | + return False |
| 108 | + try: |
| 109 | + async with httpx.AsyncClient(timeout=5.0) as client: |
| 110 | + resp = await client.get(f"{BIOMCP_BASE_URL}/health") |
| 111 | + return resp.status_code == 200 |
| 112 | + except Exception: |
| 113 | + return False |
| 114 | + |
| 115 | + |
| 116 | +async def get_interactions(drug_name: str) -> list[dict]: |
| 117 | + """Get drug-drug interactions for a given drug name. |
| 118 | +
|
| 119 | + Returns list of {"drug": str, "description": str | None}. |
| 120 | + Raises BioMCPUnavailableError if BioMCP is unreachable. |
| 121 | + """ |
| 122 | + cache_key = f"interactions:{drug_name.lower()}" |
| 123 | + cached = _cache_get(cache_key) |
| 124 | + if cached is not None: |
| 125 | + return cached |
| 126 | + |
| 127 | + if _session is None: |
| 128 | + raise BioMCPUnavailableError("BioMCP session not established") |
| 129 | + |
| 130 | + try: |
| 131 | + result = await _session.call_tool( |
| 132 | + _tool_name, |
| 133 | + {"command": f"get drug {shlex.quote(drug_name)} interactions --json"}, |
| 134 | + ) |
| 135 | + except Exception as exc: |
| 136 | + raise BioMCPUnavailableError(f"BioMCP call failed: {exc}") from exc |
| 137 | + if result.isError: |
| 138 | + raise BioMCPUnavailableError(f"BioMCP returned error for {drug_name}") |
| 139 | + |
| 140 | + # Parse the response — BioMCP returns JSON in content[0].text |
| 141 | + try: |
| 142 | + content_block = result.content[0] |
| 143 | + if not hasattr(content_block, "text"): |
| 144 | + logger.warning("BioMCP returned unexpected content type for %s", drug_name) |
| 145 | + interactions = [] |
| 146 | + else: |
| 147 | + data = json.loads(content_block.text) |
| 148 | + interactions = data.get("interactions", []) |
| 149 | + except (json.JSONDecodeError, IndexError): |
| 150 | + interactions = [] |
| 151 | + |
| 152 | + _cache_set(cache_key, interactions) |
| 153 | + return interactions |
0 commit comments