@hfyjq/crannia 1.0.0 → 1.1.1
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/LICENSE +201 -201
- package/NOTICE +45 -45
- package/THIRD-PARTY-FRONTEND.md +5266 -5266
- package/THIRD-PARTY-PYTHON.md +162 -153
- package/THIRD-PARTY.md +316 -316
- package/apps/desktop/quotes.txt +56 -56
- package/bus/core.py +671 -671
- package/bus/loaders/channel_loader.py +64 -64
- package/bus/loaders/skill_md.py +676 -676
- package/bus/skill_state.py +124 -124
- package/channels/cli_channel/manifest.yaml +5 -5
- package/channels/dingtalk_channel/manifest.yaml +12 -12
- package/channels/feishu_channel/manifest.yaml +12 -12
- package/channels/qq_bot_channel/__init__.py +1 -1
- package/channels/qq_bot_channel/handler.py +881 -881
- package/channels/qq_bot_channel/manifest.yaml +4 -4
- package/channels/telegram_channel/__init__.py +1 -1
- package/channels/telegram_channel/handler.py +813 -813
- package/channels/telegram_channel/manifest.yaml +4 -4
- package/channels/telegram_channel/media.py +231 -231
- package/channels/textfmt.py +58 -58
- package/channels/wechat_channel/__init__.py +1 -1
- package/channels/wechat_channel/auth.py +23 -5
- package/channels/wechat_channel/manifest.yaml +5 -5
- package/channels/wechat_channel/media.py +178 -178
- package/config.yaml +2 -2
- package/core/activity.py +3 -0
- package/core/agent_loop.py +390 -55
- package/core/approval.py +17 -6
- package/core/artifacts.py +7 -0
- package/core/auto_review.py +23 -5
- package/core/channel_configs.py +34 -2
- package/core/channel_turns.py +759 -759
- package/core/child_approval.py +150 -0
- package/core/config_requirements.py +205 -0
- package/core/cron/runner.py +118 -6
- package/core/cron/store.py +14 -5
- package/core/cron/tools.py +17 -5
- package/core/endpoint.py +141 -0
- package/core/events.py +23 -0
- package/core/i18n.py +329 -329
- package/core/ice/store.py +191 -191
- package/core/inbound.py +193 -193
- package/core/jobs.py +19 -3
- package/core/last_good.py +150 -150
- package/core/llm_errors.py +227 -227
- package/core/llm_retry.py +230 -230
- package/core/memory/compressor.py +1214 -1214
- package/core/memory/manager.py +14 -0
- package/core/model_configs.py +80 -0
- package/core/pipeline/scheduler.py +2 -2
- package/core/pipeline/stages/agent_loop.py +24 -4
- package/core/pipeline/stages/pre_process.py +58 -7
- package/core/prompt_assembler.py +680 -680
- package/core/rg.py +255 -255
- package/core/security.py +1544 -1544
- package/core/settings_baseline.py +70 -1
- package/core/shell.py +5 -17
- package/core/skill_settings.py +7 -2
- package/core/state_registry.py +19 -0
- package/core/subagent.py +64 -3
- package/core/task_tool.py +1 -1
- package/core/tasks_notify.py +69 -4
- package/core/tiers.py +9 -3
- package/core/tool_outcome.py +108 -0
- package/core/update_tui.py +158 -0
- package/core/updater.py +229 -40
- package/core/version.py +2 -2
- package/core/web_cache.py +152 -0
- package/crannia_tray.py +278 -278
- package/creators/models.json +4 -4
- package/data/settings.example.json +67 -0
- package/licenses/GPL-3.0.txt +619 -619
- package/licenses/LGPL-2.1.txt +502 -502
- package/licenses/LGPL-3.0.txt +165 -165
- package/licenses/MIT-chat-on-wechat.txt +18 -18
- package/licenses/MIT-deepseek-harness.txt +21 -21
- package/licenses/Molio-LICENSE.txt +44 -44
- package/locales/en.json +9 -4
- package/main.py +154 -154
- package/mcpx/manager.py +522 -522
- package/mcpx/servers/__init__.py +22 -22
- package/mcpx/servers/web_search.py +321 -33
- package/package.json +24 -10
- package/providers/anthropic/client.py +772 -772
- package/providers/cost_table.json +3779 -3779
- package/providers/deepseek/client.py +20 -20
- package/providers/deepseek/manifest.yaml +2 -2
- package/providers/factory.py +136 -136
- package/providers/lmstudio/client.py +2 -2
- package/providers/metadata.py +80 -80
- package/providers/model_capabilities.json +6665 -6665
- package/providers/moonshot/client.py +12 -12
- package/providers/ollama/client.py +2 -2
- package/providers/openai/client.py +13 -13
- package/providers/openrouter/client.py +2 -2
- package/providers/qwen/__init__.py +1 -1
- package/providers/qwen/client.py +2 -2
- package/providers/qwen/manifest.yaml +16 -16
- package/providers/rate_limiter.py +144 -144
- package/providers/siliconflow/client.py +2 -2
- package/providers/validation.py +171 -171
- package/providers/window_table.json +8909 -8909
- package/sbom.json +4413 -4296
- package/skills/entertainment/SKILL.md +35 -35
- package/skills/entertainment/__init__.py +1 -1
- package/skills/entertainment/handler.py +91 -91
- package/skills/entertainment/manifest.yaml +26 -26
- package/skills/file_parser/GUIDANCE.md +10 -10
- package/skills/file_parser/handler.py +177 -4
- package/skills/file_parser/manifest.yaml +22 -1
- package/skills/github/SKILL.md +32 -32
- package/skills/github/__init__.py +1 -1
- package/skills/github/manifest.yaml +5 -0
- package/skills/mail_parser/SKILL.md +68 -68
- package/skills/mail_parser/__init__.py +1 -1
- package/skills/mail_parser/handler.py +806 -806
- package/skills/mail_parser/manifest.yaml +5 -0
- package/skills/media_gen/GUIDANCE.md +19 -19
- package/skills/media_gen/SKILL.md +43 -43
- package/skills/media_gen/__init__.py +1 -1
- package/skills/media_gen/handler.py +430 -430
- package/skills/media_gen/manifest.yaml +93 -88
- package/skills/office_parser/cell_validation.py +127 -127
- package/skills/office_parser/excel_transform.py +936 -936
- package/skills/office_parser/layout_spec.py +243 -243
- package/skills/office_parser/pptx_export/console_encoding.py +27 -27
- package/skills/office_parser/pptx_export/resource_paths.py +88 -88
- package/skills/office_parser/pptx_export/svg_finalize/__init__.py +12 -12
- package/skills/office_parser/pptx_export/svg_finalize/align_embed_images.py +575 -575
- package/skills/office_parser/pptx_export/svg_finalize/crop_images.py +366 -366
- package/skills/office_parser/pptx_export/svg_finalize/embed_icons.py +498 -498
- package/skills/office_parser/pptx_export/svg_finalize/embed_images.py +288 -288
- package/skills/office_parser/pptx_export/svg_finalize/fix_image_aspect.py +388 -388
- package/skills/office_parser/pptx_export/svg_finalize/flatten_tspan.py +818 -818
- package/skills/office_parser/pptx_export/svg_finalize/svg_rect_to_path.py +345 -345
- package/skills/office_parser/pptx_export/svg_to_pptx/__init__.py +14 -14
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/__init__.py +1 -1
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/context.py +186 -186
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/converter.py +781 -781
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/elements.py +2490 -2490
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/paths.py +429 -429
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/styles.py +656 -656
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/__init__.py +1 -1
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/builder.py +1267 -1267
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/dimensions.py +155 -155
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/discovery.py +101 -101
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/media.py +141 -141
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/narration.py +236 -236
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/notes.py +257 -257
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/slide_xml.py +136 -136
- package/skills/office_parser/pptx_export/svg_to_pptx/tspan_flattener.py +44 -44
- package/skills/office_parser/pptx_export/svg_to_pptx/use_expander.py +129 -129
- package/skills/office_parser/references/LICENSE-Office-Word-MCP-Server.txt +20 -20
- package/skills/office_parser/references/LICENSE-excel-mcp-server.txt +21 -21
- package/skills/office_parser/references/layout_library.md +816 -816
- package/skills/office_parser/references/ppt-master/LICENSE +21 -21
- package/skills/office_parser/references/ppt-master/references/executor-base.md +474 -474
- package/skills/office_parser/references/ppt-master/references/shared-standards.md +1002 -1002
- package/skills/office_parser/references/ppt-master/references/strategist.md +880 -880
- package/skills/office_parser/references/ppt-master/references/template-designer.md +402 -402
- package/skills/office_parser/references/ppt-master/references/visual-review.md +240 -240
- package/skills/office_parser/references/ppt-master/references/visual-styles/_index.md +106 -106
- package/skills/office_parser/references/ppt-master/references/visual-styles/blueprint.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/brutalist.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/chalkboard.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/dark-tech.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/data-journalism.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/editorial.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/glassmorphism.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/ink-notes.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/ink-wash.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/memphis.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/paper-cut.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/photo-editorial.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/pixel-art.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/sketch-notes.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/soft-rounded.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/swiss-minimal.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/vintage-poster.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/zine.md +37 -37
- package/skills/office_parser/references/spec_lock.md +235 -235
- package/skills/office_parser/soffice.py +68 -68
- package/skills/office_parser/word_tools.py +2909 -2909
- package/tui/crannia.cmd +134 -0
- package/tui/crannia_tui/__init__.py +1 -0
- package/tui/crannia_tui/__main__.py +223 -0
- package/tui/crannia_tui/app.py +1318 -0
- package/tui/crannia_tui/app.tcss +153 -0
- package/tui/crannia_tui/approval.py +85 -0
- package/tui/crannia_tui/backend.py +279 -0
- package/tui/crannia_tui/channel.py +472 -0
- package/tui/crannia_tui/client.py +125 -0
- package/tui/crannia_tui/clipboard.py +62 -0
- package/tui/crannia_tui/commands.py +65 -0
- package/tui/crannia_tui/doctor.py +304 -0
- package/tui/crannia_tui/events.py +84 -0
- package/tui/crannia_tui/headless.py +152 -0
- package/tui/crannia_tui/i18n.py +164 -0
- package/tui/crannia_tui/locales/en.json +263 -0
- package/tui/crannia_tui/outcome.py +62 -0
- package/tui/crannia_tui/paths.py +181 -0
- package/tui/crannia_tui/probe.py +53 -0
- package/tui/crannia_tui/profile.py +169 -0
- package/tui/crannia_tui/render.py +209 -0
- package/tui/crannia_tui/settings.py +134 -0
- package/tui/crannia_tui/setup.py +380 -0
- package/tui/crannia_tui/term.py +116 -0
- package/tui/crannia_tui/ui.py +1236 -0
- package/tui/crannia_tui/update.py +389 -0
- package/vendor/ripgrep/COPYING.txt +3 -3
- package/vendor/ripgrep/LICENSE-MIT.txt +21 -21
- package/vendor/ripgrep/NOTICE-vscode-ripgrep.txt +13 -13
- package/vendor/ripgrep/README.md +51 -51
- package/vendor/ripgrep/UNLICENSE.txt +24 -24
- package/vendor/ripgrep/package-source.json +19 -19
- package/web/__main__.py +15 -0
- package/web/server.py +178 -20
- package/web/static/img/channel-telegram.svg +1 -1
- package/web/static/img/channel-wechat.svg +1 -1
- package/web/templates/logs.html +49 -49
- package/web/templates/models.html +46 -46
package/mcpx/manager.py
CHANGED
|
@@ -1,522 +1,522 @@
|
|
|
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
|
+
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)
|