@hfyjq/crannia 1.1.1 → 1.2.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 (306) hide show
  1. package/LICENSE +201 -201
  2. package/NOTICE +48 -45
  3. package/README.md +1 -1
  4. package/THIRD-PARTY-FRONTEND.md +5266 -5266
  5. package/THIRD-PARTY-PYTHON-linux.md +174 -0
  6. package/THIRD-PARTY-PYTHON.md +176 -162
  7. package/THIRD-PARTY.md +323 -316
  8. package/apps/desktop/quotes.txt +56 -56
  9. package/bus/core.py +677 -671
  10. package/bus/loaders/channel_loader.py +64 -64
  11. package/bus/loaders/provider_loader.py +4 -7
  12. package/bus/loaders/skill_loader.py +46 -27
  13. package/bus/loaders/skill_md.py +9 -9
  14. package/bus/mcp_disabled.py +4 -6
  15. package/bus/quarantine.py +10 -13
  16. package/bus/registry.py +2315 -2284
  17. package/bus/skill_state.py +124 -124
  18. package/channels/cli_channel/handler.py +3 -3
  19. package/channels/cli_channel/manifest.yaml +5 -5
  20. package/channels/dingtalk_channel/handler.py +32 -32
  21. package/channels/dingtalk_channel/manifest.yaml +12 -12
  22. package/channels/feishu_channel/handler.py +33 -33
  23. package/channels/feishu_channel/manifest.yaml +12 -12
  24. package/channels/qq_bot_channel/__init__.py +1 -1
  25. package/channels/qq_bot_channel/handler.py +24 -24
  26. package/channels/qq_bot_channel/manifest.yaml +4 -4
  27. package/channels/telegram_channel/__init__.py +1 -1
  28. package/channels/telegram_channel/handler.py +21 -21
  29. package/channels/telegram_channel/manifest.yaml +4 -4
  30. package/channels/telegram_channel/media.py +231 -231
  31. package/channels/textfmt.py +58 -58
  32. package/channels/wechat_channel/__init__.py +1 -1
  33. package/channels/wechat_channel/converter.py +1 -1
  34. package/channels/wechat_channel/handler.py +8 -8
  35. package/channels/wechat_channel/manifest.yaml +5 -5
  36. package/channels/wechat_channel/media.py +178 -178
  37. package/core/activity.py +753 -709
  38. package/core/agent_loop.py +7673 -7523
  39. package/core/allowlist.py +2 -3
  40. package/core/approval.py +36 -26
  41. package/core/approval_timeout.py +256 -228
  42. package/core/artifacts.py +3 -3
  43. package/core/attachment_gc.py +21 -0
  44. package/core/auto_review.py +2 -2
  45. package/core/browser/cdp.py +5 -2
  46. package/core/browser/discover.py +55 -19
  47. package/core/browser/session.py +4 -4
  48. package/core/cache_break_detector.py +97 -0
  49. package/core/cache_breakpoints.py +103 -0
  50. package/core/cache_policies.py +255 -0
  51. package/core/cancellation.py +3 -3
  52. package/core/channel_configs.py +3 -3
  53. package/core/channel_turns.py +13 -13
  54. package/core/child_approval.py +2 -3
  55. package/core/code_intel.py +11 -11
  56. package/core/command_policy.py +13 -7
  57. package/core/computer/annotate.py +231 -11
  58. package/core/computer/capture.py +140 -1
  59. package/core/computer/guard.py +7 -4
  60. package/core/computer/input.py +452 -26
  61. package/core/computer/session.py +563 -381
  62. package/core/computer/tools.py +2170 -928
  63. package/core/computer/uia.py +100 -1
  64. package/core/computer/watch.py +1 -1
  65. package/core/computer/win32.py +302 -7
  66. package/core/config_requirements.py +205 -205
  67. package/core/cron/runner.py +4 -4
  68. package/core/daily_log.py +2 -2
  69. package/core/dedup.py +2 -2
  70. package/core/egress_channels.py +326 -0
  71. package/core/egress_gate.py +96 -8
  72. package/core/egress_preapproved.py +59 -3
  73. package/core/endpoint.py +141 -141
  74. package/core/events.py +17 -8
  75. package/core/extension.py +2 -2
  76. package/core/file_history.py +15 -15
  77. package/core/file_tools.py +3 -3
  78. package/core/github_config.py +1 -1
  79. package/core/group_digest.py +3 -4
  80. package/core/group_minutes.py +5 -5
  81. package/core/group_reply.py +24 -0
  82. package/core/groups.py +5 -9
  83. package/core/hooks.py +15 -15
  84. package/core/i18n.py +2 -2
  85. package/core/ice/canary.py +3 -3
  86. package/core/ice/net_heuristics.py +2 -2
  87. package/core/im_routing.py +3 -3
  88. package/core/image_input.py +183 -43
  89. package/core/inbound.py +3 -3
  90. package/core/jobs.py +6 -6
  91. package/core/last_good.py +150 -150
  92. package/core/leaf_md.py +3 -3
  93. package/core/llm_errors.py +37 -28
  94. package/core/mail_config.py +2 -2
  95. package/core/memory/compressor.py +8 -8
  96. package/core/memory/manager.py +30 -45
  97. package/core/memory/session_memory.py +1 -2
  98. package/core/memory/short_term.py +4 -4
  99. package/core/memory_extract.py +1 -1
  100. package/core/memory_organize.py +8 -8
  101. package/core/memory_store.py +7 -9
  102. package/core/memory_transfer.py +2 -2
  103. package/core/model_capabilities.py +2 -2
  104. package/core/model_configs.py +219 -68
  105. package/core/model_profiles.py +333 -0
  106. package/core/modes.py +12 -11
  107. package/core/net_proxy.py +3 -3
  108. package/core/pipeline/scheduler.py +48 -43
  109. package/core/pipeline/stage.py +3 -0
  110. package/core/pipeline/stages/agent_loop.py +36 -15
  111. package/core/pipeline/stages/group_reply.py +22 -20
  112. package/core/pipeline/stages/post_process.py +7 -7
  113. package/core/pipeline/stages/pre_process.py +369 -77
  114. package/core/prompt_assembler.py +13 -4
  115. package/core/recycle.py +227 -16
  116. package/core/response_language.py +1 -1
  117. package/core/retention.py +2 -2
  118. package/core/rg.py +4 -3
  119. package/core/security.py +26 -8
  120. package/core/services.py +8 -8
  121. package/core/session_model.py +3 -5
  122. package/core/session_pool.py +35 -5
  123. package/core/session_recap.py +40 -3
  124. package/core/session_workspace.py +2 -3
  125. package/core/settings_baseline.py +2 -2
  126. package/core/settings_transfer.py +25 -1
  127. package/core/shell.py +52 -20
  128. package/core/side_call.py +3 -3
  129. package/core/skill_config.py +164 -0
  130. package/core/skill_factory.py +2 -2
  131. package/core/skill_guidance.py +2 -4
  132. package/core/skill_index.py +3 -4
  133. package/core/skill_settings.py +1 -1
  134. package/core/skill_sources.py +7 -7
  135. package/core/ssh_config.py +129 -0
  136. package/core/state_registry.py +67 -5
  137. package/core/subagent.py +28 -5
  138. package/core/subagent_defs.py +3 -3
  139. package/core/summarizer.py +4 -5
  140. package/core/tasks_notify.py +6 -6
  141. package/core/tiers.py +2 -2
  142. package/core/todos.py +1 -1
  143. package/core/token_calibrator.py +1 -4
  144. package/core/tool_outcome.py +108 -108
  145. package/core/touched_files.py +1 -1
  146. package/core/trace.py +12 -3
  147. package/core/unlock.py +4 -4
  148. package/core/update_tui.py +184 -158
  149. package/core/updater.py +5 -3
  150. package/core/version.py +14 -14
  151. package/core/vision_budget.py +235 -0
  152. package/core/web_cache.py +152 -152
  153. package/core/web_request.py +474 -0
  154. package/core/window_estimate.py +1 -1
  155. package/core/workspace.py +56 -26
  156. package/crannia_tray.py +278 -278
  157. package/licenses/GPL-3.0.txt +619 -619
  158. package/licenses/LGPL-2.1.txt +502 -502
  159. package/licenses/LGPL-3.0.txt +165 -165
  160. package/licenses/MIT-chat-on-wechat.txt +18 -18
  161. package/licenses/MIT-deepseek-harness.txt +21 -21
  162. package/licenses/Molio-LICENSE.txt +44 -44
  163. package/locales/en.json +1876 -1762
  164. package/main.py +154 -154
  165. package/mcpx/client.py +12 -1
  166. package/mcpx/manager.py +530 -522
  167. package/mcpx/servers/web_search.py +5 -13
  168. package/package.json +15 -23
  169. package/providers/anthropic/client.py +35 -33
  170. package/providers/base.py +13 -13
  171. package/providers/cache_policies.json +294 -0
  172. package/providers/cost_table.json +3779 -3779
  173. package/providers/lmstudio/client.py +2 -2
  174. package/providers/model_capabilities.json +6665 -6665
  175. package/providers/model_profiles.json +629 -0
  176. package/providers/ollama/client.py +2 -2
  177. package/providers/openai_compat.py +37 -16
  178. package/providers/openrouter/client.py +2 -2
  179. package/providers/qwen/__init__.py +1 -1
  180. package/providers/qwen/client.py +2 -2
  181. package/providers/qwen/manifest.yaml +16 -16
  182. package/providers/rate_limiter.py +2 -2
  183. package/providers/siliconflow/client.py +2 -2
  184. package/providers/validation.py +171 -171
  185. package/providers/vision_profiles.json +89 -0
  186. package/providers/window_table.json +8909 -8909
  187. package/requirements.txt +59 -51
  188. package/sbom-linux-x64.json +4580 -0
  189. package/sbom.json +4600 -4413
  190. package/skills/diagram/SKILL.md +47 -0
  191. package/skills/diagram/__init__.py +1 -0
  192. package/skills/diagram/handler.py +294 -0
  193. package/skills/diagram/layout.py +174 -0
  194. package/skills/diagram/manifest.yaml +106 -0
  195. package/skills/diagram/mermaid.py +170 -0
  196. package/skills/diagram/svg.py +223 -0
  197. package/skills/entertainment/SKILL.md +35 -35
  198. package/skills/entertainment/__init__.py +1 -1
  199. package/skills/entertainment/handler.py +91 -91
  200. package/skills/entertainment/manifest.yaml +26 -26
  201. package/skills/file_parser/GUIDANCE.md +10 -10
  202. package/skills/file_parser/handler.py +33 -11
  203. package/skills/github/SKILL.md +32 -32
  204. package/skills/github/__init__.py +1 -1
  205. package/skills/mail_parser/SKILL.md +68 -68
  206. package/skills/mail_parser/__init__.py +1 -1
  207. package/skills/mail_parser/handler.py +1 -1
  208. package/skills/media_gen/GUIDANCE.md +19 -19
  209. package/skills/media_gen/SKILL.md +43 -43
  210. package/skills/media_gen/__init__.py +1 -1
  211. package/skills/media_gen/handler.py +1 -1
  212. package/skills/media_gen/manifest.yaml +93 -93
  213. package/skills/netops/SKILL.md +45 -0
  214. package/skills/netops/__init__.py +1 -0
  215. package/skills/netops/handler.py +418 -0
  216. package/skills/netops/manifest.yaml +118 -0
  217. package/skills/office_parser/_excel_io.py +3 -3
  218. package/skills/office_parser/handler.py +2 -2
  219. package/skills/office_parser/ppt_tools.py +1 -1
  220. package/skills/office_parser/pptx_export/console_encoding.py +27 -27
  221. package/skills/office_parser/pptx_export/resource_paths.py +88 -88
  222. package/skills/office_parser/pptx_export/svg_finalize/__init__.py +12 -12
  223. package/skills/office_parser/pptx_export/svg_finalize/crop_images.py +366 -366
  224. package/skills/office_parser/pptx_export/svg_finalize/embed_images.py +288 -288
  225. package/skills/office_parser/pptx_export/svg_finalize/fix_image_aspect.py +388 -388
  226. package/skills/office_parser/pptx_export/svg_finalize/flatten_tspan.py +818 -818
  227. package/skills/office_parser/pptx_export/svg_finalize/svg_rect_to_path.py +345 -345
  228. package/skills/office_parser/pptx_export/svg_to_pptx/__init__.py +14 -14
  229. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/__init__.py +1 -1
  230. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/context.py +186 -186
  231. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/converter.py +781 -781
  232. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/paths.py +429 -429
  233. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/utils.py +40 -21
  234. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/__init__.py +1 -1
  235. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/builder.py +1267 -1267
  236. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/dimensions.py +155 -155
  237. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/discovery.py +101 -101
  238. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/narration.py +236 -236
  239. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/notes.py +257 -257
  240. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/slide_xml.py +136 -136
  241. package/skills/office_parser/pptx_export/svg_to_pptx/tspan_flattener.py +44 -44
  242. package/skills/office_parser/pptx_export/svg_to_pptx/use_expander.py +129 -129
  243. package/skills/office_parser/references/LICENSE-Office-Word-MCP-Server.txt +20 -20
  244. package/skills/office_parser/references/LICENSE-excel-mcp-server.txt +21 -21
  245. package/skills/office_parser/references/layout_library.md +816 -816
  246. package/skills/office_parser/references/ppt-master/LICENSE +21 -21
  247. package/skills/office_parser/references/ppt-master/references/executor-base.md +474 -474
  248. package/skills/office_parser/references/ppt-master/references/shared-standards.md +1002 -1002
  249. package/skills/office_parser/references/ppt-master/references/strategist.md +880 -880
  250. package/skills/office_parser/references/ppt-master/references/template-designer.md +402 -402
  251. package/skills/office_parser/references/ppt-master/references/visual-review.md +240 -240
  252. package/skills/office_parser/references/ppt-master/references/visual-styles/_index.md +106 -106
  253. package/skills/office_parser/references/ppt-master/references/visual-styles/blueprint.md +37 -37
  254. package/skills/office_parser/references/ppt-master/references/visual-styles/brutalist.md +38 -38
  255. package/skills/office_parser/references/ppt-master/references/visual-styles/chalkboard.md +36 -36
  256. package/skills/office_parser/references/ppt-master/references/visual-styles/dark-tech.md +37 -37
  257. package/skills/office_parser/references/ppt-master/references/visual-styles/data-journalism.md +36 -36
  258. package/skills/office_parser/references/ppt-master/references/visual-styles/editorial.md +38 -38
  259. package/skills/office_parser/references/ppt-master/references/visual-styles/glassmorphism.md +36 -36
  260. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-notes.md +37 -37
  261. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-wash.md +36 -36
  262. package/skills/office_parser/references/ppt-master/references/visual-styles/memphis.md +37 -37
  263. package/skills/office_parser/references/ppt-master/references/visual-styles/paper-cut.md +36 -36
  264. package/skills/office_parser/references/ppt-master/references/visual-styles/photo-editorial.md +38 -38
  265. package/skills/office_parser/references/ppt-master/references/visual-styles/pixel-art.md +36 -36
  266. package/skills/office_parser/references/ppt-master/references/visual-styles/sketch-notes.md +36 -36
  267. package/skills/office_parser/references/ppt-master/references/visual-styles/soft-rounded.md +37 -37
  268. package/skills/office_parser/references/ppt-master/references/visual-styles/swiss-minimal.md +38 -38
  269. package/skills/office_parser/references/ppt-master/references/visual-styles/vintage-poster.md +36 -36
  270. package/skills/office_parser/references/ppt-master/references/visual-styles/zine.md +37 -37
  271. package/skills/office_parser/references/spec_lock.md +235 -235
  272. package/skills/office_parser/soffice.py +68 -68
  273. package/skills/office_parser/word_tools.py +3 -3
  274. package/skills/ssh/SKILL.md +81 -0
  275. package/skills/ssh/__init__.py +1 -0
  276. package/skills/ssh/handler.py +609 -0
  277. package/skills/ssh/manifest.yaml +182 -0
  278. package/tui/crannia.cmd +134 -134
  279. package/tui/crannia.sh +82 -0
  280. package/tui/crannia_tui/__init__.py +1 -1
  281. package/tui/crannia_tui/app.py +240 -17
  282. package/tui/crannia_tui/app.tcss +21 -0
  283. package/tui/crannia_tui/clipboard.py +78 -10
  284. package/tui/crannia_tui/commands.py +37 -0
  285. package/tui/crannia_tui/events.py +6 -0
  286. package/tui/crannia_tui/i18n.py +164 -164
  287. package/tui/crannia_tui/locales/en.json +32 -7
  288. package/tui/crannia_tui/paths.py +4 -1
  289. package/tui/crannia_tui/profile.py +178 -169
  290. package/tui/crannia_tui/settings.py +134 -134
  291. package/tui/crannia_tui/setup.py +44 -5
  292. package/tui/crannia_tui/ui.py +156 -16
  293. package/tui/crannia_tui/update.py +393 -389
  294. package/vendor/ripgrep/COPYING.txt +3 -3
  295. package/vendor/ripgrep/LICENSE-MIT.txt +21 -21
  296. package/vendor/ripgrep/NOTICE-vscode-ripgrep.txt +13 -13
  297. package/vendor/ripgrep/README.md +30 -14
  298. package/vendor/ripgrep/UNLICENSE.txt +24 -24
  299. package/vendor/ripgrep/linux-x64/rg +0 -0
  300. package/vendor/ripgrep/package-source.json +15 -16
  301. package/web/__main__.py +12 -15
  302. package/web/server.py +8481 -8594
  303. package/web/static/img/channel-telegram.svg +1 -1
  304. package/web/static/img/channel-wechat.svg +1 -1
  305. package/web/templates/logs.html +49 -49
  306. package/web/templates/models.html +46 -46
package/mcpx/manager.py CHANGED
@@ -1,522 +1,530 @@
1
- """
2
- MCP Manager — lifecycle, built-in server loading, external connection management.
3
- """
4
-
5
- from __future__ import annotations
6
-
7
- import os
8
- import re
9
- from dataclasses import dataclass, field
10
- from typing import Any
11
-
12
- #: 「运行环境缺失」不是「连不上」。
13
- #:
14
- #: 现场:没装 Node 的机器上,`npx` 不存在,`_connect_stdio` 抛
15
- #: `FileNotFoundError [WinError 2]`,被记成 `mcp_connect_failed`,界面弹
16
- #: 「兼容性警告 / 不支持 / 已被 Crannia 屏蔽」。
17
- #: 而真正的原因是这台机器少了那个可执行文件 —— 装上就好,
18
- #: 和"这个插件坏了"是两件完全不同的事(标签在说谎)。
19
- MCP_MISSING_RUNTIME = "mcp_missing_runtime"
20
-
21
- #: 缺哪个可执行文件时该怎么跟用户说。只影响文案,不影响判定。
22
- _RUNTIME_HINTS = {
23
- "npx": "Node.js(安装包自带npx)",
24
- "node": "Node.js",
25
- "npm": "Node.js(安装包自带npm)",
26
- "uvx": "uv(装好后 uvx 才在 PATH 上)",
27
- "uv": "uv(装好后 uv 才在 PATH 上)",
28
- "python": "Python",
29
- "python3": "Python",
30
- }
31
-
32
-
33
- def missing_runtime(cfg: dict) -> str:
34
- """stdio 服务器的启动命令在这台机器上找不找得到。
35
-
36
- 返回缺的那个命令名(空串 = 没问题)。只对 stdio 有意义:
37
- `sse` / `streamable_http` 没有本地可执行文件。
38
- """
39
- import shutil
40
- from pathlib import Path
41
-
42
- if str(cfg.get("transport") or "stdio") != "stdio":
43
- return ""
44
- cmd = str(cfg.get("command") or "").strip()
45
- if not cmd:
46
- # 缺 `command` 是另一个错(配置写坏了),交给下面真实的连接去报 ——
47
- # 在这里冒充"缺运行时"会把一个配置错误说成"你没装东西"。
48
- return ""
49
- if "/" in cmd or "\\" in cmd:
50
- # 带路径的写法(`./node_modules/.bin/x`、`C:\node\npx.cmd`):判文件在不在,
51
- # 不走 PATH —— `which()` 对带路径的输入语义与平台有关。
52
- return "" if Path(cmd).is_file() else cmd
53
- return "" if shutil.which(cmd) else cmd
54
-
55
-
56
- def missing_runtime_reason(name: str, cmd: str) -> str:
57
- """给用户看的那句话。不出现「不兼容 / 不支持 / 已屏蔽」。"""
58
- hint = _RUNTIME_HINTS.get(cmd.lower().replace(".cmd", "").replace(".exe", ""),
59
- "它依赖的那个程序")
60
- return ("外部 MCP 服务器「%s」要用命令 %s 启动,当前环境找不到此对象。"
61
- "这不是兼容性问题 —— 装上%s之后重启尝试;"
62
- "或改用 Python(python -m …)或 HTTP 型的 MCP 服务器。"
63
- % (name, cmd, hint))
64
-
65
-
66
- @dataclass
67
- class MCPManager:
68
- """Central orchestrator for MCP integration.
69
-
70
- Called once at framework startup by bus/core.py. Loads built-in
71
- servers, optionally connects to configured external servers, and
72
- bridges all discovered tools to bus/registry.
73
- """
74
-
75
- config: dict = field(default_factory=dict)
76
- _external_servers: dict[str, Any] = field(default_factory=dict)
77
- _tools_registered: int = 0
78
-
79
- def load_builtin_servers(self) -> int:
80
- """
81
- Load all built-in MCP servers and register their tools.
82
-
83
- Built-in servers are defined in mcp/servers/ and run in-process.
84
- Their tools are directly registered to bus/registry without
85
- going through MCP transport.
86
-
87
- Returns the total number of tools registered.
88
- """
89
- import importlib
90
- from mcpx.servers import BUILTIN_SERVERS
91
-
92
- total = 0
93
- # 按 **`mcpx/servers/__init__.py::BUILTIN_SERVERS`**
94
- # 那份名单去 import —— 不要在这里写死某个具体模块名,
95
- # 否则"内置 MCP 有哪几条"会在三个地方各有一份(这里 / `get_status`
96
- # 里那个常数 / `web/server.py` 的两处硬编码)。
97
- for name in BUILTIN_SERVERS:
98
- try:
99
- mod = importlib.import_module("mcpx.servers." + name)
100
- n = mod.register_tools()
101
- total += n
102
- print(f"[mcp] Built-in {name}: {n} tools registered")
103
- except Exception as e: # noqa: BLE001
104
- print(f"[mcp] WARNING: Failed to load {name} server: {e}")
105
-
106
- self._tools_registered = total
107
- return total
108
-
109
- def connect_external(self, server_configs: list[dict]) -> int:
110
- """
111
- Connect to external MCP servers and register their tools.
112
-
113
- Each config dict should have:
114
- - name: str
115
- - transport: "stdio" | "sse" | "streamable_http"
116
- - command, args, env (for stdio)
117
- - url (for HTTP)
118
-
119
- Returns the number of tools registered.
120
- """
121
- # 必须用 `submit(...)`,不能用 `asyncio.run(...)`。
122
- # 每个 server 起一个新的循环时,连接绑定在"建立它的那个循环"上
123
- #循环一退连接就废(症状同 `mcpx/bridge.py::_run_async` 那条)。
124
- #全部投到同一个常驻循环上(`core/async_loop.py`)。
125
- from core.async_loop import submit
126
-
127
- total = 0
128
- for cfg in server_configs:
129
- name = cfg.get("name", "unknown")
130
- transport = cfg.get("transport", "stdio")
131
-
132
- # 连之前先看环境:缺 `npx` / `uvx` 与"服务器坏了"
133
- # 是两件事,而它们此前被压成同一句「不兼容 / 已屏蔽」。
134
- missing = missing_runtime(cfg)
135
- if missing:
136
- print(f"[mcp] '{name}' 跳过:找不到命令 {missing}(运行环境缺失,不是兼容性问题)")
137
- # `detail` 只写 ASCII 的 `command=<名字>`:界面从这一格里
138
- # 抠命令名,再用 `t()` 拼一句当前语言的提示(`plugin-notice-view.js
139
- # 的 missingCommand`)。写中文进去,英文界面就只能显示中文。
140
- self._record(name, code=MCP_MISSING_RUNTIME,
141
- reason=missing_runtime_reason(name, missing),
142
- detail="command=%s" % missing)
143
- continue
144
-
145
- try:
146
- if transport == "stdio":
147
- server = submit(_connect_stdio(name, cfg))
148
- elif transport in ("sse", "streamable_http"):
149
- server = submit(_connect_http(name, cfg))
150
- else:
151
- print(f"[mcp] Unknown transport '{transport}' for server '{name}'")
152
- continue
153
-
154
- if server and server._tools:
155
- from mcpx.client import register_external_server
156
- n = register_external_server(
157
- server, trusted_output=cfg.get("trusted_output") is True)
158
- self._external_servers[name] = server
159
- total += n
160
- print(f"[mcp] External '{name}': {n} tools ({transport})")
161
- # 连上了就把旧账划掉——
162
- # 账本是持久的,而闸只看账本。用户装好 Node 再重启时,
163
- # 上一次那条 `mcp_missing_runtime` / `mcp_connect_failed`
164
- # 还在,服务器连上了、工具却全被摘掉,而且不会再弹窗
165
- # (`hits` 已经不是 1)。一个"修好也没救"的死结。
166
- self._clear(name)
167
- except Exception as e:
168
- print(f"[mcp] WARNING: Failed to connect '{name}': {e}")
169
- # 连不上的外部服务器要记账 + 屏蔽。
170
- # 只 print 一行、不落任何状态时 —— "这台服务器挂了"
171
- # 只在启动那一刻的终端里有一行字,而工具要么没注册(模型说
172
- # "我没有这个工具"),要么注册了、调用时才抛(模型自己去猜)。
173
- self._record(name, code="mcp_connect_failed",
174
- reason="外部 MCP 服务器连不上:%s: %s" % (type(e).__name__, e),
175
- detail=str(e)[:2000])
176
-
177
- self._tools_registered += total
178
- return total
179
-
180
- @staticmethod
181
- def _record(name: str, *, code: str, reason: str, detail: str = "") -> None:
182
- """记账 + 屏蔽一条外部服务器。它自己不许炸(记不上账不该中断启动)。
183
-
184
- 归属键逐字同 `register_external_server` 那一处
185
- (它是"工具属于谁"的唯一来源,见 `bus/quarantine.owner_for_mcp`)。
186
- """
187
- try:
188
- from bus.quarantine import owner_for_mcp, quarantine, describe
189
- print(describe(quarantine(owner_for_mcp(name), code=code,
190
- reason=reason, detail=detail)))
191
- except Exception as inner: # noqa: BLE001
192
- print(f"[quarantine] 记账失败({type(inner).__name__}: {inner})")
193
-
194
- @staticmethod
195
- def _clear(name: str) -> None:
196
- """连上了,把这条的旧账划掉(幂等:没有那条账就什么都不做)。"""
197
- try:
198
- from bus.quarantine import all_entries, owner_for_mcp, release
199
- owner = owner_for_mcp(name)
200
- if owner in all_entries():
201
- release(owner)
202
- print(f"[quarantine] '{owner}' 这次连上了 —— **已解封**")
203
- except Exception as inner: # noqa: BLE001
204
- print(f"[quarantine] 解封失败({type(inner).__name__}: {inner})")
205
-
206
- def get_status(self) -> dict:
207
- """MCP 子系统的状态。两半都必须据实:
208
-
209
- 不要返回手抄的常数(例如把内置数量写死为 `1`)——
210
- 名字要从 `mcpx.servers.BUILTIN_SERVERS` 来、外部的从 `_external_servers` 现数。
211
- """
212
- from mcpx.servers import BUILTIN_SERVERS
213
- return {
214
- "builtin_servers": len(BUILTIN_SERVERS),
215
- "builtin_names": list(BUILTIN_SERVERS),
216
- "external_servers": len(self._external_servers),
217
- "external_names": sorted(self._external_servers),
218
- "tools_registered": self._tools_registered,
219
- }
220
-
221
-
222
- async def _connect_stdio(name: str, cfg: dict):
223
- """Async helper for stdio connections."""
224
- from mcpx.client import connect_stdio_server
225
- return await connect_stdio_server(
226
- name=name,
227
- command=cfg["command"],
228
- args=cfg.get("args", []),
229
- env=cfg.get("env"),
230
- # `plugin_root` 不是从配置里推断出来的,而是"这个 server 住在哪个
231
- # 插件目录";入口只有这一个,显式声明才认。
232
- plugin_root=cfg.get("plugin_root"),
233
- )
234
-
235
-
236
- async def _connect_http(name: str, cfg: dict):
237
- """Async helper for HTTP connections."""
238
- from mcpx.client import connect_http_server
239
- return await connect_http_server(
240
- name=name,
241
- url=cfg["url"],
242
- headers=cfg.get("headers") or None,
243
- )
244
-
245
-
246
- # ------------------------------------------------------------------
247
- # Module-level singleton
248
- # ------------------------------------------------------------------
249
-
250
- _manager: MCPManager | None = None
251
-
252
-
253
- def get_manager() -> MCPManager:
254
- """Return the module-level MCPManager singleton."""
255
- global _manager
256
- if _manager is None:
257
- _manager = MCPManager()
258
- return _manager
259
-
260
-
261
- def init_mcp(config: dict | None = None) -> int:
262
- """
263
- One-shot initialisation called by bus/core.py at startup.
264
-
265
- Loads built-in servers and external servers from
266
- `data/mcp_servers.json` (standard MCP format).
267
-
268
- Returns the number of MCP tools registered.
269
- """
270
- mgr = get_manager()
271
- mgr.config = config or {}
272
-
273
- total = mgr.load_builtin_servers()
274
-
275
- # Load external servers from data/mcp_servers.json (standard format)
276
- external = _load_external_config()
277
- if not external:
278
- # Fallback: legacy config.yaml mcp_servers
279
- external = mgr.config.get("mcp_servers", [])
280
-
281
- if external:
282
- total += mgr.connect_external(external)
283
-
284
- print(f"[mcp] Initialised: {total} tools ({len(mgr._external_servers)} external servers)")
285
- return total
286
-
287
-
288
- #: 配置里的环境变量占位符:`${NAME}`。
289
- #: 展开发生在解析那一刻(我们进程内),因为 stdio 的子进程环境是
290
- #: 白名单清洗过的 —— 把展开留给它拿不到值。
291
- _ENV_PLACEHOLDER = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
292
-
293
-
294
- def _expand_headers(raw):
295
- """把 `{"Authorization": "Bearer ${TOKEN}"}` 展开成真值。
296
-
297
- 返回 `(headers, missing)`:`missing` 非空,这个 server 该被跳过并出声。
298
- 只念变量名,不念值 —— 那是凭据,它不该出现在任何一行日志里。
299
- """
300
- if not isinstance(raw, dict) or not raw:
301
- return {}, []
302
- out: dict = {}
303
- missing: list[str] = []
304
- for k, v in raw.items():
305
- if not isinstance(v, str):
306
- continue
307
-
308
- def _sub(m, _missing=missing):
309
- name = m.group(1)
310
- val = os.environ.get(name)
311
- if not val:
312
- _missing.append(name)
313
- return m.group(0)
314
- return val
315
-
316
- out[str(k)] = _ENV_PLACEHOLDER.sub(_sub, v)
317
- return out, missing
318
-
319
-
320
- #: 插件根占位符。声明了 `plugin_root` 时在 command / args / env 里替换。
321
- _PLUGIN_ROOT_TOKENS = ("${CLAUDE_PLUGIN_ROOT}", "${CRANNIA_PLUGIN_ROOT}")
322
-
323
-
324
- def _expand_plugin_root(value, root):
325
- """把插件根占位符替换成实际路径。未声明 plugin_root 时原样返回。"""
326
- if not root:
327
- return value
328
- if isinstance(value, str):
329
- for token in _PLUGIN_ROOT_TOKENS:
330
- value = value.replace(token, str(root))
331
- return value
332
- if isinstance(value, list):
333
- return [_expand_plugin_root(v, root) for v in value]
334
- if isinstance(value, dict):
335
- return {k: _expand_plugin_root(v, root) for k, v in value.items()}
336
- return value
337
-
338
-
339
- def _looks_like_server(v) -> bool:
340
- """一个值像不像"MCP 服务器配置":dict,且带 `command` 或 `url`。
341
-
342
- 判据窄是有意的:宁可少认一条,也不能把 `{"$schema": "..."}` 这种
343
- 键当成服务器名(那会去起一个叫 `$schema` 的进程)。
344
- """
345
- return isinstance(v, dict) and ("command" in v or "url" in v)
346
-
347
-
348
- def _looks_like_flat_map(data) -> bool:
349
- """整份配置是不是平铺的(没有 `mcpServers`,每个值都像服务器)。
350
-
351
- 全部值都要像 —— 有一个不像就不是平铺,按坏配置处理(返回空)。
352
- """
353
- return (isinstance(data, dict) and bool(data)
354
- and all(_looks_like_server(v) for v in data.values()))
355
-
356
-
357
- def _load_user_mcp_config() -> list[dict]:
358
- """
359
- Load external MCP server configs from `data/mcp_servers.json`.
360
-
361
- Converts the standard MCP format::
362
-
363
- {"mcpServers": {"name": {"command": "npx", "args": [...]}}}
364
-
365
- to the internal format::
366
-
367
- [{"name": "name", "transport": "stdio", "command": "npx", "args": [...]}]
368
- """
369
- import json
370
- from pathlib import Path
371
-
372
- cfg_path = Path("data/mcp_servers.json")
373
- if not cfg_path.exists():
374
- return []
375
-
376
- try:
377
- data = json.loads(cfg_path.read_text(encoding="utf-8"))
378
- except (json.JSONDecodeError, OSError) as e:
379
- print(f"[mcp] WARNING: Failed to parse mcp_servers.json: {e}")
380
- return []
381
-
382
- servers = data.get("mcpServers")
383
- if isinstance(servers, dict) and servers:
384
- # 包装层优先。顶层同时还有 server 条目,收前者、忽略后者并出声
385
- # (静默丢配置是反模式;混写说明用户以为两份都生效)。
386
- extra = [k for k, v in data.items()
387
- if k != "mcpServers" and _looks_like_server(v)]
388
- if extra:
389
- print("[mcp] 这份配置同时有 `mcpServers` 和顶层条目 —— "
390
- "只收前者,忽略 %s" % ", ".join(sorted(extra)))
391
- elif _looks_like_flat_map(data):
392
- # 平铺形状:没有 `mcpServers` 包装层,直接是 `{"名字": {...}}`。
393
- # 相当一部分现成配置是这一种 —— 只认包装层会有一大片装不上。
394
- servers = data
395
- else:
396
- return []
397
- if not servers:
398
- return []
399
-
400
- return _entries_from_servers(servers)
401
-
402
-
403
- def _entries_from_servers(servers: dict, default_root: str | None = None) -> list[dict]:
404
- """把一份 `{名字: 配置}` 收成内部条目。*default_root* 用于插件包。"""
405
- result: list[dict] = []
406
- for name, cfg in servers.items():
407
- entry: dict = {"name": name}
408
-
409
- # `trusted_output` 必须跟着走这一跳。
410
- # 消费点 `connect_external` 读的是转换后的 cfg,不是原始配置 ——
411
- # 原来这一格只留在原始 cfg 里,到这里就没了,于是
412
- # `register_external_server(..., trusted_output=False)` 永远是 False。
413
- # 用户按文档写了 `trusted_output: true`,输出照样被隔离;而没有任何
414
- # 东西红(注册函数那条 `is True` 只是没命中)。
415
- # 只收真 True —— 与消费点同一条严格判定,字符串 "true" 不算。
416
- if cfg.get("trusted_output") is True:
417
- entry["trusted_output"] = True
418
-
419
- command = cfg.get("command", "")
420
- args = cfg.get("args", [])
421
- env = cfg.get("env", {})
422
-
423
- if command:
424
- # stdio transport (has a command to run)
425
- _root = cfg.get("plugin_root") or default_root
426
- entry["transport"] = "stdio"
427
- entry["command"] = _expand_plugin_root(command, _root)
428
- entry["args"] = _expand_plugin_root(args, _root)
429
- entry["env"] = _expand_plugin_root(env, _root)
430
- # `plugin_root` 是我们加的一个键 ——
431
- # 标准 MCP 配置里没有它(那个值来自"文件在哪个插件目录")。
432
- # 插件布局解析可以自动填这一格;
433
- # 在那之前,手写一个就能让"靠 `CLAUDE_PLUGIN_ROOT` 找自己文件"
434
- # 的 server 跑起来。
435
- if _root:
436
- entry["plugin_root"] = _root
437
- elif cfg.get("url"):
438
- # HTTP transport (has a URL)
439
- entry["transport"] = "streamable_http"
440
- entry["url"] = cfg["url"]
441
- # 认证头:展开 `${VAR}`;缺变量就跳过这个 server 并出声
442
- # (fail-closed —— 发一个空 token 上去只会得到一次 401,而
443
- # 用户看不出是"本机没配"还是"服务端拒了")。
444
- hdrs, missing = _expand_headers(cfg.get("headers"))
445
- if missing:
446
- print("[mcp] WARNING: server '%s' 需要环境变量 %s,本机没有 —— 跳过"
447
- % (name, ", ".join(sorted(set(missing)))))
448
- continue
449
- if hdrs:
450
- entry["headers"] = hdrs
451
- else:
452
- print(f"[mcp] WARNING: Server '{name}' missing 'command' or 'url' — skipped")
453
- continue
454
-
455
- result.append(entry)
456
-
457
- return result
458
-
459
-
460
- def _package_mcp_configs(taken: set) -> list[dict]:
461
- """插件包里的 `.mcp.json`。只扫用户自己放的包根,不扫其他产品的缓存。
462
-
463
- *taken* 是已经被用户配置文件占用的服务器名:重名时以用户配置为准。
464
- """
465
- import json
466
- from pathlib import Path
467
-
468
- try:
469
- from core import plugin_packages as _pp
470
- except Exception: # noqa: BLE001
471
- return []
472
-
473
- roots = [Path("plugins"),
474
- Path(".agents") / "plugins",
475
- Path.home() / ".agents" / "plugins"]
476
- allowed = _pp.workspace_plugins_allowed()
477
- out: list[dict] = []
478
- for pkg in _pp.discover_packages(roots):
479
- if pkg.from_workspace and not allowed:
480
- if (pkg.root / ".mcp.json").is_file():
481
- print("[mcp] 工作区插件包 %s 的 .mcp.json 没有加载:要先在"
482
- "「设置 → 安全设置 → 工作区插件」里打开" % pkg.name)
483
- continue
484
- f = pkg.root / ".mcp.json"
485
- if not f.is_file():
486
- continue
487
- try:
488
- data = json.loads(f.read_text(encoding="utf-8"))
489
- except Exception as exc: # noqa: BLE001
490
- print("[mcp] WARNING: 插件包 %s 的 .mcp.json 读不出来(%s: %s)—— 跳过"
491
- % (pkg.name, type(exc).__name__, exc))
492
- continue
493
- servers = data.get("mcpServers") if isinstance(data, dict) else None
494
- if not isinstance(servers, dict):
495
- servers = data if _looks_like_flat_map(data) else {}
496
- if not isinstance(servers, dict) or not servers:
497
- continue
498
- dup = sorted(set(servers) & taken)
499
- if dup:
500
- print("[mcp] 插件包 %s 的服务器 %s 与已有配置重名 —— 以已有配置为准"
501
- % (pkg.name, ", ".join(dup)))
502
- servers = {k: v for k, v in servers.items() if k not in taken}
503
- # 绝对路径:子进程的 cwd 不一定与我们相同。
504
- try:
505
- _root = str(pkg.root.resolve())
506
- except OSError:
507
- _root = str(pkg.root)
508
- entries = _entries_from_servers(servers, default_root=_root)
509
- taken.update(e["name"] for e in entries)
510
- out.extend(entries)
511
- return out
512
-
513
-
514
- def _load_external_config() -> list[dict]:
515
- """外部 MCP 配置:用户文件优先,插件包补充。
516
-
517
- 插件包里的服务器自动带上 `plugin_root`,因此 `.mcp.json` 里可以用
518
- `${CLAUDE_PLUGIN_ROOT}` 定位自己的文件。
519
- """
520
- user = _load_user_mcp_config()
521
- taken = {e["name"] for e in user}
522
- return user + _package_mcp_configs(taken)
1
+ """
2
+ MCP Manager — lifecycle, built-in server loading, external connection management.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ import re
9
+ from dataclasses import dataclass, field
10
+ from typing import Any
11
+
12
+ #: 「运行环境缺失」不是「连不上」。
13
+ #:
14
+ #: 现场:没装 Node 的机器上,`npx` 不存在,`_connect_stdio` 抛
15
+ #: `FileNotFoundError [WinError 2]`,被记成 `mcp_connect_failed`,界面弹
16
+ #: 「兼容性警告 / 不支持 / 已被 Crannia 屏蔽」。
17
+ #: 而真正的原因是这台机器少了那个可执行文件 —— 装上就好,
18
+ #: 和"这个插件坏了"是两件完全不同的事(标签在说谎)。
19
+ MCP_MISSING_RUNTIME = "mcp_missing_runtime"
20
+
21
+ #: 缺哪个可执行文件时该怎么跟用户说。只影响文案,不影响判定。
22
+ _RUNTIME_HINTS = {
23
+ "npx": "Node.js(安装包自带npx)",
24
+ "node": "Node.js",
25
+ "npm": "Node.js(安装包自带npm)",
26
+ "uvx": "uv(装好后 uvx 才在 PATH 上)",
27
+ "uv": "uv(装好后 uv 才在 PATH 上)",
28
+ "python": "Python",
29
+ "python3": "Python",
30
+ }
31
+
32
+
33
+ def missing_runtime(cfg: dict) -> str:
34
+ """stdio 服务器的启动命令在这台机器上找不找得到。
35
+
36
+ 返回缺的那个命令名(空串 = 没问题)。只对 stdio 有意义:
37
+ `sse` / `streamable_http` 没有本地可执行文件。
38
+ """
39
+ import shutil
40
+ from pathlib import Path
41
+
42
+ if str(cfg.get("transport") or "stdio") != "stdio":
43
+ return ""
44
+ cmd = str(cfg.get("command") or "").strip()
45
+ if not cmd:
46
+ # 缺 `command` 是另一个错(配置写坏了),交给下面真实的连接去报 ——
47
+ # 在这里冒充"缺运行时"会把一个配置错误说成"你没装东西"。
48
+ return ""
49
+ if "/" in cmd or "\\" in cmd:
50
+ # 带路径的写法(`./node_modules/.bin/x`、`C:\node\npx.cmd`):判文件在不在,
51
+ # 不走 PATH —— `which()` 对带路径的输入语义与平台有关。
52
+ return "" if Path(cmd).is_file() else cmd
53
+ return "" if shutil.which(cmd) else cmd
54
+
55
+
56
+ def missing_runtime_reason(name: str, cmd: str) -> str:
57
+ """给用户看的那句话。不出现「不兼容 / 不支持 / 已屏蔽」。"""
58
+ hint = _RUNTIME_HINTS.get(cmd.lower().replace(".cmd", "").replace(".exe", ""),
59
+ "它依赖的那个程序")
60
+ return ("外部 MCP 服务器「%s」要用命令 %s 启动,当前环境找不到此对象。"
61
+ "这不是兼容性问题 —— 装上%s之后重启尝试;"
62
+ "或改用 Python(python -m …)或 HTTP 型的 MCP 服务器。"
63
+ % (name, cmd, hint))
64
+
65
+
66
+ @dataclass
67
+ class MCPManager:
68
+ """Central orchestrator for MCP integration.
69
+
70
+ Called once at framework startup by bus/core.py. Loads built-in
71
+ servers, optionally connects to configured external servers, and
72
+ bridges all discovered tools to bus/registry.
73
+ """
74
+
75
+ config: dict = field(default_factory=dict)
76
+ _external_servers: dict[str, Any] = field(default_factory=dict)
77
+ _tools_registered: int = 0
78
+
79
+ def load_builtin_servers(self) -> int:
80
+ """
81
+ Load all built-in MCP servers and register their tools.
82
+
83
+ Built-in servers are defined in mcp/servers/ and run in-process.
84
+ Their tools are directly registered to bus/registry without
85
+ going through MCP transport.
86
+
87
+ Returns the total number of tools registered.
88
+ """
89
+ import importlib
90
+ from mcpx.servers import BUILTIN_SERVERS
91
+
92
+ total = 0
93
+ # 按 **`mcpx/servers/__init__.py::BUILTIN_SERVERS`**
94
+ # 那份名单去 import —— 不要在这里写死某个具体模块名,
95
+ # 否则"内置 MCP 有哪几条"会在三个地方各有一份(这里 / `get_status`
96
+ # 里那个常数 / `web/server.py` 的两处硬编码)。
97
+ for name in BUILTIN_SERVERS:
98
+ try:
99
+ mod = importlib.import_module("mcpx.servers." + name)
100
+ n = mod.register_tools()
101
+ total += n
102
+ print(f"[mcp] Built-in {name}: {n} tools registered")
103
+ except Exception as e: # noqa: BLE001
104
+ print(f"[mcp] WARNING: Failed to load {name} server: {e}")
105
+
106
+ self._tools_registered = total
107
+ return total
108
+
109
+ def connect_external(self, server_configs: list[dict]) -> int:
110
+ """
111
+ Connect to external MCP servers and register their tools.
112
+
113
+ Each config dict should have:
114
+ - name: str
115
+ - transport: "stdio" | "sse" | "streamable_http"
116
+ - command, args, env (for stdio)
117
+ - url (for HTTP)
118
+
119
+ Returns the number of tools registered.
120
+ """
121
+ # 必须用 `submit(...)`,不能用 `asyncio.run(...)`。
122
+ # 每个 server 起一个新的循环时,连接绑定在"建立它的那个循环"上
123
+ #循环一退连接就废(症状同 `mcpx/bridge.py::_run_async` 那条)。
124
+ #全部投到同一个常驻循环上(`core/async_loop.py`)。
125
+ from core.async_loop import submit
126
+
127
+ total = 0
128
+ for cfg in server_configs:
129
+ name = cfg.get("name", "unknown")
130
+ transport = cfg.get("transport", "stdio")
131
+
132
+ # 连之前先看环境:缺 `npx` / `uvx` 与"服务器坏了"
133
+ # 是两件事,而它们此前被压成同一句「不兼容 / 已屏蔽」。
134
+ missing = missing_runtime(cfg)
135
+ if missing:
136
+ print(f"[mcp] '{name}' 跳过:找不到命令 {missing}(运行环境缺失,不是兼容性问题)")
137
+ # `detail` 只写 ASCII 的 `command=<名字>`:界面从这一格里
138
+ # 抠命令名,再用 `t()` 拼一句当前语言的提示(`plugin-notice-view.js
139
+ # 的 missingCommand`)。写中文进去,英文界面就只能显示中文。
140
+ self._record(name, code=MCP_MISSING_RUNTIME,
141
+ reason=missing_runtime_reason(name, missing),
142
+ detail="command=%s" % missing)
143
+ continue
144
+
145
+ try:
146
+ if transport == "stdio":
147
+ server = submit(_connect_stdio(name, cfg))
148
+ elif transport in ("sse", "streamable_http"):
149
+ server = submit(_connect_http(name, cfg))
150
+ else:
151
+ print(f"[mcp] Unknown transport '{transport}' for server '{name}'")
152
+ continue
153
+
154
+ if server and server._tools:
155
+ from mcpx.client import register_external_server
156
+ n = register_external_server(
157
+ server, trusted_output=cfg.get("trusted_output") is True,
158
+ egress=cfg.get("egress"))
159
+ self._external_servers[name] = server
160
+ total += n
161
+ print(f"[mcp] External '{name}': {n} tools ({transport})")
162
+ # 连上了就把旧账划掉——
163
+ # 账本是持久的,而闸只看账本。用户装好 Node 再重启时,
164
+ # 上一次那条 `mcp_missing_runtime` / `mcp_connect_failed`
165
+ # 还在,服务器连上了、工具却全被摘掉,而且不会再弹窗
166
+ # (`hits` 已经不是 1)。一个"修好也没救"的死结。
167
+ self._clear(name)
168
+ except Exception as e:
169
+ print(f"[mcp] WARNING: Failed to connect '{name}': {e}")
170
+ # 连不上的外部服务器要记账 + 屏蔽。
171
+ # 只 print 一行、不落任何状态时 —— "这台服务器挂了"
172
+ # 只在启动那一刻的终端里有一行字,而工具要么没注册(模型说
173
+ # "我没有这个工具"),要么注册了、调用时才抛(模型自己去猜)。
174
+ self._record(name, code="mcp_connect_failed",
175
+ reason="外部 MCP 服务器连不上:%s: %s" % (type(e).__name__, e),
176
+ detail=str(e)[:2000])
177
+
178
+ self._tools_registered += total
179
+ return total
180
+
181
+ @staticmethod
182
+ def _record(name: str, *, code: str, reason: str, detail: str = "") -> None:
183
+ """记账 + 屏蔽一条外部服务器。它自己不许炸(记不上账不该中断启动)。
184
+
185
+ 归属键逐字同 `register_external_server` 那一处
186
+ (它是"工具属于谁"的唯一来源,见 `bus/quarantine.owner_for_mcp`)。
187
+ """
188
+ try:
189
+ from bus.quarantine import owner_for_mcp, quarantine, describe
190
+ print(describe(quarantine(owner_for_mcp(name), code=code,
191
+ reason=reason, detail=detail)))
192
+ except Exception as inner: # noqa: BLE001
193
+ print(f"[quarantine] 记账失败({type(inner).__name__}: {inner})")
194
+
195
+ @staticmethod
196
+ def _clear(name: str) -> None:
197
+ """连上了,把这条的旧账划掉(幂等:没有那条账就什么都不做)。"""
198
+ try:
199
+ from bus.quarantine import all_entries, owner_for_mcp, release
200
+ owner = owner_for_mcp(name)
201
+ if owner in all_entries():
202
+ release(owner)
203
+ print(f"[quarantine] '{owner}' 这次连上了 —— **已解封**")
204
+ except Exception as inner: # noqa: BLE001
205
+ print(f"[quarantine] 解封失败({type(inner).__name__}: {inner})")
206
+
207
+ def get_status(self) -> dict:
208
+ """MCP 子系统的状态。两半都必须据实:
209
+
210
+ 不要返回手抄的常数(例如把内置数量写死为 `1`)——
211
+ 名字要从 `mcpx.servers.BUILTIN_SERVERS` 来、外部的从 `_external_servers` 现数。
212
+ """
213
+ from mcpx.servers import BUILTIN_SERVERS
214
+ return {
215
+ "builtin_servers": len(BUILTIN_SERVERS),
216
+ "builtin_names": list(BUILTIN_SERVERS),
217
+ "external_servers": len(self._external_servers),
218
+ "external_names": sorted(self._external_servers),
219
+ "tools_registered": self._tools_registered,
220
+ }
221
+
222
+
223
+ async def _connect_stdio(name: str, cfg: dict):
224
+ """Async helper for stdio connections."""
225
+ from mcpx.client import connect_stdio_server
226
+ return await connect_stdio_server(
227
+ name=name,
228
+ command=cfg["command"],
229
+ args=cfg.get("args", []),
230
+ env=cfg.get("env"),
231
+ # `plugin_root` 不是从配置里推断出来的,而是"这个 server 住在哪个
232
+ # 插件目录";入口只有这一个,显式声明才认。
233
+ plugin_root=cfg.get("plugin_root"),
234
+ )
235
+
236
+
237
+ async def _connect_http(name: str, cfg: dict):
238
+ """Async helper for HTTP connections."""
239
+ from mcpx.client import connect_http_server
240
+ return await connect_http_server(
241
+ name=name,
242
+ url=cfg["url"],
243
+ headers=cfg.get("headers") or None,
244
+ )
245
+
246
+
247
+ # ------------------------------------------------------------------
248
+ # Module-level singleton
249
+ # ------------------------------------------------------------------
250
+
251
+ _manager: MCPManager | None = None
252
+
253
+
254
+ def get_manager() -> MCPManager:
255
+ """Return the module-level MCPManager singleton."""
256
+ global _manager
257
+ if _manager is None:
258
+ _manager = MCPManager()
259
+ return _manager
260
+
261
+
262
+ def init_mcp(config: dict | None = None) -> int:
263
+ """
264
+ One-shot initialisation called by bus/core.py at startup.
265
+
266
+ Loads built-in servers and external servers from
267
+ `data/mcp_servers.json` (standard MCP format).
268
+
269
+ Returns the number of MCP tools registered.
270
+ """
271
+ mgr = get_manager()
272
+ mgr.config = config or {}
273
+
274
+ total = mgr.load_builtin_servers()
275
+
276
+ # Load external servers from data/mcp_servers.json (standard format)
277
+ external = _load_external_config()
278
+ if not external:
279
+ # Fallback: legacy config.yaml mcp_servers
280
+ external = mgr.config.get("mcp_servers", [])
281
+
282
+ if external:
283
+ total += mgr.connect_external(external)
284
+
285
+ print(f"[mcp] Initialised: {total} tools ({len(mgr._external_servers)} external servers)")
286
+ return total
287
+
288
+
289
+ #: 配置里的环境变量占位符:`${NAME}`。
290
+ #: 展开发生在解析那一刻(我们进程内),因为 stdio 的子进程环境是
291
+ #: 白名单清洗过的 —— 把展开留给它拿不到值。
292
+ _ENV_PLACEHOLDER = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
293
+
294
+
295
+ def _expand_headers(raw):
296
+ """把 `{"Authorization": "Bearer ${TOKEN}"}` 展开成真值。
297
+
298
+ 返回 `(headers, missing)`:`missing` 非空,这个 server 该被跳过并出声。
299
+ 只念变量名,不念值 —— 那是凭据,它不该出现在任何一行日志里。
300
+ """
301
+ if not isinstance(raw, dict) or not raw:
302
+ return {}, []
303
+ out: dict = {}
304
+ missing: list[str] = []
305
+ for k, v in raw.items():
306
+ if not isinstance(v, str):
307
+ continue
308
+
309
+ def _sub(m, _missing=missing):
310
+ name = m.group(1)
311
+ val = os.environ.get(name)
312
+ if not val:
313
+ _missing.append(name)
314
+ return m.group(0)
315
+ return val
316
+
317
+ out[str(k)] = _ENV_PLACEHOLDER.sub(_sub, v)
318
+ return out, missing
319
+
320
+
321
+ #: 插件根占位符。声明了 `plugin_root` 时在 command / args / env 里替换。
322
+ _PLUGIN_ROOT_TOKENS = ("${CLAUDE_PLUGIN_ROOT}", "${CRANNIA_PLUGIN_ROOT}")
323
+
324
+
325
+ def _expand_plugin_root(value, root):
326
+ """把插件根占位符替换成实际路径。未声明 plugin_root 时原样返回。"""
327
+ if not root:
328
+ return value
329
+ if isinstance(value, str):
330
+ for token in _PLUGIN_ROOT_TOKENS:
331
+ value = value.replace(token, str(root))
332
+ return value
333
+ if isinstance(value, list):
334
+ return [_expand_plugin_root(v, root) for v in value]
335
+ if isinstance(value, dict):
336
+ return {k: _expand_plugin_root(v, root) for k, v in value.items()}
337
+ return value
338
+
339
+
340
+ def _looks_like_server(v) -> bool:
341
+ """一个值像不像"MCP 服务器配置":dict,且带 `command` 或 `url`。
342
+
343
+ 判据窄是有意的:宁可少认一条,也不能把 `{"$schema": "..."}` 这种
344
+ 键当成服务器名(那会去起一个叫 `$schema` 的进程)。
345
+ """
346
+ return isinstance(v, dict) and ("command" in v or "url" in v)
347
+
348
+
349
+ def _looks_like_flat_map(data) -> bool:
350
+ """整份配置是不是平铺的(没有 `mcpServers`,每个值都像服务器)。
351
+
352
+ 全部值都要像 —— 有一个不像就不是平铺,按坏配置处理(返回空)。
353
+ """
354
+ return (isinstance(data, dict) and bool(data)
355
+ and all(_looks_like_server(v) for v in data.values()))
356
+
357
+
358
+ def _load_user_mcp_config() -> list[dict]:
359
+ """
360
+ Load external MCP server configs from `data/mcp_servers.json`.
361
+
362
+ Converts the standard MCP format::
363
+
364
+ {"mcpServers": {"name": {"command": "npx", "args": [...]}}}
365
+
366
+ to the internal format::
367
+
368
+ [{"name": "name", "transport": "stdio", "command": "npx", "args": [...]}]
369
+ """
370
+ import json
371
+ from pathlib import Path
372
+
373
+ cfg_path = Path("data/mcp_servers.json")
374
+ if not cfg_path.exists():
375
+ return []
376
+
377
+ try:
378
+ data = json.loads(cfg_path.read_text(encoding="utf-8"))
379
+ except (json.JSONDecodeError, OSError) as e:
380
+ print(f"[mcp] WARNING: Failed to parse mcp_servers.json: {e}")
381
+ return []
382
+
383
+ servers = data.get("mcpServers")
384
+ if isinstance(servers, dict) and servers:
385
+ # 包装层优先。顶层同时还有 server 条目,收前者、忽略后者并出声
386
+ # (静默丢配置是反模式;混写说明用户以为两份都生效)。
387
+ extra = [k for k, v in data.items()
388
+ if k != "mcpServers" and _looks_like_server(v)]
389
+ if extra:
390
+ print("[mcp] 这份配置同时有 `mcpServers` 和顶层条目 —— "
391
+ "只收前者,忽略 %s" % ", ".join(sorted(extra)))
392
+ elif _looks_like_flat_map(data):
393
+ # 平铺形状:没有 `mcpServers` 包装层,直接是 `{"名字": {...}}`。
394
+ # 相当一部分现成配置是这一种 —— 只认包装层会有一大片装不上。
395
+ servers = data
396
+ else:
397
+ return []
398
+ if not servers:
399
+ return []
400
+
401
+ return _entries_from_servers(servers)
402
+
403
+
404
+ def _entries_from_servers(servers: dict, default_root: str | None = None) -> list[dict]:
405
+ """把一份 `{名字: 配置}` 收成内部条目。*default_root* 用于插件包。"""
406
+ result: list[dict] = []
407
+ for name, cfg in servers.items():
408
+ entry: dict = {"name": name}
409
+
410
+ # `trusted_output` 必须跟着走这一跳。
411
+ # 消费点 `connect_external` 读的是转换后的 cfg,不是原始配置 ——
412
+ # 原来这一格只留在原始 cfg 里,到这里就没了,于是
413
+ # `register_external_server(..., trusted_output=False)` 永远是 False。
414
+ # 用户按文档写了 `trusted_output: true`,输出照样被隔离;而没有任何
415
+ # 东西红(注册函数那条 `is True` 只是没命中)。
416
+ # 只收真 True —— 与消费点同一条严格判定,字符串 "true" 不算。
417
+ if cfg.get("trusted_output") is True:
418
+ entry["trusted_output"] = True
419
+
420
+ # 出网声明(P4):MCP 工具也要能被能力目录看见,否则它就是一条
421
+ # 不受声明的 egress(`core/egress_channels` 的读者会点名)。形状与
422
+ # 技能 manifest 的 `egress:` 段同一张表:channel / target / route_for /
423
+ # auto / audit。只收对象;坏的让 `declare` 出声拒绝。
424
+ if isinstance(cfg.get("egress"), dict):
425
+ entry["egress"] = dict(cfg["egress"])
426
+
427
+ command = cfg.get("command", "")
428
+ args = cfg.get("args", [])
429
+ env = cfg.get("env", {})
430
+
431
+ if command:
432
+ # stdio transport (has a command to run)
433
+ _root = cfg.get("plugin_root") or default_root
434
+ entry["transport"] = "stdio"
435
+ entry["command"] = _expand_plugin_root(command, _root)
436
+ entry["args"] = _expand_plugin_root(args, _root)
437
+ entry["env"] = _expand_plugin_root(env, _root)
438
+ # `plugin_root` 是我们加的一个键 ——
439
+ # 标准 MCP 配置里没有它(那个值来自"文件在哪个插件目录")。
440
+ # 插件布局解析可以自动填这一格;
441
+ # 在那之前,手写一个就能让"靠 `CLAUDE_PLUGIN_ROOT` 找自己文件"
442
+ # 的 server 跑起来。
443
+ if _root:
444
+ entry["plugin_root"] = _root
445
+ elif cfg.get("url"):
446
+ # HTTP transport (has a URL)
447
+ entry["transport"] = "streamable_http"
448
+ entry["url"] = cfg["url"]
449
+ # 认证头:展开 `${VAR}`;缺变量就跳过这个 server 并出声
450
+ # (fail-closed —— 发一个空 token 上去只会得到一次 401,而
451
+ # 用户看不出是"本机没配"还是"服务端拒了")。
452
+ hdrs, missing = _expand_headers(cfg.get("headers"))
453
+ if missing:
454
+ print("[mcp] WARNING: server '%s' 需要环境变量 %s,本机没有 —— 跳过"
455
+ % (name, ", ".join(sorted(set(missing)))))
456
+ continue
457
+ if hdrs:
458
+ entry["headers"] = hdrs
459
+ else:
460
+ print(f"[mcp] WARNING: Server '{name}' missing 'command' or 'url' — skipped")
461
+ continue
462
+
463
+ result.append(entry)
464
+
465
+ return result
466
+
467
+
468
+ def _package_mcp_configs(taken: set) -> list[dict]:
469
+ """插件包里的 `.mcp.json`。只扫用户自己放的包根,不扫其他产品的缓存。
470
+
471
+ *taken* 是已经被用户配置文件占用的服务器名:重名时以用户配置为准。
472
+ """
473
+ import json
474
+ from pathlib import Path
475
+
476
+ try:
477
+ from core import plugin_packages as _pp
478
+ except Exception: # noqa: BLE001
479
+ return []
480
+
481
+ roots = [Path("plugins"),
482
+ Path(".agents") / "plugins",
483
+ Path.home() / ".agents" / "plugins"]
484
+ allowed = _pp.workspace_plugins_allowed()
485
+ out: list[dict] = []
486
+ for pkg in _pp.discover_packages(roots):
487
+ if pkg.from_workspace and not allowed:
488
+ if (pkg.root / ".mcp.json").is_file():
489
+ print("[mcp] 工作区插件包 %s 的 .mcp.json 没有加载:要先在"
490
+ "「设置 → 安全设置 → 工作区插件」里打开" % pkg.name)
491
+ continue
492
+ f = pkg.root / ".mcp.json"
493
+ if not f.is_file():
494
+ continue
495
+ try:
496
+ data = json.loads(f.read_text(encoding="utf-8"))
497
+ except Exception as exc: # noqa: BLE001
498
+ print("[mcp] WARNING: 插件包 %s 的 .mcp.json 读不出来(%s: %s)—— 跳过"
499
+ % (pkg.name, type(exc).__name__, exc))
500
+ continue
501
+ servers = data.get("mcpServers") if isinstance(data, dict) else None
502
+ if not isinstance(servers, dict):
503
+ servers = data if _looks_like_flat_map(data) else {}
504
+ if not isinstance(servers, dict) or not servers:
505
+ continue
506
+ dup = sorted(set(servers) & taken)
507
+ if dup:
508
+ print("[mcp] 插件包 %s 的服务器 %s 与已有配置重名 —— 以已有配置为准"
509
+ % (pkg.name, ", ".join(dup)))
510
+ servers = {k: v for k, v in servers.items() if k not in taken}
511
+ # 绝对路径:子进程的 cwd 不一定与我们相同。
512
+ try:
513
+ _root = str(pkg.root.resolve())
514
+ except OSError:
515
+ _root = str(pkg.root)
516
+ entries = _entries_from_servers(servers, default_root=_root)
517
+ taken.update(e["name"] for e in entries)
518
+ out.extend(entries)
519
+ return out
520
+
521
+
522
+ def _load_external_config() -> list[dict]:
523
+ """外部 MCP 配置:用户文件优先,插件包补充。
524
+
525
+ 插件包里的服务器自动带上 `plugin_root`,因此 `.mcp.json` 里可以用
526
+ `${CLAUDE_PLUGIN_ROOT}` 定位自己的文件。
527
+ """
528
+ user = _load_user_mcp_config()
529
+ taken = {e["name"] for e in user}
530
+ return user + _package_mcp_configs(taken)