"""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 from stove_contract import StoveRequest _PARAM_DESCRIPTIONS = { "budget_rub": "Максимальный расход на проверку в рублях; задаётся пользователем после оценки стоимости.", "confirmed": "true после явного согласия пользователя с оценкой расхода.", "content_base64": "Байты файла в стандартной кодировке base64; файл не более 512 КБ.", "date": "Дата расчёта YYYY-MM-DD; null сбрасывает на текущую дату.", "filename": "Имя файла в собственной вкладке пользователя.", "items": "Список замечаний для оценки или запуска проверки.", "job_id": "Идентификатор задания, возвращённый chat_ask.", "limit": "Максимальное число последних сообщений; по умолчанию 100.", "message": "Текст вопроса для Инфосметы.", "review_id": "Идентификатор собственной проверки замечаний.", "stove": "Параметры печи по контракту StoveRequest; оценка ориентировочная.", "tab_id": "Идентификатор собственной вкладки; если не указан, используется вкладка MCP-клиента.", "ticket": "Одноразовый код из браузерного подтверждения prepare_clear_files.", "title": "Название диалога или проверки.", "tz": "Смещение локального времени от UTC в минутах; по умолчанию 0.", } _REVIEW_ITEM = {"type": "object", "description": "Одно замечание экспертизы и необязательная привязка к строке файла.", "properties": { "ord": {"type": "integer", "minimum": 1, "description": "Порядковый номер; по умолчанию позиция в списке."}, "text": {"type": "string", "minLength": 1, "maxLength": 10000, "description": "Текст замечания."}, "target_path": {"type": ["string", "null"], "description": "Файл результата, к которому относится замечание."}, "target_sheet": {"type": ["string", "null"], "description": "Лист файла результата."}, "target_row": {"type": ["integer", "null"], "minimum": 1, "description": "Строка файла результата."}, "target_path_before": {"type": ["string", "null"], "description": "Исходный файл до исправления."}, "target_sheet_before": {"type": ["string", "null"], "description": "Исходный лист до исправления."}, "target_row_before": {"type": ["integer", "null"], "minimum": 1, "description": "Исходная строка до исправления."}, }, "required": ["text"], "additionalProperties": False} def _stove_schema() -> dict: # The REST endpoint validates with this model. Convert pydantic-core's two # numeric keywords to standard JSON Schema so MCP clients can validate too. schema = StoveRequest.model_json_schema() def standardize(value): if isinstance(value, dict): return {("exclusiveMinimum" if key == "gt" else "maximum" if key == "le" else key): standardize(item) for key, item in value.items()} if isinstance(value, list): return [standardize(item) for item in value] return value schema = standardize(schema) stove_fields = schema["$defs"]["Stove"]["properties"] for field, description in { "kind": "Тип печи: отопительная, отопительно-варочная, кухонная, хлебная, банная или камин.", "bricks": "Число керамических и шамотных кирпичей.", "region": "Регион расчёта цен.", "zone": "Ценовая зона региона, если известна.", "mass_kg": "Масса печи в килограммах, если известна.", "bucket_volume_l": "Объём ведра в литрах для расхода материалов.", "materials": "Дополнительные материалы с количеством и единицей измерения.", "context": "Свободное пояснение к печи для подбора аналогов.", }.items(): stove_fields[field]["description"] = description for field, description in {"ceramic": "Количество керамических кирпичей.", "fireclay": "Количество шамотных кирпичей."}.items(): schema["$defs"]["Bricks"]["properties"][field]["description"] = description for field, description in {"name": "Наименование материала.", "qty": "Положительное количество.", "unit": "Единица измерения количества."}.items(): schema["$defs"]["MaterialLine"]["properties"][field]["description"] = description schema["properties"]["tab_id"] = {"type": "string", "maxLength": 128, "description": _PARAM_DESCRIPTIONS["tab_id"]} schema["properties"]["stove"]["description"] = _PARAM_DESCRIPTIONS["stove"] return schema def _schema(properties: dict, required: tuple[str, ...] = ()) -> dict: described = {key: {**value, "description": value.get("description", _PARAM_DESCRIPTIONS[key])} for key, value in properties.items()} return {"type": "object", "properties": described, "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_ITEM}}, ("items",))}, "review_create": {"scope": {"reviews:run"}, "description": "Создать проверку замечаний с явным потолком расходов.", "schema": _schema({"tab_id": {"type": "string", "maxLength": 128}, "items": {"type": "array", "minItems": 1, "maxItems": 1000, "items": _REVIEW_ITEM}, "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": _stove_schema()}, } 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