add mcp servers
This commit is contained in:
30 files changed
+8070
-21
No files matched your search
+41
-3
@@ -22,9 +22,9 @@ ALLOWED_TELEGRAM_USER_IDS=
|
||||
GHOST_MODE_ENABLED=true
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# 2. Выбор LLM-провайдера (Gemini, DeepSeek, OpenAI-совместимый)
|
||||
# 2. Выбор LLM-провайдера (Gemini, DeepSeek, OpenAI-совместимый, Antigravity)
|
||||
# ------------------------------------------------------------------------------
|
||||
# Выберите активного провайдера: 'gemini', 'deepseek' или 'openai'
|
||||
# Выберите активного провайдера: 'gemini', 'deepseek', 'openai' или 'antigravity'
|
||||
LLM_PROVIDER=gemini
|
||||
|
||||
# --- Вариант А: Google AI Studio (Gemini) ---
|
||||
@@ -53,6 +53,26 @@ OPENAI_BASE_URL=https://api.openai.com/v1
|
||||
OPENAI_MODEL=gpt-4o
|
||||
OPENAI_SUBAGENT_MODEL=gpt-4o-mini
|
||||
|
||||
# --- Вариант Г: Antigravity CLI (модели и лимиты вашей подписки Antigravity) ---
|
||||
# Требует установленный и авторизованный `agy` CLI (войдите один раз через `agy`).
|
||||
# Посмотреть список доступных моделей: `agy models`
|
||||
# Примеры моделей: gemini-4-neon-high, gemini-3.8-flash-high, claude-opus-5-5-high, claude-sonnet-5-5-high
|
||||
ANTIGRAVITY_CLI_PATH=agy
|
||||
ANTIGRAVITY_MODEL=gemini-4-neon-high
|
||||
ANTIGRAVITY_SUBAGENT_MODEL=gemini-3.8-flash-medium
|
||||
# Опциональное переопределение reasoning effort (low|medium|high|xhigh|max):
|
||||
# ANTIGRAVITY_EFFORT=
|
||||
# Максимальное время ожидания ответа за один ход (в секундах, 0 = без лимита):
|
||||
ANTIGRAVITY_TIMEOUT_SECONDS=300
|
||||
# Для Docker Compose (проброс agy и ~/.gemini с хоста в контейнер):
|
||||
# Путь к бинарнику agy на хосте (`which agy`, например /usr/bin/agy или /home/user/.local/bin/agy):
|
||||
# ANTIGRAVITY_BIN_HOST=/usr/bin/agy
|
||||
# Путь к директории ~/.gemini на хосте (полезно указать явно при запуске через sudo/systemd):
|
||||
# ANTIGRAVITY_HOME_HOST=/home/youruser/.gemini
|
||||
# UID/GID владельца ~/.gemini и ./data на хосте (`id -u` / `id -g`), чтобы контейнер не создавал root-файлы:
|
||||
# HOST_UID=1000
|
||||
# HOST_GID=1000
|
||||
|
||||
# Базовый системный промпт (можно оставить по умолчанию или кастомизировать)
|
||||
# SYSTEM_INSTRUCTION="Ты — умный персональный AI-ассистент..."
|
||||
|
||||
@@ -133,7 +153,25 @@ GOOGLE_OAUTH_CREDENTIALS_FILE=credentials.json
|
||||
GOOGLE_OAUTH_TOKEN_FILE=data/calendar_token.json
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# 5. Логирование и директории
|
||||
# 5. MCP Connectors (внешние MCP-серверы: HTTP, SSE, Stdio, OAuth 2.1, API Key и др.)
|
||||
# ------------------------------------------------------------------------------
|
||||
MCP_ENABLED=true
|
||||
# Путь к файлу конфигурации MCP-коннекторов (JSON или YAML; поддерживаются форматы mcpServers и connectors):
|
||||
# Скопируйте шаблон: cp mcp_connectors.json.example mcp_connectors.json
|
||||
MCP_CONFIG_FILE=mcp_connectors.json
|
||||
# Опционально: задать MCP-коннекторы прямо в .env в виде JSON-строки:
|
||||
# MCP_CONNECTORS_JSON={"mcpServers":{"docs":{"url":"https://mcp.example.com/mcp"}}}
|
||||
# Таймаут выполнения MCP-запросов (сек):
|
||||
MCP_REQUEST_TIMEOUT_SECONDS=60
|
||||
# Redirect URI для OAuth 2.1 PKCE (работает и без публичного домена через вставку ссылки/кода в Telegram):
|
||||
MCP_OAUTH_REDIRECT_URI=http://127.0.0.1:18765/mcp/oauth/callback
|
||||
# Включить локальный HTTP-сервер для автоматического перехвата OAuth callback (опционально):
|
||||
MCP_OAUTH_CALLBACK_ENABLED=false
|
||||
# Разрешить добавление локальных stdio MCP-серверов через Telegram-интерфейс (только для ALLOWED_TELEGRAM_USER_IDS):
|
||||
MCP_ALLOW_STDIO_FROM_BOT=true
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# 6. Логирование и директории
|
||||
# ------------------------------------------------------------------------------
|
||||
LOG_LEVEL=INFO
|
||||
DATA_DIR=data
|
||||
|
||||
@@ -32,6 +32,9 @@ COPY main.py run.py ./
|
||||
# Finalize project sync
|
||||
RUN uv sync --frozen --no-dev
|
||||
|
||||
# Writable home directory for non-root container UID (used for mounted ~/.gemini)
|
||||
RUN mkdir -p /homeagent && chmod 0777 /homeagent
|
||||
|
||||
# Use the virtual environment created by uv
|
||||
ENV PATH="/app/.venv/bin:$PATH"
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
- 🎟️ **Интеграция с Jira**: Полноценная поддержка Jira Cloud v3 enhanced search (`POST /rest/api/3/search/jql`) и Server/Data Center, просмотр задач с десериализацией ADF, создание тикетов, добавление комментариев, смена статусов, редактирование любых стандартных и кастомных полей (`jira_update_issue`), получение схемы полей (`jira_get_editable_fields`), поиск пользователей (`jira_search_users`) и фильтр задач по `statusCategory`.
|
||||
|
||||
- 📅 **Интеграция с Google Calendar**: Поддержка **Service Account** и **OAuth 2.0**, одновременный запрос расписания сразу со **всех доступных календарей** с разметкой источников, создание и удаление событий.
|
||||
- 🔌 **MCP Коннекторы (Model Context Protocol)**: Подключение любых внешних MCP-серверов (**Streamable HTTP**, **Legacy SSE**, **Stdio** с автоопределением) прямо из Telegram (`/mcp`, интерактивный мастер, импорт JSON `mcpServers`) или из конфига (`mcp_connectors.json` / `.env`). Поддержка множества методов авторизации: `none`, `bearer`, `api_key` (header/query), `basic`, `headers`, `oauth2_pkce` (с авто-discovery RFC 9728/8414 и Dynamic Client Registration RFC 7591), `oauth2_client_credentials`, `oauth2_device`, `oauth2_refresh_token`, а также `${ENV_VAR}` подстановок. Инструменты автоматически доступны всем провайдерам (Gemini, DeepSeek, OpenAI, Antigravity) и подагентам.
|
||||
- 🎯 **Система скиллов (Skills)**: Готовые сценарии (утренняя сводка, дейли стендап, триаж Jira, планировщик недели), запускаемые по триггер-фразам или командам (`/skills`, `/briefing`, `/standup`).
|
||||
- 🔌 **Простая разработка расширений**: Добавление нового инструмента за 2 минуты через декоратор `@tool` с авто-генерацией схемы для Gemini.
|
||||
|
||||
@@ -112,8 +113,10 @@ homeagent/
|
||||
| Команда | Описание |
|
||||
|---------|----------|
|
||||
| `/start` или `/help` | Статус бота, информация о топике, количество инструментов и скиллов |
|
||||
| `/mcp` | Интерактивное управление MCP коннекторами (мастер, OAuth, импорт JSON, статус, инструменты) |
|
||||
| `/skills` | Список доступных скиллов с их триггерами и описанием |
|
||||
| `/skill <название>` | Принудительный запуск конкретного скилла |
|
||||
| `/model [slug]` | Просмотр текущей модели и переключение модели на лету (для Antigravity) |
|
||||
| `/memory` | Просмотр фактов, сохраненных в глобальной памяти |
|
||||
| `/reset` | Очистка истории диалога в текущем топике форума |
|
||||
|
||||
|
||||
@@ -6,11 +6,13 @@ services:
|
||||
container_name: homeagent
|
||||
restart: unless-stopped
|
||||
init: true
|
||||
user: "${HOST_UID:-1000}:${HOST_GID:-1000}"
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
# Application path inside the container; this must match the mount target.
|
||||
DATA_DIR: /app/data
|
||||
HOME: /homeagent
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
volumes:
|
||||
@@ -19,3 +21,7 @@ services:
|
||||
- ./skills:/app/skills:ro
|
||||
- ./extensions:/app/extensions:ro
|
||||
- ./gcal.json:/app/gcal.json:ro
|
||||
# Host Antigravity CLI (`agy`) binary and auth/state directory (~/.gemini).
|
||||
# Override in .env if `agy` is in another path (e.g. ~/.local/bin/agy) or under sudo/systemd.
|
||||
- "${ANTIGRAVITY_BIN_HOST:-/usr/bin/agy}:/usr/local/bin/agy:ro"
|
||||
- "${ANTIGRAVITY_HOME_HOST:-${HOME}/.gemini}:/homeagent/.gemini"
|
||||
@@ -0,0 +1,121 @@
|
||||
# 🔌 MCP Connectors Guide (HomeAgent)
|
||||
|
||||
HomeAgent поддерживает подключение внешних **Model Context Protocol (MCP)** серверов. Все инструменты подключённых серверов автоматически регистрируются в `ToolRegistry` и становятся доступны **всем LLM-провайдерам** (`gemini`, `deepseek`, `openai`, `antigravity`) и **подагентам** (`spawn_subagent` / `spawn_parallel_subagents`).
|
||||
|
||||
---
|
||||
|
||||
## 1. Поддерживаемые транспорты
|
||||
|
||||
| Транспорт | Описание |
|
||||
|-----------|----------|
|
||||
| `auto` (по умолчанию для URL) | Автоматически определяет **Streamable HTTP** (`2025-03-26`) или **Legacy SSE** (`2024-11-05`) с прозрачным фолбэком |
|
||||
| `streamable_http` | Современный MCP Streamable HTTP (`POST`, JSON + SSE ответы, `Mcp-Session-Id`) |
|
||||
| `sse` | Классический MCP HTTP+SSE (`GET` поток + `event: endpoint` + `POST`) |
|
||||
| `stdio` | Локальные процессы (`npx`, `uvx`, `python` и др.) с передачей `env` переменных |
|
||||
|
||||
---
|
||||
|
||||
## 2. Поддерживаемые методы авторизации
|
||||
|
||||
| Метод (`auth.type`) | Описание и параметры |
|
||||
|---------------------|----------------------|
|
||||
| `none` | Без авторизации (публичные или локальные серверы) |
|
||||
| `bearer` | `Authorization: Bearer <token>` (можно изменить `token_prefix`, например `Token`) |
|
||||
| `api_key` | API-ключ в заголовке (`api_key_in: "header"`, `header_name`, `api_key_prefix`) или в query-параметре (`api_key_in: "query"`, `query_param`) |
|
||||
| `basic` | HTTP Basic Auth (`username`, `password`) |
|
||||
| `headers` | Произвольный набор кастомных HTTP-заголовков (`headers: {"X-Tenant": "...", ...}`) |
|
||||
| `oauth2_pkce` | **OAuth 2.1 Authorization Code + PKCE (S256)** с автоматическим обнаружением **RFC 9728** (`/.well-known/oauth-protected-resource`) + **RFC 8414** (`/.well-known/oauth-authorization-server`) + **Dynamic Client Registration (RFC 7591)** и автообновлением `refresh_token` |
|
||||
| `oauth2_client_credentials` | **OAuth 2.0 Client Credentials** (M2M) с авто-кэшированием и обновлением токена (`token_url` опционален при auto-discovery, `client_id`, `client_secret`, `scope`, `audience`, `client_auth_method`: `post`/`basic`) |
|
||||
| `oauth2_device` | **OAuth 2.0 Device Authorization Grant (RFC 8628)** — бот присылает ссылку и код, а затем автоматически подхватывает токен в фоне |
|
||||
| `oauth2_refresh_token` | Обновление доступа по заранее полученному `refresh_token` (`token_url`, `client_id`, опц. `client_secret`) |
|
||||
| `env` (для `stdio`) | Передача ключей через переменные окружения процесса |
|
||||
|
||||
> 💡 Во всех строковых полях конфигурации поддерживается подстановка переменных окружения `${VAR_NAME}` и `${VAR_NAME:-default}` (из `.env` или окружения системы).
|
||||
|
||||
---
|
||||
|
||||
## 3. Подключение через Telegram-бота
|
||||
|
||||
### Интерактивное меню и мастер
|
||||
Отправьте `/mcp` в Telegram:
|
||||
- Просмотр списка коннекторов, их статуса (`🟢`/`🟡`/`🔴`), транспорта и количества инструментов
|
||||
- **➕ Добавить коннектор** — пошаговый мастер (Имя → Транспорт → URL/Команда → Метод авторизации → Учётные данные → Автоподключение)
|
||||
- **📋 Импорт JSON** — вставьте готовый блок `{"mcpServers": {...}}` из Cursor / Claude Desktop / Antigravity
|
||||
- **🔐 OAuth авторизация** — для OAuth 2.1 PKCE бот выдаст ссылку, после подтверждения просто вставьте итоговую ссылку редиректа (или `code`) обратно в чат
|
||||
|
||||
### Быстрые команды
|
||||
```text
|
||||
/mcp # Меню и список
|
||||
/mcp add # Интерактивный мастер
|
||||
/mcp add docs https://mcp.example.com/mcp # Без авторизации
|
||||
/mcp add github https://api.githubcopilot.com/mcp/ bearer ghp_xxx
|
||||
/mcp add api https://mcp.example.com/mcp api_key X-API-Key=secret
|
||||
/mcp add api2 https://mcp.example.com/mcp api_key_query key=secret
|
||||
/mcp add srv https://mcp.example.com/mcp basic user:pass
|
||||
/mcp add custom https://mcp.example.com/mcp headers X-Tenant=acme;X-Key=123
|
||||
/mcp add linear https://mcp.linear.app/mcp oauth2_pkce
|
||||
/mcp add fs stdio npx -y @modelcontextprotocol/server-filesystem /tmp
|
||||
/mcp import {"mcpServers":{"docs":{"url":"https://mcp.example.com/mcp"}}}
|
||||
/mcp auth <имя> # Запустить OAuth
|
||||
/mcp code <имя> <код_или_redirect_url> # Завершить OAuth PKCE
|
||||
/mcp tools <имя> # Список инструментов
|
||||
/mcp connect <имя> / /mcp disconnect <имя>
|
||||
/mcp enable <имя> / /mcp disable <имя>
|
||||
/mcp remove <имя>
|
||||
/mcp reload
|
||||
```
|
||||
|
||||
> Коннекторы, добавленные через бота, сохраняются в `data/mcp_connectors.json` (chmod `0600`), а OAuth-токены — в `data/mcp_tokens.json` (chmod `0600`). В Docker-развёртывании оба файла автоматически сохраняются в volume `./data`.
|
||||
|
||||
---
|
||||
|
||||
## 4. Подключение через конфиг
|
||||
|
||||
### Вариант А: Файл `mcp_connectors.json` (или `.yaml` / `.yml`)
|
||||
Укажите в `.env`:
|
||||
```env
|
||||
MCP_ENABLED=true
|
||||
MCP_CONFIG_FILE=mcp_connectors.json
|
||||
```
|
||||
|
||||
Поддерживаются **оба формата** — стандартный `mcpServers` (совместимый с Claude Desktop / Cursor / Antigravity) и расширенный `connectors`:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"github": {
|
||||
"url": "https://api.githubcopilot.com/mcp/",
|
||||
"headers": {
|
||||
"Authorization": "Bearer ${GITHUB_MCP_TOKEN}"
|
||||
}
|
||||
},
|
||||
"linear": {
|
||||
"url": "https://mcp.linear.app/mcp",
|
||||
"auth": {
|
||||
"type": "oauth2_pkce",
|
||||
"scope": "read write"
|
||||
}
|
||||
},
|
||||
"filesystem": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
|
||||
"env": {
|
||||
"NODE_ENV": "production"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Вариант Б: Inline JSON в `.env`
|
||||
```env
|
||||
MCP_CONNECTORS_JSON={"mcpServers":{"docs":{"url":"https://mcp.example.com/mcp"}}}
|
||||
```
|
||||
|
||||
### Фильтрация инструментов и префиксы
|
||||
Для каждого коннектора можно задать:
|
||||
- `tool_prefix`: кастомный префикс имён инструментов (по умолчанию `mcp_<name>`)
|
||||
- `include_tools`: белый список имён удалённых инструментов
|
||||
- `exclude_tools`: чёрный список имён удалённых инструментов
|
||||
- `timeout_seconds`: индивидуальный таймаут вызовов (5–600 сек)
|
||||
- `verify_ssl`: проверка TLS-сертификата (по умолчанию `true`)
|
||||
@@ -0,0 +1 @@
|
||||
"""Todoist integration extension for HomeAgent."""
|
||||
@@ -0,0 +1,559 @@
|
||||
"""Asynchronous Todoist REST API v2 and Sync API v9 Client."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any, Optional
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
|
||||
from homeagent.config import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TodoistClient:
|
||||
"""Async Client for Todoist REST API v2 and Sync API v9."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
token: Optional[str] = None,
|
||||
api_url: Optional[str] = None,
|
||||
sync_url: Optional[str] = None,
|
||||
) -> None:
|
||||
settings = get_settings()
|
||||
self.token = (
|
||||
token
|
||||
or (settings.TODOIST_API_TOKEN.get_secret_value() if settings.TODOIST_API_TOKEN else "")
|
||||
)
|
||||
self.api_url = (api_url or settings.TODOIST_API_URL or "https://api.todoist.com/rest/v2").rstrip("/")
|
||||
self.sync_url = (sync_url or settings.TODOIST_SYNC_URL or "https://api.todoist.com/sync/v9").rstrip("/")
|
||||
|
||||
def is_configured(self) -> bool:
|
||||
return bool(self.token)
|
||||
|
||||
def _get_headers(self, request_id: Optional[str] = None) -> dict[str, str]:
|
||||
headers = {
|
||||
"Accept": "application/json",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
if self.token:
|
||||
headers["Authorization"] = f"Bearer {self.token}"
|
||||
if request_id:
|
||||
headers["X-Request-Id"] = request_id
|
||||
return headers
|
||||
|
||||
async def _request(
|
||||
self,
|
||||
method: str,
|
||||
endpoint: str,
|
||||
params: Optional[dict[str, Any]] = None,
|
||||
json_data: Optional[dict[str, Any]] = None,
|
||||
use_sync: bool = False,
|
||||
) -> Any:
|
||||
base = self.sync_url if use_sync else self.api_url
|
||||
url = f"{base}/{endpoint.lstrip('/')}"
|
||||
req_id = str(uuid.uuid4()) if method.upper() in ("POST", "PUT", "DELETE") else None
|
||||
headers = self._get_headers(request_id=req_id)
|
||||
|
||||
async with httpx.AsyncClient(timeout=25.0) as client:
|
||||
response = await client.request(
|
||||
method=method,
|
||||
url=url,
|
||||
headers=headers,
|
||||
params=params,
|
||||
json=json_data,
|
||||
)
|
||||
|
||||
if response.status_code == 204 or not response.content:
|
||||
return None
|
||||
|
||||
if response.is_error:
|
||||
error_body = response.text
|
||||
logger.error("Todoist API error %d on %s: %s", response.status_code, url, error_body)
|
||||
raise RuntimeError(f"Todoist API error ({response.status_code}): {error_body}")
|
||||
|
||||
return response.json()
|
||||
|
||||
async def _sync_command(
|
||||
self,
|
||||
cmd_type: str,
|
||||
args: dict[str, Any],
|
||||
temp_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Execute a Sync API v9 command (e.g. item_move)."""
|
||||
cmd_uuid = str(uuid.uuid4())
|
||||
cmd: dict[str, Any] = {
|
||||
"type": cmd_type,
|
||||
"uuid": cmd_uuid,
|
||||
"args": args,
|
||||
}
|
||||
if temp_id:
|
||||
cmd["temp_id"] = temp_id
|
||||
|
||||
data = await self._request(
|
||||
"POST",
|
||||
"sync",
|
||||
json_data={"commands": [cmd]},
|
||||
use_sync=True,
|
||||
)
|
||||
sync_status = (data or {}).get("sync_status", {}).get(cmd_uuid)
|
||||
if isinstance(sync_status, dict) and sync_status.get("error"):
|
||||
err_msg = sync_status.get("error", "Unknown sync error")
|
||||
err_code = sync_status.get("error_code", "")
|
||||
raise RuntimeError(f"Todoist Sync error ({err_code}): {err_msg}")
|
||||
return data or {}
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Projects
|
||||
# -------------------------------------------------------------------------
|
||||
async def list_projects(self) -> list[dict[str, Any]]:
|
||||
"""Get all user projects."""
|
||||
res = await self._request("GET", "projects")
|
||||
return res if isinstance(res, list) else []
|
||||
|
||||
async def get_project(self, project_id: str) -> dict[str, Any]:
|
||||
"""Get a project by ID."""
|
||||
return await self._request("GET", f"projects/{project_id}")
|
||||
|
||||
async def create_project(
|
||||
self,
|
||||
name: str,
|
||||
parent_id: Optional[str] = None,
|
||||
color: Optional[str] = None,
|
||||
is_favorite: Optional[bool] = None,
|
||||
view_style: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Create a new project."""
|
||||
payload: dict[str, Any] = {"name": name}
|
||||
if parent_id:
|
||||
payload["parent_id"] = parent_id
|
||||
if color:
|
||||
payload["color"] = color
|
||||
if is_favorite is not None:
|
||||
payload["is_favorite"] = is_favorite
|
||||
if view_style:
|
||||
payload["view_style"] = view_style
|
||||
return await self._request("POST", "projects", json_data=payload)
|
||||
|
||||
async def update_project(
|
||||
self,
|
||||
project_id: str,
|
||||
name: Optional[str] = None,
|
||||
color: Optional[str] = None,
|
||||
is_favorite: Optional[bool] = None,
|
||||
view_style: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Update an existing project."""
|
||||
payload: dict[str, Any] = {}
|
||||
if name is not None:
|
||||
payload["name"] = name
|
||||
if color is not None:
|
||||
payload["color"] = color
|
||||
if is_favorite is not None:
|
||||
payload["is_favorite"] = is_favorite
|
||||
if view_style is not None:
|
||||
payload["view_style"] = view_style
|
||||
return await self._request("POST", f"projects/{project_id}", json_data=payload)
|
||||
|
||||
async def delete_project(self, project_id: str) -> None:
|
||||
"""Delete a project."""
|
||||
await self._request("DELETE", f"projects/{project_id}")
|
||||
|
||||
async def get_project_collaborators(self, project_id: str) -> list[dict[str, Any]]:
|
||||
"""Get all collaborators for a shared project."""
|
||||
res = await self._request("GET", f"projects/{project_id}/collaborators")
|
||||
return res if isinstance(res, list) else []
|
||||
|
||||
async def resolve_project_id(self, project_name_or_id: str) -> Optional[str]:
|
||||
"""Resolve a project name or ID to its actual ID."""
|
||||
clean = str(project_name_or_id).strip()
|
||||
if not clean:
|
||||
return None
|
||||
projects = await self.list_projects()
|
||||
# Exact ID match
|
||||
for p in projects:
|
||||
if str(p.get("id")) == clean:
|
||||
return str(p["id"])
|
||||
# Exact case-insensitive name match
|
||||
clean_lower = clean.lower()
|
||||
for p in projects:
|
||||
if str(p.get("name", "")).strip().lower() == clean_lower:
|
||||
return str(p["id"])
|
||||
# Substring match
|
||||
for p in projects:
|
||||
if clean_lower in str(p.get("name", "")).strip().lower():
|
||||
return str(p["id"])
|
||||
return None
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Sections
|
||||
# -------------------------------------------------------------------------
|
||||
async def list_sections(self, project_id: Optional[str] = None) -> list[dict[str, Any]]:
|
||||
"""Get sections (optionally filtered by project_id)."""
|
||||
params: dict[str, Any] = {}
|
||||
if project_id:
|
||||
params["project_id"] = project_id
|
||||
res = await self._request("GET", "sections", params=params or None)
|
||||
return res if isinstance(res, list) else []
|
||||
|
||||
async def get_section(self, section_id: str) -> dict[str, Any]:
|
||||
"""Get a single section by ID."""
|
||||
return await self._request("GET", f"sections/{section_id}")
|
||||
|
||||
async def create_section(
|
||||
self,
|
||||
name: str,
|
||||
project_id: str,
|
||||
order: Optional[int] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Create a new section in a project."""
|
||||
payload: dict[str, Any] = {"name": name, "project_id": project_id}
|
||||
if order is not None:
|
||||
payload["order"] = order
|
||||
return await self._request("POST", "sections", json_data=payload)
|
||||
|
||||
async def update_section(self, section_id: str, name: str) -> dict[str, Any]:
|
||||
"""Rename a section."""
|
||||
return await self._request("POST", f"sections/{section_id}", json_data={"name": name})
|
||||
|
||||
async def delete_section(self, section_id: str) -> None:
|
||||
"""Delete a section and all its tasks."""
|
||||
await self._request("DELETE", f"sections/{section_id}")
|
||||
|
||||
async def resolve_section_id(
|
||||
self,
|
||||
section_name_or_id: str,
|
||||
project_id: Optional[str] = None,
|
||||
) -> Optional[str]:
|
||||
"""Resolve a section name or ID to its actual ID."""
|
||||
clean = str(section_name_or_id).strip()
|
||||
if not clean:
|
||||
return None
|
||||
sections = await self.list_sections(project_id=project_id)
|
||||
for s in sections:
|
||||
if str(s.get("id")) == clean:
|
||||
return str(s["id"])
|
||||
clean_lower = clean.lower()
|
||||
for s in sections:
|
||||
if str(s.get("name", "")).strip().lower() == clean_lower:
|
||||
return str(s["id"])
|
||||
for s in sections:
|
||||
if clean_lower in str(s.get("name", "")).strip().lower():
|
||||
return str(s["id"])
|
||||
return None
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Tasks
|
||||
# -------------------------------------------------------------------------
|
||||
async def list_tasks(
|
||||
self,
|
||||
project_id: Optional[str] = None,
|
||||
section_id: Optional[str] = None,
|
||||
label: Optional[str] = None,
|
||||
filter_query: Optional[str] = None,
|
||||
lang: str = "ru",
|
||||
ids: Optional[list[str]] = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Get active tasks across the account or with filters."""
|
||||
params: dict[str, Any] = {}
|
||||
if project_id:
|
||||
params["project_id"] = project_id
|
||||
if section_id:
|
||||
params["section_id"] = section_id
|
||||
if label:
|
||||
params["label"] = label
|
||||
if filter_query:
|
||||
params["filter"] = filter_query
|
||||
params["lang"] = lang
|
||||
if ids:
|
||||
params["ids"] = ",".join(str(i) for i in ids)
|
||||
|
||||
res = await self._request("GET", "tasks", params=params or None)
|
||||
return res if isinstance(res, list) else []
|
||||
|
||||
async def get_task(self, task_id: str) -> dict[str, Any]:
|
||||
"""Get an active task by ID."""
|
||||
return await self._request("GET", f"tasks/{task_id}")
|
||||
|
||||
async def create_task(
|
||||
self,
|
||||
content: str,
|
||||
description: Optional[str] = None,
|
||||
project_id: Optional[str] = None,
|
||||
section_id: Optional[str] = None,
|
||||
parent_id: Optional[str] = None,
|
||||
order: Optional[int] = None,
|
||||
labels: Optional[list[str]] = None,
|
||||
priority: Optional[int] = None,
|
||||
due_string: Optional[str] = None,
|
||||
due_date: Optional[str] = None,
|
||||
due_datetime: Optional[str] = None,
|
||||
due_lang: str = "ru",
|
||||
assignee_id: Optional[str] = None,
|
||||
duration: Optional[int] = None,
|
||||
duration_unit: Optional[str] = None,
|
||||
deadline_date: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Create a new task."""
|
||||
payload: dict[str, Any] = {"content": content}
|
||||
if description is not None:
|
||||
payload["description"] = description
|
||||
if project_id:
|
||||
payload["project_id"] = project_id
|
||||
if section_id:
|
||||
payload["section_id"] = section_id
|
||||
if parent_id:
|
||||
payload["parent_id"] = parent_id
|
||||
if order is not None:
|
||||
payload["order"] = order
|
||||
if labels is not None:
|
||||
payload["labels"] = labels
|
||||
if priority is not None:
|
||||
payload["priority"] = priority
|
||||
if due_datetime:
|
||||
payload["due_datetime"] = due_datetime
|
||||
elif due_date:
|
||||
payload["due_date"] = due_date
|
||||
elif due_string:
|
||||
payload["due_string"] = due_string
|
||||
payload["due_lang"] = due_lang
|
||||
if assignee_id:
|
||||
payload["assignee_id"] = assignee_id
|
||||
if duration is not None and duration_unit:
|
||||
payload["duration"] = duration
|
||||
payload["duration_unit"] = duration_unit
|
||||
if deadline_date:
|
||||
payload["deadline_date"] = deadline_date
|
||||
|
||||
return await self._request("POST", "tasks", json_data=payload)
|
||||
|
||||
async def quick_add_task(
|
||||
self,
|
||||
text: str,
|
||||
note: Optional[str] = None,
|
||||
reminder: Optional[str] = None,
|
||||
auto_reminder: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""Quick add a task using Todoist natural language parsing (Sync API v9 quick/add)."""
|
||||
payload: dict[str, Any] = {"text": text}
|
||||
if note:
|
||||
payload["note"] = note
|
||||
if reminder:
|
||||
payload["reminder"] = reminder
|
||||
if auto_reminder:
|
||||
payload["auto_reminder"] = True
|
||||
return await self._request("POST", "quick/add", json_data=payload, use_sync=True)
|
||||
|
||||
async def update_task(
|
||||
self,
|
||||
task_id: str,
|
||||
content: Optional[str] = None,
|
||||
description: Optional[str] = None,
|
||||
labels: Optional[list[str]] = None,
|
||||
priority: Optional[int] = None,
|
||||
due_string: Optional[str] = None,
|
||||
due_date: Optional[str] = None,
|
||||
due_datetime: Optional[str] = None,
|
||||
due_lang: str = "ru",
|
||||
assignee_id: Optional[str] = None,
|
||||
duration: Optional[int] = None,
|
||||
duration_unit: Optional[str] = None,
|
||||
deadline_date: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Update an existing task's properties via REST API v2."""
|
||||
payload: dict[str, Any] = {}
|
||||
if content is not None:
|
||||
payload["content"] = content
|
||||
if description is not None:
|
||||
payload["description"] = description
|
||||
if labels is not None:
|
||||
payload["labels"] = labels
|
||||
if priority is not None:
|
||||
payload["priority"] = priority
|
||||
if due_datetime:
|
||||
payload["due_datetime"] = due_datetime
|
||||
elif due_date:
|
||||
payload["due_date"] = due_date
|
||||
elif due_string is not None:
|
||||
payload["due_string"] = due_string
|
||||
payload["due_lang"] = due_lang
|
||||
if assignee_id is not None:
|
||||
payload["assignee_id"] = assignee_id if assignee_id else None
|
||||
if duration is not None and duration_unit:
|
||||
payload["duration"] = duration
|
||||
payload["duration_unit"] = duration_unit
|
||||
if deadline_date is not None:
|
||||
payload["deadline_date"] = deadline_date if deadline_date else None
|
||||
|
||||
return await self._request("POST", f"tasks/{task_id}", json_data=payload)
|
||||
|
||||
async def move_task(
|
||||
self,
|
||||
task_id: str,
|
||||
project_id: Optional[str] = None,
|
||||
section_id: Optional[str] = None,
|
||||
parent_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Move a task to another project, section, or parent task via Sync API v9 item_move."""
|
||||
args: dict[str, Any] = {"id": str(task_id)}
|
||||
# Todoist item_move accepts exactly one destination parameter: parent_id, section_id, or project_id
|
||||
if parent_id:
|
||||
args["parent_id"] = str(parent_id)
|
||||
elif section_id:
|
||||
args["section_id"] = str(section_id)
|
||||
elif project_id:
|
||||
args["project_id"] = str(project_id)
|
||||
else:
|
||||
raise ValueError("One of project_id, section_id, or parent_id must be specified to move a task.")
|
||||
return await self._sync_command("item_move", args)
|
||||
|
||||
async def close_task(self, task_id: str) -> None:
|
||||
"""Close (complete) a task."""
|
||||
await self._request("POST", f"tasks/{task_id}/close")
|
||||
|
||||
async def reopen_task(self, task_id: str) -> None:
|
||||
"""Reopen a completed task."""
|
||||
await self._request("POST", f"tasks/{task_id}/reopen")
|
||||
|
||||
async def delete_task(self, task_id: str) -> None:
|
||||
"""Delete a task permanently."""
|
||||
await self._request("DELETE", f"tasks/{task_id}")
|
||||
|
||||
async def list_completed_tasks(
|
||||
self,
|
||||
project_id: Optional[str] = None,
|
||||
section_id: Optional[str] = None,
|
||||
since: Optional[str] = None,
|
||||
until: Optional[str] = None,
|
||||
limit: int = 30,
|
||||
offset: int = 0,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""List completed tasks from Todoist Sync API v9."""
|
||||
params: dict[str, Any] = {"limit": limit, "offset": offset}
|
||||
if project_id:
|
||||
params["project_id"] = project_id
|
||||
if section_id:
|
||||
params["section_id"] = section_id
|
||||
if since:
|
||||
params["since"] = since
|
||||
if until:
|
||||
params["until"] = until
|
||||
|
||||
data = await self._request("GET", "completed/get_all", params=params, use_sync=True)
|
||||
if isinstance(data, dict):
|
||||
return data.get("items", [])
|
||||
return []
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Labels
|
||||
# -------------------------------------------------------------------------
|
||||
async def list_labels(self) -> list[dict[str, Any]]:
|
||||
"""Get all personal labels."""
|
||||
res = await self._request("GET", "labels")
|
||||
return res if isinstance(res, list) else []
|
||||
|
||||
async def get_label(self, label_id: str) -> dict[str, Any]:
|
||||
"""Get a personal label by ID."""
|
||||
return await self._request("GET", f"labels/{label_id}")
|
||||
|
||||
async def create_label(
|
||||
self,
|
||||
name: str,
|
||||
color: Optional[str] = None,
|
||||
order: Optional[int] = None,
|
||||
is_favorite: Optional[bool] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Create a new personal label."""
|
||||
payload: dict[str, Any] = {"name": name}
|
||||
if color:
|
||||
payload["color"] = color
|
||||
if order is not None:
|
||||
payload["order"] = order
|
||||
if is_favorite is not None:
|
||||
payload["is_favorite"] = is_favorite
|
||||
return await self._request("POST", "labels", json_data=payload)
|
||||
|
||||
async def update_label(
|
||||
self,
|
||||
label_id: str,
|
||||
name: Optional[str] = None,
|
||||
color: Optional[str] = None,
|
||||
order: Optional[int] = None,
|
||||
is_favorite: Optional[bool] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Update a personal label."""
|
||||
payload: dict[str, Any] = {}
|
||||
if name is not None:
|
||||
payload["name"] = name
|
||||
if color is not None:
|
||||
payload["color"] = color
|
||||
if order is not None:
|
||||
payload["order"] = order
|
||||
if is_favorite is not None:
|
||||
payload["is_favorite"] = is_favorite
|
||||
return await self._request("POST", f"labels/{label_id}", json_data=payload)
|
||||
|
||||
async def delete_label(self, label_id: str) -> None:
|
||||
"""Delete a personal label."""
|
||||
await self._request("DELETE", f"labels/{label_id}")
|
||||
|
||||
async def list_shared_labels(self, omit_personal: bool = False) -> list[str]:
|
||||
"""List all shared labels across active tasks."""
|
||||
res = await self._request("GET", "labels/shared", params={"omit_personal": omit_personal})
|
||||
return res if isinstance(res, list) else []
|
||||
|
||||
async def rename_shared_label(self, name: str, new_name: str) -> None:
|
||||
"""Rename a shared label across all tasks."""
|
||||
await self._request("POST", "labels/shared/rename", json_data={"name": name, "new_name": new_name})
|
||||
|
||||
async def remove_shared_label(self, name: str) -> None:
|
||||
"""Remove a shared label from all active tasks."""
|
||||
await self._request("POST", "labels/shared/remove", json_data={"name": name})
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Comments
|
||||
# -------------------------------------------------------------------------
|
||||
async def list_comments(
|
||||
self,
|
||||
task_id: Optional[str] = None,
|
||||
project_id: Optional[str] = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Get comments for a task or project."""
|
||||
if not task_id and not project_id:
|
||||
raise ValueError("Either task_id or project_id is required to list comments.")
|
||||
params: dict[str, Any] = {}
|
||||
if task_id:
|
||||
params["task_id"] = task_id
|
||||
elif project_id:
|
||||
params["project_id"] = project_id
|
||||
res = await self._request("GET", "comments", params=params)
|
||||
return res if isinstance(res, list) else []
|
||||
|
||||
async def get_comment(self, comment_id: str) -> dict[str, Any]:
|
||||
"""Get a single comment by ID."""
|
||||
return await self._request("GET", f"comments/{comment_id}")
|
||||
|
||||
async def create_comment(
|
||||
self,
|
||||
content: str,
|
||||
task_id: Optional[str] = None,
|
||||
project_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Create a comment on a task or project."""
|
||||
if not task_id and not project_id:
|
||||
raise ValueError("Either task_id or project_id is required to create a comment.")
|
||||
payload: dict[str, Any] = {"content": content}
|
||||
if task_id:
|
||||
payload["task_id"] = task_id
|
||||
elif project_id:
|
||||
payload["project_id"] = project_id
|
||||
return await self._request("POST", "comments", json_data=payload)
|
||||
|
||||
async def update_comment(self, comment_id: str, content: str) -> dict[str, Any]:
|
||||
"""Update a comment."""
|
||||
return await self._request("POST", f"comments/{comment_id}", json_data={"content": content})
|
||||
|
||||
async def delete_comment(self, comment_id: str) -> None:
|
||||
"""Delete a comment."""
|
||||
await self._request("DELETE", f"comments/{comment_id}")
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"connectors": {
|
||||
"example_bearer": {
|
||||
"transport": "auto",
|
||||
"url": "https://api.githubcopilot.com/mcp/",
|
||||
"enabled": false,
|
||||
"auth": {
|
||||
"type": "bearer",
|
||||
"token": "${GITHUB_MCP_TOKEN}"
|
||||
}
|
||||
},
|
||||
"example_api_key_header": {
|
||||
"transport": "streamable_http",
|
||||
"url": "https://mcp.example.com/mcp",
|
||||
"enabled": false,
|
||||
"auth": {
|
||||
"type": "api_key",
|
||||
"api_key": "${EXAMPLE_API_KEY}",
|
||||
"api_key_in": "header",
|
||||
"header_name": "X-API-Key"
|
||||
}
|
||||
},
|
||||
"example_oauth_pkce": {
|
||||
"transport": "auto",
|
||||
"url": "https://mcp.linear.app/mcp",
|
||||
"enabled": false,
|
||||
"auth": {
|
||||
"type": "oauth2_pkce",
|
||||
"scope": "read write"
|
||||
}
|
||||
},
|
||||
"example_oauth_client_credentials": {
|
||||
"transport": "streamable_http",
|
||||
"url": "https://mcp.internal.example.com/mcp",
|
||||
"enabled": false,
|
||||
"auth": {
|
||||
"type": "oauth2_client_credentials",
|
||||
"token_url": "https://auth.internal.example.com/oauth/token",
|
||||
"client_id": "${MCP_CLIENT_ID}",
|
||||
"client_secret": "${MCP_CLIENT_SECRET}",
|
||||
"scope": "mcp:tools"
|
||||
}
|
||||
},
|
||||
"example_stdio_filesystem": {
|
||||
"transport": "stdio",
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
|
||||
"enabled": false,
|
||||
"env": {
|
||||
"NODE_ENV": "production"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,14 @@ def check_configuration() -> None:
|
||||
oa_key = settings.OPENAI_API_KEY
|
||||
print(f"OpenAI API Key: {'[SET]' if oa_key and oa_key.get_secret_value() else '[MISSING ❌]'}")
|
||||
print(f"OpenAI Base URL: {settings.OPENAI_BASE_URL}")
|
||||
elif settings.LLM_PROVIDER == "antigravity":
|
||||
from homeagent.agent.antigravity import _resolve_cli_binary
|
||||
|
||||
cli_resolved = _resolve_cli_binary(settings.ANTIGRAVITY_CLI_PATH)
|
||||
print(f"Antigravity CLI ({settings.ANTIGRAVITY_CLI_PATH}): {f'[FOUND: {cli_resolved}]' if cli_resolved else '[MISSING ❌]'}")
|
||||
if settings.ANTIGRAVITY_EFFORT:
|
||||
print(f"Antigravity Effort: {settings.ANTIGRAVITY_EFFORT}")
|
||||
print(f"Antigravity Timeout: {settings.ANTIGRAVITY_TIMEOUT_SECONDS}s")
|
||||
else:
|
||||
print(f"Gemini API Key: {'[SET]' if settings.GEMINI_API_KEY.get_secret_value() else '[MISSING ❌]'}")
|
||||
|
||||
@@ -47,10 +55,20 @@ def check_configuration() -> None:
|
||||
print(f"Gitea Enabled: {settings.GITEA_ENABLED} (URL: {settings.GITEA_URL})")
|
||||
print(f"Jira Enabled: {settings.JIRA_ENABLED} (URL: {settings.JIRA_URL or 'not set'})")
|
||||
print(f"Google Calendar Enabled: {settings.GOOGLE_CALENDAR_ENABLED} (Auth type: {settings.GOOGLE_AUTH_TYPE})")
|
||||
print(f"MCP Connectors Enabled: {settings.MCP_ENABLED} (Config: {settings.MCP_CONFIG_FILE})")
|
||||
|
||||
app = TelegramAgentApp(settings=settings)
|
||||
tools = app.registry.list_tools()
|
||||
skills = app.skill_manager.list_skills()
|
||||
mcp_connectors = app.mcp_manager.list_connectors()
|
||||
|
||||
print(f"\n🔌 Configured MCP Connectors ({len(mcp_connectors)}):")
|
||||
for c in mcp_connectors:
|
||||
target = c.config.url or f"{c.config.command} {' '.join(c.config.args)}".strip()
|
||||
print(
|
||||
f" - {c.config.name} [{c.config.transport}] auth={c.config.auth.type} "
|
||||
f"enabled={c.config.enabled} source={c.config.source} target={target}"
|
||||
)
|
||||
|
||||
print(f"\n📦 Registered Tools ({len(tools)}):")
|
||||
for t in tools:
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Unit tests for agent factory."""
|
||||
|
||||
from homeagent.agent.antigravity import AntigravityAgent
|
||||
from homeagent.agent.factory import create_agent
|
||||
from homeagent.agent.gemini import GeminiAgent
|
||||
from homeagent.agent.openai_agent import OpenAIAgent
|
||||
@@ -39,3 +40,20 @@ def test_factory_creates_openai_compatible(tmp_path):
|
||||
assert agent.provider == "openai"
|
||||
assert agent.base_url == "https://openrouter.ai/api/v1"
|
||||
assert agent.model == "deepseek/deepseek-chat"
|
||||
|
||||
|
||||
def test_factory_creates_antigravity(tmp_path):
|
||||
settings = Settings(
|
||||
LLM_PROVIDER="antigravity",
|
||||
ANTIGRAVITY_MODEL="claude-sonnet-5-5-high",
|
||||
ANTIGRAVITY_SUBAGENT_MODEL="gemini-3.8-flash-medium",
|
||||
DATA_DIR=tmp_path,
|
||||
)
|
||||
agent = create_agent(settings=settings)
|
||||
assert isinstance(agent, AntigravityAgent)
|
||||
assert agent.provider == "antigravity"
|
||||
assert agent.model == "claude-sonnet-5-5-high"
|
||||
assert agent.subagent_model == "gemini-3.8-flash-medium"
|
||||
assert settings.get_active_provider_name() == "Antigravity"
|
||||
assert settings.get_active_model() == "claude-sonnet-5-5-high"
|
||||
assert settings.get_active_subagent_model() == "gemini-3.8-flash-medium"
|
||||
@@ -0,0 +1,500 @@
|
||||
"""Unit tests for AntigravityAgent, MCPToolBridge, and Antigravity SubagentRunner."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from typing import Any, Optional
|
||||
from unittest.mock import patch
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from homeagent.agent.antigravity import (
|
||||
AntigravityAgent,
|
||||
_format_cli_error,
|
||||
_parse_models_output,
|
||||
_strip_mcp_tool_prefix,
|
||||
)
|
||||
from homeagent.agent.conversation import ConversationManager
|
||||
from homeagent.agent.mcp_bridge import MCPToolBridge, normalize_mcp_schema
|
||||
from homeagent.agent.subagent import SubagentRunner
|
||||
from homeagent.config import Settings
|
||||
from homeagent.tools.base import tool
|
||||
from homeagent.tools.registry import ToolRegistry
|
||||
|
||||
|
||||
class FakeStreamReader:
|
||||
"""Async line reader mimicking asyncio.StreamReader for mocked subprocess stdout."""
|
||||
|
||||
def __init__(self, lines: list[bytes]) -> None:
|
||||
self._lines = list(lines)
|
||||
|
||||
async def readline(self) -> bytes:
|
||||
if not self._lines:
|
||||
return b""
|
||||
return self._lines.pop(0)
|
||||
|
||||
async def read(self) -> bytes:
|
||||
data = b"".join(self._lines)
|
||||
self._lines.clear()
|
||||
return data
|
||||
|
||||
|
||||
class FakeProcess:
|
||||
"""Minimal asyncio subprocess stub."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
stdout_lines: list[str],
|
||||
stderr_text: str = "",
|
||||
returncode: int = 0,
|
||||
) -> None:
|
||||
self.stdout = FakeStreamReader([(line + "\n").encode("utf-8") for line in stdout_lines])
|
||||
self.stderr = FakeStreamReader([stderr_text.encode("utf-8")] if stderr_text else [])
|
||||
self.returncode = returncode
|
||||
self._stdout_raw = "\n".join(stdout_lines).encode("utf-8")
|
||||
self._stderr_raw = stderr_text.encode("utf-8")
|
||||
self.killed = False
|
||||
|
||||
async def wait(self) -> int:
|
||||
return self.returncode
|
||||
|
||||
async def communicate(self) -> tuple[bytes, bytes]:
|
||||
return self._stdout_raw, self._stderr_raw
|
||||
|
||||
def kill(self) -> None:
|
||||
self.killed = True
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# MCPToolBridge tests
|
||||
# ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_normalize_mcp_schema_strips_nullable_recursively():
|
||||
schema = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"category": {"type": "string", "nullable": True, "description": "Optional category"},
|
||||
"items": {
|
||||
"type": "array",
|
||||
"items": {"type": "string", "nullable": True},
|
||||
},
|
||||
},
|
||||
}
|
||||
normalized = normalize_mcp_schema(schema)
|
||||
assert "nullable" not in normalized["properties"]["category"]
|
||||
assert "nullable" not in normalized["properties"]["items"]["items"]
|
||||
assert normalized["properties"]["category"]["type"] == "string"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_mcp_tool_bridge_protocol_and_auth(tmp_path):
|
||||
registry = ToolRegistry()
|
||||
|
||||
@tool(description="Add two numbers")
|
||||
async def add_numbers(a: int, b: int, label: Optional[str] = None) -> str:
|
||||
return f"{label or 'sum'}={a + b}"
|
||||
|
||||
@tool(description="Spawn subagent")
|
||||
async def spawn_subagent(task: str) -> str:
|
||||
return f"spawned:{task}"
|
||||
|
||||
registry.register(add_numbers)
|
||||
registry.register(spawn_subagent)
|
||||
|
||||
bridge = MCPToolBridge(registry)
|
||||
await bridge.ensure_started()
|
||||
try:
|
||||
url = bridge.get_endpoint_url(subagent=False)
|
||||
sub_url = bridge.get_endpoint_url(subagent=True)
|
||||
headers = {"Authorization": f"Bearer {bridge.token}"}
|
||||
|
||||
async with httpx.AsyncClient(trust_env=False) as client:
|
||||
# 1. Rejects missing/invalid auth
|
||||
unauth = await client.post(url, json={"jsonrpc": "2.0", "id": 1, "method": "ping"})
|
||||
assert unauth.status_code == 401
|
||||
|
||||
# 2. GET returns 405, DELETE returns 204
|
||||
assert (await client.get(url, headers=headers)).status_code == 405
|
||||
assert (await client.delete(url, headers=headers)).status_code == 204
|
||||
|
||||
# 3. initialize handshake
|
||||
init_resp = await client.post(
|
||||
url,
|
||||
headers=headers,
|
||||
json={
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "initialize",
|
||||
"params": {"protocolVersion": "2025-03-26"},
|
||||
},
|
||||
)
|
||||
assert init_resp.status_code == 200
|
||||
init_data = init_resp.json()["result"]
|
||||
assert init_data["protocolVersion"] == "2025-03-26"
|
||||
assert init_data["serverInfo"]["name"] == "homeagent"
|
||||
|
||||
# 4. notifications/initialized -> 202
|
||||
notif_resp = await client.post(
|
||||
url,
|
||||
headers=headers,
|
||||
json={"jsonrpc": "2.0", "method": "notifications/initialized"},
|
||||
)
|
||||
assert notif_resp.status_code == 202
|
||||
|
||||
# 5. tools/list on main includes both; subagent excludes spawn_subagent
|
||||
main_tools = (
|
||||
await client.post(url, headers=headers, json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
|
||||
).json()["result"]["tools"]
|
||||
assert {t["name"] for t in main_tools} == {"add_numbers", "spawn_subagent"}
|
||||
|
||||
sub_tools = (
|
||||
await client.post(sub_url, headers=headers, json={"jsonrpc": "2.0", "id": 3, "method": "tools/list"})
|
||||
).json()["result"]["tools"]
|
||||
assert {t["name"] for t in sub_tools} == {"add_numbers"}
|
||||
|
||||
# 6. tools/call executes registered tool
|
||||
call_resp = await client.post(
|
||||
url,
|
||||
headers=headers,
|
||||
json={
|
||||
"jsonrpc": "2.0",
|
||||
"id": 4,
|
||||
"method": "tools/call",
|
||||
"params": {"name": "add_numbers", "arguments": {"a": 19, "b": 23, "label": "ans"}},
|
||||
},
|
||||
)
|
||||
call_result = call_resp.json()["result"]
|
||||
assert call_result["isError"] is False
|
||||
assert call_result["content"][0]["text"] == "ans=42"
|
||||
|
||||
# 7. Calling excluded subagent tool on /mcp-subagent returns isError=True
|
||||
blocked = (
|
||||
await client.post(
|
||||
sub_url,
|
||||
headers=headers,
|
||||
json={
|
||||
"jsonrpc": "2.0",
|
||||
"id": 5,
|
||||
"method": "tools/call",
|
||||
"params": {"name": "spawn_subagent", "arguments": {"task": "recurse"}},
|
||||
},
|
||||
)
|
||||
).json()["result"]
|
||||
assert blocked["isError"] is True
|
||||
|
||||
# 8. write_mcp_config writes valid eager config
|
||||
cfg_path = bridge.write_mcp_config(tmp_path)
|
||||
cfg = json.loads(cfg_path.read_text(encoding="utf-8"))
|
||||
server_cfg = cfg["mcpServers"]["homeagent"]
|
||||
assert server_cfg["serverUrl"] == url
|
||||
assert server_cfg["tools"]["add_numbers"] == {"eager": True}
|
||||
finally:
|
||||
await bridge.stop()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# Helper parsing & formatting tests
|
||||
# ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_parse_models_output_strips_spinner_and_ansi():
|
||||
raw = (
|
||||
"\r⠋ Fetching available models...\r⠙ Fetching available models...\r"
|
||||
"\x1b[32mgemini-4-neon-high\x1b[0m Gemini 4 Neon (High)\n"
|
||||
"claude-sonnet-5-5-high\tClaude Sonnet 5.5 (High)\n"
|
||||
"gpt-oss-120b-medium GPT-OSS 120B (Medium)\n"
|
||||
)
|
||||
parsed = _parse_models_output(raw)
|
||||
assert parsed == [
|
||||
("gemini-4-neon-high", "Gemini 4 Neon (High)"),
|
||||
("claude-sonnet-5-5-high", "Claude Sonnet 5.5 (High)"),
|
||||
("gpt-oss-120b-medium", "GPT-OSS 120B (Medium)"),
|
||||
]
|
||||
|
||||
|
||||
def test_strip_mcp_tool_prefix():
|
||||
assert _strip_mcp_tool_prefix("mcp_homeagent_calendar_today_schedule") == "calendar_today_schedule"
|
||||
assert _strip_mcp_tool_prefix("web_search") == "web_search"
|
||||
|
||||
|
||||
def test_format_cli_error_messages():
|
||||
assert "не авторизован" in _format_cli_error("authentication required", "gemini-4-neon-high")
|
||||
assert "Исчерпан лимит" in _format_cli_error("quota exceeded for model", "claude-opus-5-5-high")
|
||||
assert "недоступна" in _format_cli_error("invalid model selection", "bad-model")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# AntigravityAgent tests
|
||||
# ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_antigravity_agent_missing_cli_returns_help(tmp_path):
|
||||
settings = Settings(
|
||||
LLM_PROVIDER="antigravity",
|
||||
ANTIGRAVITY_CLI_PATH="/nonexistent/agy-missing-bin",
|
||||
DATA_DIR=tmp_path,
|
||||
)
|
||||
agent = AntigravityAgent(settings=settings, registry=ToolRegistry(), conversation_manager=ConversationManager(tmp_path))
|
||||
reply = await agent.chat(chat_id=100, thread_id=None, user_message="Привет")
|
||||
assert "не найден" in reply
|
||||
await agent.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_antigravity_agent_chat_streams_progress_and_resumes_topic(tmp_path):
|
||||
settings = Settings(
|
||||
LLM_PROVIDER="antigravity",
|
||||
ANTIGRAVITY_MODEL="gemini-4-neon-high",
|
||||
ANTIGRAVITY_TIMEOUT_SECONDS=120,
|
||||
DATA_DIR=tmp_path,
|
||||
)
|
||||
registry = ToolRegistry()
|
||||
cm = ConversationManager(tmp_path)
|
||||
agent = AntigravityAgent(settings=settings, registry=registry, conversation_manager=cm)
|
||||
|
||||
captured_cmds: list[list[str]] = []
|
||||
turn1_events = [
|
||||
json.dumps({"event": "init", "conversation_id": "conv-aaa-111", "init": {"model": "gemini-4-neon-high"}}),
|
||||
json.dumps(
|
||||
{
|
||||
"event": "step_update",
|
||||
"step_update": {
|
||||
"conversation_id": "conv-aaa-111",
|
||||
"step_index": 1,
|
||||
"state": "ACTIVE",
|
||||
"step_type": "tool",
|
||||
"tool_name": "mcp_homeagent_calendar_today_schedule",
|
||||
"tool_info": {"name": "mcp_homeagent_calendar_today_schedule", "parameters": {}},
|
||||
},
|
||||
}
|
||||
),
|
||||
json.dumps(
|
||||
{
|
||||
"event": "step_update",
|
||||
"step_update": {
|
||||
"conversation_id": "conv-aaa-111",
|
||||
"step_index": 2,
|
||||
"state": "ACTIVE",
|
||||
"step_type": "agent_response",
|
||||
"text_delta": "Сегодня 2 встречи.",
|
||||
},
|
||||
}
|
||||
),
|
||||
json.dumps(
|
||||
{
|
||||
"event": "result",
|
||||
"result": {
|
||||
"conversation_id": "conv-aaa-111",
|
||||
"status": "SUCCESS",
|
||||
"response": "Сегодня 2 встречи.",
|
||||
"num_turns": 1,
|
||||
},
|
||||
}
|
||||
),
|
||||
]
|
||||
turn2_events = [
|
||||
json.dumps(
|
||||
{
|
||||
"event": "result",
|
||||
"result": {
|
||||
"conversation_id": "conv-aaa-111",
|
||||
"status": "SUCCESS",
|
||||
"response": "Первая в 10:00.",
|
||||
"num_turns": 2,
|
||||
},
|
||||
}
|
||||
)
|
||||
]
|
||||
turn3_after_reset_events = [
|
||||
json.dumps(
|
||||
{
|
||||
"event": "result",
|
||||
"result": {
|
||||
"conversation_id": "conv-bbb-222",
|
||||
"status": "SUCCESS",
|
||||
"response": "Новый диалог!",
|
||||
"num_turns": 1,
|
||||
},
|
||||
}
|
||||
)
|
||||
]
|
||||
procs = [
|
||||
FakeProcess(turn1_events),
|
||||
FakeProcess(turn2_events),
|
||||
FakeProcess(turn3_after_reset_events),
|
||||
]
|
||||
|
||||
async def fake_exec(*cmd: str, **kwargs: Any) -> FakeProcess:
|
||||
captured_cmds.append(list(cmd))
|
||||
return procs.pop(0)
|
||||
|
||||
progress_updates: list[str] = []
|
||||
|
||||
async def on_progress(text: str) -> None:
|
||||
progress_updates.append(text)
|
||||
|
||||
try:
|
||||
with (
|
||||
patch("homeagent.agent.antigravity._resolve_cli_binary", return_value="/usr/bin/agy"),
|
||||
patch("asyncio.create_subprocess_exec", side_effect=fake_exec),
|
||||
):
|
||||
# Turn 1: fresh session
|
||||
res1 = await agent.chat(chat_id=-1001, thread_id=5, user_message="Что сегодня?", on_progress=on_progress)
|
||||
assert res1 == "Сегодня 2 встречи."
|
||||
assert "--conversation" not in captured_cmds[0]
|
||||
assert "--model" in captured_cmds[0] and "gemini-4-neon-high" in captured_cmds[0]
|
||||
assert any("Проверяю расписание на сегодня" in p for p in progress_updates)
|
||||
|
||||
# Turn 2: resumes conversation_id conv-aaa-111
|
||||
res2 = await agent.chat(chat_id=-1001, thread_id=5, user_message="Во сколько первая?")
|
||||
assert res2 == "Первая в 10:00."
|
||||
assert "--conversation" in captured_cmds[1]
|
||||
cid_idx = captured_cmds[1].index("--conversation") + 1
|
||||
assert captured_cmds[1][cid_idx] == "conv-aaa-111"
|
||||
|
||||
# Verify ConversationManager also persisted messages
|
||||
msgs = cm.get_openai_messages(-1001, 5)
|
||||
assert len(msgs) == 4
|
||||
assert msgs[-1]["content"] == "Первая в 10:00."
|
||||
|
||||
# /reset via conversation_manager.clear() must reset Antigravity session too!
|
||||
cm.clear(-1001, 5)
|
||||
res3 = await agent.chat(chat_id=-1001, thread_id=5, user_message="Начнем сначала")
|
||||
assert res3 == "Новый диалог!"
|
||||
assert "--conversation" not in captured_cmds[2]
|
||||
finally:
|
||||
await agent.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_antigravity_agent_retries_when_saved_conversation_is_stale(tmp_path):
|
||||
settings = Settings(LLM_PROVIDER="antigravity", DATA_DIR=tmp_path)
|
||||
cm = ConversationManager(tmp_path)
|
||||
cm.append_openai_turn_sequence(
|
||||
10,
|
||||
None,
|
||||
[
|
||||
{"role": "user", "content": "Старый вопрос"},
|
||||
{"role": "assistant", "content": "Старый ответ"},
|
||||
],
|
||||
)
|
||||
agent = AntigravityAgent(settings=settings, registry=ToolRegistry(), conversation_manager=cm)
|
||||
agent._conversation_ids[agent._topic_key(10, None)] = "stale-conv-id"
|
||||
|
||||
cmds: list[list[str]] = []
|
||||
procs = [
|
||||
FakeProcess(
|
||||
[
|
||||
json.dumps(
|
||||
{
|
||||
"event": "result",
|
||||
"result": {
|
||||
"conversation_id": "",
|
||||
"status": "ERROR",
|
||||
"response": "",
|
||||
"error": "conversation not found: stale-conv-id",
|
||||
},
|
||||
}
|
||||
)
|
||||
],
|
||||
returncode=1,
|
||||
),
|
||||
FakeProcess(
|
||||
[
|
||||
json.dumps(
|
||||
{
|
||||
"event": "result",
|
||||
"result": {
|
||||
"conversation_id": "fresh-conv-id",
|
||||
"status": "SUCCESS",
|
||||
"response": "Восстановленный ответ",
|
||||
},
|
||||
}
|
||||
)
|
||||
],
|
||||
returncode=0,
|
||||
),
|
||||
]
|
||||
|
||||
async def fake_exec(*cmd: str, **kwargs: Any) -> FakeProcess:
|
||||
cmds.append(list(cmd))
|
||||
return procs.pop(0)
|
||||
|
||||
try:
|
||||
with (
|
||||
patch("homeagent.agent.antigravity._resolve_cli_binary", return_value="/usr/bin/agy"),
|
||||
patch("asyncio.create_subprocess_exec", side_effect=fake_exec),
|
||||
):
|
||||
res = await agent.chat(chat_id=10, thread_id=None, user_message="Продолжаем")
|
||||
assert res == "Восстановленный ответ"
|
||||
assert len(cmds) == 2
|
||||
assert "--conversation" in cmds[0]
|
||||
assert "--conversation" not in cmds[1]
|
||||
# Carryover history should be injected into retry prompt
|
||||
retry_prompt = cmds[1][cmds[1].index("-p") + 1]
|
||||
assert "Старый вопрос" in retry_prompt
|
||||
assert agent._conversation_ids[agent._topic_key(10, None)] == "fresh-conv-id"
|
||||
finally:
|
||||
await agent.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_antigravity_agent_set_model_updates_runtime_and_settings(tmp_path):
|
||||
settings = Settings(LLM_PROVIDER="antigravity", ANTIGRAVITY_MODEL="gemini-4-neon-high", DATA_DIR=tmp_path)
|
||||
agent = AntigravityAgent(settings=settings, registry=ToolRegistry(), conversation_manager=ConversationManager(tmp_path))
|
||||
|
||||
agent.set_model("claude-opus-5-5-high")
|
||||
assert agent.model == "claude-opus-5-5-high"
|
||||
assert settings.ANTIGRAVITY_MODEL == "claude-opus-5-5-high"
|
||||
assert settings.get_active_model() == "claude-opus-5-5-high"
|
||||
await agent.close()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# SubagentRunner with Antigravity provider
|
||||
# ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_subagent_runner_antigravity_mocked(tmp_path):
|
||||
settings = Settings(
|
||||
LLM_PROVIDER="antigravity",
|
||||
ANTIGRAVITY_SUBAGENT_MODEL="gemini-3.8-flash-medium",
|
||||
DATA_DIR=tmp_path,
|
||||
)
|
||||
registry = ToolRegistry()
|
||||
runner = SubagentRunner(settings=settings, registry=registry)
|
||||
|
||||
captured_cmd: list[str] = []
|
||||
sub_proc = FakeProcess(
|
||||
[
|
||||
json.dumps(
|
||||
{
|
||||
"conversation_id": "sub-conv-1",
|
||||
"status": "SUCCESS",
|
||||
"response": "Найдено 3 активных тикета в Jira.",
|
||||
}
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
async def fake_exec(*cmd: str, **kwargs: Any) -> FakeProcess:
|
||||
captured_cmd.extend(cmd)
|
||||
return sub_proc
|
||||
|
||||
try:
|
||||
with (
|
||||
patch("homeagent.agent.antigravity._resolve_cli_binary", return_value="/usr/bin/agy"),
|
||||
patch("asyncio.create_subprocess_exec", side_effect=fake_exec),
|
||||
):
|
||||
res = await runner.run_task(task="Проверь задачи Jira", role="Jira Specialist")
|
||||
assert res == "Найдено 3 активных тикета в Jira."
|
||||
assert "--model" in captured_cmd
|
||||
assert captured_cmd[captured_cmd.index("--model") + 1] == "gemini-3.8-flash-medium"
|
||||
finally:
|
||||
if getattr(runner, "_mcp_bridge", None) is not None:
|
||||
await runner._mcp_bridge.stop()
|
||||
@@ -0,0 +1,281 @@
|
||||
"""Tests for MCP Connectors Telegram Bot interface: commands, inline callbacks, wizard, ghost mode, whitelist."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
from aiohttp import web
|
||||
from aiogram import Bot, Dispatcher
|
||||
from aiogram.types import CallbackQuery, Chat, Message, Update, User
|
||||
import pytest
|
||||
|
||||
from homeagent.bot.handlers import create_bot_router
|
||||
from homeagent.bot.middlewares import WhitelistMiddleware
|
||||
from homeagent.config import Settings
|
||||
from homeagent.mcp.manager import MCPConnectorManager
|
||||
from homeagent.skills.manager import SkillManager
|
||||
from homeagent.tools.registry import ToolRegistry
|
||||
|
||||
|
||||
async def _start_mock_mcp_server(expected_bearer: str | None = None) -> tuple[web.AppRunner, str]:
|
||||
async def handle_mcp(request: web.Request) -> web.Response:
|
||||
if expected_bearer and request.headers.get("Authorization") != f"Bearer {expected_bearer}":
|
||||
return web.Response(status=401)
|
||||
if request.method == "DELETE":
|
||||
return web.Response(status=204)
|
||||
body = await request.json()
|
||||
req_id = body.get("id")
|
||||
method = body.get("method")
|
||||
if req_id is None:
|
||||
return web.Response(status=202)
|
||||
if method == "initialize":
|
||||
return web.json_response(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"result": {
|
||||
"protocolVersion": "2025-03-26",
|
||||
"capabilities": {"tools": {}},
|
||||
"serverInfo": {"name": "bot-test-mcp", "version": "1.0"},
|
||||
},
|
||||
}
|
||||
)
|
||||
if method == "tools/list":
|
||||
return web.json_response(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"result": {
|
||||
"tools": [
|
||||
{
|
||||
"name": "hello_world",
|
||||
"description": "Say hello",
|
||||
"inputSchema": {"type": "object", "properties": {"who": {"type": "string"}}},
|
||||
}
|
||||
]
|
||||
},
|
||||
}
|
||||
)
|
||||
if method == "tools/call":
|
||||
who = ((body.get("params") or {}).get("arguments") or {}).get("who", "world")
|
||||
return web.json_response(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"result": {"content": [{"type": "text", "text": f"Hello, {who}!"}], "isError": False},
|
||||
}
|
||||
)
|
||||
return web.json_response({"jsonrpc": "2.0", "id": req_id, "result": {}})
|
||||
|
||||
app = web.Application()
|
||||
app.router.add_route("*", "/mcp", handle_mcp)
|
||||
runner = web.AppRunner(app, access_log=None)
|
||||
await runner.setup()
|
||||
site = web.TCPSite(runner, "127.0.0.1", 0)
|
||||
await site.start()
|
||||
port = int(site._server.sockets[0].getsockname()[1]) # type: ignore[union-attr]
|
||||
return runner, f"http://127.0.0.1:{port}/mcp"
|
||||
|
||||
|
||||
def _make_mock_bot() -> AsyncMock:
|
||||
bot = AsyncMock(spec=Bot)
|
||||
bot.send_rich_message = AsyncMock()
|
||||
bot.send_message = AsyncMock()
|
||||
bot.delete_message = AsyncMock()
|
||||
bot.answer_callback_query = AsyncMock()
|
||||
bot.answer_guest_query = AsyncMock()
|
||||
bot.get_me = AsyncMock(return_value=MagicMock(username="homeagent_bot"))
|
||||
return bot
|
||||
|
||||
|
||||
def _make_message(bot: MagicMock, user_id: int, chat_id: int, text: str, msg_id: int = 1) -> Message:
|
||||
user = User(id=user_id, is_bot=False, first_name="Owner", username="owner")
|
||||
chat = Chat(id=chat_id, type="private")
|
||||
msg = Message(message_id=msg_id, date=datetime.now(), chat=chat, from_user=user, text=text)
|
||||
msg._bot = bot
|
||||
return msg
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bot_mcp_quick_add_tools_and_remove(tmp_path):
|
||||
runner, mcp_url = await _start_mock_mcp_server(expected_bearer="super-secret-token-999")
|
||||
try:
|
||||
settings = Settings(
|
||||
ALLOWED_TELEGRAM_USER_IDS=[111],
|
||||
DATA_DIR=tmp_path,
|
||||
MCP_CONFIG_FILE=tmp_path / "none.json",
|
||||
)
|
||||
registry = ToolRegistry()
|
||||
manager = MCPConnectorManager(settings=settings, registry=registry)
|
||||
agent = MagicMock()
|
||||
agent.chat = AsyncMock(return_value="should not be called")
|
||||
skill_manager = SkillManager(tmp_path / "skills")
|
||||
|
||||
router = create_bot_router(settings, agent, skill_manager, registry, mcp_manager=manager)
|
||||
dp = Dispatcher()
|
||||
wl = WhitelistMiddleware(settings)
|
||||
dp.message.middleware(wl)
|
||||
dp.callback_query.middleware(wl)
|
||||
dp.include_router(router)
|
||||
bot = _make_mock_bot()
|
||||
|
||||
# 1. /mcp add with bearer token
|
||||
msg = _make_message(bot, 111, 111, f"/mcp add demo {mcp_url} bearer super-secret-token-999", msg_id=10)
|
||||
await dp.feed_update(bot, Update(update_id=1, message=msg))
|
||||
|
||||
# Should attempt to delete secret message and never echo raw token
|
||||
bot.delete_message.assert_awaited_once()
|
||||
sent_md = bot.send_rich_message.await_args.kwargs["rich_message"].markdown
|
||||
assert "demo" in sent_md
|
||||
assert "подключён" in sent_md
|
||||
assert "super-secret-token-999" not in sent_md
|
||||
assert registry.get("mcp_demo_hello_world") is not None
|
||||
assert await registry.execute("mcp_demo_hello_world", {"who": "Telegram"}) == "Hello, Telegram!"
|
||||
|
||||
# 2. /mcp tools demo
|
||||
bot.send_rich_message.reset_mock()
|
||||
msg_tools = _make_message(bot, 111, 111, "/mcp tools demo", msg_id=11)
|
||||
await dp.feed_update(bot, Update(update_id=2, message=msg_tools))
|
||||
tools_md = bot.send_rich_message.await_args.kwargs["rich_message"].markdown
|
||||
assert "mcp_demo_hello_world" in tools_md
|
||||
|
||||
# 3. /mcp remove demo
|
||||
bot.send_rich_message.reset_mock()
|
||||
msg_rm = _make_message(bot, 111, 111, "/mcp remove demo", msg_id=12)
|
||||
await dp.feed_update(bot, Update(update_id=3, message=msg_rm))
|
||||
assert registry.get("mcp_demo_hello_world") is None
|
||||
assert manager.get_connector("demo") is None
|
||||
|
||||
agent.chat.assert_not_awaited()
|
||||
await manager.close()
|
||||
finally:
|
||||
await runner.cleanup()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bot_mcp_interactive_wizard_and_callback_whitelist(tmp_path):
|
||||
runner, mcp_url = await _start_mock_mcp_server(expected_bearer="wiz-secret-123456")
|
||||
try:
|
||||
settings = Settings(
|
||||
ALLOWED_TELEGRAM_USER_IDS=[222],
|
||||
DATA_DIR=tmp_path,
|
||||
MCP_CONFIG_FILE=tmp_path / "none.json",
|
||||
)
|
||||
registry = ToolRegistry()
|
||||
manager = MCPConnectorManager(settings=settings, registry=registry)
|
||||
agent = MagicMock()
|
||||
agent.chat = AsyncMock(return_value="agent reply")
|
||||
skill_manager = SkillManager(tmp_path / "skills")
|
||||
|
||||
router = create_bot_router(settings, agent, skill_manager, registry, mcp_manager=manager)
|
||||
dp = Dispatcher()
|
||||
wl = WhitelistMiddleware(settings)
|
||||
dp.message.middleware(wl)
|
||||
dp.callback_query.middleware(wl)
|
||||
dp.include_router(router)
|
||||
bot = _make_mock_bot()
|
||||
|
||||
# Unauthorized callback query must be silently blocked by WhitelistMiddleware!
|
||||
stranger = User(id=999, is_bot=False, first_name="Stranger")
|
||||
base_msg = _make_message(bot, 222, 222, "/mcp", msg_id=1)
|
||||
unauth_cb = CallbackQuery(
|
||||
id="cb-unauth",
|
||||
from_user=stranger,
|
||||
chat_instance="inst",
|
||||
message=base_msg,
|
||||
data="mcp:add",
|
||||
)
|
||||
unauth_cb._bot = bot
|
||||
await dp.feed_update(bot, Update(update_id=10, callback_query=unauth_cb))
|
||||
bot.send_rich_message.assert_not_awaited()
|
||||
|
||||
# Authorized user starts wizard via /mcp add
|
||||
owner = User(id=222, is_bot=False, first_name="Owner")
|
||||
await dp.feed_update(bot, Update(update_id=11, message=_make_message(bot, 222, 222, "/mcp add", msg_id=2)))
|
||||
assert "Шаг 1/5" in bot.send_rich_message.await_args.kwargs["rich_message"].markdown
|
||||
|
||||
# Step 1: connector name (must be intercepted by wizard, NOT sent to agent.chat!)
|
||||
await dp.feed_update(bot, Update(update_id=12, message=_make_message(bot, 222, 222, "my_wiz", msg_id=3)))
|
||||
assert "Шаг 2/5" in bot.send_rich_message.await_args.kwargs["rich_message"].markdown
|
||||
|
||||
# Step 2: pick transport via inline button callback
|
||||
cb_transport = CallbackQuery(
|
||||
id="cb-wt",
|
||||
from_user=owner,
|
||||
chat_instance="inst",
|
||||
message=base_msg,
|
||||
data="mcp:wt:streamable_http",
|
||||
)
|
||||
cb_transport._bot = bot
|
||||
await dp.feed_update(bot, Update(update_id=13, callback_query=cb_transport))
|
||||
assert "Шаг 3/5" in bot.send_rich_message.await_args.kwargs["rich_message"].markdown
|
||||
|
||||
# Step 3: send URL
|
||||
await dp.feed_update(bot, Update(update_id=14, message=_make_message(bot, 222, 222, mcp_url, msg_id=4)))
|
||||
assert "Шаг 4/5" in bot.send_rich_message.await_args.kwargs["rich_message"].markdown
|
||||
|
||||
# Step 4: pick Bearer auth via inline button callback
|
||||
cb_auth = CallbackQuery(
|
||||
id="cb-wa",
|
||||
from_user=owner,
|
||||
chat_instance="inst",
|
||||
message=base_msg,
|
||||
data="mcp:wa:bearer",
|
||||
)
|
||||
cb_auth._bot = bot
|
||||
await dp.feed_update(bot, Update(update_id=15, callback_query=cb_auth))
|
||||
assert "Шаг 5/5" in bot.send_rich_message.await_args.kwargs["rich_message"].markdown
|
||||
|
||||
# Step 5: send Bearer token -> saves, connects, registers tools!
|
||||
await dp.feed_update(bot, Update(update_id=16, message=_make_message(bot, 222, 222, "wiz-secret-123456", msg_id=5)))
|
||||
final_md = bot.send_rich_message.await_args.kwargs["rich_message"].markdown
|
||||
assert "my_wiz" in final_md
|
||||
assert "подключён" in final_md
|
||||
assert "wiz-secret-123456" not in final_md
|
||||
assert registry.get("mcp_my_wiz_hello_world") is not None
|
||||
|
||||
# Agent was never mistakenly invoked during wizard steps
|
||||
agent.chat.assert_not_awaited()
|
||||
await manager.close()
|
||||
finally:
|
||||
await runner.cleanup()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bot_mcp_ghost_mode_command(tmp_path):
|
||||
settings = Settings(
|
||||
GHOST_MODE_ENABLED=True,
|
||||
ALLOWED_TELEGRAM_USER_IDS=[333],
|
||||
DATA_DIR=tmp_path,
|
||||
MCP_CONFIG_FILE=tmp_path / "none.json",
|
||||
)
|
||||
registry = ToolRegistry()
|
||||
manager = MCPConnectorManager(settings=settings, registry=registry)
|
||||
agent = MagicMock()
|
||||
agent.chat = AsyncMock()
|
||||
skill_manager = SkillManager(tmp_path / "skills")
|
||||
|
||||
router = create_bot_router(settings, agent, skill_manager, registry, mcp_manager=manager)
|
||||
dp = Dispatcher()
|
||||
dp.include_router(router)
|
||||
bot = _make_mock_bot()
|
||||
|
||||
caller = User(id=333, is_bot=False, first_name="Owner")
|
||||
guest_msg = Message(
|
||||
message_id=1,
|
||||
date=datetime.now(),
|
||||
chat=Chat(id=-100555, type="group"),
|
||||
from_user=caller,
|
||||
text="@homeagent_bot /mcp list",
|
||||
guest_query_id="gq_mcp_list",
|
||||
guest_bot_caller_user=caller,
|
||||
)
|
||||
guest_msg._bot = bot
|
||||
|
||||
await dp.feed_update(bot, Update(update_id=20, guest_message=guest_msg))
|
||||
bot.answer_guest_query.assert_awaited_once()
|
||||
sent = bot.answer_guest_query.await_args.kwargs["result"].input_message_content.rich_message.markdown
|
||||
assert "MCP Коннекторы" in sent
|
||||
agent.chat.assert_not_awaited()
|
||||
await manager.close()
|
||||
@@ -0,0 +1,781 @@
|
||||
"""Comprehensive tests for MCP connectors: models, transports, auth methods, and manager."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import textwrap
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
from aiohttp import web
|
||||
import pytest
|
||||
|
||||
from homeagent.agent.mcp_bridge import MCPToolBridge
|
||||
from homeagent.config import Settings
|
||||
from homeagent.mcp.auth import (
|
||||
MCPAuthManager,
|
||||
MCPAuthRequiredError,
|
||||
OAuthTokenStore,
|
||||
parse_www_authenticate,
|
||||
)
|
||||
from homeagent.mcp.manager import MCPConnectorManager
|
||||
from homeagent.mcp.models import (
|
||||
MCPAuthConfig,
|
||||
MCPConnectorConfig,
|
||||
expand_env_vars,
|
||||
mask_secret,
|
||||
parse_connectors_payload,
|
||||
sanitize_mcp_input_schema,
|
||||
sanitize_tool_name,
|
||||
)
|
||||
from homeagent.tools.registry import ToolRegistry
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# Helpers: real local aiohttp test servers (Streamable HTTP, Legacy SSE, OAuth)
|
||||
# ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def _start_aiohttp_app(app: web.Application) -> tuple[web.AppRunner, str]:
|
||||
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]
|
||||
assert sockets
|
||||
port = int(sockets[0].getsockname()[1])
|
||||
return runner, f"http://127.0.0.1:{port}"
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# 1. Models, parsing, env expansion, and schema sanitization tests
|
||||
# ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_parse_connectors_payload_supports_mcp_servers_and_connectors(monkeypatch):
|
||||
monkeypatch.setenv("TEST_GH_TOKEN", "ghp_secret_123456")
|
||||
|
||||
raw_claude_format = {
|
||||
"mcpServers": {
|
||||
"github": {
|
||||
"serverUrl": "https://api.githubcopilot.com/mcp/",
|
||||
"headers": {"Authorization": "Bearer ${TEST_GH_TOKEN}"},
|
||||
},
|
||||
"local-fs": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
|
||||
"env": {"NODE_ENV": "test"},
|
||||
},
|
||||
}
|
||||
}
|
||||
conns = parse_connectors_payload(raw_claude_format, source="config")
|
||||
assert len(conns) == 2
|
||||
by_name = {c.name: c for c in conns}
|
||||
assert by_name["github"].url == "https://api.githubcopilot.com/mcp/"
|
||||
assert by_name["github"].transport == "auto"
|
||||
assert by_name["github"].resolved().headers["Authorization"] == "Bearer ghp_secret_123456"
|
||||
# Unresolved original preserves placeholder (does not leak expanded env)
|
||||
assert by_name["github"].headers["Authorization"] == "Bearer ${TEST_GH_TOKEN}"
|
||||
assert by_name["local-fs"].transport == "stdio"
|
||||
assert by_name["local-fs"].command == "npx"
|
||||
assert by_name["local-fs"].args == ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
|
||||
|
||||
assert expand_env_vars("${UNSET_VAR_XYZ:-fallback_val}") == "fallback_val"
|
||||
assert mask_secret("sk-1234567890abcdef") == "sk-1••••cdef"
|
||||
assert mask_secret("${TEST_GH_TOKEN}") == "`${TEST_GH_TOKEN}` (env)"
|
||||
|
||||
|
||||
def test_sanitize_mcp_input_schema_compatible_with_gemini_and_openai():
|
||||
complex_schema = {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$defs": {
|
||||
"Filter": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"field": {"type": "string"},
|
||||
"values": {"type": "array"},
|
||||
},
|
||||
"required": ["field"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
},
|
||||
"type": "object",
|
||||
"additionalProperties": False,
|
||||
"properties": {
|
||||
"query": {"type": "string", "description": "Search query", "default": ""},
|
||||
"limit": {"type": ["integer", "null"], "minimum": 1, "maximum": 100},
|
||||
"mode": {"const": "fast"},
|
||||
"tag": {"anyOf": [{"type": "string"}, {"type": "null"}], "description": "Optional tag"},
|
||||
"filter": {"$ref": "#/$defs/Filter"},
|
||||
},
|
||||
"required": ["query", "nonexistent_required"],
|
||||
}
|
||||
|
||||
sanitized = sanitize_mcp_input_schema(complex_schema)
|
||||
assert "$schema" not in sanitized
|
||||
assert "additionalProperties" not in sanitized
|
||||
assert sanitized["required"] == ["query"]
|
||||
assert sanitized["properties"]["limit"]["type"] == "integer"
|
||||
assert sanitized["properties"]["limit"]["nullable"] is True
|
||||
assert sanitized["properties"]["tag"]["type"] == "string"
|
||||
assert sanitized["properties"]["tag"]["nullable"] is True
|
||||
assert sanitized["properties"]["mode"]["enum"] == ["fast"]
|
||||
assert sanitized["properties"]["filter"]["type"] == "object"
|
||||
assert sanitized["properties"]["filter"]["properties"]["values"]["items"] == {"type": "string"}
|
||||
|
||||
# Verify Gemini FunctionDeclaration accepts sanitized schema cleanly!
|
||||
from homeagent.tools.base import ToolDefinition
|
||||
|
||||
registry = ToolRegistry()
|
||||
registry.register_definition(
|
||||
ToolDefinition(
|
||||
name=sanitize_tool_name("linear", "search/issues.v2"),
|
||||
description="[MCP:linear] Search issues",
|
||||
func=lambda **kw: "ok",
|
||||
parameters_schema=sanitized,
|
||||
is_async=False,
|
||||
)
|
||||
)
|
||||
decls = registry.get_function_declarations()
|
||||
assert len(decls) == 1
|
||||
assert decls[0].name == "mcp_linear_search_issues_v2"
|
||||
openai_tools = registry.get_openai_tools()
|
||||
assert openai_tools[0]["function"]["name"] == "mcp_linear_search_issues_v2"
|
||||
|
||||
|
||||
def test_sanitize_tool_name_length_and_collision():
|
||||
long_name = sanitize_tool_name("very_long_connector_name_12345", "extremely_long_remote_tool_name_that_exceeds_limit_xyz")
|
||||
assert len(long_name) <= 64
|
||||
|
||||
existing = {"mcp_demo_ping"}
|
||||
alt = sanitize_tool_name("demo", "ping", existing_names=existing)
|
||||
assert alt == "mcp_demo_ping_2"
|
||||
|
||||
|
||||
def test_parse_www_authenticate():
|
||||
hdr = 'Bearer realm="mcp", resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource", scope="read write"'
|
||||
parsed = parse_www_authenticate(hdr)
|
||||
assert parsed["realm"] == "mcp"
|
||||
assert parsed["resource_metadata"] == "https://mcp.example.com/.well-known/oauth-protected-resource"
|
||||
assert parsed["scope"] == "read write"
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# 2. Streamable HTTP transport + Bearer / API Key / Basic / Headers / SSE response
|
||||
# ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_streamable_http_all_static_auth_methods_and_sse_response(tmp_path):
|
||||
captured_requests: list[dict[str, Any]] = []
|
||||
expected_mode = {"mode": "bearer"}
|
||||
|
||||
async def handle_mcp(request: web.Request) -> web.Response:
|
||||
captured_requests.append(
|
||||
{
|
||||
"headers": dict(request.headers),
|
||||
"query": dict(request.query),
|
||||
}
|
||||
)
|
||||
mode = expected_mode["mode"]
|
||||
if mode == "bearer" and request.headers.get("Authorization") != "Bearer tok-secret-1":
|
||||
return web.Response(status=401, text="Unauthorized")
|
||||
if mode == "api_key_header" and request.headers.get("X-Custom-Key") != "Prefix key-999":
|
||||
return web.Response(status=401, text="Unauthorized")
|
||||
if mode == "api_key_query" and request.query.get("token_param") != "qkey-888":
|
||||
return web.Response(status=401, text="Unauthorized")
|
||||
if mode == "basic":
|
||||
expected_b64 = base64.b64encode(b"alice:wonderland").decode("ascii")
|
||||
if request.headers.get("Authorization") != f"Basic {expected_b64}":
|
||||
return web.Response(status=401, text="Unauthorized")
|
||||
if mode == "headers":
|
||||
if request.headers.get("X-Tenant") != "acme" or request.headers.get("X-Secret") != "s3cr3t":
|
||||
return web.Response(status=401, text="Unauthorized")
|
||||
|
||||
if request.method == "DELETE":
|
||||
return web.Response(status=204)
|
||||
|
||||
body = await request.json()
|
||||
method = body.get("method")
|
||||
req_id = body.get("id")
|
||||
if req_id is None:
|
||||
return web.Response(status=202)
|
||||
|
||||
if method == "initialize":
|
||||
return web.json_response(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"result": {
|
||||
"protocolVersion": "2025-03-26",
|
||||
"capabilities": {"tools": {}},
|
||||
"serverInfo": {"name": "mock-http-mcp", "version": "1.2.3"},
|
||||
},
|
||||
},
|
||||
headers={"Mcp-Session-Id": "sess-42"},
|
||||
)
|
||||
if method == "tools/list":
|
||||
cursor = (body.get("params") or {}).get("cursor")
|
||||
if not cursor:
|
||||
return web.json_response(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"result": {
|
||||
"tools": [
|
||||
{
|
||||
"name": "echo",
|
||||
"description": "Echo text back",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {"text": {"type": "string"}},
|
||||
"required": ["text"],
|
||||
},
|
||||
}
|
||||
],
|
||||
"nextCursor": "page2",
|
||||
},
|
||||
}
|
||||
)
|
||||
return web.json_response(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"result": {
|
||||
"tools": [
|
||||
{
|
||||
"name": "secret_admin",
|
||||
"description": "Should be excluded when filtered",
|
||||
"inputSchema": {"type": "object", "properties": {}},
|
||||
}
|
||||
]
|
||||
},
|
||||
}
|
||||
)
|
||||
if method == "tools/call":
|
||||
# Respond using text/event-stream (Streamable HTTP SSE response mode!)
|
||||
args = (body.get("params") or {}).get("arguments") or {}
|
||||
sse_payload = json.dumps(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"result": {
|
||||
"content": [{"type": "text", "text": f"ECHO:{args.get('text', '')}"}],
|
||||
"isError": False,
|
||||
},
|
||||
}
|
||||
)
|
||||
return web.Response(
|
||||
text=f": keepalive\nevent: message\ndata: {sse_payload}\n\n",
|
||||
content_type="text/event-stream",
|
||||
)
|
||||
return web.json_response({"jsonrpc": "2.0", "id": req_id, "result": {}})
|
||||
|
||||
app = web.Application()
|
||||
app.router.add_route("*", "/mcp", handle_mcp)
|
||||
runner, base_url = await _start_aiohttp_app(app)
|
||||
|
||||
try:
|
||||
registry = ToolRegistry()
|
||||
settings = Settings(DATA_DIR=tmp_path, MCP_CONFIG_FILE=tmp_path / "nonexistent.json")
|
||||
manager = MCPConnectorManager(settings=settings, registry=registry)
|
||||
|
||||
auth_cases = [
|
||||
("bearer", MCPAuthConfig(type="bearer", token="tok-secret-1")),
|
||||
(
|
||||
"api_key_header",
|
||||
MCPAuthConfig(
|
||||
type="api_key",
|
||||
api_key="key-999",
|
||||
api_key_in="header",
|
||||
header_name="X-Custom-Key",
|
||||
api_key_prefix="Prefix ",
|
||||
),
|
||||
),
|
||||
(
|
||||
"api_key_query",
|
||||
MCPAuthConfig(
|
||||
type="api_key",
|
||||
api_key="qkey-888",
|
||||
api_key_in="query",
|
||||
query_param="token_param",
|
||||
),
|
||||
),
|
||||
("basic", MCPAuthConfig(type="basic", username="alice", password="wonderland")),
|
||||
("headers", MCPAuthConfig(type="headers", headers={"X-Tenant": "acme", "X-Secret": "s3cr3t"})),
|
||||
]
|
||||
|
||||
for mode, auth_cfg in auth_cases:
|
||||
expected_mode["mode"] = mode
|
||||
cfg = MCPConnectorConfig(
|
||||
name=f"srv_{mode}",
|
||||
transport="streamable_http",
|
||||
url=f"{base_url}/mcp",
|
||||
auth=auth_cfg,
|
||||
exclude_tools=["secret_admin"],
|
||||
source="bot",
|
||||
)
|
||||
state = await manager.add_or_update_connector(cfg, connect_now=True, persist=True)
|
||||
assert state.status == "connected", f"Failed for {mode}: {state.last_error}"
|
||||
assert state.resolved_transport == "streamable_http"
|
||||
assert [t.remote_name for t in state.tools] == ["echo"]
|
||||
|
||||
tool_name = f"mcp_srv_{mode}_echo"
|
||||
out = await registry.execute(tool_name, {"text": f"hi-{mode}"})
|
||||
assert out == f"ECHO:hi-{mode}"
|
||||
|
||||
# Also verify MCPToolBridge exposes connected MCP tools to Antigravity CLI automatically!
|
||||
bridge = MCPToolBridge(registry)
|
||||
await bridge.ensure_started()
|
||||
try:
|
||||
mcp_cfg = bridge.build_mcp_config()
|
||||
assert "mcp_srv_bearer_echo" in mcp_cfg["mcpServers"]["homeagent"]["tools"]
|
||||
finally:
|
||||
await bridge.stop()
|
||||
|
||||
# Disconnecting unregisters its tools cleanly
|
||||
await manager.disconnect("srv_bearer")
|
||||
assert registry.get("mcp_srv_bearer_echo") is None
|
||||
|
||||
await manager.close()
|
||||
finally:
|
||||
await runner.cleanup()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# 3. Legacy SSE transport + Auto-detect fallback (Streamable HTTP -> SSE)
|
||||
# ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_legacy_sse_and_auto_transport_fallback(tmp_path):
|
||||
sse_queue: asyncio.Queue[str | None] = asyncio.Queue()
|
||||
|
||||
async def handle_sse_get(request: web.Request) -> web.StreamResponse:
|
||||
if request.method != "GET":
|
||||
# Force Streamable HTTP POST to get 405 so `auto` falls back to SSE!
|
||||
return web.Response(status=405, text="Method Not Allowed")
|
||||
resp = web.StreamResponse(
|
||||
status=200,
|
||||
headers={"Content-Type": "text/event-stream", "Cache-Control": "no-cache"},
|
||||
)
|
||||
await resp.prepare(request)
|
||||
await resp.write(b"event: endpoint\ndata: /messages?sid=1\n\n")
|
||||
try:
|
||||
while True:
|
||||
msg = await sse_queue.get()
|
||||
if msg is None:
|
||||
break
|
||||
await resp.write(f"event: message\ndata: {msg}\n\n".encode("utf-8"))
|
||||
except (asyncio.CancelledError, ConnectionResetError):
|
||||
pass
|
||||
return resp
|
||||
|
||||
async def handle_messages_post(request: web.Request) -> web.Response:
|
||||
body = await request.json()
|
||||
req_id = body.get("id")
|
||||
method = body.get("method")
|
||||
if req_id is None:
|
||||
return web.Response(status=202)
|
||||
if method == "initialize":
|
||||
res = {"protocolVersion": "2024-11-05", "capabilities": {"tools": {}}, "serverInfo": {"name": "sse-srv"}}
|
||||
elif method == "tools/list":
|
||||
res = {
|
||||
"tools": [
|
||||
{
|
||||
"name": "ping_sse",
|
||||
"description": "SSE ping",
|
||||
"inputSchema": {"type": "object", "properties": {}},
|
||||
}
|
||||
]
|
||||
}
|
||||
elif method == "tools/call":
|
||||
res = {"content": [{"type": "text", "text": "pong-over-sse"}], "isError": False}
|
||||
else:
|
||||
res = {}
|
||||
await sse_queue.put(json.dumps({"jsonrpc": "2.0", "id": req_id, "result": res}))
|
||||
return web.Response(status=202)
|
||||
|
||||
app = web.Application()
|
||||
app.router.add_route("*", "/stream", handle_sse_get)
|
||||
app.router.add_post("/messages", handle_messages_post)
|
||||
runner, base_url = await _start_aiohttp_app(app)
|
||||
|
||||
try:
|
||||
registry = ToolRegistry()
|
||||
settings = Settings(DATA_DIR=tmp_path, MCP_CONFIG_FILE=tmp_path / "none.json")
|
||||
manager = MCPConnectorManager(settings=settings, registry=registry)
|
||||
|
||||
# Notice URL does NOT end with /sse, so `auto` tries Streamable HTTP first, gets 405, and falls back to SSE!
|
||||
cfg = MCPConnectorConfig(
|
||||
name="legacy",
|
||||
transport="auto",
|
||||
url=f"{base_url}/stream",
|
||||
source="bot",
|
||||
)
|
||||
state = await manager.add_or_update_connector(cfg, connect_now=True, persist=True)
|
||||
assert state.status == "connected", state.last_error
|
||||
assert state.resolved_transport == "sse"
|
||||
assert await registry.execute("mcp_legacy_ping_sse", {}) == "pong-over-sse"
|
||||
await manager.close()
|
||||
finally:
|
||||
await sse_queue.put(None)
|
||||
await runner.cleanup()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# 4. Stdio transport (real Python subprocess with ENV auth)
|
||||
# ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stdio_transport_real_subprocess_with_env_auth(tmp_path):
|
||||
script = tmp_path / "fake_stdio_mcp.py"
|
||||
script.write_text(
|
||||
textwrap.dedent(
|
||||
"""
|
||||
import json, os, sys
|
||||
|
||||
for line in sys.stdin:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
msg = json.loads(line)
|
||||
if "id" not in msg or msg["id"] is None:
|
||||
continue
|
||||
req_id = msg["id"]
|
||||
method = msg.get("method")
|
||||
if method == "initialize":
|
||||
res = {"protocolVersion": "2025-03-26", "capabilities": {"tools": {}}, "serverInfo": {"name": "stdio-demo"}}
|
||||
elif method == "tools/list":
|
||||
res = {
|
||||
"tools": [
|
||||
{
|
||||
"name": "whoami",
|
||||
"description": "Return env secret tag",
|
||||
"inputSchema": {"type": "object", "properties": {"prefix": {"type": "string"}}},
|
||||
}
|
||||
]
|
||||
}
|
||||
elif method == "tools/call":
|
||||
args = (msg.get("params") or {}).get("arguments") or {}
|
||||
secret = os.environ.get("MCP_DEMO_SECRET", "missing")
|
||||
res = {"content": [{"type": "text", "text": f"{args.get('prefix', '')}:{secret}"}], "isError": False}
|
||||
else:
|
||||
res = {}
|
||||
sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": req_id, "result": res}) + "\\n")
|
||||
sys.stdout.flush()
|
||||
"""
|
||||
).strip()
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
registry = ToolRegistry()
|
||||
settings = Settings(DATA_DIR=tmp_path, MCP_CONFIG_FILE=tmp_path / "none.json")
|
||||
manager = MCPConnectorManager(settings=settings, registry=registry)
|
||||
|
||||
cfg = MCPConnectorConfig(
|
||||
name="local_py",
|
||||
transport="stdio",
|
||||
command=sys.executable,
|
||||
args=[str(script)],
|
||||
env={"MCP_DEMO_SECRET": "env-pass-777"},
|
||||
source="bot",
|
||||
)
|
||||
state = await manager.add_or_update_connector(cfg, connect_now=True, persist=True)
|
||||
assert state.status == "connected", state.last_error
|
||||
assert state.resolved_transport == "stdio"
|
||||
assert await registry.execute("mcp_local_py_whoami", {"prefix": "ok"}) == "ok:env-pass-777"
|
||||
await manager.close()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# 5. OAuth 2.1 PKCE (RFC 9728 + RFC 8414 + RFC 7591 DCR + 401 auto-upgrade + Refresh)
|
||||
# AND OAuth 2.0 Client Credentials + Device Flow + Refresh Token
|
||||
# ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_oauth2_pkce_discovery_dcr_and_refresh_end_to_end(tmp_path):
|
||||
oauth_state: dict[str, Any] = {
|
||||
"valid_tokens": set(),
|
||||
"registered_clients": {},
|
||||
"issued_codes": {},
|
||||
"refresh_count": 0,
|
||||
}
|
||||
base_url_holder = {"url": ""}
|
||||
|
||||
async def handle_prm(request: web.Request) -> web.Response:
|
||||
return web.json_response(
|
||||
{
|
||||
"resource": f"{base_url_holder['url']}/mcp",
|
||||
"authorization_servers": [base_url_holder["url"]],
|
||||
"scopes_supported": ["mcp:read", "mcp:write"],
|
||||
}
|
||||
)
|
||||
|
||||
async def handle_as_meta(request: web.Request) -> web.Response:
|
||||
u = base_url_holder["url"]
|
||||
return web.json_response(
|
||||
{
|
||||
"issuer": u,
|
||||
"authorization_endpoint": f"{u}/oauth/authorize",
|
||||
"token_endpoint": f"{u}/oauth/token",
|
||||
"registration_endpoint": f"{u}/oauth/register",
|
||||
"device_authorization_endpoint": f"{u}/oauth/device",
|
||||
}
|
||||
)
|
||||
|
||||
async def handle_dcr(request: web.Request) -> web.Response:
|
||||
data = await request.json()
|
||||
cid = "dcr-client-42"
|
||||
oauth_state["registered_clients"][cid] = data
|
||||
return web.json_response({"client_id": cid}, status=201)
|
||||
|
||||
async def handle_token(request: web.Request) -> web.Response:
|
||||
form = await request.post()
|
||||
grant = form.get("grant_type")
|
||||
if grant == "authorization_code":
|
||||
code = form.get("code")
|
||||
verifier = form.get("code_verifier", "")
|
||||
expected_challenge = oauth_state["issued_codes"].get(code)
|
||||
actual_challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode("ascii")).digest()).rstrip(b"=").decode("ascii")
|
||||
if not expected_challenge or actual_challenge != expected_challenge:
|
||||
return web.json_response({"error": "invalid_grant"}, status=400)
|
||||
tok = "pkce-access-1"
|
||||
oauth_state["valid_tokens"].add(tok)
|
||||
return web.json_response(
|
||||
{
|
||||
"access_token": tok,
|
||||
"token_type": "Bearer",
|
||||
"expires_in": 3600,
|
||||
"refresh_token": "pkce-refresh-1",
|
||||
}
|
||||
)
|
||||
if grant == "refresh_token":
|
||||
if form.get("refresh_token") not in ("pkce-refresh-1", "preset-refresh-99"):
|
||||
return web.json_response({"error": "invalid_grant"}, status=400)
|
||||
oauth_state["refresh_count"] += 1
|
||||
tok = f"refreshed-access-{oauth_state['refresh_count']}"
|
||||
oauth_state["valid_tokens"].add(tok)
|
||||
return web.json_response(
|
||||
{
|
||||
"access_token": tok,
|
||||
"token_type": "Bearer",
|
||||
"expires_in": 3600,
|
||||
"refresh_token": form.get("refresh_token"),
|
||||
}
|
||||
)
|
||||
if grant == "client_credentials":
|
||||
if form.get("client_id") == "m2m-id" and form.get("client_secret") == "m2m-secret":
|
||||
tok = "m2m-access-1"
|
||||
oauth_state["valid_tokens"].add(tok)
|
||||
return web.json_response({"access_token": tok, "token_type": "Bearer", "expires_in": 3600})
|
||||
return web.json_response({"error": "invalid_client"}, status=401)
|
||||
if grant == "urn:ietf:params:oauth:grant-type:device_code":
|
||||
polls = oauth_state.setdefault("device_polls", 0) + 1
|
||||
oauth_state["device_polls"] = polls
|
||||
if polls == 1:
|
||||
return web.json_response({"error": "authorization_pending"}, status=400)
|
||||
tok = "device-access-1"
|
||||
oauth_state["valid_tokens"].add(tok)
|
||||
return web.json_response({"access_token": tok, "token_type": "Bearer", "expires_in": 3600})
|
||||
return web.json_response({"error": "unsupported_grant_type"}, status=400)
|
||||
|
||||
async def handle_device_auth(request: web.Request) -> web.Response:
|
||||
return web.json_response(
|
||||
{
|
||||
"device_code": "dev-code-123",
|
||||
"user_code": "ABCD-EFGH",
|
||||
"verification_uri": f"{base_url_holder['url']}/activate",
|
||||
"expires_in": 300,
|
||||
"interval": 1,
|
||||
}
|
||||
)
|
||||
|
||||
async def handle_mcp(request: web.Request) -> web.Response:
|
||||
auth_hdr = request.headers.get("Authorization", "")
|
||||
token = auth_hdr[7:] if auth_hdr.startswith("Bearer ") else ""
|
||||
if token not in oauth_state["valid_tokens"]:
|
||||
return web.Response(
|
||||
status=401,
|
||||
headers={
|
||||
"WWW-Authenticate": f'Bearer resource_metadata="{base_url_holder["url"]}/.well-known/oauth-protected-resource", scope="mcp:read"'
|
||||
},
|
||||
)
|
||||
body = await request.json()
|
||||
req_id = body.get("id")
|
||||
method = body.get("method")
|
||||
if req_id is None:
|
||||
return web.Response(status=202)
|
||||
if method == "initialize":
|
||||
return web.json_response(
|
||||
{"jsonrpc": "2.0", "id": req_id, "result": {"protocolVersion": "2025-03-26", "capabilities": {"tools": {}}, "serverInfo": {"name": "oauth-mcp"}}}
|
||||
)
|
||||
if method == "tools/list":
|
||||
return web.json_response(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"result": {
|
||||
"tools": [{"name": "status", "description": "Get protected status", "inputSchema": {"type": "object", "properties": {}}}]
|
||||
},
|
||||
}
|
||||
)
|
||||
if method == "tools/call":
|
||||
return web.json_response(
|
||||
{"jsonrpc": "2.0", "id": req_id, "result": {"content": [{"type": "text", "text": f"authed-as:{token}"}], "isError": False}}
|
||||
)
|
||||
return web.json_response({"jsonrpc": "2.0", "id": req_id, "result": {}})
|
||||
|
||||
app = web.Application()
|
||||
app.router.add_get("/.well-known/oauth-protected-resource", handle_prm)
|
||||
app.router.add_get("/.well-known/oauth-authorization-server", handle_as_meta)
|
||||
app.router.add_post("/oauth/register", handle_dcr)
|
||||
app.router.add_post("/oauth/token", handle_token)
|
||||
app.router.add_post("/oauth/device", handle_device_auth)
|
||||
app.router.add_route("*", "/mcp", handle_mcp)
|
||||
runner, base_url = await _start_aiohttp_app(app)
|
||||
base_url_holder["url"] = base_url
|
||||
|
||||
try:
|
||||
registry = ToolRegistry()
|
||||
settings = Settings(DATA_DIR=tmp_path, MCP_CONFIG_FILE=tmp_path / "none.json")
|
||||
manager = MCPConnectorManager(settings=settings, registry=registry)
|
||||
|
||||
# A) Connect with auth=none -> hits 401 -> status becomes auth_required with challenge metadata!
|
||||
pkce_cfg = MCPConnectorConfig(name="saas", transport="streamable_http", url=f"{base_url}/mcp", source="bot")
|
||||
st = await manager.add_or_update_connector(pkce_cfg, connect_now=True, persist=True)
|
||||
assert st.status == "auth_required"
|
||||
assert st.oauth_challenge and "oauth-protected-resource" in (st.oauth_challenge.get("resource_metadata_url") or "")
|
||||
|
||||
# Start OAuth -> auto-upgrades to oauth2_pkce, discovers metadata, runs DCR!
|
||||
oauth_info = await manager.start_oauth("saas")
|
||||
assert oauth_info["flow"] == "pkce"
|
||||
assert "dcr-client-42" in oauth_state["registered_clients"]
|
||||
|
||||
parsed_auth_url = urlparse(oauth_info["authorize_url"])
|
||||
qs = parse_qs(parsed_auth_url.query)
|
||||
assert qs["client_id"] == ["dcr-client-42"]
|
||||
assert qs["code_challenge_method"] == ["S256"]
|
||||
oauth_state["issued_codes"]["auth-code-xyz"] = qs["code_challenge"][0]
|
||||
|
||||
# Complete PKCE by pasting full redirect URL!
|
||||
redirect_paste = f"{oauth_info['redirect_uri']}?code=auth-code-xyz&state={qs['state'][0]}"
|
||||
st2 = await manager.complete_oauth_code("saas", redirect_paste)
|
||||
assert st2.status == "connected", st2.last_error
|
||||
assert await registry.execute("mcp_saas_status", {}) == "authed-as:pkce-access-1"
|
||||
|
||||
# Simulate token invalidation on server -> client transparently refreshes via refresh_token on 401!
|
||||
oauth_state["valid_tokens"].discard("pkce-access-1")
|
||||
out_after_refresh = await registry.execute("mcp_saas_status", {})
|
||||
assert out_after_refresh == "authed-as:refreshed-access-1"
|
||||
|
||||
# Verify token file permissions are 0600
|
||||
mode = os.stat(manager.tokens_path).st_mode & 0o777
|
||||
assert mode == 0o600
|
||||
|
||||
# B) OAuth 2.0 Client Credentials (auto-discovers token_url!)
|
||||
m2m_cfg = MCPConnectorConfig(
|
||||
name="m2m",
|
||||
transport="streamable_http",
|
||||
url=f"{base_url}/mcp",
|
||||
auth=MCPAuthConfig(type="oauth2_client_credentials", client_id="m2m-id", client_secret="m2m-secret"),
|
||||
source="bot",
|
||||
)
|
||||
m2m_st = await manager.add_or_update_connector(m2m_cfg, connect_now=True, persist=True)
|
||||
assert m2m_st.status == "connected", m2m_st.last_error
|
||||
assert await registry.execute("mcp_m2m_status", {}) == "authed-as:m2m-access-1"
|
||||
|
||||
# C) OAuth 2.0 Device Flow (auto-discovers endpoints + polls pending -> token!)
|
||||
dev_cfg = MCPConnectorConfig(
|
||||
name="devflow",
|
||||
transport="streamable_http",
|
||||
url=f"{base_url}/mcp",
|
||||
auth=MCPAuthConfig(type="oauth2_device", client_id="dev-client"),
|
||||
source="bot",
|
||||
)
|
||||
await manager.add_or_update_connector(dev_cfg, connect_now=False, persist=True)
|
||||
dev_info = await manager.start_oauth("devflow")
|
||||
assert dev_info["flow"] == "device"
|
||||
assert dev_info["user_code"] == "ABCD-EFGH"
|
||||
dev_st = await manager.wait_for_device_oauth("devflow", timeout_seconds=10)
|
||||
assert dev_st.status == "connected", dev_st.last_error
|
||||
assert await registry.execute("mcp_devflow_status", {}) == "authed-as:device-access-1"
|
||||
|
||||
# D) OAuth 2.0 Refresh Token grant
|
||||
rt_cfg = MCPConnectorConfig(
|
||||
name="rtgrant",
|
||||
transport="streamable_http",
|
||||
url=f"{base_url}/mcp",
|
||||
auth=MCPAuthConfig(type="oauth2_refresh_token", refresh_token="preset-refresh-99", client_id="rt-client"),
|
||||
source="bot",
|
||||
)
|
||||
rt_st = await manager.add_or_update_connector(rt_cfg, connect_now=True, persist=True)
|
||||
assert rt_st.status == "connected", rt_st.last_error
|
||||
assert "authed-as:refreshed-access-" in await registry.execute("mcp_rtgrant_status", {})
|
||||
|
||||
await manager.close()
|
||||
finally:
|
||||
await runner.cleanup()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# 6. Config loading (JSON + YAML + MCP_CONNECTORS_JSON + persistence + stdio policy)
|
||||
# ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_config_loading_yaml_and_env_json_and_stdio_restriction(tmp_path):
|
||||
yaml_cfg = tmp_path / "mcp_connectors.yaml"
|
||||
yaml_cfg.write_text(
|
||||
textwrap.dedent(
|
||||
"""
|
||||
connectors:
|
||||
yaml_srv:
|
||||
url: https://yaml.example.com/mcp
|
||||
enabled: false
|
||||
auth:
|
||||
type: bearer
|
||||
token: yaml-tok
|
||||
"""
|
||||
).strip()
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
inline = json.dumps({"mcpServers": {"env_srv": {"url": "https://env.example.com/mcp", "disabled": True}}})
|
||||
settings = Settings(
|
||||
DATA_DIR=tmp_path / "data",
|
||||
MCP_CONFIG_FILE=yaml_cfg,
|
||||
MCP_CONNECTORS_JSON=inline,
|
||||
MCP_ALLOW_STDIO_FROM_BOT=False,
|
||||
)
|
||||
registry = ToolRegistry()
|
||||
manager = MCPConnectorManager(settings=settings, registry=registry)
|
||||
|
||||
names = {s.config.name for s in manager.list_connectors()}
|
||||
assert names == {"yaml_srv", "env_srv"}
|
||||
assert manager.get_connector("yaml_srv").status == "disabled"
|
||||
|
||||
# Bot stdio creation blocked when MCP_ALLOW_STDIO_FROM_BOT=False
|
||||
stdio_cfg = MCPConnectorConfig(name="blocked_stdio", transport="stdio", command="echo", source="bot")
|
||||
with pytest.raises(PermissionError):
|
||||
await manager.add_or_update_connector(stdio_cfg, connect_now=False, persist=True)
|
||||
|
||||
# Import JSON with markdown fences persists across fresh manager instance
|
||||
fenced = '```json\n{"mcpServers": {"imported": {"url": "https://imp.example.com/mcp", "disabled": true}}}\n```'
|
||||
states = await manager.import_from_json(fenced, connect_now=False)
|
||||
assert len(states) == 1 and states[0].config.name == "imported"
|
||||
|
||||
manager2 = MCPConnectorManager(settings=settings, registry=ToolRegistry())
|
||||
assert manager2.get_connector("imported") is not None
|
||||
await manager.close()
|
||||
await manager2.close()
|
||||
Reference in new issue
Block a user