mcp.py 5.79 KB
"""MCP 接口(JSON-RPC over HTTP,Streamable HTTP 的最小实现):让外部 Agent 安全地使用本体能力。

暴露的工具:
- 所有只读函数(名称里的 `.` 换成 `_`,如 metric_query)
- ask:统一提问(非流式)
- propose_action:提议一个动作 —— 和界面上一样只进审批队列,**外部 Agent 也不能直接执行动作**

鉴权:`Authorization: Bearer <MCP_TOKEN>`(设置页配置,留空即关闭);
身份:`X-User-Id` 指定代表哪个用户(数据范围、审计都按他),缺省为 viewer。
"""
from __future__ import annotations

import json
import logging

from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import JSONResponse

from ..core import db as core_db
from ..core import identity
from ..governance import audit
from . import actions, registry

log = logging.getLogger(__name__)
router = APIRouter(tags=["mcp"])
PROTOCOL = "2025-06-18"


def _tools() -> list[dict]:
    out = [{"name": f.name.replace(".", "_"), "description": f"{f.title}:{f.description}",
            "inputSchema": {"type": "object", "properties": f.input_schema.get("properties") or {},
                            "required": f.input_schema.get("required") or []}}
           for f in registry.FUNCTIONS.values()]
    out.append({"name": "ask", "description": "统一提问:自动选择取数、检索、查流程,返回带引用的答案",
                "inputSchema": {"type": "object", "properties": {"question": {"type": "string"}},
                                "required": ["question"]}})
    out.append({"name": "propose_action",
                "description": "提议一个业务动作。动作不会立即执行,而是进入人工审批队列,返回审批单。",
                "inputSchema": {"type": "object", "properties": {
                    "action": {"type": "string"}, "params": {"type": "object"},
                    "object_key": {"type": "string"}, "reason": {"type": "string"}},
                    "required": ["action", "reason"]}})
    return out


def _call(name: str, args: dict) -> dict:
    if name == "ask":
        from ..orchestrator import runner
        out = runner.run_collect(str(args.get("question") or ""))
        return {"answer": out.get("answer"), "citations": out.get("citations"),
                "data_refs": [{k: v for k, v in d.items() if k != "rows"} for d in out.get("data_refs") or []],
                "suggested_actions": out.get("actions")}
    if name == "propose_action":
        actor = identity.current()
        tok = identity.set_current(identity.as_ai(actor))
        try:
            return actions.propose(str(args["action"]), args.get("params") or {},
                                   object_key=str(args.get("object_key") or ""),
                                   reason=f"[MCP] {args.get('reason', '')}", initiator_kind="ai",
                                   source_ref="mcp")
        finally:
            identity.reset(tok)
    fname = name.replace("_", ".", 1)
    return registry.call_function(fname, args)


def _rpc_result(rid, result) -> dict:
    return {"jsonrpc": "2.0", "id": rid, "result": result}


def _rpc_error(rid, code: int, msg: str) -> dict:
    return {"jsonrpc": "2.0", "id": rid, "error": {"code": code, "message": msg}}


@router.post("/mcp")
async def mcp(request: Request):
    token = core_db.get_config("MCP_TOKEN", "")
    # 直接返回响应而不是抛 HTTPException:非 /api 路径的 404 会被 SPA 兜底改写成首页
    if not token:
        return JSONResponse({"detail": "MCP 未开启(在设置页配置 MCP_TOKEN)"}, status_code=404)
    if request.headers.get("authorization", "") != f"Bearer {token}":
        return JSONResponse({"detail": "MCP 令牌无效"}, status_code=401)
    uid = request.headers.get("x-user-id", "").strip()
    from ..governance import users
    actor = users.load_actor(uid or "viewer", request.headers.get("x-workspace", "") or "default")
    identity.set_current(actor)
    try:
        msg = await request.json()
    except json.JSONDecodeError:
        return JSONResponse(_rpc_error(None, -32700, "parse error"))
    rid, method, params = msg.get("id"), msg.get("method", ""), msg.get("params") or {}
    if method == "initialize":
        return JSONResponse(_rpc_result(rid, {
            "protocolVersion": PROTOCOL, "capabilities": {"tools": {"listChanged": False}},
            "serverInfo": {"name": "onto-kernel", "version": "3.0.0"}}))
    if method.startswith("notifications/"):
        return JSONResponse({}, status_code=202)
    if method == "ping":
        return JSONResponse(_rpc_result(rid, {}))
    if method == "tools/list":
        return JSONResponse(_rpc_result(rid, {"tools": _tools()}))
    if method == "tools/call":
        name, args = params.get("name", ""), params.get("arguments") or {}
        if not actor.can("ask"):
            return JSONResponse(_rpc_result(rid, {"isError": True, "content": [
                {"type": "text", "text": "该用户没有提问权限"}]}))
        try:
            import asyncio
            out = await asyncio.to_thread(_ctx_call, actor, name, args)
            audit.record("mcp.call", "mcp", name, f"MCP 调用 {name}", after={"args": args}, actor=actor)
            return JSONResponse(_rpc_result(rid, {"content": [
                {"type": "text", "text": json.dumps(out, ensure_ascii=False, default=str)[:60000]}]}))
        except HTTPException as e:
            return JSONResponse(_rpc_result(rid, {"isError": True,
                                                  "content": [{"type": "text", "text": str(e.detail)}]}))
    return JSONResponse(_rpc_error(rid, -32601, f"method not found: {method}"))


def _ctx_call(actor: identity.Actor, name: str, args: dict) -> dict:
    tok = identity.set_current(actor)
    try:
        return _call(name, args)
    finally:
        identity.reset(tok)