Files
ssw-tds-test/build/cube_mcp.py
T
ssw-tds-test e4e5faa55e init: ssw-tds-test 可信数据空间部署测试工程
初始提交,沉淀 k8s-tenant-wuguirong 租户下完整可信数据空间
的部署、真机/真数据/真多方验证成果。

包含:
- CLAUDE.md / docs/:工程入口、armv7 glibc 兼容性整改规格、
  ssw-platform#1(armv7 stdout=文件即 exit 100)issue 正文
- build/:TDS 服务端 + tdc-connector 交叉构建脚本、cube 沙箱
  编排、三方拓扑/真机验收脚本、ELF 符号扫描工具
- card/:软卡(softcard)源码与预编译产物(local/amd64/armv7)
- evidence/:验收报告、三方真实结果、armv7 stdout 矩阵复现证据
- .workbuddy/memory/:工作日志

排除:ssw-tds/ 与 ssw-acz7015/ 为上游源码独立仓库(含 .git,
体积大);build/ 下 ctx-*/dist/pglite-* 等可重建中间产物;
build/.env.*、tdc-conn-key/、.tdc-identity-secret 等明文密钥。
2026-11-13 10:19:19 +08:00

174 lines
6.3 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.
#!/usr/bin/env python3
"""cube_mcp.py —— CubeSandbox MCP 直连客户端(Python)。
🔴 为什么不用 MCP 工具直调:`create_sandbox` 的 metadata 在 **MCP schema 里声明是 string,
服务端却要 map** ⇒ 经 MCP 工具层调用必然 422(schema 校验挡前面,改不了)。
直连 JSON-RPC 才能把 map 塞进去。
用法:
python3 build/cube_mcp.py tools
python3 build/cube_mcp.py templates
python3 build/cube_mcp.py list
python3 build/cube_mcp.py create '{"template":"toolchain","timeout":14400,"metadata":{"role":"x"}}'
python3 build/cube_mcp.py call <tool> '<args-json>'
python3 build/cube_mcp.py run <sandbox_id> "shell cmd"
python3 build/cube_mcp.py put <sandbox_id> <local> <remote>
python3 build/cube_mcp.py get <sandbox_id> <remote> <local>
"""
import base64
import json
import os
import subprocess
import sys
import urllib.request
CUBE_URL = os.environ.get("CUBE_URL", "http://192.168.1.30:3000/mcp")
_SESSION = None
_RID = [0]
# 🔴 本机 HTTP 代理会把**内网明文 HTTP** 请求改写(返回 text/html)⇒
# MCP 走 urllib 会拿到非 JSON。必须把内网 host 排除在代理之外。
for _v in ("HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"):
os.environ.pop(_v, None)
os.environ["NO_PROXY"] = "192.168.1.30,192.168.1.26,localhost,127.0.0.1"
os.environ["no_proxy"] = os.environ["NO_PROXY"]
def _key() -> str:
"""取 cube API key。
🔴 不能用 `xop run --secret CUBE_KEY=llm_key`:xop 会对 stdout 的密钥**打码**
(`sk****【xop禁止将密钥泄漏】`)⇒ 拿到的是掩码,不是可用 key。
⇒ 优先从 WorkBuddy 的 MCP 配置读(明文 header,本机可信):
~/.workbuddy/mcp.json → mcpServers.cube-sandbox.headers.X-API-Key
读不到再退回环境变量 CUBE_API_KEY。
"""
env = os.environ.get("CUBE_API_KEY")
if env:
return env.strip()
cfg = os.path.expanduser("~/.workbuddy/mcp.json")
try:
with open(cfg) as fh:
data = json.load(fh)
key = ((data.get("mcpServers") or {}).get("cube-sandbox") or {}).get("headers", {}).get("X-API-Key")
if key:
return key.strip()
except Exception:
pass
raise SystemExit("取不到 cube API key(~/.workbuddy/mcp.json 或 env CUBE_API_KEY)")
# 🔴 urllib 的 ProxyHandler 在 import 时就按 env 建好了,事后 pop 环境变量**没用**。
# 必须显式构造一个「无代理」的 opener。
_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
def rpc(method: str, params: dict):
global _SESSION, _RID
_RID[0] += 1
payload = json.dumps({"jsonrpc": "2.0", "id": _RID[0], "method": method, "params": params}).encode()
headers = {
"X-API-Key": _key(),
"Content-Type": "application/json",
"Accept": "application/json, text/event-stream",
}
if _SESSION:
headers["Mcp-Session-Id"] = _SESSION
req = urllib.request.Request(CUBE_URL, data=payload, headers=headers, method="POST")
with _OPENER.open(req, timeout=1800) as resp:
if not _SESSION:
_SESSION = resp.headers.get("Mcp-Session-Id")
raw = resp.read().decode("utf-8", "replace")
for line in raw.splitlines():
if line.startswith("data: "):
return json.loads(line[6:])
return json.loads(raw) if raw.strip() else {}
def call(tool: str, args: dict):
rpc("initialize", {"protocolVersion": "2024-11-05", "capabilities": {},
"clientInfo": {"name": "cli", "version": "1"}})
return rpc("tools/call", {"name": tool, "arguments": args})
def text_of(resp: dict) -> str:
"""把 MCP 响应里的 content[] 拼成文本。"""
result = resp.get("result") or {}
if result.get("isError"):
return "ERROR: " + "\n".join(c.get("text", "") for c in result.get("content", []))
parts = []
for c in result.get("content", []):
if c.get("type") == "text":
parts.append(c.get("text", ""))
if parts:
return "\n".join(parts)
return json.dumps(result, ensure_ascii=False)
def find_b64(obj):
if isinstance(obj, dict):
for k, v in obj.items():
if k == "content_base64" and isinstance(v, str):
return v
r = find_b64(v)
if r:
return r
elif isinstance(obj, list):
for v in obj:
r = find_b64(v)
if r:
return r
return None
def main():
if len(sys.argv) < 2:
print(__doc__)
return
cmd = sys.argv[1]
if cmd == "tools":
r = rpc("initialize", {"protocolVersion": "2024-11-05", "capabilities": {},
"clientInfo": {"name": "cli", "version": "1"}})
r = rpc("tools/list", {})
for t in (r.get("result") or {}).get("tools", []):
print(" -", t["name"], "|", (t.get("description") or "").replace("\n", " ")[:80])
return
if cmd == "templates":
print(text_of(call("list_templates", {})))
return
if cmd == "list":
print(text_of(call("list_my_sandboxes", {})))
return
if cmd == "create":
args = json.loads(sys.argv[2]) if len(sys.argv) > 2 else {}
print(text_of(call("create_sandbox", args)))
return
if cmd == "call":
print(text_of(call(sys.argv[2], json.loads(sys.argv[3]) if len(sys.argv) > 3 else {})))
return
if cmd == "run":
resp = call("run_command", {"sandbox_id": sys.argv[2], "command": sys.argv[3]})
print(text_of(resp))
return
if cmd == "put":
data = base64.b64encode(open(sys.argv[3], "rb").read()).decode()
resp = call("put_file", {"sandbox_id": sys.argv[2], "path": sys.argv[4],
"content_base64": data})
print(text_of(resp))
return
if cmd == "get":
resp = call("get_file", {"sandbox_id": sys.argv[2], "path": sys.argv[3]})
b64 = find_b64(resp)
if b64:
blob = base64.b64decode(b64)
open(sys.argv[4], "wb").write(blob)
print(f"OK saved {sys.argv[4]} {len(blob)} bytes")
else:
print(json.dumps(resp, ensure_ascii=False)[:800])
return
print(__doc__)
if __name__ == "__main__":
main()