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.
- package/CHANGELOG.md +21 -0
- package/README.en.md +5 -4
- package/README.md +44 -9
- package/bin/vod-devkit +143 -111
- package/contract/tools.schema.json +38 -1
- package/integrations/codex/host.json +20 -0
- package/integrations/dsh/host.json +15 -0
- package/integrations/hermes/host.json +20 -0
- package/integrations/opencode/command/vod-doctor.md +10 -0
- package/integrations/opencode/host.json +28 -0
- package/package.json +10 -10
- package/plugins/vod-devkit/.codex-plugin/plugin.json +1 -1
- package/plugins/vod-devkit/build-info.json +3 -3
- package/plugins/vod-devkit/skills/vod-core/SKILL.md +35 -15
- package/plugins/vod-devkit/vod_mcp/__init__.py +1 -1
- package/plugins/vod-devkit/vod_mcp/config_forms.py +154 -0
- package/plugins/vod-devkit/vod_mcp/guardrails.py +25 -0
- package/plugins/vod-devkit/vod_mcp/hosts.py +80 -0
- package/plugins/vod-devkit/vod_mcp/packs.py +17 -3
- package/plugins/vod-devkit/vod_mcp/remote_app.py +100 -0
- package/plugins/vod-devkit/vod_mcp/server.py +30 -15
- package/plugins/vod-devkit/vod_mcp/skills_registry.py +124 -0
- package/plugins/vod-devkit/vod_mcp/tools.py +70 -9
- package/plugins/vod-devkit/vod_mcp/transport_remote.py +289 -0
- package/plugins/vod-devkit/vod_mcp/update_check.py +105 -0
- package/skills/vod-core/SKILL.md +35 -15
- package/vod_mcp/__init__.py +1 -1
- package/vod_mcp/config_forms.py +154 -0
- package/vod_mcp/guardrails.py +25 -0
- package/vod_mcp/hosts.py +80 -0
- package/vod_mcp/packs.py +17 -3
- package/vod_mcp/remote_app.py +100 -0
- package/vod_mcp/server.py +30 -15
- package/vod_mcp/skills_registry.py +124 -0
- package/vod_mcp/tools.py +70 -9
- package/vod_mcp/transport_remote.py +289 -0
- package/vod_mcp/update_check.py +105 -0
|
@@ -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
|
package/vod_mcp/tools.py
CHANGED
|
@@ -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=
|
|
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=
|
|
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=
|
|
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=
|
|
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
|
|
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(
|
|
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=
|
|
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
|
|
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(
|
|
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
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""版本更新检查(devkit update-check/upgrade 的裁剪版:只提醒,不自升级)。
|
|
2
|
+
|
|
3
|
+
为什么只提醒:本插件有两种分发形态,preset 形态**禁止自更新**(插件版本随
|
|
4
|
+
agent 发版管理,D-key-guard-3②)。所以升级动作永远是 install/update,工具
|
|
5
|
+
只负责回答"我这台是不是旧了",绝不下载、不解包、不改盘。
|
|
6
|
+
|
|
7
|
+
三个约束:
|
|
8
|
+
- 一次会话只打扰一次 + 拒绝后冷却 3 天(devkit 同款);状态落 runtime.json。
|
|
9
|
+
- 网络失败静默降级(离线/内网环境必须可用),不阻塞任何采集链。
|
|
10
|
+
- preset 形态完全不发外呼。
|
|
11
|
+
"""
|
|
12
|
+
import datetime
|
|
13
|
+
import json
|
|
14
|
+
import urllib.request
|
|
15
|
+
|
|
16
|
+
REGISTRY = "https://registry.npmjs.org/vod-devkit/latest"
|
|
17
|
+
CACHE_TTL_HOURS = 24
|
|
18
|
+
DISMISS_DAYS = 3
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _now():
|
|
22
|
+
return datetime.datetime.now()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _fetch_latest(timeout=3) -> str | None:
|
|
26
|
+
"""查 npm registry 的 latest 版本;任何失败返回 None(永不抛出)。"""
|
|
27
|
+
try:
|
|
28
|
+
req = urllib.request.Request(REGISTRY, headers={"accept": "application/json",
|
|
29
|
+
"user-agent": "vod-devkit"})
|
|
30
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
31
|
+
data = json.loads(resp.read().decode("utf-8", "replace") or "{}")
|
|
32
|
+
v = data.get("version")
|
|
33
|
+
return str(v) if v else None
|
|
34
|
+
except Exception:
|
|
35
|
+
return None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _version_tuple(v: str) -> tuple:
|
|
39
|
+
"""宽松 semver:只比数字段,预发布后缀按 0 处理(0.4.4-rc1 视作 0.4.4)。"""
|
|
40
|
+
core = str(v or "").split("-")[0].split("+")[0]
|
|
41
|
+
out = []
|
|
42
|
+
for part in core.split(".")[:3]:
|
|
43
|
+
try:
|
|
44
|
+
out.append(int(part))
|
|
45
|
+
except ValueError:
|
|
46
|
+
out.append(0)
|
|
47
|
+
while len(out) < 3:
|
|
48
|
+
out.append(0)
|
|
49
|
+
return tuple(out)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def check(params: dict | None = None) -> dict:
|
|
53
|
+
from vod_mcp import __version__, tools
|
|
54
|
+
params = params or {}
|
|
55
|
+
dismiss = bool(params.get("dismiss"))
|
|
56
|
+
cfg = tools._runtime_cfg()
|
|
57
|
+
state = cfg.get("update_check") or {}
|
|
58
|
+
now = _now()
|
|
59
|
+
|
|
60
|
+
if tools._distribution() == "preset":
|
|
61
|
+
return {"currentVersion": __version__, "latestVersion": None,
|
|
62
|
+
"updateAvailable": False, "checked": False,
|
|
63
|
+
"note": "本装机为产品分发形态(preset),版本随 agent 发版管理,"
|
|
64
|
+
"不做外呼检查。升级请联系产品提供方。"}
|
|
65
|
+
|
|
66
|
+
dismissed_until = state.get("dismissedUntil")
|
|
67
|
+
if dismiss:
|
|
68
|
+
until = (now + datetime.timedelta(days=DISMISS_DAYS)).date().isoformat()
|
|
69
|
+
tools._save_runtime({"update_check": {**state, "dismissedUntil": until}})
|
|
70
|
+
return {"currentVersion": __version__, "latestVersion": state.get("latestVersion"),
|
|
71
|
+
"updateAvailable": False, "checked": False,
|
|
72
|
+
"note": f"已记录:{DISMISS_DAYS} 天内不再提醒(至 {until})。"}
|
|
73
|
+
|
|
74
|
+
if dismissed_until and now.date().isoformat() < dismissed_until:
|
|
75
|
+
return {"currentVersion": __version__,
|
|
76
|
+
"latestVersion": state.get("latestVersion"),
|
|
77
|
+
"updateAvailable": False, "checked": False,
|
|
78
|
+
"note": f"用户此前已选择跳过(至 {dismissed_until}),本期不再提醒。"}
|
|
79
|
+
|
|
80
|
+
cached_at = state.get("checkedAt")
|
|
81
|
+
fresh = False
|
|
82
|
+
if cached_at:
|
|
83
|
+
try:
|
|
84
|
+
age = (now - datetime.datetime.fromisoformat(cached_at)).total_seconds()
|
|
85
|
+
fresh = age < CACHE_TTL_HOURS * 3600
|
|
86
|
+
except ValueError:
|
|
87
|
+
fresh = False
|
|
88
|
+
latest = state.get("latestVersion") if fresh else _fetch_latest()
|
|
89
|
+
if latest is None:
|
|
90
|
+
return {"currentVersion": __version__, "latestVersion": None,
|
|
91
|
+
"updateAvailable": False, "checked": False,
|
|
92
|
+
"note": "版本检查不可达(离线/内网正常现象),不影响采集;稍后重试即可。"}
|
|
93
|
+
|
|
94
|
+
if not fresh:
|
|
95
|
+
tools._save_runtime({"update_check": {**state, "checkedAt": now.isoformat(
|
|
96
|
+
timespec="seconds"), "latestVersion": latest}})
|
|
97
|
+
newer = _version_tuple(latest) > _version_tuple(__version__)
|
|
98
|
+
out = {"currentVersion": __version__, "latestVersion": latest,
|
|
99
|
+
"updateAvailable": newer, "checked": True,
|
|
100
|
+
"note": ("有新版本可用:重跑 install(幂等原位更新)或 vod-devkit update。"
|
|
101
|
+
"用户不想被打扰时用 dismiss=true 跳过 3 天。") if newer else
|
|
102
|
+
"已是最新版本。"}
|
|
103
|
+
if newer:
|
|
104
|
+
out["upgradeCommand"] = "vod-devkit update # 或重跑 install(同一行装命令)"
|
|
105
|
+
return out
|