● Zion Boggan
repos/Darwin/cortex/adapters/mcp_base.py
zionboggan.com ↗
48 lines · python
History for this file →
1
"""Thin MCP SSE client helper.
2
 
3
Uses the `mcp` Python SDK's sse_client transport to connect to an SSE MCP server,
4
call one tool, and return the raw text result. Falls back gracefully on any failure.
5
"""
6
from __future__ import annotations
7
 
8
import asyncio
9
import json
10
from contextlib import asynccontextmanager
11
from typing import Any, AsyncGenerator
12
 
13
import httpx
14
from mcp.client.sse import sse_client
15
from mcp import ClientSession
16
 
17
 
18
async def call_mcp_tool(
19
    base_url: str,
20
    tool_name: str,
21
    arguments: dict[str, Any],
22
    timeout: float = 3.5,
23
) -> list[Any]:
24
    """Call an MCP tool over SSE and return parsed content blocks.
25
 
26
    Each content block's text is JSON-parsed when possible.  The result may be:
27
      - A dict  (e.g. {"total": N, "results": [...]} from CBM search_graph)
28
      - A list  (e.g. [...entities...] from memory-graph query_entities)
29
      - A dict with "text" key (plain-text fallback when JSON parse fails)
30
 
31
    Returns empty list on any failure (timeout, connection error, parse error).
32
    """
33
    try:
34
        async with asyncio.timeout(timeout):
35
            async with sse_client(base_url) as (read, write):
36
                async with ClientSession(read, write) as session:
37
                    await session.initialize()
38
                    result = await session.call_tool(tool_name, arguments=arguments)
39
                    out: list[Any] = []
40
                    for block in (result.content or []):
41
                        if hasattr(block, "text"):
42
                            try:
43
                                out.append(json.loads(block.text))
44
                            except (json.JSONDecodeError, TypeError):
45
                                out.append({"text": block.text})
46
                    return out
47
    except Exception:
48
        return []