fix(manual): 手工导出骨架与导入边界修复,单位按目录自然序排列

- 上传口骨架收集改为空操作,骨架仅经升级入库(决策 231/补记十四)
- s_lme_lib 价格快照垫底,修手工会话组成子行价格落 0
- 导出编辑相交消解:删除块与闭合前插入冲突时重映射,防采纳定额丢失/碎 XML
- _span 识别自闭合标签,防容器配对失败留孤儿闭合
- 手工导入放开空名/同名/深层级校验
- 单位顺序改按左侧目录树序(单项入库序+组内编号自然序)
- 补齐手工导出/导入/MCP 切换相关测试
This commit is contained in:
lianjianwei2024
2026-10-28 16:20:34 +08:00
parent 34b14e74ec
commit 8250a265fb
29 changed files with 4033 additions and 1128 deletions

View File

@@ -1,27 +1,29 @@
# -*- coding: utf-8 -*-
"""MCP 接入层(2026-10-15):把产品功能以 MCP 工具暴露给 AI harness(ZCode / WorkBuddy /
DeepSeek 等一切支持 MCP 或会发 HTTP 的 agent)。
"""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(开关开了也断)
- 工具:全部复用 api_* 处理器(与界面同一套业务、写锁、分组缓存失效),**不另开第二通道**
- 收费挂钩: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 手写,只依赖标准库
Agent 注意(与 /api/schema 的 notes 一致):id 随重开变化;采纳 新行=覆盖/已有行=追加;
工程量等数值一律字符串;导出前自动校验源文件哈希。
"""
import io
import base64
import json
import os
import re
import secrets
import threading
import zipfile
PROTO_VERSION = "2025-06-18"
_API = None # api_server 模块(bind 注入,避免循环导入)
ATT_MAX_DL = 20 * 1024 * 1024 # 单附件下载上限:超过请走软件界面下载
def bind(api_module):
@@ -64,10 +66,20 @@ def status():
"endpoint": "/mcp", "port": a.PORT, "license_enforced": bool(a.license_gate._cfg.get("enforce", True))}
# ---------------------------------------------------------------- 工具实现(复用 api_*)
# ---------------------------------------------------------------- 工具实现(只读)
def _read(fn):
"""只读工具:开只读连接跑 api_* 函数。"""
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:
@@ -76,220 +88,229 @@ def _read(fn):
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()
def _paging(args):
"""limit 归一:默认 50,1~200。"""
try:
return a.api_admin_import(con, args)
finally:
con.close()
return min(max(int(args.get("limit") or 50), 1), 200)
except (TypeError, ValueError):
return 50
def _t_tree(args):
return _api().api_raw_tree(args)
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 _t_uw_detail(args):
return _api().api_raw_uw(args)
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_session_rows(args):
return _api().api_session_rows(args)
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_bill_op(args):
return _write(lambda sc: _api().api_bill_op(sc, args))
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_norm_op(args):
return _write(lambda sc: _api().api_norm_op(sc, args))
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_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", ""))
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:
a.sess.save_remark(sc, int(args.get("bill_id", 0)), args.get("remark", ""))
return {"ok": True}
return _write(run)
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_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 在本机直接可读)。"""
def _t_attachment_download(args):
"""⑤ 下载绑定附件(仅响应明确指令;id 必须来自 ①~④ 查询结果)。
type=bill/lme → 该行绑定的询价附件(bill_attach / lme_attach);
type=batch → 价格批次原件(batches.x_attach_sha)。"""
a = _api()
sc = a.sess.connect()
typ = (args.get("type") or "").strip().lower()
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}
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 _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},
{"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},
]
@@ -314,7 +335,7 @@ def _dispatch(msg):
return False, _rpc_result(cid, {
"protocolVersion": PROTO_VERSION,
"capabilities": {"tools": {"listChanged": False}},
"serverInfo": {"name": "造价审核", "version": "mcp-1.0"}})
"serverInfo": {"name": "造价审核", "version": "mcp-2.0"}})
if method == "ping":
return False, _rpc_result(cid, {})
if method == "tools/list":
@@ -343,7 +364,7 @@ def _dispatch(msg):
def handle_post(auth_header, body_text):
"""POST /mcp 入口。返回 (HTTP 状态码, 响应对象或 None[202])。
三道闸顺序:开关 → 令牌 → 授权(收费挂钩:enforce 时未激活/过期整端点断)。"""
三道闸顺序:开关 → 令牌 → 授权(收费挂钩:enforce 时套餐范围外且临时卡失效整端点断)。"""
a = _api()
if not enabled():
return 403, {"jsonrpc": "2.0", "id": None,