# -*- coding: utf-8 -*- """MCP 接入层(2026-10-15):把产品功能以 MCP 工具暴露给 AI harness(ZCode / WorkBuddy / DeepSeek 等一切支持 MCP 或会发 HTTP 的 agent)。 - 传输:Streamable HTTP(POST /mcp,JSON-RPC 2.0,单响应 JSON;无 SSE/无会话态,stateless) - 开关:全局设置 mcp_enabled(**默认关**——断开就是连不上,403);令牌 mcp_token (首次开启自动生成,调用必须带 Authorization: Bearer <令牌>,/api/mcp/status 可查) - 收费挂钩:license enforce 时未激活/过期 → 整个端点 403 LICENSE_REQUIRED(开关开了也断) - 工具:全部复用 api_* 处理器(与界面同一套业务、写锁、分组缓存失效),**不另开第二通道** - 零新增依赖:JSON-RPC 手写,只依赖标准库 Agent 注意(与 /api/schema 的 notes 一致):id 随重开变化;采纳 新行=覆盖/已有行=追加; 工程量等数值一律字符串;导出前自动校验源文件哈希。 """ import io import json import os import re import secrets import threading import zipfile PROTO_VERSION = "2025-06-18" _API = None # api_server 模块(bind 注入,避免循环导入) def bind(api_module): global _API _API = api_module def _api(): if _API is None: raise RuntimeError("mcp_server 未 bind") return _API # ---------------------------------------------------------------- 开关 / 令牌 / 门禁 def enabled(): a = _api() return (a._setting_get("global", "mcp_enabled") or "") == "1" def token(): a = _api() return a._setting_get("global", "mcp_token") or "" def set_enabled(on): """开关(持久化,重启保持)。打开时没有令牌就生成一个。返回 (enabled, token)。""" a = _api() tok = token() if on and not tok: tok = secrets.token_hex(16) a._setting_set("global", "mcp_token", tok) a._setting_set("global", "mcp_enabled", "1" if on else "0") return on, tok def status(): a = _api() return {"enabled": enabled(), "token": token(), "tools": len(TOOLS()), "endpoint": "/mcp", "port": a.PORT, "license_enforced": bool(a.license_gate._cfg.get("enforce", True))} # ---------------------------------------------------------------- 工具实现(复用 api_*) def _read(fn): """只读工具:开只读连接跑 api_* 函数。""" a = _api() sc = a.sess.connect() try: return fn(sc) finally: sc.close() def _write(fn): """写工具:写锁 + 提交/回滚 + 分组缓存失效(与各路由分支同款守护)。""" a = _api() with a.WRITE_LOCK: sc = a.sess.connect() try: r = fn(sc) sc.commit() _sid = (r.get("sid") or 0) if isinstance(r, dict) else 0 if isinstance(r, dict) and r.get("ok") and _sid: a._grp_cache_drop("session", int(_sid)) return r except Exception as e: try: sc.rollback() except Exception: pass return {"ok": False, "msg": "操作失败:%s" % e} finally: sc.close() def _t_sessions_list(args): return _api().api_sessions() def _t_project_open(args): return _api().api_audit(args) def _t_session_delete(args): return _api().api_session_delete(args) def _t_admin_import(args): a = _api() con = a.conn() try: return a.api_admin_import(con, args) finally: con.close() def _t_tree(args): return _api().api_raw_tree(args) def _t_uw_detail(args): return _api().api_raw_uw(args) def _t_session_rows(args): return _api().api_session_rows(args) def _t_bill_op(args): return _write(lambda sc: _api().api_bill_op(sc, args)) def _t_norm_op(args): return _write(lambda sc: _api().api_norm_op(sc, args)) def _t_bill_adopt(args): a = _api() def run(sc): hc = a.conn() try: return a.api_bill_adopt(sc, hc, args) finally: hc.close() return _write(run) def _t_bill_unadopt(args): a = _api() def run(sc): hc = a.conn() try: return a.api_bill_unadopt(sc, hc, args) finally: hc.close() return _write(run) def _t_lme_merge_groups(args): return _read(lambda sc: _api()._lme_merge_groups(sc, int(args.get("session_id", 0)))) def _t_lme_merge(args): return _write(lambda sc: _api().api_lme_merge(sc, args)) def _t_session_remark(args): a = _api() def run(sc): if args.get("lme_id"): a.sess.save_lme_remark(sc, int(args.get("lme_id", 0)), args.get("remark", "")) else: a.sess.save_remark(sc, int(args.get("bill_id", 0)), args.get("remark", "")) return {"ok": True} return _write(run) def _t_schema(args): return _api().api_schema() def _t_batch_tree(args): return _api().api_admin_raw_tree(args) def _t_batch_uw(args): return _api().api_admin_raw_uw(args) def _t_session_export(args): """导出 → 落盘 data/exports/,回文件路径(Agent 在本机直接可读)。""" a = _api() sc = a.sess.connect() try: raw, out_name, err = a._export_session(sc, int(args.get("session_id", 0) or 0)) finally: sc.close() if err: return {"ok": False, "msg": err} out_dir = os.path.join(a.DATA_DIR, "exports") os.makedirs(out_dir, exist_ok=True) fp = os.path.join(out_dir, "%d_%s" % (int(time.time()), out_name)) with open(fp, "wb") as f: f.write(raw) return {"ok": True, "path": fp, "bytes": len(raw), "name": out_name} # ---------------------------------------------------------------- 工具清单 def _schema(paths, *names): """从 /api/schema 事实源里摘路由描述(保证工具描述与接口同源)。""" try: s = _api().api_schema() out = [] for g in s["groups"].values(): for x in g: if x["path"] in paths: out.append(x) return out except Exception: return [] def TOOLS(): a = _api() return [ {"name": "sessions_list", "description": "会话台账(已有审核工程列表)", "inputSchema": {"type": "object", "properties": {}}, "run": _t_sessions_list}, {"name": "project_open", "description": "打开工程→解析→建/续会话(同名=原地续用)。" "path 必须是软件目录内的文件(先 upload_file)", "inputSchema": {"type": "object", "properties": {k: {"type": "string"} for k in ("path", "name", "province", "city", "district", "period_from", "period_to", "file_kind")}, "required": ["path", "name", "period_from"]}, "run": _t_project_open}, {"name": "session_delete", "description": "删会话(连同无引用的源文件副本)", "inputSchema": {"type": "object", "properties": {"ids": {"type": "array", "items": {"type": "integer"}}}, "required": ["ids"]}, "run": _t_session_delete}, {"name": "upload_file", "description": "上传本机文件进软件(base64 内容),返回软件内 path", "inputSchema": {"type": "object", "properties": {"name": {"type": "string"}, "content_base64": {"type": "string"}}, "required": ["name", "content_base64"]}, "run": lambda args: _api().api_upload(args)}, {"name": "admin_import", "description": "导入后台批次(=采纳源库)", "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}, "name": {"type": "string"}, "kind": {"type": "string"}, "force": {"type": "boolean"}}, "required": ["path", "name"]}, "run": _t_admin_import}, {"name": "session_tree", "description": "会话单位工程树", "inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"}}, "required": ["session_id"]}, "run": _t_tree}, {"name": "uw_detail", "description": "单位工程内清单树(含定额/工料机)", "inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"}, "uw_id": {"type": "string"}, "tab": {"type": "string"}}, "required": ["session_id", "uw_id"]}, "run": _t_uw_detail}, {"name": "session_rows", "description": "清单/工料机行数据", "inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"}, "type": {"type": "string"}}, "required": ["session_id", "type"]}, "run": _t_session_rows}, {"name": "bill_op", "description": "清单增删改:insert_above/insert_below/del/tdel/untdel/edit", "inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"}, "op": {"type": "string"}, "bill_id": {"type": "integer"}, "fields": {"type": "object"}}, "required": ["op", "bill_id"]}, "run": _t_bill_op}, {"name": "norm_op", "description": "定额增删改:ntdel/unntdel/unadopt(取消采纳)或 fields 行内编辑", "inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"}, "op": {"type": "string"}, "norm_id": {"type": "integer"}, "fields": {"type": "object"}}}, "run": _t_norm_op}, {"name": "bill_adopt", "description": "采纳(新行=覆盖,已有行=追加,原定额转临删)", "inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"}, "bill_id": {"type": "integer"}, "src_bill_id": {"type": "integer"}}, "required": ["session_id", "bill_id", "src_bill_id"]}, "run": _t_bill_adopt}, {"name": "bill_unadopt", "description": "清单级取消采纳", "inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"}, "bill_id": {"type": "integer"}}, "required": ["session_id", "bill_id"]}, "run": _t_bill_unadopt}, {"name": "lme_merge_groups", "description": "工料机合并分组(同名/近似)", "inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"}}, "required": ["session_id"]}, "run": _t_lme_merge_groups}, {"name": "lme_merge", "description": "合并改价+隐藏", "inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"}, "groups": {"type": "array"}}, "required": ["session_id", "groups"]}, "run": _t_lme_merge}, {"name": "session_remark", "description": "清单审核备注(持久化)", "inputSchema": {"type": "object", "properties": {"bill_id": {"type": "integer"}, "remark": {"type": "string"}}, "required": ["bill_id", "remark"]}, "run": _t_session_remark}, {"name": "session_export", "description": "导出审核版(zip 落盘 data/exports/,返回本机路径)", "inputSchema": {"type": "object", "properties": {"session_id": {"type": "integer"}}, "required": ["session_id"]}, "run": _t_session_export}, {"name": "api_schema", "description": "产品全部接口清单(工具未覆盖的功能用它走 HTTP)", "inputSchema": {"type": "object", "properties": {}}, "run": _t_schema}, ] # ---------------------------------------------------------------- JSON-RPC 分发 def _rpc_error(cid, code, message, data=None): e = {"code": code, "message": message} if data is not None: e["data"] = data return {"jsonrpc": "2.0", "id": cid, "error": e} def _rpc_result(cid, result): return {"jsonrpc": "2.0", "id": cid, "result": result} def _dispatch(msg): """单条 JSON-RPC → (is_notification, response_obj)。""" method = msg.get("method", "") cid = msg.get("id") if method == "initialize": return False, _rpc_result(cid, { "protocolVersion": PROTO_VERSION, "capabilities": {"tools": {"listChanged": False}}, "serverInfo": {"name": "造价审核", "version": "mcp-1.0"}}) if method == "ping": return False, _rpc_result(cid, {}) if method == "tools/list": tools = [{"name": t["name"], "description": t["description"], "inputSchema": t["inputSchema"]} for t in TOOLS()] return False, _rpc_result(cid, {"tools": tools}) if method == "tools/call": params = msg.get("params") or {} name = params.get("name", "") args = params.get("arguments") or {} for t in TOOLS(): if t["name"] == name: try: out = t["run"](args) text = json.dumps(out, ensure_ascii=False, default=str) return False, _rpc_result(cid, {"content": [{"type": "text", "text": text}], "isError": bool(out.get("ok") is False)}) except Exception as e: return False, _rpc_result(cid, { "content": [{"type": "text", "text": "工具执行异常:%s" % e}], "isError": True}) return False, _rpc_error(cid, -32602, "未知工具:%s" % name) if cid is None: return True, None # 未知通知:忽略 return False, _rpc_error(cid, -32601, "未知方法:%s" % method) def handle_post(auth_header, body_text): """POST /mcp 入口。返回 (HTTP 状态码, 响应对象或 None[202])。 三道闸顺序:开关 → 令牌 → 授权(收费挂钩:enforce 时未激活/过期整端点断)。""" a = _api() if not enabled(): return 403, {"jsonrpc": "2.0", "id": None, "error": {"code": -32001, "message": "MCP 未开启:请在软件「设置 → MCP 接入」打开开关", "data": {"switch_api": "/api/admin/mcp"}}} tok = token() given = (auth_header or "").strip() if given.lower().startswith("bearer "): given = given[7:].strip() if not tok or not given or not secrets.compare_digest(given, tok): return 401, {"jsonrpc": "2.0", "id": None, "error": {"code": -32002, "message": "令牌缺失或不正确(Authorization: Bearer <令牌>;" "令牌见软件「设置 → MCP 接入」或 /api/mcp/status)"}} ok, reason = a.license_gate.can_run_now() if not ok: return 403, {"jsonrpc": "2.0", "id": None, "error": {"code": -32003, "message": "授权不可用:%s" % reason, "data": {"code": "LICENSE_REQUIRED"}}} try: payload = json.loads(body_text or "null") except Exception: return 400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "JSON 解析失败"}} msgs = payload if isinstance(payload, list) else [payload] if not msgs: return 400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "空请求"}} outs, has_call = [], False for m in msgs: if not isinstance(m, dict): outs.append(_rpc_error(None, -32600, "请求必须是对象")) has_call = True continue is_note, resp = _dispatch(m) if not is_note: outs.append(resp) has_call = True if not has_call: return 202, None # 纯通知:202 空体 if isinstance(payload, list): return 200, outs return 200, outs[0]