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
@@ -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
@@ -1,23 +1,43 @@
1
1
  ---
2
2
  name: vod-core
3
- description: 'VOD 用户声音分析插件路由入口。任何"分析用户声音/反馈、发起 VOD 分析任务、查任务状态/结果、VOD 评分/分类规则、KB 检索"类请求先经本技能路由到对应工具与领域技能。写操作(发起分析)必须先获用户确认(confirm 护栏)。'
4
- version: 1
3
+ description: 'VOD 用户声音采集插件的路由入口与纪律速查。遇到"提交反馈/采集用户声音/这条反馈入库没有/问题分类与评分规则是什么/插件版本与来源/key 认证状态"类请求先读本技能,再按表路由到具体工具或领域技能。采集写操作必须先获用户明确同意。'
4
+ version: 2
5
5
  ---
6
6
 
7
- # VOD Core
7
+ # VOD Core(路由与纪律)
8
8
 
9
- VOD 分析能力入口。按意图路由:
9
+ 本插件只做**用户声音采集**:把用户对本产品的抱怨/建议/期望原话送进 VOD 囤积区。
10
+ 分析与运营归 vod-system 前端,插件没有、也不该有发起分析的入口。
11
+
12
+ ## 意图 → 工具
10
13
 
11
14
  | 意图 | 动作 |
12
15
  |---|---|
13
- | 发起分析 | 工具 vod_run_analysis(confirm:必须用户确认后传 confirmed=true;taskId 为对账主键) |
14
- | 查任务进度/结果 | vod_task_status / vod_task_result |
15
- | 知识库检索 | vod_kb_search |
16
- | 插件自述/来源核验 | vod_devkit_info |
17
- | 分类匹配/问题分类/评分规则 | 领域技能(由 vendor 机制从 VOD-Project 真源拉取:vod-category-matching / vod-problem-classification / vod-scoring-rules) |
18
-
19
- 纪律:
20
- 1. 任务 ID 是唯一对账主键,发起后一切追问以 taskId 对账,不凭记忆描述
21
- 2. 单任务条数上限、product 白名单由护栏强制,超限直接拒
22
- 3. 任何 DB 直连/凭据读取意图会被 deny——不要尝试
23
- 4. 领域规则以 vendored 技能文件为准,不凭训练数据回答 VOD 评分口径
16
+ | 用户抱怨/建议,要提交 | `vod_submit_voices`(先征得明确同意,再传 `confirmed=true`);话术见 `vod-feedback-collect` |
17
+ | 想先暂存、等用户确认后再提交 | `vod_draft_voices` → 用户确认 → `vod_commit_voices`(一次性令牌 + payload 校验) |
18
+ | 本机已提交过哪些(进度追问) | `vod_list_submitted`(本地账本口径,换机不保留) |
19
+ | 插件版本/来源核验 | `vod_devkit_info`(version + commitSha) |
20
+ | key/认证状态、引擎连通性 | `vod_auth_status`(只报指纹,不下发明文) |
21
+ | 有哪些技能、规则技能是否可用 | `vod_list_skills` |
22
+ | 取规则技能全文(分类/评分口径) | `vod_retrieve_skill`(owner pack 被裁剪时返回恢复指引) |
23
+
24
+ ## 意图 → 领域技能
25
+
26
+ | 主题 | 技能 | 加载方式 |
27
+ |---|---|---|
28
+ | 采集话术/确认时机/原话逐字纪律 | `vod-feedback-collect` | 宿主原生加载(元技能,已装进本机技能目录) |
29
+ | 六类问题分类口径(引擎 v2.2 真源) | `vod-problem-classification-rules` | 原生副本优先;读不到或怀疑过期时用 `vod_retrieve_skill` |
30
+ | 四项评分公式(引擎 v2 真源) | `vod-scoring-rules` | 同上 |
31
+
32
+ ## 纪律(违反即事故)
33
+
34
+ 1. **同意前置**:用户陈述反馈 ≠ 同意提交。先承接、再问"要提交给产品团队吗"、
35
+ 再用一句固定的引导补充话术,一次说完。
36
+ 2. **原话逐字**:`content` 放用户原话,禁改写/概括/增删语气词;回执
37
+ `echo.contents` 必须逐字转述给用户(「已收录原话:…」)。
38
+ 3. **归因不问**:product 由安装绑定决定,禁止问用户"提交到哪个产品"。
39
+ 4. **篇幅边界**:content ≤ 2000 字、单批 ≤ 50 条(护栏强制,超限直接拒)。
40
+ 5. **不碰内部面**:不尝试数据库直连、不读取或打印凭据;被 deny 时如实告知,
41
+ 不要换措辞重试。
42
+ 6. **规则口径以技能/披露内容为准**:不凭训练数据回答 VOD 分类与评分——
43
+ vendored 文本与引擎代码同源。
@@ -5,7 +5,7 @@
5
5
  2. 外部无 DB 直连路径(护栏 deny 兜底)
6
6
  3. 任务 ID 是唯一对账主键,写类工具返回一律携带
7
7
  """
8
- __version__ = "0.4.3"
8
+ __version__ = "0.5.0"
9
9
  # 默认上游:VOD 测试环境。外部用户本机无 VOD,回环默认值=装完即坏;
10
10
  # 生产地址定型后只改这一处(tools.py 与 bin/vod-devkit 共用本常量)。
11
11
  DEFAULT_JAVA_BASE = "https://vod-dev.topxtopx.com"
@@ -0,0 +1,154 @@
1
+ """宿主配置文件的形态分类与受管块扫描(单一实现,零第三方依赖)。
2
+
3
+ 背景:安装器要改两类文本配置——codex 的 `config.toml` 与 dsh 的
4
+ `cordis.patch.yml`。历史缺陷全都是"尽力猜"造成的:
5
+
6
+ - TOML:`args = ["…"]` 行内方括号让正则提前断块 → 旧 env 子表残留;
7
+ 更隐蔽的一层是残留的子表 `[mcp_servers.vod-devkit.env]` 在 TOML 语义里
8
+ 会**重新创建父表**——于是装出一个没有 command 的假 server,改完配置
9
+ 反而更坏。
10
+ - YAML:模板里的字面量 `[]` 顶层行 + 追加 `- id:` = 非法 YAML,整个
11
+ profile 启动崩溃;dsh 运行期序列化还会冲掉"打平"的块。
12
+
13
+ 借鉴 huaweicloud-devkit 的纪律(`mcp-config-merge.ts`):**一个扫描器同时
14
+ 支撑写入、删除与增量**,非已知形态在改字节**之前**拒绝——宁可装不上,
15
+ 不可改坏用户文件。本模块只做分类与扫描,不做 IO,也不做"修复"。
16
+ """
17
+ import re
18
+
19
+ # 受管 TOML 表前缀:本插件拥有该表及其全部子表
20
+ TOML_MANAGED = "mcp_servers.vod-devkit"
21
+
22
+ _HEADER = re.compile(r"^\[([^\[\]]+)\]$")
23
+ _MAPPING_ROOT = re.compile(r"^[A-Za-z_][\w.\-]*\s*:")
24
+ _DSH_ID = "- id: vod-devkit"
25
+
26
+
27
+ class Refused(Exception):
28
+ """文件形态不在已知集合内:调用方必须原样放弃修改(字节不变)。"""
29
+
30
+
31
+ # ---------------- TOML ----------------
32
+
33
+ def _split_header(line: str):
34
+ """行 → 表名;非表头返回 None。空行/注释返回 ""。"""
35
+ s = line.strip()
36
+ if not s or s.startswith("#"):
37
+ return ""
38
+ # 表头允许行尾注释:`[a.b] # note`(表名里不会出现 #)
39
+ if "#" in s:
40
+ s = s.split("#", 1)[0].strip()
41
+ m = _HEADER.match(s)
42
+ if m:
43
+ return m.group(1).strip()
44
+ if s.startswith("["):
45
+ raise Refused(f"疑似表头但不合法:{line.rstrip()[:60]}")
46
+ return None
47
+
48
+
49
+ def scan_toml_sections(text: str) -> list:
50
+ """按行扫描 TOML 表:返回 [{name, start, end}](end 为下一个表头行,排他)。"""
51
+ lines = text.splitlines()
52
+ heads = [] # (name, line_no)
53
+ for i, line in enumerate(lines):
54
+ name = _split_header(line)
55
+ if name:
56
+ heads.append((name, i))
57
+ out = []
58
+ for idx, (name, start) in enumerate(heads):
59
+ end = heads[idx + 1][1] if idx + 1 < len(heads) else len(lines)
60
+ out.append({"name": name, "start": start, "end": end})
61
+ return out
62
+
63
+
64
+ def classify_codex_toml(text: str) -> tuple:
65
+ """codex config.toml 形态判定 → (verdict, reason);verdict ∈ {ok, refuse}。
66
+
67
+ 拒绝条件(都会让"删我们那一段"变成不安全的操作):
68
+ - 表头重复定义(TOML 本身非法;删哪一份都是猜)
69
+ - 出现"疑似表头"的畸形行(我们的扫描器与用户的文件理解不一致)
70
+ """
71
+ sections = scan_toml_sections(text) # 畸形表头在此抛 Refused
72
+ seen = set()
73
+ for sec in sections:
74
+ if sec["name"] in seen:
75
+ return "refuse", f"表头重复定义 [{sec['name']}](TOML 非法,拒绝猜测)"
76
+ seen.add(sec["name"])
77
+ return "ok", ""
78
+
79
+
80
+ def managed_toml_sections(sections: list) -> list:
81
+ """属于本插件的表(含子表):name == 前缀 或 name.startswith(前缀 + ".")。"""
82
+ return [s for s in sections
83
+ if s["name"] == TOML_MANAGED or s["name"].startswith(TOML_MANAGED + ".")]
84
+
85
+
86
+ def strip_managed_toml(text: str) -> tuple:
87
+ """删除本插件拥有的全部 TOML 段(含子表)→ (new_text, removed_names)。
88
+
89
+ 子表必须一起删:留下 `[mcp_servers.vod-devkit.env]` 会在 TOML 语义里
90
+ 重建父表,得到一个没有 command 的 vod-devkit server(旧实现的残留 bug)。
91
+ """
92
+ sections = scan_toml_sections(text)
93
+ doomed = managed_toml_sections(sections)
94
+ if not doomed:
95
+ return text.rstrip(), []
96
+ lines = text.splitlines()
97
+ drop = set()
98
+ for sec in doomed:
99
+ drop.update(range(sec["start"], sec["end"]))
100
+ kept = [ln for i, ln in enumerate(lines) if i not in drop]
101
+ return "\n".join(kept).rstrip(), [s["name"] for s in doomed]
102
+
103
+
104
+ # ---------------- YAML(dsh cordis.patch.yml) ----------------
105
+
106
+ def classify_dsh_patch(lines: list) -> tuple:
107
+ """dsh profile patch 形态判定 → (verdict, reason)。
108
+
109
+ 这个文件是**顶层数组**(元素形如 `- insert:`)。拒绝条件:
110
+ - 缩进里有 tab(YAML 禁止 tab 缩进,任何解析器行为都不可依赖)
111
+ - 根是映射(追加顶层数组元素会造出非法文档)
112
+ - 根是 flow 集合(`{...}` / `[...]`,同上;字面量 `[]` 占位例外)
113
+ - 本插件的 `- id: vod-devkit` 出现多次(删/替换哪一份都是猜)
114
+ """
115
+ for ln in lines:
116
+ lead = ln[:len(ln) - len(ln.lstrip())]
117
+ if "\t" in lead:
118
+ return "refuse", "缩进含 tab(YAML 禁止 tab 缩进)"
119
+ significant = [ln for ln in lines if ln.strip() and not ln.strip().startswith("#")]
120
+ if not significant:
121
+ return "ok", ""
122
+ root = significant[0].strip()
123
+ if root.startswith("{") or (root.startswith("[") and root != "[]"):
124
+ return "refuse", f"根节点是 flow 集合({root[:20]}),本插件只写块数组"
125
+ if _MAPPING_ROOT.match(root):
126
+ return "refuse", f"根节点是映射({root[:20]}),不是本插件写的顶层数组"
127
+ if sum(1 for ln in lines if ln.strip().startswith(_DSH_ID)) > 1:
128
+ return "refuse", "出现多个 `- id: vod-devkit` 块(无法判定哪一份是活的)"
129
+ return "ok", ""
130
+
131
+
132
+ def find_dsh_block(lines: list) -> tuple:
133
+ """定位 vod-devkit 块的 (start, end);不存在返回 (None, None)。
134
+
135
+ 块边界=下一顶层元素行(`- ` 开头)或 EOF。嵌套铁律(真机实锤):
136
+ dsh 只认缩进在 `- insert:` 之下的块——命中行带缩进时 start 向上归并到
137
+ 该组头,整组替换;历史平铺形态按原语义顶格替换。install 的幂等 upsert
138
+ 与 uninstall 的摘除共用本边界语义(单一实现,防两处扫描规则漂移)。
139
+ """
140
+ for i, ln in enumerate(lines):
141
+ if ln.strip().startswith(_DSH_ID):
142
+ start = i
143
+ if ln[:1] == " ": # 嵌套形态:向上归并组头
144
+ for k in range(i - 1, -1, -1):
145
+ if lines[k].startswith("- "):
146
+ start = k
147
+ break
148
+ end = len(lines)
149
+ for j in range(start + 1, len(lines)):
150
+ if lines[j].startswith("- "):
151
+ end = j
152
+ break
153
+ return start, end
154
+ return None, None
@@ -0,0 +1,25 @@
1
+ """工具调用前置护栏(唯一实现,stdio 与 HTTP 两面共用)。
2
+
3
+ 两条面(stdio 的 handle、SDK 的 on_call_tool)必须走同一判定,否则远程面就是
4
+ 护栏缺口——新增一个传输方式不等于新增一套策略。
5
+ """
6
+ import json
7
+
8
+ from vod_mcp import policy as policy_mod
9
+
10
+
11
+ def check(name: str, args: dict) -> tuple:
12
+ """返回 (verdict, message, code);verdict ∈ allow/confirm/deny,code 为
13
+ MCP 约定的错误码(deny=-32010,confirm=-32011),allow 时 code=None。"""
14
+ pol = policy_mod.load_policy()
15
+ verdict, msg = policy_mod.decide(
16
+ policy_mod.check_tool_call(pol, name, args) if name else [])
17
+ if verdict == "deny":
18
+ return "deny", f"[guard:deny] {msg}", -32010
19
+ if verdict == "confirm":
20
+ return "confirm", f"[guard:confirm] {msg}", -32011
21
+ text_hits = policy_mod.check_text(
22
+ pol, json.dumps(policy_mod.guard_scope(args), ensure_ascii=False))
23
+ if text_hits:
24
+ return "deny", f"[guard:deny] {policy_mod.decide(text_hits)[1]}", -32010
25
+ return "allow", "", None
@@ -0,0 +1,80 @@
1
+ """宿主适配层:每个宿主的路径/探测/生成物集中在 integrations/<host>/host.json。
2
+
3
+ 动机(devkit 对表结论之一):新增宿主此前要在 1074 行的 bin 里改五处常量
4
+ 与若干字面量路径,改漏一处就是"装了一半"。把**数据**(配置落点、技能目录、
5
+ 平台差异、随装生成物)抽到 host.json,代码只保留每个宿主真正不同的安装
6
+ **逻辑**(hermes 走官方 CLI、opencode 走 JSON 合并、codex/dsh 走插件命令)。
7
+
8
+ 纪律:
9
+ - host.json 里的路径一律相对 HOME 用 `~` 表示,由本模块解析;不许在代码里
10
+ 出现第二份路径字面量。
11
+ - 平台差异用键名 "default"/"windows" 区分(当前只有 opencode 分叉)。
12
+ - `{profile}` 是 dsh 的占位符,必须由调用方显式代入(缺省不猜)。
13
+ """
14
+ import json
15
+ import platform
16
+ from pathlib import Path
17
+
18
+ ROOT = Path(__file__).resolve().parent.parent
19
+ INTEGRATIONS = ROOT / "integrations"
20
+
21
+
22
+ def hosts() -> list:
23
+ if not INTEGRATIONS.is_dir():
24
+ return []
25
+ return sorted(p.name for p in INTEGRATIONS.iterdir()
26
+ if (p / "host.json").exists())
27
+
28
+
29
+ def _pick(value):
30
+ """平台分叉取值:{"default": x, "windows": y} → 当前平台对应的字符串。"""
31
+ if isinstance(value, dict):
32
+ key = "windows" if platform.system() == "Windows" else "default"
33
+ return value.get(key, value.get("default"))
34
+ return value
35
+
36
+
37
+ def _resolve(path_str, profile: str | None = None) -> Path:
38
+ if not isinstance(path_str, str) or not path_str:
39
+ raise ValueError("host.json 的路径配置缺失")
40
+ if "{profile}" in path_str:
41
+ if not profile:
42
+ raise ValueError(f"路径 {path_str} 需要 profile 名(dsh 按 profile 组织)")
43
+ path_str = path_str.replace("{profile}", profile)
44
+ if path_str.startswith("~"):
45
+ return Path.home() / path_str[2:] if path_str.startswith("~/") else Path.home()
46
+ return Path(path_str)
47
+
48
+
49
+ def load(host: str, profile: str | None = None) -> dict:
50
+ """读一个宿主的适配数据并解析成绝对路径 → dict(键为契约的一部分)。
51
+
52
+ 返回键:id / cli / detectCLI / detectPath / configPath / skillsDir /
53
+ generated[{template, dest}] / managedPaths / notes
54
+ 未知宿主抛 KeyError(调用方据此给"不支持目标"提示,不许静默降级)。
55
+ """
56
+ p = INTEGRATIONS / host / "host.json"
57
+ if not p.exists():
58
+ raise KeyError(f"未知宿主 {host}(可选:{'、'.join(hosts())})")
59
+ raw = json.loads(p.read_text(encoding="utf-8"))
60
+ detect = raw.get("detect") or {}
61
+ spec = {
62
+ "id": raw.get("id") or host,
63
+ "cli": raw.get("cli"),
64
+ "detectCLI": detect.get("cli"),
65
+ "detectPath": (_resolve(_pick(detect["path"]), profile)
66
+ if detect.get("path") else None),
67
+ "configPath": (_resolve(_pick(raw["config"]), profile)
68
+ if raw.get("config") else None),
69
+ "skillsDir": (_resolve(_pick(raw["skillsDir"]), profile)
70
+ if raw.get("skillsDir") else None),
71
+ "generated": [
72
+ {"template": INTEGRATIONS / host / g["template"],
73
+ "dest": _resolve(_pick(g["dest"]), profile)}
74
+ for g in raw.get("generated") or []
75
+ ],
76
+ "managedPaths": [_resolve(_pick(x), profile)
77
+ for x in raw.get("managedPaths") or []],
78
+ "notes": raw.get("notes") or "",
79
+ }
80
+ return spec
package/vod_mcp/packs.py CHANGED
@@ -8,10 +8,12 @@ import sys
8
8
  ALL_PACKS = ("core", "collect", "knowledge")
9
9
 
10
10
  PACK_TOOLS = {
11
- "core": ["vod_devkit_info", "vod_auth_status"],
11
+ "core": ["vod_devkit_info", "vod_auth_status", "vod_check_update"],
12
12
  # 两段式(D-token-approval-2 极简形态)随 collect 下发;codex 话术走 draft→commit
13
13
  "collect": ["vod_submit_voices", "vod_draft_voices", "vod_commit_voices", "vod_list_submitted"],
14
- "knowledge": [], # 纯技能包:3 个领域规则技能,零工具零依赖
14
+ # 领域规则技能披露(第二轨):知道有哪几本规则、按需取全文。
15
+ # 只读、零上游调用、零依赖——与"纯知识包"的定位一致。
16
+ "knowledge": ["vod_list_skills", "vod_retrieve_skill"],
15
17
  }
16
18
 
17
19
 
@@ -44,8 +46,20 @@ def enabled_packs() -> tuple:
44
46
  return packs
45
47
 
46
48
 
47
- def enabled_tools() -> list:
49
+ # 服务面(HTTP 传输)摘除的"写本机状态"工具——对齐 huaweicloud-devkit 的
50
+ # remoteSurface 门控语义:远程面没有"本机"这个概念。
51
+ # draft/commit:草稿暂存在本机 runtime.json,HTTP 面由多客户端共享一个进程,
52
+ # "本机草稿"既不隔离也不可审计;
53
+ # list_submitted:本地账本是装机维度的记录,服务面读它不是客户端想要的答案
54
+ # (跨机对账走引擎端点)。
55
+ # 注意:submit 不摘——它对 VOD 的唯一动作是调用引擎 HTTP API,落库是服务端的事。
56
+ REMOTE_WITHHELD = ("vod_draft_voices", "vod_commit_voices", "vod_list_submitted")
57
+
58
+
59
+ def enabled_tools(remote: bool = False) -> list:
48
60
  tools = []
49
61
  for pack in enabled_packs():
50
62
  tools.extend(PACK_TOOLS[pack])
63
+ if remote:
64
+ tools = [t for t in tools if t not in REMOTE_WITHHELD]
51
65
  return tools
@@ -0,0 +1,100 @@
1
+ """远程面(Streamable HTTP)的服务实例:与 devkit 同构,工具面从契约派生。
2
+
3
+ 三处与 devkit 对齐、一处按我们自己的边界收紧:
4
+
5
+ 对齐:
6
+ - 官方 SDK 的 Streamable HTTP 传输(StreamableHTTPSessionManager,stateless +
7
+ json_response),一个进程服务多个 agent;
8
+ - 工具面由 remoteSurface 语义门控:摘掉"写本机状态"的工具(草稿/本地账本),
9
+ 保留调引擎 API 的 submit;
10
+ - initialize 的 instructions 换一版,明说远程面不给服务器本机路径(skillRoot
11
+ 等价物),规则文本请走 vod_retrieve_skill。
12
+
13
+ 收紧:
14
+ - **身份只从请求头来**。插件不代签、不落盘;缺 Authorization 时 submit 直接
15
+ 结构化拒绝(匿名令牌按设备锚点签发,服务面一进程一锚点会把配额/声量/归因
16
+ 搅在一起)。这是与 devkit 的实质差异:它的远程面不管身份,我们的写面必须管。
17
+
18
+ 插件不写库:本进程对 VOD 的全部动作仍然是调用引擎 HTTP API。
19
+ """
20
+ import asyncio
21
+ import json
22
+
23
+ from mcp import types
24
+ from mcp.server.lowlevel import Server
25
+
26
+ from vod_mcp import guardrails, packs, skills_registry, tools
27
+
28
+ REMOTE_INSTRUCTIONS = (
29
+ "vod-devkit 采集资产与纪律(远程面):技能 vod-feedback-collect 处理用户对"
30
+ "本产品的不满/建议/期望(触发词:慢/报错/体验差/希望支持/提单等)。"
31
+ "提交前必须征得用户明确同意(用户抱怨本身不构成同意);提交回执 "
32
+ "echo.contents 必须逐条原样转述给用户(「已收录原话:<content>」),"
33
+ "禁止改写、概括、增删字词。product 归因由部署绑定决定,禁止询问用户。"
34
+ "本面不提供服务器本机路径(skillRoot),规则文本用 vod_retrieve_skill 取;"
35
+ "写本机状态的工具(草稿/本地账本)不在本面提供。"
36
+ )
37
+
38
+
39
+ def _text_result(payload: dict, is_error: bool = False) -> types.CallToolResult:
40
+ return types.CallToolResult(
41
+ content=[types.TextContent(type="text",
42
+ text=json.dumps(payload, ensure_ascii=False))],
43
+ structured_content=payload,
44
+ is_error=is_error)
45
+
46
+
47
+ class _RemoteServer(Server):
48
+ """把 capabilities 对齐 devkit:{tools:{listChanged:true}}。
49
+
50
+ Python SDK 的默认 NotificationOptions 给 listChanged=false;devkit 的
51
+ remote test 明确断言 {tools: {listChanged: true}}。工具面由 pack 门控且
52
+ 本面 stateless,listChanged 只是信息性声明,但既然参照物声明了 true,就照它。
53
+ """
54
+
55
+ def create_initialization_options(self, *args, **kwargs): # noqa: D401
56
+ from mcp.server.lowlevel.server import NotificationOptions
57
+ kwargs.setdefault("notification_options", NotificationOptions(tools_changed=True))
58
+ return super().create_initialization_options(*args, **kwargs)
59
+
60
+
61
+ def build_server(remote: bool = True) -> Server:
62
+ version = tools.load_contract()["version"]
63
+
64
+ async def on_list_tools(ctx, params):
65
+ specs = tools.tool_specs(packs.enabled_tools(remote=remote))
66
+ return types.ListToolsResult(tools=[
67
+ types.Tool(name=s["name"], description=s["description"],
68
+ input_schema=s["inputSchema"]) for s in specs])
69
+
70
+ async def on_call_tool(ctx, params):
71
+ name = params.name
72
+ args = params.arguments or {}
73
+ if remote and name in packs.REMOTE_WITHHELD:
74
+ return _text_result({
75
+ "error": f"[remote] {name} 不在服务面提供",
76
+ "reason": ("该工具写本机状态(草稿/本地账本),远程面没有「本机」概念。"
77
+ "跨机对账请走引擎端点;两段式请改用 stdio 形态。"),
78
+ }, is_error=True)
79
+ verdict, msg, code = guardrails.check(name, args)
80
+ if verdict != "allow":
81
+ return _text_result({"error": msg, "code": code}, is_error=True)
82
+ client_info = {"name": "http-remote", "version": "1", "transport": "http"}
83
+ try:
84
+ out = await asyncio.to_thread(tools.dispatch, name, args, client_info)
85
+ except tools.ToolError as e:
86
+ return _text_result({"error": str(e), "code": e.code}, is_error=True)
87
+ if remote and name == "vod_list_skills":
88
+ out.pop("skillsDir", None) # 服务面不发布本机目录
89
+ return _text_result(out)
90
+
91
+ return _RemoteServer(
92
+ name="vod-devkit",
93
+ version=version,
94
+ instructions=REMOTE_INSTRUCTIONS if remote else None,
95
+ on_list_tools=on_list_tools,
96
+ on_call_tool=on_call_tool,
97
+ )
98
+
99
+
100
+ __all__ = ["build_server", "REMOTE_INSTRUCTIONS", "skills_registry"]
package/vod_mcp/server.py CHANGED
@@ -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: