Files

472 lines
16 KiB
Python

"""Минимальный MCP-клиент поверх stdio.
Клиент запускает внешний процесс, обменивается с ним построчными
JSON-RPC 2.0 сообщениями, маршрутизирует ответы по id из отдельного
потока-читателя и поддерживает таймауты запросов.
Пример:
from XUI.core.mcp.client import start_fs_server
client = start_fs_server(["/tmp/project"])
client.start()
tools = client.list_tools()
result = client.call_tool("read_file", {"path": "README.md"})
client.stop()
"""
from __future__ import annotations
import json
import os
import subprocess
import sys
import threading
from collections import deque
from dataclasses import dataclass, field
from typing import Any, Callable
PROTOCOL_VERSION = "2025-06-18"
CLIENT_NAME = "xenith-mcp-client"
CLIENT_VERSION = "1.0"
class MCPError(RuntimeError):
"""Ошибка MCP-протокола или транспорта."""
def __init__(self, message: str, *, code: int | None = None, data: Any = None):
super().__init__(message)
self.code = code
self.data = data
class MCPTimeoutError(MCPError, TimeoutError):
"""Истёк таймаут ожидания ответа."""
@dataclass
class _Pending:
method: str
event: threading.Event = field(default_factory=threading.Event)
result: Any = None
error: dict[str, Any] | None = None
NotificationCallback = Callable[[dict[str, Any]], None]
StderrCallback = Callable[[str], None]
class MCPStdioClient:
"""Потокобезопасный клиент для MCP-сервера, работающего через stdio."""
def __init__(
self,
command: list[str],
env: dict[str, str] | None = None,
cwd: str | None = None,
on_notification: NotificationCallback | None = None,
on_stderr: StderrCallback | None = None,
):
if not command or not all(isinstance(part, str) for part in command):
raise ValueError("command must be a non-empty list of strings")
self.command = list(command)
self.env = dict(env) if env is not None else None
self.cwd = cwd
self.on_notification = on_notification
self.on_stderr = on_stderr
self._proc: subprocess.Popen[str] | None = None
self._next_id = 0
self._pending: dict[int, _Pending] = {}
self._lock = threading.RLock()
self._write_lock = threading.Lock()
self._reader: threading.Thread | None = None
self._stderr_thread: threading.Thread | None = None
self._stderr_lines: deque[str] = deque(maxlen=1000)
self._notifications: deque[dict[str, Any]] = deque(maxlen=100)
self._init_result: dict[str, Any] | None = None
# ---- Управление процессом --------------------------------------------
@property
def is_running(self) -> bool:
with self._lock:
proc = self._proc
return proc is not None and proc.poll() is None
@property
def initialize_result(self) -> dict[str, Any] | None:
return self._init_result
@property
def notifications(self) -> list[dict[str, Any]]:
with self._lock:
return list(self._notifications)
def stderr_text(self) -> str:
with self._lock:
return "".join(self._stderr_lines)
def start(self) -> dict[str, Any]:
"""Запускает процесс, выполняет initialize и шлёт notifications/initialized."""
with self._lock:
if self._proc is not None:
raise MCPError("client is already started")
full_env = os.environ.copy()
if self.env:
full_env.update({str(key): str(value) for key, value in self.env.items()})
try:
proc = subprocess.Popen(
self.command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
encoding="utf-8",
errors="replace",
bufsize=1,
cwd=self.cwd,
env=full_env,
)
except (OSError, ValueError) as exc:
raise MCPError(f"failed to start MCP server: {exc}") from exc
with self._lock:
self._proc = proc
self._reader = threading.Thread(
target=self._reader_loop,
args=(proc,),
name="mcp-stdio-reader",
daemon=True,
)
self._stderr_thread = threading.Thread(
target=self._stderr_loop,
args=(proc,),
name="mcp-stdio-stderr",
daemon=True,
)
reader = self._reader
stderr_thread = self._stderr_thread
reader.start()
stderr_thread.start()
try:
init = self._request(
"initialize",
{
"protocolVersion": PROTOCOL_VERSION,
"capabilities": {},
"clientInfo": {"name": CLIENT_NAME, "version": CLIENT_VERSION},
},
timeout=15.0,
)
if not isinstance(init, dict):
raise MCPError("invalid initialize response: expected an object")
if not isinstance(init.get("protocolVersion"), str):
raise MCPError("invalid initialize response: missing protocolVersion")
self._init_result = init
self._send({"jsonrpc": "2.0", "method": "notifications/initialized"})
return init
except BaseException:
self.stop()
raise
def stop(self) -> None:
"""Завершает процесс и джойнит фоновые потоки. Идемпотентно."""
with self._lock:
proc = self._proc
if proc is None:
self._join_threads()
return
self._fail_pending(-32000, "client stopped")
try:
if proc.stdin is not None and not proc.stdin.closed:
proc.stdin.close()
except (OSError, ValueError):
pass
if proc.poll() is None:
try:
proc.terminate()
proc.wait(timeout=5.0)
except subprocess.TimeoutExpired:
try:
proc.kill()
except OSError:
pass
try:
proc.wait(timeout=5.0)
except subprocess.TimeoutExpired:
pass
except OSError:
pass
with self._lock:
if self._proc is proc:
self._proc = None
self._join_threads()
def _join_threads(self) -> None:
current = threading.current_thread()
with self._lock:
threads = [self._reader, self._stderr_thread]
for thread in threads:
if thread is None or thread is current:
continue
if thread.is_alive():
thread.join(timeout=5.0)
def __enter__(self) -> "MCPStdioClient":
self.start()
return self
def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
self.stop()
# ---- Публичные запросы ------------------------------------------------
def list_tools(self) -> list[dict[str, Any]]:
"""Возвращает все инструменты, при необходимости обходя nextCursor."""
tools: list[dict[str, Any]] = []
cursor: str | None = None
for _ in range(50):
params = {"cursor": cursor} if cursor else {}
result = self._request("tools/list", params, timeout=30.0)
if not isinstance(result, dict):
raise MCPError("invalid tools/list response")
page = result.get("tools") or []
if not isinstance(page, list):
raise MCPError("invalid tools/list response: tools is not a list")
tools.extend(item for item in page if isinstance(item, dict))
cursor = result.get("nextCursor")
if not cursor:
break
return tools
def call_tool(
self,
name: str,
arguments: dict[str, Any] | None = None,
timeout: float = 30.0,
) -> dict[str, Any]:
"""Вызывает инструмент и возвращает сырой MCP-результат."""
if not isinstance(name, str) or not name:
raise ValueError("tool name must be a non-empty string")
if arguments is None:
arguments = {}
if not isinstance(arguments, dict):
raise TypeError("arguments must be a dictionary")
result = self._request(
"tools/call",
{"name": name, "arguments": arguments},
timeout=timeout,
)
if not isinstance(result, dict):
raise MCPError("invalid tools/call response: expected an object")
return result
def ping(self, timeout: float = 10.0) -> dict[str, Any]:
result = self._request("ping", {}, timeout=timeout)
return result if isinstance(result, dict) else {}
# ---- Транспорт --------------------------------------------------------
def _request(self, method: str, params: dict[str, Any] | None = None,
timeout: float = 30.0) -> Any:
if timeout <= 0:
raise ValueError("timeout must be greater than zero")
with self._lock:
if self._proc is None:
raise MCPError("client is not started")
self._next_id += 1
request_id = self._next_id
pending = _Pending(method=method)
self._pending[request_id] = pending
message: dict[str, Any] = {
"jsonrpc": "2.0",
"id": request_id,
"method": method,
}
if params is not None:
message["params"] = params
try:
self._send(message)
except BaseException:
with self._lock:
self._pending.pop(request_id, None)
raise
if not pending.event.wait(timeout):
with self._lock:
self._pending.pop(request_id, None)
raise MCPTimeoutError(
f"timeout after {timeout:g}s while waiting for {method}"
)
if pending.error is not None:
error = pending.error
code = error.get("code")
message_text = error.get("message", "unknown MCP error")
raise MCPError(
f"{method}: {message_text} (code {code})",
code=code if isinstance(code, int) else None,
data=error.get("data"),
)
return pending.result
def _send(self, message: dict[str, Any]) -> None:
with self._lock:
proc = self._proc
if proc is None or proc.stdin is None:
raise MCPError("client is not started")
payload = json.dumps(message, ensure_ascii=False, separators=(",", ":")) + "\n"
with self._write_lock:
try:
proc.stdin.write(payload)
proc.stdin.flush()
except (BrokenPipeError, OSError, ValueError) as exc:
exit_code = proc.poll()
tail = self.stderr_text().strip().splitlines()[-5:]
detail = (" | ".join(tail)) if tail else "no stderr output"
raise MCPError(
f"failed to send {message.get('method')}: "
f"process exited (code {exit_code}); {detail}"
) from exc
# ---- Фоновые потоки ---------------------------------------------------
def _reader_loop(self, proc: subprocess.Popen[str]) -> None:
stream = proc.stdout
try:
if stream is None:
return
while True:
line = stream.readline()
if line == "":
break
line = line.strip()
if not line:
continue
try:
message = json.loads(line)
except json.JSONDecodeError:
self._record_stderr(f"invalid JSON from server: {line[:500]}")
continue
if not isinstance(message, dict):
self._record_stderr("server sent a non-object JSON message")
continue
if "id" in message and ("result" in message or "error" in message):
request_id = message.get("id")
if not isinstance(request_id, int):
# Наш клиент всегда использует целые id.
self._record_stderr(f"response with unsupported id: {request_id!r}")
continue
with self._lock:
pending = self._pending.pop(request_id, None)
if pending is None:
self._record_stderr(f"response for unknown request id={request_id}")
continue
pending.result = message.get("result")
error = message.get("error")
pending.error = error if isinstance(error, dict) else None
pending.event.set()
continue
method = message.get("method")
if isinstance(method, str):
with self._lock:
self._notifications.append(message)
callback = self.on_notification
if callback is not None:
try:
callback(message)
except Exception as exc: # noqa: BLE001
self._record_stderr(
f"notification callback error for {method}: {exc}"
)
continue
self._record_stderr(f"unknown server message: {line[:500]}")
finally:
exit_code = proc.poll()
self._fail_pending(
-32000,
f"MCP server closed the connection (exit code {exit_code})",
)
def _stderr_loop(self, proc: subprocess.Popen[str]) -> None:
stream = proc.stderr
if stream is None:
return
try:
for line in stream:
self._record_stderr(line.rstrip("\n"))
except (OSError, ValueError):
pass
def _record_stderr(self, line: str) -> None:
with self._lock:
self._stderr_lines.append(line + "\n")
callback = self.on_stderr
if callback is not None:
try:
callback(line)
except Exception:
pass
def _fail_pending(self, code: int, message: str) -> None:
with self._lock:
pending_items = list(self._pending.values())
self._pending.clear()
for pending in pending_items:
pending.error = {"code": code, "message": message}
pending.event.set()
# ---------------------------------------------------------------------------
# Помощник для встроенного fs-сервера
# ---------------------------------------------------------------------------
def _project_root() -> str:
"""XUI/core/mcp/client.py -> корень проекта (без импорта остального XUI)."""
here = os.path.abspath(__file__)
return os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(here))))
def start_fs_server(roots: list[str]) -> MCPStdioClient:
"""Создаёт (но не запускает) клиента для XUI.core.mcp.fs_server."""
if not roots:
raise ValueError("at least one root directory is required")
if getattr(sys, "frozen", False) or getattr(sys, "_MEIPASS", None):
command = [sys.executable, "--xenith-fs-server"]
else:
command = [sys.executable, "-m", "XUI.core.mcp.fs_server"]
for root in roots:
command.extend(["--root", os.path.abspath(os.fspath(root))])
env = os.environ.copy()
project_root = _project_root()
old_pythonpath = env.get("PYTHONPATH")
if old_pythonpath:
env["PYTHONPATH"] = project_root + os.pathsep + old_pythonpath
else:
env["PYTHONPATH"] = project_root
return MCPStdioClient(command, env=env)