# -*- 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-29 决策 238/239 起 9 个;①~⑤⑧ 只读,⑥⑦⑨ 写入为**主人拍板新增**, 取代 2026-10-27「只读、无任何增删改」旧口径): ① bills_query 入库项目清单:编号/名称/项目特征/单价 ② lme_prices 工料机单价 ③ market_info_prices 市场价/信息价数据 ④ recent_review_query 工作台最近审核(口径同 ①②) ⑤ attachment_download 下载绑定附件——**仅在用户明确要求附件时调用**;查询响应一律 不含附件信息;id 必须来自 ①~④ 的查询结果;三类:bill / lme(行绑定)+ batch (价格批次原件);不支持枚举、不支持全量下载 ⑥ project_import 整项目导入(写入):整项目模板 xlsx(项目目录+多对 Sheet)→ 建手工工程 ⑦ bill_adopt 清单采纳(写入):走软件采纳同一条 API,整套术语表口径,可取消可追溯; 仅在用户明确要求采纳时调用 ⑧ match_hist 历史价匹配 top-N:对会话一行找最像的历史价(match.py 同一管线), 行带 ref 票据供 ⑦⑨ 采纳 ⑨ lme_adopt 工料机价格采纳(写入):采纳即改价(页面同一条通道),价格数字来自 ⑧ 的服务端快照,不接受调用方传数字;仅在用户明确要求采纳时调用 - 零新增依赖:JSON-RPC 手写,只依赖标准库 """ import base64 import json import os import re import secrets import time import uuid 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 归一:默认 10,1~100。 2026-11-02 主人定:智能体命令没说条数=只给匹配前 10 条;说了最多给到 100。""" try: return min(max(int(args.get("limit") or 10), 1), 100) except (TypeError, ValueError): return 10 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} # ---------------------------------------------------------------- 工具实现(写入,决策 238) def _period_to_m(v): """'YYYY-MM' 或 'YYYY/MM' 或 月序号 → 月序号(年*12+月);非法返回 None。""" if v is None: return None s = str(v).strip() m = re.match(r"^(\d{4})[-/年](\d{1,2})", s) if m: return int(m.group(1)) * 12 + int(m.group(2)) try: n = int(float(s)) return n if n > 0 else None except ValueError: return None def _t_project_import(args): """⑥ 整项目导入(决策 238,写入):整项目模板 xlsx(项目目录+多对 Sheet,每对=1 个单位工程) → 建手工工程(目录树+清单一次到位)。file_b64=xlsx 内容(base64)。同名手工工程再次导入=整项目覆盖。 导入后可用 recent_review_query 查该工程(session_id),再用 bill_adopt 采纳。""" a = _api() name = (args.get("name") or "").strip() if not name: return {"ok": False, "msg": "name(工程名称)必填"} pf = _period_to_m(args.get("period_from")) pt = _period_to_m(args.get("period_to") or args.get("period_from")) if pf is None or pt is None: return {"ok": False, "msg": "period_from(YYYY-MM)必填;period_to 缺省=同 period_from"} b64 = (args.get("file_b64") or "").strip() if not b64: return {"ok": False, "msg": "file_b64(整项目模板 xlsx 的 base64 内容)必填——先向用户要 Excel 或按 template 说明生成"} import base64 as _b64 try: raw = _b64.b64decode(b64, validate=True) except Exception: return {"ok": False, "msg": "file_b64 不是合法 base64"} d = os.path.join(a.DATA_DIR, "manual_projects") os.makedirs(d, exist_ok=True) path = os.path.join(d, "mcp_%s.xlsx" % time.strftime("%Y%m%d_%H%M%S")) with open(path, "wb") as f: f.write(raw) body = {"name": name, "period_from": pf, "period_to": pt, "path": path, "province": (args.get("province") or "").strip(), "city": (args.get("city") or "").strip(), "district": (args.get("district") or "").strip(), "bulid_unit": (args.get("bulid_unit") or "").strip()} with a.WRITE_LOCK: con = a.sess.connect() try: r = a.mimp.import_project(con, body) con.commit() except Exception as e: r = {"ok": False, "msg": "导入异常:%s" % e} finally: con.close() if r.get("ok"): r["next"] = "recent_review_query(session_id=%s) 查清单;bill_adopt(session_id, bill_id, src_bill_id) 采纳" % r.get("sid") return r def _t_bill_adopt(args): """⑦ 清单采纳(决策 238,写入):把入库项目清单的定额+消耗量落到工作台会话。 bill_id=会话清单 id、src_bill_id=入库项目清单 id(都来自查询结果);走软件采纳同一条 API(术语表整套口径:新行覆盖/已有行追加、取价锚、可取消可追溯)。仅在用户明确要求 采纳时调用;每次一条,采纳后把结果如实告诉用户。""" a = _api() try: sid = int(args.get("session_id") or 0) bid = int(args.get("bill_id") or 0) except (TypeError, ValueError): return {"ok": False, "msg": "session_id / bill_id 都必须是整数 id"} src = 0 snap = None if args.get("ref"): snap = _MATCH_CACHE.get((args.get("ref") or "").strip()) if not snap or snap.get("type") != "bill": return {"ok": False, "msg": "ref 无效或已失效——请先 match_hist(type=bill)重新匹配"} try: src = int(snap.get("bill_id") or 0) except (TypeError, ValueError): src = 0 if not src: return {"ok": False, "msg": "该匹配行缺少来源清单 id,无法采纳"} else: try: src = int(args.get("src_bill_id") or 0) except (TypeError, ValueError): return {"ok": False, "msg": "src_bill_id 必须是整数 id(或改传 ref 票据)"} if not sid or not bid or not src: return {"ok": False, "msg": "参数:session_id(工作台会话)+ bill_id(会话清单)+ src_bill_id(或 ref 票据)"} with a.WRITE_LOCK: # 会话写库统一串行;采纳后分组缓存必撤(与页面路由同口径) sc = a.sess.connect() hc = a.conn() try: r = a.api_bill_adopt(sc, hc, {"session_id": sid, "bill_id": bid, "src_bill_id": src}) if r.get("ok"): # 决策 256:采纳来源快照(溯源定位)——从历史库取来源行拼渲染行同形快照 try: b = hc.execute("""SELECT b.Name, b.Attr, b.Unit, b.Price, t.Name proj, t.x_period_start_m p1, t.x_period_end_m p2 FROM bills b JOIN batches t ON t.id=b.batch_id WHERE b.id=?""", (src,)).fetchone() if b: per = ("%d-%02d" % (((b["p1"] or 0) // 12) - (1 if (b["p1"] or 0) % 12 == 0 else 0), (b["p1"] or 0) % 12 or 12)) if b["p1"] else None a.adopt_src_record(sc, sid, "bill", bid, {"src": "project", "src_id": src, "name": b["Name"], "attr": b["Attr"], "unit": b["Unit"], "price": b["Price"], "proj": b["proj"], "period": per or ("%d-%02d" % (((b["p2"] or 0) // 12) - (1 if (b["p2"] or 0) % 12 == 0 else 0), (b["p2"] or 0) % 12 or 12))}) except Exception: pass sc.commit() if r.get("ok"): try: a._grp_cache_drop("session", sid) except Exception: pass except Exception as e: try: sc.rollback() except Exception: pass r = {"ok": False, "msg": "采纳失败:%s" % e} finally: sc.close() hc.close() return r # ---- 决策 239(2026-10-29 主人定):历史价匹配 top-N + 工料机价格采纳 ---- # match_hist 返回行带 ref 票据:行数据快照(三价/名称/项目名)存本进程缓存,lme_adopt 只传 # ref——被采纳的数字全部由服务端快照取,智能体零转录、改不了价。缓存仅进程内,超限整体清空 #(语义=ref 失效请重新 match),不落盘、无泄漏面。 _MATCH_CACHE = {} _MATCH_CACHE_MAX = 2000 def _match_ref(row): if len(_MATCH_CACHE) >= _MATCH_CACHE_MAX: _MATCH_CACHE.clear() ref = uuid.uuid4().hex[:12] _MATCH_CACHE[ref] = row return ref def _sess_row_ctx(sc, sid): """会话元信息 + 匹配停用词(与工作台比对路由同口径)。""" a = _api() s = sc.execute("SELECT name, src_name, base_period_m, period_from, period_to FROM sessions WHERE id=?", (sid,)).fetchone() if not s: return None pf = (s["period_from"] if "period_from" in s.keys() else None) or s["base_period_m"] or 0 pt = (s["period_to"] if "period_to" in s.keys() else None) or pf sw = a._setting_get("global", "match_stopwords") try: a.match.set_stopwords(json.loads(sw)) if sw else a.match.set_stopwords([]) except Exception: a.match.set_stopwords([]) return {"base": (pf, pt), "self_name": (s["name"] or "").strip(), "self_src": (s["src_name"] or "").split(";")[0].strip()} def _t_match_hist(args): """⑧ 历史价匹配 top-N(决策 239,只读):对工作台的一行(清单或工料机)在全部入库项目/ 信息价/市场价里找最像的历史价,按 档位+期次距离 排序返回 top-N。每行带 ref 票据—— bill_adopt / lme_adopt 用它采纳,不需要再传价格数字。""" a = _api() try: sid = int(args.get("session_id") or 0) rid = int(args.get("row_id") or 0) except (TypeError, ValueError): return {"ok": False, "msg": "session_id / row_id 必须是整数 id"} typ = (args.get("type") or "bill").strip().lower() if typ not in ("bill", "lme"): return {"ok": False, "msg": "type 必须是 bill(清单)或 lme(工料机)"} if not sid or not rid: return {"ok": False, "msg": "参数:session_id + row_id(来自 recent_review_query 的行 id)"} try: limit = min(max(int(args.get("limit") or 5), 1), 20) except (TypeError, ValueError): limit = 5 sc = a.sess.connect() hc = a.conn() try: ctx = _sess_row_ctx(sc, sid) if ctx is None: return {"ok": False, "msg": "会话不存在(%d)" % sid} if typ == "lme": row = sc.execute("SELECT * FROM s_lmes WHERE id=? AND session_id=?", (rid, sid)).fetchone() if not row: return {"ok": False, "msg": "工料机行不存在(可能已被删除,请刷新)"} res = a.match.match_lme(hc, row, ctx["base"], limit=limit, self_name=ctx["self_name"], self_src=ctx["self_src"]) else: row = sc.execute("SELECT * FROM s_bills WHERE id=? AND session_id=?", (rid, sid)).fetchone() if not row: return {"ok": False, "msg": "清单行不存在(可能已被删除,请刷新)"} res = a.match.match_bill(hc, row, ctx["base"], [], [], [], limit, self_name=ctx["self_name"], self_src=ctx["self_src"]) finally: sc.close() hc.close() out = [] for r in res: ref = _match_ref({"type": typ, **{k: r.get(k) for k in ("name", "attr", "spec", "unit", "price", "tax", "price_tax", "proj", "src", "src_id", "bill_id")}}) out.append({"ref": ref, "tier": r.get("tier"), "src": r.get("src"), "name": r.get("name"), "spec": r.get("spec") or r.get("attr"), "unit": r.get("unit"), "price": r.get("price"), "tax": r.get("tax"), "price_tax": r.get("price_tax"), "proj": r.get("proj"), "period": r.get("period"), "sim": r.get("sim")}) return {"ok": True, "total": len(out), "hint": "挑最合适的一行,把它的 ref 传给 %s 采纳" % ("lme_adopt" if typ == "lme" else "bill_adopt"), "rows": out} def _t_lme_adopt(args): """⑨ 工料机价格采纳(决策 239,写入,仅在用户明确要求采纳时调用)。 lme_id=会话工料机行 id(recent_review_query type=lmes 的行)、ref=match_hist 返回的票据。 与页面比对框「采纳」同一条通道:三价改价端点(三价联动/编码同步/merged_codes/旧价锚) +「采纳:名称+项目+旧三价」备注。被采纳的价格来自服务端快照,不接受调用方传数字。""" a = _api() try: sid = int(args.get("session_id") or 0) lid = int(args.get("lme_id") or 0) except (TypeError, ValueError): return {"ok": False, "msg": "session_id / lme_id 必须是整数 id"} ref = (args.get("ref") or "").strip() snap = _MATCH_CACHE.get(ref) if not snap or snap.get("type") != "lme": return {"ok": False, "msg": "ref 无效或已失效——请先 match_hist 重新匹配再采纳"} if not sid or not lid: return {"ok": False, "msg": "参数:session_id + lme_id(工作台工料机行 id,来自 recent_review_query)"} sc = a.sess.connect() try: sl = sc.execute("SELECT id, Number, Name FROM s_lmes WHERE id=? AND session_id=?", (lid, sid)).fetchone() if not sl: return {"ok": False, "msg": "工料机行不存在(可能已被删除,请刷新)"} proj = sc.execute("""SELECT id, ntp, taxrate, taxp FROM s_lme_proj WHERE session_id=? AND code=? ORDER BY id LIMIT 1""", (sid, sl["Number"] or "")).fetchone() if sl["Number"] else None if not proj: return {"ok": False, "msg": "找不到该项目级工料机行(编码 %s)——项目级汇总未生成或编码为空" % (sl["Number"] or "空")} old = {"price": proj["ntp"], "tax": proj["taxrate"], "taxp": proj["taxp"]} with a.WRITE_LOCK: # 采纳即改价(决策 158)+ 采纳备注(决策 219 旧价锚口径) rp = a.api_lme_price(sc, {"session_id": sid, "id": proj["id"], "ntp": snap.get("price"), "taxrate": snap.get("tax"), "taxp": snap.get("price_tax")}) if not rp.get("ok"): sc.rollback() return {"ok": False, "msg": "采纳改价失败:" + (rp.get("msg") or "服务未响应")} # 采纳备注文案与页面 adoptTxtFor 同口径:采纳:名称+项目+旧三价(0/空=「无」) def p(v): try: return "无" if (v is None or v == "" or float(v) == 0) else v except (TypeError, ValueError): return "无" txt = "采纳:%s+%s+%s|%s|%s" % (snap.get("name") or "", snap.get("proj") or "", p(old["price"]), p(old["tax"]), p(old["taxp"])) a.sess.save_lme_remark(sc, proj["id"], txt) try: a.adopt_src_record(sc, sid, "lme", proj["id"], snap) # 决策 256:来源快照(溯源定位) except Exception: pass sc.commit() finally: sc.close() return {"ok": True, "lme_id": proj["id"], "price": snap.get("price"), "tax": snap.get("tax"), "price_tax": snap.get("price_tax"), "old": old, "msg": "已采纳《%s》%s:除税 %s → %s" % (snap.get("name") or "", snap.get("proj") or "", old["price"], snap.get("price"))} 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 _t_excel_bill_match(args): """⑩ Excel 批量清单匹配(2026-11-02 主人定,只读):Excel **只放一列清单名称**(A 列, 首行若是「清单名称/名称」表头自动跳过),逐行在全部入库项目清单里匹配**每条最优一条** ——期次近优先、同批次名称相似度高优先。期次/地区筛选=对比框同款: period_from/period_to(YYYY-MM,可选,同时是期次距离基准)、province/city/district(可选)。 行数不限;Excel 无编码无单位 → 走名称相似匹配(match_bill unit_free),无「精确编码」档属预期。""" a = _api() b64 = (args.get("file_b64") or "").strip() if not b64: return {"ok": False, "msg": "file_b64(Excel 的 base64 内容,A 列=清单名称)必填——先向用户要 Excel 或请用户粘贴名称清单"} import base64 as _b64 try: raw = _b64.b64decode(b64, validate=True) except Exception: return {"ok": False, "msg": "file_b64 不是合法 base64"} pf = _period_to_m(args.get("period_from")) pt = _period_to_m(args.get("period_to") or args.get("period_from")) prov = (args.get("province") or "").strip() city = (args.get("city") or "").strip() dist = (args.get("district") or "").strip() area = [(prov, city, dist)] if (prov or city or dist) else None try: import io as _io import openpyxl wb = openpyxl.load_workbook(_io.BytesIO(raw), read_only=True, data_only=True) except Exception as e: return {"ok": False, "msg": "Excel 读取失败:%s" % e} names = [] try: ws = wb.worksheets[0] for i, rx in enumerate(ws.iter_rows(min_col=1, max_col=1, values_only=True)): v = rx[0] if rx else None v = str(v).strip() if v is not None else "" if not v: continue if i == 0 and v in ("清单名称", "名称", "项目名称", "清单"): continue # 表头行 names.append(v) finally: wb.close() if not names: return {"ok": False, "msg": "Excel A 列没有读到任何清单名称"} hc = a.conn() rows_out = [] try: base = pf if pf is not None else 0 for nm in names: fake = {"Name": nm, "Unit": "", "Attr": "", "x_hash_exact": None, "x_hash_semi": None} try: res = a.match.match_bill(hc, fake, base, [], [], [], limit=8, pfrom=pf, pto=pt, area=area, unit_free=True) except Exception: res = [] best = sorted(res, key=lambda r: (r.get("dist") or 0, -(r.get("sim") or 0)))[0] if res else None if best: rows_out.append({"name": nm, "hit": True, "tier": best.get("tier"), "match_name": best.get("name"), "unit": best.get("unit"), "price": best.get("price"), "proj": best.get("proj"), "region": best.get("region"), "period": best.get("period"), "sim": best.get("sim")}) else: rows_out.append({"name": nm, "hit": False, "msg": "没有匹配到足够相似的历史清单"}) finally: hc.close() return {"ok": True, "total": len(rows_out), "hit": sum(1 for r in rows_out if r["hit"]), "hint": "每行=Excel 一条清单的最优匹配:期次近优先、同批次名称相似度优先;price=该清单历史单价(未匹配行带 hit=false)", "rows": rows_out} # ---------------------------------------------------------------- 工具清单 def TOOLS(): return [ {"name": "bills_query", "description": "查入库项目的清单:编号 Number、名称 Name、项目特征 Attr、单价 Price。" "keyword(编号/名称关键词)或 batch_id 至少给一个;limit 默认 10 上限 100(不传 limit=只返回匹配前 10 条)。" "响应不含附件信息。", "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}, {"name": "project_import", "description": "整项目导入(写入)。把整项目模板 xlsx(「项目目录」Sheet 定目录树+" "多对数据 Sheet,每对 分部分项N/措施项目N=序号 N 的单位工程)导入建为" "手工工程。file_b64=xlsx 文件内容(base64);name/period_from(YYYY-MM) 必填," "province/city/district/bulid_unit 可选。同名手工工程再次导入=整项目覆盖。" "导入成功后用 recent_review_query 查该工程清单,再按用户要求 bill_adopt。", "inputSchema": {"type": "object", "properties": { "name": {"type": "string"}, "period_from": {"type": "string"}, "period_to": {"type": "string"}, "file_b64": {"type": "string"}, "province": {"type": "string"}, "city": {"type": "string"}, "district": {"type": "string"}, "bulid_unit": {"type": "string"}}, "required": ["name", "period_from", "file_b64"]}, "run": _t_project_import}, {"name": "bill_adopt", "description": "清单采纳(写入,仅在用户明确要求采纳时调用)。把入库项目清单的定额+消耗量" "落到工作台会话清单上(软件采纳同一条通道:新行=整组覆盖,已有行=单价覆盖+" "定额追加;可取消可追溯)。session_id=工作台会话、bill_id=会话清单 id、" "src_bill_id=入库项目清单 id(id 必须来自查询结果)。每次采纳一条并把结果如实告诉用户。", "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": "match_hist", "description": "历史价匹配 top-N(只读)。对工作台一行(清单或工料机)在全部入库项目/信息价/" "市场价里找最像的历史价,按档位+期次距离排序返回 top-N;每行带 ref 票据," "把它传给 bill_adopt / lme_adopt 即可采纳——不需要(也不允许)自己传价格数字。" "session_id + row_id(来自 recent_review_query)+ type(bill/lme)+ limit(默认 5,上限 20)。", "inputSchema": {"type": "object", "properties": { "session_id": {"type": "integer"}, "row_id": {"type": "integer"}, "type": {"type": "string"}, "limit": {"type": "integer"}}, "required": ["session_id", "row_id"]}, "run": _t_match_hist}, {"name": "lme_adopt", "description": "工料机价格采纳(写入,仅在用户明确要求采纳时调用)。把匹配到的历史价" "(ref 票据)采纳到工作台工料机:与页面比对框「采纳」同一条通道(三价联动/" "编码同步/merged_codes/旧价锚+采纳备注)。lme_id=工作台工料机行 id" "(recent_review_query type=lmes 的行)+ ref(match_hist type=lme 返回的票据)。" "价格数字来自服务端快照,不接受调用方传数字;每次一条,结果如实告知用户。", "inputSchema": {"type": "object", "properties": { "session_id": {"type": "integer"}, "lme_id": {"type": "integer"}, "ref": {"type": "string"}}, "required": ["session_id", "lme_id", "ref"]}, "run": _t_lme_adopt}, {"name": "excel_bill_match", "description": "Excel 批量清单匹配(只读,数量不限)。Excel 只放一列清单名称(A 列," "可有「清单名称」表头),file_b64=Excel 的 base64;逐行在全部入库项目清单里" "匹配每条最优一条(期次近优先、同批次名称相似度优先)。期次/地区沿用对比框" "筛选口径:period_from/period_to(YYYY-MM,可选)、province/city/district(可选)。" "适合「按某期查一批清单的历史单价」。", "inputSchema": {"type": "object", "properties": { "file_b64": {"type": "string"}, "period_from": {"type": "string"}, "period_to": {"type": "string"}, "province": {"type": "string"}, "city": {"type": "string"}, "district": {"type": "string"}}, "required": ["file_b64"]}, "run": _t_excel_bill_match}, ] # ---------------------------------------------------------------- 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]