# -*- coding: utf-8 -*- """MCP 接入层(2026-10-15 上线;2026-10-27 主人重定义:**只读**)。 - 传输: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(开关开了也断) - 工具(2026-10-27 主人定,共 5 个,**全部只读,无任何增删改/导出**): ① bills_query 入库项目清单:编号/名称/项目特征/单价 ② lme_prices 工料机单价 ③ market_info_prices 市场价/信息价数据 ④ recent_review_query 工作台最近审核(口径同 ①②) ⑤ attachment_download 下载绑定附件——**仅在用户明确要求附件时调用**;查询响应一律 不含附件信息;id 必须来自 ①~④ 的查询结果;三类:bill / lme(行绑定)+ batch (价格批次原件);不支持枚举、不支持全量下载 - 零新增依赖:JSON-RPC 手写,只依赖标准库 """ import base64 import json import os import secrets PROTO_VERSION = "2025-06-18" _API = None # api_server 模块(bind 注入,避免循环导入) ATT_MAX_DL = 20 * 1024 * 1024 # 单附件下载上限:超过请走软件界面下载 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))} # ---------------------------------------------------------------- 工具实现(只读) def _hist(fn): """历史库只读查询(入库项目 / 市场价信息价 / 附件绑定)。""" a = _api() con = a.conn() try: return fn(con) finally: con.close() def _sess(fn): """会话库只读查询(工作台最近审核)。""" a = _api() sc = a.sess.connect() try: return fn(sc) finally: sc.close() def _paging(args): """limit 归一:默认 50,1~200。""" try: return min(max(int(args.get("limit") or 50), 1), 200) except (TypeError, ValueError): return 50 def _need_scope(args): """查询范围守卫:keyword 或 batch_id 至少给一个(防空量拖库)。""" kw = (args.get("keyword") or "").strip() try: bid = int(args.get("batch_id") or 0) except (TypeError, ValueError): bid = 0 return kw, bid def _rows(con, sql, params): cur = con.execute(sql, params) cols = [d[0] for d in cur.description] return [dict(zip(cols, r)) for r in cur.fetchall()] def _t_bills_query(args): """① 入库项目清单:Number(编号)/Name(名称)/Attr(项目特征)/Price(单价)。""" kw, bid = _need_scope(args) if not kw and not bid: return {"ok": False, "msg": "请给 keyword(清单编号/名称关键词)或 batch_id 之一"} lim = _paging(args) sql = ("SELECT b.id, b.batch_id, t.Name AS batch_name, b.Number, b.Name, b.Attr, b.Price " "FROM bills b JOIN batches t ON t.id = b.batch_id " "WHERE t.kind='project'") params = [] if bid: sql += " AND b.batch_id=?" params.append(bid) if kw: sql += " AND (b.Number LIKE ? OR b.Name LIKE ?)" params += ["%%%s%%" % kw, "%%%s%%" % kw] sql += " ORDER BY b.batch_id, b.x_seq LIMIT ?" params.append(lim) rows = _hist(lambda con: _rows(con, sql, params)) return {"ok": True, "total": len(rows), "rows": rows} def _t_lme_prices(args): """② 工料机单价:NoTaxPrice(除税)/TaxRate(税率)/TaxPrice(含税)。""" kw, bid = _need_scope(args) if not kw and not bid: return {"ok": False, "msg": "请给 keyword(工料机编号/名称/规格关键词)或 batch_id 之一"} lim = _paging(args) sql = ("SELECT l.id, l.batch_id, t.Name AS batch_name, l.Number, l.Name, " "l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice " "FROM lmes l JOIN batches t ON t.id = l.batch_id " "WHERE t.kind='project'") params = [] if bid: sql += " AND l.batch_id=?" params.append(bid) if kw: sql += " AND (l.Number LIKE ? OR l.Name LIKE ? OR l.Specification LIKE ?)" params += ["%%%s%%" % kw] * 3 sql += " ORDER BY l.batch_id, l.id LIMIT ?" params.append(lim) rows = _hist(lambda con: _rows(con, sql, params)) return {"ok": True, "total": len(rows), "rows": rows} def _t_market_info_prices(args): """③ 市场价/信息价数据(价格批次明细)。""" kw, bid = _need_scope(args) if not kw and not bid: return {"ok": False, "msg": "请给 keyword(编号/名称关键词)或 batch_id(价格批次 id)之一"} lim = _paging(args) sql = ("SELECT p.id, p.batch_id, t.Name AS batch_name, t.x_publisher, p.Code, p.Name, " "p.Specification, p.Unit, p.NoTaxPrice, p.TaxRate, p.TaxPrice, p.Class " "FROM prices p JOIN batches t ON t.id = p.batch_id " "WHERE t.kind IN ('info', 'market')") params = [] if bid: sql += " AND p.batch_id=?" params.append(bid) if kw: sql += " AND (p.Code LIKE ? OR p.Name LIKE ?)" params += ["%%%s%%" % kw, "%%%s%%" % kw] sql += " ORDER BY p.batch_id, p.id LIMIT ?" params.append(lim) rows = _hist(lambda con: _rows(con, sql, params)) return {"ok": True, "total": len(rows), "rows": rows} def _t_recent_review_query(args): """④ 工作台最近审核:不带 session_id → 最近会话列表;带 session_id+type → 行数据 (type=bills 口径同 ①,type=lmes 口径同 ②)。""" try: sid = int(args.get("session_id") or 0) except (TypeError, ValueError): sid = 0 typ = (args.get("type") or "").strip().lower() kw = (args.get("keyword") or "").strip() lim = _paging(args) if not sid: rows = _sess(lambda sc: _rows( sc, "SELECT id, name, period_from, period_to, imported_at, x_total " "FROM sessions ORDER BY imported_at DESC LIMIT ?", (lim,))) return {"ok": True, "total": len(rows), "rows": rows, "hint": "带 session_id + type(bills/lmes)查行数据"} if typ not in ("bills", "lmes"): return {"ok": False, "msg": "type 必须是 bills 或 lmes(不带 type 时返回会话列表)"} if typ == "bills": sql = ("SELECT id, Number, Name, Attr, Price, Unit, Quantity " "FROM s_bills WHERE session_id=?") else: sql = ("SELECT id, Number, Name, Specification, Unit, NoTaxPrice, TaxRate, TaxPrice " "FROM s_lmes WHERE session_id=?") params = [sid] if kw: if typ == "bills": sql += " AND (Number LIKE ? OR Name LIKE ?)" else: sql += " AND (Number LIKE ? OR Name LIKE ? OR Specification LIKE ?)" params += ["%%%s%%" % kw] * (2 if typ == "bills" else 3) sql += " ORDER BY id LIMIT ?" params.append(lim) rows = _sess(lambda sc: _rows(sc, sql, params)) return {"ok": True, "total": len(rows), "rows": rows} def _t_attachment_download(args): """⑤ 下载绑定附件(仅响应明确指令;id 必须来自 ①~④ 查询结果)。 type=bill/lme → 该行绑定的询价附件(bill_attach / lme_attach); type=batch → 价格批次原件(batches.x_attach_sha)。""" a = _api() typ = (args.get("type") or "").strip().lower() try: rid = int(args.get("id") or 0) except (TypeError, ValueError): rid = 0 if typ not in ("bill", "lme", "batch") or not rid: return {"ok": False, "msg": "参数:type=bill|lme|batch + id(来自查询结果的行/批次 id)"} def load(con): if typ == "bill": return _rows(con, "SELECT f.original_name, f.stored_path, f.size, f.sha256 " "FROM bill_attach a JOIN inquiry_files f ON f.id=a.file_id " "WHERE a.bill_id=?", (rid,)), a.INQ_DIR if typ == "lme": return _rows(con, "SELECT f.original_name, f.stored_path, f.size, f.sha256 " "FROM lme_attach a JOIN inquiry_files f ON f.id=a.file_id " "WHERE a.lme_id=?", (rid,)), a.INQ_DIR return _rows(con, "SELECT at.original_name, at.stored_path, at.size, at.sha256 " "FROM attachments at WHERE at.sha256=" "(SELECT x_attach_sha FROM batches WHERE id=?)", (rid,)), a.ATTACH_DIR files, root = _hist(load) if not files: return {"ok": False, "msg": "没有绑定附件(或 id 不存在)"} out = [] for f in files: fp = os.path.realpath(os.path.join(a.DATA_DIR, f["stored_path"] or "")) if os.path.commonpath([fp, os.path.realpath(root)]) != os.path.realpath(root): return {"ok": False, "msg": "附件路径不合法,拒绝读取"} try: with open(fp, "rb") as fh: raw = fh.read() except OSError as e: return {"ok": False, "msg": "附件读取失败:%s" % e} if len(raw) > ATT_MAX_DL: return {"ok": False, "msg": "《%s》超过 %d MB 下载上限,请在软件界面下载" % ((f["original_name"] or "")[:40], ATT_MAX_DL // 1024 // 1024)} out.append({"name": f["original_name"], "size": f["size"], "sha256": f["sha256"], "content_base64": base64.b64encode(raw).decode("ascii")}) return {"ok": True, "files": out} # ---------------------------------------------------------------- 工具清单 def TOOLS(): return [ {"name": "bills_query", "description": "查入库项目的清单:编号 Number、名称 Name、项目特征 Attr、单价 Price。" "keyword(编号/名称关键词)或 batch_id 至少给一个;limit 默认 50 上限 200。" "响应不含附件信息。", "inputSchema": {"type": "object", "properties": { "keyword": {"type": "string"}, "batch_id": {"type": "integer"}, "limit": {"type": "integer"}}, "required": []}, "run": _t_bills_query}, {"name": "lme_prices", "description": "查入库项目的工料机单价:编号、名称、规格、单位、除税价 NoTaxPrice、" "税率 TaxRate、含税价 TaxPrice。keyword 或 batch_id 至少一个。响应不含附件信息。", "inputSchema": {"type": "object", "properties": { "keyword": {"type": "string"}, "batch_id": {"type": "integer"}, "limit": {"type": "integer"}}, "required": []}, "run": _t_lme_prices}, {"name": "market_info_prices", "description": "读市场价/信息价批次明细:Code、Name、Specification、Unit、三价、Class。" "keyword(编号/名称)或 batch_id(价格批次 id)至少一个。", "inputSchema": {"type": "object", "properties": { "keyword": {"type": "string"}, "batch_id": {"type": "integer"}, "limit": {"type": "integer"}}, "required": []}, "run": _t_market_info_prices}, {"name": "recent_review_query", "description": "读工作台最近审核:不带参数=最近会话列表;session_id + type(bills=清单" "编号/名称/项目特征/单价,lmes=工料机单价)查该会话行数据,口径与" "bills_query / lme_prices 一致。可选 keyword 过滤。", "inputSchema": {"type": "object", "properties": { "session_id": {"type": "integer"}, "type": {"type": "string"}, "keyword": {"type": "string"}, "limit": {"type": "integer"}}, "required": []}, "run": _t_recent_review_query}, {"name": "attachment_download", "description": "下载绑定附件。**仅在用户明确要求下载附件时调用**(查询结果不含附件信息," "不得主动调用)。id 必须来自查询结果:type=bill/lme 用 bills_query/" "lme_prices/recent_review_query 返回的行 id;type=batch 用价格批次 id" "(批次原件)。不支持枚举或全量下载。", "inputSchema": {"type": "object", "properties": { "type": {"type": "string"}, "id": {"type": "integer"}}, "required": ["type", "id"]}, "run": _t_attachment_download}, ] # ---------------------------------------------------------------- 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-2.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]