#!/usr/bin/env bash # mcp-smoke.sh —— MCP 工具层契约尺子(第十道闸门) # # 测什么:**AI 能不能只靠 4 个元工具,把「找工具 → 看坑 → 执行」跑通**。 # 这是 P1 的唯一 KPI(PLAN.md §6.7)。 # # 用法: # bash scripts/mcp-smoke.sh # 用 debug 产物,自起隔离库 # bash scripts/mcp-smoke.sh --bin # 指定二进制 # # 退出码:0 全过 / 1 有断言失败 / 2 环境错 # # ── 断言(每条一个「不变量」)── # M1 initialize 报出 protocolVersion 与 serverInfo # M2 tools/list **恰好 4 个**元工具(分层加载的硬约束) # M3 业务工具**不出现**在 tools/list(否则 token 预算失效) # M4 通知(无 id)不产生回复 # M5 sspf_context 返回 backend / tables / 能力域 # M6 sspf_discover 无 query ⇒ 分类树;有 query ⇒ 搜索结果 # M7 sspf_describe(level=pitfalls) 返回坑与前置条件 # M8 sspf_call 真执行业务工具并返回 ok=true # M9 sspf_call 未知工具 ⇒ ok=false + TOOL_NOT_FOUND + next_actions(**不是**协议错误) # M10 sspf_call(dry_run) 不产生副作用且能报缺参 # M11 **stdout 必须是纯 NDJSON**(每一行都能被 JSON 解析) # M12 **stderr 不得混入协议 JSON**(防止重定向写反) # M46 data.query 不投影口令/密钥列(藏了几列会明说) # M47 显式要 f_password ⇒ SENSITIVE_COLUMN # # ── 阶段 B:P2-b 低代码动态 CRUD 闭环(M32–M45)── # # 先 `--seed-lowcode-demo` 造出示例功能(enCode=receivableDemo), # 再用**同一个** PGLITE_DIR 起 `--mcp`(新进程能重开同一数据目录)。 # # M32 sspf_discover(query=data.record) 能搜到 insert / update / delete # M33 sspf_describe(data.record.insert, pitfalls) 拿到坑清单 # M34 data.record.insert 不传 dryRun ⇒ **默认 true**,只出 SQL # M35 M34 之后 data.query 查不到任何行(默认演练真的没落库) # M36 dryRun=false ⇒ 真落库,返回主键 # M37 data.query 查得到(单租户 f_tenant_id='0',f_room 值正确) # M38 子表 2 行挂在外键上(主表 id = f_receivableid) # M39 data.record.update 子表**差集**:旧行⇒updateMain、新键⇒insertSub、缺席⇒hardDelete # M40 差集结果落库:保留行被改、新行进来、缺席行没了 # M41 delete 不传 dryRun ⇒ 默认演练,行还在 # M42 delete dryRun=false ⇒ 查不到(logicalDelete=false ⇒ 物理删) # M43 官方 fixture 没声明 unique ⇒ 同值两行**不被误拒**(尺子不骗人) # M44 schema.table.create(dryRun) ⇒ 两张表 + 复合主键 + 回写模型含系统列 # M45 schema.table.create(dryRun=false) 对已存在的表⇒ skipped(幂等,不重建) # # 🔴 M11/M12 是在踩过一次坑之后加的:内嵌 PostgreSQL 会往 fd 1 打 # `PostgreSQL stand-alone backend 17.5` / `backend>`,且它的 single-user 后端 # 会占用 fd 0。内核在开库前用 `dup` 把协议通道整个复制出来(`detach_stdio_for_mcp`), # 这两条断言就是钉住那个行为不被改回去。 # # 🔴 阶段 B 由 python 驱动(不是静态 NDJSON):主键是服务端生成的 UUID, # 静态请求没法在下一条里引用它。响应逐条 flush ⇒ 一问一答不会死锁。 set -u ROOT="$(cd "$(dirname "$0")/.." && pwd)" BIN="$ROOT/target/debug/sspf-admin" PASS=0 FAIL=0 while [ $# -gt 0 ]; do case "$1" in --bin) BIN="$2"; shift 2 ;; --help) sed -n '2,32p' "$0"; exit 0 ;; *) echo "未知参数: $1"; exit 2 ;; esac done [ -x "$BIN" ] || { echo "❌ 二进制不存在: ${BIN}(先 cargo build)"; exit 2; } command -v python3 >/dev/null || { echo "❌ 需要 python3"; exit 2; } ok() { PASS=$((PASS + 1)); printf ' ✅ %s\n' "$1"; } bad() { FAIL=$((FAIL + 1)); printf ' ❌ %s\n' "$1"; } TMP="$(mktemp -d /tmp/sspf-mcp-smoke.XXXXXX)" trap 'rm -rf "$TMP"' EXIT INT TERM REQ="$TMP/req.ndjson" OUT="$TMP/out.ndjson" ERR="$TMP/err.txt" cat > "$REQ" <<'NDJSON' {"jsonrpc":"2.0","id":1,"method":"initialize","params":{}} {"jsonrpc":"2.0","method":"notifications/initialized"} {"jsonrpc":"2.0","id":2,"method":"tools/list"} {"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"sspf_context","arguments":{}}} {"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"sspf_discover","arguments":{}}} {"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"sspf_discover","arguments":{"query":"表"}}} {"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"sspf_describe","arguments":{"tool_id":"schema.table.list","level":"pitfalls"}}} {"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"schema.table.list","args":{}}}} {"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"nope.nope","args":{}}}} {"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"schema.table.describe","args":{},"dry_run":true}}} {"jsonrpc":"2.0","id":10,"method":"ping","params":{}} {"jsonrpc":"2.0","id":11,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"permission.user.list","args":{}}}} {"jsonrpc":"2.0","id":12,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"permission.role.list","args":{}}}} {"jsonrpc":"2.0","id":13,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"dict.type.list","args":{}}}} {"jsonrpc":"2.0","id":14,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"data.count","args":{"table":"base_user"}}}} {"jsonrpc":"2.0","id":15,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"data.query","args":{"table":"base_user","columns":["f_account"],"limit":3}}}} {"jsonrpc":"2.0","id":16,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"schema.index.list","args":{"table":"base_user"}}}} {"jsonrpc":"2.0","id":17,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"data.query","args":{"table":"base_user","where":[{"column":"f_account; DROP TABLE x","op":"eq","value":"a"}]}}}} {"jsonrpc":"2.0","id":18,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"menu.create","args":{"fullName":"冒烟菜单","enCode":"permission.smoke.page","urlAddress":"smoke/Page"}}}} {"jsonrpc":"2.0","id":19,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"menu.create","args":{"fullName":"重复","enCode":"permission.smoke.page","urlAddress":"smoke/Other"}}}} {"jsonrpc":"2.0","id":20,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"menu.create","args":{"fullName":"坏路径","enCode":"permission.smoke.bad","urlAddress":"/bad/Path"}}}} {"jsonrpc":"2.0","id":21,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"permission.authorize.grant","args":{"objectType":"role","objectId":"role_user","menuEnCode":"permission.smoke.page"}}}} {"jsonrpc":"2.0","id":22,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"permission.user.create","args":{"account":"smoke_user","realName":"冒烟用户","password":"Smoke@123","roleIds":["role_user"]}}}} {"jsonrpc":"2.0","id":23,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"permission.effective","args":{"account":"smoke_user","withMenuDetail":true}}}} {"jsonrpc":"2.0","id":24,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"permission.authorize.revoke","args":{"objectType":"role","objectId":"role_user","menuEnCode":"permission.smoke.page"}}}} {"jsonrpc":"2.0","id":25,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"permission.effective","args":{"account":"smoke_user"}}}} {"jsonrpc":"2.0","id":26,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"permission.authorize.revoke","args":{"objectType":"role","objectId":"role_user","menuEnCode":"permission.smoke.page"}}}} {"jsonrpc":"2.0","id":27,"method":"prompts/list","params":{}} {"jsonrpc":"2.0","id":28,"method":"prompts/get","params":{"name":"new_business_module","arguments":{"module_name":"冒烟","module_code":"smoke"}}} {"jsonrpc":"2.0","id":29,"method":"prompts/get","params":{"name":"diagnose_menu_not_visible","arguments":{}}} {"jsonrpc":"2.0","id":30,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"data.query","args":{"table":"base_user","limit":2}}}} {"jsonrpc":"2.0","id":31,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"data.query","args":{"table":"base_user","columns":["f_password"],"limit":1}}}} NDJSON echo "── MCP 工具层契约尺子(4 元工具 + 分层加载)──" PGLITE_DIR="$TMP/db" "$BIN" --mcp < "$REQ" > "$OUT" 2> "$ERR" RC=$? if [ "$RC" -ne 0 ]; then echo "❌ MCP 进程退出码 ${RC}(期望 0)" echo " stderr 尾部:" tail -8 "$ERR" | sed 's/^/ /' exit 2 fi python3 - "$OUT" "$ERR" "$REQ" <<'PY' import json, sys out_path, err_path, req_path = sys.argv[1], sys.argv[2], sys.argv[3] PASS = FAIL = 0 def ok(m): global PASS; PASS += 1; print(f" ✅ {m}") def bad(m): global FAIL; FAIL += 1; print(f" ❌ {m}") # 🔴 期望回复数 **从请求文件算**,不写死 —— 加一条请求不该逼人改断言 expected = 0 for line in open(req_path, encoding='utf-8'): line = line.strip() if not line: continue try: if "id" in json.loads(line): expected += 1 except Exception: pass raw = open(out_path, encoding='utf-8', errors='replace').read() lines = [l for l in raw.splitlines() if l.strip()] # ---- M11 stdout 必须是纯 NDJSON ---- parsed = {} bad_lines = [] for i, line in enumerate(lines, 1): try: m = json.loads(line) except Exception: bad_lines.append((i, line[:80])) continue if m.get("id") is not None: parsed[m["id"]] = m if bad_lines: bad(f"M11 stdout 有 {len(bad_lines)} 行不是合法 JSON(NDJSON 被污染)") for i, s in bad_lines[:3]: print(f" 第{i}行: {s}") else: ok(f"M11 stdout 是纯 NDJSON({len(lines)} 行全部可解析)") # ---- M12 stderr 不得混协议 ---- err = open(err_path, encoding='utf-8', errors='replace').read() if '"jsonrpc"' in err: bad("M12 stderr 混入了协议 JSON(重定向写反了)") else: ok("M12 stderr 无协议 JSON(日志与协议分离)") def result(rid): return parsed.get(rid, {}).get("result") # ---- M1 initialize ---- r = result(1) if r and r.get("protocolVersion") and r.get("serverInfo", {}).get("name") == "sspf-mcp": ok(f"M1 initialize 报出 protocol={r['protocolVersion']} server={r['serverInfo']['name']}") else: bad("M1 initialize 响应不完整") # ---- M2 恰好 4 个元工具 ---- tools = (result(2) or {}).get("tools", []) names = [t.get("name") for t in tools] expect = ["sspf_context", "sspf_discover", "sspf_describe", "sspf_call"] if len(tools) == 4 and sorted(names) == sorted(expect): ok("M2 tools/list 恰好 4 个元工具") else: bad(f"M2 tools/list 应为 4 个元工具,实际 {len(tools)}: {names}") # ---- M3 业务工具不出现 ---- blob = json.dumps(result(2) or {}, ensure_ascii=False) if "context.get" in blob or "schema.table.list" in blob: bad("M3 业务工具泄漏到 tools/list(分层加载失效)") else: ok("M3 业务工具不在 tools/list(只能经 discover 访问)") # ---- M4 通知不回复 ---- if len(parsed) == expected: ok(f"M4 {expected} 条带 id 的请求各一个回复;通知无回复") else: bad(f"M4 回复数 {len(parsed)},期望 {expected}(通知不该有回复)") # ---- M5 context ---- sc = (result(3) or {}).get("structuredContent", {}) if sc.get("backend") == "native" and isinstance(sc.get("tables"), int) and sc["tables"] > 0: ok(f"M5 sspf_context: backend=native tables={sc['tables']} 能力域={len(sc.get('domains', []))}") else: bad(f"M5 sspf_context 异常: {json.dumps(sc, ensure_ascii=False)[:120]}") # ---- M6 discover 两种模式 ---- d0 = (result(4) or {}).get("structuredContent", {}) d1 = (result(5) or {}).get("structuredContent", {}) if d0.get("mode") == "categories" and isinstance(d0.get("categories"), list): ok(f"M6a discover 无 query ⇒ 分类树({len(d0['categories'])} 类)") else: bad("M6a discover 无 query 应返回分类树") if d1.get("mode") == "search" and isinstance(d1.get("results"), list): ok(f"M6b discover(query=表) ⇒ 搜索结果 {d1.get('count')} 条") else: bad("M6b discover 带 query 应返回搜索结果") # ---- M7 describe pitfalls ---- dp = (result(6) or {}).get("structuredContent", {}) if dp.get("ok") and isinstance(dp.get("pitfalls"), list) and len(dp["pitfalls"]) > 0: ok(f"M7 describe(pitfalls) 返回 {len(dp['pitfalls'])} 个坑") else: bad("M7 describe(pitfalls) 应返回坑清单") # ---- M8 call 真执行 ---- c1 = (result(7) or {}).get("structuredContent", {}) if c1.get("ok") and c1.get("data", {}).get("count", 0) > 0: ok(f"M8 sspf_call 执行业务工具成功(表数 {c1['data']['count']})") else: bad(f"M8 sspf_call 执行失败: {json.dumps(c1, ensure_ascii=False)[:120]}") # ---- M9 未知工具 ⇒ 结构化错误(不是协议错误)---- r9 = parsed.get(8, {}) c2 = (r9.get("result") or {}).get("structuredContent", {}) if "error" not in r9 and c2.get("ok") is False \ and c2.get("error", {}).get("code") == "TOOL_NOT_FOUND" \ and isinstance(c2["error"].get("next_actions"), list): ok("M9 未知工具 ⇒ ok=false + TOOL_NOT_FOUND + next_actions(业务失败未变成协议错误)") else: bad(f"M9 未知工具应返回结构化业务错误,实际: {json.dumps(r9, ensure_ascii=False)[:160]}") # ---- M10 dry_run ---- c3 = (result(9) or {}).get("structuredContent", {}) if c3.get("dry_run") is True and isinstance(c3.get("problems"), list) and len(c3["problems"]) > 0: ok(f"M10 dry_run 报出缺失必填参数({len(c3['problems'])} 项)") else: bad(f"M10 dry_run 应报缺参,实际: {json.dumps(c3, ensure_ascii=False)[:120]}") def payload(rid): """取 sspf_call 的 data 段(业务工具的真实返回)。""" return ((result(rid) or {}).get("structuredContent") or {}).get("data", {}) # ---- M13~M16 四域只读工具 ---- u = payload(11) if isinstance(u.get("users"), list) and "password" not in json.dumps(u).lower(): ok(f"M13 permission.user.list 返回 {u.get('count')} 个用户且**不含口令字段**") else: bad(f"M13 permission.user.list 异常或泄漏口令: {json.dumps(u, ensure_ascii=False)[:120]}") r = payload(12) if isinstance(r.get("roles"), list) and r.get("count", 0) >= 1: ok(f"M14 permission.role.list 返回 {r.get('count')} 个角色") else: bad("M14 permission.role.list 应至少有一个角色(种子里有 admin)") dt = payload(13) if isinstance(dt.get("types"), list): ok(f"M15 dict.type.list 返回 {dt.get('count')} 个字典分类") else: bad("M15 dict.type.list 返回形状不对") dc = payload(14) if isinstance(dc.get("count"), int): ok(f"M16 data.count(base_user) = {dc['count']}") else: bad(f"M16 data.count 应返回整数 count,实际: {json.dumps(dc, ensure_ascii=False)[:100]}") # ---- M17 列白名单确实生效(只返回请求的列;键是去 f_ 前缀的 camelCase)---- dq = payload(15) rows = dq.get("rows") or [] if isinstance(rows, list) and rows and all(set(row.keys()) == {"account"} for row in rows): ok(f"M17 data.query 只返回白名单内的列({len(rows)} 行 × 1 列,键已转 camelCase)") else: bad(f"M17 data.query 列裁剪失效: {json.dumps(rows[:1], ensure_ascii=False)[:120]}") # ---- M18 索引清单 ---- ix = payload(16) if isinstance(ix.get("indexes"), list) and ix.get("count", 0) >= 1: ok(f"M18 schema.index.list 返回 {ix.get('count')} 条索引") else: bad("M18 schema.index.list 至少应有主键索引") # ---- M19 🔴 结构注入防护:列名里带 SQL 必须被拒 ---- r17 = parsed.get(17, {}) c17 = (r17.get("result") or {}).get("structuredContent", {}) if c17.get("ok") is False and c17.get("error", {}).get("code") == "UNKNOWN_COLUMN": ok("M19 列名带 SQL 片段 ⇒ UNKNOWN_COLUMN(结构注入被挡)") else: bad(f"M19 结构注入未被挡住: {json.dumps(c17, ensure_ascii=False)[:160]}") # ---- M20~M22 写工具(建 → 重复拒 → 坏路径拒)---- w1 = (result(18) or {}).get("structuredContent", {}) wd = w1.get("data", {}) if w1.get("ok") is True and wd.get("id") and wd.get("urlAddress") == "smoke/Page": ok(f"M20 menu.create 成功(id={str(wd['id'])[:8]}…)") else: bad(f"M20 menu.create 失败: {json.dumps(w1, ensure_ascii=False)[:140]}") w2 = (result(19) or {}).get("structuredContent", {}) we = w2.get("error", {}) if w2.get("ok") is False and we.get("code") == "MENU_EXISTS": ok("M21 重复 enCode ⇒ MENU_EXISTS(唯一性应用层兜住)") else: bad(f"M21 重复建未被拒: {json.dumps(w2, ensure_ascii=False)[:140]}") w3 = (result(20) or {}).get("structuredContent", {}) w3e = w3.get("error", {}) if w3.get("ok") is False and w3e.get("code") == "BAD_URL_ADDRESS": ok("M22 urlAddress 带前导斜杠 ⇒ BAD_URL_ADDRESS") else: bad(f"M22 坏路径未被拒: {json.dumps(w3, ensure_ascii=False)[:140]}") # ---- M23~M30 授权闭环(建菜单后的最后一公里)---- g = (result(21) or {}).get("structuredContent", {}) if g.get("ok") is True and g.get("data", {}).get("granted") is True: ok("M23 permission.authorize.grant 授给角色成功") else: bad(f"M23 授权失败: {json.dumps(g, ensure_ascii=False)[:160]}") u = (result(22) or {}).get("structuredContent", {}) if u.get("ok") is True and u.get("data", {}).get("isAdministrator") is False: ok("M24 user.create 建出的是**非管理员**账号(能测出授权问题)") else: bad(f"M24 建用户失败: {json.dumps(u, ensure_ascii=False)[:160]}") e1 = (result(23) or {}).get("structuredContent", {}).get("data", {}) vis1 = [m.get("urlAddress") for m in (e1.get("visible") or {}).get("menus", []) if isinstance(m, dict)] src1 = (e1.get("sources") or {}).get("role", {}).get("menuIds") or [] if e1.get("isAdmin") is False and "smoke/Page" in vis1 and src1: ok(f"M25 effective 看到授权的菜单(visible={e1['visible']['count']},来源=role)") else: bad(f"M25 授权后仍看不到: visible={vis1} isAdmin={e1.get('isAdmin')}") rv = (result(24) or {}).get("structuredContent", {}) if rv.get("ok") is True and rv.get("data", {}).get("revoked") is True: ok("M26 revoke 撤权成功(软删)") else: bad(f"M26 撤权失败: {json.dumps(rv, ensure_ascii=False)[:160]}") e2 = (result(25) or {}).get("structuredContent", {}).get("data", {}) vis2 = [m.get("urlAddress") for m in (e2.get("visible") or {}).get("menus", []) if isinstance(m, dict)] if "smoke/Page" not in vis2: ok("M27 撤权后 effective 立刻看不到(四源并集真的变了)") else: bad(f"M27 撤权后仍可见: {vis2}") e3 = (result(26) or {}).get("structuredContent", {}) if e3.get("ok") is False and e3.get("error", {}).get("code") == "AUTHORIZE_NOT_FOUND": ok("M28 重复撤权 ⇒ AUTHORIZE_NOT_FOUND(不静默成功)") else: bad(f"M28 重复撤权未被拒: {json.dumps(e3, ensure_ascii=False)[:160]}") pl = result(27) or {} names = [x.get("name") for x in (pl.get("prompts") or [])] if len(names) >= 3 and "new_business_module" in names: ok(f"M29 prompts/list 返回 {len(names)} 个模板(含 new_business_module)") else: bad(f"M29 prompts/list 异常: {names}") pg = result(28) or {} ptext = ((pg.get("messages") or [{}])[0].get("content") or {}).get("text", "") if "非管理员" in ptext and "menu.create" in ptext and "permission.authorize.grant" in ptext: ok("M30 prompts/get 正文含关键步骤(建菜单 + 授权 + 非管理员验证)") else: bad(f"M30 模板正文缺关键步骤(长度 {len(ptext)})") # 缺参时是 JSON-RPC error(没有 result),所以要拿整条响应 pm = parsed.get(29, {}) if pm.get("error", {}).get("code") == -32602: ok("M31 模板缺必填参数 ⇒ INVALID_PARAMS(不渲染带占位符的正文)") else: bad(f"M31 缺参未被拦: {json.dumps(pm, ensure_ascii=False)[:140]}") # ---- M46/M47 敏感列:通用读工具不许投影口令 ---- q30 = payload(30) keys30 = set() for row in q30.get("rows") or []: keys30 |= set(row.keys()) if q30.get("rows") and "password" not in keys30 and "secretkey" not in keys30 \ and q30.get("hiddenColumns", 0) >= 1: ok(f"M46 data.query(base_user) 不投影口令列(藏了 {q30['hiddenColumns']} 列)") else: bad(f"M46 通用读工具泄漏了口令列: hidden={q30.get('hiddenColumns')} keys={sorted(keys30)[:8]}") c31 = (result(31) or {}).get("structuredContent", {}) if c31.get("ok") is False and c31.get("error", {}).get("code") == "SENSITIVE_COLUMN": ok("M47 显式要 f_password ⇒ SENSITIVE_COLUMN(不静默少给、也不给哈希)") else: bad(f"M47 显式要口令列没被拒: {json.dumps(c31, ensure_ascii=False)[:150]}") print() print(f"PASS={PASS} FAIL={FAIL}") sys.exit(0 if FAIL == 0 else 1) PY RC_A=$? # ============================================================================ # 阶段 B:P2-b 低代码动态 CRUD(种子 → 写工具 → 查证 → 删) # ============================================================================ echo echo "── 阶段 B:低代码动态 CRUD(receivableDemo)──" if PGLITE_DIR="$TMP/db" "$BIN" --seed-lowcode-demo > "$TMP/seed.log" 2>&1; then if grep -q "receivableDemo" "$TMP/seed.log"; then echo " ✅ 种子:receivableDemo 已就绪(建表 + 回写模型)" else echo " ❌ 种子跑完了但没报出 enCode=receivableDemo" tail -6 "$TMP/seed.log" | sed 's/^/ /' fi else echo " ❌ 种子失败(--seed-lowcode-demo)" grep -vE "stand-alone|^backend>" "$TMP/seed.log" | tail -8 | sed 's/^/ /' RC_A=1 fi python3 - "$BIN" "$TMP/db" "$TMP" <<'PY' import json, os, subprocess, sys, traceback BIN, DBDIR, TMP = sys.argv[1], sys.argv[2], sys.argv[3] env = dict(os.environ) env["PGLITE_DIR"] = DBDIR err = open(os.path.join(TMP, "mcp-b.stderr"), "w", encoding="utf-8") proc = subprocess.Popen( [BIN, "--mcp"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=err, env=env, text=True, bufsize=1, encoding="utf-8", ) PASS = FAIL = 0 def ok(m): global PASS; PASS += 1; print(f" ✅ {m}") def bad(m): global FAIL; FAIL += 1; print(f" ❌ {m}") _next = [0] def send(method, params): _next[0] += 1 rid = _next[0] proc.stdin.write(json.dumps( {"jsonrpc": "2.0", "id": rid, "method": method, "params": params}, ensure_ascii=False) + "\n") proc.stdin.flush() while True: line = proc.stdout.readline() if not line: raise RuntimeError(f"进程在读 {method}#{rid} 时退出(见 {TMP}/mcp-b.stderr)") line = line.strip() if not line: continue try: msg = json.loads(line) except Exception: continue if msg.get("id") == rid: return msg def notify(method): proc.stdin.write(json.dumps({"jsonrpc": "2.0", "method": method}) + "\n") proc.stdin.flush() def invoke(tool, args=None): msg = send("tools/call", {"name": "sspf_call", "arguments": {"tool_id": tool, "args": args or {}}}) return (msg.get("result") or {}).get("structuredContent") or {} def meta_call(name, args): msg = send("tools/call", {"name": name, "arguments": args}) return (msg.get("result") or {}).get("structuredContent") or {} def show(sc, n=160): return json.dumps(sc, ensure_ascii=False)[:n] def kinds(outcome): return [s.get("kind") for s in (outcome.get("sql") or [])] EN = "receivableDemo" MAIN = {"F_Building": "1号楼", "F_Room": "A-101", "F_Company_name": "冒烟公司", "F_Userid": "苏苏", "F_Phone": "13800000000", "F_Ost": "经理"} SUB = {"F_Month": "2026-10", "F_Rent": 1200.5, "F_Water_rent": 10, "F_Powerrate": 20, "F_Property": 30, "F_Cleaning": 5, "F_Pollutant": 2, "F_Totalbilling": 1267.5} def payload(extra_sub=None): p = dict(MAIN) # 两行子表:差集断言需要「一行保留、一行缺席」 p["tableField107"] = extra_sub if extra_sub is not None else [ dict(SUB), {**SUB, "F_Month": "2026-11", "F_Rent": 800}, ] return p try: send("initialize", {}) notify("notifications/initialized") # ---- M32 discover 能搜到三个写工具 ---- d = meta_call("sspf_discover", {"query": "data.record"}) ids = {r.get("id") for r in (d.get("results") or [])} want = {"data.record.insert", "data.record.update", "data.record.delete"} if want <= ids: ok(f"M32 discover(query=data.record) 找到 3 个写工具(共 {d.get('count')} 条结果)") else: bad(f"M32 discover 少了工具:缺 {sorted(want - ids)}(实际 {sorted(ids)})") # ---- M33 describe 拿到坑 ---- d = meta_call("sspf_describe", {"tool_id": "data.record.insert", "level": "pitfalls"}) if d.get("ok") and len(d.get("pitfalls") or []) >= 3: ok(f"M33 describe(data.record.insert) 返回 {len(d['pitfalls'])} 个坑") else: bad(f"M33 describe 异常: {show(d)}") # ---- M34 不传 dryRun ⇒ 默认演练 ---- sc = invoke("data.record.insert", {"enCode": EN, "data": payload()}) ins = sc.get("data") or {} if sc.get("ok") is True and ins.get("dryRun") is True and ins.get("statements", 0) >= 2: ok(f"M34 insert 不传 dryRun ⇒ 默认演练({ins['statements']} 条 SQL,没落库)") else: bad(f"M34 默认 dryRun 失效: {show(sc)}") # ---- M35 演练真的没写 ---- q = invoke("data.query", {"table": "test_receivable", "columns": ["f_id"], "limit": 10}) if (q.get("data") or {}).get("count") == 0: ok("M35 演练后表里 0 行(默认 dryRun 没有副作用)") else: bad(f"M35 演练却落库了: {show(q)}") # ---- M36 真落库 ---- sc = invoke("data.record.insert", {"enCode": EN, "data": payload(), "dryRun": False}) ins = sc.get("data") or {} rid = ins.get("id") or "" if sc.get("ok") is True and ins.get("dryRun") is False and rid: ok(f"M36 insert(dryRun=false) 落库成功(id={rid[:8]}…,{ins['statements']} 条 SQL)") else: bad(f"M36 落库失败: {show(sc)}") raise SystemExit(0) # ---- M37 查得到(单租户 f_tenant_id='0')---- q = invoke("data.query", {"table": "test_receivable", "limit": 10, "where": [{"column": "f_id", "op": "eq", "value": rid}]}) rows = (q.get("data") or {}).get("rows") or [] row = rows[0] if rows else {} if len(rows) == 1 and row.get("room") == "A-101" and str(row.get("tenantId")) == "0": ok("M37 data.query 查得到(room=A-101,tenantId=0 —— 单租户口径)") else: bad(f"M37 查不到或租户不对: {show(q)}") # ---- M38 子表挂在外键上 ---- def subs_of(main_id): q = invoke("data.query", {"table": "test_details", "limit": 50, "columns": ["f_id", "f_receivableid", "f_month", "f_rent"], "where": [{"column": "f_receivableid", "op": "eq", "value": main_id}]}) return (q.get("data") or {}).get("rows") or [] subs = subs_of(rid) if len(subs) == 2 and all(str(s.get("receivableid")) == rid for s in subs): ok(f"M38 子表 2 行挂在外键上(f_receivableid={rid[:8]}…)") else: bad(f"M38 子表行数/外键不对: {show(subs)}") raise SystemExit(0) keep, drop = subs[0].get("id"), subs[1].get("id") new_key = "smoke-sub-new" # ---- M39 子表差集:保留⇒update、新键⇒insert、缺席⇒delete ---- sc = invoke("data.record.update", { "enCode": EN, "recordId": rid, "dryRun": False, "data": {"F_Room": "A-102", "tableField107": [ {"F_Id": keep, "F_Month": "2026-11", "F_Rent": 1300.5}, {"F_Id": new_key, "F_Month": "2026-12", "F_Rent": 1}, ]}, }) up = sc.get("data") or {} ks = kinds(up) if (sc.get("ok") is True and "updateMain" in ks and "updateSub" in ks and "insertSub" in ks and "hardDelete" in ks): ok(f"M39 update 子表差集三类都生成({', '.join(ks)})") else: bad(f"M39 差集不对: kinds={ks} {show(sc)}") # ---- M40 差集结果落库 ---- subs2 = subs_of(rid) got = {s.get("id") for s in subs2} kept = next((s for s in subs2 if s.get("id") == keep), {}) q = invoke("data.query", {"table": "test_receivable", "limit": 5, "columns": ["f_room"], "where": [{"column": "f_id", "op": "eq", "value": rid}]}) room = ((q.get("data") or {}).get("rows") or [{}])[0].get("room") if (got == {keep, new_key} and drop not in got and str(kept.get("rent")) in ("1300.5", "1300.50") and room == "A-102"): ok("M40 差集落库正确:保留行改了、新行进来、缺席行没了;主表也改了") else: bad(f"M40 差集结果不对: ids={sorted(x for x in got if x)} rent={kept.get('rent')} room={room}") # ---- M41 delete 默认演练 ---- sc = invoke("data.record.delete", {"enCode": EN, "recordId": rid}) still = invoke("data.query", {"table": "test_receivable", "limit": 5, "columns": ["f_id"], "where": [{"column": "f_id", "op": "eq", "value": rid}]}) if (sc.get("ok") is True and (sc.get("data") or {}).get("dryRun") is True and (still.get("data") or {}).get("count") == 1): ok("M41 delete 不传 dryRun ⇒ 默认演练,行还在") else: bad(f"M41 delete 默认值失效: {show(sc)}") # ---- M42 真删 ---- sc = invoke("data.record.delete", {"enCode": EN, "recordId": rid, "dryRun": False}) gone = invoke("data.query", {"table": "test_receivable", "limit": 5, "columns": ["f_id"], "where": [{"column": "f_id", "op": "eq", "value": rid}]}) n_sub = len(subs_of(rid)) if (sc.get("ok") is True and (gone.get("data") or {}).get("count") == 0 and n_sub == 0): ok("M42 delete(dryRun=false) ⇒ 主表查不到、子表也没了(logicalDelete=false ⇒ 物理删)") else: bad(f"M42 删除不彻底: main={show(gone)} subs={n_sub}") # ---- M43 官方 fixture 没声明 unique ⇒ 同值不误拒 ---- a = invoke("data.record.insert", {"enCode": EN, "data": payload([]), "dryRun": False}) b = invoke("data.record.insert", {"enCode": EN, "data": payload([]), "dryRun": False}) if a.get("ok") is True and b.get("ok") is True: ok("M43 官方 fixture 无 unique 控件 ⇒ 同值两行不被误拒(校验不越界)") else: bad(f"M43 误拒了重复值: {show(a)} / {show(b)}") # ---- M44 建表工具:dry-run 出 DDL ---- sc = invoke("schema.table.create", {"enCode": EN}) d = sc.get("data") or {} ddl = "\n".join(d.get("ddl") or []) model = d.get("model") or [] tenant = [f for t in model for f in t.get("fields") or [] if f.get("field") == "f_tenant_id"] if (sc.get("ok") is True and d.get("dryRun") is True and len(d.get("tables") or []) == 2 and "PRIMARY KEY (f_id, f_tenant_id)" in ddl and tenant and tenant[0].get("dataType") == "varchar"): ok("M44 schema.table.create(dryRun) ⇒ 2 张表 + 复合主键 + 回写模型含系统列") else: bad(f"M44 建表演练异常: {show(sc, 200)}") # ---- M45 幂等:表已存在 ⇒ skipped ---- sc = invoke("schema.table.create", {"enCode": EN, "dryRun": False}) d = sc.get("data") or {} if (sc.get("ok") is True and not (d.get("tables") or []) and len(d.get("skipped") or []) == 2): ok("M45 对已存在的表再建 ⇒ skipped 两张(幂等,不重建)") else: bad(f"M45 幂等失效: {show(sc, 200)}") except SystemExit: pass except Exception: bad("阶段 B 异常中断") traceback.print_exc() finally: try: proc.stdin.close() except Exception: pass try: proc.wait(timeout=30) except Exception: proc.kill() err.close() print() print(f"PASS={PASS} FAIL={FAIL}") sys.exit(0 if FAIL == 0 else 1) PY RC_B=$? echo "--------------------" if [ "$RC_A" -eq 0 ] && [ "$RC_B" -eq 0 ]; then echo "全绿 ✅(MCP 工具层契约闭环 + 低代码动态 CRUD)" else echo "有 ❌,按上面修" fi [ "$RC_A" -ne 0 ] && exit "$RC_A" exit "$RC_B"