Files
ssw-tds-test/build/cube_mcp.py
T
ssw-tds-test 993a2aa538 feat(cube): 站点/接入点进 CubeSandbox + TDS 平台自包含部署
CubeSandbox 内真部署「1 站点 + 2 接入点」,并把 TDS 平台本身搬进沙箱,
切断对外部 k8s 的依赖。

- 站点 = mpc control-plane:3020 + hostd:3010;接入点 = tdc-connector:30000
- 站点沙箱内 docker + compose 拉起 db/redis/backend/frontend,
  TDS 自带库与 CA,业务数据与现网一致(22 连接器 / 243 账号 / 77 表)
- e2e 验收:站点/接入点 PASS=17/0;TDS 进沙箱 PASS=9/0(两轮稳定);
  两个接入点对沙箱内 TDS 均 ONLINE/ENV_COMPLIANT/READY

关键坑(均实测,已写入文档):
- 沙箱 cgroup2 只读 ⇒ 只能 vfs;vfs 每层全量拷贝 ⇒ 镜像必须 squash 单层
  (save+import 会丢 /bin/sh,须 create+export+import)
- 镜像默认 USER=ssw ⇒ backend 需 root 起、建 log 目录后 setpriv 切回
- containerd 僵尸让 dockerd 存活探测恒通过不了 ⇒ 用独立 containerd
- 换 TDS 实例必须重建设备证书:platform-ca 首启自生成,旧 CA 签的证书
  openssl verify 报 invalid CA certificate

登录口令加密密钥改为环境变量注入(原为硬编码,不入库)。

文档:docs/cube-sandbox-site-connector-2026-11-16.md、
      docs/tds-in-cube-sandbox-2026-11-16.md
2026-11-16 10:57:18 +08:00

181 lines
6.5 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
# ── 控制面便捷子命令 ──
if cmd == "sb-get":
print(text_of(call("get_sandbox", {"sandbox_id": sys.argv[2]})))
return
if cmd == "sb-kill":
print(text_of(call("kill_sandbox", {"sandbox_id": sys.argv[2]})))
return
print(__doc__)
if __name__ == "__main__":
main()