add mcp servers
This commit is contained in:
30 files changed
+8070
-21
No files matched your search
@@ -1,6 +1,7 @@
|
||||
"""Agent package for HomeAgent."""
|
||||
|
||||
from homeagent.agent.antigravity import AntigravityAgent
|
||||
from homeagent.agent.conversation import ConversationManager
|
||||
from homeagent.agent.gemini import GeminiAgent
|
||||
|
||||
__all__ = ["GeminiAgent", "ConversationManager"]
|
||||
__all__ = ["AntigravityAgent", "GeminiAgent", "ConversationManager"]
|
||||
@@ -0,0 +1,672 @@
|
||||
"""Antigravity CLI (`agy`) Agent using Antigravity models and subscription quotas."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import shutil
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Awaitable, Callable, Optional
|
||||
|
||||
from homeagent.agent.base import BaseAgent
|
||||
from homeagent.agent.conversation import ConversationManager
|
||||
from homeagent.agent.mcp_bridge import MCPToolBridge
|
||||
from homeagent.config import Settings, get_settings
|
||||
from homeagent.memory.global_memory import get_global_memory
|
||||
from homeagent.tools.registry import ToolRegistry, get_tool_registry
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]")
|
||||
_MCP_TOOL_PREFIX = f"mcp_{MCPToolBridge.SERVER_NAME}_"
|
||||
_STREAM_READER_LIMIT = 16 * 1024 * 1024 # 16 MiB per NDJSON event line
|
||||
|
||||
|
||||
def _resolve_cli_binary(cli_path: str) -> Optional[str]:
|
||||
"""Return resolved executable path for Antigravity CLI, or None if missing."""
|
||||
candidate = (cli_path or "agy").strip()
|
||||
if not candidate:
|
||||
return None
|
||||
if os.path.sep in candidate:
|
||||
p = Path(candidate).expanduser()
|
||||
if p.is_file() and os.access(p, os.X_OK):
|
||||
return str(p)
|
||||
return None
|
||||
return shutil.which(candidate)
|
||||
|
||||
|
||||
def _build_subprocess_env() -> dict[str, str]:
|
||||
"""Ensure localhost MCP bridge traffic bypasses any host HTTP_PROXY."""
|
||||
env = dict(os.environ)
|
||||
for key in ("NO_PROXY", "no_proxy"):
|
||||
existing = [item.strip() for item in env.get(key, "").split(",") if item.strip()]
|
||||
for host in ("127.0.0.1", "localhost"):
|
||||
if host not in existing:
|
||||
existing.append(host)
|
||||
env[key] = ",".join(existing)
|
||||
return env
|
||||
|
||||
|
||||
def _build_locked_settings_json() -> str:
|
||||
"""Restrict Antigravity CLI to HomeAgent MCP tools, denying host file/shell/web tools."""
|
||||
return json.dumps(
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [f"mcp({MCPToolBridge.SERVER_NAME}/*)"],
|
||||
"deny": [
|
||||
"command(*)",
|
||||
"write_file(*)",
|
||||
"read_file(*)",
|
||||
"read_url(*)",
|
||||
"execute_url(*)",
|
||||
"download_url(*)",
|
||||
],
|
||||
}
|
||||
},
|
||||
separators=(",", ":"),
|
||||
)
|
||||
|
||||
|
||||
def _strip_mcp_tool_prefix(tool_name: str) -> str:
|
||||
if tool_name.startswith(_MCP_TOOL_PREFIX):
|
||||
return tool_name[len(_MCP_TOOL_PREFIX) :]
|
||||
return tool_name
|
||||
|
||||
|
||||
def _write_text_atomic(path: Path, content: str) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp_path = path.parent / f".{path.name}.{os.getpid()}.{secrets.token_hex(4)}.tmp"
|
||||
try:
|
||||
tmp_path.write_text(content, encoding="utf-8")
|
||||
os.replace(tmp_path, path)
|
||||
except Exception:
|
||||
if tmp_path.exists():
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
|
||||
def _parse_models_output(raw_output: str) -> list[tuple[str, str]]:
|
||||
"""Parse `agy models` stdout into `(slug, display_name)` pairs."""
|
||||
cleaned = _ANSI_RE.sub("", raw_output)
|
||||
models: list[tuple[str, str]] = []
|
||||
for raw_line in cleaned.splitlines():
|
||||
# Strip spinner frames separated by carriage returns
|
||||
line = raw_line.split("\r")[-1].strip()
|
||||
if not line:
|
||||
continue
|
||||
if "fetching available models" in line.lower():
|
||||
continue
|
||||
parts = re.split(r"\t+|\s{2,}", line, maxsplit=1)
|
||||
if len(parts) == 2 and re.match(r"^[a-z0-9][a-z0-9._-]*$", parts[0]):
|
||||
models.append((parts[0], parts[1].strip()))
|
||||
return models
|
||||
|
||||
|
||||
def _format_cli_error(error_text: str, model: str) -> str:
|
||||
"""Format an Antigravity CLI error into an actionable Russian message for Telegram."""
|
||||
err = (error_text or "").strip()
|
||||
lower = err.lower()
|
||||
|
||||
if any(k in lower for k in ("authentication required", "not authenticated", "not logged in", "login required")):
|
||||
return (
|
||||
"⚠️ **Antigravity CLI не авторизован.**\n\n"
|
||||
"Выполните вход в интерактивной сессии на сервере:\n"
|
||||
"```bash\n"
|
||||
"agy\n"
|
||||
"```\n"
|
||||
"После авторизации бот сможет использовать ваши модели и лимиты Antigravity."
|
||||
)
|
||||
|
||||
if any(k in lower for k in ("quota", "rate limit", "resource_exhausted", "limit exceeded", "429")):
|
||||
return (
|
||||
f"⚠️ **Исчерпан лимит Antigravity для модели `{model}`.**\n\n"
|
||||
f"Детали: {err}\n\n"
|
||||
"💡 Вы можете переключить модель командой `/model <slug>` (список: `/model`) "
|
||||
"или изменить `ANTIGRAVITY_MODEL` в `.env`."
|
||||
)
|
||||
|
||||
if "invalid model selection" in lower or "not recognized as a known model" in lower:
|
||||
return (
|
||||
f"⚠️ **Модель Antigravity `{model}` недоступна.**\n\n"
|
||||
f"Детали: {err}\n\n"
|
||||
"💡 Посмотрите доступные модели командой `/model` или `agy models`."
|
||||
)
|
||||
|
||||
return f"⚠️ Ошибка Antigravity CLI (`{model}`): {err or 'неизвестная ошибка'}"
|
||||
|
||||
|
||||
def _is_stale_conversation_error(error_text: str) -> bool:
|
||||
lower = (error_text or "").lower()
|
||||
if "conversation" not in lower:
|
||||
return False
|
||||
return any(
|
||||
hint in lower
|
||||
for hint in ("not found", "does not exist", "invalid", "expired", "failed to resume", "unknown")
|
||||
)
|
||||
|
||||
|
||||
async def list_antigravity_models(cli_path: str = "agy", timeout: float = 20.0) -> list[tuple[str, str]]:
|
||||
"""Query `agy models` and return a list of `(slug, display_name)` tuples."""
|
||||
binary = _resolve_cli_binary(cli_path)
|
||||
if not binary:
|
||||
return []
|
||||
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
binary,
|
||||
"models",
|
||||
stdin=asyncio.subprocess.DEVNULL,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
try:
|
||||
stdout_bytes, _ = await asyncio.wait_for(proc.communicate(), timeout=timeout)
|
||||
except asyncio.TimeoutError:
|
||||
proc.kill()
|
||||
await proc.wait()
|
||||
return []
|
||||
|
||||
if proc.returncode != 0:
|
||||
return []
|
||||
return _parse_models_output(stdout_bytes.decode("utf-8", errors="replace"))
|
||||
|
||||
|
||||
class AntigravityAgent(BaseAgent):
|
||||
"""Agent orchestrator backed by Antigravity CLI (`agy`) and an in-process MCP tool bridge."""
|
||||
|
||||
AGENT_NAME = "homeagent"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
settings: Optional[Settings] = None,
|
||||
registry: Optional[ToolRegistry] = None,
|
||||
conversation_manager: Optional[ConversationManager] = None,
|
||||
mcp_bridge: Optional[MCPToolBridge] = None,
|
||||
) -> None:
|
||||
self.settings = settings or get_settings()
|
||||
self.registry = registry or get_tool_registry()
|
||||
self.conversation_manager = conversation_manager or ConversationManager(self.settings.DATA_DIR)
|
||||
self.provider = "antigravity"
|
||||
self.cli_path = self.settings.ANTIGRAVITY_CLI_PATH
|
||||
self.model = self.settings.ANTIGRAVITY_MODEL or "gemini-4-neon-high"
|
||||
self.subagent_model = self.settings.ANTIGRAVITY_SUBAGENT_MODEL or "gemini-3.8-flash-medium"
|
||||
self.effort = (self.settings.ANTIGRAVITY_EFFORT or "").strip() or None
|
||||
self.timeout_seconds = max(0, int(self.settings.ANTIGRAVITY_TIMEOUT_SECONDS))
|
||||
|
||||
self._bridge = mcp_bridge or MCPToolBridge(self.registry)
|
||||
self._owns_bridge = mcp_bridge is None
|
||||
self._workspace_dir = self.settings.DATA_DIR / "antigravity_workspace"
|
||||
self._conv_map_path = self.settings.DATA_DIR / "sessions" / "antigravity_conversations.json"
|
||||
self._conversation_ids: dict[str, str] = self._load_conversation_map()
|
||||
self._topic_locks: dict[tuple[int, Optional[int]], asyncio.Lock] = {}
|
||||
|
||||
if not _resolve_cli_binary(self.cli_path):
|
||||
logger.warning(
|
||||
"Antigravity CLI '%s' not found in PATH. Agent will return configuration instructions.",
|
||||
self.cli_path,
|
||||
)
|
||||
|
||||
def set_model(self, model_slug: str) -> None:
|
||||
"""Switch active Antigravity model slug at runtime."""
|
||||
slug = model_slug.strip()
|
||||
if not slug:
|
||||
raise ValueError("Model slug must not be empty.")
|
||||
self.model = slug
|
||||
self.settings.ANTIGRAVITY_MODEL = slug
|
||||
|
||||
async def list_available_models(self) -> list[tuple[str, str]]:
|
||||
"""List models currently exposed by `agy models`."""
|
||||
return await list_antigravity_models(self.cli_path)
|
||||
|
||||
def _topic_key(self, chat_id: int, thread_id: Optional[int]) -> str:
|
||||
suffix = f"thread_{thread_id}" if thread_id is not None else "main"
|
||||
return f"{chat_id}:{suffix}"
|
||||
|
||||
def _get_topic_lock(self, chat_id: int, thread_id: Optional[int]) -> asyncio.Lock:
|
||||
key = (chat_id, thread_id)
|
||||
lock = self._topic_locks.get(key)
|
||||
if lock is None:
|
||||
lock = asyncio.Lock()
|
||||
self._topic_locks[key] = lock
|
||||
return lock
|
||||
|
||||
def _load_conversation_map(self) -> dict[str, str]:
|
||||
if not self._conv_map_path.exists():
|
||||
return {}
|
||||
try:
|
||||
data = json.loads(self._conv_map_path.read_text(encoding="utf-8"))
|
||||
if isinstance(data, dict):
|
||||
return {str(k): str(v) for k, v in data.items() if k and v}
|
||||
except Exception as e:
|
||||
logger.warning("Failed to load Antigravity conversation map: %s", e)
|
||||
return {}
|
||||
|
||||
def _save_conversation_map(self) -> None:
|
||||
try:
|
||||
payload = json.dumps(self._conversation_ids, ensure_ascii=False, indent=2)
|
||||
_write_text_atomic(self._conv_map_path, payload)
|
||||
except Exception as e:
|
||||
logger.error("Failed to save Antigravity conversation map: %s", e)
|
||||
|
||||
def _clear_conversation_id(self, chat_id: int, thread_id: Optional[int]) -> None:
|
||||
key = self._topic_key(chat_id, thread_id)
|
||||
if key in self._conversation_ids:
|
||||
del self._conversation_ids[key]
|
||||
self._save_conversation_map()
|
||||
|
||||
def _prepare_workspace(self) -> None:
|
||||
"""Write custom HomeAgent persona and MCP config into the isolated workspace."""
|
||||
self._bridge.write_mcp_config(
|
||||
self._workspace_dir,
|
||||
subagent=False,
|
||||
timeout_seconds=max(60, self.timeout_seconds or 180),
|
||||
)
|
||||
|
||||
agent_md = (
|
||||
"---\n"
|
||||
f"name: {self.AGENT_NAME}\n"
|
||||
"description: HomeAgent personal AI assistant integrated with Telegram.\n"
|
||||
"---\n\n"
|
||||
f"{self.settings.SYSTEM_INSTRUCTION}\n\n"
|
||||
"Важные правила среды выполнения:\n"
|
||||
"- Ты работаешь как персональный Telegram-ассистент HomeAgent, а не как IDE для редактирования локального кода.\n"
|
||||
"- Используй ТОЛЬКО инструменты HomeAgent (префикс `mcp_homeagent_*`), подключенные через MCP "
|
||||
"(календарь, Jira, Todoist, Gitea, память, заметки, веб-поиск, песочница, подагенты и подключённые внешние MCP-коннекторы).\n"
|
||||
"- Не пытайся запускать локальные команды или читать/редактировать файлы хоста напрямую — "
|
||||
"для вычислений и кода используй инструменты песочницы HomeAgent (`code_execute`, `sandbox_*`).\n"
|
||||
"- Отвечай пользователю напрямую на его языке (обычно русском), красиво форматируя ответ в Markdown.\n"
|
||||
)
|
||||
agent_file = self._workspace_dir / ".agents" / "agents" / self.AGENT_NAME / "agent.md"
|
||||
_write_text_atomic(agent_file, agent_md)
|
||||
|
||||
def _format_prior_history_context(self, history: list[dict[str, Any]], max_messages: int = 12) -> str:
|
||||
"""Format recent messages from ConversationManager when transitioning from another provider."""
|
||||
lines: list[str] = []
|
||||
for msg in history[-max_messages:]:
|
||||
role = msg.get("role")
|
||||
content = (msg.get("content") or "").strip()
|
||||
if role == "user" and content:
|
||||
lines.append(f"Пользователь: {content[:800]}")
|
||||
elif role == "assistant" and content:
|
||||
lines.append(f"Ассистент: {content[:800]}")
|
||||
if not lines:
|
||||
return ""
|
||||
return (
|
||||
"[КОНТЕКСТ ПРЕДЫДУЩЕГО ДИАЛОГА В ЭТОМ ТОПИКЕ]:\n"
|
||||
+ "\n".join(lines)
|
||||
)
|
||||
|
||||
def _build_turn_prompt(
|
||||
self,
|
||||
user_message: str,
|
||||
*,
|
||||
prior_history: Optional[list[dict[str, Any]]] = None,
|
||||
) -> str:
|
||||
now = datetime.now()
|
||||
dt_context = (
|
||||
f"[ТЕКУЩИЙ КОНТЕКСТ ВРЕМЕНИ]: Сегодня {now.strftime('%A, %Y-%m-%d %H:%M:%S')} (локальное время)."
|
||||
)
|
||||
memory_summary = get_global_memory().get_memory_summary()
|
||||
|
||||
parts = [dt_context]
|
||||
if memory_summary:
|
||||
parts.append(memory_summary)
|
||||
if prior_history:
|
||||
history_block = self._format_prior_history_context(prior_history)
|
||||
if history_block:
|
||||
parts.append(history_block)
|
||||
parts.append(user_message)
|
||||
return "\n\n".join(parts)
|
||||
|
||||
async def _invoke_cli(
|
||||
self,
|
||||
binary: str,
|
||||
prompt: str,
|
||||
*,
|
||||
conversation_id: Optional[str],
|
||||
on_progress: Optional[Callable[[str], Awaitable[None]]],
|
||||
) -> tuple[Optional[str], Optional[str], Optional[str]]:
|
||||
"""Run a single `agy` headless turn and return `(response_text, new_conversation_id, error_text)`."""
|
||||
cmd = [
|
||||
binary,
|
||||
"-p",
|
||||
prompt,
|
||||
"--output-format",
|
||||
"stream-json",
|
||||
"--disable-slash-commands",
|
||||
"--agent",
|
||||
self.AGENT_NAME,
|
||||
"--settings",
|
||||
_build_locked_settings_json(),
|
||||
]
|
||||
if self.model:
|
||||
cmd.extend(["--model", self.model])
|
||||
if self.effort:
|
||||
cmd.extend(["--effort", self.effort])
|
||||
if self.timeout_seconds > 0:
|
||||
cmd.extend(["--print-timeout", f"{self.timeout_seconds}s"])
|
||||
if conversation_id:
|
||||
cmd.extend(["--conversation", conversation_id])
|
||||
|
||||
logger.debug(
|
||||
"Launching Antigravity CLI: model=%s, resume=%s, cwd=%s",
|
||||
self.model,
|
||||
bool(conversation_id),
|
||||
self._workspace_dir,
|
||||
)
|
||||
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*cmd,
|
||||
cwd=str(self._workspace_dir),
|
||||
env=_build_subprocess_env(),
|
||||
stdin=asyncio.subprocess.DEVNULL,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
limit=_STREAM_READER_LIMIT,
|
||||
)
|
||||
assert proc.stdout is not None and proc.stderr is not None
|
||||
|
||||
stderr_task = asyncio.create_task(proc.stderr.read())
|
||||
|
||||
captured_conversation_id: Optional[str] = conversation_id
|
||||
result_payload: Optional[dict[str, Any]] = None
|
||||
streamed_text_chunks: list[str] = []
|
||||
used_tools = False
|
||||
reported_synthesis = False
|
||||
|
||||
async def _consume_stdout() -> None:
|
||||
nonlocal captured_conversation_id, result_payload, used_tools, reported_synthesis
|
||||
assert proc.stdout is not None
|
||||
while True:
|
||||
raw_line = await proc.stdout.readline()
|
||||
if not raw_line:
|
||||
break
|
||||
line = raw_line.decode("utf-8", errors="replace").strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
event = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
logger.debug("Ignoring non-JSON line from agy stdout: %s", line[:200])
|
||||
continue
|
||||
|
||||
event_type = event.get("event")
|
||||
if event_type == "init":
|
||||
cid = event.get("conversation_id")
|
||||
if isinstance(cid, str) and cid:
|
||||
captured_conversation_id = cid
|
||||
elif event_type == "step_update":
|
||||
update = event.get("step_update") or {}
|
||||
cid = update.get("conversation_id")
|
||||
if isinstance(cid, str) and cid:
|
||||
captured_conversation_id = cid
|
||||
|
||||
step_type = update.get("step_type")
|
||||
state = update.get("state")
|
||||
|
||||
if step_type == "tool" and state == "ACTIVE":
|
||||
used_tools = True
|
||||
reported_synthesis = False
|
||||
if on_progress:
|
||||
from homeagent.bot.progress import format_tool_progress
|
||||
|
||||
raw_name = str(update.get("tool_name") or (update.get("tool_info") or {}).get("name") or "")
|
||||
clean_name = _strip_mcp_tool_prefix(raw_name)
|
||||
params = (update.get("tool_info") or {}).get("parameters")
|
||||
if not isinstance(params, dict):
|
||||
params = {}
|
||||
desc = format_tool_progress(clean_name, params)
|
||||
await on_progress(f"⏳ {desc}")
|
||||
elif step_type == "agent_response":
|
||||
delta = update.get("text_delta")
|
||||
if isinstance(delta, str) and delta:
|
||||
streamed_text_chunks.append(delta)
|
||||
if used_tools and not reported_synthesis and state == "ACTIVE" and on_progress:
|
||||
reported_synthesis = True
|
||||
await on_progress("🧠 Формулирую итоговый ответ...")
|
||||
elif event_type == "result":
|
||||
res = event.get("result")
|
||||
if isinstance(res, dict):
|
||||
result_payload = res
|
||||
cid = res.get("conversation_id")
|
||||
if isinstance(cid, str) and cid:
|
||||
captured_conversation_id = cid
|
||||
|
||||
wait_timeout: Optional[float] = (self.timeout_seconds + 15.0) if self.timeout_seconds > 0 else None
|
||||
try:
|
||||
if wait_timeout is not None:
|
||||
await asyncio.wait_for(_consume_stdout(), timeout=wait_timeout)
|
||||
rc = await asyncio.wait_for(proc.wait(), timeout=10.0)
|
||||
else:
|
||||
await _consume_stdout()
|
||||
rc = await proc.wait()
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning("Antigravity CLI timed out after %ss (model=%s)", self.timeout_seconds, self.model)
|
||||
try:
|
||||
proc.kill()
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
await proc.wait()
|
||||
stderr_task.cancel()
|
||||
try:
|
||||
await stderr_task
|
||||
except (asyncio.CancelledError, Exception):
|
||||
pass
|
||||
return (
|
||||
None,
|
||||
captured_conversation_id,
|
||||
f"Превышено время ожидания ответа ({self.timeout_seconds} сек).",
|
||||
)
|
||||
|
||||
stderr_bytes = await stderr_task
|
||||
stderr_text = stderr_bytes.decode("utf-8", errors="replace").strip()
|
||||
|
||||
if result_payload is not None:
|
||||
status = str(result_payload.get("status", "")).upper()
|
||||
if status == "SUCCESS":
|
||||
response_text = str(result_payload.get("response") or "").strip()
|
||||
if not response_text and streamed_text_chunks:
|
||||
response_text = "".join(streamed_text_chunks).strip()
|
||||
return (response_text or "*(Пустой ответ)*", captured_conversation_id, None)
|
||||
|
||||
err_msg = str(result_payload.get("error") or stderr_text or f"status={status} (exit={rc})")
|
||||
return (None, captured_conversation_id, err_msg)
|
||||
|
||||
if rc == 0 and streamed_text_chunks:
|
||||
return ("".join(streamed_text_chunks).strip(), captured_conversation_id, None)
|
||||
|
||||
return (None, captured_conversation_id, stderr_text or f"Antigravity CLI завершился с кодом {rc}")
|
||||
|
||||
async def chat(
|
||||
self,
|
||||
chat_id: int,
|
||||
thread_id: Optional[int],
|
||||
user_message: str,
|
||||
max_tool_iterations: int = 8,
|
||||
on_progress: Optional[Callable[[str], Awaitable[None]]] = None,
|
||||
) -> str:
|
||||
"""Process a user message within the topic context via Antigravity CLI."""
|
||||
del max_tool_iterations # Managed internally by Antigravity CLI turn execution
|
||||
|
||||
binary = _resolve_cli_binary(self.cli_path)
|
||||
if not binary:
|
||||
return (
|
||||
"⚠️ **Antigravity CLI (`agy`) не найден.**\n\n"
|
||||
"Убедитесь, что `agy` установлен, доступен в `PATH` (или укажите путь в `ANTIGRAVITY_CLI_PATH`) "
|
||||
"и вы вошли в аккаунт командой `agy`."
|
||||
)
|
||||
|
||||
lock = self._get_topic_lock(chat_id, thread_id)
|
||||
async with lock:
|
||||
await self._bridge.ensure_started()
|
||||
self._prepare_workspace()
|
||||
|
||||
if on_progress:
|
||||
await on_progress("🤔 Формирую ответ...")
|
||||
|
||||
# Respect /reset (which calls conversation_manager.clear) and carryover history
|
||||
existing_history = self.conversation_manager.get_openai_messages(chat_id, thread_id)
|
||||
topic_key = self._topic_key(chat_id, thread_id)
|
||||
saved_cid = self._conversation_ids.get(topic_key)
|
||||
|
||||
if not existing_history and saved_cid:
|
||||
self._clear_conversation_id(chat_id, thread_id)
|
||||
saved_cid = None
|
||||
|
||||
prior_history = existing_history if (existing_history and not saved_cid) else None
|
||||
prompt = self._build_turn_prompt(user_message, prior_history=prior_history)
|
||||
|
||||
response_text, new_cid, error_text = await self._invoke_cli(
|
||||
binary,
|
||||
prompt,
|
||||
conversation_id=saved_cid,
|
||||
on_progress=on_progress,
|
||||
)
|
||||
|
||||
# If resuming an old Antigravity conversation failed because it no longer exists,
|
||||
# transparently retry once as a fresh session with prior history context.
|
||||
if error_text and saved_cid and _is_stale_conversation_error(error_text):
|
||||
logger.info(
|
||||
"Stale Antigravity conversation %s for topic %s; starting fresh session.",
|
||||
saved_cid,
|
||||
topic_key,
|
||||
)
|
||||
self._clear_conversation_id(chat_id, thread_id)
|
||||
retry_prompt = self._build_turn_prompt(user_message, prior_history=existing_history or None)
|
||||
response_text, new_cid, error_text = await self._invoke_cli(
|
||||
binary,
|
||||
retry_prompt,
|
||||
conversation_id=None,
|
||||
on_progress=on_progress,
|
||||
)
|
||||
|
||||
if error_text is not None or response_text is None:
|
||||
logger.error("Antigravity CLI error for topic %s: %s", topic_key, error_text)
|
||||
return _format_cli_error(error_text or "", self.model)
|
||||
|
||||
if new_cid:
|
||||
self._conversation_ids[topic_key] = new_cid
|
||||
self._save_conversation_map()
|
||||
|
||||
self.conversation_manager.append_openai_turn_sequence(
|
||||
chat_id,
|
||||
thread_id,
|
||||
[
|
||||
{"role": "user", "content": user_message},
|
||||
{"role": "assistant", "content": response_text},
|
||||
],
|
||||
)
|
||||
return response_text
|
||||
|
||||
async def close(self) -> None:
|
||||
"""Stop owned MCP tool bridge cleanly."""
|
||||
if self._owns_bridge:
|
||||
await self._bridge.stop()
|
||||
|
||||
|
||||
async def run_antigravity_subagent_task(
|
||||
*,
|
||||
settings: Settings,
|
||||
registry: ToolRegistry,
|
||||
task: str,
|
||||
role: str,
|
||||
context: Optional[str] = None,
|
||||
bridge: Optional[MCPToolBridge] = None,
|
||||
) -> str:
|
||||
"""Execute a stateless subagent task via Antigravity CLI using ANTIGRAVITY_SUBAGENT_MODEL."""
|
||||
binary = _resolve_cli_binary(settings.ANTIGRAVITY_CLI_PATH)
|
||||
if not binary:
|
||||
return "Ошибка: Antigravity CLI (`agy`) не найден для подагента."
|
||||
|
||||
owns_bridge = bridge is None
|
||||
active_bridge = bridge or MCPToolBridge(registry)
|
||||
await active_bridge.ensure_started()
|
||||
|
||||
workspace_dir = settings.DATA_DIR / "antigravity_subagent_workspace"
|
||||
subagent_name = "homeagent-subagent"
|
||||
timeout_seconds = max(0, int(settings.ANTIGRAVITY_TIMEOUT_SECONDS))
|
||||
|
||||
try:
|
||||
active_bridge.write_mcp_config(
|
||||
workspace_dir,
|
||||
subagent=True,
|
||||
timeout_seconds=max(60, timeout_seconds or 180),
|
||||
)
|
||||
|
||||
agent_md = (
|
||||
"---\n"
|
||||
f"name: {subagent_name}\n"
|
||||
"description: Fast autonomous HomeAgent subagent.\n"
|
||||
"---\n\n"
|
||||
"Ты — быстрый автономный AI-подагент HomeAgent.\n"
|
||||
"Используй доступные MCP-инструменты HomeAgent (`mcp_homeagent_*`), чтобы получить актуальные данные "
|
||||
"или выполнить порученное действие, и верни емкую выжимку в Markdown главному агенту-координатору.\n"
|
||||
)
|
||||
_write_text_atomic(workspace_dir / ".agents" / "agents" / subagent_name / "agent.md", agent_md)
|
||||
|
||||
prompt_parts = [
|
||||
f"Роль подагента: {role}",
|
||||
f"Задача: {task}",
|
||||
]
|
||||
if context:
|
||||
prompt_parts.append(f"Дополнительный контекст от главного агента:\n{context}")
|
||||
prompt = "\n\n".join(prompt_parts)
|
||||
|
||||
model = settings.ANTIGRAVITY_SUBAGENT_MODEL or "gemini-3.8-flash-medium"
|
||||
cmd = [
|
||||
binary,
|
||||
"-p",
|
||||
prompt,
|
||||
"--output-format",
|
||||
"json",
|
||||
"--disable-slash-commands",
|
||||
"--agent",
|
||||
subagent_name,
|
||||
"--model",
|
||||
model,
|
||||
"--settings",
|
||||
_build_locked_settings_json(),
|
||||
]
|
||||
if timeout_seconds > 0:
|
||||
cmd.extend(["--print-timeout", f"{timeout_seconds}s"])
|
||||
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*cmd,
|
||||
cwd=str(workspace_dir),
|
||||
env=_build_subprocess_env(),
|
||||
stdin=asyncio.subprocess.DEVNULL,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
wait_timeout: Optional[float] = (timeout_seconds + 15.0) if timeout_seconds > 0 else None
|
||||
try:
|
||||
if wait_timeout is not None:
|
||||
stdout_bytes, stderr_bytes = await asyncio.wait_for(proc.communicate(), timeout=wait_timeout)
|
||||
else:
|
||||
stdout_bytes, stderr_bytes = await proc.communicate()
|
||||
except asyncio.TimeoutError:
|
||||
proc.kill()
|
||||
await proc.wait()
|
||||
return f"Ошибка подагента ({role}): превышен таймаут Antigravity CLI ({timeout_seconds} сек)."
|
||||
|
||||
stdout_text = stdout_bytes.decode("utf-8", errors="replace").strip()
|
||||
stderr_text = stderr_bytes.decode("utf-8", errors="replace").strip()
|
||||
|
||||
try:
|
||||
payload = json.loads(stdout_text)
|
||||
except Exception:
|
||||
if proc.returncode == 0 and stdout_text:
|
||||
return stdout_text
|
||||
return f"Ошибка подагента ({role}): {stderr_text or stdout_text or f'exit={proc.returncode}'}"
|
||||
|
||||
if str(payload.get("status", "")).upper() == "SUCCESS":
|
||||
return str(payload.get("response") or "").strip() or "(Подагент завершил работу без вывода)"
|
||||
|
||||
return f"Ошибка подагента ({role}): {payload.get('error') or stderr_text or payload.get('status')}"
|
||||
finally:
|
||||
if owns_bridge:
|
||||
await active_bridge.stop()
|
||||
@@ -29,3 +29,7 @@ class BaseAgent(ABC):
|
||||
Final markdown response text for the user
|
||||
"""
|
||||
pass
|
||||
|
||||
async def close(self) -> None:
|
||||
"""Release any resources owned by the agent on application shutdown."""
|
||||
return None
|
||||
@@ -3,6 +3,7 @@
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from homeagent.agent.antigravity import AntigravityAgent
|
||||
from homeagent.agent.base import BaseAgent
|
||||
from homeagent.agent.conversation import ConversationManager
|
||||
from homeagent.agent.gemini import GeminiAgent
|
||||
@@ -40,6 +41,12 @@ def create_agent(
|
||||
conversation_manager=conversation_manager,
|
||||
provider_override="openai",
|
||||
)
|
||||
elif provider == "antigravity":
|
||||
return AntigravityAgent(
|
||||
settings=settings,
|
||||
registry=registry,
|
||||
conversation_manager=conversation_manager,
|
||||
)
|
||||
elif provider == "gemini":
|
||||
return GeminiAgent(
|
||||
settings=settings,
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
"""In-process Streamable HTTP MCP server bridging HomeAgent ToolRegistry to Antigravity CLI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
from aiohttp import web
|
||||
|
||||
from homeagent.tools.registry import ToolRegistry
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
EXCLUDED_SUBAGENT_TOOLS = frozenset({"spawn_subagent", "spawn_parallel_subagents"})
|
||||
|
||||
|
||||
def normalize_mcp_schema(schema: Any) -> Any:
|
||||
"""Normalize HomeAgent tool parameter schema into clean standard JSON Schema for MCP."""
|
||||
if isinstance(schema, list):
|
||||
return [normalize_mcp_schema(item) for item in schema]
|
||||
if not isinstance(schema, dict):
|
||||
return schema
|
||||
|
||||
cleaned: dict[str, Any] = {}
|
||||
for key, value in schema.items():
|
||||
if key == "nullable":
|
||||
continue
|
||||
cleaned[key] = normalize_mcp_schema(value)
|
||||
|
||||
if cleaned.get("type") == "object" and "properties" not in cleaned:
|
||||
cleaned["properties"] = {}
|
||||
return cleaned
|
||||
|
||||
|
||||
class MCPToolBridge:
|
||||
"""Lightweight localhost Streamable HTTP MCP server exposing a HomeAgent ToolRegistry.
|
||||
|
||||
Mounts two authenticated JSON-RPC 2.0 endpoints on ``127.0.0.1`` (ephemeral port):
|
||||
- ``/mcp``: all registered tools in ``registry``
|
||||
- ``/mcp-subagent``: all registered tools except subagent-spawning tools (prevents recursion)
|
||||
"""
|
||||
|
||||
SERVER_NAME = "homeagent"
|
||||
SERVER_VERSION = "1.0.0"
|
||||
|
||||
def __init__(self, registry: ToolRegistry) -> None:
|
||||
self.registry = registry
|
||||
self._token: str = secrets.token_urlsafe(32)
|
||||
self._runner: Optional[web.AppRunner] = None
|
||||
self._site: Optional[web.TCPSite] = None
|
||||
self._port: Optional[int] = None
|
||||
self._start_lock = asyncio.Lock()
|
||||
|
||||
@property
|
||||
def is_running(self) -> bool:
|
||||
return self._port is not None and self._runner is not None
|
||||
|
||||
@property
|
||||
def port(self) -> int:
|
||||
if self._port is None:
|
||||
raise RuntimeError("MCPToolBridge is not started yet.")
|
||||
return self._port
|
||||
|
||||
@property
|
||||
def token(self) -> str:
|
||||
return self._token
|
||||
|
||||
def get_endpoint_url(self, *, subagent: bool = False) -> str:
|
||||
path = "/mcp-subagent" if subagent else "/mcp"
|
||||
return f"http://127.0.0.1:{self.port}{path}"
|
||||
|
||||
async def ensure_started(self) -> None:
|
||||
"""Start the local HTTP MCP server if it is not already running."""
|
||||
if self.is_running:
|
||||
return
|
||||
async with self._start_lock:
|
||||
if self.is_running:
|
||||
return
|
||||
app = web.Application()
|
||||
app.router.add_route("*", "/mcp", self._handle_main_mcp)
|
||||
app.router.add_route("*", "/mcp-subagent", self._handle_subagent_mcp)
|
||||
|
||||
runner = web.AppRunner(app, access_log=None)
|
||||
await runner.setup()
|
||||
site = web.TCPSite(runner, "127.0.0.1", 0)
|
||||
await site.start()
|
||||
|
||||
sockets = getattr(site._server, "sockets", None) # type: ignore[union-attr]
|
||||
if not sockets:
|
||||
await runner.cleanup()
|
||||
raise RuntimeError("Failed to bind MCPToolBridge to an ephemeral localhost port.")
|
||||
|
||||
self._port = int(sockets[0].getsockname()[1])
|
||||
self._runner = runner
|
||||
self._site = site
|
||||
logger.info("MCPToolBridge listening on http://127.0.0.1:%d/mcp", self._port)
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""Stop the local HTTP MCP server and release its port."""
|
||||
async with self._start_lock:
|
||||
if self._runner is not None:
|
||||
try:
|
||||
await self._runner.cleanup()
|
||||
except Exception as e:
|
||||
logger.debug("Error stopping MCPToolBridge: %s", e)
|
||||
self._runner = None
|
||||
self._site = None
|
||||
self._port = None
|
||||
|
||||
def build_mcp_config(
|
||||
self,
|
||||
*,
|
||||
subagent: bool = False,
|
||||
timeout_seconds: int = 180,
|
||||
) -> dict[str, Any]:
|
||||
"""Build `.agents/mcp_config.json` structure with all exposed tools set to eager."""
|
||||
tools_config: dict[str, dict[str, bool]] = {}
|
||||
for tool_def in self.registry.list_tools():
|
||||
if subagent and tool_def.name in EXCLUDED_SUBAGENT_TOOLS:
|
||||
continue
|
||||
tools_config[tool_def.name] = {"eager": True}
|
||||
|
||||
return {
|
||||
"mcpServers": {
|
||||
self.SERVER_NAME: {
|
||||
"serverUrl": self.get_endpoint_url(subagent=subagent),
|
||||
"headers": {
|
||||
"Authorization": f"Bearer {self._token}",
|
||||
},
|
||||
"tools": tools_config,
|
||||
"timeoutSeconds": timeout_seconds,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def write_mcp_config(
|
||||
self,
|
||||
workspace_dir: Path,
|
||||
*,
|
||||
subagent: bool = False,
|
||||
timeout_seconds: int = 180,
|
||||
) -> Path:
|
||||
"""Atomically write `<workspace_dir>/.agents/mcp_config.json` with restrictive permissions."""
|
||||
agents_dir = workspace_dir / ".agents"
|
||||
agents_dir.mkdir(parents=True, exist_ok=True)
|
||||
config_path = agents_dir / "mcp_config.json"
|
||||
payload = json.dumps(
|
||||
self.build_mcp_config(subagent=subagent, timeout_seconds=timeout_seconds),
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
|
||||
tmp_path = agents_dir / f".mcp_config.{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, config_path)
|
||||
except Exception:
|
||||
if tmp_path.exists():
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
raise
|
||||
return config_path
|
||||
|
||||
async def _handle_main_mcp(self, request: web.Request) -> web.Response:
|
||||
return await self._handle_mcp(request, exclude_subagents=False)
|
||||
|
||||
async def _handle_subagent_mcp(self, request: web.Request) -> web.Response:
|
||||
return await self._handle_mcp(request, exclude_subagents=True)
|
||||
|
||||
async def _handle_mcp(self, request: web.Request, *, exclude_subagents: bool) -> web.Response:
|
||||
expected_auth = f"Bearer {self._token}"
|
||||
if not secrets.compare_digest(request.headers.get("Authorization", ""), expected_auth):
|
||||
return web.Response(status=401, text="Unauthorized")
|
||||
|
||||
if request.method == "GET":
|
||||
# Streamable HTTP: 405 indicates no server-initiated SSE stream on GET
|
||||
return web.Response(status=405, text="Method Not Allowed")
|
||||
|
||||
if request.method == "DELETE":
|
||||
return web.Response(status=204)
|
||||
|
||||
if request.method != "POST":
|
||||
return web.Response(status=405, text="Method Not Allowed")
|
||||
|
||||
raw_body = await request.read()
|
||||
if not raw_body.strip():
|
||||
return web.json_response(
|
||||
{"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Empty request body"}},
|
||||
status=400,
|
||||
)
|
||||
|
||||
try:
|
||||
body = json.loads(raw_body.decode("utf-8"))
|
||||
except Exception:
|
||||
return web.json_response(
|
||||
{"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}},
|
||||
status=400,
|
||||
)
|
||||
|
||||
if not isinstance(body, dict):
|
||||
return web.json_response(
|
||||
{"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "Invalid Request"}},
|
||||
status=400,
|
||||
)
|
||||
|
||||
method = body.get("method")
|
||||
req_id = body.get("id")
|
||||
params = body.get("params") if isinstance(body.get("params"), dict) else {}
|
||||
|
||||
# JSON-RPC notification (no id): acknowledge with 202 Accepted
|
||||
if "id" not in body or req_id is None:
|
||||
return web.Response(status=202)
|
||||
|
||||
if not isinstance(method, str):
|
||||
return web.json_response(
|
||||
{"jsonrpc": "2.0", "id": req_id, "error": {"code": -32600, "message": "Invalid Request"}}
|
||||
)
|
||||
|
||||
if method == "initialize":
|
||||
protocol_version = params.get("protocolVersion") or "2025-03-26"
|
||||
return web.json_response(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"result": {
|
||||
"protocolVersion": protocol_version,
|
||||
"capabilities": {"tools": {"listChanged": False}},
|
||||
"serverInfo": {
|
||||
"name": self.SERVER_NAME,
|
||||
"version": self.SERVER_VERSION,
|
||||
},
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
if method == "ping":
|
||||
return web.json_response({"jsonrpc": "2.0", "id": req_id, "result": {}})
|
||||
|
||||
if method == "tools/list":
|
||||
tools_payload: list[dict[str, Any]] = []
|
||||
for tool_def in self.registry.list_tools():
|
||||
if exclude_subagents and tool_def.name in EXCLUDED_SUBAGENT_TOOLS:
|
||||
continue
|
||||
schema = normalize_mcp_schema(tool_def.parameters_schema)
|
||||
if not isinstance(schema, dict) or schema.get("type") != "object":
|
||||
schema = {"type": "object", "properties": {}}
|
||||
tools_payload.append(
|
||||
{
|
||||
"name": tool_def.name,
|
||||
"description": tool_def.description,
|
||||
"inputSchema": schema,
|
||||
}
|
||||
)
|
||||
return web.json_response(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"result": {"tools": tools_payload},
|
||||
}
|
||||
)
|
||||
|
||||
if method == "tools/call":
|
||||
tool_name = params.get("name")
|
||||
arguments = params.get("arguments")
|
||||
if not isinstance(tool_name, str) or not tool_name:
|
||||
return web.json_response(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"error": {"code": -32602, "message": "Missing or invalid tool name"},
|
||||
}
|
||||
)
|
||||
if arguments is None:
|
||||
arguments = {}
|
||||
if not isinstance(arguments, dict):
|
||||
return web.json_response(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"error": {"code": -32602, "message": "Tool arguments must be an object"},
|
||||
}
|
||||
)
|
||||
if exclude_subagents and tool_name in EXCLUDED_SUBAGENT_TOOLS:
|
||||
return web.json_response(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"result": {
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": f"Error: Tool '{tool_name}' is disabled for subagents.",
|
||||
}
|
||||
],
|
||||
"isError": True,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
if self.registry.get(tool_name) is None:
|
||||
return web.json_response(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"result": {
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": f"Error: Tool '{tool_name}' not found in registry.",
|
||||
}
|
||||
],
|
||||
"isError": True,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
result_text = await self.registry.execute(tool_name, arguments)
|
||||
return web.json_response(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"result": {
|
||||
"content": [{"type": "text", "text": result_text}],
|
||||
"isError": False,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
return web.json_response(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"error": {"code": -32601, "message": f"Method not found: {method}"},
|
||||
}
|
||||
)
|
||||
@@ -70,13 +70,19 @@ class SubagentRunner:
|
||||
for tool_def in self.registry.list_tools():
|
||||
if tool_def.name in ("spawn_subagent", "spawn_parallel_subagents"):
|
||||
continue
|
||||
declarations.append(
|
||||
types.FunctionDeclaration(
|
||||
try:
|
||||
fd = types.FunctionDeclaration(
|
||||
name=tool_def.name,
|
||||
description=tool_def.description,
|
||||
parameters=tool_def.parameters_schema,
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
fd = types.FunctionDeclaration(
|
||||
name=tool_def.name,
|
||||
description=tool_def.description,
|
||||
parameters_json_schema=tool_def.parameters_schema,
|
||||
)
|
||||
declarations.append(fd)
|
||||
if not declarations:
|
||||
return None
|
||||
return [types.Tool(function_declarations=declarations)]
|
||||
@@ -241,6 +247,30 @@ class SubagentRunner:
|
||||
|
||||
return f"Подагент ({role}) достиг лимита итераций без итогового ответа."
|
||||
|
||||
async def _run_task_antigravity(
|
||||
self,
|
||||
task: str,
|
||||
role: str,
|
||||
context: Optional[str] = None,
|
||||
) -> str:
|
||||
from homeagent.agent.antigravity import run_antigravity_subagent_task
|
||||
from homeagent.agent.mcp_bridge import MCPToolBridge
|
||||
|
||||
logger.info("[SUBAGENT ANTIGRAVITY START] Role='%s', Task='%s'", role, task)
|
||||
if not hasattr(self, "_mcp_bridge") or self._mcp_bridge is None:
|
||||
self._mcp_bridge = MCPToolBridge(self.registry)
|
||||
|
||||
result = await run_antigravity_subagent_task(
|
||||
settings=self.settings,
|
||||
registry=self.registry,
|
||||
task=task,
|
||||
role=role,
|
||||
context=context,
|
||||
bridge=self._mcp_bridge,
|
||||
)
|
||||
logger.info("[SUBAGENT ANTIGRAVITY DONE] Role='%s'", role)
|
||||
return result
|
||||
|
||||
async def run_task(
|
||||
self,
|
||||
task: str,
|
||||
@@ -253,6 +283,10 @@ class SubagentRunner:
|
||||
return await self._run_task_gemini(
|
||||
task=task, role=role, context=context, max_tool_iterations=max_tool_iterations
|
||||
)
|
||||
elif self.settings.LLM_PROVIDER == "antigravity":
|
||||
return await self._run_task_antigravity(
|
||||
task=task, role=role, context=context
|
||||
)
|
||||
else:
|
||||
return await self._run_task_openai(
|
||||
task=task, role=role, context=context, max_tool_iterations=max_tool_iterations
|
||||
|
||||
@@ -10,6 +10,7 @@ from aiogram import Bot, Router
|
||||
from aiogram.enums import ChatAction, ParseMode
|
||||
from aiogram.filters import Command
|
||||
from aiogram.types import (
|
||||
InlineKeyboardMarkup,
|
||||
InlineQueryResultArticle,
|
||||
InputRichMessage,
|
||||
InputRichMessageContent,
|
||||
@@ -18,9 +19,11 @@ from aiogram.types import (
|
||||
)
|
||||
|
||||
from homeagent.agent.base import BaseAgent
|
||||
from homeagent.bot.mcp_handlers import MCPBotController
|
||||
from homeagent.bot.progress import ProgressReporter
|
||||
from homeagent.bot.utils import split_message
|
||||
from homeagent.config import Settings
|
||||
from homeagent.mcp.manager import MCPConnectorManager
|
||||
from homeagent.memory.global_memory import get_global_memory
|
||||
from homeagent.skills.manager import SkillManager
|
||||
from homeagent.tools.registry import ToolRegistry
|
||||
@@ -49,9 +52,11 @@ def create_bot_router(
|
||||
agent: BaseAgent,
|
||||
skill_manager: SkillManager,
|
||||
tool_registry: ToolRegistry,
|
||||
mcp_manager: Optional[MCPConnectorManager] = None,
|
||||
) -> Router:
|
||||
"""Create and configure the main Aiogram Router."""
|
||||
router = Router(name="main_router")
|
||||
mcp_controller = MCPBotController(mcp_manager, _send_reply) if mcp_manager is not None else None
|
||||
|
||||
@router.message(Command("start", "help"))
|
||||
async def handle_start(message: Message) -> None:
|
||||
@@ -61,6 +66,8 @@ def create_bot_router(
|
||||
|
||||
skills = skill_manager.list_skills()
|
||||
tools = tool_registry.list_tools()
|
||||
mcp_states = mcp_manager.list_connectors() if mcp_manager is not None else []
|
||||
mcp_connected = sum(1 for s in mcp_states if s.status == "connected")
|
||||
|
||||
greeting = (
|
||||
f"👋 **Привет! Я твой персональный AI-ассистент.**\n\n"
|
||||
@@ -71,10 +78,13 @@ def create_bot_router(
|
||||
f"- Главная модель (Orchestrator): `{settings.get_active_model()}`\n"
|
||||
f"- Модель быстрых подагентов: `{settings.get_active_subagent_model()}`\n"
|
||||
f"- Доступно скиллов: **{len(skills)}** (введите `/skills`)\n"
|
||||
f"- MCP коннекторов: **{mcp_connected}/{len(mcp_states)}** (введите `/mcp`)\n"
|
||||
f"- Доступно инструментов: **{len(tools)}**\n\n"
|
||||
f"📋 **Полезные команды:**\n"
|
||||
f"• `/mcp` — подключить и настроить MCP коннекторы\n"
|
||||
f"• `/skills` — список готовых скиллов и триггеров\n"
|
||||
f"• `/skill <название>` — запустить конкретный скилл\n"
|
||||
f"• `/model` — текущая модель (и переключение для Antigravity)\n"
|
||||
f"• `/memory` — посмотреть факты в глобальной памяти\n"
|
||||
f"• `/reset` — очистить контекст диалога в текущем топике\n"
|
||||
f"• `/help` — показать это сообщение\n\n"
|
||||
@@ -120,6 +130,53 @@ def create_bot_router(
|
||||
lines.append("\n_Эти данные автоматически подмешиваются в системный промпт во всех топиках._")
|
||||
await _send_reply(message, "\n".join(lines))
|
||||
|
||||
async def _build_model_command_response(raw_text: str) -> str:
|
||||
parts = raw_text.strip().split(maxsplit=1)
|
||||
requested_model = parts[1].strip() if len(parts) > 1 else ""
|
||||
|
||||
if requested_model:
|
||||
set_model_fn = getattr(agent, "set_model", None)
|
||||
if callable(set_model_fn):
|
||||
set_model_fn(requested_model)
|
||||
return (
|
||||
f"✅ Активная модель **{settings.get_active_provider_name()}** переключена на:\n"
|
||||
f"`{settings.get_active_model()}`"
|
||||
)
|
||||
return (
|
||||
f"ℹ️ Текущий провайдер `{settings.get_active_provider_name()}` использует модель "
|
||||
f"`{settings.get_active_model()}`.\n"
|
||||
"Переключение модели на лету поддерживается для провайдера `antigravity`; "
|
||||
"для остальных провайдеров измените модель в `.env` и перезапустите бота."
|
||||
)
|
||||
|
||||
lines = [
|
||||
"🤖 **Активная конфигурация LLM:**\n",
|
||||
f"- Провайдер: `{settings.get_active_provider_name()}` (`{settings.LLM_PROVIDER}`)",
|
||||
f"- Главная модель: `{settings.get_active_model()}`",
|
||||
f"- Модель подагентов: `{settings.get_active_subagent_model()}`",
|
||||
]
|
||||
|
||||
list_models_fn = getattr(agent, "list_available_models", None)
|
||||
if callable(list_models_fn):
|
||||
available = await list_models_fn()
|
||||
if available:
|
||||
lines.append("\n📋 **Доступные модели Antigravity** (переключить: `/model <slug>`):")
|
||||
for slug, label in available:
|
||||
marker = " ✅" if slug == settings.get_active_model() else ""
|
||||
lines.append(f"- `{slug}` — {label}{marker}")
|
||||
else:
|
||||
lines.append(
|
||||
"\n💡 Переключить модель: `/model <slug>` (список можно посмотреть командой `agy models`)."
|
||||
)
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
@router.message(Command("model", "models"))
|
||||
async def handle_model(message: Message) -> None:
|
||||
raw_text = message.text or ""
|
||||
reply_text = await _build_model_command_response(raw_text)
|
||||
await _send_reply(message, reply_text)
|
||||
|
||||
@router.message(Command("reset"))
|
||||
async def handle_reset(message: Message) -> None:
|
||||
chat_id = message.chat.id
|
||||
@@ -131,8 +188,14 @@ def create_bot_router(
|
||||
f"🧹 Контекст диалога {topic_info} успешно очищен. Глобальная память сохранена.",
|
||||
)
|
||||
|
||||
if mcp_controller is not None:
|
||||
mcp_controller.register_handlers(router)
|
||||
|
||||
@router.message()
|
||||
async def handle_message(message: Message) -> None:
|
||||
if mcp_controller is not None and await mcp_controller.handle_wizard_message(message):
|
||||
return
|
||||
|
||||
text = message.text or message.caption or ""
|
||||
if not text.strip():
|
||||
return
|
||||
@@ -259,11 +322,16 @@ def create_bot_router(
|
||||
f"💡 **Как меня использовать:**\n"
|
||||
f"• Упомяните `{bot_tag} <ваш вопрос>` с любой задачей или вопросом.\n"
|
||||
f"• Ответьте тегом `{bot_tag}` на любое сообщение, чтобы я проанализировал или объяснил его.\n"
|
||||
f"• Команды: `/skills`, `/memory`, `/reset`."
|
||||
f"• Команды: `/mcp`, `/skills`, `/model`, `/memory`, `/reset`."
|
||||
)
|
||||
await _send_guest_reply(active_bot, guest_query_id, help_msg)
|
||||
return
|
||||
|
||||
if mcp_controller is not None and (cmd_lower == "/mcp" or cmd_lower.startswith("/mcp ")):
|
||||
reply_text = await mcp_controller.handle_text_command(cleaned_text)
|
||||
await _send_guest_reply(active_bot, guest_query_id, reply_text)
|
||||
return
|
||||
|
||||
if cmd_lower == "/skills":
|
||||
skills = skill_manager.list_skills()
|
||||
if not skills:
|
||||
@@ -298,6 +366,11 @@ def create_bot_router(
|
||||
await _send_guest_reply(active_bot, guest_query_id, "\n".join(lines))
|
||||
return
|
||||
|
||||
if cmd_lower == "/model" or cmd_lower == "/models" or cmd_lower.startswith("/model "):
|
||||
reply_text = await _build_model_command_response(cleaned_text)
|
||||
await _send_guest_reply(active_bot, guest_query_id, reply_text)
|
||||
return
|
||||
|
||||
if cmd_lower == "/reset":
|
||||
agent.conversation_manager.clear(chat_id, thread_id)
|
||||
topic_info = f"в топике #{thread_id}" if thread_id else "в этом чате"
|
||||
@@ -356,15 +429,24 @@ def create_bot_router(
|
||||
return router
|
||||
|
||||
|
||||
async def _send_reply(message: Message, text: str) -> None:
|
||||
async def _send_reply(
|
||||
message: Message,
|
||||
text: str,
|
||||
reply_markup: Optional[InlineKeyboardMarkup] = None,
|
||||
) -> None:
|
||||
"""Send reply strictly using Telegram sendRichMessage API with InputRichMessage."""
|
||||
rich_msg = InputRichMessage(markdown=text)
|
||||
extra_kwargs: dict[str, object] = {}
|
||||
if reply_markup is not None:
|
||||
extra_kwargs["reply_markup"] = reply_markup
|
||||
|
||||
try:
|
||||
await message.bot.send_rich_message(
|
||||
chat_id=message.chat.id,
|
||||
rich_message=rich_msg,
|
||||
message_thread_id=message.message_thread_id,
|
||||
reply_parameters=message.as_reply_parameters(),
|
||||
**extra_kwargs,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning("Failed sending markdown rich message, trying html/plain rich message: %s", e)
|
||||
@@ -375,6 +457,7 @@ async def _send_reply(message: Message, text: str) -> None:
|
||||
rich_message=InputRichMessage(html=text),
|
||||
message_thread_id=message.message_thread_id,
|
||||
reply_parameters=message.as_reply_parameters(),
|
||||
**extra_kwargs,
|
||||
)
|
||||
except Exception as e2:
|
||||
logger.error("Failed sending rich message via sendRichMessage: %s", e2)
|
||||
@@ -385,6 +468,7 @@ async def _send_reply(message: Message, text: str) -> None:
|
||||
text=text,
|
||||
message_thread_id=message.message_thread_id,
|
||||
reply_parameters=message.as_reply_parameters(),
|
||||
**extra_kwargs,
|
||||
)
|
||||
except Exception as final_err:
|
||||
logger.error("Failed sending message completely: %s", final_err)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -144,6 +144,12 @@ def format_tool_progress(name: str, args: dict[str, Any]) -> str:
|
||||
cnt = len(tasks) if isinstance(tasks, list) else ""
|
||||
return f"👥 Запускаю {cnt} параллельных подагентов..."
|
||||
|
||||
if name.startswith("mcp_"):
|
||||
parts = name.split("_", 2)
|
||||
if len(parts) == 3:
|
||||
return f"🔌 MCP [{parts[1]}]: выполняю `{parts[2]}`..."
|
||||
return f"🔌 MCP: выполняю `{name}`..."
|
||||
|
||||
return f"🔧 Выполняю `{name}`..."
|
||||
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ from homeagent.agent.factory import create_agent
|
||||
from homeagent.bot.handlers import create_bot_router
|
||||
from homeagent.bot.middlewares import WhitelistMiddleware
|
||||
from homeagent.config import Settings, get_settings
|
||||
from homeagent.mcp.manager import MCPConnectorManager
|
||||
from homeagent.skills.manager import SkillManager
|
||||
from homeagent.tools.loader import load_extensions_from_directory
|
||||
from homeagent.tools.registry import get_tool_registry
|
||||
@@ -31,10 +32,16 @@ class TelegramAgentApp:
|
||||
# Load dynamic extensions from directory
|
||||
load_extensions_from_directory(self.settings.EXTENSIONS_DIR, self.registry)
|
||||
|
||||
# Initialize MCP connectors manager (config + persisted bot connectors)
|
||||
self.mcp_manager = MCPConnectorManager(
|
||||
settings=self.settings,
|
||||
registry=self.registry,
|
||||
)
|
||||
|
||||
# Initialize skills
|
||||
self.skill_manager = SkillManager(self.settings.SKILLS_DIR)
|
||||
|
||||
# Initialize LLM agent according to active provider (Gemini, DeepSeek, or OpenAI)
|
||||
# Initialize LLM agent according to active provider (Gemini, DeepSeek, OpenAI, or Antigravity)
|
||||
self.agent: BaseAgent = create_agent(
|
||||
settings=self.settings,
|
||||
registry=self.registry,
|
||||
@@ -53,9 +60,10 @@ class TelegramAgentApp:
|
||||
except Exception as e:
|
||||
logger.warning("Could not initialize Telegram Bot with provided token: %s", e)
|
||||
|
||||
# Enforce strict whitelist middleware on message and ghost/guest events
|
||||
# Enforce strict whitelist middleware on message, callback_query, and ghost/guest events
|
||||
whitelist_middleware = WhitelistMiddleware(self.settings)
|
||||
self.dp.message.middleware(whitelist_middleware)
|
||||
self.dp.callback_query.middleware(whitelist_middleware)
|
||||
self.dp.guest_message.middleware(whitelist_middleware)
|
||||
|
||||
# Register router
|
||||
@@ -64,6 +72,7 @@ class TelegramAgentApp:
|
||||
agent=self.agent,
|
||||
skill_manager=self.skill_manager,
|
||||
tool_registry=self.registry,
|
||||
mcp_manager=self.mcp_manager,
|
||||
)
|
||||
self.dp.include_router(router)
|
||||
|
||||
@@ -74,7 +83,9 @@ class TelegramAgentApp:
|
||||
|
||||
commands = [
|
||||
BotCommand(command="start", description="Запустить бота / статус"),
|
||||
BotCommand(command="mcp", description="Управление MCP коннекторами"),
|
||||
BotCommand(command="skills", description="Список доступных скиллов"),
|
||||
BotCommand(command="model", description="Текущая модель / переключение модели"),
|
||||
BotCommand(command="memory", description="Глобальная память фактов"),
|
||||
BotCommand(command="reset", description="Очистить контекст текущего топика"),
|
||||
BotCommand(command="help", description="Справка по командам"),
|
||||
@@ -89,12 +100,22 @@ class TelegramAgentApp:
|
||||
if not self.bot:
|
||||
raise ValueError("Cannot start bot: TELEGRAM_BOT_TOKEN is missing or invalid.")
|
||||
|
||||
if self.settings.MCP_ENABLED:
|
||||
await self.mcp_manager.connect_all()
|
||||
|
||||
logger.info("Starting HomeAgent Telegram Bot...")
|
||||
logger.info("Allowed User IDs: %s", self.settings.ALLOWED_TELEGRAM_USER_IDS)
|
||||
logger.info("Ghost Bot Mode: %s", "Enabled (Bot API 10.0+ guest_message)" if self.settings.GHOST_MODE_ENABLED else "Disabled")
|
||||
logger.info("LLM Provider: %s", self.settings.get_active_provider_name())
|
||||
logger.info("Orchestrator Model: %s", self.settings.get_active_model())
|
||||
logger.info("Subagent Model: %s", self.settings.get_active_subagent_model())
|
||||
mcp_states = self.mcp_manager.list_connectors()
|
||||
logger.info(
|
||||
"MCP Connectors (%d total, %d connected): %s",
|
||||
len(mcp_states),
|
||||
sum(1 for s in mcp_states if s.status == "connected"),
|
||||
[f"{s.config.name}:{s.status}" for s in mcp_states],
|
||||
)
|
||||
logger.info("Registered Tools (%d): %s", len(self.registry.list_tools()), [t.name for t in self.registry.list_tools()])
|
||||
logger.info("Loaded Skills (%d): %s", len(self.skill_manager.list_skills()), [s.name for s in self.skill_manager.list_skills()])
|
||||
|
||||
@@ -107,4 +128,6 @@ class TelegramAgentApp:
|
||||
logger.info("Polling with allowed_updates: %s", allowed_updates)
|
||||
await self.dp.start_polling(self.bot, allowed_updates=allowed_updates)
|
||||
finally:
|
||||
await self.mcp_manager.close()
|
||||
await self.agent.close()
|
||||
await self.bot.session.close()
|
||||
+69
-5
@@ -27,10 +27,10 @@ class Settings(BaseSettings):
|
||||
description="Enable or disable Ghost/Guest Bot mode (Telegram Bot API 10.0+ guest_message). Allows responding in chats without being added as a member.",
|
||||
)
|
||||
|
||||
# LLM Provider selection: 'gemini', 'deepseek', or 'openai' (compatible)
|
||||
LLM_PROVIDER: Literal["gemini", "deepseek", "openai"] = Field(
|
||||
# LLM Provider selection: 'gemini', 'deepseek', 'openai', or 'antigravity'
|
||||
LLM_PROVIDER: Literal["gemini", "deepseek", "openai", "antigravity"] = Field(
|
||||
default="gemini",
|
||||
description="Active LLM provider: 'gemini', 'deepseek', or 'openai'",
|
||||
description="Active LLM provider: 'gemini', 'deepseek', 'openai', or 'antigravity'",
|
||||
)
|
||||
|
||||
# Google AI Studio (Gemini)
|
||||
@@ -83,20 +83,48 @@ class Settings(BaseSettings):
|
||||
description="Fast model for subagents on OpenAI-compatible endpoint",
|
||||
)
|
||||
|
||||
# Antigravity CLI (uses Antigravity models and subscription quotas via `agy`)
|
||||
ANTIGRAVITY_CLI_PATH: str = Field(
|
||||
default="agy",
|
||||
description="Path or command name for Antigravity CLI binary (`agy`)",
|
||||
)
|
||||
ANTIGRAVITY_MODEL: str = Field(
|
||||
default="gemini-4-neon-high",
|
||||
description="Antigravity model slug (run `agy models` to list available models)",
|
||||
)
|
||||
ANTIGRAVITY_SUBAGENT_MODEL: str = Field(
|
||||
default="gemini-3.8-flash-medium",
|
||||
description="Fast Antigravity model slug used for subagents",
|
||||
)
|
||||
ANTIGRAVITY_EFFORT: Optional[str] = Field(
|
||||
default=None,
|
||||
description="Optional reasoning effort override for Antigravity CLI (low|medium|high|xhigh|max)",
|
||||
)
|
||||
ANTIGRAVITY_TIMEOUT_SECONDS: int = Field(
|
||||
default=300,
|
||||
description="Maximum seconds to wait for a single Antigravity CLI turn (0 = no limit)",
|
||||
)
|
||||
|
||||
SYSTEM_INSTRUCTION: str = Field(
|
||||
default=(
|
||||
"Ты — умный персональный AI-ассистент и главный координатор (Orchestrator), интегрированный в Telegram. "
|
||||
"Ты помогаешь пользователю управлять задачами в Jira, расписанием в Google Календаре, репозиториями в Gitea, "
|
||||
"Ты помогаешь пользователю управлять задачами в Todoist и Jira, расписанием в Google Календаре, репозиториями в Gitea, "
|
||||
"искать актуальную информацию в интернете (web_search, web_fetch_page), безопасно выполнять код и вычисления в песочнице (code_execute, sandbox_run_command), "
|
||||
"помнить важные факты и выполнять специализированные скиллы. "
|
||||
"Для быстрого и эффективного сбора данных из нескольких источников ты можешь запускать быстрых подагентов параллельно "
|
||||
"через spawn_parallel_subagents (например, один подагент проверяет Календарь, второй — задачи в Jira, третий ищет информацию в интернете). "
|
||||
"через spawn_parallel_subagents (например, один подагент проверяет Календарь, второй — задачи в Todoist/Jira, третий ищет информацию в интернете). "
|
||||
"Отвечай емко, красиво и структурированно, используя Markdown для списков, жирного шрифта и таблиц. "
|
||||
"Всегда выполняй действия через доступные инструменты (tools), если требуется проверить актуальные данные или совершить действие."
|
||||
),
|
||||
description="Default system instruction for Gemini",
|
||||
)
|
||||
|
||||
# Todoist Integration
|
||||
TODOIST_ENABLED: bool = Field(default=True, description="Enable or disable Todoist tools")
|
||||
TODOIST_API_TOKEN: Optional[SecretStr] = Field(default=None, description="Todoist Personal API Token")
|
||||
TODOIST_API_URL: str = Field(default="https://api.todoist.com/rest/v2", description="Todoist REST API v2 base URL")
|
||||
TODOIST_SYNC_URL: str = Field(default="https://api.todoist.com/sync/v9", description="Todoist Sync API v9 base URL")
|
||||
|
||||
# Jira Integration
|
||||
JIRA_ENABLED: bool = Field(default=True, description="Enable or disable Jira tools")
|
||||
JIRA_URL: Optional[str] = Field(default=None, description="Base Jira URL, e.g. https://your-domain.atlassian.net")
|
||||
@@ -160,11 +188,43 @@ class Settings(BaseSettings):
|
||||
EXTENSIONS_DIR: Path = Field(default=Path("extensions"), description="Directory with dynamic extensions")
|
||||
LOG_LEVEL: str = Field(default="INFO", description="Logging level")
|
||||
|
||||
# MCP Connectors Integration
|
||||
MCP_ENABLED: bool = Field(
|
||||
default=True,
|
||||
description="Enable or disable external MCP connectors",
|
||||
)
|
||||
MCP_CONFIG_FILE: Path = Field(
|
||||
default=Path("mcp_connectors.json"),
|
||||
description="Path to MCP connectors config file (JSON or YAML; supports `mcpServers` and `connectors` formats)",
|
||||
)
|
||||
MCP_CONNECTORS_JSON: Optional[str] = Field(
|
||||
default=None,
|
||||
description="Optional inline JSON string defining MCP connectors (supports `mcpServers` and `connectors` formats)",
|
||||
)
|
||||
MCP_REQUEST_TIMEOUT_SECONDS: int = Field(
|
||||
default=60,
|
||||
description="Default request timeout in seconds for MCP connector tool calls",
|
||||
)
|
||||
MCP_OAUTH_REDIRECT_URI: str = Field(
|
||||
default="http://127.0.0.1:18765/mcp/oauth/callback",
|
||||
description="Default OAuth 2.1 PKCE redirect URI for MCP connectors",
|
||||
)
|
||||
MCP_OAUTH_CALLBACK_ENABLED: bool = Field(
|
||||
default=False,
|
||||
description="Start a local HTTP callback listener for MCP OAuth redirects (manual code/URL paste in Telegram always works)",
|
||||
)
|
||||
MCP_ALLOW_STDIO_FROM_BOT: bool = Field(
|
||||
default=True,
|
||||
description="Allow whitelisted users to add local stdio MCP connectors from the Telegram bot interface",
|
||||
)
|
||||
|
||||
def get_active_provider_name(self) -> str:
|
||||
if self.LLM_PROVIDER == "deepseek":
|
||||
return "DeepSeek"
|
||||
if self.LLM_PROVIDER == "openai":
|
||||
return "OpenAI-Compatible"
|
||||
if self.LLM_PROVIDER == "antigravity":
|
||||
return "Antigravity"
|
||||
return "Google Gemini"
|
||||
|
||||
def get_active_model(self) -> str:
|
||||
@@ -172,6 +232,8 @@ class Settings(BaseSettings):
|
||||
return self.DEEPSEEK_MODEL
|
||||
if self.LLM_PROVIDER == "openai":
|
||||
return self.OPENAI_MODEL
|
||||
if self.LLM_PROVIDER == "antigravity":
|
||||
return self.ANTIGRAVITY_MODEL
|
||||
return self.GEMINI_MODEL
|
||||
|
||||
def get_active_subagent_model(self) -> str:
|
||||
@@ -179,6 +241,8 @@ class Settings(BaseSettings):
|
||||
return self.DEEPSEEK_SUBAGENT_MODEL
|
||||
if self.LLM_PROVIDER == "openai":
|
||||
return self.OPENAI_SUBAGENT_MODEL
|
||||
if self.LLM_PROVIDER == "antigravity":
|
||||
return self.ANTIGRAVITY_SUBAGENT_MODEL
|
||||
return self.GEMINI_SUBAGENT_MODEL
|
||||
|
||||
@field_validator("ALLOWED_TELEGRAM_USER_IDS", mode="after")
|
||||
|
||||
@@ -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
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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
|
||||
@@ -29,6 +29,12 @@ class ToolRegistry:
|
||||
logger.debug("Registered tool: %s (%s)", tool_def.name, tool_def.description)
|
||||
return tool_def
|
||||
|
||||
def register_definition(self, tool_def: ToolDefinition) -> ToolDefinition:
|
||||
"""Register a pre-constructed ToolDefinition directly (used by dynamic providers like MCP)."""
|
||||
self._tools[tool_def.name] = tool_def
|
||||
logger.debug("Registered tool definition: %s (%s)", tool_def.name, tool_def.description)
|
||||
return tool_def
|
||||
|
||||
def unregister(self, name: str) -> bool:
|
||||
if name in self._tools:
|
||||
del self._tools[name]
|
||||
@@ -45,11 +51,23 @@ class ToolRegistry:
|
||||
"""Convert all registered tools into google-genai FunctionDeclaration objects."""
|
||||
declarations: list[types.FunctionDeclaration] = []
|
||||
for tool_def in self._tools.values():
|
||||
fd = types.FunctionDeclaration(
|
||||
name=tool_def.name,
|
||||
description=tool_def.description,
|
||||
parameters=tool_def.parameters_schema,
|
||||
)
|
||||
try:
|
||||
fd = types.FunctionDeclaration(
|
||||
name=tool_def.name,
|
||||
description=tool_def.description,
|
||||
parameters=tool_def.parameters_schema,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.debug(
|
||||
"Falling back to parameters_json_schema for tool '%s': %s",
|
||||
tool_def.name,
|
||||
e,
|
||||
)
|
||||
fd = types.FunctionDeclaration(
|
||||
name=tool_def.name,
|
||||
description=tool_def.description,
|
||||
parameters_json_schema=tool_def.parameters_schema,
|
||||
)
|
||||
declarations.append(fd)
|
||||
return declarations
|
||||
|
||||
|
||||
Reference in new issue
Block a user