vod-devkit 0.4.3 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.en.md +5 -4
  3. package/README.md +44 -9
  4. package/bin/vod-devkit +143 -111
  5. package/contract/tools.schema.json +38 -1
  6. package/integrations/codex/host.json +20 -0
  7. package/integrations/dsh/host.json +15 -0
  8. package/integrations/hermes/host.json +20 -0
  9. package/integrations/opencode/command/vod-doctor.md +10 -0
  10. package/integrations/opencode/host.json +28 -0
  11. package/package.json +10 -10
  12. package/plugins/vod-devkit/.codex-plugin/plugin.json +1 -1
  13. package/plugins/vod-devkit/build-info.json +3 -3
  14. package/plugins/vod-devkit/skills/vod-core/SKILL.md +35 -15
  15. package/plugins/vod-devkit/vod_mcp/__init__.py +1 -1
  16. package/plugins/vod-devkit/vod_mcp/config_forms.py +154 -0
  17. package/plugins/vod-devkit/vod_mcp/guardrails.py +25 -0
  18. package/plugins/vod-devkit/vod_mcp/hosts.py +80 -0
  19. package/plugins/vod-devkit/vod_mcp/packs.py +17 -3
  20. package/plugins/vod-devkit/vod_mcp/remote_app.py +100 -0
  21. package/plugins/vod-devkit/vod_mcp/server.py +30 -15
  22. package/plugins/vod-devkit/vod_mcp/skills_registry.py +124 -0
  23. package/plugins/vod-devkit/vod_mcp/tools.py +70 -9
  24. package/plugins/vod-devkit/vod_mcp/transport_remote.py +289 -0
  25. package/plugins/vod-devkit/vod_mcp/update_check.py +105 -0
  26. package/skills/vod-core/SKILL.md +35 -15
  27. package/vod_mcp/__init__.py +1 -1
  28. package/vod_mcp/config_forms.py +154 -0
  29. package/vod_mcp/guardrails.py +25 -0
  30. package/vod_mcp/hosts.py +80 -0
  31. package/vod_mcp/packs.py +17 -3
  32. package/vod_mcp/remote_app.py +100 -0
  33. package/vod_mcp/server.py +30 -15
  34. package/vod_mcp/skills_registry.py +124 -0
  35. package/vod_mcp/tools.py +70 -9
  36. package/vod_mcp/transport_remote.py +289 -0
  37. package/vod_mcp/update_check.py +105 -0
@@ -12,7 +12,7 @@ from pathlib import Path
12
12
  # Hermes 等宿主出于安全过滤环境变量,stdio 子进程只继承白名单)
13
13
  sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
14
14
 
15
- from vod_mcp import packs, policy as policy_mod, tools # noqa: E402
15
+ from vod_mcp import guardrails, packs, tools # noqa: E402
16
16
 
17
17
  _PROTOCOL_VERSION = "2025-06-18"
18
18
  _client_info = {}
@@ -26,12 +26,16 @@ def _error(req_id, code, message):
26
26
  return {"jsonrpc": "2.0", "id": req_id, "error": {"code": code, "message": message}}
27
27
 
28
28
 
29
- def handle(message: dict) -> dict | None:
29
+ def handle(message: dict, client_info: dict | None = None) -> dict | None:
30
+ """JSON-RPC 分派(两面共用:stdio 逐行调用;HTTP 面每请求调用一次)。
31
+
32
+ client_info 由传输层提供(HTTP 面=固定标识 + 认证形态,stdio 面=握手自报)。
33
+ """
30
34
  method = message.get("method", "")
31
35
  req_id = message.get("id")
32
36
  if method == "initialize":
33
37
  global _client_info
34
- _client_info = (message.get("params") or {}).get("clientInfo") or {}
38
+ _client_info = client_info or (message.get("params") or {}).get("clientInfo") or {}
35
39
  return _result(req_id, {
36
40
  "protocolVersion": _PROTOCOL_VERSION,
37
41
  "capabilities": {"tools": {}},
@@ -57,18 +61,9 @@ def handle(message: dict) -> dict | None:
57
61
  params = message.get("params") or {}
58
62
  name = params.get("name") or ""
59
63
  args = params.get("arguments") or {}
60
- pol = policy_mod.load_policy()
61
- verdict, msg = policy_mod.decide(
62
- policy_mod.check_tool_call(pol, name, args) if name else [])
63
- if verdict == "deny":
64
- return _error(req_id, -32010, f"[guard:deny] {msg}")
65
- if verdict == "confirm":
66
- return _error(req_id, -32011, f"[guard:confirm] {msg}")
67
- text_hits = policy_mod.check_text(
68
- pol, json.dumps(policy_mod.guard_scope(args), ensure_ascii=False))
69
- if text_hits:
70
- return _error(req_id, -32010,
71
- f"[guard:deny] {policy_mod.decide(text_hits)[1]}")
64
+ verdict, msg, code = guardrails.check(name, args)
65
+ if verdict != "allow":
66
+ return _error(req_id, code, msg)
72
67
  try:
73
68
  out = tools.dispatch(name, args, _client_info)
74
69
  return _result(req_id, {
@@ -84,6 +79,16 @@ def handle(message: dict) -> dict | None:
84
79
 
85
80
 
86
81
  def main():
82
+ import argparse
83
+ ap = argparse.ArgumentParser(prog="vod-mcp-server",
84
+ description="vod-devkit MCP server(默认 stdio)")
85
+ ap.add_argument("--transport", choices=["stdio", "remote"], default="stdio",
86
+ help="stdio(默认,宿主拉起子进程);remote(Streamable HTTP,"
87
+ "一个进程服务多个 agent)")
88
+ ap.add_argument("--port", type=int, default=9528, help="remote 端口(默认 9528)")
89
+ ap.add_argument("--host", default="127.0.0.1", help="remote 绑定地址(默认回环)")
90
+ args, _unknown = ap.parse_known_args()
91
+
87
92
  # 启动自诊(排障:写 /tmp,宿主过滤环境变量时可观察实际 env)
88
93
  try:
89
94
  tools._ensure_first_boot() # D-key-guard-3①:首启标记+构建机残留清理(preset 兜底)
@@ -93,6 +98,16 @@ def main():
93
98
  f"VOD_PACKS={os.environ.get('VOD_PACKS')!r} "
94
99
  f"distribution={tools._distribution()} "
95
100
  f"cwd={os.getcwd()}")
101
+ if args.transport == "remote":
102
+ try:
103
+ from vod_mcp import transport_remote
104
+ except ImportError as e: # 零依赖红线:远程面才需要 SDK
105
+ print("[vod-devkit] 远程面需要官方 MCP SDK:\n"
106
+ " pip install 'vod-devkit[remote]' # 或 pip install 'mcp>=1.0'\n"
107
+ f"(stdio 形态不需要任何第三方依赖;导入失败:{e})", file=sys.stderr)
108
+ sys.exit(2)
109
+ sys.exit(transport_remote.serve(args.host, args.port))
110
+
96
111
  for line in sys.stdin:
97
112
  line = line.strip()
98
113
  if not line:
@@ -0,0 +1,124 @@
1
+ """领域技能披露(MCP 侧,devkit 双轨模型的第二轨)。
2
+
3
+ 为什么需要第二轨:领域规则技能(分类/评分)目前靠"安装器把 SKILL.md 拷进
4
+ 宿主的原生技能目录"分发,而各宿主目录是独立副本——本仓实锤过多次漂移
5
+ (skillHashes 只能事后发现,装完就分叉)。disclosure 让技能文本成为
6
+ **server data**:任何 MCP 宿主(包括没有原生技能目录的宿主,如 dsh headless)
7
+ 都能按需取到与包内完全一致的规则全文,且改规则不必碰四份宿主拷贝。
8
+
9
+ 分工(与 devkit 一致):
10
+ - 元技能(vod-core / vod-feedback-collect)仍原生安装——它们的价值在
11
+ 宿主侧自动激活(触发词命中),走工具调用会丢掉激活时机。
12
+ - 领域规则技能由本模块披露,归属 knowledge pack:pack 被裁剪时拒绝并
13
+ 给恢复指引,不静默返回空。
14
+ """
15
+ import re
16
+ from pathlib import Path
17
+
18
+ SKILLS_ROOT = Path(__file__).resolve().parent.parent / "skills"
19
+
20
+ # 技能 → 归属 pack(core 常驻;knowledge 可裁剪)
21
+ SKILL_PACK = {
22
+ "vod-problem-classification-rules": "knowledge",
23
+ "vod-scoring-rules": "knowledge",
24
+ }
25
+ META_SKILLS = ("vod-core", "vod-feedback-collect")
26
+
27
+ _BODY_CAP = 12000 # 单技能全文上限(超出截断并标注,不静默丢内容)
28
+
29
+ # 契约纪律:披露内容里的内部机制词不因"技能是内部文档"而豁免——
30
+ # 这些文本会进模型上下文并可能被复述给终端用户。
31
+ _INTERNAL_WORDS = re.compile(r"(t_vod_[a-z_]+|jdbc:|mysql://)")
32
+
33
+
34
+ class SkillError(Exception):
35
+ """披露失败(未知技能/未启用 pack)——调用方转成 MCP error 对象。"""
36
+
37
+ def __init__(self, message: str, code: int = -32010):
38
+ super().__init__(message)
39
+ self.code = code
40
+
41
+
42
+ def _frontmatter(text: str) -> dict:
43
+ """取 SKILL.md 的 YAML frontmatter 键值(只认一层,不引 yaml 依赖)。"""
44
+ out = {}
45
+ if not text.startswith("---"):
46
+ return out
47
+ body = text.split("---", 2)[1] if text.count("---") >= 2 else ""
48
+ for line in body.splitlines():
49
+ if ":" not in line:
50
+ continue
51
+ k, v = line.split(":", 1)
52
+ out[k.strip()] = v.strip().strip("'\"")
53
+ return out
54
+
55
+
56
+ def _skill_dirs() -> list:
57
+ if not SKILLS_ROOT.is_dir():
58
+ return []
59
+ return sorted(p for p in SKILLS_ROOT.iterdir()
60
+ if p.is_dir() and (p / "SKILL.md").exists())
61
+
62
+
63
+ def _server_face() -> bool:
64
+ from vod_mcp import tools
65
+ return bool(tools._SERVER_FACE.get())
66
+
67
+
68
+ def list_skills(params: dict) -> dict:
69
+ """列出可披露的技能(元技能一并列出,标出 pack 与是否原生安装)。"""
70
+ from vod_mcp import packs
71
+ enabled = set(packs.enabled_packs())
72
+ items = []
73
+ for d in _skill_dirs():
74
+ text = (d / "SKILL.md").read_text(encoding="utf-8")
75
+ meta = _frontmatter(text)
76
+ pack = SKILL_PACK.get(d.name, "core")
77
+ items.append({
78
+ "name": d.name,
79
+ "pack": pack,
80
+ "enabled": pack in enabled,
81
+ "native": d.name in META_SKILLS,
82
+ "description": meta.get("description", ""),
83
+ "chars": len(text),
84
+ })
85
+ return {"skills": items, "packs": sorted(enabled),
86
+ "note": "领域规则技能用 vod_retrieve_skill 取全文;元技能由宿主原生"
87
+ "加载,只在本工具里列名以便路由。"}
88
+
89
+
90
+ def retrieve_skill(params: dict) -> dict:
91
+ """按名取技能全文(含 frontmatter + 正文)。owner-pack 裁剪即拒绝。"""
92
+ from vod_mcp import packs
93
+ name = (params or {}).get("name") or ""
94
+ name = name.strip()
95
+ if not name:
96
+ raise SkillError("name 必填(先用 vod_list_skills 查名字)", -32602)
97
+ d = SKILLS_ROOT / name
98
+ if not re.fullmatch(r"[a-z0-9][a-z0-9-]{2,63}", name) or not (d / "SKILL.md").exists():
99
+ known = [p.name for p in _skill_dirs()]
100
+ raise SkillError(f"未知技能 {name!r};可用:{'、'.join(known)}", -32602)
101
+ pack = SKILL_PACK.get(name, "core")
102
+ enabled = set(packs.enabled_packs())
103
+ if pack not in enabled:
104
+ raise SkillError(
105
+ f"技能 {name} 属于 {pack} pack,当前安装未启用(VOD_PACKS="
106
+ f"{','.join(sorted(enabled))})——如需启用,重跑 install 并带上 "
107
+ f"--packs {','.join(sorted(enabled | {pack}))}", -32010)
108
+ text = (d / "SKILL.md").read_text(encoding="utf-8")
109
+ truncated = False
110
+ if len(text) > _BODY_CAP:
111
+ text = text[:_BODY_CAP]
112
+ truncated = True
113
+ if _INTERNAL_WORDS.search(text):
114
+ # 不拦内容(规则文本是内部资产),但给出复述纪律提醒
115
+ note = "注意:本技能含内部表名/连接串字样,向终端用户复述时不要照抄。"
116
+ else:
117
+ note = ""
118
+ out = {"name": name, "pack": pack, "chars": len(text), "truncated": truncated,
119
+ "content": text, "note": note}
120
+ # 服务面(HTTP)不发布服务器本机路径——对齐 devkit「remote 不给 skillRoot」:
121
+ # 未鉴权的远程面不该把自己的安装路径交出去。
122
+ if not _server_face():
123
+ out["path"] = str(d / "SKILL.md")
124
+ return out
@@ -9,6 +9,7 @@ ExternalApiKeyFilter Bearer)。
9
9
  POST …/external/voice/submit(现有接口,提交即分析)
10
10
  POST …/external/token(VOD-KEY,零字段匿名令牌)
11
11
  """
12
+ import contextvars
12
13
  import json
13
14
  import os
14
15
  import stat
@@ -19,6 +20,22 @@ from pathlib import Path
19
20
  from vod_mcp import provenance
20
21
  from vod_mcp import DEFAULT_JAVA_BASE
21
22
 
23
+ # ── 服务面(HTTP 传输)上下文 ────────────────────────────────────────────
24
+ # 每个请求由 transport_remote 注入,逐请求隔离(contextvars 随 asyncio 任务/
25
+ # 线程传播),因此并发客户端不会互相覆盖 key。
26
+ # 身份:stdio 面=装在哪台机器;HTTP 面=这个请求带了谁的 key。
27
+ # 插件自己不产生身份(不代签、不落盘),只把请求头的 Bearer 转成引擎鉴权。
28
+ _REQ_KEY = contextvars.ContextVar("vod_req_key", default=None)
29
+ _SERVER_FACE = contextvars.ContextVar("vod_server_face", default=False)
30
+
31
+
32
+ def _eff_key(explicit=None) -> str:
33
+ """当前生效的 key:显式参数 > 请求头(HTTP 面)> env/runtime(stdio 面)。"""
34
+ if explicit is not None:
35
+ return explicit
36
+ return _REQ_KEY.get() or JAVA_KEY
37
+
38
+
22
39
  # D-followup-impl-2:追问拒答语义词集(答"没有"类=两字段不上送)。
23
40
  # 契约话术承诺了"不方便回复没有",客户端必须技术兜底——模型不守话术纪律时
24
41
  # 键集合仍零漂移(test_followup_declined_or_blank_omitted 回归锁)。
@@ -88,7 +105,7 @@ def _load_meta(force: bool = False) -> dict:
88
105
  "catalog": cache["data"].get("productCatalog") or [],
89
106
  "stale": False, "source": "cache"}
90
107
  try:
91
- out = _http("GET", _META_PATH, None, base=JAVA_BASE, key=JAVA_KEY, timeout=10)
108
+ out = _http("GET", _META_PATH, None, base=JAVA_BASE, key=_eff_key(), timeout=10)
92
109
  data = out.get("data") or {}
93
110
  if isinstance(data.get("products"), list) and data["products"]:
94
111
  _save_runtime({"meta_cache": {"fetchedAt": int(now), "data": data}})
@@ -304,7 +321,7 @@ def _flush_pending(product):
304
321
  if product:
305
322
  body["product"] = product
306
323
  try:
307
- out = _http("POST", _SUBMIT_HOARDING, body, base=JAVA_BASE, key=JAVA_KEY)
324
+ out = _http("POST", _SUBMIT_HOARDING, body, base=JAVA_BASE, key=_eff_key())
308
325
  ids = (out or {}).get("voiceIds") or ((out or {}).get("data") or {}).get("voiceIds")
309
326
  if ids is None:
310
327
  failed += 1
@@ -434,9 +451,17 @@ def submit_voices(params: dict, client_info: dict | None = None,
434
451
  }
435
452
  if product:
436
453
  body["product"] = product
437
- out = _http("POST", _EXISTING_SUBMIT, body, base=JAVA_BASE, key=JAVA_KEY)
454
+ out = _http("POST", _EXISTING_SUBMIT, body, base=JAVA_BASE, key=_eff_key())
438
455
  return vid, (out.get("data") or {}).get("taskId")
439
456
 
457
+ # 服务面(HTTP):身份只能来自请求头。缺 key 时 fail fast——不先打引擎再
458
+ # 靠 401 兜底(那会多一次无意义外呼,且引擎若宽容 200 就绕过了守卫)。
459
+ if _SERVER_FACE.get() and not _eff_key():
460
+ raise ToolError(
461
+ "服务面(HTTP 传输)不代签身份:请在本请求带上 Authorization: Bearer "
462
+ "<VOD key>(插件只搬运身份,不产生身份;落库与配额都在服务端)",
463
+ code=-32012)
464
+
440
465
  # ---- 主路径:囤积端点批式提交 ----
441
466
  body = {"voices": [_hoard_voice(v, content) for _, v, content in items]}
442
467
  if product: # 无归因不带 product(引擎 UNKNOWN 档),不本地拦截
@@ -444,18 +469,26 @@ def submit_voices(params: dict, client_info: dict | None = None,
444
469
  out = None
445
470
  fallback = False
446
471
  try:
447
- out = _http("POST", _SUBMIT_HOARDING, body, base=JAVA_BASE, key=JAVA_KEY)
472
+ out = _http("POST", _SUBMIT_HOARDING, body, base=JAVA_BASE, key=_eff_key())
448
473
  except ToolError as ex:
449
474
  if ex.code == 404:
450
475
  fallback = True # 囤积端点未部署 → 落到下方 legacy 回落
451
- elif not JAVA_KEY or ex.code == -32012:
476
+ elif not _eff_key() or ex.code == -32012:
477
+ if _SERVER_FACE.get():
478
+ # 服务面(HTTP):不代签身份。匿名令牌按设备锚点签发,一进程
479
+ # 一锚点会把配额/声量/归因全搅在一起(服务端多用户形态的
480
+ # 已拍板口径:formal/host key + 按请求透传)。
481
+ raise ToolError(
482
+ "服务面(HTTP 传输)不代签身份:请在本请求带上 "
483
+ "Authorization: Bearer <VOD key>,或改用 stdio 形态的匿名链",
484
+ code=-32012)
452
485
  if _explicit_key():
453
- _raise_explicit_key_rejected(JAVA_KEY)
486
+ _raise_explicit_key_rejected(_eff_key())
454
487
  # 缺 key/匿名令牌失效 → 零字段匿名令牌 → 落 runtime.json → 重试一次
455
488
  token = _acquire_anon_token_or_raise()
456
489
  JAVA_KEY = token
457
490
  _save_runtime({"java_key": token, "token_tier": "anonymous"})
458
- out = _http("POST", _SUBMIT_HOARDING, body, base=JAVA_BASE, key=JAVA_KEY)
491
+ out = _http("POST", _SUBMIT_HOARDING, body, base=JAVA_BASE, key=_eff_key())
459
492
  else:
460
493
  raise # 网络/413 等如实上抛
461
494
  if not fallback:
@@ -503,9 +536,13 @@ def submit_voices(params: dict, client_info: dict | None = None,
503
536
  accepted += 1
504
537
  voice_ids.append(vid)
505
538
  task_ids.append(None)
506
- elif (not JAVA_KEY or e.code == -32012) and not voice_ids:
539
+ elif (not _eff_key() or e.code == -32012) and not voice_ids:
540
+ if _SERVER_FACE.get():
541
+ rejected.append({"index": i, "reason":
542
+ "服务面(HTTP 传输)不代签身份:请带 Authorization: Bearer <VOD key>"})
543
+ continue
507
544
  if _explicit_key():
508
- _raise_explicit_key_rejected(JAVA_KEY)
545
+ _raise_explicit_key_rejected(_eff_key())
509
546
  # 零字段匿名令牌:缺 key/401 → 自动取令牌 → 落 runtime.json → 重试一次
510
547
  token = _acquire_anon_token_or_raise()
511
548
  JAVA_KEY = token
@@ -905,7 +942,31 @@ def _sha256(s: str) -> str:
905
942
  import hashlib
906
943
  return hashlib.sha256(s.encode()).hexdigest()
907
944
 
945
+ def check_update(params: dict, client_info: dict | None = None) -> dict:
946
+ from vod_mcp import update_check as uc
947
+ return uc.check(params)
948
+
949
+
950
+ def list_skills(params: dict, client_info: dict | None = None) -> dict:
951
+ from vod_mcp import skills_registry as sr
952
+ try:
953
+ return sr.list_skills(params)
954
+ except sr.SkillError as e:
955
+ raise ToolError(str(e), code=e.code)
956
+
957
+
958
+ def retrieve_skill(params: dict, client_info: dict | None = None) -> dict:
959
+ from vod_mcp import skills_registry as sr
960
+ try:
961
+ return sr.retrieve_skill(params)
962
+ except sr.SkillError as e:
963
+ raise ToolError(str(e), code=e.code)
964
+
965
+
908
966
  _HANDLERS = {
967
+ "vod_check_update": check_update,
968
+ "vod_list_skills": list_skills,
969
+ "vod_retrieve_skill": retrieve_skill,
909
970
  "vod_submit_voices": submit_voices,
910
971
  "vod_list_submitted": list_submitted,
911
972
  "vod_devkit_info": devkit_info,
@@ -0,0 +1,289 @@
1
+ """远程面 HTTP 外壳(Streamable HTTP):形态逐项对齐 huaweicloud-devkit。
2
+
3
+ devkit 的契约(mcp-server-remote.ts + test/remote-mcp-server.test.ts 实测),
4
+ 本文件照抄行为,不另发明:
5
+
6
+ POST → Streamable HTTP(官方 SDK,stateless + json_response)
7
+ GET → 405 Allow: POST, OPTIONS("the shell keeps the method filter")
8
+ OPTIONS → 204 + Access-Control-Allow-Origin: *
9
+ 通知(无 id)→ 202
10
+ 坏 JSON → 400 -32700
11
+ 默认 127.0.0.1:9528,--port/--host 可改;无内建鉴权
12
+
13
+ 实现手段的差异(唯一):devkit 用 @modelcontextprotocol/sdk + node:http 直接
14
+ 拿 WebStandard Request;Python SDK 的入口是 ASGI(StreamableHTTPSessionManager
15
+ .handle_request(scope, receive, send)),而本仓不引入 ASGI 服务器,所以这里
16
+ 用一个小的 ASGI 适配层把 stdlib http.server 的请求转成 scope/receive/send。
17
+ 协议处理仍然全部在 SDK 里,与 devkit 同源。
18
+
19
+ 身份:请求头 Authorization: Bearer <key> 逐请求注入(见 tools._REQ_KEY),
20
+ 不落盘、不进 env;插件不代签身份——缺 key 时 submit 结构化拒绝。
21
+ """
22
+ import asyncio
23
+ import json
24
+ import sys
25
+ import threading
26
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
27
+
28
+ DEFAULT_HOST = "127.0.0.1"
29
+ DEFAULT_PORT = 9528
30
+ MAX_BODY = 4 * 1024 * 1024
31
+ LOOPBACK = ("127.0.0.1", "localhost", "::1")
32
+
33
+
34
+ class RemoteRuntime:
35
+ """持有 asyncio 事件循环 + SDK session manager 的生命周期。"""
36
+
37
+ def __init__(self, host: str, port: int):
38
+ from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
39
+ from vod_mcp.remote_app import build_server
40
+
41
+ self.host, self.port = host, port
42
+ self._loop = asyncio.new_event_loop()
43
+ # stateless + json_response:与 devkit 的 WebStandardStreamableHTTPServerTransport
44
+ # ({sessionIdGenerator: undefined, enableJsonResponse: true}) 等价
45
+ self.manager = StreamableHTTPSessionManager(
46
+ app=build_server(remote=True), json_response=True, stateless=True)
47
+ self._ready = threading.Event()
48
+ self._thread = threading.Thread(target=self._serve_loop, daemon=True)
49
+
50
+ def _serve_loop(self):
51
+ asyncio.set_event_loop(self._loop)
52
+
53
+ async def run():
54
+ async with self.manager.run():
55
+ self._ready.set()
56
+ await asyncio.Event().wait() # 直到进程退出
57
+
58
+ self._loop.run_until_complete(run())
59
+
60
+ def start(self):
61
+ self._thread.start()
62
+ if not self._ready.wait(timeout=15):
63
+ raise RuntimeError("MCP session manager 启动超时")
64
+
65
+ def request(self, scope: dict, body: bytes, sink, timeout: float = 60) -> None:
66
+ """把一次 HTTP 请求投递进事件循环,响应**逐块下沉**给 sink。
67
+
68
+ sink.start(status, headers) / sink.body(bytes) / sink.end()。
69
+ 逐块而不是攒全再写:devkit 的 shell 也是 `for await (chunk of
70
+ response.body) res.write(chunk)`——SSE 这种长响应攒全再写等于把流式
71
+ 语义废掉(客户端一个字节都看不到,直到响应结束)。
72
+ """
73
+ state = {"body_sent": False}
74
+
75
+ async def receive():
76
+ if state["body_sent"]:
77
+ return {"type": "http.disconnect"}
78
+ state["body_sent"] = True
79
+ return {"type": "http.request", "body": body, "more_body": False}
80
+
81
+ async def send(message):
82
+ if message["type"] == "http.response.start":
83
+ headers = [(k.decode() if isinstance(k, bytes) else k,
84
+ v.decode() if isinstance(v, bytes) else v)
85
+ for k, v in message.get("headers", [])]
86
+ sink.start(message["status"], headers)
87
+ elif message["type"] == "http.response.body":
88
+ chunk = message.get("body") or b""
89
+ if chunk:
90
+ sink.body(chunk)
91
+
92
+ async def run():
93
+ try:
94
+ await self.manager.handle_request(scope, receive, send)
95
+ finally:
96
+ sink.end()
97
+
98
+ fut = asyncio.run_coroutine_threadsafe(run(), self._loop)
99
+ try:
100
+ fut.result(timeout=timeout)
101
+ except Exception as e: # 传输层异常:写 stderr 并让外壳答 500/断连
102
+ sys.stderr.write(f"remote transport error: {e}\n")
103
+ raise
104
+
105
+
106
+ def _normalize_headers(handler) -> list:
107
+ """把请求头规范到 SDK 能接的形态——逐条照 devkit 的外壳做法。
108
+
109
+ devkit 在构造 `Request` 前做两件事(mcp-server-remote.ts):
110
+ ① 缺 content-type 或 `text/plain*` → 覆盖成 `application/json`
111
+ (裸 `curl -d` 与 undici 默认体不因此吃 415);
112
+ ② 缺 accept → 补 `application/json, text/event-stream`
113
+ (否则 SDK 的 accept 协商会 406)。
114
+ 这两条不是"宽松",是让最小客户端也能跑通同一份契约。
115
+ """
116
+ headers = []
117
+ ctype = (handler.headers.get("Content-Type") or "").strip()
118
+ if not ctype or ctype.lower().startswith("text/plain"):
119
+ ctype = "application/json"
120
+ seen_ctype = False
121
+ for k, v in handler.headers.items():
122
+ lk = k.lower()
123
+ if lk == "content-type":
124
+ seen_ctype = True
125
+ headers.append((b"content-type", ctype.encode()))
126
+ continue
127
+ headers.append((lk.encode(), str(v).encode()))
128
+ if not seen_ctype:
129
+ headers.append((b"content-type", ctype.encode()))
130
+ if not handler.headers.get("Accept"):
131
+ headers.append((b"accept", b"application/json, text/event-stream"))
132
+ return headers
133
+
134
+
135
+ def _scope(handler, body: bytes) -> dict:
136
+ from urllib.parse import urlsplit
137
+ parts = urlsplit(handler.path)
138
+ return {
139
+ "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1",
140
+ "method": handler.command, "scheme": "http",
141
+ "path": parts.path or "/", "raw_path": (parts.path or "/").encode(),
142
+ "query_string": (parts.query or "").encode(),
143
+ "headers": _normalize_headers(handler),
144
+ "client": (handler.client_address[0], handler.client_address[1]),
145
+ "server": (handler.server.server_address[0], handler.server.server_address[1]),
146
+ "root_path": "",
147
+ }
148
+
149
+
150
+ class _StreamSink:
151
+ """把 ASGI 的 send 回调落成 HTTP 响应字节流(逐块,不攒全)。
152
+
153
+ 与 devkit 的 `for await (chunk of response.body) res.write(chunk)` 等价:
154
+ - 响应头里有 content-length → 原样写;
155
+ - 没有(SSE 这类流式响应)→ 用 chunked 分帧,客户端能立刻收到字节。
156
+ """
157
+
158
+ def __init__(self, handler):
159
+ self.h = handler
160
+ self.started = False
161
+ self.chunked = False
162
+ self.closed = False
163
+
164
+ def start(self, status, headers):
165
+ h = self.h
166
+ h.send_response_only(status)
167
+ hdrs = [(k, v) for k, v in headers if k.lower() != "transfer-encoding"]
168
+ self.chunked = not any(k.lower() == "content-length" for k, _ in hdrs)
169
+ for k, v in hdrs:
170
+ h.send_header(k, v)
171
+ h._cors()
172
+ if self.chunked:
173
+ h.send_header("Transfer-Encoding", "chunked")
174
+ h.end_headers()
175
+ h.wfile.flush()
176
+ self.started = True
177
+
178
+ def body(self, chunk: bytes):
179
+ if not self.started:
180
+ raise RuntimeError("ASGI body 先于 response.start")
181
+ if self.chunked:
182
+ self.h.wfile.write(f"{len(chunk):X}\r\n".encode() + chunk + b"\r\n")
183
+ else:
184
+ self.h.wfile.write(chunk)
185
+ self.h.wfile.flush()
186
+
187
+ def end(self):
188
+ if not self.started or self.closed:
189
+ return
190
+ self.closed = True
191
+ if self.chunked:
192
+ self.h.wfile.write(b"0\r\n\r\n")
193
+ self.h.wfile.flush()
194
+
195
+
196
+ class _Handler(BaseHTTPRequestHandler):
197
+ protocol_version = "HTTP/1.1"
198
+ server_version = "vod-devkit-mcp"
199
+
200
+ def log_message(self, fmt, *args): # 静默:日志走 /tmp/vod_mcp_server.log
201
+ pass
202
+
203
+ def _cors(self):
204
+ self.send_header("Access-Control-Allow-Origin", "*")
205
+ self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
206
+ self.send_header("Access-Control-Allow-Headers",
207
+ "Content-Type, MCP-Protocol-Version, Mcp-Session-Id, Accept, Authorization")
208
+ self.send_header("Access-Control-Expose-Headers",
209
+ "MCP-Protocol-Version, Mcp-Session-Id")
210
+
211
+ def _empty(self, code, extra=None):
212
+ self.send_response(code)
213
+ for k, v in (extra or {}).items():
214
+ self.send_header(k, v)
215
+ self._cors()
216
+ self.send_header("Content-Length", "0")
217
+ self.end_headers()
218
+
219
+ def _json(self, code, payload):
220
+ data = json.dumps(payload, ensure_ascii=False).encode()
221
+ self.send_response(code)
222
+ self.send_header("Content-Type", "application/json")
223
+ self.send_header("Content-Length", str(len(data)))
224
+ self._cors()
225
+ self.end_headers()
226
+ self.wfile.write(data)
227
+
228
+ def do_OPTIONS(self):
229
+ self._empty(204)
230
+
231
+ def do_GET(self):
232
+ # 与 devkit 同契约:GET 不进传输层(SDK 会把它变成 SSE 长连)
233
+ self._empty(405, {"Allow": "POST, OPTIONS"})
234
+
235
+ def do_POST(self):
236
+ length = int(self.headers.get("Content-Length") or 0)
237
+ if length <= 0 or length > MAX_BODY:
238
+ self._json(400, {"jsonrpc": "2.0", "id": None,
239
+ "error": {"code": -32700, "message": "空或超大请求体"}})
240
+ return
241
+ body = self.rfile.read(length)
242
+ try:
243
+ message = json.loads(body.decode("utf-8", "replace"))
244
+ except json.JSONDecodeError:
245
+ self._json(400, {"jsonrpc": "2.0", "id": None,
246
+ "error": {"code": -32700, "message": "Parse error"}})
247
+ return
248
+ # 通知(含 notifications/initialized):不构造 transport,直接 202
249
+ #(devkit 同样的短路,保留 devkit 的 202 契约)
250
+ if isinstance(message, dict) and "id" not in message:
251
+ self._empty(202)
252
+ return
253
+ raw_auth = (self.headers.get("Authorization") or "").strip()
254
+ key = raw_auth[7:].strip() if raw_auth.lower().startswith("bearer ") else ""
255
+
256
+ from vod_mcp import tools
257
+ sink = _StreamSink(self)
258
+ tok_key = tools._REQ_KEY.set(key or None)
259
+ tok_face = tools._SERVER_FACE.set(True)
260
+ try:
261
+ self.server.runtime.request(_scope(self, body), body, sink)
262
+ except Exception as e: # 传输层异常:能答就答 500,已经流出去就断连
263
+ if not sink.started:
264
+ self._json(500, {"jsonrpc": "2.0", "id": None,
265
+ "error": {"code": -32603, "message": str(e)}})
266
+ return
267
+ finally:
268
+ tools._SERVER_FACE.reset(tok_face)
269
+ tools._REQ_KEY.reset(tok_key)
270
+
271
+
272
+ def serve(host: str, port: int) -> int:
273
+ if host not in LOOPBACK:
274
+ print(f"[vod-devkit] 警告:远程 MCP 绑定非回环地址 {host}——本进程无内建鉴权,"
275
+ "不要把它匿名暴露到公网;TLS 与身份校验应由反代承担。", file=sys.stderr)
276
+ runtime = RemoteRuntime(host, port)
277
+ runtime.start()
278
+ httpd = ThreadingHTTPServer((host, port), _Handler)
279
+ httpd.daemon_threads = True
280
+ httpd.runtime = runtime
281
+ real_port = httpd.server_address[1]
282
+ print(f"vod-devkit MCP server (remote) listening on {host}:{real_port}", file=sys.stderr)
283
+ try:
284
+ httpd.serve_forever()
285
+ except KeyboardInterrupt:
286
+ pass
287
+ finally:
288
+ httpd.server_close()
289
+ return 0