Add user-bound external MCP server and OAuth access
This commit is contained in:
@@ -9,7 +9,7 @@ User=mcp-user
|
|||||||
WorkingDirectory=/home/mcp-user/smeta-web-release
|
WorkingDirectory=/home/mcp-user/smeta-web-release
|
||||||
EnvironmentFile=/home/mcp-user/smeta-web-release/.env
|
EnvironmentFile=/home/mcp-user/smeta-web-release/.env
|
||||||
Environment=PATH=/home/mcp-user/.npm-global/bin:/home/mcp-user/.local/bin:/usr/local/bin:/usr/bin:/bin
|
Environment=PATH=/home/mcp-user/.npm-global/bin:/home/mcp-user/.local/bin:/usr/local/bin:/usr/bin:/bin
|
||||||
Environment=PYTHONPATH=/home/mcp-user/.local/lib/python3.10/site-packages
|
Environment=PYTHONPATH=/home/mcp-user/smeta-web-release/.deps:/home/mcp-user/.local/lib/python3.10/site-packages
|
||||||
ExecStartPre=/usr/bin/python3 /home/mcp-user/smeta-web-release/scripts/shadow/preflight.py /home/mcp-user/smeta-web-release/.env
|
ExecStartPre=/usr/bin/python3 /home/mcp-user/smeta-web-release/scripts/shadow/preflight.py /home/mcp-user/smeta-web-release/.env
|
||||||
ExecStart=/usr/bin/python3 -m uvicorn main:app --host 127.0.0.1 --port 8106
|
ExecStart=/usr/bin/python3 -m uvicorn main:app --host 127.0.0.1 --port 8106
|
||||||
Restart=on-failure
|
Restart=on-failure
|
||||||
|
|||||||
@@ -31,6 +31,18 @@
|
|||||||
боевой HEAD, health, journey-канарейку и денежный сторож; до слова
|
боевой HEAD, health, journey-канарейку и денежный сторож; до слова
|
||||||
владельца приёмка продового шага — только негативная проба отказа.
|
владельца приёмка продового шага — только негативная проба отказа.
|
||||||
|
|
||||||
|
---
|
||||||
|
## 2026-11-27 — внешний MCP для сторонних ИИ
|
||||||
|
1. **Действие:** удалённый MCP с OAuth, файлами, расчётами и доступом к данным пользователя.
|
||||||
|
2. **Класс риска:** внешний канал, общий сервер/БД, персональные файлы, денежный расход.
|
||||||
|
3. **Прогон №1/№100/№1000:** один вызов должен проверять право и бюджет; 100 вызовов не смешивают вкладки; 1000 не обходят лимиты и не растят бесконечно очередь/логи.
|
||||||
|
4. **Побочку видят:** пользователь (файлы, диалог, баланс), оператор (журнал), все пользователи (нагрузка).
|
||||||
|
5. **Чекер:** читает результат и счётчики тестового аккаунта; не пишет в боевые файлы и не отправляет внешние сообщения.
|
||||||
|
6. **Обратимость:** отдельный route и выключатель MCP; уже выданные стороннему ИИ данные не отзываются, поэтому нужен consent до первого чтения.
|
||||||
|
7. **Отвергнуто:** публиковать существующий ARM `/api/mcp`: device pass и process-global env не дают безопасного многоарендного доступа.
|
||||||
|
8. **Вживую:** реальный удалённый клиент на release-dev, два тестовых пользователя, нормативный и файловый инструмент, отказ при чужом ID.
|
||||||
|
9. **Независимый сигнал:** полный серверный gate и live smoke на точном SHA; прод ждёт явной команды владельца.
|
||||||
|
|
||||||
---
|
---
|
||||||
## 2026-11-26 — единая история для выкладки
|
## 2026-11-26 — единая история для выкладки
|
||||||
1. **Действие:** закрепить `origin/main` как единственный источник кода боевого
|
1. **Действие:** закрепить `origin/main` как единственный источник кода боевого
|
||||||
|
|||||||
@@ -1,26 +1,26 @@
|
|||||||
# Подключение внешнего ИИ к будущему MCP Инфосметы
|
# Подключение внешнего ИИ к MCP Инфосметы
|
||||||
|
|
||||||
Статус на 2026-11-27: **контракт подготовлен, удалённый сервер ещё не развёрнут**. Этот документ служит инструкцией для разработки клиента и проверкой будущего релиза. Адрес прода нельзя использовать до отдельной выкладки.
|
Статус на 2026-11-27: реализация готовится к проверке на release dev. Адрес прода будет доступен после отдельной команды владельца на выкладку.
|
||||||
|
|
||||||
## Данные для подключения
|
## Данные для подключения
|
||||||
|
|
||||||
- Транспорт: MCP Streamable HTTP; адрес после выкладки: `https://infosmeta.ru/mcp`.
|
- Транспорт: MCP Streamable HTTP версии `2025-11-25` (SDK 1.30.0); адрес после выкладки: `https://infosmeta.ru/mcp`. Поддерживаются также версии `2024-11-05`, `2025-03-26`, `2025-06-18` в рамках SDK.
|
||||||
- Авторизация: OAuth 2.1. Клиент получает токен через discovery MCP resource server и authorization server с согласием пользователя; в каждом POST передаёт `Authorization: Bearer <access token>`. Сайт JWT, ARM-пропуск и ключ печного REST API не принимаются.
|
- Авторизация: OAuth 2.1. Клиент получает токен через discovery MCP resource server и authorization server с согласием пользователя; в каждом POST передаёт `Authorization: Bearer <access token>`. Сайт JWT, ARM-пропуск и ключ печного REST API не принимаются.
|
||||||
- Права определяют, какие инструменты видны в `tools/list`; пользователь может отозвать подключение. Для записи и платных действий запрашиваются дополнительные scopes и подтверждение/потолок расходов.
|
- Права определяют, какие инструменты видны в `tools/list`; пользователь отзывает подключение в меню аккаунта «Подключённые ИИ». Для записи и платных действий запрашиваются дополнительные scopes. У проверки замечаний нужен явный `budget_rub`, у удаления файлов — отдельное подтверждение в браузере.
|
||||||
- Не хранить токены в промпте, URL, логах, репозитории или конфиге с общим доступом.
|
- Не хранить токены в промпте, URL, логах, репозитории или конфиге с общим доступом.
|
||||||
|
|
||||||
## Проверка транспорта
|
## Проверка транспорта
|
||||||
|
|
||||||
После успешного OAuth-обмена клиент отправляет запрос как отдельный POST. Пример ниже показывает форму протокола; он начнёт работать только после реализации сервера и выдачи настоящего MCP-токена.
|
После успешного OAuth-обмена клиент отправляет запрос как отдельный POST. Стандартный MCP-клиент сначала получает `401` с `resource_metadata`, затем использует discovery, динамическую регистрацию, authorization code + PKCE (`S256`), открывает страницу согласия пользователю и обменивает код на токен. Обязательный resource: URL `/mcp` текущего окружения. Токен обновляется через `/token`; отзыв — через `/revoke` или страницу подключений.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
curl -sS 'https://infosmeta.ru/mcp' \
|
curl -sS 'https://infosmeta.ru/mcp' \
|
||||||
-H "Authorization: Bearer $MCP_ACCESS_TOKEN" \
|
-H "Authorization: Bearer $MCP_ACCESS_TOKEN" \
|
||||||
-H 'Content-Type: application/json' \
|
-H 'Content-Type: application/json' \
|
||||||
-H 'Accept: application/json, text/event-stream' \
|
-H 'Accept: application/json, text/event-stream' \
|
||||||
-H 'MCP-Protocol-Version: 2026-07-28' \
|
-H 'MCP-Protocol-Version: 2025-11-25' \
|
||||||
-H 'Mcp-Method: tools/list' \
|
-H 'Mcp-Method: tools/list' \
|
||||||
--data '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"infosmeta-smoke","version":"1.0.0"},"io.modelcontextprotocol/clientCapabilities":{}}}}'
|
--data '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2025-11-25","io.modelcontextprotocol/clientInfo":{"name":"infosmeta-smoke","version":"1.0.0"},"io.modelcontextprotocol/clientCapabilities":{}}}}'
|
||||||
```
|
```
|
||||||
|
|
||||||
Вызов инструмента потребует также `Mcp-Name`, совпадающий с `params.name`. Пример для нормативного поиска:
|
Вызов инструмента потребует также `Mcp-Name`, совпадающий с `params.name`. Пример для нормативного поиска:
|
||||||
@@ -34,7 +34,7 @@ curl -sS 'https://infosmeta.ru/mcp' \
|
|||||||
"name": "find_ksr",
|
"name": "find_ksr",
|
||||||
"arguments": {"query": "кирпич керамический", "limit": 5},
|
"arguments": {"query": "кирпич керамический", "limit": 5},
|
||||||
"_meta": {
|
"_meta": {
|
||||||
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
|
"io.modelcontextprotocol/protocolVersion": "2025-11-25",
|
||||||
"io.modelcontextprotocol/clientInfo": {"name": "infosmeta-smoke", "version": "1.0.0"},
|
"io.modelcontextprotocol/clientInfo": {"name": "infosmeta-smoke", "version": "1.0.0"},
|
||||||
"io.modelcontextprotocol/clientCapabilities": {}
|
"io.modelcontextprotocol/clientCapabilities": {}
|
||||||
}
|
}
|
||||||
@@ -42,6 +42,10 @@ curl -sS 'https://infosmeta.ru/mcp' \
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Клиент должен принимать JSON-ответ и поток SSE, читать машиночитаемый статус инструмента, а не угадывать успех по тексту. Отказ `401` инициирует OAuth discovery/обновление токена; `403` с `insufficient_scope` — запрос дополнительного согласия; `429` — повтор после указанной паузы. Повторять записывающий или платный вызов только с тем же ключом идемпотентности. При передаче файлов использовать серверные `file_id` и ресурсы, а не путь на машине ИИ.
|
Клиент должен принимать JSON-ответ и поток SSE и проверять `isError`. Отказ `401` инициирует OAuth discovery/обновление токена. Для дополнительных прав требуется повторное согласие. Платный или записывающий вызов не следует автоматически повторять после таймаута: общий ключ идемпотентности для всех инструментов пока не введён. Передавайте серверное имя файла и `tab_id`; путь на машине ИИ не является серверным путём.
|
||||||
|
|
||||||
|
`tools/list` содержит 30 исходных сметных инструментов и адаптеры сайта. Основные новые инструменты: `stove_estimate`, `chat_ask`, `chat_job_status`, `chat_job_cancel`, `get_limits`, `get_my_stats`, `get_data_version`, `list_dialogs`, `read_dialog`, `rename_dialog`, `set_dialog_date`, `upload_small_file`, `get_file`, `create_upload`, `review_estimate_cost`, `review_create`, `review_status`, `review_list`, `review_cancel`, `review_resume`, `review_report`, `prepare_clear_files`, `clear_files`. Точные JSON Schema выдаёт сам `tools/list`; запрос печи соответствует `stove_contract.StoveRequest`, вложенному в аргумент `stove`.
|
||||||
|
|
||||||
|
Для файла свыше 512 КБ вызовите `create_upload`: он вернёт `upload_url`, куда отправляется `multipart/form-data` с полем `file` и тем же OAuth Bearer. `get_file` вернёт содержимое небольшого файла в base64 либо `download_url` для большого; скачивание также требует Bearer. `chat_ask` возвращает `job_id`; результат и состояние читаются через `chat_job_status`. `prepare_clear_files` вернёт ссылку подтверждения; откройте её человеку в браузере, затем передайте `ticket` из URL в `clear_files`.
|
||||||
|
|
||||||
Полный перечень: [TOOL_CATALOG.md](TOOL_CATALOG.md). Правила реализации и приёмки: [EXTERNAL_MCP_PLAN.md](EXTERNAL_MCP_PLAN.md). Для расчёта печи поля и допустимые значения уже определены в [REST-инструкции](../stove-api/INTEGRATION.md) и `stove_contract.py`; MCP-адаптер использует тот же запрос и те же предупреждения об ориентировочности.
|
Полный перечень: [TOOL_CATALOG.md](TOOL_CATALOG.md). Правила реализации и приёмки: [EXTERNAL_MCP_PLAN.md](EXTERNAL_MCP_PLAN.md). Для расчёта печи поля и допустимые значения уже определены в [REST-инструкции](../stove-api/INTEGRATION.md) и `stove_contract.py`; MCP-адаптер использует тот же запрос и те же предупреждения об ориентировочности.
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
# Внешний MCP для Инфосметы
|
# Внешний MCP для Инфосметы
|
||||||
|
|
||||||
Дата: 2026-11-27. Статус: проект внедрения, сервер по этому документу ещё не реализован.
|
Дата: 2026-11-27. Статус: архитектурный план; реализация ведётся в `feat/external-mcp`, итог проверяется release dev.
|
||||||
|
|
||||||
## Решение и допущения
|
## Решение и допущения
|
||||||
|
|
||||||
- Цель владельца: сторонний ИИ подключается к Инфосмете по удалённому MCP и получает **все пользовательские возможности** сервиса. «Базовые» означает базовое подключение, а не ограничение домена печами.
|
- Цель владельца: сторонний ИИ подключается к Инфосмете по удалённому MCP и получает **все пользовательские возможности** сервиса. «Базовые» означает базовое подключение, а не ограничение домена печами.
|
||||||
- Действия выполняются от имени конкретного пользователя Инфосметы. Наличие MCP не повышает его права, баланс или лимиты. Операторские действия доступны только операторской роли и отдельным разрешениям.
|
- Действия выполняются от имени конкретного пользователя Инфосметы. Наличие MCP не повышает его права, баланс или лимиты. Операторские действия доступны только операторской роли и отдельным разрешениям.
|
||||||
- Первый публичный контракт — `https://infosmeta.ru/mcp` по Streamable HTTP, версия протокола `2026-07-28`, с совместимостью с реально используемыми клиентами, которую подтверждает отдельный набор проверок. На деве — собственный URL и тот же путь. Релизная версия SDK фиксируется после совместимого прогона; текущий `requirements.txt` не содержит `mcp`.
|
- Первый публичный контракт — `https://infosmeta.ru/mcp` по Streamable HTTP, версия протокола `2025-11-25` через Python SDK 1.30.0. Эта версия сохраняет совместимость с текущим Pydantic 2.11.4. На деве — собственный URL и тот же путь.
|
||||||
- Внешний ИИ получает инструменты, ресурсы и ссылки на результат. Он не получает доступ к серверной ФС, базе или внутреннему API напрямую.
|
- Внешний ИИ получает инструменты, ресурсы и ссылки на результат. Он не получает доступ к серверной ФС, базе или внутреннему API напрямую.
|
||||||
|
|
||||||
## Что уже есть
|
## Что уже есть
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# Задача: внешний MCP Инфосметы
|
||||||
|
|
||||||
|
Дата: 2026-11-27. Основание: команда владельца «$s внедряй» после согласования полного охвата пользовательских возможностей и OAuth-подключения.
|
||||||
|
|
||||||
|
## Критерии приёмки
|
||||||
|
|
||||||
|
1. Стандартный удалённый MCP-клиент проходит discovery → вход пользователя → согласие → выдачу токена, получает `tools/list`; без токена 401, чужая аудитория/отзыв/чужой scope отвергаются.
|
||||||
|
2. Каждый из 30 действующих доменных инструментов доступен через внешний MCP в рамках своего scope; два одновременных пользователя не смешивают рабочие папки и вкладки. Вызов file-инструмента с чужой вкладкой/файлом отвергается.
|
||||||
|
3. Через MCP доступны остальные рабочие возможности: печная оценка, чат, пользовательские файлы, проверка замечаний, история и личные лимиты. У них сохраняются прежние квоты, бюджет, владелец и ошибки.
|
||||||
|
4. Старые stdio MCP и ARM `/api/mcp` работают; dev `release` на точном SHA проходит полный gate и живой вызов внешнего клиента. Прод только после отдельной команды владельца.
|
||||||
|
|
||||||
|
## Шаги и зависимости
|
||||||
|
|
||||||
|
1. Зафиксировать транспорт и OAuth AS/RS на официальном MCP SDK, добавить отдельные хранилища клиентов, согласий и токенов. Тесты: регистрация, PKCE, недействительный токен, отзыв.
|
||||||
|
2. Завести `ToolContext` и рефакторинг 30 функций без process-global env. Зависит от 1. Тесты: параллельные пользователи и старый stdio.
|
||||||
|
3. Подключить доменные инструменты, схемы и права. Зависит от 2. Тесты: `tools/list`, вызов нормативов/файлов, deny без scope.
|
||||||
|
4. Подключить чат, печи, проверки, файлы и личные данные через существующие сервисы с идемпотентностью и лимитами. Зависит от 1–3. Тесты: по одному реальному сценарию на класс, отказ чужому пользователю, расчёт затрат.
|
||||||
|
5. Документация, полный gate, release dev smoke. Зависит от 1–4.
|
||||||
|
|
||||||
|
Риски регрессии: обновление Pydantic (MCP SDK 2.3.0 требует >=2.12, текущий pin 2.11.4), ASGI lifespan и старые startup hooks, глобальный `SMETA_USER`/`SMETA_TAB`, файловые пути, повтор платных операций. Приоритет: безопасность и корректное списание перед скоростью.
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
# Каталог внешнего MCP
|
# Каталог внешнего MCP
|
||||||
|
|
||||||
Снимок кода от 2026-11-27. Это **проект публичного каталога**, не перечень уже доступных удалённо инструментов. Точные `inputSchema` и поля результата фиксируются при реализации на основе действующих моделей и сервисов; для внутренних инструментов исходный реестр — `smeta_mcp.TOOLS` (30 записей). Прежде чем публиковать инструмент, проверить доступность его базы, эффект записи, пределы аргументов и владельца результата.
|
Снимок кода от 2026-11-27. Реальный перечень и схемы выдаёт `tools/list` согласно scopes токена; исходный реестр доменных инструментов — `smeta_mcp.TOOLS` (30 записей), адаптеры — `mcp_adapters.CATALOG`. Таблица ниже объясняет назначение и права. Внешний транспорт ограничивает тело 4 МБ, строки и массивы, проверяет владельца вкладки и возвращает ошибку для результата свыше 1 МБ.
|
||||||
|
|
||||||
| Внутренний инструмент | Назначение | Предлагаемый scope | Эффект и условие |
|
| Внутренний инструмент | Назначение | Scope | Эффект и условие |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| `regional_rate` | ТЕР/ТССЦ региона | `norms:read` | чтение; статус незагруженной базы |
|
| `regional_rate` | ТЕР/ТССЦ региона | `norms:read` | чтение; статус незагруженной базы |
|
||||||
| `find_in_tsn` | ТСН Москвы | `norms:read` | чтение; регион/редакция/дата |
|
| `find_in_tsn` | ТСН Москвы | `norms:read` | чтение; регион/редакция/дата |
|
||||||
@@ -39,7 +39,7 @@
|
|||||||
|
|
||||||
## Остальные возможности приложения
|
## Остальные возможности приложения
|
||||||
|
|
||||||
Имена ниже — предложения нового MCP API; реализация должна переиспользовать правила соответствующих веб-сервисов, а не напрямую копировать HTTP-обработчики.
|
Имена ниже показывают реализованные адаптеры обычных пользовательских операций. Источником точного контракта остаётся `tools/list`.
|
||||||
|
|
||||||
| Группа | Инструменты/ресурсы | Scope | Текущая основа |
|
| Группа | Инструменты/ресурсы | Scope | Текущая основа |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
|
|||||||
+203
@@ -0,0 +1,203 @@
|
|||||||
|
"""OAuth protected Streamable HTTP bridge for the existing Infosmeta tools."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from jsonschema import Draft202012Validator, ValidationError as SchemaError
|
||||||
|
|
||||||
|
from mcp.server.auth.middleware.auth_context import get_access_token
|
||||||
|
from mcp.server.auth.settings import AuthSettings, ClientRegistrationOptions, RevocationOptions
|
||||||
|
from mcp.server.fastmcp import FastMCP
|
||||||
|
from mcp.server.transport_security import TransportSecuritySettings
|
||||||
|
from mcp.types import CallToolResult, TextContent, Tool
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
|
import db
|
||||||
|
import mcp_adapters
|
||||||
|
from mcp_context import ToolContext, bind_tool_context
|
||||||
|
from mcp_identity import InfosmetaOAuthProvider, SCOPES
|
||||||
|
from path_safety import safe_work_dir
|
||||||
|
import smeta_mcp
|
||||||
|
|
||||||
|
log = logging.getLogger("smeta_web")
|
||||||
|
|
||||||
|
|
||||||
|
def _error_result(code: str, detail: str) -> CallToolResult:
|
||||||
|
return CallToolResult(content=[TextContent(type="text", text=json.dumps(
|
||||||
|
{"error": code, "detail": detail}, ensure_ascii=False))], isError=True)
|
||||||
|
|
||||||
|
|
||||||
|
_NORMS = {
|
||||||
|
"regional_rate", "find_in_tsn", "find_in_real_estimates", "find_ka_price",
|
||||||
|
"find_in_vor", "find_expertise_remarks", "find_recalc_index",
|
||||||
|
"find_direct_costs_index", "find_resource_price", "find_salary",
|
||||||
|
"find_ksr", "find_gesn_composition", "find_base_price",
|
||||||
|
}
|
||||||
|
_FILES_READ = {
|
||||||
|
"read_xlsx_sheet", "list_files", "extract_complaints_pairs", "parse_gge_file",
|
||||||
|
"parse_gsfx_file", "parse_arp_file",
|
||||||
|
}
|
||||||
|
_FILES_WRITE = {"apply_pukts_to_registry", "update_xlsx_cells"}
|
||||||
|
_ESTIMATE_WRITE = {"build_ka_form", "calc_estimate", "show_estimate"}
|
||||||
|
|
||||||
|
TOOL_SCOPES: dict[str, frozenset[str]] = {
|
||||||
|
**{name: frozenset({"norms:read"}) for name in _NORMS},
|
||||||
|
**{name: frozenset({"files:read"}) for name in _FILES_READ},
|
||||||
|
**{name: frozenset({"files:write"}) for name in _FILES_WRITE},
|
||||||
|
**{name: frozenset({"estimates:write"}) for name in _ESTIMATE_WRITE},
|
||||||
|
"calc_rim_rate": frozenset({"estimates:read"}),
|
||||||
|
"verify_estimate_file": frozenset({"files:read", "estimates:read"}),
|
||||||
|
"ocr_scans": frozenset({"files:read", "estimates:read"}),
|
||||||
|
"parse_gge_archive": frozenset({"files:read", "files:write"}),
|
||||||
|
"precheck_estimate": frozenset({"files:read", "estimates:write"}),
|
||||||
|
"export_estimate_gge": frozenset({"files:write", "estimates:write"}),
|
||||||
|
}
|
||||||
|
if set(TOOL_SCOPES) != set(smeta_mcp.TOOLS):
|
||||||
|
raise RuntimeError("External MCP scope map does not cover every domain tool")
|
||||||
|
|
||||||
|
|
||||||
|
def _bounded_schema(schema: dict) -> dict:
|
||||||
|
result = dict(schema)
|
||||||
|
kind = result.get("type")
|
||||||
|
if kind == "string":
|
||||||
|
result.setdefault("maxLength", 2000)
|
||||||
|
elif kind == "array":
|
||||||
|
result.setdefault("maxItems", 1000)
|
||||||
|
if isinstance(result.get("items"), dict):
|
||||||
|
result["items"] = _bounded_schema(result["items"])
|
||||||
|
elif kind == "object":
|
||||||
|
result["properties"] = {key: _bounded_schema(value)
|
||||||
|
for key, value in result.get("properties", {}).items()}
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _domain_schema(meta: dict) -> dict:
|
||||||
|
schema = _bounded_schema(meta["inputSchema"])
|
||||||
|
schema["properties"] = {**schema.get("properties", {}),
|
||||||
|
"tab_id": {"type": "string", "maxLength": 128}}
|
||||||
|
schema["additionalProperties"] = False
|
||||||
|
return schema
|
||||||
|
|
||||||
|
|
||||||
|
async def resolve_context(token, tab_id: str | None = None) -> ToolContext:
|
||||||
|
if not token.subject:
|
||||||
|
raise PermissionError("MCP token has no user")
|
||||||
|
if tab_id is None:
|
||||||
|
suffix = hashlib.sha256(token.client_id.encode()).hexdigest()[:16]
|
||||||
|
tab_id = f"mcp-{suffix}-{hashlib.sha256(token.subject.encode()).hexdigest()[:12]}"
|
||||||
|
if not isinstance(tab_id, str) or not tab_id or len(tab_id) > 128:
|
||||||
|
raise ValueError("Invalid tab_id")
|
||||||
|
owner = await asyncio.to_thread(db.tab_owner, tab_id)
|
||||||
|
if owner is not None and owner != token.subject:
|
||||||
|
raise PermissionError("This tab belongs to another user")
|
||||||
|
work_dir = safe_work_dir(token.subject, tab_id)
|
||||||
|
await asyncio.to_thread(db.ensure_session, token.subject, tab_id)
|
||||||
|
return ToolContext(token.subject, tab_id, work_dir, token.client_id,
|
||||||
|
frozenset(token.scopes))
|
||||||
|
|
||||||
|
|
||||||
|
class InfosmetaMCP(FastMCP):
|
||||||
|
def __init__(self, provider: InfosmetaOAuthProvider, *, allowed_hosts: list[str]):
|
||||||
|
issuer = provider.issuer
|
||||||
|
resource = provider.resource
|
||||||
|
super().__init__(
|
||||||
|
name="Infosmeta", instructions="Сметные нормы, файлы и расчёты Инфосметы.",
|
||||||
|
auth_server_provider=provider,
|
||||||
|
auth=AuthSettings(
|
||||||
|
issuer_url=issuer,
|
||||||
|
resource_server_url=resource,
|
||||||
|
validate_token_resource=True,
|
||||||
|
client_registration_options=ClientRegistrationOptions(
|
||||||
|
enabled=True, valid_scopes=sorted(SCOPES), default_scopes=["norms:read"]),
|
||||||
|
revocation_options=RevocationOptions(enabled=True),
|
||||||
|
required_scopes=[],
|
||||||
|
),
|
||||||
|
streamable_http_path="/mcp",
|
||||||
|
stateless_http=True,
|
||||||
|
json_response=True,
|
||||||
|
transport_security=TransportSecuritySettings(
|
||||||
|
enable_dns_rebinding_protection=True,
|
||||||
|
allowed_hosts=allowed_hosts,
|
||||||
|
allowed_origins=[issuer],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
async def list_tools(self) -> list[Tool]:
|
||||||
|
token = get_access_token()
|
||||||
|
if token is None or not token.subject:
|
||||||
|
return []
|
||||||
|
granted = set(token.scopes)
|
||||||
|
domain = [Tool(name=name, description=meta["description"],
|
||||||
|
inputSchema=_domain_schema(meta))
|
||||||
|
for name, meta in smeta_mcp.TOOLS.items()
|
||||||
|
if TOOL_SCOPES[name] <= granted]
|
||||||
|
adapters = [Tool(name=name, description=meta["description"], inputSchema=meta["schema"])
|
||||||
|
for name, meta in mcp_adapters.CATALOG.items() if meta["scope"] <= granted]
|
||||||
|
return domain + adapters
|
||||||
|
|
||||||
|
async def call_tool(self, name: str, arguments: dict[str, Any]):
|
||||||
|
result = None
|
||||||
|
try:
|
||||||
|
result = await self._call_tool(name, arguments)
|
||||||
|
except PermissionError:
|
||||||
|
result = _error_result("permission_denied", "Недостаточно прав или объект недоступен")
|
||||||
|
except HTTPException as exc:
|
||||||
|
result = _error_result("request_failed", str(exc.detail)[:300])
|
||||||
|
except ValueError as exc:
|
||||||
|
result = _error_result("invalid_request", str(exc)[:300])
|
||||||
|
except Exception:
|
||||||
|
log.exception("External MCP tool failed: %s", name)
|
||||||
|
result = _error_result("internal_error", "Не удалось выполнить действие")
|
||||||
|
token = get_access_token()
|
||||||
|
if token and token.subject:
|
||||||
|
try:
|
||||||
|
await asyncio.to_thread(db.log_action, token.subject, "mcp_tool", "POST", "/mcp",
|
||||||
|
f"client={token.client_id};tool={name}", None,
|
||||||
|
400 if result.isError else 200)
|
||||||
|
except Exception:
|
||||||
|
log.exception("External MCP audit write failed")
|
||||||
|
return result
|
||||||
|
|
||||||
|
async def _call_tool(self, name: str, arguments: dict[str, Any]):
|
||||||
|
token = get_access_token()
|
||||||
|
if token is None or not token.subject:
|
||||||
|
raise ValueError("Authentication required")
|
||||||
|
if name not in smeta_mcp.TOOLS and name not in mcp_adapters.CATALOG:
|
||||||
|
raise ValueError("Unknown tool")
|
||||||
|
required = (TOOL_SCOPES[name] if name in smeta_mcp.TOOLS
|
||||||
|
else mcp_adapters.CATALOG[name]["scope"])
|
||||||
|
if not required <= set(token.scopes):
|
||||||
|
raise PermissionError("Insufficient scope")
|
||||||
|
if not isinstance(arguments, dict):
|
||||||
|
raise ValueError("Tool arguments must be an object")
|
||||||
|
schema = (_domain_schema(smeta_mcp.TOOLS[name]) if name in smeta_mcp.TOOLS
|
||||||
|
else mcp_adapters.CATALOG[name]["schema"])
|
||||||
|
try:
|
||||||
|
Draft202012Validator(schema).validate(arguments)
|
||||||
|
except SchemaError as exc:
|
||||||
|
raise ValueError("Invalid tool arguments: " + exc.message[:200]) from None
|
||||||
|
args = dict(arguments)
|
||||||
|
context = await resolve_context(token, args.pop("tab_id", None))
|
||||||
|
|
||||||
|
if name in mcp_adapters.CATALOG:
|
||||||
|
with bind_tool_context(context):
|
||||||
|
result = await mcp_adapters.run(name, args, context)
|
||||||
|
else:
|
||||||
|
def run():
|
||||||
|
with bind_tool_context(context):
|
||||||
|
return smeta_mcp.TOOLS[name]["fn"](**args)
|
||||||
|
|
||||||
|
result = await asyncio.to_thread(run)
|
||||||
|
payload = json.dumps(result, ensure_ascii=False, default=str)
|
||||||
|
if len(payload) > 1_000_000:
|
||||||
|
raise ValueError("Tool result is too large; narrow the request")
|
||||||
|
content = [TextContent(type="text", text=payload)]
|
||||||
|
return CallToolResult(content=content, isError=bool(isinstance(result, dict) and "error" in result))
|
||||||
|
|
||||||
|
|
||||||
|
def create_mcp_app(provider: InfosmetaOAuthProvider, *, allowed_hosts: list[str]):
|
||||||
|
return InfosmetaMCP(provider, allowed_hosts=allowed_hosts).streamable_http_app()
|
||||||
@@ -998,6 +998,11 @@ def _целое(request: Request, имя: str, по_умолчанию: int) ->
|
|||||||
|
|
||||||
|
|
||||||
def _get_user(request: Request) -> str:
|
def _get_user(request: Request) -> str:
|
||||||
|
if request.scope.get("mcp_internal") is True:
|
||||||
|
from mcp_context import current_tool_context
|
||||||
|
context = current_tool_context()
|
||||||
|
if context is not None:
|
||||||
|
return context.username
|
||||||
auth = request.headers.get("authorization", "")
|
auth = request.headers.get("authorization", "")
|
||||||
token = auth.removeprefix("Bearer ").strip()
|
token = auth.removeprefix("Bearer ").strip()
|
||||||
if not token:
|
if not token:
|
||||||
@@ -2080,7 +2085,7 @@ async def chat(request: Request):
|
|||||||
# есть сам прогон, обрыв связи убивает работу. Включено — прогон уходит в фоновую задачу,
|
# есть сам прогон, обрыв связи убивает работу. Включено — прогон уходит в фоновую задачу,
|
||||||
# а браузеру отдаётся зеркало её журнала: закрытая вкладка больше не выбрасывает минуты
|
# а браузеру отдаётся зеркало её журнала: закрытая вкладка больше не выбрасывает минуты
|
||||||
# работы, за которые человек уже заплатил.
|
# работы, за которые человек уже заплатил.
|
||||||
if db.get_app_setting("agent_jobs", "off") == "on":
|
if db.get_app_setting("agent_jobs", "off") == "on" or request.scope.get("mcp_internal") is True:
|
||||||
поток = _stream_as_job(message, user, tab_id)
|
поток = _stream_as_job(message, user, tab_id)
|
||||||
else:
|
else:
|
||||||
поток = _stream_and_save(message, user, tab_id)
|
поток = _stream_and_save(message, user, tab_id)
|
||||||
@@ -3216,6 +3221,11 @@ def _reviews_enabled() -> bool:
|
|||||||
def _review_owner(request: Request) -> str:
|
def _review_owner(request: Request) -> str:
|
||||||
"""Программная дверь: пропуск устройства. С входом на сайте — 403 (не 401): дверь
|
"""Программная дверь: пропуск устройства. С входом на сайте — 403 (не 401): дверь
|
||||||
не та, и человеку это надо сказать прямо."""
|
не та, и человеку это надо сказать прямо."""
|
||||||
|
if request.scope.get("mcp_internal") is True:
|
||||||
|
from mcp_context import current_tool_context
|
||||||
|
context = current_tool_context()
|
||||||
|
if context is not None and "reviews:run" in context.scopes:
|
||||||
|
return context.username
|
||||||
import device_auth
|
import device_auth
|
||||||
try:
|
try:
|
||||||
return device_auth.require_device(request)["username"]
|
return device_auth.require_device(request)["username"]
|
||||||
@@ -3348,9 +3358,12 @@ async def reviews_create(request: Request):
|
|||||||
f"попробуйте через {verdict.retry_seconds} с.",
|
f"попробуйте через {verdict.retry_seconds} с.",
|
||||||
"axis": verdict.axis, "retry_seconds": verdict.retry_seconds},
|
"axis": verdict.axis, "retry_seconds": verdict.retry_seconds},
|
||||||
code="quota_exceeded")
|
code="quota_exceeded")
|
||||||
import device_auth
|
if request.scope.get("mcp_internal") is True:
|
||||||
device = await asyncio.to_thread(device_auth.require_device, request)
|
tab_id = await asyncio.to_thread(_review_tab, user, request.headers.get("x-tab-id"))
|
||||||
tab_id = await asyncio.to_thread(_review_tab, user, device.get("tab_id"))
|
else:
|
||||||
|
import device_auth
|
||||||
|
device = await asyncio.to_thread(device_auth.require_device, request)
|
||||||
|
tab_id = await asyncio.to_thread(_review_tab, user, device.get("tab_id"))
|
||||||
est = await asyncio.to_thread(_review_estimate, user, len(items))
|
est = await asyncio.to_thread(_review_estimate, user, len(items))
|
||||||
got = await asyncio.to_thread(db.create_review, user, tab_id, body.get("title") or "",
|
got = await asyncio.to_thread(db.create_review, user, tab_id, body.get("title") or "",
|
||||||
items, est["est_rub"], budget,
|
items, est["est_rub"], budget,
|
||||||
@@ -5379,6 +5392,173 @@ for _dep_url in ("/batch", "/batch2", "/batch3", "/ssr", "/wizard",
|
|||||||
"/generate", "/reference", "/check"):
|
"/generate", "/reference", "/check"):
|
||||||
app.add_api_route(_dep_url, _deprecated_moved, methods=["GET"], include_in_schema=False)
|
app.add_api_route(_dep_url, _deprecated_moved, methods=["GET"], include_in_schema=False)
|
||||||
|
|
||||||
|
|
||||||
|
# External user-bound MCP. The mount is last, so the established web and ARM
|
||||||
|
# routes keep their precedence. Its ASGI session manager has its own lifespan.
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
from external_mcp import create_mcp_app, resolve_context
|
||||||
|
from mcp_identity import InfosmetaOAuthProvider
|
||||||
|
from mcp_context import bind_tool_context
|
||||||
|
|
||||||
|
_mcp_issuer = os.environ.get("PUBLIC_BASE_URL", "https://infosmeta.ru").rstrip("/")
|
||||||
|
_mcp_provider = InfosmetaOAuthProvider(_mcp_issuer, _mcp_issuer + "/mcp")
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/oauth/consent", response_class=HTMLResponse)
|
||||||
|
async def mcp_consent_page(request: Request):
|
||||||
|
if not await _mcp_provider.pending(request.query_params.get("ticket", "")):
|
||||||
|
raise HTTPException(404, "Запрос подключения истёк")
|
||||||
|
return HTMLResponse(Path("static/mcp-consent.html").read_text(encoding="utf-8"),
|
||||||
|
headers={"Cache-Control": "no-store"})
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/mcp/clients", response_class=HTMLResponse)
|
||||||
|
async def mcp_clients_page():
|
||||||
|
return HTMLResponse(Path("static/mcp-clients.html").read_text(encoding="utf-8"),
|
||||||
|
headers={"Cache-Control": "no-store"})
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/mcp/confirm-action", response_class=HTMLResponse)
|
||||||
|
async def mcp_action_page(request: Request):
|
||||||
|
if not await _mcp_provider.action_info(request.query_params.get("ticket", "")):
|
||||||
|
raise HTTPException(404, "Запрос подтверждения истёк")
|
||||||
|
return HTMLResponse(Path("static/mcp-confirm-action.html").read_text(encoding="utf-8"),
|
||||||
|
headers={"Cache-Control": "no-store"})
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/mcp/action")
|
||||||
|
async def mcp_action_info(request: Request):
|
||||||
|
info = await _mcp_provider.action_info(request.query_params.get("ticket", ""))
|
||||||
|
if not info:
|
||||||
|
raise HTTPException(404, "Запрос подтверждения истёк")
|
||||||
|
return {"tab_id": info["tab_id"], "kind": info["kind"]}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/mcp/action")
|
||||||
|
async def mcp_action_approve(request: Request):
|
||||||
|
user = _get_user(request)
|
||||||
|
body = await _тело(request)
|
||||||
|
if not isinstance(body.get("ticket"), str):
|
||||||
|
raise HTTPException(400, "Нужен ticket")
|
||||||
|
try:
|
||||||
|
await _mcp_provider.approve_action(body["ticket"], user)
|
||||||
|
except ValueError:
|
||||||
|
raise HTTPException(404, "Запрос подтверждения истёк")
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/mcp/consent")
|
||||||
|
async def mcp_consent_info(request: Request):
|
||||||
|
pending = await _mcp_provider.pending(request.query_params.get("ticket", ""))
|
||||||
|
if not pending:
|
||||||
|
raise HTTPException(404, "Запрос подключения истёк")
|
||||||
|
return pending
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/oauth/consent")
|
||||||
|
async def mcp_consent_decision(request: Request):
|
||||||
|
user = _get_user(request)
|
||||||
|
body = await _тело(request)
|
||||||
|
if not isinstance(body.get("ticket"), str) or type(body.get("approved")) is not bool:
|
||||||
|
raise HTTPException(400, "Неверное решение о подключении")
|
||||||
|
pending = await _mcp_provider.pending(body["ticket"])
|
||||||
|
try:
|
||||||
|
redirect = await _mcp_provider.confirm(body["ticket"], user, approved=body["approved"])
|
||||||
|
except ValueError:
|
||||||
|
raise HTTPException(400, "Запрос подключения истёк")
|
||||||
|
try:
|
||||||
|
await asyncio.to_thread(log_action, user, "mcp_consent", "POST", "/oauth/consent",
|
||||||
|
f"client={pending['client_id'] if pending else '?'};approved={body['approved']}",
|
||||||
|
_client_ip(request) or None, 200)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("MCP consent audit failed")
|
||||||
|
return JSONResponse({"redirect": redirect}, headers={"Cache-Control": "no-store"})
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/mcp/clients")
|
||||||
|
async def mcp_connected_clients(request: Request):
|
||||||
|
return await _mcp_provider.list_clients_for_user(_get_user(request))
|
||||||
|
|
||||||
|
|
||||||
|
@app.delete("/api/mcp/clients/{client_id}")
|
||||||
|
async def mcp_disconnect_client(client_id: str, request: Request):
|
||||||
|
user = _get_user(request)
|
||||||
|
await _mcp_provider.revoke_client_for_user(user, client_id)
|
||||||
|
try:
|
||||||
|
await asyncio.to_thread(log_action, user, "mcp_revoke", "DELETE", "/api/mcp/clients",
|
||||||
|
f"client={client_id}", _client_ip(request) or None, 200)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("MCP revoke audit failed")
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
async def _mcp_file_context(request: Request, needed_scope: str):
|
||||||
|
raw = request.headers.get("authorization", "").removeprefix("Bearer ").strip()
|
||||||
|
token = await _mcp_provider.load_access_token(raw) if raw else None
|
||||||
|
if token is None:
|
||||||
|
raise HTTPException(401, "MCP token required")
|
||||||
|
if needed_scope not in token.scopes:
|
||||||
|
raise HTTPException(403, "Insufficient MCP scope")
|
||||||
|
try:
|
||||||
|
return await resolve_context(token, request.query_params.get("tab_id"))
|
||||||
|
except (ValueError, PermissionError):
|
||||||
|
raise HTTPException(403, "This tab is unavailable")
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/mcp/files")
|
||||||
|
async def mcp_upload_file(request: Request):
|
||||||
|
context = await _mcp_file_context(request, "files:write")
|
||||||
|
try:
|
||||||
|
length = int(request.headers.get("content-length") or 0)
|
||||||
|
except ValueError:
|
||||||
|
raise HTTPException(400, "Invalid Content-Length")
|
||||||
|
if length > MAX_UPLOAD_SIZE + 1024 * 1024:
|
||||||
|
raise HTTPException(413, "File is too large")
|
||||||
|
form = await request.form(max_files=1, max_fields=1)
|
||||||
|
file = form.get("file")
|
||||||
|
from starlette.datastructures import UploadFile as _StarletteUploadFile
|
||||||
|
if not isinstance(file, _StarletteUploadFile):
|
||||||
|
raise HTTPException(400, "Expected multipart field 'file'")
|
||||||
|
from mcp_adapters import _request as mcp_internal_request
|
||||||
|
with bind_tool_context(context):
|
||||||
|
return await upload(mcp_internal_request(context, path="/api/upload", method="POST"), file)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/mcp/files/{filename}")
|
||||||
|
async def mcp_download_file(filename: str, request: Request):
|
||||||
|
context = await _mcp_file_context(request, "files:read")
|
||||||
|
from mcp_adapters import _request as mcp_internal_request
|
||||||
|
with bind_tool_context(context):
|
||||||
|
response = await download_file(filename, mcp_internal_request(context, path="/api/files/" + filename))
|
||||||
|
response.headers["Cache-Control"] = "no-store"
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/mcp/reviews/{review_id}/report")
|
||||||
|
async def mcp_review_report(review_id: int, request: Request):
|
||||||
|
context = await _mcp_file_context(request, "reviews:run")
|
||||||
|
from mcp_adapters import _request as mcp_internal_request
|
||||||
|
with bind_tool_context(context):
|
||||||
|
response = await reviews_report(review_id, mcp_internal_request(context, path=f"/api/reviews/{review_id}/report"))
|
||||||
|
response.headers["Cache-Control"] = "no-store"
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
_mcp_host = _mcp_issuer.split("://", 1)[1]
|
||||||
|
_mcp_http_app = create_mcp_app(_mcp_provider, allowed_hosts=[_mcp_host])
|
||||||
|
_web_lifespan = app.router.lifespan_context
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def _web_with_mcp_lifespan(app_instance):
|
||||||
|
async with _web_lifespan(app_instance):
|
||||||
|
async with _mcp_http_app.router.lifespan_context(_mcp_http_app):
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
app.router.lifespan_context = _web_with_mcp_lifespan
|
||||||
|
app.mount("/", _mcp_http_app)
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import uvicorn
|
import uvicorn
|
||||||
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "8000")))
|
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "8000")))
|
||||||
|
|||||||
+249
@@ -0,0 +1,249 @@
|
|||||||
|
"""User-facing web operations exposed with the same service checks over MCP."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import base64
|
||||||
|
import binascii
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
from urllib.parse import urlencode
|
||||||
|
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from starlette.datastructures import UploadFile
|
||||||
|
from starlette.requests import Request
|
||||||
|
from starlette.responses import Response
|
||||||
|
|
||||||
|
import db
|
||||||
|
from mcp_context import ToolContext
|
||||||
|
|
||||||
|
|
||||||
|
def _schema(properties: dict, required: tuple[str, ...] = ()) -> dict:
|
||||||
|
return {"type": "object", "properties": properties, "required": list(required),
|
||||||
|
"additionalProperties": False}
|
||||||
|
|
||||||
|
|
||||||
|
CATALOG: dict[str, dict] = {
|
||||||
|
"get_limits": {"scope": {"account:read"}, "description": "Личные остатки, баланс и суточные лимиты.", "schema": _schema({})},
|
||||||
|
"get_my_stats": {"scope": {"account:read"}, "description": "Личная статистика расходов.",
|
||||||
|
"schema": _schema({"tz": {"type": "integer", "minimum": -840, "maximum": 840}})},
|
||||||
|
"get_data_version": {"scope": {"account:read"}, "description": "Периоды и версии нормативных данных.", "schema": _schema({})},
|
||||||
|
"list_dialogs": {"scope": {"account:read"}, "description": "Свои диалоги.", "schema": _schema({})},
|
||||||
|
"read_dialog": {"scope": {"account:read"}, "description": "История сообщений текущего или своего диалога.",
|
||||||
|
"schema": _schema({"tab_id": {"type": "string", "maxLength": 128},
|
||||||
|
"limit": {"type": "integer", "minimum": 1, "maximum": 200}})},
|
||||||
|
"rename_dialog": {"scope": {"chat:run"}, "description": "Переименовать свой диалог.",
|
||||||
|
"schema": _schema({"tab_id": {"type": "string", "maxLength": 128},
|
||||||
|
"title": {"type": "string", "minLength": 1, "maxLength": 120}}, ("title",))},
|
||||||
|
"set_dialog_date": {"scope": {"chat:run"}, "description": "Закрепить дату расчёта сметы в своём диалоге; null возвращает текущую дату.",
|
||||||
|
"schema": _schema({"tab_id": {"type": "string", "maxLength": 128},
|
||||||
|
"date": {"type": ["string", "null"]}})},
|
||||||
|
"upload_small_file": {"scope": {"files:write"}, "description": "Загрузить небольшой файл в свою вкладку в base64; действуют лимиты сайта.",
|
||||||
|
"schema": _schema({"tab_id": {"type": "string", "maxLength": 128},
|
||||||
|
"filename": {"type": "string", "maxLength": 200},
|
||||||
|
"content_base64": {"type": "string", "maxLength": 700000}},
|
||||||
|
("filename", "content_base64"))},
|
||||||
|
"get_file": {"scope": {"files:read"}, "description": "Получить свой файл до 512 КБ в base64 с проверкой разрешения на выгрузку.",
|
||||||
|
"schema": _schema({"tab_id": {"type": "string", "maxLength": 128},
|
||||||
|
"filename": {"type": "string", "maxLength": 200}}, ("filename",))},
|
||||||
|
"create_upload": {"scope": {"files:write"}, "description": "Получить адрес загрузки большого файла по OAuth Bearer (multipart поле file).",
|
||||||
|
"schema": _schema({"tab_id": {"type": "string", "maxLength": 128}})},
|
||||||
|
"prepare_clear_files": {"scope": {"files:write"}, "description": "Подготовить браузерное подтверждение удаления файлов и истории своей вкладки.",
|
||||||
|
"schema": _schema({"tab_id": {"type": "string", "maxLength": 128}})},
|
||||||
|
"clear_files": {"scope": {"files:write"}, "description": "Очистить файлы и историю после подтверждения человеком в браузере.",
|
||||||
|
"schema": _schema({"tab_id": {"type": "string", "maxLength": 128},
|
||||||
|
"ticket": {"type": "string", "maxLength": 100}}, ("ticket",))},
|
||||||
|
"review_estimate_cost": {"scope": {"reviews:run"}, "description": "Оценка бюджета проверки замечаний.",
|
||||||
|
"schema": _schema({"items": {"type": "array", "maxItems": 1000}}, ("items",))},
|
||||||
|
"review_create": {"scope": {"reviews:run"}, "description": "Создать проверку замечаний с явным потолком расходов.",
|
||||||
|
"schema": _schema({"tab_id": {"type": "string", "maxLength": 128},
|
||||||
|
"items": {"type": "array", "minItems": 1, "maxItems": 1000},
|
||||||
|
"title": {"type": "string", "maxLength": 120},
|
||||||
|
"budget_rub": {"type": "number", "minimum": 0},
|
||||||
|
"confirmed": {"type": "boolean", "const": True}},
|
||||||
|
("items", "budget_rub", "confirmed"))},
|
||||||
|
"review_status": {"scope": {"reviews:run"}, "description": "Статус своей проверки.",
|
||||||
|
"schema": _schema({"review_id": {"type": "integer", "minimum": 1}}, ("review_id",))},
|
||||||
|
"review_list": {"scope": {"reviews:run"}, "description": "Список своих проверок.", "schema": _schema({})},
|
||||||
|
"review_report": {"scope": {"reviews:run"}, "description": "Ссылка на отчёт своей проверки замечаний.",
|
||||||
|
"schema": _schema({"review_id": {"type": "integer", "minimum": 1}}, ("review_id",))},
|
||||||
|
"review_cancel": {"scope": {"reviews:run"}, "description": "Остановить свою проверку.",
|
||||||
|
"schema": _schema({"review_id": {"type": "integer", "minimum": 1}}, ("review_id",))},
|
||||||
|
"review_resume": {"scope": {"reviews:run"}, "description": "Продолжить свою проверку с новым потолком расходов.",
|
||||||
|
"schema": _schema({"review_id": {"type": "integer", "minimum": 1},
|
||||||
|
"budget_rub": {"type": "number", "minimum": 0}}, ("review_id", "budget_rub"))},
|
||||||
|
"chat_ask": {"scope": {"chat:run"}, "description": "Задать вопрос Инфосмете с обычными квотами; возвращает номер фонового задания.",
|
||||||
|
"schema": _schema({"tab_id": {"type": "string", "maxLength": 128},
|
||||||
|
"message": {"type": "string", "minLength": 1, "maxLength": 10000}}, ("message",))},
|
||||||
|
"chat_job_status": {"scope": {"chat:run"}, "description": "Статус своего задания и последние события ответа.",
|
||||||
|
"schema": _schema({"job_id": {"type": "integer", "minimum": 1}}, ("job_id",))},
|
||||||
|
"chat_job_cancel": {"scope": {"chat:run"}, "description": "Остановить своё задание.",
|
||||||
|
"schema": _schema({"job_id": {"type": "integer", "minimum": 1}}, ("job_id",))},
|
||||||
|
"stove_estimate": {"scope": {"stove:estimate"}, "description": "Ориентировочная оценка кладки печи с аналогами и пропусками, по тем же лимитам и бюджету, что REST API.",
|
||||||
|
"schema": _schema({"stove": {"type": "object"}}, ("stove",))},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _request(context: ToolContext, *, path: str, method: str = "GET", body: dict | None = None,
|
||||||
|
query: dict | None = None, headers: dict[str, str] | None = None) -> Request:
|
||||||
|
raw = json.dumps(body or {}, ensure_ascii=False).encode()
|
||||||
|
sent = False
|
||||||
|
|
||||||
|
async def receive():
|
||||||
|
nonlocal sent
|
||||||
|
if not sent:
|
||||||
|
sent = True
|
||||||
|
return {"type": "http.request", "body": raw, "more_body": False}
|
||||||
|
return {"type": "http.request", "body": b"", "more_body": False}
|
||||||
|
|
||||||
|
request_headers = [(b"x-tab-id", context.tab_id.encode()),
|
||||||
|
(b"content-type", b"application/json")]
|
||||||
|
request_headers.extend((key.lower().encode(), value.encode()) for key, value in (headers or {}).items())
|
||||||
|
return Request({"type": "http", "method": method, "scheme": "https", "path": path,
|
||||||
|
"root_path": "", "query_string": urlencode(query or {}).encode(),
|
||||||
|
"headers": request_headers,
|
||||||
|
"client": ("127.0.0.1", 0), "server": ("127.0.0.1", 443),
|
||||||
|
"mcp_internal": True}, receive=receive)
|
||||||
|
|
||||||
|
|
||||||
|
async def run(name: str, args: dict, context: ToolContext):
|
||||||
|
import main
|
||||||
|
user, tab = context.username, context.tab_id
|
||||||
|
if name == "get_limits":
|
||||||
|
return await asyncio.to_thread(main._person_view, user)
|
||||||
|
if name == "get_my_stats":
|
||||||
|
return await main.my_stats_endpoint(_request(context, path="/api/my-stats"),
|
||||||
|
tz=str(args.get("tz", 0)))
|
||||||
|
if name == "get_data_version":
|
||||||
|
return await main.data_version()
|
||||||
|
if name == "list_dialogs":
|
||||||
|
return await asyncio.to_thread(db.list_sessions, user)
|
||||||
|
if name == "read_dialog":
|
||||||
|
return await asyncio.to_thread(db.get_history, user, tab, limit=args.get("limit", 100))
|
||||||
|
if name == "rename_dialog":
|
||||||
|
return await main.rename_session_ep(tab, _request(context, path=f"/api/sessions/{tab}/title",
|
||||||
|
method="POST", body={"title": args["title"]}))
|
||||||
|
if name == "set_dialog_date":
|
||||||
|
return await main.set_session_date_ep(tab, _request(context, path=f"/api/sessions/{tab}/date",
|
||||||
|
method="POST", body={"date": args.get("date")}))
|
||||||
|
if name == "upload_small_file":
|
||||||
|
try:
|
||||||
|
payload = base64.b64decode(args["content_base64"], validate=True)
|
||||||
|
except (ValueError, TypeError, binascii.Error) as exc:
|
||||||
|
raise ValueError("Invalid base64 content") from exc
|
||||||
|
if len(payload) > 512 * 1024:
|
||||||
|
raise ValueError("File is larger than 512 KB")
|
||||||
|
file = UploadFile(filename=args["filename"], file=io.BytesIO(payload))
|
||||||
|
return await main.upload(_request(context, path="/api/upload", method="POST"), file)
|
||||||
|
if name == "get_file":
|
||||||
|
response = await main.download_file(args["filename"], _request(context, path="/api/files/"+args["filename"]))
|
||||||
|
if not isinstance(response, Response) or response.status_code >= 400:
|
||||||
|
raise HTTPException(getattr(response, "status_code", 500), "File unavailable")
|
||||||
|
path = Path(response.path)
|
||||||
|
size = await asyncio.to_thread(lambda: path.stat().st_size)
|
||||||
|
if size > 512 * 1024:
|
||||||
|
from urllib.parse import quote
|
||||||
|
return {"filename": args["filename"], "size": size,
|
||||||
|
"download_url": main._mcp_issuer + "/mcp/files/" + quote(args["filename"])
|
||||||
|
+ "?" + urlencode({"tab_id": tab}), "auth": "OAuth Bearer"}
|
||||||
|
raw = await asyncio.to_thread(path.read_bytes)
|
||||||
|
return {"filename": args["filename"], "size": size,
|
||||||
|
"content_base64": base64.b64encode(raw).decode()}
|
||||||
|
if name == "create_upload":
|
||||||
|
return {"upload_url": main._mcp_issuer + "/mcp/files?" + urlencode({"tab_id": tab}),
|
||||||
|
"method": "POST", "content_type": "multipart/form-data",
|
||||||
|
"file_field": "file", "auth": "OAuth Bearer"}
|
||||||
|
if name == "prepare_clear_files":
|
||||||
|
url = await main._mcp_provider.prepare_action(user, context.client_id, tab, "clear_files")
|
||||||
|
return {"confirmation_url": url, "expires_in": 600,
|
||||||
|
"next_step": "После подтверждения в браузере вызовите clear_files с ticket из URL"}
|
||||||
|
if name == "clear_files":
|
||||||
|
await main._mcp_provider.consume_action(args["ticket"], user, context.client_id, tab, "clear_files")
|
||||||
|
return await main.clear_files(_request(context, path="/api/clear-files", method="POST"))
|
||||||
|
if name == "review_estimate_cost":
|
||||||
|
return await main.reviews_estimate(_request(context, path="/api/reviews/estimate",
|
||||||
|
method="POST", body={"items": args["items"]}))
|
||||||
|
if name == "review_create":
|
||||||
|
return await main.reviews_create(_request(context, path="/api/reviews", method="POST", body=args))
|
||||||
|
if name == "review_status":
|
||||||
|
return await main.reviews_get(args["review_id"], _request(context, path="/api/reviews/status"))
|
||||||
|
if name == "review_list":
|
||||||
|
return await main.reviews_list(_request(context, path="/api/reviews"))
|
||||||
|
if name == "review_report":
|
||||||
|
if await asyncio.to_thread(db.get_review, user, args["review_id"]) is None:
|
||||||
|
raise HTTPException(404, "Проверка не найдена")
|
||||||
|
return {"download_url": main._mcp_issuer + f"/mcp/reviews/{args['review_id']}/report",
|
||||||
|
"auth": "OAuth Bearer"}
|
||||||
|
if name == "review_cancel":
|
||||||
|
return await main.reviews_cancel(args["review_id"], _request(context, path="/api/reviews/cancel", method="POST"))
|
||||||
|
if name == "review_resume":
|
||||||
|
return await main.reviews_resume(args["review_id"], _request(context, path="/api/reviews/resume",
|
||||||
|
method="POST", body={"budget_rub": args["budget_rub"]}))
|
||||||
|
if name == "chat_ask":
|
||||||
|
response = await main.chat(_request(context, path="/api/chat", method="POST",
|
||||||
|
body={"message": args["message"], "tab_id": tab}))
|
||||||
|
stream = response.body_iterator
|
||||||
|
first = await stream.__anext__()
|
||||||
|
await stream.aclose()
|
||||||
|
if first.startswith("event: job\n"):
|
||||||
|
job = json.loads(first.split("data: ", 1)[1])["job"]
|
||||||
|
return {"job_id": job, "status": "running", "tab_id": tab}
|
||||||
|
return {"status": "refused", "event": first}
|
||||||
|
if name == "chat_job_status":
|
||||||
|
job = await asyncio.to_thread(db.get_job, args["job_id"])
|
||||||
|
if not job or job["username"] != user:
|
||||||
|
raise HTTPException(404, "Задание не найдено")
|
||||||
|
active = main.JOBS._jobs.get(str(args["job_id"]))
|
||||||
|
return {"job_id": args["job_id"], "status": job["status"],
|
||||||
|
"events": (active["events"][-50:] if active else []),
|
||||||
|
"tab_id": job["tab_id"]}
|
||||||
|
if name == "chat_job_cancel":
|
||||||
|
return await main.job_cancel(args["job_id"], _request(context, path="/api/jobs/cancel", method="POST"))
|
||||||
|
if name == "stove_estimate":
|
||||||
|
import stove_api
|
||||||
|
secret = await asyncio.to_thread(_stove_key_for_user, user)
|
||||||
|
response = await stove_api.estimate(_request(context, path="/api/v1/stove-estimate",
|
||||||
|
method="POST", body={"stove": args["stove"]}, headers={"x-api-key": secret}))
|
||||||
|
payload = json.loads(response.body)
|
||||||
|
if response.status_code >= 400:
|
||||||
|
return {"error": payload.get("code", "service_unavailable"),
|
||||||
|
"detail": payload.get("detail"), "retry_after": response.headers.get("Retry-After")}
|
||||||
|
return payload
|
||||||
|
raise ValueError("Unknown MCP adapter")
|
||||||
|
|
||||||
|
|
||||||
|
def _stove_key_for_user(username: str) -> str:
|
||||||
|
"""A private per-user REST key reuses stove limits, matching budget and history."""
|
||||||
|
from contextlib import closing
|
||||||
|
from cryptography.fernet import InvalidToken
|
||||||
|
import stove_keys
|
||||||
|
from mcp_identity import _cipher
|
||||||
|
|
||||||
|
with closing(db._conn()) as conn, conn:
|
||||||
|
conn.execute("CREATE TABLE IF NOT EXISTS mcp_stove_credentials "
|
||||||
|
"(username TEXT PRIMARY KEY, key_id INTEGER NOT NULL, secret_cipher BLOB NOT NULL)")
|
||||||
|
row = conn.execute("SELECT key_id, secret_cipher FROM mcp_stove_credentials WHERE username=?",
|
||||||
|
(username,)).fetchone()
|
||||||
|
if row:
|
||||||
|
key = stove_keys.get_key(row["key_id"])
|
||||||
|
if not key or key.get("disabled") or key.get("revoked_at"):
|
||||||
|
raise PermissionError("Stove estimation is disabled for this user")
|
||||||
|
try:
|
||||||
|
return _cipher().decrypt(row["secret_cipher"]).decode()
|
||||||
|
except InvalidToken as exc:
|
||||||
|
raise RuntimeError("Stove credential cannot be decrypted") from exc
|
||||||
|
made = stove_keys.create_key(name=f"MCP {username}", allowed_ip="127.0.0.1",
|
||||||
|
note="Private MCP identity key")
|
||||||
|
try:
|
||||||
|
with closing(db._conn()) as conn, conn:
|
||||||
|
conn.execute("INSERT INTO mcp_stove_credentials VALUES (?,?,?)",
|
||||||
|
(username, made["id"], _cipher().encrypt(made["secret"].encode())))
|
||||||
|
return made["secret"]
|
||||||
|
except Exception:
|
||||||
|
stove_keys.revoke_key(made["id"])
|
||||||
|
with closing(db._conn()) as conn:
|
||||||
|
row = conn.execute("SELECT secret_cipher FROM mcp_stove_credentials WHERE username=?",
|
||||||
|
(username,)).fetchone()
|
||||||
|
if row:
|
||||||
|
return _cipher().decrypt(row["secret_cipher"]).decode()
|
||||||
|
raise
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
"""Per-request identity for domain tools shared by stdio and remote MCP."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from contextvars import ContextVar
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Iterator
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ToolContext:
|
||||||
|
username: str
|
||||||
|
tab_id: str
|
||||||
|
work_dir: Path
|
||||||
|
client_id: str
|
||||||
|
scopes: frozenset[str]
|
||||||
|
|
||||||
|
|
||||||
|
_current: ContextVar[ToolContext | None] = ContextVar("smeta_mcp_tool_context", default=None)
|
||||||
|
|
||||||
|
|
||||||
|
def current_tool_context() -> ToolContext | None:
|
||||||
|
return _current.get()
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def bind_tool_context(context: ToolContext) -> Iterator[None]:
|
||||||
|
marker = _current.set(context)
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
_current.reset(marker)
|
||||||
+362
@@ -0,0 +1,362 @@
|
|||||||
|
"""OAuth state for the external MCP endpoint. Only hashes of grants/tokens reach SQLite."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import base64
|
||||||
|
from contextlib import closing
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
import time
|
||||||
|
from urllib.parse import urlencode, urlparse
|
||||||
|
|
||||||
|
from cryptography.fernet import Fernet
|
||||||
|
from mcp.server.auth.provider import (
|
||||||
|
AccessToken, AuthorizationCode, AuthorizationParams, AuthorizeError,
|
||||||
|
RefreshToken, RegistrationError, TokenError, construct_redirect_uri,
|
||||||
|
)
|
||||||
|
from mcp.shared.auth import OAuthClientInformationFull, OAuthToken
|
||||||
|
|
||||||
|
import db
|
||||||
|
|
||||||
|
SCOPES = frozenset({
|
||||||
|
"norms:read", "estimates:read", "estimates:write", "files:read", "files:write",
|
||||||
|
"chat:run", "reviews:run", "stove:estimate", "account:read",
|
||||||
|
})
|
||||||
|
ACCESS_TTL = 3600
|
||||||
|
REFRESH_TTL = 30 * 86400
|
||||||
|
GRANT_TTL = 300
|
||||||
|
|
||||||
|
|
||||||
|
def _digest(value: str) -> str:
|
||||||
|
return hashlib.sha256(value.encode()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def _cipher() -> Fernet:
|
||||||
|
secret = os.environ.get("SESSION_SECRET", "")
|
||||||
|
if not secret:
|
||||||
|
raise RuntimeError("SESSION_SECRET is required for MCP client credential storage")
|
||||||
|
key = base64.urlsafe_b64encode(hashlib.sha256(("mcp-client:" + secret).encode()).digest())
|
||||||
|
return Fernet(key)
|
||||||
|
|
||||||
|
|
||||||
|
def init_db() -> None:
|
||||||
|
with closing(db._conn()) as conn, conn:
|
||||||
|
conn.executescript("""
|
||||||
|
CREATE TABLE IF NOT EXISTS mcp_oauth_clients (
|
||||||
|
client_id TEXT PRIMARY KEY, metadata TEXT NOT NULL, secret_cipher BLOB,
|
||||||
|
created_at REAL NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS mcp_oauth_pending (
|
||||||
|
ticket_hash TEXT PRIMARY KEY, client_id TEXT NOT NULL, params TEXT NOT NULL,
|
||||||
|
expires_at REAL NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS mcp_oauth_codes (
|
||||||
|
code_hash TEXT PRIMARY KEY, client_id TEXT NOT NULL, grant TEXT NOT NULL,
|
||||||
|
expires_at REAL NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS mcp_oauth_tokens (
|
||||||
|
token_hash TEXT PRIMARY KEY, kind TEXT NOT NULL, family TEXT NOT NULL,
|
||||||
|
client_id TEXT NOT NULL, username TEXT NOT NULL, scopes TEXT NOT NULL,
|
||||||
|
resource TEXT NOT NULL, expires_at REAL NOT NULL, revoked_at REAL
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_mcp_oauth_tokens_user
|
||||||
|
ON mcp_oauth_tokens(username, client_id, revoked_at);
|
||||||
|
CREATE TABLE IF NOT EXISTS mcp_oauth_consents (
|
||||||
|
username TEXT NOT NULL, client_id TEXT NOT NULL, scopes TEXT NOT NULL,
|
||||||
|
approved_at REAL NOT NULL, revoked_at REAL,
|
||||||
|
PRIMARY KEY(username, client_id)
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS mcp_pending_actions (
|
||||||
|
ticket_hash TEXT PRIMARY KEY, username TEXT NOT NULL, client_id TEXT NOT NULL,
|
||||||
|
tab_id TEXT NOT NULL, kind TEXT NOT NULL, expires_at REAL NOT NULL,
|
||||||
|
approved_at REAL
|
||||||
|
);
|
||||||
|
""")
|
||||||
|
|
||||||
|
|
||||||
|
def _active_user(username: str) -> bool:
|
||||||
|
user = db.get_user_by_email(username)
|
||||||
|
return bool(user and user.get("verified") and not user.get("blocked")
|
||||||
|
and not user.get("deleted_at"))
|
||||||
|
|
||||||
|
|
||||||
|
class InfosmetaOAuthProvider:
|
||||||
|
"""Persistent OAuth provider used by the SDK's AS and bearer middleware."""
|
||||||
|
|
||||||
|
def __init__(self, issuer: str, resource: str):
|
||||||
|
self.issuer = issuer.rstrip("/")
|
||||||
|
self.resource = resource.rstrip("/")
|
||||||
|
if not self.resource.startswith(self.issuer + "/"):
|
||||||
|
raise ValueError("MCP resource must be within issuer origin")
|
||||||
|
init_db()
|
||||||
|
|
||||||
|
async def get_client(self, client_id: str) -> OAuthClientInformationFull | None:
|
||||||
|
def read():
|
||||||
|
with closing(db._conn()) as conn:
|
||||||
|
return conn.execute("SELECT metadata, secret_cipher FROM mcp_oauth_clients WHERE client_id=?",
|
||||||
|
(client_id,)).fetchone()
|
||||||
|
row = await asyncio.to_thread(read)
|
||||||
|
if row is None:
|
||||||
|
return None
|
||||||
|
data = json.loads(row["metadata"])
|
||||||
|
if row["secret_cipher"]:
|
||||||
|
data["client_secret"] = _cipher().decrypt(row["secret_cipher"]).decode()
|
||||||
|
return OAuthClientInformationFull.model_validate(data)
|
||||||
|
|
||||||
|
async def register_client(self, client_info: OAuthClientInformationFull) -> None:
|
||||||
|
if not client_info.redirect_uris or len(client_info.redirect_uris) > 8:
|
||||||
|
raise RegistrationError("invalid_redirect_uri", "One to eight redirect URIs are required")
|
||||||
|
for uri in client_info.redirect_uris:
|
||||||
|
parsed = urlparse(str(uri))
|
||||||
|
loopback = parsed.hostname in {"localhost", "127.0.0.1", "::1"}
|
||||||
|
if parsed.scheme != "https" and not (parsed.scheme == "http" and loopback):
|
||||||
|
raise RegistrationError("invalid_redirect_uri", "Use HTTPS or localhost loopback")
|
||||||
|
if parsed.fragment or parsed.username or parsed.password:
|
||||||
|
raise RegistrationError("invalid_redirect_uri", "Redirect URI must not contain credentials or fragment")
|
||||||
|
requested = set((client_info.scope or "").split())
|
||||||
|
if not requested.issubset(SCOPES):
|
||||||
|
raise RegistrationError("invalid_client_metadata", "Unknown scope")
|
||||||
|
metadata = client_info.model_dump(mode="json")
|
||||||
|
secret = metadata.pop("client_secret", None)
|
||||||
|
ciphertext = _cipher().encrypt(secret.encode()) if secret else None
|
||||||
|
def write():
|
||||||
|
with closing(db._conn()) as conn, conn:
|
||||||
|
conn.execute("INSERT INTO mcp_oauth_clients VALUES (?, ?, ?, ?)",
|
||||||
|
(client_info.client_id, json.dumps(metadata), ciphertext, time.time()))
|
||||||
|
await asyncio.to_thread(write)
|
||||||
|
|
||||||
|
async def authorize(self, client: OAuthClientInformationFull,
|
||||||
|
params: AuthorizationParams) -> str:
|
||||||
|
if params.resource != self.resource:
|
||||||
|
raise AuthorizeError("invalid_target", "Token is only issued for this MCP resource")
|
||||||
|
scopes = params.scopes or []
|
||||||
|
if not scopes or not set(scopes).issubset(SCOPES):
|
||||||
|
raise AuthorizeError("invalid_scope", "No supported scopes requested")
|
||||||
|
ticket = secrets.token_urlsafe(32)
|
||||||
|
def write():
|
||||||
|
with closing(db._conn()) as conn, conn:
|
||||||
|
conn.execute("INSERT INTO mcp_oauth_pending VALUES (?, ?, ?, ?)",
|
||||||
|
(_digest(ticket), client.client_id,
|
||||||
|
params.model_dump_json(), time.time() + GRANT_TTL))
|
||||||
|
await asyncio.to_thread(write)
|
||||||
|
return f"{self.issuer}/oauth/consent?{urlencode({'ticket': ticket})}"
|
||||||
|
|
||||||
|
async def pending(self, ticket: str) -> dict | None:
|
||||||
|
def read():
|
||||||
|
with closing(db._conn()) as conn:
|
||||||
|
return conn.execute("SELECT p.client_id, p.params, p.expires_at, c.metadata "
|
||||||
|
"FROM mcp_oauth_pending p JOIN mcp_oauth_clients c "
|
||||||
|
"ON c.client_id=p.client_id WHERE p.ticket_hash=?",
|
||||||
|
(_digest(ticket),)).fetchone()
|
||||||
|
row = await asyncio.to_thread(read)
|
||||||
|
if row is None or row["expires_at"] < time.time():
|
||||||
|
return None
|
||||||
|
params = AuthorizationParams.model_validate_json(row["params"])
|
||||||
|
meta = json.loads(row["metadata"])
|
||||||
|
return {"client_id": row["client_id"], "client_name": meta.get("client_name") or row["client_id"],
|
||||||
|
"scopes": params.scopes or [], "redirect_uri": str(params.redirect_uri)}
|
||||||
|
|
||||||
|
async def confirm(self, ticket: str, username: str, *, approved: bool) -> str:
|
||||||
|
if approved and not await asyncio.to_thread(_active_user, username):
|
||||||
|
raise ValueError("Account is unavailable")
|
||||||
|
def write():
|
||||||
|
with closing(db._conn()) as conn, conn:
|
||||||
|
conn.execute("BEGIN IMMEDIATE")
|
||||||
|
row = conn.execute("SELECT client_id, params, expires_at FROM mcp_oauth_pending "
|
||||||
|
"WHERE ticket_hash=?", (_digest(ticket),)).fetchone()
|
||||||
|
if row is None or row["expires_at"] < time.time():
|
||||||
|
raise ValueError("Consent request expired")
|
||||||
|
conn.execute("DELETE FROM mcp_oauth_pending WHERE ticket_hash=?", (_digest(ticket),))
|
||||||
|
params = AuthorizationParams.model_validate_json(row["params"])
|
||||||
|
if not approved:
|
||||||
|
return construct_redirect_uri(str(params.redirect_uri),
|
||||||
|
error="access_denied", state=params.state, iss=self.issuer)
|
||||||
|
code = secrets.token_urlsafe(32)
|
||||||
|
grant = AuthorizationCode(code=code, scopes=params.scopes or [],
|
||||||
|
expires_at=time.time() + GRANT_TTL, client_id=row["client_id"],
|
||||||
|
code_challenge=params.code_challenge, redirect_uri=params.redirect_uri,
|
||||||
|
redirect_uri_provided_explicitly=params.redirect_uri_provided_explicitly,
|
||||||
|
resource=self.resource, subject=username)
|
||||||
|
data = grant.model_dump(mode="json", exclude={"code"})
|
||||||
|
conn.execute("INSERT INTO mcp_oauth_codes VALUES (?, ?, ?, ?)",
|
||||||
|
(_digest(code), row["client_id"], json.dumps(data), grant.expires_at))
|
||||||
|
conn.execute("INSERT INTO mcp_oauth_consents VALUES (?, ?, ?, ?, NULL) "
|
||||||
|
"ON CONFLICT(username,client_id) DO UPDATE SET "
|
||||||
|
"scopes=excluded.scopes, approved_at=excluded.approved_at, revoked_at=NULL",
|
||||||
|
(username, row["client_id"], json.dumps(grant.scopes), time.time()))
|
||||||
|
return construct_redirect_uri(str(params.redirect_uri), code=code,
|
||||||
|
state=params.state, iss=self.issuer)
|
||||||
|
return await asyncio.to_thread(write)
|
||||||
|
|
||||||
|
async def load_authorization_code(self, client: OAuthClientInformationFull,
|
||||||
|
authorization_code: str) -> AuthorizationCode | None:
|
||||||
|
def read():
|
||||||
|
with closing(db._conn()) as conn:
|
||||||
|
return conn.execute("SELECT grant, expires_at FROM mcp_oauth_codes "
|
||||||
|
"WHERE code_hash=? AND client_id=?",
|
||||||
|
(_digest(authorization_code), client.client_id)).fetchone()
|
||||||
|
row = await asyncio.to_thread(read)
|
||||||
|
if row is None or row["expires_at"] < time.time():
|
||||||
|
return None
|
||||||
|
return AuthorizationCode.model_validate({**json.loads(row["grant"]), "code": authorization_code})
|
||||||
|
|
||||||
|
def _issue(self, conn, *, client_id: str, username: str, scopes: list[str],
|
||||||
|
resource: str, family: str | None = None) -> OAuthToken:
|
||||||
|
family = family or secrets.token_urlsafe(24)
|
||||||
|
access, refresh = secrets.token_urlsafe(32), secrets.token_urlsafe(32)
|
||||||
|
now = time.time()
|
||||||
|
for raw, kind, expires in ((access, "access", now + ACCESS_TTL),
|
||||||
|
(refresh, "refresh", now + REFRESH_TTL)):
|
||||||
|
conn.execute("INSERT INTO mcp_oauth_tokens VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL)",
|
||||||
|
(_digest(raw), kind, family, client_id, username,
|
||||||
|
json.dumps(scopes), resource, expires))
|
||||||
|
return OAuthToken(access_token=access, refresh_token=refresh, expires_in=ACCESS_TTL,
|
||||||
|
scope=" ".join(scopes))
|
||||||
|
|
||||||
|
async def exchange_authorization_code(self, client: OAuthClientInformationFull,
|
||||||
|
authorization_code: AuthorizationCode) -> OAuthToken:
|
||||||
|
if not authorization_code.subject or not await asyncio.to_thread(_active_user, authorization_code.subject):
|
||||||
|
raise TokenError("invalid_grant", "Account is unavailable")
|
||||||
|
def write():
|
||||||
|
with closing(db._conn()) as conn, conn:
|
||||||
|
row = conn.execute("DELETE FROM mcp_oauth_codes WHERE code_hash=? AND client_id=? "
|
||||||
|
"RETURNING grant", (_digest(authorization_code.code), client.client_id)).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise TokenError("invalid_grant", "Authorization code was already used")
|
||||||
|
saved = AuthorizationCode.model_validate({**json.loads(row["grant"]),
|
||||||
|
"code": authorization_code.code})
|
||||||
|
if saved.expires_at < time.time() or saved.subject != authorization_code.subject \
|
||||||
|
or saved.resource != self.resource:
|
||||||
|
raise TokenError("invalid_grant", "Authorization code is invalid")
|
||||||
|
return self._issue(conn, client_id=client.client_id, username=saved.subject,
|
||||||
|
scopes=saved.scopes, resource=self.resource)
|
||||||
|
return await asyncio.to_thread(write)
|
||||||
|
|
||||||
|
async def load_refresh_token(self, client: OAuthClientInformationFull,
|
||||||
|
refresh_token: str) -> RefreshToken | None:
|
||||||
|
row = await asyncio.to_thread(self._token_row, refresh_token, "refresh", client.client_id)
|
||||||
|
if row is None:
|
||||||
|
return None
|
||||||
|
return RefreshToken(token=refresh_token, client_id=client.client_id,
|
||||||
|
scopes=json.loads(row["scopes"]), expires_at=int(row["expires_at"]),
|
||||||
|
resource=row["resource"], subject=row["username"])
|
||||||
|
|
||||||
|
async def exchange_refresh_token(self, client: OAuthClientInformationFull,
|
||||||
|
refresh_token: RefreshToken, scopes: list[str]) -> OAuthToken:
|
||||||
|
if not set(scopes).issubset(refresh_token.scopes):
|
||||||
|
raise TokenError("invalid_scope", "Scope expansion requires consent")
|
||||||
|
if not refresh_token.subject or not await asyncio.to_thread(_active_user, refresh_token.subject):
|
||||||
|
raise TokenError("invalid_grant", "Account is unavailable")
|
||||||
|
def write():
|
||||||
|
with closing(db._conn()) as conn, conn:
|
||||||
|
conn.execute("BEGIN IMMEDIATE")
|
||||||
|
row = conn.execute("SELECT family, expires_at FROM mcp_oauth_tokens "
|
||||||
|
"WHERE token_hash=? AND kind='refresh' AND client_id=? "
|
||||||
|
"AND revoked_at IS NULL", (_digest(refresh_token.token), client.client_id)).fetchone()
|
||||||
|
if row is None or row["expires_at"] < time.time():
|
||||||
|
raise TokenError("invalid_grant", "Refresh token was already used")
|
||||||
|
conn.execute("UPDATE mcp_oauth_tokens SET revoked_at=? WHERE family=? AND revoked_at IS NULL",
|
||||||
|
(time.time(), row["family"]))
|
||||||
|
return self._issue(conn, client_id=client.client_id, username=refresh_token.subject,
|
||||||
|
scopes=scopes or refresh_token.scopes, resource=self.resource,
|
||||||
|
family=row["family"])
|
||||||
|
return await asyncio.to_thread(write)
|
||||||
|
|
||||||
|
def _token_row(self, raw: str, kind: str, client_id: str | None = None):
|
||||||
|
with closing(db._conn()) as conn:
|
||||||
|
query = "SELECT * FROM mcp_oauth_tokens WHERE token_hash=? AND kind=? AND revoked_at IS NULL"
|
||||||
|
args: tuple = (_digest(raw), kind)
|
||||||
|
if client_id is not None:
|
||||||
|
query += " AND client_id=?"
|
||||||
|
args += (client_id,)
|
||||||
|
row = conn.execute(query, args).fetchone()
|
||||||
|
if row is None or row["expires_at"] < time.time() or row["resource"] != self.resource:
|
||||||
|
return None
|
||||||
|
return row if _active_user(row["username"]) else None
|
||||||
|
|
||||||
|
async def load_access_token(self, token: str) -> AccessToken | None:
|
||||||
|
row = await asyncio.to_thread(self._token_row, token, "access")
|
||||||
|
if row is None:
|
||||||
|
return None
|
||||||
|
return AccessToken(token=token, client_id=row["client_id"],
|
||||||
|
scopes=json.loads(row["scopes"]), expires_at=int(row["expires_at"]),
|
||||||
|
resource=row["resource"], subject=row["username"],
|
||||||
|
claims={"iss": self.issuer})
|
||||||
|
|
||||||
|
async def revoke_token(self, token: AccessToken | RefreshToken) -> None:
|
||||||
|
def write():
|
||||||
|
with closing(db._conn()) as conn, conn:
|
||||||
|
row = conn.execute("SELECT family FROM mcp_oauth_tokens WHERE token_hash=?",
|
||||||
|
(_digest(token.token),)).fetchone()
|
||||||
|
if row:
|
||||||
|
conn.execute("UPDATE mcp_oauth_tokens SET revoked_at=? WHERE family=? AND revoked_at IS NULL",
|
||||||
|
(time.time(), row["family"]))
|
||||||
|
await asyncio.to_thread(write)
|
||||||
|
|
||||||
|
async def revoke_client_for_user(self, username: str, client_id: str) -> None:
|
||||||
|
def write():
|
||||||
|
with closing(db._conn()) as conn, conn:
|
||||||
|
conn.execute("UPDATE mcp_oauth_consents SET revoked_at=? "
|
||||||
|
"WHERE username=? AND client_id=?", (time.time(), username, client_id))
|
||||||
|
conn.execute("UPDATE mcp_oauth_tokens SET revoked_at=? "
|
||||||
|
"WHERE username=? AND client_id=? AND revoked_at IS NULL",
|
||||||
|
(time.time(), username, client_id))
|
||||||
|
await asyncio.to_thread(write)
|
||||||
|
|
||||||
|
async def list_clients_for_user(self, username: str) -> list[dict]:
|
||||||
|
def read():
|
||||||
|
with closing(db._conn()) as conn:
|
||||||
|
rows = conn.execute("SELECT c.client_id, c.metadata, g.scopes, g.approved_at "
|
||||||
|
"FROM mcp_oauth_consents g JOIN mcp_oauth_clients c "
|
||||||
|
"ON c.client_id=g.client_id WHERE g.username=? AND g.revoked_at IS NULL",
|
||||||
|
(username,)).fetchall()
|
||||||
|
return [{"client_id": r["client_id"],
|
||||||
|
"client_name": json.loads(r["metadata"]).get("client_name") or r["client_id"],
|
||||||
|
"scopes": json.loads(r["scopes"]), "approved_at": r["approved_at"]}
|
||||||
|
for r in rows]
|
||||||
|
return await asyncio.to_thread(read)
|
||||||
|
|
||||||
|
async def prepare_action(self, username: str, client_id: str, tab_id: str, kind: str) -> str:
|
||||||
|
if kind != "clear_files":
|
||||||
|
raise ValueError("Unknown action")
|
||||||
|
ticket = secrets.token_urlsafe(32)
|
||||||
|
def write():
|
||||||
|
with closing(db._conn()) as conn, conn:
|
||||||
|
conn.execute("INSERT INTO mcp_pending_actions VALUES (?,?,?,?,?,?,NULL)",
|
||||||
|
(_digest(ticket), username, client_id, tab_id, kind, time.time() + 600))
|
||||||
|
await asyncio.to_thread(write)
|
||||||
|
return f"{self.issuer}/mcp/confirm-action?{urlencode({'ticket': ticket})}"
|
||||||
|
|
||||||
|
async def action_info(self, ticket: str) -> dict | None:
|
||||||
|
def read():
|
||||||
|
with closing(db._conn()) as conn:
|
||||||
|
return conn.execute("SELECT username, client_id, tab_id, kind, expires_at, approved_at "
|
||||||
|
"FROM mcp_pending_actions WHERE ticket_hash=?", (_digest(ticket),)).fetchone()
|
||||||
|
row = await asyncio.to_thread(read)
|
||||||
|
if not row or row["expires_at"] < time.time():
|
||||||
|
return None
|
||||||
|
return {key: row[key] for key in ("username", "client_id", "tab_id", "kind", "approved_at")}
|
||||||
|
|
||||||
|
async def approve_action(self, ticket: str, username: str) -> None:
|
||||||
|
def write():
|
||||||
|
with closing(db._conn()) as conn, conn:
|
||||||
|
changed = conn.execute("UPDATE mcp_pending_actions SET approved_at=? "
|
||||||
|
"WHERE ticket_hash=? AND username=? AND expires_at>? AND approved_at IS NULL",
|
||||||
|
(time.time(), _digest(ticket), username, time.time()))
|
||||||
|
if changed.rowcount != 1:
|
||||||
|
raise ValueError("Confirmation expired")
|
||||||
|
await asyncio.to_thread(write)
|
||||||
|
|
||||||
|
async def consume_action(self, ticket: str, username: str, client_id: str,
|
||||||
|
tab_id: str, kind: str) -> None:
|
||||||
|
def write():
|
||||||
|
with closing(db._conn()) as conn, conn:
|
||||||
|
row = conn.execute("DELETE FROM mcp_pending_actions WHERE ticket_hash=? "
|
||||||
|
"AND username=? AND client_id=? AND tab_id=? AND kind=? AND approved_at IS NOT NULL "
|
||||||
|
"AND expires_at>? RETURNING ticket_hash",
|
||||||
|
(_digest(ticket), username, client_id, tab_id, kind, time.time())).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise PermissionError("Action needs browser confirmation")
|
||||||
|
await asyncio.to_thread(write)
|
||||||
@@ -6,6 +6,7 @@ fastapi==0.135.2
|
|||||||
uvicorn[standard]==0.42.0
|
uvicorn[standard]==0.42.0
|
||||||
starlette==0.52.1
|
starlette==0.52.1
|
||||||
pydantic==2.11.4
|
pydantic==2.11.4
|
||||||
|
mcp==1.30.0 # Streamable HTTP + OAuth; совместим с текущим Pydantic
|
||||||
python-jose[cryptography]==3.5.0
|
python-jose[cryptography]==3.5.0
|
||||||
python-multipart==0.0.22
|
python-multipart==0.0.22
|
||||||
httpx==0.28.1
|
httpx==0.28.1
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ mkdir -p "$checkout/tests/fixtures/tsn_local"
|
|||||||
for pdf in tsn3-1.pdf index222.pdf; do
|
for pdf in tsn3-1.pdf index222.pdf; do
|
||||||
cp "$prod/tests/fixtures/tsn_local/$pdf" "$checkout/tests/fixtures/tsn_local/$pdf"
|
cp "$prod/tests/fixtures/tsn_local/$pdf" "$checkout/tests/fixtures/tsn_local/$pdf"
|
||||||
done
|
done
|
||||||
|
PYTHONPATH="$stage/.deps${PYTHONPATH:+:$PYTHONPATH}" \
|
||||||
APP_DIR="$checkout" COPY_DIR=/home/mcp-user/smeta-prod-auto-predeploy \
|
APP_DIR="$checkout" COPY_DIR=/home/mcp-user/smeta-prod-auto-predeploy \
|
||||||
bash "$checkout/scripts/predeploy-tests.sh" > "$log" 2>&1 || {
|
bash "$checkout/scripts/predeploy-tests.sh" > "$log" 2>&1 || {
|
||||||
tail -30 "$log" >&2
|
tail -30 "$log" >&2
|
||||||
|
|||||||
@@ -35,6 +35,8 @@ if systemctl is-active --quiet smeta-web-release; then
|
|||||||
sudo systemctl stop smeta-web-release
|
sudo systemctl stop smeta-web-release
|
||||||
fi
|
fi
|
||||||
git -C "$stage" merge --ff-only "$sha"
|
git -C "$stage" merge --ff-only "$sha"
|
||||||
|
bash "$stage/scripts/ensure-release-mcp.sh"
|
||||||
|
export PYTHONPATH="$stage/.deps${PYTHONPATH:+:$PYTHONPATH}"
|
||||||
cp "$prod/$index" "$stage/$index"
|
cp "$prod/$index" "$stage/$index"
|
||||||
sqlite3 "$prod/smeta-web.db" ".backup $stage/smeta-web.db"
|
sqlite3 "$prod/smeta-web.db" ".backup $stage/smeta-web.db"
|
||||||
mkdir -p "$stage/tests/fixtures/tsn_local"
|
mkdir -p "$stage/tests/fixtures/tsn_local"
|
||||||
@@ -72,6 +74,6 @@ test "$(sha256sum "$prod/$index" | cut -d' ' -f1)" = \
|
|||||||
"$(sha256sum "$stage/$index" | cut -d' ' -f1)"
|
"$(sha256sum "$stage/$index" | cut -d' ' -f1)"
|
||||||
|
|
||||||
(cd "$stage" && set -a && . ./.env && set +a &&
|
(cd "$stage" && set -a && . ./.env && set +a &&
|
||||||
PYTHONPATH="$stage" timeout 420 python3 scripts/release_smoke.py)
|
PYTHONPATH="$stage:$stage/.deps" timeout 420 python3 scripts/release_smoke.py)
|
||||||
python3 "$stage/scripts/release_gate.py" mark "$sha" "$stage" "$prod/$index" "$marker"
|
python3 "$stage/scripts/release_gate.py" mark "$sha" "$stage" "$prod/$index" "$marker"
|
||||||
echo "RELEASE_DEV_OK sha=$sha port=8106 log=$log"
|
echo "RELEASE_DEV_OK sha=$sha port=8106 log=$log"
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Keep the release candidate's MCP SDK out of the production Python environment.
|
||||||
|
set -euo pipefail
|
||||||
|
target=/home/mcp-user/smeta-web-release/.deps
|
||||||
|
mkdir -p "$target"
|
||||||
|
if PYTHONPATH="$target${PYTHONPATH:+:$PYTHONPATH}" python3 - <<'PY'
|
||||||
|
from importlib.metadata import version
|
||||||
|
assert version('mcp') == '1.30.0'
|
||||||
|
assert version('PyJWT') == '2.10.1'
|
||||||
|
PY
|
||||||
|
then
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
python3 -m pip install -q --disable-pip-version-check --no-deps --upgrade \
|
||||||
|
--target "$target" 'mcp==1.30.0' 'PyJWT==2.10.1'
|
||||||
|
PYTHONPATH="$target${PYTHONPATH:+:$PYTHONPATH}" python3 - <<'PY'
|
||||||
|
from importlib.metadata import version
|
||||||
|
assert version('mcp') == '1.30.0'
|
||||||
|
assert version('PyJWT') == '2.10.1'
|
||||||
|
from mcp.server.fastmcp import FastMCP
|
||||||
|
PY
|
||||||
@@ -19,6 +19,7 @@ mkdir -p "$COPY_DIR"
|
|||||||
# .git тоже нужен: test_predeploy вызывает git внутри копии (rollback-floor).
|
# .git тоже нужен: test_predeploy вызывает git внутри копии (rollback-floor).
|
||||||
rsync -a --delete \
|
rsync -a --delete \
|
||||||
--exclude "__pycache__" --exclude "*.pyc" --exclude "uploads" --exclude "logs" \
|
--exclude "__pycache__" --exclude "*.pyc" --exclude "uploads" --exclude "logs" \
|
||||||
|
--exclude ".deps" --exclude ".venv" \
|
||||||
--exclude ".predeploy-stamp" \
|
--exclude ".predeploy-stamp" \
|
||||||
"$APP_DIR"/ "$COPY_DIR"/ || exit 1
|
"$APP_DIR"/ "$COPY_DIR"/ || exit 1
|
||||||
cd "$COPY_DIR" || exit 1
|
cd "$COPY_DIR" || exit 1
|
||||||
|
|||||||
@@ -3,6 +3,9 @@
|
|||||||
import json
|
import json
|
||||||
import secrets
|
import secrets
|
||||||
import sqlite3
|
import sqlite3
|
||||||
|
import os
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
import auth
|
import auth
|
||||||
import db
|
import db
|
||||||
@@ -10,6 +13,34 @@ import regional_ref
|
|||||||
from scripts.shadow.send import send
|
from scripts.shadow.send import send
|
||||||
|
|
||||||
|
|
||||||
|
def mcp_smoke(email: str) -> None:
|
||||||
|
from mcp_identity import InfosmetaOAuthProvider
|
||||||
|
resource = os.environ.get("PUBLIC_BASE_URL", "http://127.0.0.1:8106").rstrip("/") + "/mcp"
|
||||||
|
provider = InfosmetaOAuthProvider(resource.removesuffix("/mcp"), resource)
|
||||||
|
with db._conn() as conn:
|
||||||
|
token = provider._issue(conn, client_id="release-smoke", username=email,
|
||||||
|
scopes=["files:read", "norms:read"], resource=resource)
|
||||||
|
base = "http://127.0.0.1:8106"
|
||||||
|
headers = {"MCP-Protocol-Version": "2025-11-25", "Accept": "application/json, text/event-stream"}
|
||||||
|
with httpx.Client(timeout=15.0, trust_env=False) as client:
|
||||||
|
denied = client.post(base + "/mcp", headers=headers,
|
||||||
|
json={"jsonrpc": "2.0", "id": 1, "method": "tools/list"})
|
||||||
|
assert denied.status_code == 401 and "resource_metadata" in denied.headers.get("www-authenticate", "")
|
||||||
|
meta = client.get(base + "/.well-known/oauth-authorization-server")
|
||||||
|
assert meta.status_code == 200 and meta.json()["token_endpoint"].endswith("/token")
|
||||||
|
allowed = client.post(base + "/mcp", headers={**headers, "Authorization": "Bearer " + token.access_token,
|
||||||
|
"Mcp-Method": "tools/list"}, json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
|
||||||
|
assert allowed.status_code == 200, allowed.text[:200]
|
||||||
|
names = {entry["name"] for entry in allowed.json()["result"]["tools"]}
|
||||||
|
assert "regional_rate" in names and "list_files" in names and "stove_estimate" not in names
|
||||||
|
called = client.post(base + "/mcp", headers={**headers, "Authorization": "Bearer " + token.access_token,
|
||||||
|
"Mcp-Method": "tools/call", "Mcp-Name": "list_files"},
|
||||||
|
json={"jsonrpc": "2.0", "id": 3, "method": "tools/call",
|
||||||
|
"params": {"name": "list_files", "arguments": {}}})
|
||||||
|
assert called.status_code == 200 and not called.json()["result"]["isError"]
|
||||||
|
print(json.dumps({"mcp_discovery": True, "mcp_tool_call": True}))
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
email = "release-smoke@local"
|
email = "release-smoke@local"
|
||||||
if db.get_user_by_email(email) is None:
|
if db.get_user_by_email(email) is None:
|
||||||
@@ -17,6 +48,7 @@ def main() -> None:
|
|||||||
db.admin_verify_user(email)
|
db.admin_verify_user(email)
|
||||||
db.set_user_agent_access(email, True)
|
db.set_user_agent_access(email, True)
|
||||||
try:
|
try:
|
||||||
|
mcp_smoke(email)
|
||||||
with sqlite3.connect(str(regional_ref.DEFAULT_DB)) as regional:
|
with sqlite3.connect(str(regional_ref.DEFAULT_DB)) as regional:
|
||||||
sample = regional.execute(
|
sample = regional.execute(
|
||||||
"select s.name, w.code from works w join subjects s "
|
"select s.name, w.code from works w join subjects s "
|
||||||
|
|||||||
@@ -22,6 +22,10 @@ PROTOCOL_VERSION = "2025-06-18"
|
|||||||
|
|
||||||
|
|
||||||
def _user_tab() -> tuple[str, str]:
|
def _user_tab() -> tuple[str, str]:
|
||||||
|
from mcp_context import current_tool_context
|
||||||
|
bound = current_tool_context()
|
||||||
|
if bound is not None:
|
||||||
|
return bound.username, bound.tab_id
|
||||||
return (
|
return (
|
||||||
os.environ.get("SMETA_USER", "").strip(),
|
os.environ.get("SMETA_USER", "").strip(),
|
||||||
os.environ.get("SMETA_TAB", "default").strip() or "default",
|
os.environ.get("SMETA_TAB", "default").strip() or "default",
|
||||||
@@ -37,6 +41,12 @@ def _work_dir(user: str, tab: str) -> Path:
|
|||||||
|
|
||||||
Иначе — DATA_DIR/user/tab (как на хосте main-приложения).
|
Иначе — DATA_DIR/user/tab (как на хосте main-приложения).
|
||||||
"""
|
"""
|
||||||
|
from mcp_context import current_tool_context
|
||||||
|
bound = current_tool_context()
|
||||||
|
if bound is not None:
|
||||||
|
if (user, tab) != (bound.username, bound.tab_id):
|
||||||
|
raise PermissionError("MCP context does not own this work directory")
|
||||||
|
return bound.work_dir
|
||||||
direct = os.environ.get("SMETA_WORK_DIR")
|
direct = os.environ.get("SMETA_WORK_DIR")
|
||||||
if direct:
|
if direct:
|
||||||
return Path(direct)
|
return Path(direct)
|
||||||
|
|||||||
@@ -730,6 +730,7 @@ html { color-scheme: light; }
|
|||||||
onclick="closeAccountMenu(); toggleInvitePanel()">Пригласить коллегу</button>
|
onclick="closeAccountMenu(); toggleInvitePanel()">Пригласить коллегу</button>
|
||||||
<button type="button" role="menuitem" id="btn-device"
|
<button type="button" role="menuitem" id="btn-device"
|
||||||
onclick="closeAccountMenu(); connectProgram()">Подключить программу</button>
|
onclick="closeAccountMenu(); connectProgram()">Подключить программу</button>
|
||||||
|
<button type="button" role="menuitem" onclick="closeAccountMenu(); location.href='/mcp/clients'">Подключённые ИИ</button>
|
||||||
<div class="account-menu-sep" aria-hidden="true"></div>
|
<div class="account-menu-sep" aria-hidden="true"></div>
|
||||||
<button type="button" role="menuitem" onclick="logout()">Выйти</button>
|
<button type="button" role="menuitem" onclick="logout()">Выйти</button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>Подключённые ИИ — Инфосмета</title><style>
|
||||||
|
body{font:16px/1.5 system-ui,sans-serif;background:#f5f7fa;color:#202735;margin:0;padding:24px}
|
||||||
|
main{max-width:640px;margin:6vh auto;background:white;padding:32px;border-radius:16px;box-shadow:0 4px 32px #172c451a}
|
||||||
|
li{padding:14px 0;border-bottom:1px solid #dde4ed}button{background:#b12d37;color:white;border:0;border-radius:7px;padding:8px 12px;cursor:pointer}
|
||||||
|
</style></head><body><main><p><a href="/">← Инфосмета</a></p><h1>Подключённые ИИ</h1><p>Здесь можно отозвать доступ. После отзыва потребуется новое подключение.</p>
|
||||||
|
<p id="status" role="status"></p><ul id="clients"></ul></main><script>
|
||||||
|
const token=localStorage.getItem('token');
|
||||||
|
const status=document.getElementById('status');
|
||||||
|
const list=document.getElementById('clients');
|
||||||
|
if(!token){status.textContent='Войдите в Инфосмету и обновите страницу.';}
|
||||||
|
else load();
|
||||||
|
async function load(){
|
||||||
|
const r=await fetch('/api/mcp/clients',{headers:{Authorization:'Bearer '+token},cache:'no-store'});
|
||||||
|
if(!r.ok){status.textContent='Сеанс истёк. Войдите снова.';return;}
|
||||||
|
const clients=await r.json();list.replaceChildren();
|
||||||
|
if(!clients.length){status.textContent='Активных подключений нет.';return;}
|
||||||
|
status.textContent='';
|
||||||
|
for(const c of clients){
|
||||||
|
const li=document.createElement('li');
|
||||||
|
const title=document.createElement('strong');title.textContent=c.client_name;
|
||||||
|
const rights=document.createElement('p');rights.textContent='Права: '+c.scopes.join(', ');
|
||||||
|
const button=document.createElement('button');button.textContent='Отозвать доступ';
|
||||||
|
button.onclick=async()=>{
|
||||||
|
if(!confirm('Отозвать доступ для '+c.client_name+'?'))return;
|
||||||
|
button.disabled=true;
|
||||||
|
const gone=await fetch('/api/mcp/clients/'+encodeURIComponent(c.client_id),{method:'DELETE',headers:{Authorization:'Bearer '+token}});
|
||||||
|
if(gone.ok)load();else{button.disabled=false;status.textContent='Не удалось отозвать доступ.';}
|
||||||
|
};
|
||||||
|
li.append(title,rights,button);list.append(li);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script></body></html>
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Подтверждение — Инфосмета</title><style>
|
||||||
|
body{font:16px/1.5 system-ui,sans-serif;background:#f5f7fa;color:#202735;margin:0;padding:24px}
|
||||||
|
main{max-width:530px;margin:8vh auto;background:white;padding:32px;border-radius:16px;box-shadow:0 4px 32px #172c451a}
|
||||||
|
button{background:#b12d37;color:white;border:0;border-radius:8px;padding:12px 18px;font:inherit;cursor:pointer}
|
||||||
|
</style></head><body><main><h1>Подтвердить очистку файлов</h1><p id="details"></p>
|
||||||
|
<p>Файлы и история этой вкладки будут удалены. Действие нельзя отменить.</p>
|
||||||
|
<p id="login" hidden>Войдите в Инфосмету в соседней вкладке и вернитесь сюда. <a href="/" target="_blank" rel="noopener">Открыть вход</a></p>
|
||||||
|
<p id="status" role="status"></p><button id="approve" type="button">Подтвердить удаление</button></main><script>
|
||||||
|
(async()=>{
|
||||||
|
const ticket=new URLSearchParams(location.search).get('ticket');
|
||||||
|
const status=document.getElementById('status');
|
||||||
|
if(!ticket){status.textContent='Ссылка неполная.';return;}
|
||||||
|
const r=await fetch('/api/mcp/action?ticket='+encodeURIComponent(ticket),{cache:'no-store'});
|
||||||
|
if(!r.ok){status.textContent='Запрос устарел.';return;}
|
||||||
|
const data=await r.json();
|
||||||
|
document.getElementById('details').textContent='Вкладка: '+data.tab_id;
|
||||||
|
if(!localStorage.getItem('token'))document.getElementById('login').hidden=false;
|
||||||
|
document.getElementById('approve').onclick=async()=>{
|
||||||
|
const token=localStorage.getItem('token');
|
||||||
|
if(!token){document.getElementById('login').hidden=false;status.textContent='Сначала войдите.';return;}
|
||||||
|
const done=await fetch('/api/mcp/action',{method:'POST',headers:{'Content-Type':'application/json','Authorization':'Bearer '+token},body:JSON.stringify({ticket})});
|
||||||
|
status.textContent=done.ok?'Подтверждено. Вернитесь к вашему ИИ и продолжите очистку.':'Подтверждение не удалось. Проверьте вход и повторите запрос.';
|
||||||
|
if(done.ok)document.getElementById('approve').disabled=true;
|
||||||
|
};
|
||||||
|
})();
|
||||||
|
</script></body></html>
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Подключение ИИ — Инфосмета</title>
|
||||||
|
<style>
|
||||||
|
body{font:16px/1.5 system-ui,sans-serif;background:#f5f7fa;color:#202735;margin:0;padding:24px}
|
||||||
|
main{max-width:550px;margin:8vh auto;background:white;padding:32px;border-radius:16px;box-shadow:0 4px 32px #172c451a}
|
||||||
|
h1{font-size:1.5rem}ul{padding-left:1.4rem}button{border:0;border-radius:8px;padding:12px 18px;font:inherit;cursor:pointer}
|
||||||
|
#approve{background:#1868cf;color:white}#deny{background:#e9edf3;color:#202735}p.status{min-height:1.5em}
|
||||||
|
</style></head><body><main>
|
||||||
|
<h1>Подключить внешний ИИ</h1>
|
||||||
|
<p id="client"></p><p>После разрешения приложение сможет действовать от вашего имени в указанных пределах.</p>
|
||||||
|
<ul id="scopes"></ul>
|
||||||
|
<p id="login" hidden>Войдите в Инфосмету в соседней вкладке, затем вернитесь сюда. <a href="/" target="_blank" rel="noopener">Открыть вход</a></p>
|
||||||
|
<p class="status" id="status" role="status"></p>
|
||||||
|
<button id="approve" type="button">Разрешить</button> <button id="deny" type="button">Отказать</button>
|
||||||
|
</main><script>
|
||||||
|
(async () => {
|
||||||
|
const ticket = new URLSearchParams(location.search).get('ticket');
|
||||||
|
const status = document.getElementById('status');
|
||||||
|
if (!ticket) { status.textContent = 'Ссылка неполная.'; return; }
|
||||||
|
const info = await fetch('/api/mcp/consent?ticket=' + encodeURIComponent(ticket), {cache:'no-store'});
|
||||||
|
if (!info.ok) { status.textContent = 'Запрос устарел. Начните подключение заново.'; return; }
|
||||||
|
const data = await info.json();
|
||||||
|
document.getElementById('client').textContent = 'Приложение: ' + data.client_name;
|
||||||
|
const list = document.getElementById('scopes');
|
||||||
|
for (const scope of data.scopes) { const li=document.createElement('li'); li.textContent=scope; list.append(li); }
|
||||||
|
const token = localStorage.getItem('token');
|
||||||
|
if (!token) document.getElementById('login').hidden = false;
|
||||||
|
async function decide(approved) {
|
||||||
|
const bearer = localStorage.getItem('token');
|
||||||
|
if (!bearer) { document.getElementById('login').hidden=false; status.textContent='Сначала войдите в Инфосмету.'; return; }
|
||||||
|
status.textContent='Проверяем доступ…';
|
||||||
|
const res=await fetch('/oauth/consent',{method:'POST',headers:{'Content-Type':'application/json','Authorization':'Bearer '+bearer},body:JSON.stringify({ticket,approved})});
|
||||||
|
if (res.status===401) { document.getElementById('login').hidden=false; status.textContent='Вход истёк. Войдите снова.'; return; }
|
||||||
|
if (!res.ok) { status.textContent='Не удалось завершить подключение. Повторите его из клиента.'; return; }
|
||||||
|
location.assign((await res.json()).redirect);
|
||||||
|
}
|
||||||
|
document.getElementById('approve').onclick=()=>decide(true);
|
||||||
|
document.getElementById('deny').onclick=()=>decide(false);
|
||||||
|
})();
|
||||||
|
</script></body></html>
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
"""A remote MCP call must not borrow another user's process environment."""
|
||||||
|
import asyncio
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def test_explicit_context_overrides_process_environment(monkeypatch, tmp_path):
|
||||||
|
monkeypatch.setenv("SMETA_USER", "wrong-user")
|
||||||
|
monkeypatch.setenv("SMETA_TAB", "wrong-tab")
|
||||||
|
monkeypatch.setenv("SMETA_WORK_DIR", str(tmp_path / "wrong"))
|
||||||
|
import smeta_mcp
|
||||||
|
from mcp_context import ToolContext, bind_tool_context
|
||||||
|
own = tmp_path / "alice"
|
||||||
|
with bind_tool_context(ToolContext("alice", "alice-tab", own, "client-a", frozenset())):
|
||||||
|
assert smeta_mcp._user_tab() == ("alice", "alice-tab")
|
||||||
|
assert smeta_mcp._work_dir("alice", "alice-tab") == own
|
||||||
|
assert smeta_mcp._user_tab() == ("wrong-user", "wrong-tab")
|
||||||
|
|
||||||
|
|
||||||
|
def test_parallel_contexts_do_not_mix(monkeypatch, tmp_path):
|
||||||
|
monkeypatch.setenv("SMETA_USER", "wrong-user")
|
||||||
|
import smeta_mcp
|
||||||
|
from mcp_context import ToolContext, bind_tool_context
|
||||||
|
|
||||||
|
async def one(user):
|
||||||
|
with bind_tool_context(ToolContext(user, "tab", Path(tmp_path / user),
|
||||||
|
"client", frozenset())):
|
||||||
|
await asyncio.sleep(0)
|
||||||
|
return await asyncio.to_thread(smeta_mcp._user_tab)
|
||||||
|
|
||||||
|
async def both():
|
||||||
|
return await asyncio.gather(one("alice"), one("bob"))
|
||||||
|
|
||||||
|
assert asyncio.run(both()) == [
|
||||||
|
("alice", "tab"), ("bob", "tab")]
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
"""OAuth grant and revocation contract for the external MCP server."""
|
||||||
|
import asyncio
|
||||||
|
from urllib.parse import parse_qs, urlparse
|
||||||
|
|
||||||
|
from pydantic import AnyUrl
|
||||||
|
from mcp.server.auth.provider import AuthorizationParams
|
||||||
|
from mcp.shared.auth import OAuthClientInformationFull
|
||||||
|
|
||||||
|
|
||||||
|
def test_approved_client_receives_user_bound_token_and_revocation(tmp_path, monkeypatch):
|
||||||
|
import db
|
||||||
|
monkeypatch.setattr(db, "DB_PATH", tmp_path / "mcp.db")
|
||||||
|
db.init_db()
|
||||||
|
db.create_user("alice@example.test", "hash")
|
||||||
|
db.admin_verify_user("alice@example.test")
|
||||||
|
|
||||||
|
from mcp_identity import InfosmetaOAuthProvider
|
||||||
|
provider = InfosmetaOAuthProvider("https://infosmeta.test", "https://infosmeta.test/mcp")
|
||||||
|
asyncio.run(provider.register_client(OAuthClientInformationFull(
|
||||||
|
client_id="client-a", client_name="Тестовый ИИ",
|
||||||
|
redirect_uris=[AnyUrl("http://localhost:9876/callback")],
|
||||||
|
token_endpoint_auth_method="none", scope="norms:read files:read")))
|
||||||
|
client = asyncio.run(provider.get_client("client-a"))
|
||||||
|
params = AuthorizationParams(state="state-a", scopes=["norms:read"],
|
||||||
|
code_challenge="a" * 43, redirect_uri=AnyUrl("http://localhost:9876/callback"),
|
||||||
|
redirect_uri_provided_explicitly=True, resource="https://infosmeta.test/mcp")
|
||||||
|
|
||||||
|
consent_url = asyncio.run(provider.authorize(client, params))
|
||||||
|
ticket = parse_qs(urlparse(consent_url).query)["ticket"][0]
|
||||||
|
callback_url = asyncio.run(provider.confirm(ticket, "alice@example.test", approved=True))
|
||||||
|
code = parse_qs(urlparse(callback_url).query)["code"][0]
|
||||||
|
grant = asyncio.run(provider.load_authorization_code(client, code))
|
||||||
|
token = asyncio.run(provider.exchange_authorization_code(client, grant))
|
||||||
|
access = asyncio.run(provider.load_access_token(token.access_token))
|
||||||
|
|
||||||
|
assert access.subject == "alice@example.test"
|
||||||
|
assert access.client_id == "client-a"
|
||||||
|
assert access.resource == "https://infosmeta.test/mcp"
|
||||||
|
assert access.scopes == ["norms:read"]
|
||||||
|
assert asyncio.run(provider.load_authorization_code(client, code)) is None
|
||||||
|
asyncio.run(provider.revoke_token(access))
|
||||||
|
assert asyncio.run(provider.load_access_token(token.access_token)) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_wrong_resource_is_rejected(tmp_path, monkeypatch):
|
||||||
|
import db
|
||||||
|
monkeypatch.setattr(db, "DB_PATH", tmp_path / "mcp.db")
|
||||||
|
db.init_db()
|
||||||
|
from mcp_identity import InfosmetaOAuthProvider
|
||||||
|
from mcp.server.auth.provider import AuthorizeError
|
||||||
|
provider = InfosmetaOAuthProvider("https://infosmeta.test", "https://infosmeta.test/mcp")
|
||||||
|
client = OAuthClientInformationFull(client_id="x", redirect_uris=[AnyUrl("http://localhost/cb")])
|
||||||
|
params = AuthorizationParams(state=None, scopes=["norms:read"],
|
||||||
|
code_challenge="a" * 43, redirect_uri=AnyUrl("http://localhost/cb"),
|
||||||
|
redirect_uri_provided_explicitly=True, resource="https://other.test/mcp")
|
||||||
|
try:
|
||||||
|
asyncio.run(provider.authorize(client, params))
|
||||||
|
except AuthorizeError as error:
|
||||||
|
assert error.error == "invalid_target"
|
||||||
|
else:
|
||||||
|
raise AssertionError("чужой resource должен быть отклонён")
|
||||||
|
|
||||||
|
|
||||||
|
def test_destructive_action_requires_browser_confirmation_once(tmp_path, monkeypatch):
|
||||||
|
import db
|
||||||
|
monkeypatch.setattr(db, "DB_PATH", tmp_path / "mcp.db")
|
||||||
|
db.init_db()
|
||||||
|
from mcp_identity import InfosmetaOAuthProvider
|
||||||
|
provider = InfosmetaOAuthProvider("https://infosmeta.test", "https://infosmeta.test/mcp")
|
||||||
|
url = asyncio.run(provider.prepare_action("alice@example.test", "client-a", "tab-a", "clear_files"))
|
||||||
|
ticket = parse_qs(urlparse(url).query)["ticket"][0]
|
||||||
|
try:
|
||||||
|
asyncio.run(provider.consume_action(ticket, "alice@example.test", "client-a", "tab-a", "clear_files"))
|
||||||
|
except PermissionError:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
raise AssertionError("browser confirmation required")
|
||||||
|
try:
|
||||||
|
asyncio.run(provider.approve_action(ticket, "bob@example.test"))
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
raise AssertionError("another user cannot confirm")
|
||||||
|
asyncio.run(provider.approve_action(ticket, "alice@example.test"))
|
||||||
|
asyncio.run(provider.consume_action(ticket, "alice@example.test", "client-a", "tab-a", "clear_files"))
|
||||||
|
try:
|
||||||
|
asyncio.run(provider.consume_action(ticket, "alice@example.test", "client-a", "tab-a", "clear_files"))
|
||||||
|
except PermissionError:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
raise AssertionError("confirmation must be single-use")
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
"""The public transport must enforce bearer auth and tool scopes."""
|
||||||
|
from contextlib import closing
|
||||||
|
import asyncio
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from urllib.parse import parse_qs, urlparse
|
||||||
|
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
|
||||||
|
def _request(client, token=None):
|
||||||
|
headers = {"MCP-Protocol-Version": "2025-11-25", "Mcp-Method": "tools/list",
|
||||||
|
"Accept": "application/json, text/event-stream"}
|
||||||
|
if token:
|
||||||
|
headers["Authorization"] = "Bearer " + token
|
||||||
|
return client.post("/mcp", headers=headers, json={
|
||||||
|
"jsonrpc": "2.0", "id": 1, "method": "tools/list",
|
||||||
|
"params": {"_meta": {"io.modelcontextprotocol/protocolVersion": "2025-11-25",
|
||||||
|
"io.modelcontextprotocol/clientInfo": {"name": "test", "version": "1"},
|
||||||
|
"io.modelcontextprotocol/clientCapabilities": {}}}})
|
||||||
|
|
||||||
|
|
||||||
|
def test_transport_requires_token_and_filters_tools(tmp_path, monkeypatch):
|
||||||
|
import db
|
||||||
|
monkeypatch.setattr(db, "DB_PATH", tmp_path / "mcp.db")
|
||||||
|
db.init_db()
|
||||||
|
db.create_user("alice@example.test", "hash")
|
||||||
|
db.admin_verify_user("alice@example.test")
|
||||||
|
|
||||||
|
from mcp_identity import InfosmetaOAuthProvider
|
||||||
|
from external_mcp import create_mcp_app
|
||||||
|
provider = InfosmetaOAuthProvider("https://testserver", "https://testserver/mcp")
|
||||||
|
with closing(db._conn()) as conn, conn:
|
||||||
|
token = provider._issue(conn, client_id="ai-client", username="alice@example.test",
|
||||||
|
scopes=["norms:read"], resource=provider.resource)
|
||||||
|
app = create_mcp_app(provider, allowed_hosts=["testserver"])
|
||||||
|
with TestClient(app, base_url="https://testserver") as client:
|
||||||
|
denied = _request(client)
|
||||||
|
assert denied.status_code == 401
|
||||||
|
assert "resource_metadata" in denied.headers["www-authenticate"]
|
||||||
|
allowed = _request(client, token.access_token)
|
||||||
|
assert allowed.status_code == 200, allowed.text
|
||||||
|
names = {tool["name"] for tool in allowed.json()["result"]["tools"]}
|
||||||
|
assert "find_ksr" in names
|
||||||
|
assert "list_files" not in names
|
||||||
|
|
||||||
|
|
||||||
|
def test_oauth_discovery_pkce_and_tool_call(tmp_path, monkeypatch):
|
||||||
|
import db
|
||||||
|
monkeypatch.setattr(db, "DB_PATH", tmp_path / "mcp.db")
|
||||||
|
monkeypatch.setenv("DATA_DIR", str(tmp_path / "data"))
|
||||||
|
monkeypatch.setenv("SESSION_SECRET", "test-only-mcp-secret")
|
||||||
|
db.init_db()
|
||||||
|
db.create_user("alice@example.test", "hash")
|
||||||
|
db.admin_verify_user("alice@example.test")
|
||||||
|
db.create_user("bob@example.test", "hash")
|
||||||
|
db.admin_verify_user("bob@example.test")
|
||||||
|
db.ensure_session("bob@example.test", "bob-tab")
|
||||||
|
from mcp_identity import InfosmetaOAuthProvider
|
||||||
|
from external_mcp import create_mcp_app
|
||||||
|
provider = InfosmetaOAuthProvider("https://testserver", "https://testserver/mcp")
|
||||||
|
app = create_mcp_app(provider, allowed_hosts=["testserver"])
|
||||||
|
verifier = "v" * 43
|
||||||
|
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip("=")
|
||||||
|
with TestClient(app, base_url="https://testserver") as client:
|
||||||
|
meta = client.get("/.well-known/oauth-authorization-server")
|
||||||
|
assert meta.status_code == 200
|
||||||
|
registration = client.post("/register", json={
|
||||||
|
"client_name": "Test AI", "redirect_uris": ["http://localhost:9876/callback"],
|
||||||
|
"scope": "files:read account:read stove:estimate",
|
||||||
|
"grant_types": ["authorization_code", "refresh_token"],
|
||||||
|
"response_types": ["code"],
|
||||||
|
})
|
||||||
|
assert registration.status_code == 201, registration.text
|
||||||
|
client_id = registration.json()["client_id"]
|
||||||
|
client_secret = registration.json()["client_secret"]
|
||||||
|
auth = client.get("/authorize", params={
|
||||||
|
"response_type": "code", "client_id": client_id,
|
||||||
|
"redirect_uri": "http://localhost:9876/callback",
|
||||||
|
"code_challenge": challenge, "code_challenge_method": "S256",
|
||||||
|
"scope": "files:read account:read stove:estimate", "resource": "https://testserver/mcp", "state": "xyz",
|
||||||
|
}, follow_redirects=False)
|
||||||
|
assert auth.status_code == 302, auth.text
|
||||||
|
ticket = parse_qs(urlparse(auth.headers["location"]).query)["ticket"][0]
|
||||||
|
callback = asyncio.run(provider.confirm(ticket, "alice@example.test", approved=True))
|
||||||
|
code = parse_qs(urlparse(callback).query)["code"][0]
|
||||||
|
token = client.post("/token", data={
|
||||||
|
"grant_type": "authorization_code", "client_id": client_id,
|
||||||
|
"client_secret": client_secret,
|
||||||
|
"code": code, "code_verifier": verifier,
|
||||||
|
"redirect_uri": "http://localhost:9876/callback",
|
||||||
|
"resource": "https://testserver/mcp",
|
||||||
|
})
|
||||||
|
assert token.status_code == 200, token.text
|
||||||
|
bearer = token.json()["access_token"]
|
||||||
|
call = client.post("/mcp", headers={
|
||||||
|
"Authorization": "Bearer " + bearer,
|
||||||
|
"MCP-Protocol-Version": "2025-11-25",
|
||||||
|
"Mcp-Method": "tools/call", "Mcp-Name": "list_files",
|
||||||
|
"Accept": "application/json, text/event-stream",
|
||||||
|
}, json={"jsonrpc": "2.0", "id": 2, "method": "tools/call",
|
||||||
|
"params": {"name": "list_files", "arguments": {}}})
|
||||||
|
assert call.status_code == 200, call.text
|
||||||
|
assert call.json()["result"]["isError"] is False
|
||||||
|
assert "files" in call.json()["result"]["content"][0]["text"]
|
||||||
|
foreign = client.post("/mcp", headers={
|
||||||
|
"Authorization": "Bearer " + bearer,
|
||||||
|
"MCP-Protocol-Version": "2025-11-25",
|
||||||
|
"Mcp-Method": "tools/call", "Mcp-Name": "list_files",
|
||||||
|
"Accept": "application/json, text/event-stream",
|
||||||
|
}, json={"jsonrpc": "2.0", "id": 3, "method": "tools/call",
|
||||||
|
"params": {"name": "list_files", "arguments": {"tab_id": "bob-tab"}}})
|
||||||
|
assert foreign.status_code == 200
|
||||||
|
assert foreign.json()["result"]["isError"] is True
|
||||||
|
limits = client.post("/mcp", headers={
|
||||||
|
"Authorization": "Bearer " + bearer,
|
||||||
|
"MCP-Protocol-Version": "2025-11-25",
|
||||||
|
"Mcp-Method": "tools/call", "Mcp-Name": "get_limits",
|
||||||
|
"Accept": "application/json, text/event-stream",
|
||||||
|
}, json={"jsonrpc": "2.0", "id": 4, "method": "tools/call",
|
||||||
|
"params": {"name": "get_limits", "arguments": {}}})
|
||||||
|
assert limits.status_code == 200, limits.text
|
||||||
|
assert limits.json()["result"]["isError"] is False, limits.text
|
||||||
|
stove = client.post("/mcp", headers={
|
||||||
|
"Authorization": "Bearer " + bearer,
|
||||||
|
"MCP-Protocol-Version": "2025-11-25",
|
||||||
|
"Mcp-Method": "tools/call", "Mcp-Name": "stove_estimate",
|
||||||
|
"Accept": "application/json, text/event-stream",
|
||||||
|
}, json={"jsonrpc": "2.0", "id": 5, "method": "tools/call",
|
||||||
|
"params": {"name": "stove_estimate", "arguments": {"stove": {}}}})
|
||||||
|
assert stove.status_code == 200, stove.text
|
||||||
|
payload = stove.json()["result"]
|
||||||
|
assert payload["isError"] is True, stove.text
|
||||||
|
assert json.loads(payload["content"][0]["text"])["error"] == "invalid_request"
|
||||||
|
replay = client.post("/token", data={
|
||||||
|
"grant_type": "authorization_code", "client_id": client_id,
|
||||||
|
"client_secret": client_secret,
|
||||||
|
"code": code, "code_verifier": verifier,
|
||||||
|
"redirect_uri": "http://localhost:9876/callback",
|
||||||
|
"resource": "https://testserver/mcp",
|
||||||
|
})
|
||||||
|
assert replay.status_code == 400
|
||||||
Reference in New Issue
Block a user