add mcp servers

This commit is contained in:
timka123 committed 2026-11-23 16:35:53 +03:00
1 parent ae966d7017
commit 9ac0d1aa63
30 files changed
+8070 -21

No files matched your search

+52
View File
@@ -0,0 +1,52 @@
"""MCP (Model Context Protocol) Connectors client, auth, and manager package."""
from homeagent.mcp.auth import (
MCPAuthError,
MCPAuthManager,
MCPAuthRequiredError,
OAuthTokenRecord,
OAuthTokenStore,
PendingOAuthDevice,
PendingOAuthPKCE,
)
from homeagent.mcp.client import MCPClient, MCPProtocolError
from homeagent.mcp.manager import MCPConnectorManager
from homeagent.mcp.models import (
AuthType,
ConnectorStatus,
MCPAuthConfig,
MCPConnectorConfig,
MCPConnectorState,
MCPToolInfo,
TransportType,
expand_env_vars,
mask_secret,
parse_connectors_payload,
sanitize_mcp_input_schema,
sanitize_tool_name,
)
__all__ = [
"AuthType",
"ConnectorStatus",
"MCPAuthConfig",
"MCPAuthError",
"MCPAuthManager",
"MCPAuthRequiredError",
"MCPClient",
"MCPConnectorConfig",
"MCPConnectorManager",
"MCPConnectorState",
"MCPProtocolError",
"MCPToolInfo",
"OAuthTokenRecord",
"OAuthTokenStore",
"PendingOAuthDevice",
"PendingOAuthPKCE",
"TransportType",
"expand_env_vars",
"mask_secret",
"parse_connectors_payload",
"sanitize_mcp_input_schema",
"sanitize_tool_name",
]
File diff suppressed because it is too large. Load diff
+864
View File
@@ -0,0 +1,864 @@
"""Async MCP Client with Streamable HTTP, Legacy SSE, Auto-detect, and Stdio transports."""
from __future__ import annotations
import asyncio
import json
import logging
import os
from abc import ABC, abstractmethod
from typing import Any, Optional
from urllib.parse import urljoin
import httpx
from homeagent.mcp.auth import (
MCPAuthError,
MCPAuthManager,
MCPAuthRequiredError,
parse_www_authenticate,
)
from homeagent.mcp.models import MCPConnectorConfig, is_loopback_url
logger = logging.getLogger(__name__)
MCP_PROTOCOL_VERSION = "2025-03-26"
_STDIO_READER_LIMIT = 16 * 1024 * 1024 # 16 MiB
class MCPProtocolError(Exception):
"""Raised when an MCP transport or JSON-RPC protocol error occurs."""
def __init__(self, message: str, *, status_code: Optional[int] = None, code: Optional[int] = None) -> None:
super().__init__(message)
self.status_code = status_code
self.code = code
def _parse_sse_text_messages(raw_text: str) -> list[dict[str, Any]]:
"""Parse JSON-RPC payloads from a buffered `text/event-stream` HTTP response body."""
messages: list[dict[str, Any]] = []
data_lines: list[str] = []
def _flush() -> None:
nonlocal data_lines
if not data_lines:
return
payload = "\n".join(data_lines).strip()
data_lines = []
if not payload or payload == "[DONE]":
return
try:
parsed = json.loads(payload)
if isinstance(parsed, dict):
messages.append(parsed)
elif isinstance(parsed, list):
messages.extend(item for item in parsed if isinstance(item, dict))
except json.JSONDecodeError:
logger.debug("Skipping non-JSON SSE data frame: %s", payload[:200])
for line in raw_text.splitlines():
if not line.strip():
_flush()
continue
if line.startswith(":"):
continue
if line.startswith("data:"):
data_lines.append(line[5:].lstrip(" "))
_flush()
return messages
def _format_tool_call_result(result: dict[str, Any]) -> str:
"""Format an MCP `tools/call` result dict into clean text for the LLM agent."""
is_error = bool(result.get("isError"))
parts: list[str] = []
content = result.get("content")
if isinstance(content, list):
for item in content:
if not isinstance(item, dict):
parts.append(str(item))
continue
item_type = item.get("type")
if item_type == "text":
text = item.get("text")
if text is not None:
parts.append(str(text))
elif item_type == "resource":
res = item.get("resource") or {}
uri = res.get("uri", "")
if res.get("text") is not None:
header = f"[Resource: {uri}]\n" if uri else ""
parts.append(f"{header}{res['text']}")
elif res.get("blob"):
mime = res.get("mimeType", "application/octet-stream")
parts.append(f"[Binary Resource: {uri} ({mime}, {len(res['blob'])} base64 chars)]")
elif item_type == "resource_link":
uri = item.get("uri", "")
name = item.get("name") or uri
desc = item.get("description") or ""
parts.append(f"[Resource Link: {name} ({uri})]{(' - ' + desc) if desc else ''}")
elif item_type == "image":
mime = item.get("mimeType", "image/*")
parts.append(f"[Image: {mime}]")
elif item_type == "audio":
mime = item.get("mimeType", "audio/*")
parts.append(f"[Audio: {mime}]")
else:
parts.append(json.dumps(item, ensure_ascii=False))
structured = result.get("structuredContent")
if structured is not None and not parts:
parts.append(json.dumps(structured, ensure_ascii=False, indent=2))
elif structured is not None:
parts.append("\nStructured content:\n" + json.dumps(structured, ensure_ascii=False, indent=2))
body = "\n".join(p for p in parts if p).strip()
if not body:
body = json.dumps(result, ensure_ascii=False)
if is_error:
return f"MCP Tool Error: {body}"
return body
class BaseMCPTransport(ABC):
"""Abstract base class for MCP transports."""
transport_name: str = "unknown"
@abstractmethod
async def connect(self) -> None:
pass
@abstractmethod
async def request(self, method: str, params: Optional[dict[str, Any]] = None) -> dict[str, Any]:
pass
@abstractmethod
async def notify(self, method: str, params: Optional[dict[str, Any]] = None) -> None:
pass
@abstractmethod
async def close(self) -> None:
pass
class StreamableHTTPTransport(BaseMCPTransport):
"""MCP Streamable HTTP transport (spec 2025-03-26+)."""
transport_name = "streamable_http"
def __init__(self, config: MCPConnectorConfig, auth_manager: MCPAuthManager) -> None:
self.config = config
self.auth_manager = auth_manager
self._resolved = config.resolved()
self._url = (self._resolved.url or "").strip()
self._client: Optional[httpx.AsyncClient] = None
self._session_id: Optional[str] = None
self._protocol_version: Optional[str] = None
self._next_id = 1
self._lock = asyncio.Lock()
async def connect(self) -> None:
if not self._url:
raise MCPProtocolError(f"Коннектор '{self.config.name}' не имеет URL.")
self._client = httpx.AsyncClient(
timeout=httpx.Timeout(float(self.config.timeout_seconds), connect=20.0),
verify=self.config.verify_ssl,
follow_redirects=True,
trust_env=not is_loopback_url(self._url),
)
def set_protocol_version(self, version: str) -> None:
self._protocol_version = version
async def _post_jsonrpc(self, payload: dict[str, Any], *, expect_response: bool) -> Optional[dict[str, Any]]:
if self._client is None:
await self.connect()
assert self._client is not None
for attempt in range(2):
auth_headers, query_params = await self.auth_manager.build_request_auth(self.config)
headers = {
"Content-Type": "application/json",
"Accept": "application/json, text/event-stream",
**auth_headers,
}
if self._session_id:
headers["Mcp-Session-Id"] = self._session_id
if self._protocol_version:
headers["MCP-Protocol-Version"] = self._protocol_version
try:
resp = await self._client.post(
self._url,
json=payload,
headers=headers,
params=query_params or None,
)
except httpx.HTTPError as e:
raise MCPProtocolError(f"Ошибка соединения с {self._url}: {e}") from e
if resp.status_code == 401:
www_auth = resp.headers.get("WWW-Authenticate", "")
if attempt == 0 and await self.auth_manager.handle_unauthorized(self.config, www_auth):
continue
challenge = parse_www_authenticate(www_auth)
raise MCPAuthRequiredError(
f"Сервер '{self.config.name}' вернул HTTP 401 Unauthorized.",
www_authenticate=www_auth,
resource_metadata_url=challenge.get("resource_metadata"),
scope=challenge.get("scope"),
)
session_hdr = resp.headers.get("Mcp-Session-Id") or resp.headers.get("mcp-session-id")
if session_hdr:
self._session_id = session_hdr
if resp.status_code == 202 or (not expect_response and resp.status_code in (200, 204)):
return None
if resp.status_code >= 400:
snippet = resp.text[:400].strip()
raise MCPProtocolError(
f"HTTP {resp.status_code} от {self._url}: {snippet or resp.reason_phrase}",
status_code=resp.status_code,
)
if not expect_response:
return None
content_type = (resp.headers.get("content-type") or "").lower()
req_id = payload.get("id")
if "text/event-stream" in content_type:
messages = _parse_sse_text_messages(resp.text)
for msg in messages:
if msg.get("id") == req_id:
return msg
if messages:
return messages[-1]
raise MCPProtocolError("Сервер вернул пустой SSE-поток без JSON-RPC ответа.")
try:
data = resp.json()
except Exception as e:
raise MCPProtocolError(
f"Некорректный JSON от {self._url} (content-type={content_type}): {resp.text[:200]}"
) from e
if isinstance(data, list):
for item in data:
if isinstance(item, dict) and item.get("id") == req_id:
return item
raise MCPProtocolError(f"JSON-RPC batch ответ не содержит id={req_id}.")
if not isinstance(data, dict):
raise MCPProtocolError(f"Неожиданный формат JSON-RPC ответа: {type(data).__name__}")
return data
raise MCPAuthRequiredError(f"Не удалось авторизоваться на '{self.config.name}' (HTTP 401).")
async def request(self, method: str, params: Optional[dict[str, Any]] = None) -> dict[str, Any]:
async with self._lock:
req_id = self._next_id
self._next_id += 1
payload: dict[str, Any] = {"jsonrpc": "2.0", "id": req_id, "method": method}
if params is not None:
payload["params"] = params
msg = await self._post_jsonrpc(payload, expect_response=True)
if msg is None:
raise MCPProtocolError(f"Пустой ответ на JSON-RPC метод '{method}'.")
if "error" in msg and msg["error"] is not None:
err = msg["error"]
err_msg = err.get("message", str(err)) if isinstance(err, dict) else str(err)
err_code = err.get("code") if isinstance(err, dict) else None
raise MCPProtocolError(f"JSON-RPC error ({method}): {err_msg}", code=err_code)
result = msg.get("result")
return result if isinstance(result, dict) else {"value": result}
async def notify(self, method: str, params: Optional[dict[str, Any]] = None) -> None:
payload: dict[str, Any] = {"jsonrpc": "2.0", "method": method}
if params is not None:
payload["params"] = params
await self._post_jsonrpc(payload, expect_response=False)
async def close(self) -> None:
client = self._client
self._client = None
if client is not None:
if self._session_id:
try:
auth_headers, query_params = await self.auth_manager.build_request_auth(self.config)
headers = {**auth_headers, "Mcp-Session-Id": self._session_id}
await client.delete(self._url, headers=headers, params=query_params or None, timeout=5.0)
except Exception:
pass
await client.aclose()
self._session_id = None
class SSETransport(BaseMCPTransport):
"""Legacy MCP HTTP + SSE transport (spec 2024-11-05)."""
transport_name = "sse"
def __init__(self, config: MCPConnectorConfig, auth_manager: MCPAuthManager) -> None:
self.config = config
self.auth_manager = auth_manager
self._resolved = config.resolved()
self._url = (self._resolved.url or "").strip()
self._client: Optional[httpx.AsyncClient] = None
self._post_url: Optional[str] = None
self._endpoint_ready = asyncio.Event()
self._reader_task: Optional[asyncio.Task[None]] = None
self._reader_error: Optional[Exception] = None
self._pending: dict[Any, asyncio.Future[dict[str, Any]]] = {}
self._next_id = 1
self._lock = asyncio.Lock()
async def connect(self) -> None:
if not self._url:
raise MCPProtocolError(f"Коннектор '{self.config.name}' не имеет URL.")
self._client = httpx.AsyncClient(
timeout=httpx.Timeout(float(self.config.timeout_seconds), connect=20.0, read=None),
verify=self.config.verify_ssl,
follow_redirects=True,
trust_env=not is_loopback_url(self._url),
)
self._endpoint_ready.clear()
self._reader_error = None
self._reader_task = asyncio.create_task(self._run_sse_loop())
try:
await asyncio.wait_for(self._endpoint_ready.wait(), timeout=min(20.0, float(self.config.timeout_seconds)))
except asyncio.TimeoutError:
await self.close()
raise MCPProtocolError(f"Таймаут ожидания SSE event `endpoint` от {self._url}.")
if self._reader_error is not None:
err = self._reader_error
await self.close()
raise err
if not self._post_url:
await self.close()
raise MCPProtocolError(f"SSE сервер {self._url} не прислал URL endpoint.")
async def _run_sse_loop(self) -> None:
assert self._client is not None
try:
for attempt in range(2):
auth_headers, query_params = await self.auth_manager.build_request_auth(self.config)
headers = {"Accept": "text/event-stream", "Cache-Control": "no-cache", **auth_headers}
async with self._client.stream(
"GET",
self._url,
headers=headers,
params=query_params or None,
) as resp:
if resp.status_code == 401:
www_auth = resp.headers.get("WWW-Authenticate", "")
if attempt == 0 and await self.auth_manager.handle_unauthorized(self.config, www_auth):
continue
challenge = parse_www_authenticate(www_auth)
self._reader_error = MCPAuthRequiredError(
f"SSE сервер '{self.config.name}' вернул HTTP 401 Unauthorized.",
www_authenticate=www_auth,
resource_metadata_url=challenge.get("resource_metadata"),
scope=challenge.get("scope"),
)
self._endpoint_ready.set()
return
if resp.status_code >= 400:
body = (await resp.aread()).decode("utf-8", errors="replace")[:300]
self._reader_error = MCPProtocolError(
f"SSE HTTP {resp.status_code} от {self._url}: {body}",
status_code=resp.status_code,
)
self._endpoint_ready.set()
return
event_name = "message"
data_lines: list[str] = []
async for raw_line in resp.aiter_lines():
line = raw_line.rstrip("\r")
if not line:
if data_lines:
data_str = "\n".join(data_lines)
self._dispatch_sse_event(event_name, data_str)
data_lines = []
event_name = "message"
continue
if line.startswith(":"):
continue
if line.startswith("event:"):
event_name = line[6:].strip() or "message"
elif line.startswith("data:"):
data_lines.append(line[5:].lstrip(" "))
break
except asyncio.CancelledError:
raise
except Exception as e:
self._reader_error = e if isinstance(e, (MCPProtocolError, MCPAuthError)) else MCPProtocolError(str(e))
self._endpoint_ready.set()
for fut in list(self._pending.values()):
if not fut.done():
fut.set_exception(self._reader_error)
self._pending.clear()
def _dispatch_sse_event(self, event_name: str, data_str: str) -> None:
if event_name == "endpoint":
endpoint = data_str.strip()
if endpoint:
self._post_url = urljoin(self._url, endpoint)
self._endpoint_ready.set()
return
if event_name == "message":
try:
msg = json.loads(data_str)
except json.JSONDecodeError:
logger.debug("Ignoring non-JSON SSE message: %s", data_str[:200])
return
if isinstance(msg, dict) and "id" in msg:
fut = self._pending.pop(msg["id"], None)
if fut and not fut.done():
fut.set_result(msg)
async def request(self, method: str, params: Optional[dict[str, Any]] = None) -> dict[str, Any]:
if not self._post_url or self._client is None:
raise MCPProtocolError("SSE транспорт не подключен.")
async with self._lock:
req_id = self._next_id
self._next_id += 1
payload: dict[str, Any] = {"jsonrpc": "2.0", "id": req_id, "method": method}
if params is not None:
payload["params"] = params
loop = asyncio.get_running_loop()
fut: asyncio.Future[dict[str, Any]] = loop.create_future()
self._pending[req_id] = fut
try:
auth_headers, query_params = await self.auth_manager.build_request_auth(self.config)
headers = {"Content-Type": "application/json", **auth_headers}
resp = await self._client.post(
self._post_url,
json=payload,
headers=headers,
params=query_params or None,
timeout=float(self.config.timeout_seconds),
)
if resp.status_code == 401:
www_auth = resp.headers.get("WWW-Authenticate", "")
challenge = parse_www_authenticate(www_auth)
raise MCPAuthRequiredError(
f"SSE POST '{self.config.name}' вернул HTTP 401 Unauthorized.",
www_authenticate=www_auth,
resource_metadata_url=challenge.get("resource_metadata"),
scope=challenge.get("scope"),
)
if resp.status_code >= 400:
raise MCPProtocolError(
f"SSE POST HTTP {resp.status_code}: {resp.text[:300]}",
status_code=resp.status_code,
)
# Some SSE servers return inline JSON-RPC response on POST 200
if resp.status_code == 200 and resp.content and "application/json" in (resp.headers.get("content-type") or "").lower():
inline = resp.json()
if isinstance(inline, dict) and inline.get("id") == req_id and not fut.done():
fut.set_result(inline)
msg = await asyncio.wait_for(fut, timeout=float(self.config.timeout_seconds))
except asyncio.TimeoutError:
self._pending.pop(req_id, None)
raise MCPProtocolError(f"Таймаут ожидания ответа SSE на метод '{method}'.")
except Exception:
self._pending.pop(req_id, None)
raise
if "error" in msg and msg["error"] is not None:
err = msg["error"]
err_msg = err.get("message", str(err)) if isinstance(err, dict) else str(err)
err_code = err.get("code") if isinstance(err, dict) else None
raise MCPProtocolError(f"JSON-RPC error ({method}): {err_msg}", code=err_code)
result = msg.get("result")
return result if isinstance(result, dict) else {"value": result}
async def notify(self, method: str, params: Optional[dict[str, Any]] = None) -> None:
if not self._post_url or self._client is None:
return
payload: dict[str, Any] = {"jsonrpc": "2.0", "method": method}
if params is not None:
payload["params"] = params
auth_headers, query_params = await self.auth_manager.build_request_auth(self.config)
headers = {"Content-Type": "application/json", **auth_headers}
await self._client.post(
self._post_url,
json=payload,
headers=headers,
params=query_params or None,
timeout=float(self.config.timeout_seconds),
)
async def close(self) -> None:
task = self._reader_task
self._reader_task = None
if task is not None and not task.done():
task.cancel()
try:
await task
except (asyncio.CancelledError, Exception):
pass
for fut in list(self._pending.values()):
if not fut.done():
fut.cancel()
self._pending.clear()
client = self._client
self._client = None
if client is not None:
await client.aclose()
self._post_url = None
class StdioTransport(BaseMCPTransport):
"""Local subprocess Stdio MCP transport (newline-delimited JSON-RPC 2.0)."""
transport_name = "stdio"
def __init__(self, config: MCPConnectorConfig) -> None:
self.config = config
self._resolved = config.resolved()
self._proc: Optional[asyncio.subprocess.Process] = None
self._stdout_task: Optional[asyncio.Task[None]] = None
self._stderr_task: Optional[asyncio.Task[None]] = None
self._pending: dict[Any, asyncio.Future[dict[str, Any]]] = {}
self._write_lock = asyncio.Lock()
self._next_id = 1
self._stderr_tail: list[str] = []
async def connect(self) -> None:
command = (self._resolved.command or "").strip()
if not command:
raise MCPProtocolError(f"Stdio коннектор '{self.config.name}' не имеет команды.")
env = dict(os.environ)
env.update(self._resolved.env)
try:
self._proc = await asyncio.create_subprocess_exec(
command,
*self._resolved.args,
cwd=self._resolved.cwd or None,
env=env,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
limit=_STDIO_READER_LIMIT,
)
except FileNotFoundError as e:
raise MCPProtocolError(f"Команда '{command}' не найдена в PATH.") from e
except Exception as e:
raise MCPProtocolError(f"Не удалось запустить stdio сервер '{command}': {e}") from e
self._stdout_task = asyncio.create_task(self._read_stdout())
self._stderr_task = asyncio.create_task(self._read_stderr())
async def _read_stdout(self) -> None:
assert self._proc is not None and self._proc.stdout is not None
try:
while True:
raw_line = await self._proc.stdout.readline()
if not raw_line:
break
line = raw_line.decode("utf-8", errors="replace").strip()
if not line:
continue
try:
msg = json.loads(line)
except json.JSONDecodeError:
logger.debug("MCP stdio [%s] non-JSON stdout: %s", self.config.name, line[:200])
continue
if isinstance(msg, dict) and "id" in msg:
fut = self._pending.pop(msg["id"], None)
if fut and not fut.done():
fut.set_result(msg)
except asyncio.CancelledError:
raise
finally:
stderr_hint = "\n".join(self._stderr_tail[-5:]).strip()
err_msg = f"Stdio процесс '{self.config.name}' завершился."
if stderr_hint:
err_msg += f" stderr: {stderr_hint}"
err = MCPProtocolError(err_msg)
for fut in list(self._pending.values()):
if not fut.done():
fut.set_exception(err)
self._pending.clear()
async def _read_stderr(self) -> None:
assert self._proc is not None and self._proc.stderr is not None
try:
while True:
raw_line = await self._proc.stderr.readline()
if not raw_line:
break
line = raw_line.decode("utf-8", errors="replace").rstrip()
if line:
self._stderr_tail.append(line)
if len(self._stderr_tail) > 20:
self._stderr_tail.pop(0)
logger.debug("MCP stdio [%s] stderr: %s", self.config.name, line[:300])
except asyncio.CancelledError:
raise
async def _write_message(self, payload: dict[str, Any]) -> None:
if self._proc is None or self._proc.stdin is None or self._proc.returncode is not None:
raise MCPProtocolError(f"Stdio процесс '{self.config.name}' не запущен.")
encoded = (json.dumps(payload, ensure_ascii=False) + "\n").encode("utf-8")
async with self._write_lock:
self._proc.stdin.write(encoded)
await self._proc.stdin.drain()
async def request(self, method: str, params: Optional[dict[str, Any]] = None) -> dict[str, Any]:
async with self._write_lock:
req_id = self._next_id
self._next_id += 1
payload: dict[str, Any] = {"jsonrpc": "2.0", "id": req_id, "method": method}
if params is not None:
payload["params"] = params
loop = asyncio.get_running_loop()
fut: asyncio.Future[dict[str, Any]] = loop.create_future()
self._pending[req_id] = fut
try:
await self._write_message(payload)
msg = await asyncio.wait_for(fut, timeout=float(self.config.timeout_seconds))
except asyncio.TimeoutError:
self._pending.pop(req_id, None)
raise MCPProtocolError(f"Таймаут ожидания ответа от stdio сервера '{self.config.name}' ({method}).")
except Exception:
self._pending.pop(req_id, None)
raise
if "error" in msg and msg["error"] is not None:
err = msg["error"]
err_msg = err.get("message", str(err)) if isinstance(err, dict) else str(err)
err_code = err.get("code") if isinstance(err, dict) else None
raise MCPProtocolError(f"JSON-RPC error ({method}): {err_msg}", code=err_code)
result = msg.get("result")
return result if isinstance(result, dict) else {"value": result}
async def notify(self, method: str, params: Optional[dict[str, Any]] = None) -> None:
payload: dict[str, Any] = {"jsonrpc": "2.0", "method": method}
if params is not None:
payload["params"] = params
await self._write_message(payload)
async def close(self) -> None:
proc = self._proc
self._proc = None
if proc is not None:
if proc.stdin is not None:
try:
proc.stdin.close()
except Exception:
pass
if proc.returncode is None:
try:
proc.terminate()
await asyncio.wait_for(proc.wait(), timeout=3.0)
except asyncio.TimeoutError:
try:
proc.kill()
await proc.wait()
except Exception:
pass
except Exception:
pass
for task in (self._stdout_task, self._stderr_task):
if task is not None and not task.done():
task.cancel()
try:
await task
except (asyncio.CancelledError, Exception):
pass
self._stdout_task = None
self._stderr_task = None
for fut in list(self._pending.values()):
if not fut.done():
fut.cancel()
self._pending.clear()
class MCPClient:
"""High-level MCP client performing handshake, tool discovery, and tool execution."""
def __init__(self, config: MCPConnectorConfig, auth_manager: MCPAuthManager) -> None:
self.config = config
self.auth_manager = auth_manager
self._transport: Optional[BaseMCPTransport] = None
self.server_info: dict[str, Any] = {}
self.protocol_version: Optional[str] = None
self.capabilities: dict[str, Any] = {}
self.resolved_transport: Optional[str] = None
@property
def is_connected(self) -> bool:
return self._transport is not None
async def _initialize_transport(self, transport: BaseMCPTransport) -> None:
await transport.connect()
init_result = await transport.request(
"initialize",
{
"protocolVersion": MCP_PROTOCOL_VERSION,
"capabilities": {},
"clientInfo": {"name": "homeagent", "version": "1.0.0"},
},
)
protocol_version = str(init_result.get("protocolVersion") or MCP_PROTOCOL_VERSION)
if isinstance(transport, StreamableHTTPTransport):
transport.set_protocol_version(protocol_version)
await transport.notify("notifications/initialized")
self.protocol_version = protocol_version
self.server_info = init_result.get("serverInfo") if isinstance(init_result.get("serverInfo"), dict) else {}
self.capabilities = init_result.get("capabilities") if isinstance(init_result.get("capabilities"), dict) else {}
self.resolved_transport = transport.transport_name
self._transport = transport
async def connect(self) -> None:
"""Connect to the configured MCP server, auto-detecting Streamable HTTP vs SSE when transport='auto'."""
await self.close()
mode = self.config.transport
if mode == "stdio":
transport = StdioTransport(self.config)
try:
await self._initialize_transport(transport)
except Exception:
await transport.close()
raise
return
if mode == "streamable_http":
transport = StreamableHTTPTransport(self.config, self.auth_manager)
try:
await self._initialize_transport(transport)
except Exception:
await transport.close()
raise
return
if mode == "sse":
transport = SSETransport(self.config, self.auth_manager)
try:
await self._initialize_transport(transport)
except Exception:
await transport.close()
raise
return
# Auto mode for remote HTTP URLs
url_lower = (self.config.url or "").lower().rstrip("/")
prefer_sse = url_lower.endswith("/sse")
order = (
[SSETransport(self.config, self.auth_manager), StreamableHTTPTransport(self.config, self.auth_manager)]
if prefer_sse
else [StreamableHTTPTransport(self.config, self.auth_manager), SSETransport(self.config, self.auth_manager)]
)
last_err: Optional[Exception] = None
for idx, transport in enumerate(order):
try:
await self._initialize_transport(transport)
return
except MCPAuthError:
await transport.close()
raise
except Exception as e:
await transport.close()
last_err = e
if idx == 0:
logger.debug(
"MCP '%s' transport '%s' failed (%s), falling back to '%s'",
self.config.name,
transport.transport_name,
e,
order[1].transport_name,
)
assert last_err is not None
raise last_err
async def list_tools(self) -> list[dict[str, Any]]:
"""Discover all tools from the connected MCP server (handling pagination)."""
if self._transport is None:
raise MCPProtocolError(f"Коннектор '{self.config.name}' не подключен.")
tools: list[dict[str, Any]] = []
cursor: Optional[str] = None
seen_cursors: set[str] = set()
while True:
params: dict[str, Any] = {}
if cursor:
params["cursor"] = cursor
result = await self._transport.request("tools/list", params if params else None)
batch = result.get("tools")
if isinstance(batch, list):
tools.extend(item for item in batch if isinstance(item, dict))
next_cursor = result.get("nextCursor")
if isinstance(next_cursor, str) and next_cursor and next_cursor not in seen_cursors:
seen_cursors.add(next_cursor)
cursor = next_cursor
else:
break
return tools
async def call_tool(self, name: str, arguments: Optional[dict[str, Any]] = None) -> str:
"""Invoke a remote MCP tool and format its output as string."""
if self._transport is None:
raise MCPProtocolError(f"Коннектор '{self.config.name}' не подключен.")
result = await self._transport.request(
"tools/call",
{
"name": name,
"arguments": arguments or {},
},
)
return _format_tool_call_result(result)
async def ping(self) -> bool:
if self._transport is None:
return False
try:
await self._transport.request("ping")
return True
except Exception:
return False
async def close(self) -> None:
transport = self._transport
self._transport = None
if transport is not None:
await transport.close()
+559
View File
@@ -0,0 +1,559 @@
"""MCP Connector Manager: config + bot persistence, lifecycle, OAuth flows, and dynamic ToolRegistry integration."""
from __future__ import annotations
import asyncio
import json
import logging
import os
import secrets
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Optional
import yaml
from homeagent.config import Settings, get_settings
from homeagent.mcp.auth import (
MCPAuthError,
MCPAuthManager,
MCPAuthRequiredError,
OAuthTokenStore,
)
from homeagent.mcp.client import MCPClient, MCPProtocolError
from homeagent.mcp.models import (
MCPConnectorConfig,
MCPConnectorState,
MCPToolInfo,
normalize_connector_name,
parse_connectors_payload,
sanitize_mcp_input_schema,
sanitize_tool_name,
)
from homeagent.tools.base import ToolDefinition
from homeagent.tools.registry import ToolRegistry, get_tool_registry
logger = logging.getLogger(__name__)
def _write_json_atomic_private(path: Path, data: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
payload = json.dumps(data, ensure_ascii=False, indent=2)
tmp_path = path.parent / f".{path.name}.{os.getpid()}.{secrets.token_hex(4)}.tmp"
fd = os.open(tmp_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(payload)
os.replace(tmp_path, path)
except Exception:
if tmp_path.exists():
tmp_path.unlink(missing_ok=True)
raise
def _load_structured_file(path: Path) -> Any:
raw = path.read_text(encoding="utf-8").strip()
if not raw:
return {}
if path.suffix.lower() in (".yaml", ".yml"):
return yaml.safe_load(raw)
return json.loads(raw)
class MCPConnectorManager:
"""Manages external MCP connectors loaded from config and Telegram bot interface."""
def __init__(
self,
settings: Optional[Settings] = None,
registry: Optional[ToolRegistry] = None,
) -> None:
self.settings = settings or get_settings()
self.registry = registry or get_tool_registry()
self.storage_path: Path = self.settings.DATA_DIR / "mcp_connectors.json"
self.tokens_path: Path = self.settings.DATA_DIR / "mcp_tokens.json"
self.token_store = OAuthTokenStore(self.tokens_path)
self.auth_manager = MCPAuthManager(
self.token_store,
default_redirect_uri=self.settings.MCP_OAUTH_REDIRECT_URI,
enable_local_callback_server=self.settings.MCP_OAUTH_CALLBACK_ENABLED,
on_auto_pkce_complete=self._on_auto_pkce_complete,
)
self._configs: dict[str, MCPConnectorConfig] = {}
self._bot_configs: dict[str, MCPConnectorConfig] = {}
self._config_file_names: set[str] = set()
self._states: dict[str, MCPConnectorState] = {}
self._clients: dict[str, MCPClient] = {}
self._registered_tools: dict[str, list[str]] = {}
self._connector_locks: dict[str, asyncio.Lock] = {}
self._load_all_configs()
def _get_lock(self, name: str) -> asyncio.Lock:
lock = self._connector_locks.get(name)
if lock is None:
lock = asyncio.Lock()
self._connector_locks[name] = lock
return lock
async def _on_auto_pkce_complete(self, name: str) -> None:
"""Auto-connect connector after local OAuth callback server receives redirect."""
try:
await self.connect(name)
logger.info("Auto-connected MCP connector '%s' after OAuth callback.", name)
except Exception as e:
logger.warning("Failed auto-connecting MCP connector '%s' after OAuth callback: %s", name, e)
def _load_all_configs(self) -> None:
"""Load connectors from config file, inline env JSON, and persistent bot store."""
default_timeout = self.settings.MCP_REQUEST_TIMEOUT_SECONDS
merged: dict[str, MCPConnectorConfig] = {}
self._config_file_names = set()
# 1. Config file (JSON or YAML)
cfg_file = self.settings.MCP_CONFIG_FILE
if cfg_file and cfg_file.exists() and cfg_file.is_file():
try:
raw_data = _load_structured_file(cfg_file)
for conn in parse_connectors_payload(raw_data, source="config", default_timeout=default_timeout):
merged[conn.name] = conn
self._config_file_names.add(conn.name)
logger.info("Loaded %d MCP connector(s) from %s", len(merged), cfg_file)
except Exception as e:
logger.error("Failed loading MCP config file %s: %s", cfg_file, e)
# 2. Inline MCP_CONNECTORS_JSON from .env
inline_json = (self.settings.MCP_CONNECTORS_JSON or "").strip()
if inline_json:
try:
raw_inline = json.loads(inline_json)
for conn in parse_connectors_payload(raw_inline, source="config", default_timeout=default_timeout):
merged[conn.name] = conn
self._config_file_names.add(conn.name)
except Exception as e:
logger.error("Failed parsing MCP_CONNECTORS_JSON: %s", e)
# 3. Persisted bot-managed connectors & overrides from DATA_DIR/mcp_connectors.json
self._bot_configs = {}
if self.storage_path.exists():
try:
raw_store = json.loads(self.storage_path.read_text(encoding="utf-8"))
for conn in parse_connectors_payload(raw_store, source="bot", default_timeout=default_timeout):
self._bot_configs[conn.name] = conn
merged[conn.name] = conn
except Exception as e:
logger.error("Failed loading bot MCP connectors store %s: %s", self.storage_path, e)
self._configs = merged
for name, cfg in self._configs.items():
prev = self._states.get(name)
if prev is None:
self._states[name] = MCPConnectorState(
config=cfg,
status="disabled" if not cfg.enabled else "disconnected",
)
else:
prev.config = cfg
if not cfg.enabled and prev.status != "connected":
prev.status = "disabled"
# Drop states for removed configs
for stale_name in list(self._states.keys()):
if stale_name not in self._configs:
del self._states[stale_name]
def _save_bot_store(self) -> None:
payload = {
"connectors": {
name: cfg.model_dump(mode="json", exclude_none=True)
for name, cfg in self._bot_configs.items()
}
}
_write_json_atomic_private(self.storage_path, payload)
def list_connectors(self) -> list[MCPConnectorState]:
return [self._states[name] for name in sorted(self._states.keys())]
def get_connector(self, name: str) -> Optional[MCPConnectorState]:
try:
norm = normalize_connector_name(name)
except ValueError:
return None
return self._states.get(norm)
def _unregister_connector_tools(self, name: str) -> int:
tool_names = self._registered_tools.pop(name, [])
count = 0
for t_name in tool_names:
if self.registry.unregister(t_name):
count += 1
return count
def _register_connector_tools(
self,
config: MCPConnectorConfig,
raw_tools: list[dict[str, Any]],
) -> list[MCPToolInfo]:
self._unregister_connector_tools(config.name)
include_set = set(config.include_tools) if config.include_tools else None
exclude_set = set(config.exclude_tools) if config.exclude_tools else set()
existing_registry_names = {t.name for t in self.registry.list_tools()}
discovered: list[MCPToolInfo] = []
registered_names: list[str] = []
for item in raw_tools:
remote_name = str(item.get("name") or "").strip()
if not remote_name:
continue
if include_set is not None and remote_name not in include_set:
continue
if remote_name in exclude_set:
continue
raw_desc = str(item.get("description") or remote_name).strip()
full_desc = f"[MCP:{config.name}] {raw_desc}"
input_schema = sanitize_mcp_input_schema(item.get("inputSchema"))
registered_name = sanitize_tool_name(
config.name,
remote_name,
tool_prefix=config.tool_prefix,
existing_names=existing_registry_names,
)
existing_registry_names.add(registered_name)
tool_fn = self._make_tool_executor(config.name, remote_name)
tool_def = ToolDefinition(
name=registered_name,
description=full_desc,
func=tool_fn,
parameters_schema=input_schema,
is_async=True,
)
self.registry.register_definition(tool_def)
registered_names.append(registered_name)
discovered.append(
MCPToolInfo(
remote_name=remote_name,
registered_name=registered_name,
description=raw_desc,
input_schema=input_schema,
)
)
self._registered_tools[config.name] = registered_names
return discovered
def _make_tool_executor(self, connector_name: str, remote_tool_name: str):
async def _execute_mcp_tool(**kwargs: Any) -> str:
client = self._clients.get(connector_name)
if client is None or not client.is_connected:
state = await self.connect(connector_name)
if state.status != "connected":
return f"Error: MCP connector '{connector_name}' is not connected ({state.last_error or state.status})."
client = self._clients.get(connector_name)
if client is None:
return f"Error: MCP connector '{connector_name}' is unavailable."
try:
return await client.call_tool(remote_tool_name, kwargs)
except MCPAuthRequiredError as e:
state = self._states.get(connector_name)
if state:
state.status = "auth_required"
state.last_error = str(e)
return f"Error: MCP connector '{connector_name}' requires re-authentication (/mcp auth {connector_name})."
except MCPProtocolError as e:
# One transparent reconnect retry if transport broke mid-session
logger.warning("MCP tool '%s.%s' failed (%s); attempting reconnect once.", connector_name, remote_tool_name, e)
state = await self.connect(connector_name)
if state.status == "connected" and connector_name in self._clients:
return await self._clients[connector_name].call_tool(remote_tool_name, kwargs)
return f"Error executing MCP tool '{connector_name}.{remote_tool_name}': {e}"
return _execute_mcp_tool
async def connect_all(self) -> dict[str, MCPConnectorState]:
"""Connect all enabled MCP connectors concurrently (never raises on individual failure)."""
if not self.settings.MCP_ENABLED:
logger.info("MCP connectors disabled via MCP_ENABLED=false.")
return {}
enabled_names = [name for name, cfg in self._configs.items() if cfg.enabled]
if not enabled_names:
return {}
logger.info("Connecting %d enabled MCP connector(s): %s", len(enabled_names), enabled_names)
tasks = [self.connect(name) for name in enabled_names]
await asyncio.gather(*tasks, return_exceptions=True)
return dict(self._states)
async def connect(self, name: str) -> MCPConnectorState:
"""Connect (or reconnect) a single MCP connector and register its discovered tools."""
norm = normalize_connector_name(name)
if norm not in self._configs:
raise KeyError(f"MCP коннектор '{norm}' не найден.")
async with self._get_lock(norm):
config = self._configs[norm]
state = self._states[norm]
state.config = config
state.status = "connecting"
state.last_error = None
state.oauth_challenge = None
# Close previous client if any
old_client = self._clients.pop(norm, None)
if old_client is not None:
await old_client.close()
client = MCPClient(config, self.auth_manager)
try:
await client.connect()
raw_tools = await client.list_tools()
tools_info = self._register_connector_tools(config, raw_tools)
self._clients[norm] = client
state.status = "connected"
state.resolved_transport = client.resolved_transport
state.server_info = client.server_info
state.protocol_version = client.protocol_version
state.tools = tools_info
state.last_error = None
state.connected_at = datetime.now(timezone.utc).isoformat()
logger.info(
"Connected MCP connector '%s' via %s (%d tools)",
norm,
client.resolved_transport,
len(tools_info),
)
return state
except MCPAuthRequiredError as e:
await client.close()
self._unregister_connector_tools(norm)
state.status = "auth_required"
state.tools = []
state.last_error = str(e)
state.oauth_challenge = {
"www_authenticate": e.www_authenticate,
"resource_metadata_url": e.resource_metadata_url,
"scope": e.scope,
}
logger.info("MCP connector '%s' requires interactive authentication: %s", norm, e)
return state
except Exception as e:
await client.close()
self._unregister_connector_tools(norm)
state.status = "error"
state.tools = []
state.last_error = str(e)
logger.warning("Failed connecting MCP connector '%s': %s", norm, e)
return state
async def disconnect(self, name: str) -> MCPConnectorState:
"""Disconnect an MCP connector and unregister its tools."""
norm = normalize_connector_name(name)
if norm not in self._configs:
raise KeyError(f"MCP коннектор '{norm}' не найден.")
async with self._get_lock(norm):
client = self._clients.pop(norm, None)
if client is not None:
await client.close()
self._unregister_connector_tools(norm)
state = self._states[norm]
state.tools = []
state.status = "disabled" if not state.config.enabled else "disconnected"
state.last_error = None
return state
async def add_or_update_connector(
self,
config: MCPConnectorConfig,
*,
connect_now: bool = True,
persist: bool = True,
) -> MCPConnectorState:
"""Add or update an MCP connector, optionally persisting to bot storage and connecting immediately."""
if config.transport == "stdio" and config.source == "bot" and not self.settings.MCP_ALLOW_STDIO_FROM_BOT:
raise PermissionError(
"Добавление локальных stdio MCP-серверов из Telegram отключено настройкой MCP_ALLOW_STDIO_FROM_BOT=false."
)
self._configs[config.name] = config
if persist:
self._bot_configs[config.name] = config
self._save_bot_store()
state = self._states.get(config.name)
if state is None:
state = MCPConnectorState(
config=config,
status="disabled" if not config.enabled else "disconnected",
)
self._states[config.name] = state
else:
state.config = config
if connect_now and config.enabled and self.settings.MCP_ENABLED:
return await self.connect(config.name)
if not config.enabled:
await self.disconnect(config.name)
return self._states[config.name]
async def import_from_json(
self,
raw_text: str,
*,
connect_now: bool = True,
) -> list[MCPConnectorState]:
"""Parse a JSON or YAML snippet (`mcpServers` or `connectors`) and add/connect all entries."""
text = raw_text.strip()
# Strip optional markdown code fences
if text.startswith("```"):
lines = text.splitlines()
if lines and lines[0].startswith("```"):
lines = lines[1:]
if lines and lines[-1].strip() == "```":
lines = lines[:-1]
text = "\n".join(lines).strip()
try:
parsed = json.loads(text)
except json.JSONDecodeError:
parsed = yaml.safe_load(text)
configs = parse_connectors_payload(
parsed,
source="bot",
default_timeout=self.settings.MCP_REQUEST_TIMEOUT_SECONDS,
)
if not configs:
raise ValueError("Не найдено ни одного MCP коннектора в переданной конфигурации.")
states: list[MCPConnectorState] = []
for cfg in configs:
state = await self.add_or_update_connector(cfg, connect_now=connect_now, persist=True)
states.append(state)
return states
async def set_enabled(self, name: str, enabled: bool) -> MCPConnectorState:
"""Enable or disable a connector persistently and connect/disconnect accordingly."""
norm = normalize_connector_name(name)
if norm not in self._configs:
raise KeyError(f"MCP коннектор '{norm}' не найден.")
updated = self._configs[norm].model_copy(update={"enabled": enabled, "source": "bot"})
return await self.add_or_update_connector(updated, connect_now=enabled, persist=True)
async def remove_connector(self, name: str) -> bool:
"""Disconnect, unregister tools, clear tokens, and remove a connector."""
norm = normalize_connector_name(name)
if norm not in self._configs:
return False
await self.disconnect(norm)
self.auth_manager.clear_tokens(norm)
self._bot_configs.pop(norm, None)
self._save_bot_store()
# If it was defined in config file, disable it or remove from active runtime?
# Remove from runtime completely (user can /mcp reload to restore file-based entries)
self._configs.pop(norm, None)
self._states.pop(norm, None)
return True
async def start_oauth(self, name: str) -> dict[str, Any]:
"""Start OAuth 2.1 PKCE or OAuth 2.0 Device flow for a connector.
If a remote connector previously returned HTTP 401 with OAuth discovery metadata,
its auth mode is automatically upgraded to `oauth2_pkce` so `/mcp auth <name>` works seamlessly!
"""
norm = normalize_connector_name(name)
if norm not in self._configs:
raise KeyError(f"MCP коннектор '{norm}' не найден.")
config = self._configs[norm]
state = self._states[norm]
if config.auth.type == "oauth2_device":
pending = await self.auth_manager.start_device_flow(config)
return {
"flow": "device",
"connector": norm,
"user_code": pending.user_code,
"verification_uri": pending.verification_uri,
"verification_uri_complete": pending.verification_uri_complete,
"interval": pending.interval,
}
# Auto-upgrade to oauth2_pkce if server requested OAuth via 401 or user invoked /mcp auth
if config.auth.type != "oauth2_pkce":
if config.transport == "stdio":
raise MCPAuthError(f"Коннектор '{norm}' использует локальный stdio и не поддерживает OAuth.")
challenge_scope = (state.oauth_challenge or {}).get("scope")
updated_auth = config.auth.model_copy(
update={
"type": "oauth2_pkce",
"scope": config.auth.scope or challenge_scope,
}
)
config = config.model_copy(update={"auth": updated_auth, "source": "bot"})
self._configs[norm] = config
self._bot_configs[norm] = config
state.config = config
self._save_bot_store()
resource_meta_url = (state.oauth_challenge or {}).get("resource_metadata_url")
authorize_url, pending = await self.auth_manager.start_pkce_flow(
config,
resource_metadata_url=resource_meta_url,
)
return {
"flow": "pkce",
"connector": norm,
"authorize_url": authorize_url,
"redirect_uri": pending.redirect_uri,
"local_callback_enabled": self.settings.MCP_OAUTH_CALLBACK_ENABLED,
}
async def complete_oauth_code(self, name: str, code_or_url: str) -> MCPConnectorState:
"""Complete OAuth 2.1 PKCE with authorization code or callback URL and connect immediately."""
norm = normalize_connector_name(name)
if norm not in self._configs:
raise KeyError(f"MCP коннектор '{norm}' не найден.")
await self.auth_manager.complete_pkce_flow(norm, code_or_url)
return await self.connect(norm)
async def wait_for_device_oauth(self, name: str, *, timeout_seconds: int = 300) -> MCPConnectorState:
"""Poll pending OAuth 2.0 Device Flow until authorized, then connect immediately."""
norm = normalize_connector_name(name)
if norm not in self._configs:
raise KeyError(f"MCP коннектор '{norm}' не найден.")
await self.auth_manager.poll_device_flow(norm, timeout_seconds=timeout_seconds)
return await self.connect(norm)
async def reload(self) -> dict[str, MCPConnectorState]:
"""Disconnect all active connectors, reload configs from disk, and reconnect enabled ones."""
for name in list(self._clients.keys()):
await self.disconnect(name)
self._load_all_configs()
return await self.connect_all()
async def close(self) -> None:
"""Cleanly shut down all active MCP clients and optional OAuth callback server."""
for name in list(self._clients.keys()):
try:
await self.disconnect(name)
except Exception as e:
logger.debug("Error disconnecting MCP '%s' on close: %s", name, e)
await self.auth_manager.close()
+575
View File
@@ -0,0 +1,575 @@
"""Data models, config parsing, secret masking, and schema sanitization for MCP connectors."""
from __future__ import annotations
import copy
import hashlib
import os
import re
from typing import Any, Literal, Optional
from urllib.parse import urlparse
from pydantic import BaseModel, Field, field_validator, model_validator
TransportType = Literal["auto", "streamable_http", "sse", "stdio"]
AuthType = Literal[
"none",
"bearer",
"api_key",
"basic",
"headers",
"oauth2_client_credentials",
"oauth2_pkce",
"oauth2_device",
"oauth2_refresh_token",
]
ConnectorStatus = Literal[
"disconnected",
"connecting",
"connected",
"auth_required",
"disabled",
"error",
]
_ENV_VAR_RE = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-(.*?))?\}")
_SLUG_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$")
_SAFE_IDENT_RE = re.compile(r"[^a-zA-Z0-9_-]+")
# JSON Schema keywords not supported by google-genai FunctionDeclaration `parameters`
_UNSUPPORTED_SCHEMA_KEYS = frozenset(
{
"$schema",
"$id",
"$defs",
"$ref",
"$comment",
"definitions",
"additionalProperties",
"patternProperties",
"propertyNames",
"examples",
"default",
"title",
"exclusiveMinimum",
"exclusiveMaximum",
"readOnly",
"writeOnly",
"deprecated",
"contentEncoding",
"contentMediaType",
"minContains",
"maxContains",
"dependentRequired",
"dependentSchemas",
"if",
"then",
"else",
"not",
"allOf",
"oneOf",
}
)
def expand_env_vars(value: Any) -> Any:
"""Recursively expand `${VAR}` and `${VAR:-default}` using current environment variables."""
if isinstance(value, str):
def _replace(match: re.Match[str]) -> str:
var_name = match.group(1)
default_val = match.group(2)
env_val = os.environ.get(var_name)
if env_val is not None:
return env_val
if default_val is not None:
return default_val
return match.group(0)
return _ENV_VAR_RE.sub(_replace, value)
if isinstance(value, dict):
return {k: expand_env_vars(v) for k, v in value.items()}
if isinstance(value, list):
return [expand_env_vars(item) for item in value]
return value
def is_loopback_url(url: Optional[str]) -> bool:
"""Return True if URL targets localhost/loopback (so HTTP_PROXY should be bypassed)."""
if not url:
return False
host = (urlparse(url).hostname or "").lower()
return host in ("localhost", "127.0.0.1", "::1") or host.endswith(".localhost")
def mask_secret(value: Optional[str]) -> str:
"""Mask a secret value for safe display in Telegram UI and logs."""
if not value:
return "не задан"
s = value.strip()
if s.startswith("${") and s.endswith("}"):
return f"`{s}` (env)"
if len(s) <= 8:
return "••••••••"
return f"{s[:4]}••••{s[-4:]}"
def normalize_connector_name(name: str) -> str:
"""Normalize and validate an MCP connector slug."""
cleaned = name.strip().lower().replace(" ", "_")
cleaned = _SAFE_IDENT_RE.sub("_", cleaned).strip("_-")
if not cleaned:
raise ValueError("Имя коннектора не может быть пустым.")
if len(cleaned) > 48:
cleaned = cleaned[:48].rstrip("_-")
if not _SLUG_RE.match(cleaned):
raise ValueError(
f"Некорректное имя коннектора '{name}'. Используйте латинские буквы, цифры, '-' или '_'."
)
return cleaned
def sanitize_tool_name(
connector_name: str,
remote_name: str,
*,
tool_prefix: Optional[str] = None,
existing_names: Optional[set[str]] = None,
) -> str:
"""Build a valid LLM function name (<= 64 chars, `[a-zA-Z0-9_-]`) for an MCP tool."""
prefix = (tool_prefix or f"mcp_{connector_name}").strip()
prefix = _SAFE_IDENT_RE.sub("_", prefix).strip("_")
if not prefix or not prefix[0].isalpha():
prefix = f"mcp_{prefix}" if prefix else "mcp"
clean_remote = _SAFE_IDENT_RE.sub("_", remote_name.strip()).strip("_") or "tool"
candidate = f"{prefix}_{clean_remote}"
if len(candidate) > 64:
digest = hashlib.sha256(f"{connector_name}:{remote_name}".encode("utf-8")).hexdigest()[:6]
max_base = 64 - 1 - len(digest)
candidate = f"{candidate[:max_base].rstrip('_')}_{digest}"
if existing_names is not None and candidate in existing_names:
idx = 2
while True:
suffix = f"_{idx}"
base = candidate[: 64 - len(suffix)].rstrip("_")
alt = f"{base}{suffix}"
if alt not in existing_names:
candidate = alt
break
idx += 1
return candidate
def _resolve_ref(ref: str, root: dict[str, Any]) -> Optional[dict[str, Any]]:
"""Resolve a local JSON pointer `$ref` such as `#/$defs/Filter`."""
if not ref.startswith("#/"):
return None
parts = ref[2:].split("/")
current: Any = root
for part in parts:
part = part.replace("~1", "/").replace("~0", "~")
if isinstance(current, dict) and part in current:
current = current[part]
else:
return None
return copy.deepcopy(current) if isinstance(current, dict) else None
def _sanitize_schema_node(
node: Any,
root: dict[str, Any],
seen_refs: frozenset[str] = frozenset(),
) -> dict[str, Any]:
if not isinstance(node, dict):
return {"type": "string"}
# Resolve $ref if present
ref = node.get("$ref")
if isinstance(ref, str) and ref not in seen_refs:
resolved = _resolve_ref(ref, root)
if resolved is not None:
merged = {**resolved, **{k: v for k, v in node.items() if k != "$ref"}}
return _sanitize_schema_node(merged, root, seen_refs | {ref})
# Simplify anyOf / oneOf with null into nullable type
for union_key in ("anyOf", "oneOf"):
variants = node.get(union_key)
if isinstance(variants, list) and variants:
non_null = [v for v in variants if not (isinstance(v, dict) and v.get("type") == "null")]
has_null = len(non_null) < len(variants)
if len(non_null) == 1 and isinstance(non_null[0], dict):
merged = dict(non_null[0])
if "description" in node and "description" not in merged:
merged["description"] = node["description"]
sanitized = _sanitize_schema_node(merged, root, seen_refs)
if has_null:
sanitized["nullable"] = True
return sanitized
if non_null and isinstance(non_null[0], dict):
# Keep Gemini-compatible anyOf if simple, or collapse to first non-null type
merged = dict(non_null[0])
if "description" in node and "description" not in merged:
merged["description"] = node["description"]
sanitized = _sanitize_schema_node(merged, root, seen_refs)
if has_null:
sanitized["nullable"] = True
return sanitized
cleaned: dict[str, Any] = {}
# Handle type arrays such as ["string", "null"]
raw_type = node.get("type")
if isinstance(raw_type, list):
non_null_types = [t for t in raw_type if isinstance(t, str) and t != "null"]
has_null = "null" in raw_type
cleaned["type"] = non_null_types[0] if non_null_types else "string"
if has_null:
cleaned["nullable"] = True
elif isinstance(raw_type, str) and raw_type != "null":
cleaned["type"] = raw_type
# Convert const -> enum
if "const" in node and "enum" not in node:
const_val = node["const"]
if isinstance(const_val, (str, int, float, bool)):
cleaned["enum"] = [str(const_val)] if cleaned.get("type") == "string" else [const_val]
cleaned.setdefault("type", "string")
for key, value in node.items():
if key in _UNSUPPORTED_SCHEMA_KEYS or key in ("type", "const", "anyOf"):
continue
if key == "properties" and isinstance(value, dict):
cleaned["properties"] = {
str(prop_name): _sanitize_schema_node(prop_schema, root, seen_refs)
for prop_name, prop_schema in value.items()
}
elif key == "items":
if isinstance(value, dict):
cleaned["items"] = _sanitize_schema_node(value, root, seen_refs)
elif isinstance(value, list) and value:
cleaned["items"] = _sanitize_schema_node(value[0], root, seen_refs)
else:
cleaned["items"] = {"type": "string"}
elif key == "required" and isinstance(value, list):
cleaned["required"] = [str(item) for item in value if isinstance(item, str)]
elif key == "enum" and isinstance(value, list):
cleaned["enum"] = value
elif key in ("description", "format", "nullable", "minimum", "maximum", "minItems", "maxItems", "minLength", "maxLength", "pattern"):
cleaned[key] = value
if "type" not in cleaned:
if "properties" in cleaned:
cleaned["type"] = "object"
elif "items" in cleaned:
cleaned["type"] = "array"
else:
cleaned["type"] = "string"
if cleaned["type"] == "object":
cleaned.setdefault("properties", {})
if "required" in cleaned:
props = cleaned["properties"]
valid_req = [r for r in cleaned["required"] if r in props]
if valid_req:
cleaned["required"] = valid_req
else:
del cleaned["required"]
elif cleaned["type"] == "array":
cleaned.setdefault("items", {"type": "string"})
return cleaned
def sanitize_mcp_input_schema(schema: Any) -> dict[str, Any]:
"""Convert an arbitrary MCP JSON Schema into a clean schema compatible with Gemini, OpenAI, and MCPToolBridge."""
if not isinstance(schema, dict):
return {"type": "object", "properties": {}}
sanitized = _sanitize_schema_node(schema, schema)
if sanitized.get("type") != "object":
return {"type": "object", "properties": {}}
sanitized.setdefault("properties", {})
return sanitized
class MCPAuthConfig(BaseModel):
"""Authentication configuration supporting static, custom header, and OAuth 2.x MCP flows."""
type: AuthType = "none"
# Bearer token
token: Optional[str] = None
token_prefix: str = "Bearer"
# API Key (header or query)
api_key: Optional[str] = None
api_key_in: Literal["header", "query"] = "header"
header_name: str = "X-API-Key"
query_param: str = "api_key"
api_key_prefix: str = ""
# HTTP Basic
username: Optional[str] = None
password: Optional[str] = None
# Custom static headers
headers: dict[str, str] = Field(default_factory=dict)
# OAuth 2.0 / 2.1 fields
client_id: Optional[str] = None
client_secret: Optional[str] = None
authorization_url: Optional[str] = None
token_url: Optional[str] = None
device_authorization_url: Optional[str] = None
registration_url: Optional[str] = None
redirect_uri: Optional[str] = None
scope: Optional[str] = None
audience: Optional[str] = None
resource: Optional[str] = None
refresh_token: Optional[str] = None
client_auth_method: Literal["post", "basic"] = "post"
extra_token_params: dict[str, str] = Field(default_factory=dict)
def resolved(self) -> MCPAuthConfig:
"""Return a copy with `${ENV_VAR}` placeholders expanded from os.environ."""
expanded = expand_env_vars(self.model_dump())
return MCPAuthConfig.model_validate(expanded)
def summary(self) -> str:
"""Human-readable summary with all secrets masked."""
if self.type == "none":
return "none (без авторизации)"
if self.type == "bearer":
return f"bearer ({self.token_prefix} {mask_secret(self.token)})"
if self.type == "api_key":
loc = f"header `{self.header_name}`" if self.api_key_in == "header" else f"query `{self.query_param}`"
return f"api_key ({loc}: {mask_secret(self.api_key)})"
if self.type == "basic":
return f"basic (user: `{self.username or '?'}`, pass: {mask_secret(self.password)})"
if self.type == "headers":
keys = ", ".join(f"`{k}`" for k in self.headers.keys()) or "нет"
return f"headers ({keys})"
if self.type == "oauth2_client_credentials":
return f"oauth2_client_credentials (client_id: `{self.client_id or '?'}`)"
if self.type == "oauth2_pkce":
cid = self.client_id or "auto/DCR"
return f"oauth2_pkce (client_id: `{cid}`)"
if self.type == "oauth2_device":
return f"oauth2_device (client_id: `{self.client_id or '?'}`)"
if self.type == "oauth2_refresh_token":
return f"oauth2_refresh_token (token: {mask_secret(self.refresh_token)})"
return str(self.type)
class MCPConnectorConfig(BaseModel):
"""Configuration for a single external MCP connector."""
name: str
transport: TransportType = "auto"
enabled: bool = True
# Remote transports (streamable_http / sse / auto)
url: Optional[str] = None
headers: dict[str, str] = Field(default_factory=dict)
# Local stdio transport
command: Optional[str] = None
args: list[str] = Field(default_factory=list)
env: dict[str, str] = Field(default_factory=dict)
cwd: Optional[str] = None
# Authentication
auth: MCPAuthConfig = Field(default_factory=MCPAuthConfig)
# Tool exposure controls
tool_prefix: Optional[str] = None
include_tools: list[str] = Field(default_factory=list)
exclude_tools: list[str] = Field(default_factory=list)
# Connection options
timeout_seconds: int = Field(default=60, ge=5, le=600)
verify_ssl: bool = True
source: Literal["config", "bot"] = "config"
@field_validator("name", mode="before")
@classmethod
def _validate_name(cls, v: Any) -> str:
return normalize_connector_name(str(v))
@model_validator(mode="after")
def _validate_transport_fields(self) -> MCPConnectorConfig:
if self.transport == "auto":
if self.command and not self.url:
self.transport = "stdio"
if self.transport == "stdio":
if not self.command:
raise ValueError(f"Коннектор '{self.name}' с транспортом 'stdio' требует поле 'command'.")
else:
if not self.url:
raise ValueError(
f"Коннектор '{self.name}' с транспортом '{self.transport}' требует поле 'url'."
)
return self
def resolved(self) -> MCPConnectorConfig:
"""Return a copy with `${ENV_VAR}` placeholders expanded from os.environ."""
expanded = expand_env_vars(self.model_dump())
return MCPConnectorConfig.model_validate(expanded)
class MCPToolInfo(BaseModel):
"""Metadata about a tool discovered from an MCP server."""
remote_name: str
registered_name: str
description: str = ""
input_schema: dict[str, Any] = Field(default_factory=lambda: {"type": "object", "properties": {}})
class MCPConnectorState(BaseModel):
"""Runtime status and discovered tools for an MCP connector."""
config: MCPConnectorConfig
status: ConnectorStatus = "disconnected"
resolved_transport: Optional[str] = None
server_info: dict[str, Any] = Field(default_factory=dict)
protocol_version: Optional[str] = None
tools: list[MCPToolInfo] = Field(default_factory=list)
last_error: Optional[str] = None
connected_at: Optional[str] = None
oauth_challenge: Optional[dict[str, Any]] = None
def _normalize_single_connector_entry(
name: str,
raw: dict[str, Any],
*,
source: Literal["config", "bot"],
default_timeout: int = 60,
) -> MCPConnectorConfig:
"""Normalize a single entry from `mcpServers` or `connectors` format into `MCPConnectorConfig`."""
data = dict(raw)
# Support aliases from Claude Desktop / Cursor / Antigravity configs
if "serverUrl" in data and "url" not in data:
data["url"] = data.pop("serverUrl")
if "server_url" in data and "url" not in data:
data["url"] = data.pop("server_url")
if "disabled" in data and "enabled" not in data:
data["enabled"] = not bool(data.pop("disabled"))
if "timeoutSeconds" in data and "timeout_seconds" not in data:
data["timeout_seconds"] = int(data.pop("timeoutSeconds"))
if "timeout" in data and "timeout_seconds" not in data:
data["timeout_seconds"] = int(data.pop("timeout"))
if "type" in data and "transport" not in data:
raw_t = str(data.pop("type")).strip().lower()
mapping = {
"http": "streamable_http",
"streamable-http": "streamable_http",
"streamable_http": "streamable_http",
"streamablehttp": "streamable_http",
"sse": "sse",
"stdio": "stdio",
"auto": "auto",
}
if raw_t in mapping:
data["transport"] = mapping[raw_t]
if "transport" in data and isinstance(data["transport"], str):
t_val = data["transport"].strip().lower().replace("-", "_")
if t_val == "http":
t_val = "streamable_http"
data["transport"] = t_val
if "transport" not in data:
data["transport"] = "stdio" if data.get("command") and not data.get("url") else "auto"
# Normalize auth shorthand if provided as string or dict
raw_auth = data.get("auth")
if isinstance(raw_auth, str):
data["auth"] = {"type": raw_auth}
elif isinstance(raw_auth, dict):
auth_dict = dict(raw_auth)
if "type" in auth_dict and isinstance(auth_dict["type"], str):
a_type = auth_dict["type"].strip().lower().replace("-", "_")
aliases = {
"oauth": "oauth2_pkce",
"oauth2": "oauth2_pkce",
"pkce": "oauth2_pkce",
"client_credentials": "oauth2_client_credentials",
"device": "oauth2_device",
"device_code": "oauth2_device",
"refresh_token": "oauth2_refresh_token",
"apikey": "api_key",
"api-key": "api_key",
"custom_headers": "headers",
"header": "headers",
}
auth_dict["type"] = aliases.get(a_type, a_type)
data["auth"] = auth_dict
data["name"] = name
data.setdefault("timeout_seconds", default_timeout)
data["source"] = source
return MCPConnectorConfig.model_validate(data)
def parse_connectors_payload(
payload: Any,
*,
source: Literal["config", "bot"] = "config",
default_timeout: int = 60,
) -> list[MCPConnectorConfig]:
"""Parse MCP connectors from standard `mcpServers`, HomeAgent `connectors`, list, or bare dict."""
if not payload:
return []
items: list[tuple[str, dict[str, Any]]] = []
if isinstance(payload, dict):
if "mcpServers" in payload and isinstance(payload["mcpServers"], dict):
for name, entry in payload["mcpServers"].items():
if isinstance(entry, dict):
items.append((str(name), entry))
if "connectors" in payload:
conns = payload["connectors"]
if isinstance(conns, dict):
for name, entry in conns.items():
if isinstance(entry, dict):
items.append((str(name), entry))
elif isinstance(conns, list):
for entry in conns:
if isinstance(entry, dict) and entry.get("name"):
items.append((str(entry["name"]), entry))
if "mcpServers" not in payload and "connectors" not in payload:
# Either a single connector dict with "name", or a mapping {name: {...}}
if "name" in payload and (
"url" in payload or "serverUrl" in payload or "command" in payload
):
items.append((str(payload["name"]), payload))
else:
for name, entry in payload.items():
if isinstance(entry, dict):
items.append((str(name), entry))
elif isinstance(payload, list):
for entry in payload:
if isinstance(entry, dict) and entry.get("name"):
items.append((str(entry["name"]), entry))
else:
raise ValueError("Некорректный формат конфигурации MCP коннекторов (ожидался JSON/YAML объект или список).")
result: list[MCPConnectorConfig] = []
for name, entry in items:
result.append(
_normalize_single_connector_entry(
name,
entry,
source=source,
default_timeout=default_timeout,
)
)
return result