Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d972f4b314
|
||
|
|
2b3518f873
|
||
|
|
3fde449ea7
|
||
|
|
3777ca71eb
|
||
|
|
9ac0d1aa63
|
||
|
|
ae966d7017 |
No files matched your search
+43
-3
@@ -22,9 +22,9 @@ ALLOWED_TELEGRAM_USER_IDS=
|
|||||||
GHOST_MODE_ENABLED=true
|
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
|
LLM_PROVIDER=gemini
|
||||||
|
|
||||||
# --- Вариант А: Google AI Studio (Gemini) ---
|
# --- Вариант А: Google AI Studio (Gemini) ---
|
||||||
@@ -53,6 +53,26 @@ OPENAI_BASE_URL=https://api.openai.com/v1
|
|||||||
OPENAI_MODEL=gpt-4o
|
OPENAI_MODEL=gpt-4o
|
||||||
OPENAI_SUBAGENT_MODEL=gpt-4o-mini
|
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-ассистент..."
|
# SYSTEM_INSTRUCTION="Ты — умный персональный AI-ассистент..."
|
||||||
|
|
||||||
@@ -133,7 +153,27 @@ GOOGLE_OAUTH_CREDENTIALS_FILE=credentials.json
|
|||||||
GOOGLE_OAUTH_TOKEN_FILE=data/calendar_token.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
|
||||||
|
# Опционально: HTTPS URL документа OAuth Client ID Metadata (MCP 2025-11-25 CIMD, например для Zenmoney и др.):
|
||||||
|
# MCP_OAUTH_CLIENT_METADATA_URL=https://your-domain.example/homeagent-mcp-client.json
|
||||||
|
# Включить локальный 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
|
LOG_LEVEL=INFO
|
||||||
DATA_DIR=data
|
DATA_DIR=data
|
||||||
|
|||||||
@@ -32,6 +32,9 @@ COPY main.py run.py ./
|
|||||||
# Finalize project sync
|
# Finalize project sync
|
||||||
RUN uv sync --frozen --no-dev
|
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
|
# Use the virtual environment created by uv
|
||||||
ENV PATH="/app/.venv/bin:$PATH"
|
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`.
|
- 🎟️ **Интеграция с 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**, одновременный запрос расписания сразу со **всех доступных календарей** с разметкой источников, создание и удаление событий.
|
- 📅 **Интеграция с 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`).
|
- 🎯 **Система скиллов (Skills)**: Готовые сценарии (утренняя сводка, дейли стендап, триаж Jira, планировщик недели), запускаемые по триггер-фразам или командам (`/skills`, `/briefing`, `/standup`).
|
||||||
- 🔌 **Простая разработка расширений**: Добавление нового инструмента за 2 минуты через декоратор `@tool` с авто-генерацией схемы для Gemini.
|
- 🔌 **Простая разработка расширений**: Добавление нового инструмента за 2 минуты через декоратор `@tool` с авто-генерацией схемы для Gemini.
|
||||||
|
|
||||||
@@ -112,8 +113,10 @@ homeagent/
|
|||||||
| Команда | Описание |
|
| Команда | Описание |
|
||||||
|---------|----------|
|
|---------|----------|
|
||||||
| `/start` или `/help` | Статус бота, информация о топике, количество инструментов и скиллов |
|
| `/start` или `/help` | Статус бота, информация о топике, количество инструментов и скиллов |
|
||||||
|
| `/mcp` | Интерактивное управление MCP коннекторами (мастер, OAuth, импорт JSON, статус, инструменты) |
|
||||||
| `/skills` | Список доступных скиллов с их триггерами и описанием |
|
| `/skills` | Список доступных скиллов с их триггерами и описанием |
|
||||||
| `/skill <название>` | Принудительный запуск конкретного скилла |
|
| `/skill <название>` | Принудительный запуск конкретного скилла |
|
||||||
|
| `/model [slug]` | Просмотр текущей модели и переключение модели на лету (для Antigravity) |
|
||||||
| `/memory` | Просмотр фактов, сохраненных в глобальной памяти |
|
| `/memory` | Просмотр фактов, сохраненных в глобальной памяти |
|
||||||
| `/reset` | Очистка истории диалога в текущем топике форума |
|
| `/reset` | Очистка истории диалога в текущем топике форума |
|
||||||
|
|
||||||
|
|||||||
@@ -6,11 +6,13 @@ services:
|
|||||||
container_name: homeagent
|
container_name: homeagent
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
init: true
|
init: true
|
||||||
|
user: "${HOST_UID:-1000}:${HOST_GID:-1000}"
|
||||||
env_file:
|
env_file:
|
||||||
- .env
|
- .env
|
||||||
environment:
|
environment:
|
||||||
# Application path inside the container; this must match the mount target.
|
# Application path inside the container; this must match the mount target.
|
||||||
DATA_DIR: /app/data
|
DATA_DIR: /app/data
|
||||||
|
HOME: /homeagent
|
||||||
extra_hosts:
|
extra_hosts:
|
||||||
- "host.docker.internal:host-gateway"
|
- "host.docker.internal:host-gateway"
|
||||||
volumes:
|
volumes:
|
||||||
@@ -19,3 +21,7 @@ services:
|
|||||||
- ./skills:/app/skills:ro
|
- ./skills:/app/skills:ro
|
||||||
- ./extensions:/app/extensions:ro
|
- ./extensions:/app/extensions:ro
|
||||||
- ./gcal.json:/app/gcal.json: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,122 @@
|
|||||||
|
# 🔌 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-бота (Zero-Config)
|
||||||
|
|
||||||
|
Вам **не нужно знать** транспорт (Streamable HTTP / Legacy SSE / Stdio) или тип авторизации — бот сделает всё сам:
|
||||||
|
|
||||||
|
### Способ 1: В одно сообщение или через кнопку **⚡ Подключить MCP**
|
||||||
|
Отправьте `/mcp` → **⚡ Подключить MCP** (или сразу `/mcp <что угодно>`):
|
||||||
|
- **Просто URL**: `/mcp https://mcp.linear.app/mcp`
|
||||||
|
- Бот сам придумает имя (`linear`), определит Streamable HTTP или Legacy SSE и попробует подключиться.
|
||||||
|
- Если сервер поддерживает OAuth 2.1 — бот **автоматически** выполнит discovery + Dynamic Client Registration и сразу пришлёт ссылку входа.
|
||||||
|
- Если сервер требует ключ/токен — бот попросит просто вставить его одним сообщением и **сам переберёт форматы** (`Bearer`, `X-API-Key`, `ApiKey`, `Token`, query-параметр, `Basic Auth`, кастомные заголовки) до успешного подключения!
|
||||||
|
- **URL + токен сразу**: `/mcp https://mcp.example.com/mcp мой_токен`
|
||||||
|
- **Локальная команда**: `/mcp npx -y @modelcontextprotocol/server-filesystem /tmp` (поддерживаются и `KEY=VAL` перед командой)
|
||||||
|
- **JSON-конфиг из инструкции**: `/mcp {"mcpServers": {...}}` (или одиночный `{"url": "..."}`)
|
||||||
|
- **Команда `curl` из примера**: `/mcp curl -H "X-API-Key: ..." https://...`
|
||||||
|
|
||||||
|
> Если нужен полный ручной контроль — используйте кнопку **⚙️ Ручная настройка** или команду `/mcp wizard`.
|
||||||
|
|
||||||
|
### Все команды
|
||||||
|
```text
|
||||||
|
/mcp # Меню и список
|
||||||
|
/mcp https://mcp.linear.app/mcp # Автоподключение в одно сообщение
|
||||||
|
/mcp add # Запустить быстрое автоподключение
|
||||||
|
/mcp wizard # Ручная пошаговая настройка
|
||||||
|
/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,15 @@
|
|||||||
|
{
|
||||||
|
"client_id": "https://your-public-host.example/homeagent-mcp-client.json",
|
||||||
|
"client_name": "HomeAgent",
|
||||||
|
"redirect_uris": [
|
||||||
|
"http://127.0.0.1:18765/mcp/oauth/callback"
|
||||||
|
],
|
||||||
|
"grant_types": [
|
||||||
|
"authorization_code",
|
||||||
|
"refresh_token"
|
||||||
|
],
|
||||||
|
"response_types": [
|
||||||
|
"code"
|
||||||
|
],
|
||||||
|
"token_endpoint_auth_method": "none"
|
||||||
|
}
|
||||||
@@ -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
|
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 API Key: {'[SET]' if oa_key and oa_key.get_secret_value() else '[MISSING ❌]'}")
|
||||||
print(f"OpenAI Base URL: {settings.OPENAI_BASE_URL}")
|
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:
|
else:
|
||||||
print(f"Gemini API Key: {'[SET]' if settings.GEMINI_API_KEY.get_secret_value() else '[MISSING ❌]'}")
|
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"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"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"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)
|
app = TelegramAgentApp(settings=settings)
|
||||||
tools = app.registry.list_tools()
|
tools = app.registry.list_tools()
|
||||||
skills = app.skill_manager.list_skills()
|
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)}):")
|
print(f"\n📦 Registered Tools ({len(tools)}):")
|
||||||
for t in tools:
|
for t in tools:
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
"""Agent package for HomeAgent."""
|
"""Agent package for HomeAgent."""
|
||||||
|
|
||||||
|
from homeagent.agent.antigravity import AntigravityAgent
|
||||||
from homeagent.agent.conversation import ConversationManager
|
from homeagent.agent.conversation import ConversationManager
|
||||||
from homeagent.agent.gemini import GeminiAgent
|
from homeagent.agent.gemini import GeminiAgent
|
||||||
|
|
||||||
__all__ = ["GeminiAgent", "ConversationManager"]
|
__all__ = ["AntigravityAgent", "GeminiAgent", "ConversationManager"]
|
||||||
@@ -0,0 +1,730 @@
|
|||||||
|
"""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.attachments import (
|
||||||
|
Attachment,
|
||||||
|
build_history_user_text,
|
||||||
|
format_inline_text_attachments,
|
||||||
|
stage_attachments_in_sandbox,
|
||||||
|
)
|
||||||
|
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_*`), "
|
||||||
|
"а для просмотра прикреплённых пользователем изображений, PDF, аудио и видео используй инструмент `mcp_homeagent_inspect_attachment`.\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,
|
||||||
|
attachments: Optional[list[Attachment]] = 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)
|
||||||
|
|
||||||
|
if attachments:
|
||||||
|
inline_text, binary_attachments = format_inline_text_attachments(attachments)
|
||||||
|
if inline_text:
|
||||||
|
parts.append(inline_text)
|
||||||
|
|
||||||
|
inspectable_lines: list[str] = []
|
||||||
|
other_binary_lines: list[str] = []
|
||||||
|
for att in binary_attachments:
|
||||||
|
if att.is_raster_image or att.is_pdf or att.is_audio or att.is_video:
|
||||||
|
inspectable_lines.append(
|
||||||
|
f"- ID: `{att.attachment_id}` | {att.to_summary_line()}"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
sandbox_hint = (
|
||||||
|
f" (доступен в песочнице по пути `{att.sandbox_path}`)"
|
||||||
|
if att.sandbox_path
|
||||||
|
else ""
|
||||||
|
)
|
||||||
|
other_binary_lines.append(
|
||||||
|
f"- ID: `{att.attachment_id}` | {att.to_summary_line()}{sandbox_hint}"
|
||||||
|
)
|
||||||
|
|
||||||
|
if inspectable_lines:
|
||||||
|
parts.append(
|
||||||
|
"[ВЛОЖЕНИЯ ПОЛЬЗОВАТЕЛЯ]:\n"
|
||||||
|
+ "\n".join(inspectable_lines)
|
||||||
|
+ "\nОБЯЗАТЕЛЬНО вызови инструмент `mcp_homeagent_inspect_attachment(attachment_id=...)` "
|
||||||
|
"для каждого указанного ID, чтобы просмотреть/прочитать вложение перед формированием ответа!"
|
||||||
|
)
|
||||||
|
if other_binary_lines:
|
||||||
|
parts.append(
|
||||||
|
"[БИНАРНЫЕ ФАЙЛЫ ПОЛЬЗОВАТЕЛЯ]:\n"
|
||||||
|
+ "\n".join(other_binary_lines)
|
||||||
|
+ "\nДля анализа или обработки этих файлов используй инструменты песочницы (`code_execute`, `sandbox_run_command`)."
|
||||||
|
)
|
||||||
|
|
||||||
|
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,
|
||||||
|
attachments: Optional[list[Attachment]] = 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:
|
||||||
|
staged_attachments = stage_attachments_in_sandbox(attachments, self.settings)
|
||||||
|
if staged_attachments:
|
||||||
|
self._bridge.register_attachments(staged_attachments)
|
||||||
|
|
||||||
|
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,
|
||||||
|
attachments=staged_attachments,
|
||||||
|
)
|
||||||
|
|
||||||
|
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,
|
||||||
|
attachments=staged_attachments,
|
||||||
|
)
|
||||||
|
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": build_history_user_text(user_message, staged_attachments)},
|
||||||
|
{"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()
|
||||||
@@ -0,0 +1,602 @@
|
|||||||
|
"""Multimodal attachment representation, text extraction, and sandbox staging for HomeAgent."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import io
|
||||||
|
import logging
|
||||||
|
import mimetypes
|
||||||
|
import re
|
||||||
|
import uuid
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
import zipfile
|
||||||
|
from dataclasses import dataclass, field, replace
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import TYPE_CHECKING, Optional
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from homeagent.config import Settings
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Raster image MIME types natively supported by multimodal LLMs (Gemini, OpenAI, Antigravity)
|
||||||
|
RASTER_IMAGE_MIMES = frozenset(
|
||||||
|
{
|
||||||
|
"image/jpeg",
|
||||||
|
"image/png",
|
||||||
|
"image/webp",
|
||||||
|
"image/gif",
|
||||||
|
"image/bmp",
|
||||||
|
"image/heic",
|
||||||
|
"image/heif",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
# OpenAI Chat Completions image_url supported MIME types
|
||||||
|
OPENAI_IMAGE_MIMES = frozenset(
|
||||||
|
{
|
||||||
|
"image/jpeg",
|
||||||
|
"image/png",
|
||||||
|
"image/webp",
|
||||||
|
"image/gif",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
TEXT_MIMES = frozenset(
|
||||||
|
{
|
||||||
|
"application/json",
|
||||||
|
"application/xml",
|
||||||
|
"application/javascript",
|
||||||
|
"application/x-javascript",
|
||||||
|
"application/typescript",
|
||||||
|
"application/x-yaml",
|
||||||
|
"application/yaml",
|
||||||
|
"application/toml",
|
||||||
|
"application/x-sh",
|
||||||
|
"application/x-shellscript",
|
||||||
|
"application/sql",
|
||||||
|
"application/x-python-code",
|
||||||
|
"application/xhtml+xml",
|
||||||
|
"application/csv",
|
||||||
|
"image/svg+xml",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
TEXT_EXTENSIONS = frozenset(
|
||||||
|
{
|
||||||
|
".txt",
|
||||||
|
".md",
|
||||||
|
".markdown",
|
||||||
|
".rst",
|
||||||
|
".py",
|
||||||
|
".pyi",
|
||||||
|
".js",
|
||||||
|
".mjs",
|
||||||
|
".cjs",
|
||||||
|
".ts",
|
||||||
|
".tsx",
|
||||||
|
".jsx",
|
||||||
|
".json",
|
||||||
|
".jsonl",
|
||||||
|
".ndjson",
|
||||||
|
".yaml",
|
||||||
|
".yml",
|
||||||
|
".toml",
|
||||||
|
".ini",
|
||||||
|
".cfg",
|
||||||
|
".conf",
|
||||||
|
".env",
|
||||||
|
".csv",
|
||||||
|
".tsv",
|
||||||
|
".log",
|
||||||
|
".xml",
|
||||||
|
".html",
|
||||||
|
".htm",
|
||||||
|
".css",
|
||||||
|
".scss",
|
||||||
|
".sass",
|
||||||
|
".less",
|
||||||
|
".sql",
|
||||||
|
".sh",
|
||||||
|
".bash",
|
||||||
|
".zsh",
|
||||||
|
".fish",
|
||||||
|
".ps1",
|
||||||
|
".bat",
|
||||||
|
".go",
|
||||||
|
".rs",
|
||||||
|
".java",
|
||||||
|
".kt",
|
||||||
|
".kts",
|
||||||
|
".scala",
|
||||||
|
".c",
|
||||||
|
".h",
|
||||||
|
".cpp",
|
||||||
|
".hpp",
|
||||||
|
".cc",
|
||||||
|
".cs",
|
||||||
|
".rb",
|
||||||
|
".php",
|
||||||
|
".swift",
|
||||||
|
".m",
|
||||||
|
".r",
|
||||||
|
".lua",
|
||||||
|
".pl",
|
||||||
|
".ex",
|
||||||
|
".exs",
|
||||||
|
".erl",
|
||||||
|
".hs",
|
||||||
|
".clj",
|
||||||
|
".dart",
|
||||||
|
".vue",
|
||||||
|
".svelte",
|
||||||
|
".graphql",
|
||||||
|
".gql",
|
||||||
|
".proto",
|
||||||
|
".tf",
|
||||||
|
".hcl",
|
||||||
|
".diff",
|
||||||
|
".patch",
|
||||||
|
".svg",
|
||||||
|
".dockerfile",
|
||||||
|
".gitignore",
|
||||||
|
".dockerignore",
|
||||||
|
".editorconfig",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
TEXT_FILENAMES = frozenset(
|
||||||
|
{
|
||||||
|
"dockerfile",
|
||||||
|
"makefile",
|
||||||
|
"cmakelists.txt",
|
||||||
|
"readme",
|
||||||
|
"license",
|
||||||
|
"procfile",
|
||||||
|
"gemfile",
|
||||||
|
"rakefile",
|
||||||
|
"justfile",
|
||||||
|
"vagrantfile",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
OFFICE_EXTENSIONS = frozenset({".docx", ".xlsx", ".pptx", ".odt", ".ods"})
|
||||||
|
|
||||||
|
OFFICE_MIMES = frozenset(
|
||||||
|
{
|
||||||
|
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||||
|
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
||||||
|
"application/vnd.oasis.opendocument.text",
|
||||||
|
"application/vnd.oasis.opendocument.spreadsheet",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
_MAX_OFFICE_XML_MEMBER_BYTES = 10 * 1024 * 1024 # 10 MiB safety cap per zip member
|
||||||
|
_MAX_TEXT_HEURISTIC_BYTES = 5 * 1024 * 1024 # 5 MiB cap for unknown octet-stream sniffing
|
||||||
|
|
||||||
|
|
||||||
|
def sniff_mime_from_bytes(data: bytes) -> Optional[str]:
|
||||||
|
"""Detect common binary MIME types from magic bytes."""
|
||||||
|
if not data:
|
||||||
|
return None
|
||||||
|
if data.startswith(b"\x89PNG\r\n\x1a\n"):
|
||||||
|
return "image/png"
|
||||||
|
if data.startswith(b"\xff\xd8\xff"):
|
||||||
|
return "image/jpeg"
|
||||||
|
if data.startswith((b"GIF87a", b"GIF89a")):
|
||||||
|
return "image/gif"
|
||||||
|
if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP":
|
||||||
|
return "image/webp"
|
||||||
|
if data.startswith(b"BM"):
|
||||||
|
return "image/bmp"
|
||||||
|
if data.startswith(b"%PDF-"):
|
||||||
|
return "application/pdf"
|
||||||
|
if data.startswith(b"OggS"):
|
||||||
|
return "audio/ogg"
|
||||||
|
if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WAVE":
|
||||||
|
return "audio/wav"
|
||||||
|
if data.startswith(b"fLaC"):
|
||||||
|
return "audio/flac"
|
||||||
|
if data.startswith(b"ID3") or (len(data) >= 2 and data[0] == 0xFF and (data[1] & 0xE0) == 0xE0):
|
||||||
|
return "audio/mpeg"
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_mime_type(
|
||||||
|
filename: str,
|
||||||
|
mime_type: Optional[str],
|
||||||
|
*,
|
||||||
|
data: Optional[bytes] = None,
|
||||||
|
default: str = "application/octet-stream",
|
||||||
|
) -> str:
|
||||||
|
"""Resolve and normalize a file's MIME type using magic bytes, header, and filename."""
|
||||||
|
cleaned = (mime_type or "").split(";", 1)[0].strip().lower()
|
||||||
|
if cleaned == "image/jpg":
|
||||||
|
cleaned = "image/jpeg"
|
||||||
|
if cleaned == "audio/mp3":
|
||||||
|
cleaned = "audio/mpeg"
|
||||||
|
|
||||||
|
sniffed = sniff_mime_from_bytes(data) if data else None
|
||||||
|
|
||||||
|
# Trust definitive magic bytes when MIME is missing/generic or mismatched image subtype
|
||||||
|
if sniffed:
|
||||||
|
if not cleaned or cleaned == "application/octet-stream":
|
||||||
|
return sniffed
|
||||||
|
if cleaned.startswith("image/") and sniffed.startswith("image/"):
|
||||||
|
return sniffed
|
||||||
|
|
||||||
|
if cleaned and cleaned != "application/octet-stream":
|
||||||
|
return cleaned
|
||||||
|
|
||||||
|
if filename:
|
||||||
|
guessed, _ = mimetypes.guess_type(filename)
|
||||||
|
if guessed:
|
||||||
|
guessed_clean = guessed.lower()
|
||||||
|
if guessed_clean == "image/jpg":
|
||||||
|
guessed_clean = "image/jpeg"
|
||||||
|
if guessed_clean != "application/octet-stream":
|
||||||
|
return guessed_clean
|
||||||
|
|
||||||
|
return cleaned or default
|
||||||
|
|
||||||
|
|
||||||
|
def format_size(num_bytes: int) -> str:
|
||||||
|
"""Format byte size into a compact human-readable Russian string."""
|
||||||
|
if num_bytes < 1024:
|
||||||
|
return f"{num_bytes} Б"
|
||||||
|
if num_bytes < 1024 * 1024:
|
||||||
|
return f"{num_bytes / 1024:.1f} КБ"
|
||||||
|
return f"{num_bytes / (1024 * 1024):.1f} МБ"
|
||||||
|
|
||||||
|
|
||||||
|
def _decode_text_bytes(data: bytes) -> Optional[str]:
|
||||||
|
"""Decode text bytes trying UTF-8 first, then charset_normalizer if installed."""
|
||||||
|
if b"\x00" in data[:8192]:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return data.decode("utf-8-sig")
|
||||||
|
except UnicodeDecodeError:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
from charset_normalizer import from_bytes
|
||||||
|
|
||||||
|
best = from_bytes(data).best()
|
||||||
|
if best is not None:
|
||||||
|
return str(best)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
return data.decode("cp1251")
|
||||||
|
except UnicodeDecodeError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_docx_text(zf: zipfile.ZipFile) -> str:
|
||||||
|
if "word/document.xml" not in zf.namelist():
|
||||||
|
return ""
|
||||||
|
info = zf.getinfo("word/document.xml")
|
||||||
|
if info.file_size > _MAX_OFFICE_XML_MEMBER_BYTES:
|
||||||
|
return ""
|
||||||
|
root = ET.fromstring(zf.read(info))
|
||||||
|
paragraphs: list[str] = []
|
||||||
|
for elem in root.iter():
|
||||||
|
if elem.tag.endswith("}p"):
|
||||||
|
texts = [t.text for t in elem.iter() if t.tag.endswith("}t") and t.text]
|
||||||
|
if texts:
|
||||||
|
paragraphs.append("".join(texts))
|
||||||
|
return "\n".join(paragraphs)
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_xlsx_text(zf: zipfile.ZipFile, max_rows_per_sheet: int = 200) -> str:
|
||||||
|
shared_strings: list[str] = []
|
||||||
|
if "xl/sharedStrings.xml" in zf.namelist():
|
||||||
|
info = zf.getinfo("xl/sharedStrings.xml")
|
||||||
|
if info.file_size <= _MAX_OFFICE_XML_MEMBER_BYTES:
|
||||||
|
ss_root = ET.fromstring(zf.read(info))
|
||||||
|
for si in ss_root.iter():
|
||||||
|
if si.tag.endswith("}si"):
|
||||||
|
parts = [t.text for t in si.iter() if t.tag.endswith("}t") and t.text]
|
||||||
|
shared_strings.append("".join(parts))
|
||||||
|
|
||||||
|
sheet_names = sorted(
|
||||||
|
name for name in zf.namelist() if name.startswith("xl/worksheets/sheet") and name.endswith(".xml")
|
||||||
|
)
|
||||||
|
sections: list[str] = []
|
||||||
|
for sheet_path in sheet_names[:10]:
|
||||||
|
info = zf.getinfo(sheet_path)
|
||||||
|
if info.file_size > _MAX_OFFICE_XML_MEMBER_BYTES:
|
||||||
|
continue
|
||||||
|
root = ET.fromstring(zf.read(info))
|
||||||
|
rows: list[str] = []
|
||||||
|
for row in root.iter():
|
||||||
|
if not row.tag.endswith("}row"):
|
||||||
|
continue
|
||||||
|
cells: list[str] = []
|
||||||
|
for cell in row:
|
||||||
|
if not cell.tag.endswith("}c"):
|
||||||
|
continue
|
||||||
|
cell_type = cell.attrib.get("t", "")
|
||||||
|
val = ""
|
||||||
|
if cell_type == "inlineStr":
|
||||||
|
val = "".join(t.text for t in cell.iter() if t.tag.endswith("}t") and t.text)
|
||||||
|
else:
|
||||||
|
v_elem = next((ch for ch in cell if ch.tag.endswith("}v")), None)
|
||||||
|
if v_elem is not None and v_elem.text is not None:
|
||||||
|
if cell_type == "s":
|
||||||
|
try:
|
||||||
|
val = shared_strings[int(v_elem.text)]
|
||||||
|
except (ValueError, IndexError):
|
||||||
|
val = v_elem.text
|
||||||
|
else:
|
||||||
|
val = v_elem.text
|
||||||
|
cells.append(val.replace("\t", " ").replace("\n", " "))
|
||||||
|
if any(c.strip() for c in cells):
|
||||||
|
rows.append("\t".join(cells))
|
||||||
|
if len(rows) >= max_rows_per_sheet:
|
||||||
|
rows.append(f"... [показаны первые {max_rows_per_sheet} строк]")
|
||||||
|
break
|
||||||
|
if rows:
|
||||||
|
label = Path(sheet_path).stem
|
||||||
|
sections.append(f"### Лист {label}\n" + "\n".join(rows))
|
||||||
|
return "\n\n".join(sections)
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_pptx_text(zf: zipfile.ZipFile) -> str:
|
||||||
|
slide_names = sorted(
|
||||||
|
name for name in zf.namelist() if name.startswith("ppt/slides/slide") and name.endswith(".xml")
|
||||||
|
)
|
||||||
|
slides: list[str] = []
|
||||||
|
for idx, slide_path in enumerate(slide_names[:50], 1):
|
||||||
|
info = zf.getinfo(slide_path)
|
||||||
|
if info.file_size > _MAX_OFFICE_XML_MEMBER_BYTES:
|
||||||
|
continue
|
||||||
|
root = ET.fromstring(zf.read(info))
|
||||||
|
texts = [t.text for t in root.iter() if t.tag.endswith("}t") and t.text]
|
||||||
|
if texts:
|
||||||
|
slides.append(f"### Слайд {idx}\n" + " ".join(texts))
|
||||||
|
return "\n\n".join(slides)
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_odf_text(zf: zipfile.ZipFile) -> str:
|
||||||
|
if "content.xml" not in zf.namelist():
|
||||||
|
return ""
|
||||||
|
info = zf.getinfo("content.xml")
|
||||||
|
if info.file_size > _MAX_OFFICE_XML_MEMBER_BYTES:
|
||||||
|
return ""
|
||||||
|
root = ET.fromstring(zf.read(info))
|
||||||
|
lines: list[str] = []
|
||||||
|
for elem in root.iter():
|
||||||
|
if elem.tag.endswith(("}p", "}h")):
|
||||||
|
text = "".join(elem.itertext()).strip()
|
||||||
|
if text:
|
||||||
|
lines.append(text)
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_office_text(data: bytes, ext: str, mime_type: str) -> Optional[str]:
|
||||||
|
try:
|
||||||
|
with zipfile.ZipFile(io.BytesIO(data)) as zf:
|
||||||
|
if ext == ".docx" or "wordprocessingml" in mime_type:
|
||||||
|
text = _extract_docx_text(zf)
|
||||||
|
elif ext == ".xlsx" or "spreadsheetml" in mime_type:
|
||||||
|
text = _extract_xlsx_text(zf)
|
||||||
|
elif ext == ".pptx" or "presentationml" in mime_type:
|
||||||
|
text = _extract_pptx_text(zf)
|
||||||
|
elif ext in (".odt", ".ods") or "opendocument" in mime_type:
|
||||||
|
text = _extract_odf_text(zf)
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
return text.strip() or None
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug("Failed extracting Office XML text (%s): %s", ext or mime_type, e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Attachment:
|
||||||
|
"""In-memory representation of a file or image attached to a Telegram message."""
|
||||||
|
|
||||||
|
filename: str
|
||||||
|
mime_type: str
|
||||||
|
data: bytes
|
||||||
|
kind: str = "document" # image, document, audio, voice, video, animation, sticker
|
||||||
|
source: str = "message" # message, reply
|
||||||
|
attachment_id: str = field(default_factory=lambda: uuid.uuid4().hex[:12])
|
||||||
|
sandbox_path: Optional[str] = None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def size_bytes(self) -> int:
|
||||||
|
return len(self.data)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def human_size(self) -> str:
|
||||||
|
return format_size(self.size_bytes)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def extension(self) -> str:
|
||||||
|
return Path(self.filename).suffix.lower()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_raster_image(self) -> bool:
|
||||||
|
return self.mime_type.lower() in RASTER_IMAGE_MIMES
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_pdf(self) -> bool:
|
||||||
|
return self.mime_type.lower() == "application/pdf" or self.extension == ".pdf"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_audio(self) -> bool:
|
||||||
|
return self.mime_type.lower().startswith("audio/")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_video(self) -> bool:
|
||||||
|
return self.mime_type.lower().startswith("video/")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_office_xml(self) -> bool:
|
||||||
|
return self.extension in OFFICE_EXTENSIONS or self.mime_type.lower() in OFFICE_MIMES
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_text(self) -> bool:
|
||||||
|
mime = self.mime_type.lower()
|
||||||
|
if mime.startswith("text/") or mime in TEXT_MIMES:
|
||||||
|
return True
|
||||||
|
if self.extension in TEXT_EXTENSIONS:
|
||||||
|
return True
|
||||||
|
if Path(self.filename).name.lower() in TEXT_FILENAMES:
|
||||||
|
return True
|
||||||
|
if mime == "application/octet-stream" and self.size_bytes <= _MAX_TEXT_HEURISTIC_BYTES:
|
||||||
|
if sniff_mime_from_bytes(self.data) is not None:
|
||||||
|
return False
|
||||||
|
return _decode_text_bytes(self.data) is not None
|
||||||
|
return False
|
||||||
|
|
||||||
|
def base64_data(self) -> str:
|
||||||
|
return base64.b64encode(self.data).decode("ascii")
|
||||||
|
|
||||||
|
def extract_text(self, max_chars: int = 30000) -> Optional[str]:
|
||||||
|
"""Extract UTF-8 text from plain text, code, config, or Office XML files."""
|
||||||
|
text: Optional[str] = None
|
||||||
|
if self.is_office_xml:
|
||||||
|
text = _extract_office_text(self.data, self.extension, self.mime_type.lower())
|
||||||
|
elif self.is_text:
|
||||||
|
text = _decode_text_bytes(self.data)
|
||||||
|
|
||||||
|
if text is None:
|
||||||
|
return None
|
||||||
|
if max_chars > 0 and len(text) > max_chars:
|
||||||
|
omitted = len(text) - max_chars
|
||||||
|
return (
|
||||||
|
text[:max_chars]
|
||||||
|
+ f"\n\n... [Текст обрезан: показано {max_chars} из {len(text)} символов, пропущено {omitted}]"
|
||||||
|
)
|
||||||
|
return text
|
||||||
|
|
||||||
|
def to_summary_line(self) -> str:
|
||||||
|
parts = [f"{self.filename} ({self.mime_type}, {self.human_size})"]
|
||||||
|
if self.source == "reply":
|
||||||
|
parts.append("из цитируемого сообщения")
|
||||||
|
if self.sandbox_path:
|
||||||
|
parts.append(f"в песочнице: `{self.sandbox_path}`")
|
||||||
|
return " — ".join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
def _sanitize_upload_filename(filename: str, attachment_id: str) -> str:
|
||||||
|
"""Create a safe filesystem filename without directory traversal."""
|
||||||
|
base = Path(filename or "file.bin").name
|
||||||
|
safe = re.sub(r"[^a-zA-Z0-9._-]+", "_", base).strip("._")
|
||||||
|
if not safe:
|
||||||
|
safe = "file.bin"
|
||||||
|
# Keep filename bounded
|
||||||
|
if len(safe) > 80:
|
||||||
|
stem = Path(safe).stem[:60]
|
||||||
|
suffix = Path(safe).suffix[:16]
|
||||||
|
safe = f"{stem}{suffix}"
|
||||||
|
return f"{attachment_id[:8]}_{safe}"
|
||||||
|
|
||||||
|
|
||||||
|
def stage_attachments_in_sandbox(
|
||||||
|
attachments: Optional[list[Attachment]],
|
||||||
|
settings: "Settings",
|
||||||
|
) -> list[Attachment]:
|
||||||
|
"""Copy incoming attachments into sandbox_workspace/uploads so tools can process them if needed."""
|
||||||
|
if not attachments:
|
||||||
|
return []
|
||||||
|
if not getattr(settings, "SANDBOX_ENABLED", False):
|
||||||
|
return list(attachments)
|
||||||
|
|
||||||
|
uploads_dir = settings.DATA_DIR / "sandbox_workspace" / "uploads"
|
||||||
|
try:
|
||||||
|
uploads_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Could not create sandbox uploads dir %s: %s", uploads_dir, e)
|
||||||
|
return list(attachments)
|
||||||
|
|
||||||
|
staged: list[Attachment] = []
|
||||||
|
uploads_resolved = uploads_dir.resolve()
|
||||||
|
for att in attachments:
|
||||||
|
if att.sandbox_path:
|
||||||
|
staged.append(att)
|
||||||
|
continue
|
||||||
|
safe_name = _sanitize_upload_filename(att.filename, att.attachment_id)
|
||||||
|
target = (uploads_dir / safe_name).resolve()
|
||||||
|
if not str(target).startswith(str(uploads_resolved)):
|
||||||
|
staged.append(att)
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
target.write_bytes(att.data)
|
||||||
|
staged.append(replace(att, sandbox_path=f"uploads/{safe_name}"))
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Failed staging attachment %s into sandbox: %s", att.filename, e)
|
||||||
|
staged.append(att)
|
||||||
|
return staged
|
||||||
|
|
||||||
|
|
||||||
|
def build_default_attachment_prompt(attachments: list[Attachment]) -> str:
|
||||||
|
"""Generate a helpful default Russian user prompt when media/files are sent without caption."""
|
||||||
|
if not attachments:
|
||||||
|
return ""
|
||||||
|
if all(a.is_raster_image for a in attachments):
|
||||||
|
if len(attachments) == 1:
|
||||||
|
return (
|
||||||
|
"Пользователь прикрепил изображение без подписи. "
|
||||||
|
"Внимательно изучи его, опиши содержимое и ответь по существу "
|
||||||
|
"(если на изображении есть текст, задача, ошибка или вопрос — разбери их)."
|
||||||
|
)
|
||||||
|
return (
|
||||||
|
f"Пользователь прикрепил {len(attachments)} изображений без подписи. "
|
||||||
|
"Внимательно изучи их, опиши содержимое и ответь по существу."
|
||||||
|
)
|
||||||
|
if all(a.is_audio or a.kind == "voice" for a in attachments):
|
||||||
|
return (
|
||||||
|
"Пользователь отправил голосовое/аудио сообщение без подписи. "
|
||||||
|
"Прослушай его, разбери содержание и ответь по существу."
|
||||||
|
)
|
||||||
|
if len(attachments) == 1:
|
||||||
|
return (
|
||||||
|
f"Пользователь прикрепил файл `{attachments[0].filename}` без подписи. "
|
||||||
|
"Изучи его содержимое, сделай структурированное резюме и предложи, чем можешь помочь."
|
||||||
|
)
|
||||||
|
return (
|
||||||
|
f"Пользователь прикрепил {len(attachments)} вложений без подписи. "
|
||||||
|
"Изучи их содержимое, кратко резюмируй ключевую информацию и ответь по существу."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def build_history_user_text(
|
||||||
|
user_message: str,
|
||||||
|
attachments: Optional[list[Attachment]],
|
||||||
|
) -> str:
|
||||||
|
"""Build a compact text-only turn representation safe to persist in ConversationManager."""
|
||||||
|
if not attachments:
|
||||||
|
return user_message
|
||||||
|
summary_lines = [f"- {att.to_summary_line()}" for att in attachments]
|
||||||
|
header = "[Прикреплённые вложения]:\n" + "\n".join(summary_lines)
|
||||||
|
if user_message.strip():
|
||||||
|
return f"{header}\n\n{user_message}"
|
||||||
|
return header
|
||||||
|
|
||||||
|
|
||||||
|
def format_inline_text_attachments(
|
||||||
|
attachments: list[Attachment],
|
||||||
|
*,
|
||||||
|
max_chars_per_file: int = 30000,
|
||||||
|
) -> tuple[str, list[Attachment]]:
|
||||||
|
"""Extract readable text/Office files into prompt blocks and return remaining binary attachments."""
|
||||||
|
text_blocks: list[str] = []
|
||||||
|
remaining_binary: list[Attachment] = []
|
||||||
|
|
||||||
|
for att in attachments:
|
||||||
|
extracted = att.extract_text(max_chars=max_chars_per_file)
|
||||||
|
if extracted is not None:
|
||||||
|
sandbox_hint = f" | путь в песочнице: `{att.sandbox_path}`" if att.sandbox_path else ""
|
||||||
|
source_hint = " (из цитируемого сообщения)" if att.source == "reply" else ""
|
||||||
|
text_blocks.append(
|
||||||
|
f"[Содержимое файла `{att.filename}` ({att.mime_type}, {att.human_size}){source_hint}{sandbox_hint}]:\n"
|
||||||
|
f"```\n{extracted}\n```"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
remaining_binary.append(att)
|
||||||
|
|
||||||
|
return "\n\n".join(text_blocks), remaining_binary
|
||||||
@@ -3,6 +3,8 @@
|
|||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from typing import Any, Awaitable, Callable, Optional
|
from typing import Any, Awaitable, Callable, Optional
|
||||||
|
|
||||||
|
from homeagent.agent.attachments import Attachment
|
||||||
|
|
||||||
|
|
||||||
class BaseAgent(ABC):
|
class BaseAgent(ABC):
|
||||||
"""Abstract base class for all LLM agents."""
|
"""Abstract base class for all LLM agents."""
|
||||||
@@ -15,6 +17,7 @@ class BaseAgent(ABC):
|
|||||||
user_message: str,
|
user_message: str,
|
||||||
max_tool_iterations: int = 8,
|
max_tool_iterations: int = 8,
|
||||||
on_progress: Optional[Callable[[str], Awaitable[None]]] = None,
|
on_progress: Optional[Callable[[str], Awaitable[None]]] = None,
|
||||||
|
attachments: Optional[list[Attachment]] = None,
|
||||||
) -> str:
|
) -> str:
|
||||||
"""Process user message within chat topic and execute tools as needed.
|
"""Process user message within chat topic and execute tools as needed.
|
||||||
|
|
||||||
@@ -24,8 +27,13 @@ class BaseAgent(ABC):
|
|||||||
user_message: Incoming user prompt
|
user_message: Incoming user prompt
|
||||||
max_tool_iterations: Safety cap on consecutive tool call loops
|
max_tool_iterations: Safety cap on consecutive tool call loops
|
||||||
on_progress: Optional async callback for reporting status updates to the user
|
on_progress: Optional async callback for reporting status updates to the user
|
||||||
|
attachments: Optional list of downloaded Telegram images/files attached to the turn
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Final markdown response text for the user
|
Final markdown response text for the user
|
||||||
"""
|
"""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
async def close(self) -> None:
|
||||||
|
"""Release any resources owned by the agent on application shutdown."""
|
||||||
|
return None
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
import logging
|
import logging
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
|
from homeagent.agent.antigravity import AntigravityAgent
|
||||||
from homeagent.agent.base import BaseAgent
|
from homeagent.agent.base import BaseAgent
|
||||||
from homeagent.agent.conversation import ConversationManager
|
from homeagent.agent.conversation import ConversationManager
|
||||||
from homeagent.agent.gemini import GeminiAgent
|
from homeagent.agent.gemini import GeminiAgent
|
||||||
@@ -40,6 +41,12 @@ def create_agent(
|
|||||||
conversation_manager=conversation_manager,
|
conversation_manager=conversation_manager,
|
||||||
provider_override="openai",
|
provider_override="openai",
|
||||||
)
|
)
|
||||||
|
elif provider == "antigravity":
|
||||||
|
return AntigravityAgent(
|
||||||
|
settings=settings,
|
||||||
|
registry=registry,
|
||||||
|
conversation_manager=conversation_manager,
|
||||||
|
)
|
||||||
elif provider == "gemini":
|
elif provider == "gemini":
|
||||||
return GeminiAgent(
|
return GeminiAgent(
|
||||||
settings=settings,
|
settings=settings,
|
||||||
|
|||||||
@@ -7,6 +7,12 @@ from typing import Any, Awaitable, Callable, Optional
|
|||||||
from google import genai
|
from google import genai
|
||||||
from google.genai import types
|
from google.genai import types
|
||||||
|
|
||||||
|
from homeagent.agent.attachments import (
|
||||||
|
Attachment,
|
||||||
|
build_history_user_text,
|
||||||
|
format_inline_text_attachments,
|
||||||
|
stage_attachments_in_sandbox,
|
||||||
|
)
|
||||||
from homeagent.agent.base import BaseAgent
|
from homeagent.agent.base import BaseAgent
|
||||||
from homeagent.agent.conversation import ConversationManager
|
from homeagent.agent.conversation import ConversationManager
|
||||||
from homeagent.config import Settings, get_settings
|
from homeagent.config import Settings, get_settings
|
||||||
@@ -63,6 +69,7 @@ class GeminiAgent(BaseAgent):
|
|||||||
user_message: str,
|
user_message: str,
|
||||||
max_tool_iterations: int = 8,
|
max_tool_iterations: int = 8,
|
||||||
on_progress: Optional[Callable[[str], Awaitable[None]]] = None,
|
on_progress: Optional[Callable[[str], Awaitable[None]]] = None,
|
||||||
|
attachments: Optional[list[Attachment]] = None,
|
||||||
) -> str:
|
) -> str:
|
||||||
"""Process a user message within the topic context, running tools as requested by Gemini."""
|
"""Process a user message within the topic context, running tools as requested by Gemini."""
|
||||||
if not self._client:
|
if not self._client:
|
||||||
@@ -75,14 +82,50 @@ class GeminiAgent(BaseAgent):
|
|||||||
# 1. Fetch current conversation history
|
# 1. Fetch current conversation history
|
||||||
history = list(self.conversation_manager.get_history(chat_id, thread_id))
|
history = list(self.conversation_manager.get_history(chat_id, thread_id))
|
||||||
|
|
||||||
# 2. Add current user message
|
# 2. Stage and build multimodal user message
|
||||||
user_content = types.Content(
|
staged_attachments = stage_attachments_in_sandbox(attachments, self.settings)
|
||||||
role="user",
|
user_parts: list[types.Part] = []
|
||||||
parts=[types.Part.from_text(text=user_message)],
|
|
||||||
|
if staged_attachments:
|
||||||
|
inline_text, binary_attachments = format_inline_text_attachments(staged_attachments)
|
||||||
|
text_sections: list[str] = []
|
||||||
|
if inline_text:
|
||||||
|
text_sections.append(inline_text)
|
||||||
|
|
||||||
|
binary_notes: list[str] = []
|
||||||
|
for att in binary_attachments:
|
||||||
|
if att.is_raster_image or att.is_pdf or att.is_audio or att.is_video:
|
||||||
|
user_parts.append(types.Part.from_bytes(data=att.data, mime_type=att.mime_type))
|
||||||
|
binary_notes.append(f"- Прикреплено вложение: {att.to_summary_line()}")
|
||||||
|
else:
|
||||||
|
sandbox_hint = (
|
||||||
|
f" Файл сохранён в песочнице: `{att.sandbox_path}` (можно обработать через `code_execute`)."
|
||||||
|
if att.sandbox_path
|
||||||
|
else ""
|
||||||
)
|
)
|
||||||
|
binary_notes.append(
|
||||||
|
f"- Бинарный файл (напрямую не отображается): {att.to_summary_line()}.{sandbox_hint}"
|
||||||
|
)
|
||||||
|
|
||||||
|
if binary_notes:
|
||||||
|
text_sections.append("[Вложения пользователя]:\n" + "\n".join(binary_notes))
|
||||||
|
if user_message.strip():
|
||||||
|
text_sections.append(user_message)
|
||||||
|
|
||||||
|
combined_text = "\n\n".join(text_sections) or user_message
|
||||||
|
user_parts.insert(0, types.Part.from_text(text=combined_text))
|
||||||
|
else:
|
||||||
|
user_parts.append(types.Part.from_text(text=user_message))
|
||||||
|
|
||||||
|
user_content = types.Content(role="user", parts=user_parts)
|
||||||
history.append(user_content)
|
history.append(user_content)
|
||||||
|
|
||||||
turn_contents: list[types.Content] = [user_content]
|
# Persist compact text-only turn representation (avoid storing raw base64 blobs in session JSON)
|
||||||
|
history_user_content = types.Content(
|
||||||
|
role="user",
|
||||||
|
parts=[types.Part.from_text(text=build_history_user_text(user_message, staged_attachments))],
|
||||||
|
)
|
||||||
|
turn_contents: list[types.Content] = [history_user_content]
|
||||||
system_instruction = self._build_system_instruction()
|
system_instruction = self._build_system_instruction()
|
||||||
tools_config = self._get_tools_config()
|
tools_config = self._get_tools_config()
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,482 @@
|
|||||||
|
"""In-process Streamable HTTP MCP server bridging HomeAgent ToolRegistry to Antigravity CLI."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
from collections import OrderedDict
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from aiohttp import web
|
||||||
|
|
||||||
|
from homeagent.agent.attachments import Attachment
|
||||||
|
from homeagent.tools.registry import ToolRegistry
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
EXCLUDED_SUBAGENT_TOOLS = frozenset({"spawn_subagent", "spawn_parallel_subagents"})
|
||||||
|
_MAX_STORED_ATTACHMENTS = 32
|
||||||
|
|
||||||
|
|
||||||
|
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"
|
||||||
|
ATTACHMENT_TOOL_NAME = "inspect_attachment"
|
||||||
|
|
||||||
|
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()
|
||||||
|
self._attachments: OrderedDict[str, Attachment] = OrderedDict()
|
||||||
|
|
||||||
|
def register_attachments(self, attachments: list[Attachment]) -> None:
|
||||||
|
"""Store attachments in memory so Antigravity CLI can inspect them safely via MCP."""
|
||||||
|
for att in attachments:
|
||||||
|
self._attachments[att.attachment_id] = att
|
||||||
|
self._attachments.move_to_end(att.attachment_id)
|
||||||
|
while len(self._attachments) > _MAX_STORED_ATTACHMENTS:
|
||||||
|
self._attachments.popitem(last=False)
|
||||||
|
|
||||||
|
def get_attachment(self, attachment_id: str) -> Optional[Attachment]:
|
||||||
|
return self._attachments.get(attachment_id)
|
||||||
|
|
||||||
|
def clear_attachments(self) -> None:
|
||||||
|
self._attachments.clear()
|
||||||
|
|
||||||
|
def _build_attachment_tool_definition(self) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"name": self.ATTACHMENT_TOOL_NAME,
|
||||||
|
"description": (
|
||||||
|
"Получить и просмотреть вложение (изображение, скриншот, PDF, аудио, видео или документ), "
|
||||||
|
"прикреплённое пользователем в Telegram, по его `attachment_id`. "
|
||||||
|
"Возвращает нативный мультимодальный контент (image/resource/text) без доступа к файловой системе хоста."
|
||||||
|
),
|
||||||
|
"inputSchema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"attachment_id": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Идентификатор вложения из блока [ВЛОЖЕНИЯ ПОЛЬЗОВАТЕЛЯ].",
|
||||||
|
},
|
||||||
|
"max_chars": {
|
||||||
|
"type": "integer",
|
||||||
|
"description": "Максимальное число символов для текстовых файлов (по умолчанию 30000).",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"required": ["attachment_id"],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
def _handle_inspect_attachment(self, arguments: dict[str, Any]) -> tuple[list[dict[str, Any]], bool]:
|
||||||
|
attachment_id = str(arguments.get("attachment_id") or "").strip()
|
||||||
|
if not attachment_id:
|
||||||
|
return ([{"type": "text", "text": "Ошибка: необходимо указать параметр `attachment_id`."}], True)
|
||||||
|
|
||||||
|
att = self._attachments.get(attachment_id)
|
||||||
|
if att is None:
|
||||||
|
available = ", ".join(self._attachments.keys()) or "нет доступных вложений"
|
||||||
|
return (
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"type": "text",
|
||||||
|
"text": f"Ошибка: вложение с ID '{attachment_id}' не найдено. Доступные ID: {available}.",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
True,
|
||||||
|
)
|
||||||
|
|
||||||
|
raw_max_chars = arguments.get("max_chars", 30000)
|
||||||
|
try:
|
||||||
|
max_chars = max(500, min(int(raw_max_chars), 100000))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
max_chars = 30000
|
||||||
|
|
||||||
|
if att.is_raster_image:
|
||||||
|
return (
|
||||||
|
[
|
||||||
|
{"type": "text", "text": f"Изображение пользователя: {att.to_summary_line()}"},
|
||||||
|
{
|
||||||
|
"type": "image",
|
||||||
|
"data": att.base64_data(),
|
||||||
|
"mimeType": att.mime_type,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
False,
|
||||||
|
)
|
||||||
|
|
||||||
|
if att.is_pdf or att.is_audio or att.is_video:
|
||||||
|
return (
|
||||||
|
[
|
||||||
|
{"type": "text", "text": f"Мультимедийный/PDF файл пользователя: {att.to_summary_line()}"},
|
||||||
|
{
|
||||||
|
"type": "resource",
|
||||||
|
"resource": {
|
||||||
|
"uri": f"attachment://{att.attachment_id}/{att.filename}",
|
||||||
|
"mimeType": att.mime_type,
|
||||||
|
"blob": att.base64_data(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
False,
|
||||||
|
)
|
||||||
|
|
||||||
|
extracted = att.extract_text(max_chars=max_chars)
|
||||||
|
if extracted is not None:
|
||||||
|
return (
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"type": "text",
|
||||||
|
"text": f"Файл пользователя: {att.to_summary_line()}\n\n{extracted}",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
False,
|
||||||
|
)
|
||||||
|
|
||||||
|
sandbox_hint = (
|
||||||
|
f" Файл сохранён в изолированной песочнице по пути `{att.sandbox_path}` — "
|
||||||
|
"вы можете обработать его через `code_execute` или `sandbox_run_command`."
|
||||||
|
if att.sandbox_path
|
||||||
|
else ""
|
||||||
|
)
|
||||||
|
return (
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"type": "text",
|
||||||
|
"text": f"Бинарный файл пользователя: {att.to_summary_line()}.{sandbox_hint}",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
False,
|
||||||
|
)
|
||||||
|
|
||||||
|
@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}
|
||||||
|
if not subagent and self._attachments:
|
||||||
|
tools_config[self.ATTACHMENT_TOOL_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,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
if not exclude_subagents and self._attachments:
|
||||||
|
tools_payload.append(self._build_attachment_tool_definition())
|
||||||
|
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 tool_name == self.ATTACHMENT_TOOL_NAME and not exclude_subagents:
|
||||||
|
content_blocks, is_error = self._handle_inspect_attachment(arguments)
|
||||||
|
return web.json_response(
|
||||||
|
{
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": req_id,
|
||||||
|
"result": {
|
||||||
|
"content": content_blocks,
|
||||||
|
"isError": is_error,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
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}"},
|
||||||
|
}
|
||||||
|
)
|
||||||
@@ -8,6 +8,13 @@ from typing import Any, Awaitable, Callable, Optional
|
|||||||
import openai
|
import openai
|
||||||
from openai import AsyncOpenAI
|
from openai import AsyncOpenAI
|
||||||
|
|
||||||
|
from homeagent.agent.attachments import (
|
||||||
|
OPENAI_IMAGE_MIMES,
|
||||||
|
Attachment,
|
||||||
|
build_history_user_text,
|
||||||
|
format_inline_text_attachments,
|
||||||
|
stage_attachments_in_sandbox,
|
||||||
|
)
|
||||||
from homeagent.agent.base import BaseAgent
|
from homeagent.agent.base import BaseAgent
|
||||||
from homeagent.agent.conversation import ConversationManager
|
from homeagent.agent.conversation import ConversationManager
|
||||||
from homeagent.config import Settings, get_settings
|
from homeagent.config import Settings, get_settings
|
||||||
@@ -71,6 +78,93 @@ class OpenAIAgent(BaseAgent):
|
|||||||
|
|
||||||
return "\n\n".join(parts)
|
return "\n\n".join(parts)
|
||||||
|
|
||||||
|
def _build_user_turn(
|
||||||
|
self,
|
||||||
|
user_message: str,
|
||||||
|
attachments: list[Attachment],
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Build an OpenAI/DeepSeek user message payload supporting images, PDFs, audio, and text files."""
|
||||||
|
if not attachments:
|
||||||
|
return {"role": "user", "content": user_message}
|
||||||
|
|
||||||
|
inline_text, binary_attachments = format_inline_text_attachments(attachments)
|
||||||
|
text_sections: list[str] = []
|
||||||
|
if inline_text:
|
||||||
|
text_sections.append(inline_text)
|
||||||
|
|
||||||
|
multimodal_blocks: list[dict[str, Any]] = []
|
||||||
|
notes: list[str] = []
|
||||||
|
|
||||||
|
if self.provider == "deepseek":
|
||||||
|
# DeepSeek Chat Completions API is text-only; avoid sending image_url/file blocks that return HTTP 400
|
||||||
|
for att in binary_attachments:
|
||||||
|
sandbox_hint = (
|
||||||
|
f" Файл сохранён в песочнице: `{att.sandbox_path}` — при необходимости можно обработать его через `code_execute`."
|
||||||
|
if att.sandbox_path
|
||||||
|
else ""
|
||||||
|
)
|
||||||
|
notes.append(
|
||||||
|
f"- Бинарное вложение {att.to_summary_line()} (активный провайдер DeepSeek текстовый и не принимает "
|
||||||
|
f"изображения/PDF/аудио напрямую; для анализа картинок переключитесь на Gemini, OpenAI или Antigravity).{sandbox_hint}"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
for att in binary_attachments:
|
||||||
|
mime = att.mime_type.lower()
|
||||||
|
if mime in OPENAI_IMAGE_MIMES:
|
||||||
|
multimodal_blocks.append(
|
||||||
|
{
|
||||||
|
"type": "image_url",
|
||||||
|
"image_url": {"url": f"data:{mime};base64,{att.base64_data()}"},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
notes.append(f"- Прикреплено изображение: {att.to_summary_line()}")
|
||||||
|
elif att.is_pdf:
|
||||||
|
multimodal_blocks.append(
|
||||||
|
{
|
||||||
|
"type": "file",
|
||||||
|
"file": {
|
||||||
|
"filename": att.filename,
|
||||||
|
"file_data": f"data:application/pdf;base64,{att.base64_data()}",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
notes.append(f"- Прикреплён PDF-документ: {att.to_summary_line()}")
|
||||||
|
elif mime in ("audio/wav", "audio/x-wav", "audio/mpeg", "audio/mp3"):
|
||||||
|
audio_fmt = "wav" if "wav" in mime else "mp3"
|
||||||
|
multimodal_blocks.append(
|
||||||
|
{
|
||||||
|
"type": "input_audio",
|
||||||
|
"input_audio": {
|
||||||
|
"data": att.base64_data(),
|
||||||
|
"format": audio_fmt,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
notes.append(f"- Прикреплено аудио: {att.to_summary_line()}")
|
||||||
|
else:
|
||||||
|
sandbox_hint = (
|
||||||
|
f" Файл сохранён в песочнице: `{att.sandbox_path}` (можно обработать через `code_execute`)."
|
||||||
|
if att.sandbox_path
|
||||||
|
else ""
|
||||||
|
)
|
||||||
|
notes.append(
|
||||||
|
f"- Вложение `{att.filename}` ({att.mime_type}, {att.human_size}) не поддерживается напрямую "
|
||||||
|
f"форматом OpenAI Chat Completions.{sandbox_hint}"
|
||||||
|
)
|
||||||
|
|
||||||
|
if notes:
|
||||||
|
text_sections.append("[Вложения пользователя]:\n" + "\n".join(notes))
|
||||||
|
if user_message.strip():
|
||||||
|
text_sections.append(user_message)
|
||||||
|
|
||||||
|
combined_text = "\n\n".join(text_sections) or user_message
|
||||||
|
if multimodal_blocks:
|
||||||
|
return {
|
||||||
|
"role": "user",
|
||||||
|
"content": [{"type": "text", "text": combined_text}, *multimodal_blocks],
|
||||||
|
}
|
||||||
|
return {"role": "user", "content": combined_text}
|
||||||
|
|
||||||
async def chat(
|
async def chat(
|
||||||
self,
|
self,
|
||||||
chat_id: int,
|
chat_id: int,
|
||||||
@@ -78,6 +172,7 @@ class OpenAIAgent(BaseAgent):
|
|||||||
user_message: str,
|
user_message: str,
|
||||||
max_tool_iterations: int = 100,
|
max_tool_iterations: int = 100,
|
||||||
on_progress: Optional[Callable[[str], Awaitable[None]]] = None,
|
on_progress: Optional[Callable[[str], Awaitable[None]]] = None,
|
||||||
|
attachments: Optional[list[Attachment]] = None,
|
||||||
) -> str:
|
) -> str:
|
||||||
"""Process user message within topic context using DeepSeek / OpenAI API."""
|
"""Process user message within topic context using DeepSeek / OpenAI API."""
|
||||||
if not self._client:
|
if not self._client:
|
||||||
@@ -107,8 +202,9 @@ class OpenAIAgent(BaseAgent):
|
|||||||
# 1. Fetch current conversation history
|
# 1. Fetch current conversation history
|
||||||
history = list(self.conversation_manager.get_openai_messages(chat_id, thread_id))
|
history = list(self.conversation_manager.get_openai_messages(chat_id, thread_id))
|
||||||
|
|
||||||
# 2. Add current user message
|
# 2. Stage attachments and build current user message
|
||||||
user_turn: dict[str, Any] = {"role": "user", "content": user_message}
|
staged_attachments = stage_attachments_in_sandbox(attachments, self.settings)
|
||||||
|
user_turn = self._build_user_turn(user_message, staged_attachments)
|
||||||
history.append(user_turn)
|
history.append(user_turn)
|
||||||
|
|
||||||
system_instruction = self._build_system_instruction()
|
system_instruction = self._build_system_instruction()
|
||||||
@@ -117,7 +213,12 @@ class OpenAIAgent(BaseAgent):
|
|||||||
*history,
|
*history,
|
||||||
]
|
]
|
||||||
|
|
||||||
turn_sequence: list[dict[str, Any]] = [user_turn]
|
# Persist compact text-only turn representation (avoid storing megabyte base64 payloads in session JSON)
|
||||||
|
history_user_turn: dict[str, Any] = {
|
||||||
|
"role": "user",
|
||||||
|
"content": build_history_user_text(user_message, staged_attachments),
|
||||||
|
}
|
||||||
|
turn_sequence: list[dict[str, Any]] = [history_user_turn]
|
||||||
tools = self.registry.get_openai_tools()
|
tools = self.registry.get_openai_tools()
|
||||||
|
|
||||||
for iteration in range(max_tool_iterations):
|
for iteration in range(max_tool_iterations):
|
||||||
|
|||||||
@@ -70,13 +70,19 @@ class SubagentRunner:
|
|||||||
for tool_def in self.registry.list_tools():
|
for tool_def in self.registry.list_tools():
|
||||||
if tool_def.name in ("spawn_subagent", "spawn_parallel_subagents"):
|
if tool_def.name in ("spawn_subagent", "spawn_parallel_subagents"):
|
||||||
continue
|
continue
|
||||||
declarations.append(
|
try:
|
||||||
types.FunctionDeclaration(
|
fd = types.FunctionDeclaration(
|
||||||
name=tool_def.name,
|
name=tool_def.name,
|
||||||
description=tool_def.description,
|
description=tool_def.description,
|
||||||
parameters=tool_def.parameters_schema,
|
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:
|
if not declarations:
|
||||||
return None
|
return None
|
||||||
return [types.Tool(function_declarations=declarations)]
|
return [types.Tool(function_declarations=declarations)]
|
||||||
@@ -241,6 +247,30 @@ class SubagentRunner:
|
|||||||
|
|
||||||
return f"Подагент ({role}) достиг лимита итераций без итогового ответа."
|
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(
|
async def run_task(
|
||||||
self,
|
self,
|
||||||
task: str,
|
task: str,
|
||||||
@@ -253,6 +283,10 @@ class SubagentRunner:
|
|||||||
return await self._run_task_gemini(
|
return await self._run_task_gemini(
|
||||||
task=task, role=role, context=context, max_tool_iterations=max_tool_iterations
|
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:
|
else:
|
||||||
return await self._run_task_openai(
|
return await self._run_task_openai(
|
||||||
task=task, role=role, context=context, max_tool_iterations=max_tool_iterations
|
task=task, role=role, context=context, max_tool_iterations=max_tool_iterations
|
||||||
|
|||||||
+227
-30
@@ -10,6 +10,7 @@ from aiogram import Bot, Router
|
|||||||
from aiogram.enums import ChatAction, ParseMode
|
from aiogram.enums import ChatAction, ParseMode
|
||||||
from aiogram.filters import Command
|
from aiogram.filters import Command
|
||||||
from aiogram.types import (
|
from aiogram.types import (
|
||||||
|
InlineKeyboardMarkup,
|
||||||
InlineQueryResultArticle,
|
InlineQueryResultArticle,
|
||||||
InputRichMessage,
|
InputRichMessage,
|
||||||
InputRichMessageContent,
|
InputRichMessageContent,
|
||||||
@@ -17,10 +18,14 @@ from aiogram.types import (
|
|||||||
Message,
|
Message,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
from homeagent.agent.attachments import Attachment, build_default_attachment_prompt
|
||||||
from homeagent.agent.base import BaseAgent
|
from homeagent.agent.base import BaseAgent
|
||||||
|
from homeagent.bot.mcp_handlers import MCPBotController
|
||||||
|
from homeagent.bot.media import MediaGroupBuffer, extract_message_attachments, has_supported_media
|
||||||
from homeagent.bot.progress import ProgressReporter
|
from homeagent.bot.progress import ProgressReporter
|
||||||
from homeagent.bot.utils import split_message
|
from homeagent.bot.utils import split_message
|
||||||
from homeagent.config import Settings
|
from homeagent.config import Settings
|
||||||
|
from homeagent.mcp.manager import MCPConnectorManager
|
||||||
from homeagent.memory.global_memory import get_global_memory
|
from homeagent.memory.global_memory import get_global_memory
|
||||||
from homeagent.skills.manager import SkillManager
|
from homeagent.skills.manager import SkillManager
|
||||||
from homeagent.tools.registry import ToolRegistry
|
from homeagent.tools.registry import ToolRegistry
|
||||||
@@ -49,9 +54,12 @@ def create_bot_router(
|
|||||||
agent: BaseAgent,
|
agent: BaseAgent,
|
||||||
skill_manager: SkillManager,
|
skill_manager: SkillManager,
|
||||||
tool_registry: ToolRegistry,
|
tool_registry: ToolRegistry,
|
||||||
|
mcp_manager: Optional[MCPConnectorManager] = None,
|
||||||
) -> Router:
|
) -> Router:
|
||||||
"""Create and configure the main Aiogram Router."""
|
"""Create and configure the main Aiogram Router."""
|
||||||
router = Router(name="main_router")
|
router = Router(name="main_router")
|
||||||
|
mcp_controller = MCPBotController(mcp_manager, _send_reply) if mcp_manager is not None else None
|
||||||
|
media_group_buffer = MediaGroupBuffer()
|
||||||
|
|
||||||
@router.message(Command("start", "help"))
|
@router.message(Command("start", "help"))
|
||||||
async def handle_start(message: Message) -> None:
|
async def handle_start(message: Message) -> None:
|
||||||
@@ -61,6 +69,8 @@ def create_bot_router(
|
|||||||
|
|
||||||
skills = skill_manager.list_skills()
|
skills = skill_manager.list_skills()
|
||||||
tools = tool_registry.list_tools()
|
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 = (
|
greeting = (
|
||||||
f"👋 **Привет! Я твой персональный AI-ассистент.**\n\n"
|
f"👋 **Привет! Я твой персональный AI-ассистент.**\n\n"
|
||||||
@@ -71,15 +81,19 @@ def create_bot_router(
|
|||||||
f"- Главная модель (Orchestrator): `{settings.get_active_model()}`\n"
|
f"- Главная модель (Orchestrator): `{settings.get_active_model()}`\n"
|
||||||
f"- Модель быстрых подагентов: `{settings.get_active_subagent_model()}`\n"
|
f"- Модель быстрых подагентов: `{settings.get_active_subagent_model()}`\n"
|
||||||
f"- Доступно скиллов: **{len(skills)}** (введите `/skills`)\n"
|
f"- Доступно скиллов: **{len(skills)}** (введите `/skills`)\n"
|
||||||
|
f"- MCP коннекторов: **{mcp_connected}/{len(mcp_states)}** (введите `/mcp`)\n"
|
||||||
f"- Доступно инструментов: **{len(tools)}**\n\n"
|
f"- Доступно инструментов: **{len(tools)}**\n\n"
|
||||||
f"📋 **Полезные команды:**\n"
|
f"📋 **Полезные команды:**\n"
|
||||||
|
f"• `/mcp` — подключить и настроить MCP коннекторы\n"
|
||||||
f"• `/skills` — список готовых скиллов и триггеров\n"
|
f"• `/skills` — список готовых скиллов и триггеров\n"
|
||||||
f"• `/skill <название>` — запустить конкретный скилл\n"
|
f"• `/skill <название>` — запустить конкретный скилл\n"
|
||||||
|
f"• `/model` — текущая модель (и переключение для Antigravity)\n"
|
||||||
f"• `/memory` — посмотреть факты в глобальной памяти\n"
|
f"• `/memory` — посмотреть факты в глобальной памяти\n"
|
||||||
f"• `/reset` — очистить контекст диалога в текущем топике\n"
|
f"• `/reset` — очистить контекст диалога в текущем топике\n"
|
||||||
f"• `/help` — показать это сообщение\n\n"
|
f"• `/help` — показать это сообщение\n\n"
|
||||||
f"Просто напиши мне любой вопрос или команду, например:\n"
|
f"Просто напиши мне любой вопрос или команду, например:\n"
|
||||||
f"_«Какие у меня созвоны на сегодня?»_ или _«Сделай утренний план»_."
|
f"_«Какие у меня созвоны на сегодня?»_ или _«Сделай утренний план»_.\n"
|
||||||
|
f"📎 Также можно присылать **фото, скриншоты, PDF, документы (DOCX/XLSX/PPTX), код, логи и аудио/голосовые** — с подписью или без."
|
||||||
)
|
)
|
||||||
await _send_reply(message, greeting)
|
await _send_reply(message, greeting)
|
||||||
|
|
||||||
@@ -120,6 +134,53 @@ def create_bot_router(
|
|||||||
lines.append("\n_Эти данные автоматически подмешиваются в системный промпт во всех топиках._")
|
lines.append("\n_Эти данные автоматически подмешиваются в системный промпт во всех топиках._")
|
||||||
await _send_reply(message, "\n".join(lines))
|
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"))
|
@router.message(Command("reset"))
|
||||||
async def handle_reset(message: Message) -> None:
|
async def handle_reset(message: Message) -> None:
|
||||||
chat_id = message.chat.id
|
chat_id = message.chat.id
|
||||||
@@ -131,38 +192,106 @@ def create_bot_router(
|
|||||||
f"🧹 Контекст диалога {topic_info} успешно очищен. Глобальная память сохранена.",
|
f"🧹 Контекст диалога {topic_info} успешно очищен. Глобальная память сохранена.",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if mcp_controller is not None:
|
||||||
|
mcp_controller.register_handlers(router)
|
||||||
|
|
||||||
@router.message()
|
@router.message()
|
||||||
async def handle_message(message: Message) -> None:
|
async def handle_message(message: Message) -> None:
|
||||||
text = message.text or message.caption or ""
|
if mcp_controller is not None and await mcp_controller.handle_wizard_message(message):
|
||||||
if not text.strip():
|
return
|
||||||
|
|
||||||
|
grouped_messages = await media_group_buffer.collect(message)
|
||||||
|
if grouped_messages is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
text_parts = [
|
||||||
|
(m.text or m.caption or "").strip()
|
||||||
|
for m in grouped_messages
|
||||||
|
if (m.text or m.caption or "").strip()
|
||||||
|
]
|
||||||
|
text = "\n".join(text_parts)
|
||||||
|
|
||||||
|
reply_msg = message.reply_to_message
|
||||||
|
has_msg_media = any(has_supported_media(m) for m in grouped_messages)
|
||||||
|
has_reply_media = bool(reply_msg and has_supported_media(reply_msg))
|
||||||
|
has_media = has_msg_media or has_reply_media
|
||||||
|
|
||||||
|
if not text and not has_media:
|
||||||
return
|
return
|
||||||
|
|
||||||
chat_id = message.chat.id
|
chat_id = message.chat.id
|
||||||
thread_id = message.message_thread_id
|
thread_id = message.message_thread_id
|
||||||
|
active_bot = message.bot
|
||||||
|
|
||||||
# 1. Check if the message triggers a skill
|
max_size_bytes = max(1, int(settings.MAX_ATTACHMENT_SIZE_MB)) * 1024 * 1024
|
||||||
matched = skill_manager.match_trigger(text)
|
max_count = max(1, int(settings.MAX_ATTACHMENTS_PER_MESSAGE))
|
||||||
|
|
||||||
|
# 1. Show typing indicator and dynamic progress message while downloading / thinking
|
||||||
|
typing_task = asyncio.create_task(_keep_typing(message))
|
||||||
|
progress = ProgressReporter(bot=active_bot, chat_id=chat_id, thread_id=thread_id) if active_bot else None
|
||||||
|
if progress is not None:
|
||||||
|
await progress.start("📥 Загружаю вложения..." if has_media else "⏳ Думаю...")
|
||||||
|
|
||||||
|
attachments: list[Attachment] = []
|
||||||
|
warnings: list[str] = []
|
||||||
|
try:
|
||||||
|
if has_msg_media and active_bot is not None:
|
||||||
|
msg_atts, msg_warns = await extract_message_attachments(
|
||||||
|
active_bot,
|
||||||
|
grouped_messages,
|
||||||
|
max_size_bytes=max_size_bytes,
|
||||||
|
max_count=max_count,
|
||||||
|
source="message",
|
||||||
|
)
|
||||||
|
attachments.extend(msg_atts)
|
||||||
|
warnings.extend(msg_warns)
|
||||||
|
|
||||||
|
if has_reply_media and reply_msg is not None and active_bot is not None and len(attachments) < max_count:
|
||||||
|
reply_atts, reply_warns = await extract_message_attachments(
|
||||||
|
active_bot,
|
||||||
|
[reply_msg],
|
||||||
|
max_size_bytes=max_size_bytes,
|
||||||
|
max_count=max_count - len(attachments),
|
||||||
|
source="reply",
|
||||||
|
)
|
||||||
|
attachments.extend(reply_atts)
|
||||||
|
warnings.extend(reply_warns)
|
||||||
|
|
||||||
|
if not text and not attachments:
|
||||||
|
if warnings:
|
||||||
|
warning_text = "\n".join(f"⚠️ {w}" for w in warnings)
|
||||||
|
await _send_reply(message, warning_text)
|
||||||
|
return
|
||||||
|
|
||||||
|
# 2. Check if the message triggers a skill
|
||||||
|
matched = skill_manager.match_trigger(text) if text else None
|
||||||
if matched:
|
if matched:
|
||||||
skill, extra_args = matched
|
skill, extra_args = matched
|
||||||
prompt_to_run = skill.render(extra_instructions=extra_args)
|
prompt_to_run = skill.render(extra_instructions=extra_args)
|
||||||
logger.info("Executing skill '%s' for chat=%d, thread=%s", skill.name, chat_id, thread_id)
|
logger.info("Executing skill '%s' for chat=%d, thread=%s", skill.name, chat_id, thread_id)
|
||||||
else:
|
elif text:
|
||||||
prompt_to_run = text
|
prompt_to_run = text
|
||||||
|
else:
|
||||||
|
prompt_to_run = build_default_attachment_prompt(attachments)
|
||||||
|
|
||||||
# 2. Show typing indicator and dynamic progress message while agent is working
|
if warnings:
|
||||||
typing_task = asyncio.create_task(_keep_typing(message))
|
prompt_to_run += "\n\n[Предупреждения при загрузке вложений]:\n" + "\n".join(
|
||||||
progress = ProgressReporter(bot=message.bot, chat_id=chat_id, thread_id=thread_id)
|
f"- {w}" for w in warnings
|
||||||
await progress.start("⏳ Думаю...")
|
|
||||||
|
|
||||||
try:
|
|
||||||
response_text = await agent.chat(
|
|
||||||
chat_id=chat_id,
|
|
||||||
thread_id=thread_id,
|
|
||||||
user_message=prompt_to_run,
|
|
||||||
on_progress=progress.update,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
chat_kwargs: dict[str, object] = {
|
||||||
|
"chat_id": chat_id,
|
||||||
|
"thread_id": thread_id,
|
||||||
|
"user_message": prompt_to_run,
|
||||||
|
"on_progress": progress.update if progress is not None else None,
|
||||||
|
}
|
||||||
|
if attachments:
|
||||||
|
chat_kwargs["attachments"] = attachments
|
||||||
|
|
||||||
|
response_text = await agent.chat(**chat_kwargs) # type: ignore[arg-type]
|
||||||
finally:
|
finally:
|
||||||
typing_task.cancel()
|
typing_task.cancel()
|
||||||
|
if progress is not None:
|
||||||
await progress.finish()
|
await progress.finish()
|
||||||
|
|
||||||
# 3. Split and send chunks strictly as Rich Messages (up to 32K chars)
|
# 3. Split and send chunks strictly as Rich Messages (up to 32K chars)
|
||||||
@@ -259,11 +388,16 @@ def create_bot_router(
|
|||||||
f"💡 **Как меня использовать:**\n"
|
f"💡 **Как меня использовать:**\n"
|
||||||
f"• Упомяните `{bot_tag} <ваш вопрос>` с любой задачей или вопросом.\n"
|
f"• Упомяните `{bot_tag} <ваш вопрос>` с любой задачей или вопросом.\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)
|
await _send_guest_reply(active_bot, guest_query_id, help_msg)
|
||||||
return
|
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":
|
if cmd_lower == "/skills":
|
||||||
skills = skill_manager.list_skills()
|
skills = skill_manager.list_skills()
|
||||||
if not skills:
|
if not skills:
|
||||||
@@ -298,6 +432,11 @@ def create_bot_router(
|
|||||||
await _send_guest_reply(active_bot, guest_query_id, "\n".join(lines))
|
await _send_guest_reply(active_bot, guest_query_id, "\n".join(lines))
|
||||||
return
|
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":
|
if cmd_lower == "/reset":
|
||||||
agent.conversation_manager.clear(chat_id, thread_id)
|
agent.conversation_manager.clear(chat_id, thread_id)
|
||||||
topic_info = f"в топике #{thread_id}" if thread_id else "в этом чате"
|
topic_info = f"в топике #{thread_id}" if thread_id else "в этом чате"
|
||||||
@@ -308,19 +447,54 @@ def create_bot_router(
|
|||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
# If empty text and no reply context
|
# Extract media/file attachments from the guest message and/or replied message
|
||||||
if not cleaned_text and not reply_context:
|
attachments: list[Attachment] = []
|
||||||
|
warnings: list[str] = []
|
||||||
|
max_size_bytes = max(1, int(settings.MAX_ATTACHMENT_SIZE_MB)) * 1024 * 1024
|
||||||
|
max_count = max(1, int(settings.MAX_ATTACHMENTS_PER_MESSAGE))
|
||||||
|
|
||||||
|
if has_supported_media(message):
|
||||||
|
msg_atts, msg_warns = await extract_message_attachments(
|
||||||
|
active_bot,
|
||||||
|
[message],
|
||||||
|
max_size_bytes=max_size_bytes,
|
||||||
|
max_count=max_count,
|
||||||
|
source="message",
|
||||||
|
)
|
||||||
|
attachments.extend(msg_atts)
|
||||||
|
warnings.extend(msg_warns)
|
||||||
|
|
||||||
|
if (
|
||||||
|
message.reply_to_message
|
||||||
|
and has_supported_media(message.reply_to_message)
|
||||||
|
and len(attachments) < max_count
|
||||||
|
):
|
||||||
|
reply_atts, reply_warns = await extract_message_attachments(
|
||||||
|
active_bot,
|
||||||
|
[message.reply_to_message],
|
||||||
|
max_size_bytes=max_size_bytes,
|
||||||
|
max_count=max_count - len(attachments),
|
||||||
|
source="reply",
|
||||||
|
)
|
||||||
|
attachments.extend(reply_atts)
|
||||||
|
warnings.extend(reply_warns)
|
||||||
|
|
||||||
|
# If empty text, no reply context, and no attachments
|
||||||
|
if not cleaned_text and not reply_context and not attachments:
|
||||||
|
if warnings:
|
||||||
|
await _send_guest_reply(active_bot, guest_query_id, "\n".join(f"⚠️ {w}" for w in warnings))
|
||||||
|
return
|
||||||
bot_tag = f"@{bot_username}" if bot_username else "@bot"
|
bot_tag = f"@{bot_username}" if bot_username else "@bot"
|
||||||
welcome_msg = (
|
welcome_msg = (
|
||||||
f"👋 **Привет! Я персональный AI-ассистент HomeAgent (Ghost Mode).**\n\n"
|
f"👋 **Привет! Я персональный AI-ассистент HomeAgent (Ghost Mode).**\n\n"
|
||||||
f"Я отвечаю в чатах без необходимости добавления в участники.\n"
|
f"Я отвечаю в чатах без необходимости добавления в участники.\n"
|
||||||
f"Напишите `{bot_tag} <вопрос>` или ответьте моим тегом на любое сообщение!"
|
f"Напишите `{bot_tag} <вопрос>` или ответьте моим тегом на любое сообщение, фото или файл!"
|
||||||
)
|
)
|
||||||
await _send_guest_reply(active_bot, guest_query_id, welcome_msg)
|
await _send_guest_reply(active_bot, guest_query_id, welcome_msg)
|
||||||
return
|
return
|
||||||
|
|
||||||
# 2. Check if the message triggers a skill
|
# 2. Check if the message triggers a skill
|
||||||
matched = skill_manager.match_trigger(cleaned_text)
|
matched = skill_manager.match_trigger(cleaned_text) if cleaned_text else None
|
||||||
if matched:
|
if matched:
|
||||||
skill, extra_args = matched
|
skill, extra_args = matched
|
||||||
prompt_to_run = skill.render(extra_instructions=extra_args)
|
prompt_to_run = skill.render(extra_instructions=extra_args)
|
||||||
@@ -329,24 +503,36 @@ def create_bot_router(
|
|||||||
if reply_context:
|
if reply_context:
|
||||||
if cleaned_text:
|
if cleaned_text:
|
||||||
prompt_to_run = f"{reply_context}[Запрос/вопрос пользователя]:\n{cleaned_text}"
|
prompt_to_run = f"{reply_context}[Запрос/вопрос пользователя]:\n{cleaned_text}"
|
||||||
|
elif attachments:
|
||||||
|
prompt_to_run = f"{reply_context}{build_default_attachment_prompt(attachments)}"
|
||||||
else:
|
else:
|
||||||
prompt_to_run = (
|
prompt_to_run = (
|
||||||
f"{reply_context}\n"
|
f"{reply_context}\n"
|
||||||
f"Пользователь упомянул тебя в ответ на это сообщение без дополнительного текста. "
|
f"Пользователь упомянул тебя в ответ на это сообщение без дополнительного текста. "
|
||||||
f"Пожалуйста, проанализируй это сообщение, объясни его суть или дай полезный ответ по контексту."
|
f"Пожалуйста, проанализируй это сообщение, объясни его суть или дай полезный ответ по контексту."
|
||||||
)
|
)
|
||||||
else:
|
elif cleaned_text:
|
||||||
prompt_to_run = cleaned_text
|
prompt_to_run = cleaned_text
|
||||||
|
else:
|
||||||
|
prompt_to_run = build_default_attachment_prompt(attachments)
|
||||||
|
|
||||||
|
if warnings:
|
||||||
|
prompt_to_run += "\n\n[Предупреждения при загрузке вложений]:\n" + "\n".join(
|
||||||
|
f"- {w}" for w in warnings
|
||||||
|
)
|
||||||
|
|
||||||
# 3. Process with AI agent
|
# 3. Process with AI agent
|
||||||
typing_task = asyncio.create_task(_keep_typing(message))
|
typing_task = asyncio.create_task(_keep_typing(message))
|
||||||
try:
|
try:
|
||||||
response_text = await agent.chat(
|
guest_chat_kwargs: dict[str, object] = {
|
||||||
chat_id=chat_id,
|
"chat_id": chat_id,
|
||||||
thread_id=thread_id,
|
"thread_id": thread_id,
|
||||||
user_message=prompt_to_run,
|
"user_message": prompt_to_run,
|
||||||
on_progress=None,
|
"on_progress": None,
|
||||||
)
|
}
|
||||||
|
if attachments:
|
||||||
|
guest_chat_kwargs["attachments"] = attachments
|
||||||
|
response_text = await agent.chat(**guest_chat_kwargs) # type: ignore[arg-type]
|
||||||
finally:
|
finally:
|
||||||
typing_task.cancel()
|
typing_task.cancel()
|
||||||
|
|
||||||
@@ -356,15 +542,24 @@ def create_bot_router(
|
|||||||
return 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."""
|
"""Send reply strictly using Telegram sendRichMessage API with InputRichMessage."""
|
||||||
rich_msg = InputRichMessage(markdown=text)
|
rich_msg = InputRichMessage(markdown=text)
|
||||||
|
extra_kwargs: dict[str, object] = {}
|
||||||
|
if reply_markup is not None:
|
||||||
|
extra_kwargs["reply_markup"] = reply_markup
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await message.bot.send_rich_message(
|
await message.bot.send_rich_message(
|
||||||
chat_id=message.chat.id,
|
chat_id=message.chat.id,
|
||||||
rich_message=rich_msg,
|
rich_message=rich_msg,
|
||||||
message_thread_id=message.message_thread_id,
|
message_thread_id=message.message_thread_id,
|
||||||
reply_parameters=message.as_reply_parameters(),
|
reply_parameters=message.as_reply_parameters(),
|
||||||
|
**extra_kwargs,
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning("Failed sending markdown rich message, trying html/plain rich message: %s", e)
|
logger.warning("Failed sending markdown rich message, trying html/plain rich message: %s", e)
|
||||||
@@ -375,6 +570,7 @@ async def _send_reply(message: Message, text: str) -> None:
|
|||||||
rich_message=InputRichMessage(html=text),
|
rich_message=InputRichMessage(html=text),
|
||||||
message_thread_id=message.message_thread_id,
|
message_thread_id=message.message_thread_id,
|
||||||
reply_parameters=message.as_reply_parameters(),
|
reply_parameters=message.as_reply_parameters(),
|
||||||
|
**extra_kwargs,
|
||||||
)
|
)
|
||||||
except Exception as e2:
|
except Exception as e2:
|
||||||
logger.error("Failed sending rich message via sendRichMessage: %s", e2)
|
logger.error("Failed sending rich message via sendRichMessage: %s", e2)
|
||||||
@@ -385,6 +581,7 @@ async def _send_reply(message: Message, text: str) -> None:
|
|||||||
text=text,
|
text=text,
|
||||||
message_thread_id=message.message_thread_id,
|
message_thread_id=message.message_thread_id,
|
||||||
reply_parameters=message.as_reply_parameters(),
|
reply_parameters=message.as_reply_parameters(),
|
||||||
|
**extra_kwargs,
|
||||||
)
|
)
|
||||||
except Exception as final_err:
|
except Exception as final_err:
|
||||||
logger.error("Failed sending message completely: %s", final_err)
|
logger.error("Failed sending message completely: %s", final_err)
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,240 @@
|
|||||||
|
"""Telegram media and file extraction helpers, including album (media_group_id) batching."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import io
|
||||||
|
import logging
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from aiogram import Bot
|
||||||
|
from aiogram.types import Message
|
||||||
|
|
||||||
|
from homeagent.agent.attachments import Attachment, format_size, normalize_mime_type
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def has_supported_media(message: Message) -> bool:
|
||||||
|
"""Return True if the Telegram message carries any downloadable image, file, or media."""
|
||||||
|
return bool(
|
||||||
|
message.photo
|
||||||
|
or message.document
|
||||||
|
or message.audio
|
||||||
|
or message.voice
|
||||||
|
or message.video
|
||||||
|
or message.video_note
|
||||||
|
or message.animation
|
||||||
|
or message.sticker
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def _download_file_bytes(bot: Bot, file_id: str) -> bytes:
|
||||||
|
"""Download a Telegram file by file_id into bytes."""
|
||||||
|
buf = io.BytesIO()
|
||||||
|
result = await bot.download(file_id, destination=buf)
|
||||||
|
data = buf.getvalue()
|
||||||
|
if data:
|
||||||
|
return data
|
||||||
|
if result is not None:
|
||||||
|
if hasattr(result, "getvalue"):
|
||||||
|
return result.getvalue()
|
||||||
|
if hasattr(result, "read"):
|
||||||
|
return result.read()
|
||||||
|
return b""
|
||||||
|
|
||||||
|
|
||||||
|
def _describe_media_item(message: Message) -> Optional[tuple[str, str, str, Optional[int], str]]:
|
||||||
|
"""Inspect a Telegram message and return `(file_id, filename, mime_type, file_size, kind)` or None."""
|
||||||
|
if message.photo:
|
||||||
|
largest = message.photo[-1]
|
||||||
|
uid = getattr(largest, "file_unique_id", None) or "img"
|
||||||
|
return (largest.file_id, f"photo_{uid}.jpg", "image/jpeg", largest.file_size, "image")
|
||||||
|
|
||||||
|
if message.document:
|
||||||
|
doc = message.document
|
||||||
|
uid = getattr(doc, "file_unique_id", None) or "doc"
|
||||||
|
filename = doc.file_name or f"document_{uid}"
|
||||||
|
mime_type = doc.mime_type or "application/octet-stream"
|
||||||
|
kind = "image" if mime_type.lower().startswith("image/") else "document"
|
||||||
|
return (doc.file_id, filename, mime_type, doc.file_size, kind)
|
||||||
|
|
||||||
|
if message.voice:
|
||||||
|
voice = message.voice
|
||||||
|
uid = getattr(voice, "file_unique_id", None) or "voice"
|
||||||
|
mime_type = voice.mime_type or "audio/ogg"
|
||||||
|
return (voice.file_id, f"voice_{uid}.ogg", mime_type, voice.file_size, "voice")
|
||||||
|
|
||||||
|
if message.audio:
|
||||||
|
audio = message.audio
|
||||||
|
uid = getattr(audio, "file_unique_id", None) or "audio"
|
||||||
|
filename = audio.file_name or f"audio_{uid}.mp3"
|
||||||
|
mime_type = audio.mime_type or "audio/mpeg"
|
||||||
|
return (audio.file_id, filename, mime_type, audio.file_size, "audio")
|
||||||
|
|
||||||
|
if message.video:
|
||||||
|
video = message.video
|
||||||
|
uid = getattr(video, "file_unique_id", None) or "video"
|
||||||
|
filename = video.file_name or f"video_{uid}.mp4"
|
||||||
|
mime_type = video.mime_type or "video/mp4"
|
||||||
|
return (video.file_id, filename, mime_type, video.file_size, "video")
|
||||||
|
|
||||||
|
if message.video_note:
|
||||||
|
vn = message.video_note
|
||||||
|
uid = getattr(vn, "file_unique_id", None) or "vnote"
|
||||||
|
return (vn.file_id, f"video_note_{uid}.mp4", "video/mp4", vn.file_size, "video")
|
||||||
|
|
||||||
|
if message.animation:
|
||||||
|
anim = message.animation
|
||||||
|
uid = getattr(anim, "file_unique_id", None) or "anim"
|
||||||
|
filename = anim.file_name or f"animation_{uid}.mp4"
|
||||||
|
mime_type = anim.mime_type or "video/mp4"
|
||||||
|
return (anim.file_id, filename, mime_type, anim.file_size, "animation")
|
||||||
|
|
||||||
|
if message.sticker:
|
||||||
|
sticker = message.sticker
|
||||||
|
uid = getattr(sticker, "file_unique_id", None) or "sticker"
|
||||||
|
if getattr(sticker, "is_animated", False):
|
||||||
|
# Lottie .tgs sticker is gzipped JSON vector animation — skip cleanly via caller warning
|
||||||
|
return (sticker.file_id, f"sticker_{uid}.tgs", "application/x-tgsticker", sticker.file_size, "sticker_animated")
|
||||||
|
if getattr(sticker, "is_video", False):
|
||||||
|
return (sticker.file_id, f"sticker_{uid}.webm", "video/webm", sticker.file_size, "sticker")
|
||||||
|
return (sticker.file_id, f"sticker_{uid}.webp", "image/webp", sticker.file_size, "sticker")
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def extract_message_attachments(
|
||||||
|
bot: Optional[Bot],
|
||||||
|
messages: list[Message],
|
||||||
|
*,
|
||||||
|
max_size_bytes: int = 20 * 1024 * 1024,
|
||||||
|
max_count: int = 10,
|
||||||
|
source: str = "message",
|
||||||
|
) -> tuple[list[Attachment], list[str]]:
|
||||||
|
"""Download supported attachments from one or more Telegram messages.
|
||||||
|
|
||||||
|
Returns `(attachments, warnings)`.
|
||||||
|
"""
|
||||||
|
attachments: list[Attachment] = []
|
||||||
|
warnings: list[str] = []
|
||||||
|
|
||||||
|
if bot is None:
|
||||||
|
return attachments, warnings
|
||||||
|
|
||||||
|
for msg in messages:
|
||||||
|
info = _describe_media_item(msg)
|
||||||
|
if info is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
file_id, filename, raw_mime, file_size, kind = info
|
||||||
|
if kind == "sticker_animated":
|
||||||
|
warnings.append("Анимированные стикеры (.tgs) не поддерживаются для анализа.")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if len(attachments) >= max_count:
|
||||||
|
warnings.append(
|
||||||
|
f"Достигнут лимит вложений ({max_count} файлов на сообщение): `{filename}` пропущен."
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if file_size is not None and file_size > max_size_bytes:
|
||||||
|
warnings.append(
|
||||||
|
f"Файл `{filename}` слишком большой ({format_size(file_size)}). "
|
||||||
|
f"Максимальный размер — {format_size(max_size_bytes)}."
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = await _download_file_bytes(bot, file_id)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Failed downloading Telegram attachment '%s' (%s): %s", filename, file_id, e)
|
||||||
|
err_msg = str(e)
|
||||||
|
if "file is too big" in err_msg.lower():
|
||||||
|
warnings.append(
|
||||||
|
f"Файл `{filename}` превышает лимит Telegram Bot API (20 МБ) и не может быть скачан."
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
warnings.append(f"Не удалось скачать вложение `{filename}`: {err_msg}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not data:
|
||||||
|
warnings.append(f"Вложение `{filename}` оказалось пустым (0 байт).")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if len(data) > max_size_bytes:
|
||||||
|
warnings.append(
|
||||||
|
f"Файл `{filename}` слишком большой ({format_size(len(data))}). "
|
||||||
|
f"Максимальный размер — {format_size(max_size_bytes)}."
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
normalized_mime = normalize_mime_type(filename, raw_mime, data=data)
|
||||||
|
resolved_kind = "image" if normalized_mime.startswith("image/") and kind == "document" else kind
|
||||||
|
attachments.append(
|
||||||
|
Attachment(
|
||||||
|
filename=filename,
|
||||||
|
mime_type=normalized_mime,
|
||||||
|
data=data,
|
||||||
|
kind=resolved_kind,
|
||||||
|
source=source,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
return attachments, warnings
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class _MediaGroupState:
|
||||||
|
messages: list[Message] = field(default_factory=list)
|
||||||
|
last_arrival: float = 0.0
|
||||||
|
first_arrival: float = 0.0
|
||||||
|
|
||||||
|
|
||||||
|
class MediaGroupBuffer:
|
||||||
|
"""Debounces Telegram album updates sharing the same `media_group_id` into one batch."""
|
||||||
|
|
||||||
|
def __init__(self, delay_seconds: float = 0.6, max_wait_seconds: float = 2.5) -> None:
|
||||||
|
self.delay_seconds = delay_seconds
|
||||||
|
self.max_wait_seconds = max_wait_seconds
|
||||||
|
self._groups: dict[tuple[int, Optional[int], str], _MediaGroupState] = {}
|
||||||
|
|
||||||
|
async def collect(self, message: Message) -> Optional[list[Message]]:
|
||||||
|
"""Collect messages belonging to a media group.
|
||||||
|
|
||||||
|
- If `message.media_group_id` is None, returns `[message]` immediately.
|
||||||
|
- For a media group, the first arriving coroutine waits until arrivals settle and
|
||||||
|
returns all collected messages sorted by `message_id`. Subsequent arrivals in the
|
||||||
|
same group append to the batch and return `None`.
|
||||||
|
"""
|
||||||
|
group_id = getattr(message, "media_group_id", None)
|
||||||
|
if not group_id:
|
||||||
|
return [message]
|
||||||
|
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
now = loop.time()
|
||||||
|
key = (message.chat.id, message.message_thread_id, str(group_id))
|
||||||
|
|
||||||
|
existing = self._groups.get(key)
|
||||||
|
if existing is not None:
|
||||||
|
existing.messages.append(message)
|
||||||
|
existing.last_arrival = now
|
||||||
|
return None
|
||||||
|
|
||||||
|
state = _MediaGroupState(messages=[message], last_arrival=now, first_arrival=now)
|
||||||
|
self._groups[key] = state
|
||||||
|
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
now = loop.time()
|
||||||
|
since_last = now - state.last_arrival
|
||||||
|
since_first = now - state.first_arrival
|
||||||
|
if since_last >= self.delay_seconds or since_first >= self.max_wait_seconds:
|
||||||
|
break
|
||||||
|
sleep_for = min(self.delay_seconds - since_last, self.max_wait_seconds - since_first)
|
||||||
|
await asyncio.sleep(max(0.01, sleep_for))
|
||||||
|
finally:
|
||||||
|
self._groups.pop(key, None)
|
||||||
|
|
||||||
|
return sorted(state.messages, key=lambda m: m.message_id)
|
||||||
@@ -43,6 +43,9 @@ def format_tool_progress(name: str, args: dict[str, Any]) -> str:
|
|||||||
if name == "sandbox_reset":
|
if name == "sandbox_reset":
|
||||||
return "🧹 Очищаю рабочую песочницу..."
|
return "🧹 Очищаю рабочую песочницу..."
|
||||||
|
|
||||||
|
if name == "inspect_attachment":
|
||||||
|
return "📎 Изучаю прикреплённый файл..."
|
||||||
|
|
||||||
if name == "calendar_today_schedule":
|
if name == "calendar_today_schedule":
|
||||||
return "📅 Проверяю расписание на сегодня..."
|
return "📅 Проверяю расписание на сегодня..."
|
||||||
|
|
||||||
@@ -144,6 +147,32 @@ def format_tool_progress(name: str, args: dict[str, Any]) -> str:
|
|||||||
cnt = len(tasks) if isinstance(tasks, list) else ""
|
cnt = len(tasks) if isinstance(tasks, list) else ""
|
||||||
return f"👥 Запускаю {cnt} параллельных подагентов..."
|
return f"👥 Запускаю {cnt} параллельных подагентов..."
|
||||||
|
|
||||||
|
if name == "mcp_connect":
|
||||||
|
src = str(args.get("source", "")).strip()
|
||||||
|
short_src = f"`{src[:40]}...`" if len(src) > 40 else f"`{src}`" if src else ""
|
||||||
|
return f"🔌 Подключаю MCP-сервер {short_src}..."
|
||||||
|
|
||||||
|
if name == "mcp_provide_auth":
|
||||||
|
cname = str(args.get("connector_name", "")).strip()
|
||||||
|
return f"🔑 Проверяю авторизацию MCP `{cname}`..." if cname else "🔑 Проверяю авторизацию MCP..."
|
||||||
|
|
||||||
|
if name == "mcp_list_connectors":
|
||||||
|
return "🔌 Проверяю список MCP коннекторов..."
|
||||||
|
|
||||||
|
if name == "mcp_disconnect":
|
||||||
|
cname = str(args.get("connector_name", "")).strip()
|
||||||
|
return f"⏹ Отключаю MCP `{cname}`..."
|
||||||
|
|
||||||
|
if name == "mcp_remove_connector":
|
||||||
|
cname = str(args.get("connector_name", "")).strip()
|
||||||
|
return f"🗑 Удаляю MCP `{cname}`..."
|
||||||
|
|
||||||
|
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}`..."
|
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.handlers import create_bot_router
|
||||||
from homeagent.bot.middlewares import WhitelistMiddleware
|
from homeagent.bot.middlewares import WhitelistMiddleware
|
||||||
from homeagent.config import Settings, get_settings
|
from homeagent.config import Settings, get_settings
|
||||||
|
from homeagent.mcp.manager import MCPConnectorManager
|
||||||
from homeagent.skills.manager import SkillManager
|
from homeagent.skills.manager import SkillManager
|
||||||
from homeagent.tools.loader import load_extensions_from_directory
|
from homeagent.tools.loader import load_extensions_from_directory
|
||||||
from homeagent.tools.registry import get_tool_registry
|
from homeagent.tools.registry import get_tool_registry
|
||||||
@@ -31,10 +32,16 @@ class TelegramAgentApp:
|
|||||||
# Load dynamic extensions from directory
|
# Load dynamic extensions from directory
|
||||||
load_extensions_from_directory(self.settings.EXTENSIONS_DIR, self.registry)
|
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
|
# Initialize skills
|
||||||
self.skill_manager = SkillManager(self.settings.SKILLS_DIR)
|
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(
|
self.agent: BaseAgent = create_agent(
|
||||||
settings=self.settings,
|
settings=self.settings,
|
||||||
registry=self.registry,
|
registry=self.registry,
|
||||||
@@ -53,9 +60,10 @@ class TelegramAgentApp:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning("Could not initialize Telegram Bot with provided token: %s", 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)
|
whitelist_middleware = WhitelistMiddleware(self.settings)
|
||||||
self.dp.message.middleware(whitelist_middleware)
|
self.dp.message.middleware(whitelist_middleware)
|
||||||
|
self.dp.callback_query.middleware(whitelist_middleware)
|
||||||
self.dp.guest_message.middleware(whitelist_middleware)
|
self.dp.guest_message.middleware(whitelist_middleware)
|
||||||
|
|
||||||
# Register router
|
# Register router
|
||||||
@@ -64,6 +72,7 @@ class TelegramAgentApp:
|
|||||||
agent=self.agent,
|
agent=self.agent,
|
||||||
skill_manager=self.skill_manager,
|
skill_manager=self.skill_manager,
|
||||||
tool_registry=self.registry,
|
tool_registry=self.registry,
|
||||||
|
mcp_manager=self.mcp_manager,
|
||||||
)
|
)
|
||||||
self.dp.include_router(router)
|
self.dp.include_router(router)
|
||||||
|
|
||||||
@@ -74,7 +83,9 @@ class TelegramAgentApp:
|
|||||||
|
|
||||||
commands = [
|
commands = [
|
||||||
BotCommand(command="start", description="Запустить бота / статус"),
|
BotCommand(command="start", description="Запустить бота / статус"),
|
||||||
|
BotCommand(command="mcp", description="Управление MCP коннекторами"),
|
||||||
BotCommand(command="skills", description="Список доступных скиллов"),
|
BotCommand(command="skills", description="Список доступных скиллов"),
|
||||||
|
BotCommand(command="model", description="Текущая модель / переключение модели"),
|
||||||
BotCommand(command="memory", description="Глобальная память фактов"),
|
BotCommand(command="memory", description="Глобальная память фактов"),
|
||||||
BotCommand(command="reset", description="Очистить контекст текущего топика"),
|
BotCommand(command="reset", description="Очистить контекст текущего топика"),
|
||||||
BotCommand(command="help", description="Справка по командам"),
|
BotCommand(command="help", description="Справка по командам"),
|
||||||
@@ -89,12 +100,22 @@ class TelegramAgentApp:
|
|||||||
if not self.bot:
|
if not self.bot:
|
||||||
raise ValueError("Cannot start bot: TELEGRAM_BOT_TOKEN is missing or invalid.")
|
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("Starting HomeAgent Telegram Bot...")
|
||||||
logger.info("Allowed User IDs: %s", self.settings.ALLOWED_TELEGRAM_USER_IDS)
|
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("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("LLM Provider: %s", self.settings.get_active_provider_name())
|
||||||
logger.info("Orchestrator Model: %s", self.settings.get_active_model())
|
logger.info("Orchestrator Model: %s", self.settings.get_active_model())
|
||||||
logger.info("Subagent Model: %s", self.settings.get_active_subagent_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("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()])
|
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)
|
logger.info("Polling with allowed_updates: %s", allowed_updates)
|
||||||
await self.dp.start_polling(self.bot, allowed_updates=allowed_updates)
|
await self.dp.start_polling(self.bot, allowed_updates=allowed_updates)
|
||||||
finally:
|
finally:
|
||||||
|
await self.mcp_manager.close()
|
||||||
|
await self.agent.close()
|
||||||
await self.bot.session.close()
|
await self.bot.session.close()
|
||||||
+87
-5
@@ -26,11 +26,19 @@ class Settings(BaseSettings):
|
|||||||
default=True,
|
default=True,
|
||||||
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.",
|
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.",
|
||||||
)
|
)
|
||||||
|
MAX_ATTACHMENT_SIZE_MB: int = Field(
|
||||||
|
default=20,
|
||||||
|
description="Maximum size in MB for incoming Telegram image/file attachments (Telegram Bot API limit is 20 MB).",
|
||||||
|
)
|
||||||
|
MAX_ATTACHMENTS_PER_MESSAGE: int = Field(
|
||||||
|
default=10,
|
||||||
|
description="Maximum number of attachments accepted in a single turn (including Telegram media groups).",
|
||||||
|
)
|
||||||
|
|
||||||
# LLM Provider selection: 'gemini', 'deepseek', or 'openai' (compatible)
|
# LLM Provider selection: 'gemini', 'deepseek', 'openai', or 'antigravity'
|
||||||
LLM_PROVIDER: Literal["gemini", "deepseek", "openai"] = Field(
|
LLM_PROVIDER: Literal["gemini", "deepseek", "openai", "antigravity"] = Field(
|
||||||
default="gemini",
|
default="gemini",
|
||||||
description="Active LLM provider: 'gemini', 'deepseek', or 'openai'",
|
description="Active LLM provider: 'gemini', 'deepseek', 'openai', or 'antigravity'",
|
||||||
)
|
)
|
||||||
|
|
||||||
# Google AI Studio (Gemini)
|
# Google AI Studio (Gemini)
|
||||||
@@ -83,20 +91,54 @@ class Settings(BaseSettings):
|
|||||||
description="Fast model for subagents on OpenAI-compatible endpoint",
|
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(
|
SYSTEM_INSTRUCTION: str = Field(
|
||||||
default=(
|
default=(
|
||||||
"Ты — умный персональный AI-ассистент и главный координатор (Orchestrator), интегрированный в Telegram. "
|
"Ты — умный персональный AI-ассистент и главный координатор (Orchestrator), интегрированный в Telegram. "
|
||||||
"Ты помогаешь пользователю управлять задачами в Jira, расписанием в Google Календаре, репозиториями в Gitea, "
|
"Ты помогаешь пользователю управлять задачами в Todoist и Jira, расписанием в Google Календаре, репозиториями в Gitea, "
|
||||||
"искать актуальную информацию в интернете (web_search, web_fetch_page), безопасно выполнять код и вычисления в песочнице (code_execute, sandbox_run_command), "
|
"искать актуальную информацию в интернете (web_search, web_fetch_page), безопасно выполнять код и вычисления в песочнице (code_execute, sandbox_run_command), "
|
||||||
|
"подключать внешние MCP-серверы (mcp_connect, mcp_provide_auth, mcp_list_connectors, mcp_disconnect, mcp_remove_connector), "
|
||||||
"помнить важные факты и выполнять специализированные скиллы. "
|
"помнить важные факты и выполнять специализированные скиллы. "
|
||||||
|
"Ты также умеешь анализировать прикреплённые пользователем изображения, скриншоты, PDF, голосовые/аудио, документы (DOCX/XLSX/PPTX) и текстовые/исходные файлы; "
|
||||||
|
"при необходимости сложной обработки данных из файлов используй инструменты песочницы (`code_execute`, `sandbox_run_command`) с сохранёнными путями в `uploads/`. "
|
||||||
|
"ВАЖНО: если пользователь просит подключить, добавить, настроить или авторизовать MCP-сервер (даёт URL, команду или JSON), "
|
||||||
|
"ВСЕГДА вызывай встроенный инструмент `mcp_connect` (и `mcp_provide_auth` для передачи токена, ключа, client_id или OAuth-ссылки), "
|
||||||
|
"и НЕ пытайся открывать MCP URL через `web_fetch_page` или искать инструкцию в `web_search`. "
|
||||||
"Для быстрого и эффективного сбора данных из нескольких источников ты можешь запускать быстрых подагентов параллельно "
|
"Для быстрого и эффективного сбора данных из нескольких источников ты можешь запускать быстрых подагентов параллельно "
|
||||||
"через spawn_parallel_subagents (например, один подагент проверяет Календарь, второй — задачи в Jira, третий ищет информацию в интернете). "
|
"через spawn_parallel_subagents (например, один подагент проверяет Календарь, второй — задачи в Todoist/Jira, третий ищет информацию в интернете). "
|
||||||
"Отвечай емко, красиво и структурированно, используя Markdown для списков, жирного шрифта и таблиц. "
|
"Отвечай емко, красиво и структурированно, используя Markdown для списков, жирного шрифта и таблиц. "
|
||||||
"Всегда выполняй действия через доступные инструменты (tools), если требуется проверить актуальные данные или совершить действие."
|
"Всегда выполняй действия через доступные инструменты (tools), если требуется проверить актуальные данные или совершить действие."
|
||||||
),
|
),
|
||||||
description="Default system instruction for Gemini",
|
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 Integration
|
||||||
JIRA_ENABLED: bool = Field(default=True, description="Enable or disable Jira tools")
|
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")
|
JIRA_URL: Optional[str] = Field(default=None, description="Base Jira URL, e.g. https://your-domain.atlassian.net")
|
||||||
@@ -160,11 +202,47 @@ class Settings(BaseSettings):
|
|||||||
EXTENSIONS_DIR: Path = Field(default=Path("extensions"), description="Directory with dynamic extensions")
|
EXTENSIONS_DIR: Path = Field(default=Path("extensions"), description="Directory with dynamic extensions")
|
||||||
LOG_LEVEL: str = Field(default="INFO", description="Logging level")
|
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_CLIENT_METADATA_URL: Optional[str] = Field(
|
||||||
|
default=None,
|
||||||
|
description="Optional HTTPS URL to an OAuth Client ID Metadata Document (MCP 2025-11-25 CIMD) used automatically when a server supports client_id_metadata_document_supported",
|
||||||
|
)
|
||||||
|
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:
|
def get_active_provider_name(self) -> str:
|
||||||
if self.LLM_PROVIDER == "deepseek":
|
if self.LLM_PROVIDER == "deepseek":
|
||||||
return "DeepSeek"
|
return "DeepSeek"
|
||||||
if self.LLM_PROVIDER == "openai":
|
if self.LLM_PROVIDER == "openai":
|
||||||
return "OpenAI-Compatible"
|
return "OpenAI-Compatible"
|
||||||
|
if self.LLM_PROVIDER == "antigravity":
|
||||||
|
return "Antigravity"
|
||||||
return "Google Gemini"
|
return "Google Gemini"
|
||||||
|
|
||||||
def get_active_model(self) -> str:
|
def get_active_model(self) -> str:
|
||||||
@@ -172,6 +250,8 @@ class Settings(BaseSettings):
|
|||||||
return self.DEEPSEEK_MODEL
|
return self.DEEPSEEK_MODEL
|
||||||
if self.LLM_PROVIDER == "openai":
|
if self.LLM_PROVIDER == "openai":
|
||||||
return self.OPENAI_MODEL
|
return self.OPENAI_MODEL
|
||||||
|
if self.LLM_PROVIDER == "antigravity":
|
||||||
|
return self.ANTIGRAVITY_MODEL
|
||||||
return self.GEMINI_MODEL
|
return self.GEMINI_MODEL
|
||||||
|
|
||||||
def get_active_subagent_model(self) -> str:
|
def get_active_subagent_model(self) -> str:
|
||||||
@@ -179,6 +259,8 @@ class Settings(BaseSettings):
|
|||||||
return self.DEEPSEEK_SUBAGENT_MODEL
|
return self.DEEPSEEK_SUBAGENT_MODEL
|
||||||
if self.LLM_PROVIDER == "openai":
|
if self.LLM_PROVIDER == "openai":
|
||||||
return self.OPENAI_SUBAGENT_MODEL
|
return self.OPENAI_SUBAGENT_MODEL
|
||||||
|
if self.LLM_PROVIDER == "antigravity":
|
||||||
|
return self.ANTIGRAVITY_SUBAGENT_MODEL
|
||||||
return self.GEMINI_SUBAGENT_MODEL
|
return self.GEMINI_SUBAGENT_MODEL
|
||||||
|
|
||||||
@field_validator("ALLOWED_TELEGRAM_USER_IDS", mode="after")
|
@field_validator("ALLOWED_TELEGRAM_USER_IDS", mode="after")
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
"""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.autodiscover import (
|
||||||
|
SmartProbeResult,
|
||||||
|
derive_connector_name_from_command,
|
||||||
|
derive_connector_name_from_url,
|
||||||
|
looks_like_smart_mcp_input,
|
||||||
|
parse_smart_input,
|
||||||
|
smart_apply_credentials_and_probe,
|
||||||
|
smart_connect_connector,
|
||||||
|
)
|
||||||
|
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,881 @@
|
|||||||
|
"""Zero-config smart auto-discovery and credential probing for MCP connectors."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
import shlex
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Literal, Optional
|
||||||
|
from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse
|
||||||
|
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
from homeagent.mcp.auth import MCPAuthError, MCPAuthRequiredError
|
||||||
|
from homeagent.mcp.client import MCPClient, MCPProtocolError
|
||||||
|
from homeagent.mcp.manager import MCPConnectorManager
|
||||||
|
from homeagent.mcp.models import (
|
||||||
|
MCPAuthConfig,
|
||||||
|
MCPConnectorConfig,
|
||||||
|
MCPConnectorState,
|
||||||
|
normalize_connector_name,
|
||||||
|
parse_connectors_payload,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_QUERY_AUTH_KEYS = frozenset({"api_key", "apikey", "key", "token", "access_token", "auth", "secret"})
|
||||||
|
_GENERIC_SUBDOMAINS = frozenset({"mcp", "api", "www", "app", "server", "remote", "beta", "staging", "dev", "v1", "v2"})
|
||||||
|
_GENERIC_PATH_PARTS = frozenset({"mcp", "sse", "api", "v1", "v2", "v3", "rpc", "jsonrpc", "stream", "messages"})
|
||||||
|
_ENV_ASSIGN_RE = re.compile(r"^([A-Za-z_][A-Za-z0-9_]*)=(.*)$")
|
||||||
|
_STDIO_HINT_ENV_RE = re.compile(r"\b([A-Z][A-Z0-9_]{2,}_(?:TOKEN|KEY|API_KEY|SECRET|PASSWORD|PAT))\b")
|
||||||
|
_COMMON_STDIO_COMMANDS = frozenset(
|
||||||
|
{
|
||||||
|
"npx",
|
||||||
|
"pnpx",
|
||||||
|
"bunx",
|
||||||
|
"uvx",
|
||||||
|
"uv",
|
||||||
|
"pipx",
|
||||||
|
"python",
|
||||||
|
"python3",
|
||||||
|
"node",
|
||||||
|
"deno",
|
||||||
|
"bun",
|
||||||
|
"docker",
|
||||||
|
"podman",
|
||||||
|
"sh",
|
||||||
|
"bash",
|
||||||
|
"go",
|
||||||
|
"cargo",
|
||||||
|
"java",
|
||||||
|
"ruby",
|
||||||
|
"php",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
SmartOutcome = Literal[
|
||||||
|
"connected",
|
||||||
|
"oauth_pkce_ready",
|
||||||
|
"oauth_device_ready",
|
||||||
|
"need_basic",
|
||||||
|
"need_credentials",
|
||||||
|
"stdio_error",
|
||||||
|
"error",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class SmartProbeResult:
|
||||||
|
"""Result of smart auto-connect or credential probing."""
|
||||||
|
|
||||||
|
outcome: SmartOutcome
|
||||||
|
state: MCPConnectorState
|
||||||
|
oauth_info: Optional[dict[str, Any]] = None
|
||||||
|
discovered_oauth: Optional[dict[str, Any]] = None
|
||||||
|
detected_auth_label: Optional[str] = None
|
||||||
|
hinted_env_vars: list[str] = field(default_factory=list)
|
||||||
|
probe_attempts: list[str] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
def _dedupe_name(base: str, existing: set[str]) -> str:
|
||||||
|
try:
|
||||||
|
clean = normalize_connector_name(base)
|
||||||
|
except ValueError:
|
||||||
|
clean = "mcp_server"
|
||||||
|
if clean not in existing:
|
||||||
|
return clean
|
||||||
|
idx = 2
|
||||||
|
while f"{clean}_{idx}" in existing:
|
||||||
|
idx += 1
|
||||||
|
return f"{clean}_{idx}"
|
||||||
|
|
||||||
|
|
||||||
|
def derive_connector_name_from_url(url: str, existing: Optional[set[str]] = None) -> str:
|
||||||
|
"""Derive a clean, friendly connector slug from an MCP server URL."""
|
||||||
|
existing_set = existing or set()
|
||||||
|
parsed = urlparse(url)
|
||||||
|
host = (parsed.hostname or "").lower()
|
||||||
|
path_parts = [p for p in parsed.path.split("/") if p and p.lower() not in _GENERIC_PATH_PARTS]
|
||||||
|
|
||||||
|
candidate = ""
|
||||||
|
if host in ("localhost", "127.0.0.1", "::1") or re.match(r"^\d+\.\d+\.\d+\.\d+$", host):
|
||||||
|
if path_parts:
|
||||||
|
candidate = path_parts[0]
|
||||||
|
elif parsed.port:
|
||||||
|
candidate = f"local_{parsed.port}"
|
||||||
|
else:
|
||||||
|
candidate = "local_mcp"
|
||||||
|
elif host:
|
||||||
|
labels = [lbl for lbl in host.split(".") if lbl]
|
||||||
|
# Strip TLD (and ccTLD like .co.uk)
|
||||||
|
if len(labels) >= 2:
|
||||||
|
labels = labels[:-1]
|
||||||
|
if len(labels) >= 2 and labels[-1] in ("co", "com", "org", "net", "gov"):
|
||||||
|
labels = labels[:-1]
|
||||||
|
meaningful = [lbl for lbl in labels if lbl not in _GENERIC_SUBDOMAINS]
|
||||||
|
if meaningful:
|
||||||
|
candidate = meaningful[-1]
|
||||||
|
elif labels:
|
||||||
|
candidate = labels[-1]
|
||||||
|
elif path_parts:
|
||||||
|
candidate = path_parts[0]
|
||||||
|
|
||||||
|
if not candidate:
|
||||||
|
candidate = path_parts[0] if path_parts else "mcp_server"
|
||||||
|
|
||||||
|
return _dedupe_name(candidate, existing_set)
|
||||||
|
|
||||||
|
|
||||||
|
def derive_connector_name_from_command(
|
||||||
|
command: str,
|
||||||
|
args: list[str],
|
||||||
|
existing: Optional[set[str]] = None,
|
||||||
|
) -> str:
|
||||||
|
"""Derive a friendly connector slug from a stdio command + args."""
|
||||||
|
existing_set = existing or set()
|
||||||
|
cmd_base = Path(command).stem.lower()
|
||||||
|
candidate = ""
|
||||||
|
|
||||||
|
if cmd_base in ("npx", "pnpx", "bunx", "uvx", "pipx"):
|
||||||
|
for arg in args:
|
||||||
|
if arg.startswith("-"):
|
||||||
|
continue
|
||||||
|
pkg = arg.strip()
|
||||||
|
# Drop npm version suffix like @1.2.3
|
||||||
|
if "@" in pkg[1:]:
|
||||||
|
pkg = pkg[: pkg.rfind("@")]
|
||||||
|
# Split scope/package
|
||||||
|
if "/" in pkg:
|
||||||
|
scope, name = pkg.split("/", 1)
|
||||||
|
scope = scope.lstrip("@")
|
||||||
|
cleaned_name = re.sub(r"^(?:mcp[-_]?server[-_]?|server[-_]?|mcp[-_]?)", "", name, flags=re.IGNORECASE)
|
||||||
|
cleaned_name = re.sub(r"[-_]?mcp(?:[-_]?server)?$", "", cleaned_name, flags=re.IGNORECASE)
|
||||||
|
if cleaned_name and cleaned_name.lower() not in ("server", "mcp"):
|
||||||
|
candidate = cleaned_name
|
||||||
|
else:
|
||||||
|
candidate = scope
|
||||||
|
else:
|
||||||
|
cleaned_name = re.sub(r"^(?:mcp[-_]?server[-_]?|server[-_]?|mcp[-_]?)", "", pkg, flags=re.IGNORECASE)
|
||||||
|
cleaned_name = re.sub(r"[-_]?mcp(?:[-_]?server)?$", "", cleaned_name, flags=re.IGNORECASE)
|
||||||
|
candidate = cleaned_name or pkg
|
||||||
|
break
|
||||||
|
elif cmd_base in ("python", "python3", "node", "deno", "bun", "uv"):
|
||||||
|
for arg in args:
|
||||||
|
if arg.startswith("-") or arg in ("run", "exec", "-m"):
|
||||||
|
continue
|
||||||
|
candidate = Path(arg).stem
|
||||||
|
break
|
||||||
|
|
||||||
|
if not candidate:
|
||||||
|
candidate = cmd_base or "stdio_mcp"
|
||||||
|
|
||||||
|
return _dedupe_name(candidate, existing_set)
|
||||||
|
|
||||||
|
|
||||||
|
def _strip_code_fences(text: str) -> str:
|
||||||
|
s = text.strip()
|
||||||
|
if s.startswith("```"):
|
||||||
|
lines = s.splitlines()
|
||||||
|
if lines and lines[0].startswith("```"):
|
||||||
|
lines = lines[1:]
|
||||||
|
if lines and lines[-1].strip() == "```":
|
||||||
|
lines = lines[:-1]
|
||||||
|
return "\n".join(lines).strip()
|
||||||
|
return s
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_url_credentials(url: str) -> tuple[str, MCPAuthConfig]:
|
||||||
|
"""Extract embedded Basic auth (`user:pass@host`) or API-key query params from a URL."""
|
||||||
|
parsed = urlparse(url)
|
||||||
|
auth = MCPAuthConfig(type="none")
|
||||||
|
|
||||||
|
netloc = parsed.netloc
|
||||||
|
if parsed.username is not None:
|
||||||
|
auth = MCPAuthConfig(
|
||||||
|
type="basic",
|
||||||
|
username=parsed.username,
|
||||||
|
password=parsed.password or "",
|
||||||
|
)
|
||||||
|
host_part = parsed.hostname or ""
|
||||||
|
if ":" in host_part and not host_part.startswith("["):
|
||||||
|
host_part = f"[{host_part}]"
|
||||||
|
netloc = f"{host_part}:{parsed.port}" if parsed.port else host_part
|
||||||
|
|
||||||
|
query_pairs = parse_qsl(parsed.query, keep_blank_values=True)
|
||||||
|
remaining_pairs: list[tuple[str, str]] = []
|
||||||
|
if auth.type == "none":
|
||||||
|
for k, v in query_pairs:
|
||||||
|
if k.lower() in _QUERY_AUTH_KEYS and v and auth.type == "none":
|
||||||
|
auth = MCPAuthConfig(
|
||||||
|
type="api_key",
|
||||||
|
api_key=v,
|
||||||
|
api_key_in="query",
|
||||||
|
query_param=k,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
remaining_pairs.append((k, v))
|
||||||
|
else:
|
||||||
|
remaining_pairs = query_pairs
|
||||||
|
|
||||||
|
clean_url = urlunparse(
|
||||||
|
parsed._replace(
|
||||||
|
netloc=netloc,
|
||||||
|
query=urlencode(remaining_pairs, doseq=True),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return clean_url, auth
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_curl_input(
|
||||||
|
raw_text: str,
|
||||||
|
*,
|
||||||
|
existing_names: set[str],
|
||||||
|
default_timeout: int,
|
||||||
|
) -> MCPConnectorConfig:
|
||||||
|
"""Parse a pasted `curl ...` snippet into an `MCPConnectorConfig`."""
|
||||||
|
normalized = raw_text.replace("\\\n", " ").strip()
|
||||||
|
tokens = shlex.split(normalized)
|
||||||
|
url: Optional[str] = None
|
||||||
|
headers: dict[str, str] = {}
|
||||||
|
basic_user: Optional[str] = None
|
||||||
|
basic_pass: Optional[str] = None
|
||||||
|
|
||||||
|
i = 1
|
||||||
|
while i < len(tokens):
|
||||||
|
tok = tokens[i]
|
||||||
|
if tok in ("-H", "--header") and i + 1 < len(tokens):
|
||||||
|
hdr = tokens[i + 1]
|
||||||
|
if ":" in hdr:
|
||||||
|
k, v = hdr.split(":", 1)
|
||||||
|
headers[k.strip()] = v.strip()
|
||||||
|
i += 2
|
||||||
|
continue
|
||||||
|
if tok in ("-u", "--user") and i + 1 < len(tokens):
|
||||||
|
cred = tokens[i + 1]
|
||||||
|
if ":" in cred:
|
||||||
|
basic_user, basic_pass = cred.split(":", 1)
|
||||||
|
else:
|
||||||
|
basic_user, basic_pass = cred, ""
|
||||||
|
i += 2
|
||||||
|
continue
|
||||||
|
if tok in ("-X", "--request", "-d", "--data", "--data-raw", "--data-binary"):
|
||||||
|
i += 2
|
||||||
|
continue
|
||||||
|
if tok.startswith("http://") or tok.startswith("https://"):
|
||||||
|
url = tok
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
if not url:
|
||||||
|
raise ValueError("Не удалось найти URL в команде `curl`.")
|
||||||
|
|
||||||
|
clean_url, url_auth = _extract_url_credentials(url)
|
||||||
|
auth = url_auth
|
||||||
|
extra_headers: dict[str, str] = {}
|
||||||
|
|
||||||
|
if basic_user is not None:
|
||||||
|
auth = MCPAuthConfig(type="basic", username=basic_user, password=basic_pass or "")
|
||||||
|
|
||||||
|
for k, v in headers.items():
|
||||||
|
kl = k.lower()
|
||||||
|
if kl in ("content-type", "accept"):
|
||||||
|
continue
|
||||||
|
if kl == "authorization" and auth.type == "none":
|
||||||
|
parts = v.split(None, 1)
|
||||||
|
if len(parts) == 2 and parts[0].lower() == "bearer":
|
||||||
|
auth = MCPAuthConfig(type="bearer", token=parts[1].strip())
|
||||||
|
continue
|
||||||
|
if kl in ("x-api-key", "api-key") and auth.type == "none":
|
||||||
|
auth = MCPAuthConfig(type="api_key", api_key=v, header_name=k, api_key_in="header")
|
||||||
|
continue
|
||||||
|
extra_headers[k] = v
|
||||||
|
|
||||||
|
if extra_headers and auth.type == "none":
|
||||||
|
auth = MCPAuthConfig(type="headers", headers=extra_headers)
|
||||||
|
extra_headers = {}
|
||||||
|
|
||||||
|
name = derive_connector_name_from_url(clean_url, existing_names)
|
||||||
|
return MCPConnectorConfig(
|
||||||
|
name=name,
|
||||||
|
transport="auto",
|
||||||
|
url=clean_url,
|
||||||
|
headers=extra_headers,
|
||||||
|
auth=auth,
|
||||||
|
timeout_seconds=default_timeout,
|
||||||
|
source="bot",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _looks_like_structured_config(text: str) -> bool:
|
||||||
|
stripped = _strip_code_fences(text)
|
||||||
|
if not stripped:
|
||||||
|
return False
|
||||||
|
if stripped.startswith("{") or stripped.startswith("["):
|
||||||
|
return True
|
||||||
|
if "mcpServers:" in stripped or stripped.startswith("connectors:"):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _looks_like_url(token: str) -> bool:
|
||||||
|
return token.startswith("http://") or token.startswith("https://")
|
||||||
|
|
||||||
|
|
||||||
|
def _looks_like_stdio_command(tokens: list[str]) -> bool:
|
||||||
|
if not tokens:
|
||||||
|
return False
|
||||||
|
idx = 0
|
||||||
|
while idx < len(tokens) and _ENV_ASSIGN_RE.match(tokens[idx]):
|
||||||
|
idx += 1
|
||||||
|
if idx >= len(tokens):
|
||||||
|
return False
|
||||||
|
cmd = tokens[idx]
|
||||||
|
cmd_base = Path(cmd).name.lower()
|
||||||
|
if cmd_base in _COMMON_STDIO_COMMANDS:
|
||||||
|
return True
|
||||||
|
if cmd.startswith("/") or cmd.startswith("./") or cmd.startswith("~/"):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def looks_like_smart_mcp_input(raw_text: str) -> bool:
|
||||||
|
"""Return True if raw_text looks like a URL, JSON/YAML config, curl command, or stdio command."""
|
||||||
|
s = raw_text.strip()
|
||||||
|
if not s:
|
||||||
|
return False
|
||||||
|
if _looks_like_structured_config(s):
|
||||||
|
return True
|
||||||
|
if s.lower().startswith("curl "):
|
||||||
|
return True
|
||||||
|
try:
|
||||||
|
tokens = shlex.split(s)
|
||||||
|
except ValueError:
|
||||||
|
tokens = s.split()
|
||||||
|
if not tokens:
|
||||||
|
return False
|
||||||
|
if _looks_like_url(tokens[0]):
|
||||||
|
return True
|
||||||
|
if len(tokens) >= 2 and _looks_like_url(tokens[1]):
|
||||||
|
return True
|
||||||
|
if _looks_like_stdio_command(tokens):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def parse_smart_input(
|
||||||
|
raw_text: str,
|
||||||
|
*,
|
||||||
|
existing_names: Optional[set[str]] = None,
|
||||||
|
default_timeout: int = 60,
|
||||||
|
) -> tuple[list[MCPConnectorConfig], Optional[str]]:
|
||||||
|
"""Parse any free-form user input (URL, command, JSON/YAML, curl) into connector config(s).
|
||||||
|
|
||||||
|
Returns `(configs, inline_credential)` where `inline_credential` is an optional trailing
|
||||||
|
token/key supplied alongside a URL (e.g. `https://mcp.example.com/mcp ghp_xxx`) that should
|
||||||
|
be probed automatically.
|
||||||
|
"""
|
||||||
|
existing = set(existing_names or set())
|
||||||
|
text = raw_text.strip()
|
||||||
|
if not text:
|
||||||
|
raise ValueError("Пустой ввод. Отправьте URL, команду запуска или JSON-конфиг MCP-сервера.")
|
||||||
|
|
||||||
|
# 1. JSON or YAML snippet
|
||||||
|
if _looks_like_structured_config(text):
|
||||||
|
cleaned = _strip_code_fences(text)
|
||||||
|
try:
|
||||||
|
parsed = json.loads(cleaned)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
parsed = yaml.safe_load(cleaned)
|
||||||
|
|
||||||
|
# Support bare single server object without "name": {"url": "...", ...} or {"command": "..."}
|
||||||
|
if isinstance(parsed, dict) and "mcpServers" not in parsed and "connectors" not in parsed:
|
||||||
|
has_direct_target = any(k in parsed for k in ("url", "serverUrl", "server_url", "command"))
|
||||||
|
if has_direct_target and "name" not in parsed:
|
||||||
|
parsed = dict(parsed)
|
||||||
|
target_url = parsed.get("url") or parsed.get("serverUrl") or parsed.get("server_url")
|
||||||
|
if target_url:
|
||||||
|
parsed["name"] = derive_connector_name_from_url(str(target_url), existing)
|
||||||
|
else:
|
||||||
|
parsed["name"] = derive_connector_name_from_command(
|
||||||
|
str(parsed.get("command") or "stdio"),
|
||||||
|
list(parsed.get("args") or []),
|
||||||
|
existing,
|
||||||
|
)
|
||||||
|
|
||||||
|
configs = parse_connectors_payload(parsed, source="bot", default_timeout=default_timeout)
|
||||||
|
if not configs:
|
||||||
|
raise ValueError("В переданном JSON/YAML не найдено ни одного MCP-сервера.")
|
||||||
|
return configs, None
|
||||||
|
|
||||||
|
# 2. curl command
|
||||||
|
if text.lower().startswith("curl "):
|
||||||
|
cfg = _parse_curl_input(text, existing_names=existing, default_timeout=default_timeout)
|
||||||
|
return [cfg], None
|
||||||
|
|
||||||
|
# Tokenize shell-style
|
||||||
|
try:
|
||||||
|
tokens = shlex.split(text)
|
||||||
|
except ValueError as e:
|
||||||
|
raise ValueError(f"Не удалось разобрать ввод: {e}") from e
|
||||||
|
|
||||||
|
if not tokens:
|
||||||
|
raise ValueError("Пустой ввод.")
|
||||||
|
|
||||||
|
# 3. URL directly: `<url>` or `<url> <token_or_key>`
|
||||||
|
if _looks_like_url(tokens[0]):
|
||||||
|
clean_url, url_auth = _extract_url_credentials(tokens[0])
|
||||||
|
name = derive_connector_name_from_url(clean_url, existing)
|
||||||
|
inline_cred = " ".join(tokens[1:]).strip() or None
|
||||||
|
cfg = MCPConnectorConfig(
|
||||||
|
name=name,
|
||||||
|
transport="auto",
|
||||||
|
url=clean_url,
|
||||||
|
auth=url_auth,
|
||||||
|
timeout_seconds=default_timeout,
|
||||||
|
source="bot",
|
||||||
|
)
|
||||||
|
return [cfg], inline_cred
|
||||||
|
|
||||||
|
# 4. `<name> <url>` or `<name> <url> <token_or_key>`
|
||||||
|
if len(tokens) >= 2 and _looks_like_url(tokens[1]):
|
||||||
|
name = normalize_connector_name(tokens[0])
|
||||||
|
clean_url, url_auth = _extract_url_credentials(tokens[1])
|
||||||
|
inline_cred = " ".join(tokens[2:]).strip() or None
|
||||||
|
cfg = MCPConnectorConfig(
|
||||||
|
name=name,
|
||||||
|
transport="auto",
|
||||||
|
url=clean_url,
|
||||||
|
auth=url_auth,
|
||||||
|
timeout_seconds=default_timeout,
|
||||||
|
source="bot",
|
||||||
|
)
|
||||||
|
return [cfg], inline_cred
|
||||||
|
|
||||||
|
# 5. `<name> stdio <command> [args...]`
|
||||||
|
if len(tokens) >= 3 and tokens[1].lower() == "stdio":
|
||||||
|
name = normalize_connector_name(tokens[0])
|
||||||
|
env: dict[str, str] = {}
|
||||||
|
idx = 2
|
||||||
|
while idx < len(tokens):
|
||||||
|
m = _ENV_ASSIGN_RE.match(tokens[idx])
|
||||||
|
if not m:
|
||||||
|
break
|
||||||
|
env[m.group(1)] = m.group(2)
|
||||||
|
idx += 1
|
||||||
|
if idx >= len(tokens):
|
||||||
|
raise ValueError("Укажите команду запуска после `stdio`.")
|
||||||
|
cfg = MCPConnectorConfig(
|
||||||
|
name=name,
|
||||||
|
transport="stdio",
|
||||||
|
command=tokens[idx],
|
||||||
|
args=tokens[idx + 1 :],
|
||||||
|
env=env,
|
||||||
|
timeout_seconds=default_timeout,
|
||||||
|
source="bot",
|
||||||
|
)
|
||||||
|
return [cfg], None
|
||||||
|
|
||||||
|
# 6. Direct stdio command: `[KEY=VAL ...] npx -y @modelcontextprotocol/server-filesystem /tmp`
|
||||||
|
if _looks_like_stdio_command(tokens):
|
||||||
|
env = {}
|
||||||
|
idx = 0
|
||||||
|
while idx < len(tokens):
|
||||||
|
m = _ENV_ASSIGN_RE.match(tokens[idx])
|
||||||
|
if not m:
|
||||||
|
break
|
||||||
|
env[m.group(1)] = m.group(2)
|
||||||
|
idx += 1
|
||||||
|
command = tokens[idx]
|
||||||
|
args = tokens[idx + 1 :]
|
||||||
|
name = derive_connector_name_from_command(command, args, existing)
|
||||||
|
cfg = MCPConnectorConfig(
|
||||||
|
name=name,
|
||||||
|
transport="stdio",
|
||||||
|
command=command,
|
||||||
|
args=args,
|
||||||
|
env=env,
|
||||||
|
timeout_seconds=default_timeout,
|
||||||
|
source="bot",
|
||||||
|
)
|
||||||
|
return [cfg], None
|
||||||
|
|
||||||
|
raise ValueError(
|
||||||
|
"Не удалось распознать MCP-сервер. Отправьте:\n"
|
||||||
|
"• **URL** (например: `https://mcp.linear.app/mcp`)\n"
|
||||||
|
"• **Команду** (например: `npx -y @modelcontextprotocol/server-filesystem /tmp`)\n"
|
||||||
|
"• **JSON-конфиг** (`{\"mcpServers\": {...}}`)\n"
|
||||||
|
"• Или **`curl`** команду"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_hinted_env_vars(error_text: Optional[str]) -> list[str]:
|
||||||
|
if not error_text:
|
||||||
|
return []
|
||||||
|
seen: list[str] = []
|
||||||
|
for match in _STDIO_HINT_ENV_RE.finditer(error_text):
|
||||||
|
var = match.group(1)
|
||||||
|
if var not in seen:
|
||||||
|
seen.append(var)
|
||||||
|
return seen[:5]
|
||||||
|
|
||||||
|
|
||||||
|
def _is_auth_failure(state: MCPConnectorState) -> bool:
|
||||||
|
if state.status == "auth_required":
|
||||||
|
return True
|
||||||
|
if state.last_status_code in (401, 403):
|
||||||
|
return True
|
||||||
|
err = (state.last_error or "").lower()
|
||||||
|
return any(hint in err for hint in ("401", "403", "unauthorized", "forbidden", "authentication required"))
|
||||||
|
|
||||||
|
|
||||||
|
async def smart_connect_connector(
|
||||||
|
manager: MCPConnectorManager,
|
||||||
|
config: MCPConnectorConfig,
|
||||||
|
*,
|
||||||
|
inline_credential: Optional[str] = None,
|
||||||
|
) -> SmartProbeResult:
|
||||||
|
"""Save a connector, auto-probe transport & auth, and kick off OAuth automatically if advertised."""
|
||||||
|
if inline_credential and config.transport != "stdio" and config.auth.type == "none":
|
||||||
|
await manager.add_or_update_connector(config, connect_now=False, persist=True)
|
||||||
|
return await smart_apply_credentials_and_probe(manager, config.name, inline_credential)
|
||||||
|
|
||||||
|
state = await manager.add_or_update_connector(config, connect_now=True, persist=True)
|
||||||
|
if state.status == "connected":
|
||||||
|
return SmartProbeResult(
|
||||||
|
outcome="connected",
|
||||||
|
state=state,
|
||||||
|
detected_auth_label=config.auth.summary(),
|
||||||
|
)
|
||||||
|
|
||||||
|
if config.transport == "stdio":
|
||||||
|
return SmartProbeResult(
|
||||||
|
outcome="stdio_error",
|
||||||
|
state=state,
|
||||||
|
hinted_env_vars=_extract_hinted_env_vars(state.last_error),
|
||||||
|
)
|
||||||
|
|
||||||
|
if _is_auth_failure(state):
|
||||||
|
challenge = state.oauth_challenge or {}
|
||||||
|
www_auth = str(challenge.get("www_authenticate") or "")
|
||||||
|
resource_meta_url = challenge.get("resource_metadata_url")
|
||||||
|
|
||||||
|
# 1. Try OAuth 2.1 auto-discovery (RFC 9728 + RFC 8414 + RFC 7591 DCR)
|
||||||
|
discovered: dict[str, Any] = {}
|
||||||
|
if config.url:
|
||||||
|
try:
|
||||||
|
discovered = await manager.auth_manager.discover_oauth_metadata(
|
||||||
|
config.url,
|
||||||
|
resource_metadata_url=resource_meta_url,
|
||||||
|
verify_ssl=config.verify_ssl,
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug("Smart OAuth discovery error for '%s': %s", config.name, e)
|
||||||
|
|
||||||
|
has_pkce = bool(discovered.get("authorization_endpoint") and discovered.get("token_endpoint"))
|
||||||
|
has_cimd = bool(
|
||||||
|
discovered.get("client_id_metadata_document_supported")
|
||||||
|
and manager.auth_manager.default_client_metadata_url
|
||||||
|
)
|
||||||
|
can_auto_pkce = has_pkce and bool(
|
||||||
|
config.auth.client_id or discovered.get("registration_endpoint") or has_cimd
|
||||||
|
)
|
||||||
|
|
||||||
|
if can_auto_pkce:
|
||||||
|
try:
|
||||||
|
oauth_info = await manager.start_oauth(config.name)
|
||||||
|
return SmartProbeResult(
|
||||||
|
outcome="oauth_pkce_ready",
|
||||||
|
state=manager.get_connector(config.name) or state,
|
||||||
|
oauth_info=oauth_info,
|
||||||
|
discovered_oauth=discovered,
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.info("Auto OAuth PKCE start skipped for '%s': %s", config.name, e)
|
||||||
|
|
||||||
|
# 2. Check Basic Auth challenge
|
||||||
|
if www_auth.lower().startswith("basic"):
|
||||||
|
return SmartProbeResult(
|
||||||
|
outcome="need_basic",
|
||||||
|
state=state,
|
||||||
|
discovered_oauth=discovered or None,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 3. Ask user for a single credential paste (token / API key / user:pass / header)
|
||||||
|
return SmartProbeResult(
|
||||||
|
outcome="need_credentials",
|
||||||
|
state=state,
|
||||||
|
discovered_oauth=discovered or None,
|
||||||
|
)
|
||||||
|
|
||||||
|
return SmartProbeResult(outcome="error", state=state)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_kv_multiline(raw: str) -> dict[str, str]:
|
||||||
|
result: dict[str, str] = {}
|
||||||
|
for line in raw.splitlines():
|
||||||
|
for part in line.split(";"):
|
||||||
|
part = part.strip()
|
||||||
|
if not part:
|
||||||
|
continue
|
||||||
|
if "=" in part and (":" not in part or part.index("=") < part.index(":")):
|
||||||
|
k, v = part.split("=", 1)
|
||||||
|
elif ":" in part:
|
||||||
|
k, v = part.split(":", 1)
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
k, v = k.strip(), v.strip()
|
||||||
|
if k:
|
||||||
|
result[k] = v
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _build_credential_candidates(
|
||||||
|
raw_secret: str,
|
||||||
|
discovered_oauth: Optional[dict[str, Any]] = None,
|
||||||
|
) -> list[tuple[str, MCPAuthConfig]]:
|
||||||
|
"""Build an ordered list of `(label, MCPAuthConfig)` candidates to probe automatically."""
|
||||||
|
text = raw_secret.strip()
|
||||||
|
if not text:
|
||||||
|
return []
|
||||||
|
|
||||||
|
disc = discovered_oauth or {}
|
||||||
|
candidates: list[tuple[str, MCPAuthConfig]] = []
|
||||||
|
|
||||||
|
# 1. Explicit key=value OAuth parameters (multi-param)
|
||||||
|
kv = _parse_kv_multiline(text)
|
||||||
|
if "client_id" in kv and "client_secret" in kv and "authorization_url" not in kv:
|
||||||
|
candidates.append(
|
||||||
|
(
|
||||||
|
"OAuth 2.0 Client Credentials",
|
||||||
|
MCPAuthConfig(
|
||||||
|
type="oauth2_client_credentials",
|
||||||
|
client_id=kv["client_id"],
|
||||||
|
client_secret=kv["client_secret"],
|
||||||
|
token_url=kv.get("token_url") or disc.get("token_endpoint"),
|
||||||
|
scope=kv.get("scope"),
|
||||||
|
audience=kv.get("audience"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return candidates
|
||||||
|
|
||||||
|
if "refresh_token" in kv:
|
||||||
|
candidates.append(
|
||||||
|
(
|
||||||
|
"OAuth 2.0 Refresh Token",
|
||||||
|
MCPAuthConfig(
|
||||||
|
type="oauth2_refresh_token",
|
||||||
|
refresh_token=kv["refresh_token"],
|
||||||
|
token_url=kv.get("token_url") or disc.get("token_endpoint"),
|
||||||
|
client_id=kv.get("client_id"),
|
||||||
|
client_secret=kv.get("client_secret"),
|
||||||
|
scope=kv.get("scope"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return candidates
|
||||||
|
|
||||||
|
if "client_id" in kv and (
|
||||||
|
"authorization_url" in kv or disc.get("authorization_endpoint")
|
||||||
|
):
|
||||||
|
candidates.append(
|
||||||
|
(
|
||||||
|
"OAuth 2.1 PKCE",
|
||||||
|
MCPAuthConfig(
|
||||||
|
type="oauth2_pkce",
|
||||||
|
client_id=kv["client_id"],
|
||||||
|
client_secret=kv.get("client_secret"),
|
||||||
|
authorization_url=kv.get("authorization_url") or disc.get("authorization_endpoint"),
|
||||||
|
token_url=kv.get("token_url") or disc.get("token_endpoint"),
|
||||||
|
scope=kv.get("scope"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return candidates
|
||||||
|
|
||||||
|
# 1b. Client ID Metadata Document URL (MCP 2025-11-25 CIMD) pasted directly
|
||||||
|
if (
|
||||||
|
disc.get("client_id_metadata_document_supported")
|
||||||
|
and disc.get("authorization_endpoint")
|
||||||
|
and text.startswith("https://")
|
||||||
|
and " " not in text
|
||||||
|
):
|
||||||
|
scopes_list = disc.get("scopes_supported")
|
||||||
|
default_scope = (
|
||||||
|
" ".join(str(s) for s in scopes_list if s)
|
||||||
|
if isinstance(scopes_list, list) and scopes_list
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
candidates.append(
|
||||||
|
(
|
||||||
|
"OAuth 2.1 PKCE (Client Metadata URL)",
|
||||||
|
MCPAuthConfig(
|
||||||
|
type="oauth2_pkce",
|
||||||
|
client_id=text,
|
||||||
|
authorization_url=disc.get("authorization_endpoint"),
|
||||||
|
token_url=disc.get("token_endpoint"),
|
||||||
|
scope=default_scope,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return candidates
|
||||||
|
|
||||||
|
# 2. Explicit `Authorization: ...` or `Bearer <tok>` / `Token <tok>` / `ApiKey <tok>`
|
||||||
|
lower = text.lower()
|
||||||
|
if "\n" not in text and lower.startswith("bearer "):
|
||||||
|
tok = text[7:].strip()
|
||||||
|
candidates.append(("Bearer Token", MCPAuthConfig(type="bearer", token=tok)))
|
||||||
|
return candidates
|
||||||
|
|
||||||
|
if "\n" not in text and lower.startswith("authorization:"):
|
||||||
|
val = text.split(":", 1)[1].strip()
|
||||||
|
if val.lower().startswith("bearer "):
|
||||||
|
candidates.append(("Bearer Token", MCPAuthConfig(type="bearer", token=val[7:].strip())))
|
||||||
|
else:
|
||||||
|
candidates.append(("Custom Header (Authorization)", MCPAuthConfig(type="headers", headers={"Authorization": val})))
|
||||||
|
return candidates
|
||||||
|
|
||||||
|
# 3. Multiple headers (newline or semicolon separated `Header: Value`)
|
||||||
|
if ("\n" in text or ";" in text) and kv:
|
||||||
|
candidates.append(("Custom Headers", MCPAuthConfig(type="headers", headers=kv)))
|
||||||
|
return candidates
|
||||||
|
|
||||||
|
# 4. Single `Header-Name: value` (with space after colon or header-like left side with `-`)
|
||||||
|
if ":" in text and " " not in text.split(":", 1)[0]:
|
||||||
|
left, right = text.split(":", 1)
|
||||||
|
left_s, right_s = left.strip(), right.strip()
|
||||||
|
if ("-" in left_s or left_s.lower() in ("x-api-key", "apikey", "api-key", "authorization", "x-token", "x-auth-token")) and right_s:
|
||||||
|
candidates.append((f"API Key (header {left_s})", MCPAuthConfig(type="api_key", header_name=left_s, api_key=right_s, api_key_in="header")))
|
||||||
|
candidates.append(("Custom Headers", MCPAuthConfig(type="headers", headers={left_s: right_s})))
|
||||||
|
return candidates
|
||||||
|
# Looks like `username:password`
|
||||||
|
if " " not in text and right_s and not text.startswith(("http://", "https://")):
|
||||||
|
candidates.append(("Basic Auth", MCPAuthConfig(type="basic", username=left_s, password=right_s)))
|
||||||
|
# Also fallback to bearer/api_key in case token itself contains a colon (e.g. `id:secret`)
|
||||||
|
candidates.append(("Bearer Token", MCPAuthConfig(type="bearer", token=text)))
|
||||||
|
candidates.append(("API Key (X-API-Key)", MCPAuthConfig(type="api_key", api_key=text, header_name="X-API-Key", api_key_in="header")))
|
||||||
|
return candidates
|
||||||
|
|
||||||
|
# 5. Single `param=value` or `Header=value`
|
||||||
|
if "=" in text and " " not in text and text.count("=") == 1 and not text.endswith("="):
|
||||||
|
left, right = text.split("=", 1)
|
||||||
|
if left and right and re.match(r"^[A-Za-z][A-Za-z0-9_-]{1,31}$", left):
|
||||||
|
if left.lower() in _QUERY_AUTH_KEYS:
|
||||||
|
candidates.append((f"API Key (query {left})", MCPAuthConfig(type="api_key", api_key=right, query_param=left, api_key_in="query")))
|
||||||
|
candidates.append((f"API Key (header {left})", MCPAuthConfig(type="api_key", api_key=right, header_name=left, api_key_in="header")))
|
||||||
|
else:
|
||||||
|
candidates.append((f"API Key (header {left})", MCPAuthConfig(type="api_key", api_key=right, header_name=left, api_key_in="header")))
|
||||||
|
candidates.append((f"API Key (query {left})", MCPAuthConfig(type="api_key", api_key=right, query_param=left, api_key_in="query")))
|
||||||
|
candidates.append(("Bearer Token", MCPAuthConfig(type="bearer", token=text)))
|
||||||
|
return candidates
|
||||||
|
|
||||||
|
# 6. Plain token / API key -> probe common MCP auth schemes automatically!
|
||||||
|
candidates.extend(
|
||||||
|
[
|
||||||
|
("Bearer Token", MCPAuthConfig(type="bearer", token=text)),
|
||||||
|
("API Key (X-API-Key)", MCPAuthConfig(type="api_key", api_key=text, header_name="X-API-Key", api_key_in="header")),
|
||||||
|
("Authorization: ApiKey", MCPAuthConfig(type="bearer", token=text, token_prefix="ApiKey")),
|
||||||
|
("Authorization: Token", MCPAuthConfig(type="bearer", token=text, token_prefix="Token")),
|
||||||
|
("API Key (query api_key)", MCPAuthConfig(type="api_key", api_key=text, query_param="api_key", api_key_in="query")),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
return candidates
|
||||||
|
|
||||||
|
|
||||||
|
async def smart_apply_credentials_and_probe(
|
||||||
|
manager: MCPConnectorManager,
|
||||||
|
connector_name: str,
|
||||||
|
raw_secret: str,
|
||||||
|
*,
|
||||||
|
discovered_oauth: Optional[dict[str, Any]] = None,
|
||||||
|
hinted_env_vars: Optional[list[str]] = None,
|
||||||
|
) -> SmartProbeResult:
|
||||||
|
"""Automatically detect auth format from raw user credential, probe the MCP server, and save the winner."""
|
||||||
|
state = manager.get_connector(connector_name)
|
||||||
|
if state is None:
|
||||||
|
raise KeyError(f"Коннектор '{connector_name}' не найден.")
|
||||||
|
|
||||||
|
base_cfg = state.config
|
||||||
|
|
||||||
|
# Stdio: update ENV variables and reconnect
|
||||||
|
if base_cfg.transport == "stdio":
|
||||||
|
new_env = dict(base_cfg.env)
|
||||||
|
kv = _parse_kv_multiline(raw_secret)
|
||||||
|
if kv:
|
||||||
|
new_env.update(kv)
|
||||||
|
elif hinted_env_vars:
|
||||||
|
new_env[hinted_env_vars[0]] = raw_secret.strip()
|
||||||
|
else:
|
||||||
|
raise ValueError("Укажите переменную окружения в формате `API_KEY=значение`.")
|
||||||
|
|
||||||
|
updated_cfg = base_cfg.model_copy(update={"env": new_env, "source": "bot"})
|
||||||
|
new_state = await manager.add_or_update_connector(updated_cfg, connect_now=True, persist=True)
|
||||||
|
if new_state.status == "connected":
|
||||||
|
return SmartProbeResult(
|
||||||
|
outcome="connected",
|
||||||
|
state=new_state,
|
||||||
|
detected_auth_label=f"ENV ({', '.join(kv.keys() if kv else hinted_env_vars[:1])})",
|
||||||
|
)
|
||||||
|
return SmartProbeResult(
|
||||||
|
outcome="stdio_error",
|
||||||
|
state=new_state,
|
||||||
|
hinted_env_vars=_extract_hinted_env_vars(new_state.last_error),
|
||||||
|
)
|
||||||
|
|
||||||
|
candidates = _build_credential_candidates(raw_secret, discovered_oauth=discovered_oauth)
|
||||||
|
if not candidates:
|
||||||
|
raise ValueError("Пустые учётные данные.")
|
||||||
|
|
||||||
|
# If candidate is interactive OAuth2 PKCE (with user-supplied client_id), save and start PKCE!
|
||||||
|
if len(candidates) == 1 and candidates[0][1].type == "oauth2_pkce":
|
||||||
|
updated_cfg = base_cfg.model_copy(update={"auth": candidates[0][1], "source": "bot"})
|
||||||
|
await manager.add_or_update_connector(updated_cfg, connect_now=False, persist=True)
|
||||||
|
oauth_info = await manager.start_oauth(base_cfg.name)
|
||||||
|
return SmartProbeResult(
|
||||||
|
outcome="oauth_pkce_ready",
|
||||||
|
state=manager.get_connector(base_cfg.name) or state,
|
||||||
|
oauth_info=oauth_info,
|
||||||
|
detected_auth_label="OAuth 2.1 PKCE",
|
||||||
|
)
|
||||||
|
|
||||||
|
attempts: list[str] = []
|
||||||
|
last_error: Optional[str] = None
|
||||||
|
|
||||||
|
for label, auth_cfg in candidates:
|
||||||
|
attempts.append(label)
|
||||||
|
probe_cfg = base_cfg.model_copy(
|
||||||
|
update={
|
||||||
|
"auth": auth_cfg,
|
||||||
|
"timeout_seconds": min(base_cfg.timeout_seconds, 15),
|
||||||
|
"source": "bot",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
client = MCPClient(probe_cfg, manager.auth_manager)
|
||||||
|
try:
|
||||||
|
await client.connect()
|
||||||
|
await client.list_tools()
|
||||||
|
await client.close()
|
||||||
|
|
||||||
|
# Winner found! Persist with original timeout and connect through manager so tools register cleanly.
|
||||||
|
winning_cfg = base_cfg.model_copy(update={"auth": auth_cfg, "source": "bot"})
|
||||||
|
final_state = await manager.add_or_update_connector(winning_cfg, connect_now=True, persist=True)
|
||||||
|
return SmartProbeResult(
|
||||||
|
outcome="connected",
|
||||||
|
state=final_state,
|
||||||
|
detected_auth_label=label,
|
||||||
|
probe_attempts=attempts,
|
||||||
|
)
|
||||||
|
except (MCPAuthError, MCPAuthRequiredError, MCPProtocolError, Exception) as e:
|
||||||
|
last_error = str(e)
|
||||||
|
await client.close()
|
||||||
|
logger.debug("Smart auth probe '%s' failed for '%s': %s", label, base_cfg.name, e)
|
||||||
|
|
||||||
|
state.last_error = last_error or "Сервер отклонил переданные учётные данные."
|
||||||
|
return SmartProbeResult(
|
||||||
|
outcome="need_credentials",
|
||||||
|
state=state,
|
||||||
|
discovered_oauth=discovered_oauth,
|
||||||
|
probe_attempts=attempts,
|
||||||
|
)
|
||||||
@@ -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,793 @@
|
|||||||
|
"""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, tool
|
||||||
|
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,
|
||||||
|
default_client_metadata_url=self.settings.MCP_OAUTH_CLIENT_METADATA_URL,
|
||||||
|
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._discovered_oauth_cache: dict[str, dict[str, Any]] = {}
|
||||||
|
|
||||||
|
self._load_all_configs()
|
||||||
|
if self.settings.MCP_ENABLED:
|
||||||
|
self.register_management_tools()
|
||||||
|
|
||||||
|
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"))
|
||||||
|
if isinstance(raw_store, dict) and raw_store.get("default_client_metadata_url"):
|
||||||
|
if not self.auth_manager.default_client_metadata_url:
|
||||||
|
self.auth_manager.default_client_metadata_url = str(
|
||||||
|
raw_store["default_client_metadata_url"]
|
||||||
|
).strip()
|
||||||
|
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: dict[str, Any] = {
|
||||||
|
"connectors": {
|
||||||
|
name: cfg.model_dump(mode="json", exclude_none=True)
|
||||||
|
for name, cfg in self._bot_configs.items()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.auth_manager.default_client_metadata_url:
|
||||||
|
payload["default_client_metadata_url"] = self.auth_manager.default_client_metadata_url
|
||||||
|
try:
|
||||||
|
_write_json_atomic_private(self.storage_path, payload)
|
||||||
|
except PermissionError as e:
|
||||||
|
logger.error(
|
||||||
|
"Permission denied saving MCP connectors to %s (%s). "
|
||||||
|
"Connectors will stay active in memory until restart; fix directory ownership on DATA_DIR.",
|
||||||
|
self.storage_path,
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
|
||||||
|
def set_default_client_metadata_url(self, url: Optional[str]) -> Optional[str]:
|
||||||
|
"""Persist a default OAuth Client ID Metadata Document URL (MCP 2025-11-25 CIMD)."""
|
||||||
|
cleaned = (url or "").strip() or None
|
||||||
|
if cleaned is not None and not cleaned.startswith("https://"):
|
||||||
|
raise ValueError("Client ID Metadata URL должен начинаться с `https://`.")
|
||||||
|
self.auth_manager.default_client_metadata_url = cleaned
|
||||||
|
self._save_bot_store()
|
||||||
|
return cleaned
|
||||||
|
|
||||||
|
def register_management_tools(self) -> None:
|
||||||
|
"""Register built-in agent tools so the LLM can connect and manage MCP servers from natural language."""
|
||||||
|
manager = self
|
||||||
|
|
||||||
|
@tool(
|
||||||
|
name="mcp_connect",
|
||||||
|
description=(
|
||||||
|
"Подключить внешний MCP-сервер (Model Context Protocol) по URL, команде запуска (stdio), "
|
||||||
|
"curl-примеру или JSON-конфигу. Автоматически определяет транспорт (Streamable HTTP / SSE / Stdio), "
|
||||||
|
"обнаруживает OAuth 2.1 и регистрирует инструменты сервера."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
async def mcp_connect(source: str) -> str:
|
||||||
|
"""Подключить внешний MCP-сервер.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
source: URL MCP-сервера (например https://api.zenmoney.app/mcp), команда запуска, curl или JSON-конфиг
|
||||||
|
"""
|
||||||
|
from homeagent.mcp.autodiscover import parse_smart_input, smart_connect_connector
|
||||||
|
|
||||||
|
existing = {s.config.name for s in manager.list_connectors()}
|
||||||
|
configs, inline_cred = parse_smart_input(
|
||||||
|
source,
|
||||||
|
existing_names=existing,
|
||||||
|
default_timeout=manager.settings.MCP_REQUEST_TIMEOUT_SECONDS,
|
||||||
|
)
|
||||||
|
|
||||||
|
outputs: list[str] = []
|
||||||
|
for cfg in configs:
|
||||||
|
probe = await smart_connect_connector(
|
||||||
|
manager,
|
||||||
|
cfg,
|
||||||
|
inline_credential=inline_cred if len(configs) == 1 else None,
|
||||||
|
)
|
||||||
|
st = probe.state
|
||||||
|
if probe.discovered_oauth:
|
||||||
|
manager._discovered_oauth_cache[st.config.name] = probe.discovered_oauth
|
||||||
|
|
||||||
|
if probe.outcome == "connected":
|
||||||
|
tool_names = ", ".join(t.registered_name for t in st.tools[:15])
|
||||||
|
more = f" (+ ещё {len(st.tools) - 15})" if len(st.tools) > 15 else ""
|
||||||
|
outputs.append(
|
||||||
|
f"✅ MCP коннектор '{st.config.name}' подключён "
|
||||||
|
f"(транспорт: {st.resolved_transport}, авторизация: {probe.detected_auth_label or st.config.auth.type}, "
|
||||||
|
f"инструментов: {len(st.tools)}).\n"
|
||||||
|
f"Доступные инструменты: {tool_names}{more}"
|
||||||
|
)
|
||||||
|
elif probe.outcome == "oauth_pkce_ready" and probe.oauth_info:
|
||||||
|
outputs.append(
|
||||||
|
f"🔐 MCP коннектор '{st.config.name}' требует OAuth 2.1 авторизации.\n"
|
||||||
|
f"Передай пользователю эту ссылку для входа:\n{probe.oauth_info['authorize_url']}\n"
|
||||||
|
f"Попроси пользователя после подтверждения скопировать итоговую ссылку редиректа (или code) "
|
||||||
|
f"и отправить сюда — затем вызови `mcp_provide_auth(connector_name='{st.config.name}', credential_or_url=...)`."
|
||||||
|
)
|
||||||
|
elif probe.outcome == "oauth_device_ready" and probe.oauth_info:
|
||||||
|
uri = probe.oauth_info.get("verification_uri_complete") or probe.oauth_info.get("verification_uri")
|
||||||
|
outputs.append(
|
||||||
|
f"📱 MCP коннектор '{st.config.name}' требует OAuth Device Flow.\n"
|
||||||
|
f"Ссылка: {uri}\nКод: {probe.oauth_info['user_code']}"
|
||||||
|
)
|
||||||
|
elif probe.outcome == "need_basic":
|
||||||
|
outputs.append(
|
||||||
|
f"👤 MCP коннектор '{st.config.name}' требует Basic Auth (логин и пароль).\n"
|
||||||
|
f"Попроси пользователя прислать `login:password` и передай в `mcp_provide_auth(connector_name='{st.config.name}', credential_or_url=...)`."
|
||||||
|
)
|
||||||
|
elif probe.outcome == "need_credentials":
|
||||||
|
disc = probe.discovered_oauth or {}
|
||||||
|
extra = ""
|
||||||
|
if disc.get("authorization_endpoint"):
|
||||||
|
if disc.get("client_id_metadata_document_supported"):
|
||||||
|
extra = (
|
||||||
|
f"\nСервер поддерживает OAuth 2.1 ({disc['authorization_endpoint']}) через Client ID Metadata Document "
|
||||||
|
"(без Dynamic Client Registration), а также Bearer/API токен. "
|
||||||
|
"Пользователь может прислать: (1) личный токен/API-ключ, ИЛИ "
|
||||||
|
"(2) `client_id=...` (или HTTPS URL JSON-документа клиента), чтобы получить ссылку OAuth-входа."
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
extra = (
|
||||||
|
f"\nСервер поддерживает OAuth 2.1 ({disc['authorization_endpoint']}), "
|
||||||
|
"но без Dynamic Client Registration. Пользователь может прислать личный токен/API-ключ "
|
||||||
|
"или `client_id=...`."
|
||||||
|
)
|
||||||
|
outputs.append(
|
||||||
|
f"🔑 MCP коннектор '{st.config.name}' ({st.config.url}) требует авторизацию.{extra}\n"
|
||||||
|
f"Попроси пользователя прислать токен/ключ (или `client_id=...` / `login:password` / `Header: value`) "
|
||||||
|
f"и вызови `mcp_provide_auth(connector_name='{st.config.name}', credential_or_url=...)`."
|
||||||
|
)
|
||||||
|
elif probe.outcome == "stdio_error" and probe.hinted_env_vars:
|
||||||
|
outputs.append(
|
||||||
|
f"🔑 Локальному MCP '{st.config.name}' не хватает переменных окружения: {', '.join(probe.hinted_env_vars)}.\n"
|
||||||
|
f"Ошибка: {st.last_error}\n"
|
||||||
|
f"Попроси пользователя прислать значение и передай через `mcp_provide_auth`."
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
outputs.append(
|
||||||
|
f"❌ Не удалось подключить MCP '{st.config.name}': {st.last_error or st.status}"
|
||||||
|
)
|
||||||
|
|
||||||
|
return "\n\n".join(outputs)
|
||||||
|
|
||||||
|
@tool(
|
||||||
|
name="mcp_provide_auth",
|
||||||
|
description=(
|
||||||
|
"Передать токен, API-ключ, login:password, заголовок, OAuth client_id, "
|
||||||
|
"либо OAuth redirect URL / code для авторизации и подключения MCP-коннектора."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
async def mcp_provide_auth(connector_name: str, credential_or_url: str) -> str:
|
||||||
|
"""Авторизовать MCP-коннектор.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
connector_name: Имя MCP коннектора (например zenmoney, linear, github)
|
||||||
|
credential_or_url: Токен, API-ключ, login:password, Header: value, client_id=... или OAuth redirect URL / code
|
||||||
|
"""
|
||||||
|
from homeagent.mcp.autodiscover import smart_apply_credentials_and_probe
|
||||||
|
|
||||||
|
norm = normalize_connector_name(connector_name)
|
||||||
|
if manager.auth_manager.get_pending_pkce(norm) is not None:
|
||||||
|
st = await manager.complete_oauth_code(norm, credential_or_url)
|
||||||
|
if st.status == "connected":
|
||||||
|
tool_names = ", ".join(t.registered_name for t in st.tools[:15])
|
||||||
|
return (
|
||||||
|
f"✅ OAuth авторизация для '{norm}' завершена! Подключено инструментов: {len(st.tools)}.\n"
|
||||||
|
f"Инструменты: {tool_names}"
|
||||||
|
)
|
||||||
|
return f"⚠️ OAuth токен получен, но подключение '{norm}' завершилось статусом {st.status}: {st.last_error}"
|
||||||
|
|
||||||
|
probe = await smart_apply_credentials_and_probe(
|
||||||
|
manager,
|
||||||
|
norm,
|
||||||
|
credential_or_url,
|
||||||
|
discovered_oauth=manager._discovered_oauth_cache.get(norm),
|
||||||
|
)
|
||||||
|
st = probe.state
|
||||||
|
if probe.outcome == "connected":
|
||||||
|
tool_names = ", ".join(t.registered_name for t in st.tools[:15])
|
||||||
|
return (
|
||||||
|
f"✅ MCP коннектор '{norm}' авторизован и подключён! "
|
||||||
|
f"Метод: {probe.detected_auth_label}, транспорт: {st.resolved_transport}, "
|
||||||
|
f"инструментов: {len(st.tools)}.\nИнструменты: {tool_names}"
|
||||||
|
)
|
||||||
|
if probe.outcome == "oauth_pkce_ready" and probe.oauth_info:
|
||||||
|
return (
|
||||||
|
f"🔐 Ссылка для OAuth-входа в '{norm}':\n{probe.oauth_info['authorize_url']}\n"
|
||||||
|
f"Попроси пользователя открыть её, подтвердить доступ и прислать итоговую ссылку редиректа обратно."
|
||||||
|
)
|
||||||
|
tried = f" (проверены: {', '.join(probe.probe_attempts)})" if probe.probe_attempts else ""
|
||||||
|
return f"❌ Сервер '{norm}' отклонил учётные данные{tried}: {st.last_error or st.status}"
|
||||||
|
|
||||||
|
@tool(
|
||||||
|
name="mcp_list_connectors",
|
||||||
|
description="Показать список всех настроенных MCP-коннекторов, их статус и зарегистрированные инструменты.",
|
||||||
|
)
|
||||||
|
def mcp_list_connectors() -> str:
|
||||||
|
"""Список MCP коннекторов."""
|
||||||
|
states = manager.list_connectors()
|
||||||
|
if not states:
|
||||||
|
return "MCP коннекторы пока не настроены. Используй `mcp_connect` или команду `/mcp`."
|
||||||
|
lines = [f"MCP коннекторы ({len(states)}):"]
|
||||||
|
for st in states:
|
||||||
|
tools_preview = ", ".join(t.registered_name for t in st.tools[:8])
|
||||||
|
lines.append(
|
||||||
|
f"- {st.config.name}: status={st.status}, transport={st.resolved_transport or st.config.transport}, "
|
||||||
|
f"auth={st.config.auth.type}, tools={len(st.tools)}"
|
||||||
|
+ (f" [{tools_preview}]" if tools_preview else "")
|
||||||
|
+ (f" (error: {st.last_error})" if st.last_error else "")
|
||||||
|
)
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
@tool(
|
||||||
|
name="mcp_disconnect",
|
||||||
|
description="Отключить MCP-коннектор и убрать его инструменты из текущей сессии.",
|
||||||
|
)
|
||||||
|
async def mcp_disconnect(connector_name: str) -> str:
|
||||||
|
"""Отключить MCP-коннектор.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
connector_name: Имя MCP коннектора
|
||||||
|
"""
|
||||||
|
st = await manager.disconnect(connector_name)
|
||||||
|
return f"⏹ MCP коннектор '{st.config.name}' отключён."
|
||||||
|
|
||||||
|
@tool(
|
||||||
|
name="mcp_remove_connector",
|
||||||
|
description="Удалить MCP-коннектор и его сохранённые OAuth-токены.",
|
||||||
|
)
|
||||||
|
async def mcp_remove_connector(connector_name: str) -> str:
|
||||||
|
"""Удалить MCP-коннектор.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
connector_name: Имя MCP коннектора
|
||||||
|
"""
|
||||||
|
ok = await manager.remove_connector(connector_name)
|
||||||
|
if ok:
|
||||||
|
return f"🗑 MCP коннектор '{connector_name}' удалён."
|
||||||
|
return f"Коннектор '{connector_name}' не найден."
|
||||||
|
|
||||||
|
self.registry.register(mcp_connect)
|
||||||
|
self.registry.register(mcp_provide_auth)
|
||||||
|
self.registry.register(mcp_list_connectors)
|
||||||
|
self.registry.register(mcp_disconnect)
|
||||||
|
self.registry.register(mcp_remove_connector)
|
||||||
|
|
||||||
|
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.last_status_code = 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.last_status_code = 401
|
||||||
|
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)
|
||||||
|
state.last_status_code = e.status_code if isinstance(e, MCPProtocolError) else None
|
||||||
|
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,576 @@
|
|||||||
|
"""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
|
||||||
|
last_status_code: Optional[int] = 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)
|
logger.debug("Registered tool: %s (%s)", tool_def.name, tool_def.description)
|
||||||
return tool_def
|
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:
|
def unregister(self, name: str) -> bool:
|
||||||
if name in self._tools:
|
if name in self._tools:
|
||||||
del self._tools[name]
|
del self._tools[name]
|
||||||
@@ -45,11 +51,23 @@ class ToolRegistry:
|
|||||||
"""Convert all registered tools into google-genai FunctionDeclaration objects."""
|
"""Convert all registered tools into google-genai FunctionDeclaration objects."""
|
||||||
declarations: list[types.FunctionDeclaration] = []
|
declarations: list[types.FunctionDeclaration] = []
|
||||||
for tool_def in self._tools.values():
|
for tool_def in self._tools.values():
|
||||||
|
try:
|
||||||
fd = types.FunctionDeclaration(
|
fd = types.FunctionDeclaration(
|
||||||
name=tool_def.name,
|
name=tool_def.name,
|
||||||
description=tool_def.description,
|
description=tool_def.description,
|
||||||
parameters=tool_def.parameters_schema,
|
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)
|
declarations.append(fd)
|
||||||
return declarations
|
return declarations
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
"""Unit tests for agent factory."""
|
"""Unit tests for agent factory."""
|
||||||
|
|
||||||
|
from homeagent.agent.antigravity import AntigravityAgent
|
||||||
from homeagent.agent.factory import create_agent
|
from homeagent.agent.factory import create_agent
|
||||||
from homeagent.agent.gemini import GeminiAgent
|
from homeagent.agent.gemini import GeminiAgent
|
||||||
from homeagent.agent.openai_agent import OpenAIAgent
|
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.provider == "openai"
|
||||||
assert agent.base_url == "https://openrouter.ai/api/v1"
|
assert agent.base_url == "https://openrouter.ai/api/v1"
|
||||||
assert agent.model == "deepseek/deepseek-chat"
|
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,700 @@
|
|||||||
|
"""Unit tests for multimodal image and file attachments across Telegram handlers and all LLM agents."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import base64
|
||||||
|
from datetime import datetime
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import struct
|
||||||
|
from typing import Any
|
||||||
|
from unittest.mock import AsyncMock, MagicMock, patch
|
||||||
|
import zipfile
|
||||||
|
import zlib
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
from aiogram import Bot, Dispatcher
|
||||||
|
from aiogram.types import Chat, Document, Message, PhotoSize, Sticker, Update, User, Voice
|
||||||
|
|
||||||
|
from homeagent.agent.antigravity import AntigravityAgent
|
||||||
|
from homeagent.agent.attachments import (
|
||||||
|
Attachment,
|
||||||
|
build_default_attachment_prompt,
|
||||||
|
build_history_user_text,
|
||||||
|
normalize_mime_type,
|
||||||
|
stage_attachments_in_sandbox,
|
||||||
|
)
|
||||||
|
from homeagent.agent.conversation import ConversationManager
|
||||||
|
from homeagent.agent.gemini import GeminiAgent
|
||||||
|
from homeagent.agent.mcp_bridge import MCPToolBridge
|
||||||
|
from homeagent.agent.openai_agent import OpenAIAgent
|
||||||
|
from homeagent.bot.handlers import create_bot_router
|
||||||
|
from homeagent.bot.media import MediaGroupBuffer, extract_message_attachments
|
||||||
|
from homeagent.bot.progress import format_tool_progress
|
||||||
|
from homeagent.config import Settings
|
||||||
|
from homeagent.skills.manager import SkillManager
|
||||||
|
from homeagent.tools.registry import ToolRegistry
|
||||||
|
|
||||||
|
|
||||||
|
def _make_png(w: int = 4, h: int = 4, rgb: tuple[int, int, int] = (255, 0, 0)) -> bytes:
|
||||||
|
raw = b"".join(b"\x00" + bytes(rgb) * w for _ in range(h))
|
||||||
|
|
||||||
|
def _chunk(tag: bytes, data: bytes) -> bytes:
|
||||||
|
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
|
||||||
|
|
||||||
|
return (
|
||||||
|
b"\x89PNG\r\n\x1a\n"
|
||||||
|
+ _chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0))
|
||||||
|
+ _chunk(b"IDAT", zlib.compress(raw))
|
||||||
|
+ _chunk(b"IEND", b"")
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _make_docx(paragraphs: list[str]) -> bytes:
|
||||||
|
buf = io.BytesIO()
|
||||||
|
body = "".join(f"<w:p><w:r><w:t>{p}</w:t></w:r></w:p>" for p in paragraphs)
|
||||||
|
xml = (
|
||||||
|
'<?xml version="1.0" encoding="UTF-8"?>'
|
||||||
|
'<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">'
|
||||||
|
f"<w:body>{body}</w:body></w:document>"
|
||||||
|
)
|
||||||
|
with zipfile.ZipFile(buf, "w") as zf:
|
||||||
|
zf.writestr("word/document.xml", xml)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def _make_xlsx() -> bytes:
|
||||||
|
buf = io.BytesIO()
|
||||||
|
shared = (
|
||||||
|
'<?xml version="1.0" encoding="UTF-8"?>'
|
||||||
|
'<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
|
||||||
|
"<si><t>Name</t></si><si><t>Score</t></si><si><t>Alice</t></si>"
|
||||||
|
"</sst>"
|
||||||
|
)
|
||||||
|
sheet = (
|
||||||
|
'<?xml version="1.0" encoding="UTF-8"?>'
|
||||||
|
'<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>'
|
||||||
|
'<row r="1"><c r="A1" t="s"><v>0</v></c><c r="B1" t="s"><v>1</v></c></row>'
|
||||||
|
'<row r="2"><c r="A2" t="s"><v>2</v></c><c r="B2"><v>99</v></c></row>'
|
||||||
|
"</sheetData></worksheet>"
|
||||||
|
)
|
||||||
|
with zipfile.ZipFile(buf, "w") as zf:
|
||||||
|
zf.writestr("xl/sharedStrings.xml", shared)
|
||||||
|
zf.writestr("xl/worksheets/sheet1.xml", sheet)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
# Attachment model & extraction tests
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_attachment_mime_sniffing_and_text_extraction():
|
||||||
|
png_bytes = _make_png()
|
||||||
|
assert normalize_mime_type("file.bin", "application/octet-stream", data=png_bytes) == "image/png"
|
||||||
|
assert normalize_mime_type("scan.bin", None, data=b"%PDF-1.7\n...") == "application/pdf"
|
||||||
|
assert normalize_mime_type("script.py", "application/octet-stream", data=b"print(1)\n") in (
|
||||||
|
"text/x-python",
|
||||||
|
"text/plain",
|
||||||
|
"application/x-python-code",
|
||||||
|
)
|
||||||
|
|
||||||
|
py_att = Attachment(filename="script.py", mime_type="text/x-python", data=b"print('hello')\n")
|
||||||
|
assert py_att.is_text
|
||||||
|
assert py_att.extract_text() == "print('hello')\n"
|
||||||
|
|
||||||
|
png_att = Attachment(filename="shot.png", mime_type="image/png", data=png_bytes)
|
||||||
|
assert png_att.is_raster_image
|
||||||
|
assert not png_att.is_text
|
||||||
|
assert png_att.extract_text() is None
|
||||||
|
|
||||||
|
docx_att = Attachment(
|
||||||
|
filename="report.docx",
|
||||||
|
mime_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||||
|
data=_make_docx(["Привет мир", "Второй абзац"]),
|
||||||
|
)
|
||||||
|
assert docx_att.is_office_xml
|
||||||
|
assert docx_att.extract_text() == "Привет мир\nВторой абзац"
|
||||||
|
|
||||||
|
xlsx_att = Attachment(
|
||||||
|
filename="metrics.xlsx",
|
||||||
|
mime_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
data=_make_xlsx(),
|
||||||
|
)
|
||||||
|
xlsx_text = xlsx_att.extract_text()
|
||||||
|
assert xlsx_text is not None
|
||||||
|
assert "Name\tScore" in xlsx_text
|
||||||
|
assert "Alice\t99" in xlsx_text
|
||||||
|
|
||||||
|
|
||||||
|
def test_stage_attachments_in_sandbox_sanitizes_paths(tmp_path):
|
||||||
|
settings = Settings(DATA_DIR=tmp_path, SANDBOX_ENABLED=True)
|
||||||
|
att = Attachment(
|
||||||
|
filename="../../etc/evil name.csv",
|
||||||
|
mime_type="text/csv",
|
||||||
|
data=b"a,b\n1,2\n",
|
||||||
|
attachment_id="abcdef123456",
|
||||||
|
)
|
||||||
|
staged = stage_attachments_in_sandbox([att], settings)
|
||||||
|
assert len(staged) == 1
|
||||||
|
assert staged[0].sandbox_path is not None
|
||||||
|
assert staged[0].sandbox_path.startswith("uploads/abcdef12_")
|
||||||
|
assert ".." not in staged[0].sandbox_path
|
||||||
|
written = tmp_path / "sandbox_workspace" / staged[0].sandbox_path
|
||||||
|
assert written.read_bytes() == b"a,b\n1,2\n"
|
||||||
|
|
||||||
|
|
||||||
|
def test_default_prompt_and_history_summary():
|
||||||
|
img = Attachment(filename="pic.jpg", mime_type="image/jpeg", data=b"\xff\xd8\xff\xe0", kind="image")
|
||||||
|
assert "изображение" in build_default_attachment_prompt([img])
|
||||||
|
summary = build_history_user_text("Что тут?", [img])
|
||||||
|
assert "pic.jpg" in summary
|
||||||
|
assert "Что тут?" in summary
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
# Telegram media extraction & MediaGroupBuffer tests
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_extract_message_attachments_photo_doc_oversize_and_animated_sticker():
|
||||||
|
png_bytes = _make_png()
|
||||||
|
bot = MagicMock(spec=Bot)
|
||||||
|
|
||||||
|
async def fake_download(file_id: str, destination=None, **kwargs):
|
||||||
|
payload = {
|
||||||
|
"photo_large": png_bytes,
|
||||||
|
"doc_txt": b"hello world",
|
||||||
|
"voice_1": b"OggS\x00\x02data",
|
||||||
|
}[file_id]
|
||||||
|
if destination is not None:
|
||||||
|
destination.write(payload)
|
||||||
|
return destination
|
||||||
|
|
||||||
|
bot.download = AsyncMock(side_effect=fake_download)
|
||||||
|
chat = Chat(id=1, type="private")
|
||||||
|
user = User(id=1, is_bot=False, first_name="U")
|
||||||
|
|
||||||
|
msg_photo = Message(
|
||||||
|
message_id=1,
|
||||||
|
date=datetime.now(),
|
||||||
|
chat=chat,
|
||||||
|
from_user=user,
|
||||||
|
photo=[
|
||||||
|
PhotoSize(file_id="photo_small", file_unique_id="s1", width=90, height=90, file_size=500),
|
||||||
|
PhotoSize(file_id="photo_large", file_unique_id="l1", width=800, height=600, file_size=len(png_bytes)),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
msg_doc = Message(
|
||||||
|
message_id=2,
|
||||||
|
date=datetime.now(),
|
||||||
|
chat=chat,
|
||||||
|
from_user=user,
|
||||||
|
document=Document(file_id="doc_txt", file_unique_id="d1", file_name="notes.txt", mime_type="text/plain", file_size=11),
|
||||||
|
)
|
||||||
|
msg_huge = Message(
|
||||||
|
message_id=3,
|
||||||
|
date=datetime.now(),
|
||||||
|
chat=chat,
|
||||||
|
from_user=user,
|
||||||
|
document=Document(file_id="doc_huge", file_unique_id="d2", file_name="huge.zip", file_size=50 * 1024 * 1024),
|
||||||
|
)
|
||||||
|
msg_voice = Message(
|
||||||
|
message_id=4,
|
||||||
|
date=datetime.now(),
|
||||||
|
chat=chat,
|
||||||
|
from_user=user,
|
||||||
|
voice=Voice(file_id="voice_1", file_unique_id="v1", duration=3, mime_type="audio/ogg", file_size=10),
|
||||||
|
)
|
||||||
|
msg_tgs = Message(
|
||||||
|
message_id=5,
|
||||||
|
date=datetime.now(),
|
||||||
|
chat=chat,
|
||||||
|
from_user=user,
|
||||||
|
sticker=Sticker(
|
||||||
|
file_id="stk_1",
|
||||||
|
file_unique_id="st1",
|
||||||
|
type="regular",
|
||||||
|
width=512,
|
||||||
|
height=512,
|
||||||
|
is_animated=True,
|
||||||
|
is_video=False,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
atts, warns = await extract_message_attachments(
|
||||||
|
bot,
|
||||||
|
[msg_photo, msg_doc, msg_huge, msg_voice, msg_tgs],
|
||||||
|
max_size_bytes=5 * 1024 * 1024,
|
||||||
|
)
|
||||||
|
assert len(atts) == 3
|
||||||
|
assert atts[0].filename == "photo_l1.jpg"
|
||||||
|
assert atts[0].data == png_bytes
|
||||||
|
assert atts[1].filename == "notes.txt"
|
||||||
|
assert atts[2].kind == "voice"
|
||||||
|
assert atts[2].mime_type == "audio/ogg"
|
||||||
|
assert len(warns) == 2
|
||||||
|
assert any("huge.zip" in w for w in warns)
|
||||||
|
assert any(".tgs" in w for w in warns)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_media_group_buffer_batches_album():
|
||||||
|
buf = MediaGroupBuffer(delay_seconds=0.05, max_wait_seconds=0.5)
|
||||||
|
chat = Chat(id=10, type="private")
|
||||||
|
m1 = Message(message_id=101, date=datetime.now(), chat=chat, media_group_id="grp1", caption="Две фотки")
|
||||||
|
m2 = Message(message_id=102, date=datetime.now(), chat=chat, media_group_id="grp1")
|
||||||
|
|
||||||
|
t1 = asyncio.create_task(buf.collect(m1))
|
||||||
|
await asyncio.sleep(0.01)
|
||||||
|
res2 = await buf.collect(m2)
|
||||||
|
res1 = await t1
|
||||||
|
|
||||||
|
assert res2 is None
|
||||||
|
assert res1 is not None
|
||||||
|
assert [m.message_id for m in res1] == [101, 102]
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
# GeminiAgent multimodal tests
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_gemini_agent_sends_multimodal_parts_and_persists_compact_history(tmp_path):
|
||||||
|
settings = Settings(LLM_PROVIDER="gemini", GEMINI_API_KEY="fake-key", DATA_DIR=tmp_path)
|
||||||
|
cm = ConversationManager(tmp_path)
|
||||||
|
agent = GeminiAgent(settings=settings, registry=ToolRegistry(), conversation_manager=cm)
|
||||||
|
|
||||||
|
mock_resp = MagicMock()
|
||||||
|
mock_resp.function_calls = None
|
||||||
|
mock_resp.text = "На картинке красный квадрат, а в файле число 42."
|
||||||
|
|
||||||
|
mock_client = MagicMock()
|
||||||
|
mock_client.aio.models.generate_content = AsyncMock(return_value=mock_resp)
|
||||||
|
agent._client = mock_client
|
||||||
|
|
||||||
|
png_bytes = _make_png()
|
||||||
|
atts = [
|
||||||
|
Attachment(filename="red.png", mime_type="image/png", data=png_bytes, kind="image"),
|
||||||
|
Attachment(filename="data.txt", mime_type="text/plain", data=b"answer=42", kind="document"),
|
||||||
|
]
|
||||||
|
reply = await agent.chat(chat_id=1, thread_id=None, user_message="Разбери", attachments=atts)
|
||||||
|
assert "красный квадрат" in reply
|
||||||
|
|
||||||
|
sent_contents = mock_client.aio.models.generate_content.await_args.kwargs["contents"]
|
||||||
|
user_parts = sent_contents[-1].parts
|
||||||
|
assert any(getattr(p, "text", None) and "answer=42" in p.text for p in user_parts)
|
||||||
|
assert any(
|
||||||
|
getattr(p, "inline_data", None)
|
||||||
|
and p.inline_data.mime_type == "image/png"
|
||||||
|
and p.inline_data.data == png_bytes
|
||||||
|
for p in user_parts
|
||||||
|
)
|
||||||
|
|
||||||
|
# Saved session history must NOT contain raw binary bytes, only compact summary
|
||||||
|
saved_history = cm.get_openai_messages(1, None)
|
||||||
|
assert len(saved_history) == 2
|
||||||
|
assert "red.png" in saved_history[0]["content"]
|
||||||
|
assert "data.txt" in saved_history[0]["content"]
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
# OpenAIAgent & DeepSeek multimodal tests
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_openai_agent_sends_image_pdf_and_inline_text(tmp_path):
|
||||||
|
settings = Settings(LLM_PROVIDER="openai", OPENAI_API_KEY="sk-test", OPENAI_MODEL="gpt-4o", DATA_DIR=tmp_path)
|
||||||
|
cm = ConversationManager(tmp_path)
|
||||||
|
agent = OpenAIAgent(settings=settings, registry=ToolRegistry(), conversation_manager=cm)
|
||||||
|
|
||||||
|
mock_choice = MagicMock()
|
||||||
|
mock_choice.message.content = "Вижу фото, PDF и код."
|
||||||
|
mock_choice.message.tool_calls = None
|
||||||
|
mock_resp = MagicMock(choices=[mock_choice])
|
||||||
|
|
||||||
|
mock_client = MagicMock()
|
||||||
|
mock_client.chat.completions.create = AsyncMock(return_value=mock_resp)
|
||||||
|
agent._client = mock_client
|
||||||
|
|
||||||
|
png_bytes = _make_png()
|
||||||
|
pdf_bytes = b"%PDF-1.4\n%%EOF"
|
||||||
|
atts = [
|
||||||
|
Attachment(filename="screen.png", mime_type="image/png", data=png_bytes, kind="image"),
|
||||||
|
Attachment(filename="doc.pdf", mime_type="application/pdf", data=pdf_bytes, kind="document"),
|
||||||
|
Attachment(filename="main.py", mime_type="text/x-python", data=b"x = 123", kind="document"),
|
||||||
|
]
|
||||||
|
reply = await agent.chat(chat_id=2, thread_id=5, user_message="Проверь вложения", attachments=atts)
|
||||||
|
assert reply == "Вижу фото, PDF и код."
|
||||||
|
|
||||||
|
sent_messages = mock_client.chat.completions.create.await_args.kwargs["messages"]
|
||||||
|
user_content = sent_messages[-1]["content"]
|
||||||
|
assert isinstance(user_content, list)
|
||||||
|
block_types = [b["type"] for b in user_content]
|
||||||
|
assert block_types == ["text", "image_url", "file"]
|
||||||
|
assert "x = 123" in user_content[0]["text"]
|
||||||
|
assert user_content[1]["image_url"]["url"].startswith("data:image/png;base64,")
|
||||||
|
assert user_content[2]["file"]["filename"] == "doc.pdf"
|
||||||
|
assert user_content[2]["file"]["file_data"].startswith("data:application/pdf;base64,")
|
||||||
|
|
||||||
|
# History persisted as compact string (no base64 data URI)
|
||||||
|
saved = cm.get_openai_messages(2, 5)
|
||||||
|
assert isinstance(saved[0]["content"], str)
|
||||||
|
assert "base64," not in saved[0]["content"]
|
||||||
|
assert "screen.png" in saved[0]["content"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_deepseek_agent_inlines_text_and_avoids_image_url_blocks(tmp_path):
|
||||||
|
settings = Settings(LLM_PROVIDER="deepseek", DEEPSEEK_API_KEY="sk-ds", DATA_DIR=tmp_path)
|
||||||
|
cm = ConversationManager(tmp_path)
|
||||||
|
agent = OpenAIAgent(settings=settings, registry=ToolRegistry(), conversation_manager=cm)
|
||||||
|
|
||||||
|
mock_choice = MagicMock()
|
||||||
|
mock_choice.message.content = "Прочитал текст, картинку посмотреть не могу."
|
||||||
|
mock_choice.message.tool_calls = None
|
||||||
|
mock_resp = MagicMock(choices=[mock_choice])
|
||||||
|
|
||||||
|
mock_client = MagicMock()
|
||||||
|
mock_client.chat.completions.create = AsyncMock(return_value=mock_resp)
|
||||||
|
agent._client = mock_client
|
||||||
|
|
||||||
|
atts = [
|
||||||
|
Attachment(filename="pic.png", mime_type="image/png", data=_make_png(), kind="image"),
|
||||||
|
Attachment(filename="log.txt", mime_type="text/plain", data=b"ERROR: boom", kind="document"),
|
||||||
|
]
|
||||||
|
reply = await agent.chat(chat_id=3, thread_id=None, user_message="Что здесь?", attachments=atts)
|
||||||
|
assert "Прочитал текст" in reply
|
||||||
|
|
||||||
|
sent_messages = mock_client.chat.completions.create.await_args.kwargs["messages"]
|
||||||
|
user_content = sent_messages[-1]["content"]
|
||||||
|
assert isinstance(user_content, str)
|
||||||
|
assert "ERROR: boom" in user_content
|
||||||
|
assert "DeepSeek текстовый" in user_content
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
# MCPToolBridge & AntigravityAgent multimodal tests
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_mcp_tool_bridge_inspect_attachment_image_pdf_and_text(tmp_path):
|
||||||
|
bridge = MCPToolBridge(ToolRegistry())
|
||||||
|
png_bytes = _make_png()
|
||||||
|
pdf_bytes = b"%PDF-1.4\n%%EOF"
|
||||||
|
img = Attachment(filename="shot.png", mime_type="image/png", data=png_bytes, attachment_id="img1")
|
||||||
|
pdf = Attachment(filename="spec.pdf", mime_type="application/pdf", data=pdf_bytes, attachment_id="pdf1")
|
||||||
|
txt = Attachment(filename="note.md", mime_type="text/markdown", data=b"# Title\nBody", attachment_id="txt1")
|
||||||
|
|
||||||
|
bridge.register_attachments([img, pdf, txt])
|
||||||
|
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:
|
||||||
|
# Main endpoint exposes inspect_attachment; subagent endpoint does not
|
||||||
|
main_tools = (
|
||||||
|
await client.post(url, headers=headers, json={"jsonrpc": "2.0", "id": 1, "method": "tools/list"})
|
||||||
|
).json()["result"]["tools"]
|
||||||
|
assert any(t["name"] == "inspect_attachment" for t in main_tools)
|
||||||
|
|
||||||
|
sub_tools = (
|
||||||
|
await client.post(sub_url, headers=headers, json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
|
||||||
|
).json()["result"]["tools"]
|
||||||
|
assert all(t["name"] != "inspect_attachment" for t in sub_tools)
|
||||||
|
|
||||||
|
# 1. Image returns native MCP image block
|
||||||
|
img_res = (
|
||||||
|
await client.post(
|
||||||
|
url,
|
||||||
|
headers=headers,
|
||||||
|
json={
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": 3,
|
||||||
|
"method": "tools/call",
|
||||||
|
"params": {"name": "inspect_attachment", "arguments": {"attachment_id": "img1"}},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
).json()["result"]
|
||||||
|
assert img_res["isError"] is False
|
||||||
|
assert img_res["content"][1]["type"] == "image"
|
||||||
|
assert img_res["content"][1]["mimeType"] == "image/png"
|
||||||
|
assert base64.b64decode(img_res["content"][1]["data"]) == png_bytes
|
||||||
|
|
||||||
|
# 2. PDF returns native MCP resource blob
|
||||||
|
pdf_res = (
|
||||||
|
await client.post(
|
||||||
|
url,
|
||||||
|
headers=headers,
|
||||||
|
json={
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": 4,
|
||||||
|
"method": "tools/call",
|
||||||
|
"params": {"name": "inspect_attachment", "arguments": {"attachment_id": "pdf1"}},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
).json()["result"]
|
||||||
|
assert pdf_res["isError"] is False
|
||||||
|
assert pdf_res["content"][1]["type"] == "resource"
|
||||||
|
assert pdf_res["content"][1]["resource"]["mimeType"] == "application/pdf"
|
||||||
|
assert base64.b64decode(pdf_res["content"][1]["resource"]["blob"]) == pdf_bytes
|
||||||
|
|
||||||
|
# 3. Text returns text content
|
||||||
|
txt_res = (
|
||||||
|
await client.post(
|
||||||
|
url,
|
||||||
|
headers=headers,
|
||||||
|
json={
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": 5,
|
||||||
|
"method": "tools/call",
|
||||||
|
"params": {"name": "inspect_attachment", "arguments": {"attachment_id": "txt1"}},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
).json()["result"]
|
||||||
|
assert txt_res["isError"] is False
|
||||||
|
assert "# Title" in txt_res["content"][0]["text"]
|
||||||
|
|
||||||
|
# mcp_config.json marks inspect_attachment as eager
|
||||||
|
cfg_path = bridge.write_mcp_config(tmp_path)
|
||||||
|
cfg = json.loads(cfg_path.read_text(encoding="utf-8"))
|
||||||
|
assert cfg["mcpServers"]["homeagent"]["tools"]["inspect_attachment"] == {"eager": True}
|
||||||
|
finally:
|
||||||
|
await bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_antigravity_agent_chat_with_attachments_keeps_read_file_denied(tmp_path):
|
||||||
|
settings = Settings(LLM_PROVIDER="antigravity", DATA_DIR=tmp_path)
|
||||||
|
cm = ConversationManager(tmp_path)
|
||||||
|
agent = AntigravityAgent(settings=settings, registry=ToolRegistry(), conversation_manager=cm)
|
||||||
|
|
||||||
|
captured_cmd: list[str] = []
|
||||||
|
|
||||||
|
class _FakeStream:
|
||||||
|
def __init__(self, lines: list[bytes]) -> None:
|
||||||
|
self._lines = list(lines)
|
||||||
|
|
||||||
|
async def readline(self) -> bytes:
|
||||||
|
return self._lines.pop(0) if self._lines else b""
|
||||||
|
|
||||||
|
async def read(self) -> bytes:
|
||||||
|
return b"".join(self._lines)
|
||||||
|
|
||||||
|
class _FakeProc:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.stdout = _FakeStream(
|
||||||
|
[
|
||||||
|
(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"event": "result",
|
||||||
|
"result": {
|
||||||
|
"conversation_id": "conv-att-1",
|
||||||
|
"status": "SUCCESS",
|
||||||
|
"response": "На фото зелёный квадрат, конфиг корректный.",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
+ "\n"
|
||||||
|
).encode("utf-8")
|
||||||
|
]
|
||||||
|
)
|
||||||
|
self.stderr = _FakeStream([])
|
||||||
|
self.returncode = 0
|
||||||
|
|
||||||
|
async def wait(self) -> int:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
async def fake_exec(*cmd: str, **kwargs: Any) -> _FakeProc:
|
||||||
|
captured_cmd.extend(cmd)
|
||||||
|
return _FakeProc()
|
||||||
|
|
||||||
|
img = Attachment(filename="green.png", mime_type="image/png", data=_make_png(), attachment_id="att999")
|
||||||
|
cfg_att = Attachment(filename="app.json", mime_type="application/json", data=b'{"ok": true}', attachment_id="att888")
|
||||||
|
|
||||||
|
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=50, thread_id=None, user_message="Проверь", attachments=[img, cfg_att])
|
||||||
|
assert "зелёный квадрат" in res
|
||||||
|
prompt = captured_cmd[captured_cmd.index("-p") + 1]
|
||||||
|
assert "mcp_homeagent_inspect_attachment" in prompt
|
||||||
|
assert "att999" in prompt
|
||||||
|
assert '{"ok": true}' in prompt
|
||||||
|
|
||||||
|
# Host read_file(*) MUST remain strictly denied
|
||||||
|
settings_arg = json.loads(captured_cmd[captured_cmd.index("--settings") + 1])
|
||||||
|
assert "read_file(*)" in settings_arg["permissions"]["deny"]
|
||||||
|
assert agent._bridge.get_attachment("att999") is not None
|
||||||
|
finally:
|
||||||
|
await agent.close()
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
# End-to-end Telegram handler tests (photo, reply, album, ghost mode)
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_handle_message_photo_without_caption_and_reply_attachment(tmp_path):
|
||||||
|
settings = Settings(ALLOWED_TELEGRAM_USER_IDS=[111], DATA_DIR=tmp_path)
|
||||||
|
agent = MagicMock()
|
||||||
|
agent.chat = AsyncMock(return_value="Это красная картинка!")
|
||||||
|
router = create_bot_router(settings, agent, SkillManager(tmp_path / "skills"), ToolRegistry())
|
||||||
|
dp = Dispatcher()
|
||||||
|
dp.include_router(router)
|
||||||
|
|
||||||
|
png_bytes = _make_png()
|
||||||
|
bot = MagicMock(spec=Bot)
|
||||||
|
bot.send_rich_message = AsyncMock()
|
||||||
|
bot.send_message = AsyncMock(return_value=MagicMock(edit_text=AsyncMock(), delete=AsyncMock()))
|
||||||
|
bot.send_chat_action = AsyncMock()
|
||||||
|
|
||||||
|
async def fake_download(file_id: str, destination=None, **kwargs):
|
||||||
|
if destination is not None:
|
||||||
|
destination.write(png_bytes)
|
||||||
|
return destination
|
||||||
|
|
||||||
|
bot.download = AsyncMock(side_effect=fake_download)
|
||||||
|
|
||||||
|
user = User(id=111, is_bot=False, first_name="Owner")
|
||||||
|
chat = Chat(id=111, type="private")
|
||||||
|
photo_msg = Message(
|
||||||
|
message_id=10,
|
||||||
|
date=datetime.now(),
|
||||||
|
chat=chat,
|
||||||
|
from_user=user,
|
||||||
|
photo=[PhotoSize(file_id="p_1", file_unique_id="u1", width=64, height=64, file_size=len(png_bytes))],
|
||||||
|
)
|
||||||
|
photo_msg._bot = bot
|
||||||
|
|
||||||
|
await dp.feed_update(bot, Update(update_id=1, message=photo_msg))
|
||||||
|
|
||||||
|
agent.chat.assert_awaited_once()
|
||||||
|
kwargs = agent.chat.await_args.kwargs
|
||||||
|
assert "изображение без подписи" in kwargs["user_message"]
|
||||||
|
assert len(kwargs["attachments"]) == 1
|
||||||
|
assert kwargs["attachments"][0].mime_type == "image/png"
|
||||||
|
assert kwargs["attachments"][0].data == png_bytes
|
||||||
|
bot.send_rich_message.assert_awaited_once()
|
||||||
|
|
||||||
|
# Now test replying to a photo with a text question
|
||||||
|
agent.chat.reset_mock()
|
||||||
|
reply_msg = Message(
|
||||||
|
message_id=11,
|
||||||
|
date=datetime.now(),
|
||||||
|
chat=chat,
|
||||||
|
from_user=user,
|
||||||
|
text="Какой здесь цвет?",
|
||||||
|
reply_to_message=photo_msg,
|
||||||
|
)
|
||||||
|
reply_msg._bot = bot
|
||||||
|
|
||||||
|
await dp.feed_update(bot, Update(update_id=2, message=reply_msg))
|
||||||
|
agent.chat.assert_awaited_once()
|
||||||
|
reply_kwargs = agent.chat.await_args.kwargs
|
||||||
|
assert reply_kwargs["user_message"] == "Какой здесь цвет?"
|
||||||
|
assert len(reply_kwargs["attachments"]) == 1
|
||||||
|
assert reply_kwargs["attachments"][0].source == "reply"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_handle_message_oversized_document_replies_with_warning(tmp_path):
|
||||||
|
settings = Settings(ALLOWED_TELEGRAM_USER_IDS=[111], MAX_ATTACHMENT_SIZE_MB=1, DATA_DIR=tmp_path)
|
||||||
|
agent = MagicMock()
|
||||||
|
agent.chat = AsyncMock()
|
||||||
|
router = create_bot_router(settings, agent, SkillManager(tmp_path / "skills"), ToolRegistry())
|
||||||
|
dp = Dispatcher()
|
||||||
|
dp.include_router(router)
|
||||||
|
|
||||||
|
bot = MagicMock(spec=Bot)
|
||||||
|
bot.send_rich_message = AsyncMock()
|
||||||
|
bot.send_message = AsyncMock(return_value=MagicMock(edit_text=AsyncMock(), delete=AsyncMock()))
|
||||||
|
bot.send_chat_action = AsyncMock()
|
||||||
|
|
||||||
|
user = User(id=111, is_bot=False, first_name="Owner")
|
||||||
|
chat = Chat(id=111, type="private")
|
||||||
|
huge_msg = Message(
|
||||||
|
message_id=20,
|
||||||
|
date=datetime.now(),
|
||||||
|
chat=chat,
|
||||||
|
from_user=user,
|
||||||
|
document=Document(file_id="big", file_unique_id="b1", file_name="video.zip", file_size=5 * 1024 * 1024),
|
||||||
|
)
|
||||||
|
huge_msg._bot = bot
|
||||||
|
|
||||||
|
await dp.feed_update(bot, Update(update_id=3, message=huge_msg))
|
||||||
|
agent.chat.assert_not_awaited()
|
||||||
|
bot.send_rich_message.assert_awaited_once()
|
||||||
|
sent_md = bot.send_rich_message.await_args.kwargs["rich_message"].markdown
|
||||||
|
assert "video.zip" in sent_md
|
||||||
|
assert "слишком большой" in sent_md
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_guest_message_with_replied_photo(tmp_path):
|
||||||
|
settings = Settings(GHOST_MODE_ENABLED=True, ALLOWED_TELEGRAM_USER_IDS=[777], DATA_DIR=tmp_path)
|
||||||
|
agent = MagicMock()
|
||||||
|
agent.chat = AsyncMock(return_value="На скриншоте ошибка 502.")
|
||||||
|
router = create_bot_router(settings, agent, SkillManager(tmp_path / "skills"), ToolRegistry())
|
||||||
|
dp = Dispatcher()
|
||||||
|
dp.include_router(router)
|
||||||
|
|
||||||
|
png_bytes = _make_png()
|
||||||
|
bot = MagicMock(spec=Bot)
|
||||||
|
bot.get_me = AsyncMock(return_value=MagicMock(username="homeagent_bot"))
|
||||||
|
bot.answer_guest_query = AsyncMock()
|
||||||
|
bot.send_chat_action = AsyncMock()
|
||||||
|
|
||||||
|
async def fake_download(file_id: str, destination=None, **kwargs):
|
||||||
|
if destination is not None:
|
||||||
|
destination.write(png_bytes)
|
||||||
|
return destination
|
||||||
|
|
||||||
|
bot.download = AsyncMock(side_effect=fake_download)
|
||||||
|
|
||||||
|
replied = Message(
|
||||||
|
message_id=50,
|
||||||
|
date=datetime.now(),
|
||||||
|
chat=Chat(id=-100500, type="supergroup"),
|
||||||
|
from_user=User(id=222, is_bot=False, first_name="Alice"),
|
||||||
|
photo=[PhotoSize(file_id="gp_1", file_unique_id="gu1", width=320, height=240, file_size=len(png_bytes))],
|
||||||
|
caption="Смотрите что вылезло",
|
||||||
|
)
|
||||||
|
caller = User(id=777, is_bot=False, first_name="Owner")
|
||||||
|
guest = Message(
|
||||||
|
message_id=51,
|
||||||
|
date=datetime.now(),
|
||||||
|
chat=Chat(id=-100500, type="supergroup"),
|
||||||
|
from_user=caller,
|
||||||
|
reply_to_message=replied,
|
||||||
|
text="@homeagent_bot что это за ошибка?",
|
||||||
|
guest_query_id="gq_photo_1",
|
||||||
|
guest_bot_caller_user=caller,
|
||||||
|
)
|
||||||
|
guest._bot = bot
|
||||||
|
|
||||||
|
await dp.feed_update(bot, Update(update_id=4, guest_message=guest))
|
||||||
|
|
||||||
|
agent.chat.assert_awaited_once()
|
||||||
|
kwargs = agent.chat.await_args.kwargs
|
||||||
|
assert "Смотрите что вылезло" in kwargs["user_message"]
|
||||||
|
assert "что это за ошибка?" in kwargs["user_message"]
|
||||||
|
assert len(kwargs["attachments"]) == 1
|
||||||
|
assert kwargs["attachments"][0].source == "reply"
|
||||||
|
bot.answer_guest_query.assert_awaited_once()
|
||||||
|
|
||||||
|
|
||||||
|
def test_progress_format_for_inspect_attachment():
|
||||||
|
assert "прикреплённый файл" in format_tool_progress("inspect_attachment", {"attachment_id": "abc"})
|
||||||
@@ -0,0 +1,662 @@
|
|||||||
|
"""Tests for MCP Connectors Telegram Bot interface: zero-config Smart Connect, manual wizard, commands, ghost mode, whitelist."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
import textwrap
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
from unittest.mock import AsyncMock, MagicMock
|
||||||
|
from urllib.parse import parse_qs, urlparse
|
||||||
|
|
||||||
|
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.autodiscover import (
|
||||||
|
derive_connector_name_from_command,
|
||||||
|
derive_connector_name_from_url,
|
||||||
|
parse_smart_input,
|
||||||
|
)
|
||||||
|
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,
|
||||||
|
expected_api_key_header: tuple[str, 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 expected_api_key_header:
|
||||||
|
hdr_name, hdr_val = expected_api_key_header
|
||||||
|
if request.headers.get(hdr_name) != hdr_val:
|
||||||
|
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: AsyncMock, 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
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
# Smart name derivation & free-form parsing tests
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_smart_name_derivation_and_input_parsing():
|
||||||
|
assert derive_connector_name_from_url("https://mcp.linear.app/mcp") == "linear"
|
||||||
|
assert derive_connector_name_from_url("https://mcp.notion.com/sse", {"notion"}) == "notion_2"
|
||||||
|
assert derive_connector_name_from_url("http://127.0.0.1:8080/weather/mcp") == "weather"
|
||||||
|
assert derive_connector_name_from_url("http://127.0.0.1:8080/mcp") == "local_8080"
|
||||||
|
|
||||||
|
assert derive_connector_name_from_command("npx", ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]) == "filesystem"
|
||||||
|
assert derive_connector_name_from_command("uvx", ["mcp-server-git"]) == "git"
|
||||||
|
assert derive_connector_name_from_command("python3", ["/opt/my_weather.py"]) == "my_weather"
|
||||||
|
|
||||||
|
# Embedded URL Basic Auth
|
||||||
|
cfgs, cred = parse_smart_input("https://bob:s3cr3t@mcp.acme.io/mcp")
|
||||||
|
assert cred is None and len(cfgs) == 1
|
||||||
|
assert cfgs[0].name == "acme"
|
||||||
|
assert cfgs[0].url == "https://mcp.acme.io/mcp"
|
||||||
|
assert cfgs[0].auth.type == "basic" and cfgs[0].auth.username == "bob" and cfgs[0].auth.password == "s3cr3t"
|
||||||
|
|
||||||
|
# Embedded query API key
|
||||||
|
cfgs_q, _ = parse_smart_input("https://mcp.example.com/mcp?api_key=k123&other=1")
|
||||||
|
assert cfgs_q[0].auth.type == "api_key" and cfgs_q[0].auth.api_key_in == "query" and cfgs_q[0].auth.api_key == "k123"
|
||||||
|
assert "api_key" not in (cfgs_q[0].url or "") and "other=1" in (cfgs_q[0].url or "")
|
||||||
|
|
||||||
|
# curl snippet
|
||||||
|
cfgs_curl, _ = parse_smart_input('curl -H "Authorization: Bearer tok_abc" https://mcp.github.com/mcp')
|
||||||
|
assert cfgs_curl[0].name == "github"
|
||||||
|
assert cfgs_curl[0].auth.type == "bearer" and cfgs_curl[0].auth.token == "tok_abc"
|
||||||
|
|
||||||
|
# Bare JSON without name or mcpServers wrapper
|
||||||
|
cfgs_json, _ = parse_smart_input('{"url": "https://mcp.stripe.com/mcp", "headers": {"X-Api": "1"}}')
|
||||||
|
assert cfgs_json[0].name == "stripe"
|
||||||
|
|
||||||
|
# Stdio command with leading ENV vars
|
||||||
|
cfgs_stdio, _ = parse_smart_input("GITHUB_TOKEN=ghp_1 npx -y @modelcontextprotocol/server-github")
|
||||||
|
assert cfgs_stdio[0].transport == "stdio"
|
||||||
|
assert cfgs_stdio[0].name == "github"
|
||||||
|
assert cfgs_stdio[0].env == {"GITHUB_TOKEN": "ghp_1"}
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
# Zero-Config Smart Connect E2E tests (user pastes ONLY URL + raw key, or ONLY URL for OAuth!)
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_smart_connect_auto_probes_x_api_key_without_user_knowing_auth_type(tmp_path):
|
||||||
|
"""User clicks Add -> pastes JUST a URL -> bot detects 401 -> user pastes JUST the raw key -> bot auto-detects X-API-Key!"""
|
||||||
|
runner, mcp_url = await _start_mock_mcp_server(expected_api_key_header=("X-API-Key", "raw-secret-key-777"))
|
||||||
|
try:
|
||||||
|
settings = Settings(
|
||||||
|
ALLOWED_TELEGRAM_USER_IDS=[101],
|
||||||
|
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()
|
||||||
|
wl = WhitelistMiddleware(settings)
|
||||||
|
dp.message.middleware(wl)
|
||||||
|
dp.callback_query.middleware(wl)
|
||||||
|
dp.include_router(router)
|
||||||
|
bot = _make_mock_bot()
|
||||||
|
|
||||||
|
# 1. User simply sends `/mcp <url>` — no name, no transport, no auth type!
|
||||||
|
await dp.feed_update(bot, Update(update_id=1, message=_make_message(bot, 101, 101, f"/mcp {mcp_url}", msg_id=1)))
|
||||||
|
prompt_md = bot.send_rich_message.await_args.kwargs["rich_message"].markdown
|
||||||
|
assert "требует авторизацию" in prompt_md
|
||||||
|
|
||||||
|
# 2. User simply replies with the raw API key string (without knowing it goes into X-API-Key!)
|
||||||
|
await dp.feed_update(bot, Update(update_id=2, message=_make_message(bot, 101, 101, "raw-secret-key-777", msg_id=2)))
|
||||||
|
|
||||||
|
# Secret message deleted, never echoed, auth auto-detected as api_key (X-API-Key), tools registered!
|
||||||
|
bot.delete_message.assert_awaited_once()
|
||||||
|
reply_md = bot.send_rich_message.await_args.kwargs["rich_message"].markdown
|
||||||
|
assert "подключён" in reply_md
|
||||||
|
assert "X-API-Key" in reply_md
|
||||||
|
assert "raw-secret-key-777" not in reply_md
|
||||||
|
|
||||||
|
connectors = manager.list_connectors()
|
||||||
|
assert len(connectors) == 1
|
||||||
|
conn = connectors[0]
|
||||||
|
assert conn.status == "connected"
|
||||||
|
assert conn.config.auth.type == "api_key"
|
||||||
|
assert conn.config.auth.header_name == "X-API-Key"
|
||||||
|
assert await registry.execute(conn.tools[0].registered_name, {"who": "Magic"}) == "Hello, Magic!"
|
||||||
|
|
||||||
|
agent.chat.assert_not_awaited()
|
||||||
|
await manager.close()
|
||||||
|
finally:
|
||||||
|
await runner.cleanup()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_smart_connect_auto_discovers_and_completes_oauth_pkce_from_url_alone(tmp_path):
|
||||||
|
"""User pastes ONLY a URL -> bot hits 401 -> auto-discovers OAuth + DCR -> sends login link -> user pastes redirect URL -> connected!"""
|
||||||
|
oauth_state: dict[str, Any] = {"valid_tokens": set(), "issued_codes": {}}
|
||||||
|
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"]]}
|
||||||
|
)
|
||||||
|
|
||||||
|
async def handle_as(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",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
async def handle_dcr(request: web.Request) -> web.Response:
|
||||||
|
return web.json_response({"client_id": "auto-dcr-client"}, status=201)
|
||||||
|
|
||||||
|
async def handle_token(request: web.Request) -> web.Response:
|
||||||
|
form = await request.post()
|
||||||
|
verifier = form.get("code_verifier", "")
|
||||||
|
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode("ascii")).digest()).rstrip(b"=").decode("ascii")
|
||||||
|
if oauth_state["issued_codes"].get(form.get("code")) != challenge:
|
||||||
|
return web.json_response({"error": "invalid_grant"}, status=400)
|
||||||
|
oauth_state["valid_tokens"].add("smart-oauth-tok")
|
||||||
|
return web.json_response({"access_token": "smart-oauth-tok", "token_type": "Bearer", "expires_in": 3600})
|
||||||
|
|
||||||
|
async def handle_mcp(request: web.Request) -> web.Response:
|
||||||
|
if request.headers.get("Authorization") != "Bearer smart-oauth-tok":
|
||||||
|
return web.Response(
|
||||||
|
status=401,
|
||||||
|
headers={"WWW-Authenticate": f'Bearer resource_metadata="{base_url_holder["url"]}/.well-known/oauth-protected-resource"'},
|
||||||
|
)
|
||||||
|
body = await request.json()
|
||||||
|
req_id = body.get("id")
|
||||||
|
if req_id is None:
|
||||||
|
return web.Response(status=202)
|
||||||
|
if body.get("method") == "initialize":
|
||||||
|
return web.json_response({"jsonrpc": "2.0", "id": req_id, "result": {"protocolVersion": "2025-03-26", "capabilities": {"tools": {}}, "serverInfo": {"name": "smart-oauth"}}})
|
||||||
|
if body.get("method") == "tools/list":
|
||||||
|
return web.json_response({"jsonrpc": "2.0", "id": req_id, "result": {"tools": [{"name": "ping", "description": "Ping", "inputSchema": {"type": "object", "properties": {}}}]}})
|
||||||
|
return web.json_response({"jsonrpc": "2.0", "id": req_id, "result": {"content": [{"type": "text", "text": "oauth-ok"}], "isError": False}})
|
||||||
|
|
||||||
|
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)
|
||||||
|
app.router.add_post("/oauth/register", handle_dcr)
|
||||||
|
app.router.add_post("/oauth/token", handle_token)
|
||||||
|
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]
|
||||||
|
base_url = f"http://127.0.0.1:{port}"
|
||||||
|
base_url_holder["url"] = base_url
|
||||||
|
|
||||||
|
try:
|
||||||
|
settings = Settings(ALLOWED_TELEGRAM_USER_IDS=[102], DATA_DIR=tmp_path, MCP_CONFIG_FILE=tmp_path / "none.json")
|
||||||
|
registry = ToolRegistry()
|
||||||
|
manager = MCPConnectorManager(settings=settings, registry=registry)
|
||||||
|
agent = MagicMock()
|
||||||
|
agent.chat = AsyncMock()
|
||||||
|
router = create_bot_router(settings, agent, SkillManager(tmp_path / "skills"), registry, mcp_manager=manager)
|
||||||
|
dp = Dispatcher()
|
||||||
|
dp.include_router(router)
|
||||||
|
bot = _make_mock_bot()
|
||||||
|
|
||||||
|
# Step 1: User taps Add (/mcp add) then pastes ONLY the URL
|
||||||
|
await dp.feed_update(bot, Update(update_id=1, message=_make_message(bot, 102, 102, "/mcp add", msg_id=1)))
|
||||||
|
assert "Быстрое подключение MCP" in bot.send_rich_message.await_args.kwargs["rich_message"].markdown
|
||||||
|
|
||||||
|
await dp.feed_update(bot, Update(update_id=2, message=_make_message(bot, 102, 102, f"{base_url}/mcp", msg_id=2)))
|
||||||
|
oauth_md = bot.send_rich_message.await_args.kwargs["rich_message"].markdown
|
||||||
|
assert "OAuth-вход" in oauth_md
|
||||||
|
assert "/oauth/authorize" in oauth_md
|
||||||
|
|
||||||
|
# Extract authorize URL from bot reply and simulate browser redirect
|
||||||
|
auth_line = [ln for ln in oauth_md.splitlines() if "/oauth/authorize" in ln][0].strip()
|
||||||
|
qs = parse_qs(urlparse(auth_line).query)
|
||||||
|
oauth_state["issued_codes"]["code-999"] = qs["code_challenge"][0]
|
||||||
|
redirect_url = f"{qs['redirect_uri'][0]}?code=code-999&state={qs['state'][0]}"
|
||||||
|
|
||||||
|
# Step 2: User simply pastes the redirect URL back in chat!
|
||||||
|
await dp.feed_update(bot, Update(update_id=3, message=_make_message(bot, 102, 102, redirect_url, msg_id=3)))
|
||||||
|
done_md = bot.send_rich_message.await_args.kwargs["rich_message"].markdown
|
||||||
|
assert "подключён" in done_md
|
||||||
|
|
||||||
|
conn = manager.list_connectors()[0]
|
||||||
|
assert conn.status == "connected"
|
||||||
|
assert await registry.execute(conn.tools[0].registered_name, {}) == "oauth-ok"
|
||||||
|
agent.chat.assert_not_awaited()
|
||||||
|
await manager.close()
|
||||||
|
finally:
|
||||||
|
await runner.cleanup()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_smart_connect_stdio_command_directly(tmp_path):
|
||||||
|
"""User sends `/mcp python script.py` directly without knowing about stdio transport."""
|
||||||
|
script = tmp_path / "echo_mcp.py"
|
||||||
|
script.write_text(
|
||||||
|
textwrap.dedent(
|
||||||
|
"""
|
||||||
|
import json, sys
|
||||||
|
for line in sys.stdin:
|
||||||
|
msg = json.loads(line)
|
||||||
|
if "id" not in msg or msg["id"] is None:
|
||||||
|
continue
|
||||||
|
m = msg.get("method")
|
||||||
|
if m == "initialize":
|
||||||
|
res = {"protocolVersion": "2025-03-26", "capabilities": {"tools": {}}, "serverInfo": {"name": "echo"}}
|
||||||
|
elif m == "tools/list":
|
||||||
|
res = {"tools": [{"name": "hi", "description": "Hi", "inputSchema": {"type": "object", "properties": {}}}]}
|
||||||
|
else:
|
||||||
|
res = {"content": [{"type": "text", "text": "stdio-magic"}], "isError": False}
|
||||||
|
sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": res}) + "\\n")
|
||||||
|
sys.stdout.flush()
|
||||||
|
"""
|
||||||
|
).strip()
|
||||||
|
+ "\n",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
|
||||||
|
settings = Settings(ALLOWED_TELEGRAM_USER_IDS=[103], DATA_DIR=tmp_path, MCP_CONFIG_FILE=tmp_path / "none.json")
|
||||||
|
registry = ToolRegistry()
|
||||||
|
manager = MCPConnectorManager(settings=settings, registry=registry)
|
||||||
|
agent = MagicMock()
|
||||||
|
agent.chat = AsyncMock()
|
||||||
|
router = create_bot_router(settings, agent, SkillManager(tmp_path / "skills"), registry, mcp_manager=manager)
|
||||||
|
dp = Dispatcher()
|
||||||
|
dp.include_router(router)
|
||||||
|
bot = _make_mock_bot()
|
||||||
|
|
||||||
|
await dp.feed_update(bot, Update(update_id=1, message=_make_message(bot, 103, 103, f"/mcp {sys.executable} {script}", msg_id=1)))
|
||||||
|
md = bot.send_rich_message.await_args.kwargs["rich_message"].markdown
|
||||||
|
assert "подключён" in md
|
||||||
|
assert registry.get("mcp_echo_mcp_hi") is not None
|
||||||
|
assert await registry.execute("mcp_echo_mcp_hi", {}) == "stdio-magic"
|
||||||
|
await manager.close()
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
# Explicit CLI, Manual Wizard, Callback Whitelist, and Ghost Mode tests
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
@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. Explicit `/mcp add demo <url> bearer <token>` still works
|
||||||
|
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))
|
||||||
|
|
||||||
|
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_manual_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 manual wizard via /mcp wizard
|
||||||
|
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 wizard", msg_id=2)))
|
||||||
|
assert "Шаг 1/5" in bot.send_rich_message.await_args.kwargs["rich_message"].markdown
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
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.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()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_agent_builtin_mcp_tools_and_cimd_oauth_flow(tmp_path):
|
||||||
|
"""LLM agent can connect & authenticate MCP servers via built-in mcp_connect/mcp_provide_auth tools (including CIMD OAuth like Zenmoney)."""
|
||||||
|
base_url_holder = {"url": ""}
|
||||||
|
valid_tokens: set[str] = set()
|
||||||
|
|
||||||
|
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": ["all"],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
async def handle_as(request: web.Request) -> web.Response:
|
||||||
|
u = base_url_holder["url"]
|
||||||
|
return web.json_response(
|
||||||
|
{
|
||||||
|
"issuer": u,
|
||||||
|
"authorization_endpoint": f"{u}/oauth2/authorize/",
|
||||||
|
"token_endpoint": f"{u}/oauth2/token/",
|
||||||
|
"client_id_metadata_document_supported": True,
|
||||||
|
"code_challenge_methods_supported": ["S256"],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
async def handle_mcp(request: web.Request) -> web.Response:
|
||||||
|
auth_hdr = request.headers.get("Authorization", "")
|
||||||
|
if auth_hdr not in {f"Bearer {t}" for t in valid_tokens}:
|
||||||
|
return web.Response(
|
||||||
|
status=401,
|
||||||
|
headers={
|
||||||
|
"WWW-Authenticate": f'Bearer resource_metadata="{base_url_holder["url"]}/.well-known/oauth-protected-resource/mcp", scope="all"'
|
||||||
|
},
|
||||||
|
)
|
||||||
|
body = await request.json()
|
||||||
|
req_id = body.get("id")
|
||||||
|
if req_id is None:
|
||||||
|
return web.Response(status=202)
|
||||||
|
if body.get("method") == "initialize":
|
||||||
|
return web.json_response(
|
||||||
|
{"jsonrpc": "2.0", "id": req_id, "result": {"protocolVersion": "2025-03-26", "capabilities": {"tools": {}}, "serverInfo": {"name": "zen-mock"}}}
|
||||||
|
)
|
||||||
|
if body.get("method") == "tools/list":
|
||||||
|
return web.json_response(
|
||||||
|
{"jsonrpc": "2.0", "id": req_id, "result": {"tools": [{"name": "get_balance", "description": "Get balance", "inputSchema": {"type": "object", "properties": {}}}]}}
|
||||||
|
)
|
||||||
|
return web.json_response(
|
||||||
|
{"jsonrpc": "2.0", "id": req_id, "result": {"content": [{"type": "text", "text": "1000 RUB"}], "isError": False}}
|
||||||
|
)
|
||||||
|
|
||||||
|
app = web.Application()
|
||||||
|
app.router.add_get("/.well-known/oauth-protected-resource/mcp", handle_prm)
|
||||||
|
app.router.add_get("/.well-known/oauth-authorization-server", handle_as)
|
||||||
|
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]
|
||||||
|
base_url = f"http://127.0.0.1:{port}"
|
||||||
|
base_url_holder["url"] = base_url
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Case 1: Without MCP_OAUTH_CLIENT_METADATA_URL -> agent gets clear CIMD/token instructions, then authenticates with token
|
||||||
|
registry = ToolRegistry()
|
||||||
|
settings = Settings(DATA_DIR=tmp_path / "case1", MCP_CONFIG_FILE=tmp_path / "none.json")
|
||||||
|
manager = MCPConnectorManager(settings=settings, registry=registry)
|
||||||
|
assert registry.get("mcp_connect") is not None
|
||||||
|
assert registry.get("mcp_provide_auth") is not None
|
||||||
|
|
||||||
|
res1 = await registry.execute("mcp_connect", {"source": f"zenmoney {base_url}/mcp"})
|
||||||
|
assert "Client ID Metadata Document" in res1
|
||||||
|
assert "mcp_provide_auth" in res1
|
||||||
|
|
||||||
|
valid_tokens.add("zen-personal-tok")
|
||||||
|
res2 = await registry.execute("mcp_provide_auth", {"connector_name": "zenmoney", "credential_or_url": "zen-personal-tok"})
|
||||||
|
assert "авторизован и подключён" in res2
|
||||||
|
assert await registry.execute("mcp_zenmoney_get_balance", {}) == "1000 RUB"
|
||||||
|
|
||||||
|
list_out = await registry.execute("mcp_list_connectors", {})
|
||||||
|
assert "zenmoney" in list_out and "connected" in list_out
|
||||||
|
|
||||||
|
await registry.execute("mcp_remove_connector", {"connector_name": "zenmoney"})
|
||||||
|
assert registry.get("mcp_zenmoney_get_balance") is None
|
||||||
|
await manager.close()
|
||||||
|
|
||||||
|
# Case 2: With MCP_OAUTH_CLIENT_METADATA_URL -> auto-starts OAuth 2.1 PKCE using CIMD URL as client_id!
|
||||||
|
registry2 = ToolRegistry()
|
||||||
|
settings2 = Settings(
|
||||||
|
DATA_DIR=tmp_path / "case2",
|
||||||
|
MCP_CONFIG_FILE=tmp_path / "none.json",
|
||||||
|
MCP_OAUTH_CLIENT_METADATA_URL="https://example.org/homeagent-client.json",
|
||||||
|
)
|
||||||
|
manager2 = MCPConnectorManager(settings=settings2, registry=registry2)
|
||||||
|
res_cimd = await registry2.execute("mcp_connect", {"source": f"zenmoney {base_url}/mcp"})
|
||||||
|
assert "oauth2/authorize/" in res_cimd
|
||||||
|
assert "client_id=https%3A%2F%2Fexample.org%2Fhomeagent-client.json" in res_cimd
|
||||||
|
assert "scope=all" in res_cimd
|
||||||
|
|
||||||
|
# Case 3: Persisting default_client_metadata_url via set_default_client_metadata_url survives restart
|
||||||
|
manager2.set_default_client_metadata_url("https://example.org/custom-client.json")
|
||||||
|
settings3 = Settings(DATA_DIR=tmp_path / "case2", MCP_CONFIG_FILE=tmp_path / "none.json")
|
||||||
|
manager3 = MCPConnectorManager(settings=settings3, registry=ToolRegistry())
|
||||||
|
assert manager3.auth_manager.default_client_metadata_url == "https://example.org/custom-client.json"
|
||||||
|
await manager2.close()
|
||||||
|
await manager3.close()
|
||||||
|
finally:
|
||||||
|
await runner.cleanup()
|
||||||
|
|
||||||
@@ -0,0 +1,818 @@
|
|||||||
|
"""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()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_validate_cimd_url_catches_text_plain_and_mismatched_client_id(tmp_path):
|
||||||
|
async def handle_bad(request: web.Request) -> web.Response:
|
||||||
|
return web.Response(
|
||||||
|
text=json.dumps({"client_id": "https://other.example/x.json", "redirect_uris": []}),
|
||||||
|
content_type="text/plain",
|
||||||
|
)
|
||||||
|
|
||||||
|
async def handle_good(request: web.Request) -> web.Response:
|
||||||
|
url = str(request.url)
|
||||||
|
return web.json_response(
|
||||||
|
{
|
||||||
|
"client_id": url,
|
||||||
|
"client_name": "HomeAgent",
|
||||||
|
"redirect_uris": ["http://127.0.0.1:18765/mcp/oauth/callback"],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
app = web.Application()
|
||||||
|
app.router.add_get("/bad.json", handle_bad)
|
||||||
|
app.router.add_get("/good.json", handle_good)
|
||||||
|
runner, base_url = await _start_aiohttp_app(app)
|
||||||
|
try:
|
||||||
|
store = OAuthTokenStore(tmp_path / "tok.json")
|
||||||
|
auth_mgr = MCPAuthManager(store)
|
||||||
|
|
||||||
|
bad_warnings = await auth_mgr.validate_cimd_url(f"{base_url}/bad.json")
|
||||||
|
assert any("application/json" in w for w in bad_warnings)
|
||||||
|
assert any("client_id" in w for w in bad_warnings)
|
||||||
|
assert any("redirect_uris" in w for w in bad_warnings)
|
||||||
|
|
||||||
|
good_warnings = await auth_mgr.validate_cimd_url(f"{base_url}/good.json")
|
||||||
|
assert good_warnings == []
|
||||||
|
finally:
|
||||||
|
await runner.cleanup()
|
||||||
Reference in new issue
Block a user