crypto_client.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. from __future__ import annotations
  2. from typing import Any
  3. import json
  4. import anyio
  5. from mcp import ClientSession
  6. from mcp.client.sse import sse_client
  7. async def get_regime(base_url: str, symbol: str, timeframe: str = "1h") -> dict[str, Any]:
  8. async with sse_client(base_url) as (read_stream, write_stream):
  9. async with ClientSession(read_stream, write_stream) as session:
  10. await session.initialize()
  11. result = await session.call_tool("get_regime", {"symbol": symbol, "timeframe": timeframe})
  12. content = getattr(result, "content", None)
  13. if not content:
  14. return {"error": "EMPTY_RESULT", "symbol": symbol, "timeframe": timeframe}
  15. # FastMCP commonly returns tool results as text content blocks.
  16. first = content[0]
  17. text = getattr(first, "text", None)
  18. if text is None and isinstance(first, dict):
  19. text = first.get("text")
  20. if text is None:
  21. return {"error": "UNPARSEABLE_RESULT", "symbol": symbol, "timeframe": timeframe}
  22. try:
  23. return json.loads(text)
  24. except Exception:
  25. return {"raw": text, "symbol": symbol, "timeframe": timeframe}
  26. async def get_price(base_url: str, symbol: str) -> dict[str, Any]:
  27. async with sse_client(base_url) as (read_stream, write_stream):
  28. async with ClientSession(read_stream, write_stream) as session:
  29. await session.initialize()
  30. result = await session.call_tool("get_price", {"symbol": symbol})
  31. content = getattr(result, "content", None)
  32. if not content:
  33. return {"error": "EMPTY_RESULT", "symbol": symbol}
  34. first = content[0]
  35. text = getattr(first, "text", None)
  36. if text is None and isinstance(first, dict):
  37. text = first.get("text")
  38. if text is None:
  39. return {"error": "UNPARSEABLE_RESULT", "symbol": symbol}
  40. try:
  41. return json.loads(text)
  42. except Exception:
  43. return {"raw": text, "symbol": symbol}