Files
smeta-web/external_mcp.py

227 lines
10 KiB
Python

"""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
from starlette.responses import Response
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 _tool_result(value: Any) -> CallToolResult:
if isinstance(value, Response):
try:
parsed = json.loads(value.body)
except (AttributeError, TypeError, ValueError):
parsed = None
if value.status_code >= 400:
value = ({**parsed, "error": parsed.get("code") or parsed.get("error") or "upstream_error",
"status": value.status_code} if isinstance(parsed, dict)
else {"error": "upstream_error", "status": value.status_code,
"detail": "Downstream service failed"})
elif parsed is not None:
value = parsed
else:
raise ValueError("Tool returned a non-JSON HTTP response")
payload = json.dumps(value, ensure_ascii=False, default=str)
if len(payload) > 1_000_000:
raise ValueError("Tool result is too large; narrow the request")
is_error = isinstance(value, dict) and "error" in value
normalized = json.loads(payload)
structured = (normalized if isinstance(normalized, dict) else {"items": normalized}
if isinstance(normalized, list) else {"value": normalized})
return CallToolResult(content=[TextContent(type="text", text=payload)],
structuredContent=structured, isError=is_error)
def _error_result(code: str, detail: str) -> CallToolResult:
return _tool_result({"error": code, "detail": detail})
_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,
"description": "Собственная вкладка; если не указана, используется вкладка MCP-клиента."}}
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)
return _tool_result(result)
def create_mcp_app(provider: InfosmetaOAuthProvider, *, allowed_hosts: list[str]):
return InfosmetaMCP(provider, allowed_hosts=allowed_hosts).streamable_http_app()