ReMe/reme/components/client/mcp_client.py
jinliyl 54fa3381d7
Some checks failed
CI and Release / Docker / Build and test / amd64 (push) Has been cancelled
CI and Release / Docker / Build and test / arm64 (push) Has been cancelled
Security / CodeQL / Analyze python (push) Has been cancelled
CI / Python quality / Pre-commit (push) Has been cancelled
CI / Python tests / Unit Tests - py3.12 (push) Has been cancelled
CI / Python tests / Unit Tests - py3.13 (push) Has been cancelled
CI / Python tests / Unit Tests - py3.14 (push) Has been cancelled
CI / Python packages / Build and verify distributions (push) Has been cancelled
CI / Python quality / GitHub Actions (push) Has been cancelled
CI / Python tests / Hermes embedded - ubuntu-latest (push) Has been cancelled
CI / Python tests / Hermes embedded - windows-latest (push) Has been cancelled
CI / Python tests / Unit Tests - py3.11 (push) Has been cancelled
CI / ReMe Studio / Studio checks (push) Has been cancelled
Deploy / Documentation / Build documentation (push) Has been cancelled
CI / Windows / CLI smoke - py3.11 (push) Has been cancelled
Security / CodeQL / Analyze javascript-typescript (push) Has been cancelled
CI and Release / Docker / Publish multi-platform tags (push) Has been cancelled
Deploy / Documentation / deploy (push) Has been cancelled
refactor(core): reorganize the ReMe runtime and shared helpers (#769)
* refactor(core): reorganize the ReMe runtime and shared helpers

* test(status): import the base component from its canonical module

* test: remove redundant unit checks

* refactor(core): use canonical runtime imports and shared CLI discovery

Restore evolve behavior to the base branch and update its imports. Use Application as the runtime entry point and encode SSE in the HTTP service.

* fix(cli): honor caller config when service replay is incomplete

Use partial startup overrides for port probes and resolve named configs before requesting the service process working directory.
2026-11-20 22:06:46 +08:00

139 lines
5.3 KiB
Python

"""MCP client for ReMe services."""
from collections.abc import AsyncGenerator
from typing import TYPE_CHECKING, Any
from ...constants import DEFAULT_MCP_PATH, DEFAULT_MCP_SSE_PATH
from .base_client import BaseClient
from ...core.registry import R
if TYPE_CHECKING:
from fastmcp.client.client import CallToolResult
_VALID_TRANSPORTS = {"sse", "stdio", "streamable-http"}
@R.register("mcp")
class MCPClient(BaseClient):
"""MCP client that communicates with ReMe MCP service via fastmcp.Client.
Usage:
# SSE (default)
client = MCPClient(host="localhost", port=8000)
async with client:
async for text in client(action="my_tool", query="hello"):
print(text)
# Streamable HTTP
client = MCPClient(transport="streamable-http", host="localhost", port=8000)
# Stdio
client = MCPClient(transport="stdio", command="python", args=["server.py"])
# Custom transport object
from fastmcp.client import SSETransport
client = MCPClient(transport=SSETransport(url="http://host:port/sse"))
"""
def __init__(
self,
transport: str | Any = "sse",
host: str | None = None,
port: int | None = None,
timeout: float = 30.0,
**kwargs,
):
super().__init__(**kwargs)
if isinstance(transport, str) and transport not in _VALID_TRANSPORTS:
raise ValueError(f"Unknown transport: {transport!r}, expected one of {sorted(_VALID_TRANSPORTS)}")
if isinstance(transport, str) and transport != "stdio":
self.host, self.port = self._resolve_service_address(host, port)
self.transport = transport
self.timeout = timeout
def _build_transport(self):
if not isinstance(self.transport, str):
return self.transport
from fastmcp.client import SSETransport, StdioTransport, StreamableHttpTransport
transport_map = {
"sse": SSETransport,
"stdio": StdioTransport,
"streamable-http": StreamableHttpTransport,
}
cls = transport_map[self.transport]
if self.transport == "stdio":
command = self.kwargs.get("command", "")
args = self.kwargs.get("args", [])
return cls(command=command, args=args)
path = DEFAULT_MCP_SSE_PATH if self.transport == "sse" else DEFAULT_MCP_PATH
url = self._build_service_url(self.host, self.port, path)
return cls(url=url)
# pylint: disable=unnecessary-dunder-call
async def _start(self) -> None:
if self.client is None:
from fastmcp import Client
self.client = Client(self._build_transport(), timeout=self.timeout)
await self.client.__aenter__()
# pylint: disable=invalid-overridden-method
async def _execute(self, action: str, payload: dict) -> AsyncGenerator[str, None]:
if self.client is None:
raise RuntimeError("Client not initialized. Call _start() first.")
result: "CallToolResult" = await self.client.call_tool(action, payload)
yield self._extract_text(result)
async def list_actions(self) -> list[dict]:
"""Return MCP tool descriptors using the SDK's snake_case field names."""
if self.client is None:
raise RuntimeError("Client not initialized. Call _start() first.")
tools = await self.client.list_tools()
actions = []
for tool in tools:
action = tool.model_dump()
# SDK 1 uses wire names as Python fields; preserve the SDK 2 catalog
# contract without rewriting user-owned schemas or metadata.
for wire, field in (("inputSchema", "input_schema"), ("outputSchema", "output_schema"), ("_meta", "meta")):
if wire in action:
action[field] = action.pop(wire)
annotations = action.get("annotations")
if isinstance(annotations, dict):
for wire, field in (
("readOnlyHint", "read_only_hint"),
("destructiveHint", "destructive_hint"),
("idempotentHint", "idempotent_hint"),
("openWorldHint", "open_world_hint"),
):
if wire in annotations:
annotations[field] = annotations.pop(wire)
execution = action.get("execution")
if isinstance(execution, dict) and "taskSupport" in execution:
execution["task_support"] = execution.pop("taskSupport")
for icon in action.get("icons") or []:
if isinstance(icon, dict) and "mimeType" in icon:
icon["mime_type"] = icon.pop("mimeType")
actions.append(action)
return actions
# pylint: disable=unnecessary-dunder-call
async def _close(self) -> None:
if self.client is not None:
await self.client.__aexit__(None, None, None)
self.client = None
@staticmethod
def _extract_text(result: "CallToolResult") -> str:
"""Join text blocks in order and ignore non-text content when text is available."""
texts = [block.text for block in result.content if isinstance(getattr(block, "text", None), str)]
if texts:
return "\n".join(texts)
return str(result.content)