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

133 lines
5.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""MCP 接入回归(2026-10-15;2026-10-27 主人重定义:只读 5 工具):
默认关 → /mcp 403;打开(自动生成令牌)→ 无令牌 401、带令牌 initialize/tools/list/tools/call
可用;工具集=只读 5 件套(无任何写/导出工具);关闭 → 再断;/api/mcp/status 反映状态。
"""
import json
import sqlite3
import api_harness as H
from api_harness import post, server # noqa: F401
NEW_TOOLS = {"bills_query", "lme_prices", "market_info_prices",
"recent_review_query", "attachment_download"}
def _mcp(server, body, token=None):
headers = {"Content-Type": "application/json"}
if token:
headers["Authorization"] = "Bearer " + token
return server["client"].post("/mcp", content=json.dumps(body), headers=headers)
def _rpc(mid, method, params=None):
b = {"jsonrpc": "2.0", "id": mid, "method": method}
if params is not None:
b["params"] = params
return b
def _call(server, token, mid, name, args):
r = _mcp(server, _rpc(mid, "tools/call", {"name": name, "arguments": args}), token)
assert r.status_code == 200, r.text[:200]
j = r.json()
assert j["result"]["isError"] is False, j
return json.loads(j["result"]["content"][0]["text"])
def _call_err(server, token, mid, name, args):
r = _mcp(server, _rpc(mid, "tools/call", {"name": name, "arguments": args}), token)
j = r.json()
return json.loads(j["result"]["content"][0]["text"])
def test_mcp_switch_lifecycle(server):
# 默认关:JSON-RPC 也被 403 挡住
r = _mcp(server, _rpc(1, "tools/list"))
assert r.status_code == 403 and "未开启" in r.text, r.text[:200]
# 打开(自动生成令牌)
t = post(server, "/api/admin/mcp", {"enabled": True})
assert t["ok"] is True and t["enabled"] is True and len(t["token"]) == 32, t
# 无令牌 → 401
r = _mcp(server, _rpc(1, "initialize", {"protocolVersion": "2025-06-18"}))
assert r.status_code == 401, r.text[:200]
# initialize
r = _mcp(server, _rpc(1, "initialize", {"protocolVersion": "2025-06-18"}), t["token"])
assert r.status_code == 200, r.text[:200]
j = r.json()
assert j["result"]["serverInfo"]["name"] == "造价审核"
# 通知(无 id)→ 202 空体
r = _mcp(server, {"jsonrpc": "2.0", "method": "notifications/initialized"}, t["token"])
assert r.status_code == 202, r.status_code
# 关闭 → 再断
t2 = post(server, "/api/admin/mcp", {"enabled": False})
assert t2["enabled"] is False
r = _mcp(server, _rpc(9, "tools/list"), t["token"])
assert r.status_code == 403
# 状态接口
st = server["client"].get("/api/mcp/status").json()
assert st["enabled"] is False and st["endpoint"] == "/mcp" and st["tools"] == 5
def test_mcp_readonly_toolset(server):
t = post(server, "/api/admin/mcp", {"enabled": True})
tok = t["token"]
try:
# 工具集 = 只读 5 件套,一个不多一个不少(旧写工具全部移除)
r = _mcp(server, _rpc(2, "tools/list"), tok)
names = {x["name"] for x in r.json()["result"]["tools"]}
assert names == NEW_TOOLS, names
for gone in ("bill_op", "norm_op", "bill_adopt", "lme_merge", "session_delete",
"session_export", "api_schema", "upload_file", "project_open"):
assert gone not in names
# 范围守卫:keyword/batch_id 都不给 → 拒绝
for tool in ("bills_query", "lme_prices", "market_info_prices"):
out = _call_err(server, tok, 3, tool, {})
assert out.get("ok") is False and "keyword" in out.get("msg", ""), (tool, out)
# 最近审核:无参 → 会话列表结构
out = _call(server, tok, 4, "recent_review_query", {})
assert out["ok"] is True and isinstance(out["rows"], list)
# 带错误 type → 拒绝
out = _call_err(server, tok, 5, "recent_review_query", {"session_id": 1, "type": "x"})
assert out.get("ok") is False
# 附件下载:参数不合法 → 拒绝
out = _call_err(server, tok, 6, "attachment_download", {"type": "xx", "id": 1})
assert out.get("ok") is False
# 真实附件路径(无绑定)→ 拒绝且不抛异常
out = _call_err(server, tok, 7, "attachment_download", {"type": "bill", "id": 1})
assert out.get("ok") is False
# 未知工具 → -32602
r = _mcp(server, _rpc(8, "tools/call", {"name": "nope", "arguments": {}}), tok)
assert r.json()["error"]["code"] == -32602
finally:
post(server, "/api/admin/mcp", {"enabled": False})
def test_mcp_query_matches_db(server):
"""market_info_prices 与库内事实一致(数据自证,不写死数字)。"""
t = post(server, "/api/admin/mcp", {"enabled": True})
tok = t["token"]
try:
con = sqlite3.connect(server["db"])
row = con.execute("SELECT id FROM batches WHERE kind IN ('info','market') "
"AND id IN (SELECT DISTINCT batch_id FROM prices) LIMIT 1").fetchone()
if row:
bid = row[0]
want = con.execute("SELECT COUNT(*) FROM prices WHERE batch_id=?", (bid,)).fetchone()[0]
out = _call(server, tok, 1, "market_info_prices", {"batch_id": bid, "limit": 200})
got = len(out["rows"])
assert out["ok"] and got == min(want, 200), (want, got)
if out["rows"]:
for k in ("Code", "Name", "Unit", "NoTaxPrice", "TaxPrice"):
assert k in out["rows"][0], out["rows"][0].keys()
con.close()
finally:
post(server, "/api/admin/mcp", {"enabled": False})
def test_schema_has_mcp_group(server):
r = server["client"].get("/api/schema").json()
assert "MCP 接入" in r["groups"]
paths = [x["path"] for x in r["groups"]["MCP 接入"]]
assert "/mcp" in paths and "/api/mcp/status" in paths