"""Инструменты по HTTP (T3): JSON-RPC 2.0 поверх пропуска устройства. Отдаём только замороженный перечень плана (§1.6) — инструменты, которым не нужна серверная рабочая папка. Файловые инструменты по HTTP закрыты: файлов человека на сервере нет, и вызов упирался бы в несуществующий путь. Права проверяются на каждом вызове; неизвестный или запрещённый инструмент — ошибка JSON-RPC, а не 500. """ from __future__ import annotations import asyncio import os import threading from fastapi import HTTPException, Request from fastapi.responses import JSONResponse ALLOWED_TOOLS = ( "find_in_real_estimates", "find_ka_price", "build_ka_form", "find_in_vor", "find_expertise_remarks", "find_recalc_index", "find_direct_costs_index", "find_resource_price", "find_salary", "calc_rim_rate", "find_ksr", "find_gesn_composition", "find_base_price", "calc_estimate", "show_estimate", ) PROTOCOL_VERSION = "2025-06-18" # Инструменты пишут панель сметы в файл рабочей папки, а путь берётся из SMETA_USER и # SMETA_TAB. По HTTP их выставляем на время вызова и сериализуем вызовы: иначе два # человека писали бы одну и ту же панель, и оба видели бы чужое. _call_lock = threading.Lock() def _error(req_id, code: int, message: str, status: int = 200) -> JSONResponse: return JSONResponse(status_code=status, content={"jsonrpc": "2.0", "id": req_id, "error": {"code": code, "message": message}}) def _result(req_id, result: dict) -> dict: return {"jsonrpc": "2.0", "id": req_id, "result": result} def _serialize(value): """Результат инструмента → JSON-совместимое. Всё, что не сводится, — строкой: ответ инструмента важнее его формы.""" import json try: json.dumps(value, ensure_ascii=False) return value except (TypeError, ValueError): return json.loads(json.dumps(value, ensure_ascii=False, default=str)) async def handle(request: Request): import device_auth device = await asyncio.to_thread(device_auth.require_device, request) import db user = await asyncio.to_thread(db.get_user_by_email, device["username"]) if not user or user.get("blocked") or user.get("deleted_at") or user.get("read_only"): raise HTTPException(403, "Учётная запись не может пользоваться программой") try: body = await request.json() except Exception: # noqa: BLE001 raise HTTPException(400, "Тело JSON-RPC не разобралось") if not isinstance(body, dict): return _error(None, -32600, "JSON-RPC: ожидается объект") raw_id = body.get("id") req_id = raw_id if isinstance(raw_id, (str, int)) and not isinstance(raw_id, bool) else None method = body.get("method") if "id" not in body: # Уведомление JSON-RPC 2.0: ответ по спецификации не отправляется вовсе. from fastapi.responses import Response return Response(status_code=204) if body.get("jsonrpc") not in (None, "2.0"): return _error(req_id, -32600, "Нужна версия JSON-RPC 2.0") params = body.get("params") or {} if not isinstance(params, dict): return _error(req_id, -32602, "params: ожидается объект") import smeta_mcp if method == "initialize": return _result(req_id, { "protocolVersion": PROTOCOL_VERSION, "capabilities": {"tools": {"listChanged": False}}, "serverInfo": {"name": "smeta-web", "version": "1.0"}, }) if method == "tools/list": tools = [] for name in ALLOWED_TOOLS: entry = smeta_mcp.TOOLS.get(name) if entry is None: continue tools.append({"name": name, "description": entry.get("description") or "", "inputSchema": entry.get("inputSchema") or {"type": "object", "properties": {}}}) return _result(req_id, {"tools": tools}) if method == "tools/call": name = params.get("name") or "" if name not in ALLOWED_TOOLS or name not in smeta_mcp.TOOLS: return _error(req_id, -32601, f"Инструмент {name!r} по HTTP не разрешён") entry = smeta_mcp.TOOLS[name] args = params.get("arguments") or {} if not isinstance(args, dict): return _error(req_id, -32602, "arguments: ожидается объект") def _call_with_identity(): with _call_lock: old_user = os.environ.get("SMETA_USER") old_tab = os.environ.get("SMETA_TAB") os.environ["SMETA_USER"] = device["username"] os.environ["SMETA_TAB"] = device.get("tab_id") or "default" try: return entry["fn"](**args) finally: for key, old in (("SMETA_USER", old_user), ("SMETA_TAB", old_tab)): if old is None: os.environ.pop(key, None) else: os.environ[key] = old try: value = await asyncio.to_thread(_call_with_identity) except TypeError as e: return _error(req_id, -32602, f"Аргументы не подошли: {e}") except Exception as e: # noqa: BLE001 — инструмент упал: понятная ошибка, не 500 return _error(req_id, -32603, f"Инструмент не выполнился: {type(e).__name__}") return JSONResponse(status_code=200, content=_result(req_id, {"content": [ {"type": "text", "text": __import__("json").dumps( _serialize(value), ensure_ascii=False)}], "isError": False})) return _error(req_id, -32601, f"Метод {method!r} не поддерживается")