codebee 0.1.96 → 0.1.98
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/README.md +4 -2
- package/app/core/agent_context.py +21 -3
- package/app/core/board.py +39 -2
- package/app/core/builtin_agent.py +409 -34
- package/app/core/checkpoints.py +505 -0
- package/app/core/jobs.py +8 -1
- package/app/core/manager.py +109 -11
- package/app/core/mcp_client.py +200 -29
- package/app/core/pipeline.py +289 -40
- package/app/core/policy.py +36 -4
- package/app/core/project_memory.py +139 -0
- package/app/core/publish/auto.py +80 -19
- package/app/core/publish/browser.py +39 -0
- package/app/core/publish/fanqie.py +2 -0
- package/app/core/publish/flow.py +96 -17
- package/app/core/publish/flows-fanqie-calibrated.json +23 -11
- package/app/core/publish/ledger.py +38 -1
- package/app/core/runner.py +21 -11
- package/app/core/settings.py +13 -5
- package/app/core/settings_schema.py +14 -3
- package/app/core/store.py +21 -6
- package/app/core/tool_outputs.py +107 -0
- package/app/core/wxdigest.py +8 -1
- package/app/main.py +76 -2
- package/app/ui/app.js +356 -82
- package/app/ui/assets/workbench-reference.png +0 -0
- package/app/ui/board.css +451 -666
- package/app/ui/board.html +97 -94
- package/app/ui/board.js +316 -112
- package/app/ui/hive3d.js +242 -0
- package/app/ui/i18n.js +93 -10
- package/app/ui/index.html +31 -3
- package/app/ui/style.css +97 -111
- package/package.json +3 -2
package/app/core/manager.py
CHANGED
|
@@ -91,19 +91,21 @@ def _safe_config_path(raw):
|
|
|
91
91
|
# ---------------------------------------------------------------- 检测
|
|
92
92
|
|
|
93
93
|
def _which_cli(cli):
|
|
94
|
-
"""PATH 找 CLI
|
|
95
|
-
|
|
96
|
-
winget 装的 CLI(如 Claude Code
|
|
97
|
-
%LOCALAPPDATA%\\Microsoft\\WinGet\\Packages\\<PkgId>_
|
|
98
|
-
|
|
99
|
-
落空 → 卡片「未安装」假象,点安装又被 winget
|
|
100
|
-
|
|
101
|
-
<cli>.exe
|
|
94
|
+
"""PATH 找 CLI;落空再按平台兜底磁盘已知安装位。
|
|
95
|
+
|
|
96
|
+
Windows 兜 winget 便携包两处标准落点:winget 装的 CLI(如 Claude Code)
|
|
97
|
+
把 exe 放进 %LOCALAPPDATA%\\Microsoft\\WinGet\\Packages\\<PkgId>_*\\,并把
|
|
98
|
+
该目录写进注册表用户 PATH——注册表更新后已在跑的进程(本服务)不继承,
|
|
99
|
+
shutil.which 落空 → 卡片「未安装」假象,点安装又被 winget「已装无可升级」
|
|
100
|
+
非零退出拒掉(2026-09-30 实案)。Links 是便携包符号链接标准目录,Packages
|
|
101
|
+
按 <cli>.exe 通配兜另一形态。POSIX 兜 runner 同款三落点(~/.local/bin 与
|
|
102
|
+
brew bin,Mac 服务吃不到 shell rc 里的 PATH 时同样假「未安装」)。
|
|
103
|
+
两条都只兜 which 落空的场景,零额外开销。"""
|
|
102
104
|
path = shutil.which(cli)
|
|
103
105
|
if path:
|
|
104
106
|
return path
|
|
105
107
|
if os.name != "nt":
|
|
106
|
-
return
|
|
108
|
+
return runner._fallback_probe_cli(cli)
|
|
107
109
|
local = os.environ.get("LOCALAPPDATA")
|
|
108
110
|
if not local:
|
|
109
111
|
return None
|
|
@@ -1974,7 +1976,10 @@ def _winget_already_ok(cmd, op, res):
|
|
|
1974
1976
|
还要复检 installed 才按成功收口。"""
|
|
1975
1977
|
if res.get("ok") or op not in ("install", "upgrade"):
|
|
1976
1978
|
return False
|
|
1977
|
-
|
|
1979
|
+
# 首 token 可能已被 _resolve_mgmt_tool 换成绝对路径(PATH 快照落空兜底),
|
|
1980
|
+
# 所以按 basename 认 winget,别用 startswith
|
|
1981
|
+
head = str(cmd or "").strip().split()[0] if str(cmd or "").strip() else ""
|
|
1982
|
+
if os.path.basename(head).lower().rstrip(".exe") != "winget":
|
|
1978
1983
|
return False
|
|
1979
1984
|
code = res.get("exit_code")
|
|
1980
1985
|
try:
|
|
@@ -1986,6 +1991,85 @@ def _winget_already_ok(cmd, op, res):
|
|
|
1986
1991
|
return any(m in out for m in _WINGET_NOOP_MARKERS)
|
|
1987
1992
|
|
|
1988
1993
|
|
|
1994
|
+
def _uv_install_hint():
|
|
1995
|
+
if sys.platform == "darwin":
|
|
1996
|
+
return "brew install uv(或官网 curl -LsSf https://astral.sh/uv/install.sh | sh)"
|
|
1997
|
+
return "winget install astral-sh.uv,或 pip install uv"
|
|
1998
|
+
|
|
1999
|
+
|
|
2000
|
+
def _uv_mirror_env():
|
|
2001
|
+
"""uv 系命令的镜像兜底 env(用户没自己配才补默认,绝不覆盖)。
|
|
2002
|
+
|
|
2003
|
+
uv tool install --python 3.12 会现场下载 CPython 独立构建(GitHub 直连,
|
|
2004
|
+
国内常断流),包体走 PyPI——npmmirror/清华这对镜像是 2026-09 本机 uv
|
|
2005
|
+
实装验证过的组合。"""
|
|
2006
|
+
env = {}
|
|
2007
|
+
if not os.environ.get("UV_PYTHON_INSTALL_MIRROR"):
|
|
2008
|
+
env["UV_PYTHON_INSTALL_MIRROR"] = (
|
|
2009
|
+
"https://registry.npmmirror.com/-/binary/python-build-standalone")
|
|
2010
|
+
if not os.environ.get("UV_DEFAULT_INDEX"):
|
|
2011
|
+
env["UV_DEFAULT_INDEX"] = "https://pypi.tuna.tsinghua.edu.cn/simple"
|
|
2012
|
+
return env
|
|
2013
|
+
|
|
2014
|
+
|
|
2015
|
+
def _cmd_head_is_uv(cmd):
|
|
2016
|
+
stripped = str(cmd or "").strip()
|
|
2017
|
+
if not stripped:
|
|
2018
|
+
return False
|
|
2019
|
+
return os.path.basename(stripped.split()[0]).lower() in ("uv", "uv.exe")
|
|
2020
|
+
|
|
2021
|
+
|
|
2022
|
+
def _bootstrap_uv(cancel_event=None, log_path=None):
|
|
2023
|
+
"""uv 不在本机时自动补装一个——安装按钮「点了就该装上」的契约兜底。
|
|
2024
|
+
|
|
2025
|
+
按平台选渠道,全部免 sudo 非交互:POSIX 先 brew(在才用)后官方 curl
|
|
2026
|
+
脚本(落 ~/.local/bin,探测表可寻址);Windows 先 winget 后 pip。装完
|
|
2027
|
+
不指望 PATH 快照自愈——调用方重跑 _resolve_mgmt_tool 用绝对路径接管。
|
|
2028
|
+
返回 {ok, detail};失败 detail 列出试过的渠道与结局,供人话收口。"""
|
|
2029
|
+
candidates = []
|
|
2030
|
+
if sys.platform == "win32":
|
|
2031
|
+
if shutil.which("winget"):
|
|
2032
|
+
candidates.append(("winget", "winget install -e --id astral-sh.uv --silent"))
|
|
2033
|
+
if shutil.which("py"):
|
|
2034
|
+
candidates.append(("pip(py)", "py -3 -m pip install uv"))
|
|
2035
|
+
elif shutil.which("python"):
|
|
2036
|
+
candidates.append(("pip", "python -m pip install uv"))
|
|
2037
|
+
else:
|
|
2038
|
+
if shutil.which("brew"):
|
|
2039
|
+
candidates.append(("brew", "brew install uv"))
|
|
2040
|
+
if shutil.which("curl"):
|
|
2041
|
+
candidates.append(("curl", "curl -LsSf https://astral.sh/uv/install.sh | sh"))
|
|
2042
|
+
attempts = []
|
|
2043
|
+
for label, cmd in candidates:
|
|
2044
|
+
res = runner.run_process(shell_cmd=cmd, cwd=str(paths.ROOT),
|
|
2045
|
+
timeout=900, cancel_event=cancel_event,
|
|
2046
|
+
log_path=log_path)
|
|
2047
|
+
if res["ok"]:
|
|
2048
|
+
return {"ok": True, "detail": "已自动补装 uv(%s)" % label}
|
|
2049
|
+
attempts.append("%s 退出码 %s" % (label, res.get("exit_code")))
|
|
2050
|
+
return {"ok": False,
|
|
2051
|
+
"detail": "、".join(attempts) or "本机没有 brew/curl/winget/pip 任一渠道"}
|
|
2052
|
+
|
|
2053
|
+
|
|
2054
|
+
def _resolve_mgmt_tool(cmd, op):
|
|
2055
|
+
"""install/upgrade 命令首 token 的工具本体解析。
|
|
2056
|
+
|
|
2057
|
+
服务 PATH 是启动快照,本机后装的 uv/npm 不在快照里时 shell 报
|
|
2058
|
+
command not found 退出码 127,零信息量。磁盘已知落点能探到就把首 token
|
|
2059
|
+
原地换成绝对路径(装完即用,不必重启服务);探不到且是 uv 系安装命令
|
|
2060
|
+
则返回 uv_missing=True——本机连 uv 都没有,包无从装起,人话报错并跳过
|
|
2061
|
+
AI 修复(修复链装上 uv 后复检目标 CLI 仍未装,白烧一轮诊断)。
|
|
2062
|
+
返回 (替换后的命令, uv_missing)。"""
|
|
2063
|
+
stripped = str(cmd or "").strip()
|
|
2064
|
+
first = stripped.split()[0] if stripped else ""
|
|
2065
|
+
if not first or os.path.isabs(first) or shutil.which(first):
|
|
2066
|
+
return cmd, False
|
|
2067
|
+
found = runner._fallback_probe_cli(first)
|
|
2068
|
+
if found:
|
|
2069
|
+
return found + stripped[len(first):], False
|
|
2070
|
+
return cmd, (first == "uv" and op in ("install", "upgrade"))
|
|
2071
|
+
|
|
2072
|
+
|
|
1989
2073
|
def run_mgmt_command(entry, op, cancel_event=None, log_path=None):
|
|
1990
2074
|
"""执行 install/upgrade/uninstall 命令(由任务执行器异步运行,日志实时落盘)。"""
|
|
1991
2075
|
if op == "uninstall":
|
|
@@ -2000,8 +2084,22 @@ def run_mgmt_command(entry, op, cancel_event=None, log_path=None):
|
|
|
2000
2084
|
return {"ok": False,
|
|
2001
2085
|
"error": "未配置 %s 命令:请在 data/catalog.json 的 \"%s\" 里补充,或用官方渠道安装"
|
|
2002
2086
|
% (op, entry["id"])}
|
|
2087
|
+
cmd, uv_missing = _resolve_mgmt_tool(cmd, op)
|
|
2088
|
+
if uv_missing:
|
|
2089
|
+
# 「提供安装就该能装上」:uv 不在本机先自动补装,装 uv 不该是用户
|
|
2090
|
+
# 操心的事;真补不上才退回人话指引(2026-10-09 Mac 双装失败实案)
|
|
2091
|
+
boot = _bootstrap_uv(cancel_event=cancel_event, log_path=log_path)
|
|
2092
|
+
if boot["ok"]:
|
|
2093
|
+
cmd, uv_missing = _resolve_mgmt_tool(cmd, op)
|
|
2094
|
+
if uv_missing:
|
|
2095
|
+
return {"ok": False, "uv_missing": True,
|
|
2096
|
+
"error": "自动安装 uv 未成功(%s)。请手动安装:%s;"
|
|
2097
|
+
"装完重启 CodeBee,再点一次安装。"
|
|
2098
|
+
% (boot["detail"], _uv_install_hint())}
|
|
2099
|
+
# uv 全家桶命令挂镜像兜底:Python 独立构建/包索引国内直连常断(只补缺不覆盖)
|
|
2003
2100
|
res = runner.run_process(shell_cmd=cmd, cwd=str(paths.ROOT),
|
|
2004
|
-
timeout=1800, cancel_event=cancel_event, log_path=log_path
|
|
2101
|
+
timeout=1800, cancel_event=cancel_event, log_path=log_path,
|
|
2102
|
+
env=_uv_mirror_env() if _cmd_head_is_uv(cmd) else None)
|
|
2005
2103
|
winget_noop = _winget_already_ok(cmd, op, res)
|
|
2006
2104
|
detect_all(force=True)
|
|
2007
2105
|
with _LOCK:
|
package/app/core/mcp_client.py
CHANGED
|
@@ -17,15 +17,20 @@ name 用于工具名前缀(mcp__<name>__<tool>),必须 [a-z0-9_-]。
|
|
|
17
17
|
from __future__ import annotations
|
|
18
18
|
|
|
19
19
|
import json
|
|
20
|
+
import hashlib
|
|
20
21
|
import os
|
|
21
22
|
import re
|
|
23
|
+
import shutil
|
|
22
24
|
import subprocess
|
|
25
|
+
import sys
|
|
23
26
|
import threading
|
|
24
27
|
import time
|
|
28
|
+
from pathlib import Path
|
|
25
29
|
|
|
26
30
|
_LOCK = threading.RLock()
|
|
27
31
|
_TOOLS_CACHE = {} # server_key → (ts, tools)
|
|
28
32
|
_TOOLS_TTL = 300.0
|
|
33
|
+
_TOOLS_CONFIG_SHA = ""
|
|
29
34
|
|
|
30
35
|
MAX_SERVERS = 4
|
|
31
36
|
MAX_MCP_TOOLS = 24 # 全部服务器合计注入内置智能体的工具数上限
|
|
@@ -39,8 +44,10 @@ _CLIENT_INFO = {"name": "CodeBee", "version": "1.0"}
|
|
|
39
44
|
|
|
40
45
|
def invalidate_tools_cache():
|
|
41
46
|
"""服务器配置变化后丢弃已发现工具(插件启停等场景调用)。"""
|
|
47
|
+
global _TOOLS_CONFIG_SHA
|
|
42
48
|
with _LOCK:
|
|
43
49
|
_TOOLS_CACHE.clear()
|
|
50
|
+
_TOOLS_CONFIG_SHA = ""
|
|
44
51
|
|
|
45
52
|
|
|
46
53
|
def parse_servers(text):
|
|
@@ -70,18 +77,86 @@ def parse_servers(text):
|
|
|
70
77
|
args = [str(a) for a in args][:16]
|
|
71
78
|
env = item.get("env") if isinstance(item.get("env"), dict) else {}
|
|
72
79
|
env = {str(k): str(v) for k, v in list(env.items())[:16]}
|
|
73
|
-
|
|
80
|
+
disabled = item.get("disabled_tools")
|
|
81
|
+
if not isinstance(disabled, list):
|
|
82
|
+
disabled = []
|
|
83
|
+
disabled = list(dict.fromkeys(str(x).strip()[:120] for x in disabled
|
|
84
|
+
if str(x or "").strip()))[:200]
|
|
85
|
+
out.append({"name": name, "command": command, "args": args, "env": env,
|
|
86
|
+
"disabled_tools": disabled})
|
|
74
87
|
return out, None
|
|
75
88
|
|
|
76
89
|
|
|
90
|
+
def _sandbox_launch(server, sandbox, workdir):
|
|
91
|
+
"""Build an OS-isolated stdio server launch or refuse to spawn it.
|
|
92
|
+
|
|
93
|
+
MCP tools are arbitrary configured programs. On Linux they run under
|
|
94
|
+
bubblewrap with only declared roots mounted; platforms without an equivalent
|
|
95
|
+
backend fail closed. Runtime variables are synthetic/minimal unless explicitly
|
|
96
|
+
included in the task env allowlist.
|
|
97
|
+
"""
|
|
98
|
+
from . import policy
|
|
99
|
+
if not sandbox or not workdir:
|
|
100
|
+
raise RuntimeError("MCP 调用缺少任务沙箱策略或工作目录,拒绝启动")
|
|
101
|
+
if os.name != "posix" or sys.platform == "darwin" or not shutil.which("bwrap"):
|
|
102
|
+
raise RuntimeError("MCP 服务尚无可用的 OS 隔离后端,拒绝启动")
|
|
103
|
+
root = Path(workdir).expanduser().resolve(strict=True)
|
|
104
|
+
normalized = policy.normalize_sandbox(sandbox, root)
|
|
105
|
+
roots = [Path(value).resolve(strict=True)
|
|
106
|
+
for value in normalized.get("allowed_roots") or []]
|
|
107
|
+
if not roots:
|
|
108
|
+
raise RuntimeError("MCP 沙箱没有允许目录,拒绝启动")
|
|
109
|
+
cwd = root if policy.path_allowed(root, normalized) else roots[0]
|
|
110
|
+
argv = _bubblewrap_argv(server, normalized, roots, cwd)
|
|
111
|
+
return argv, _sandbox_env(server, normalized), str(cwd)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _sandbox_env(server, sandbox):
|
|
115
|
+
"""Pass only the minimal runtime environment and explicitly allowed values."""
|
|
116
|
+
env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"),
|
|
117
|
+
"HOME": "/tmp", "TMPDIR": "/tmp"}
|
|
118
|
+
for name in sandbox.get("env_allowlist") or []:
|
|
119
|
+
if name in os.environ:
|
|
120
|
+
env[name] = os.environ[name]
|
|
121
|
+
elif name in (server.get("env") or {}):
|
|
122
|
+
env[name] = str(server["env"][name])
|
|
123
|
+
return env
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _bubblewrap_argv(server, sandbox, roots, cwd):
|
|
127
|
+
"""Build bwrap argv from already validated paths (also host-testable)."""
|
|
128
|
+
argv = ["bwrap", "--die-with-parent", "--new-session", "--tmpfs", "/"]
|
|
129
|
+
for system_path in ("/usr", "/bin", "/sbin", "/lib", "/lib64", "/etc"):
|
|
130
|
+
if os.path.exists(system_path):
|
|
131
|
+
argv.extend(["--dir", system_path, "--ro-bind", system_path, system_path])
|
|
132
|
+
argv.extend(["--dir", "/proc", "--dir", "/dev", "--proc", "/proc",
|
|
133
|
+
"--dev", "/dev", "--tmpfs", "/tmp"])
|
|
134
|
+
if sandbox.get("network") is False:
|
|
135
|
+
argv.append("--unshare-net")
|
|
136
|
+
for allowed_root in roots:
|
|
137
|
+
for parent in reversed(allowed_root.parents):
|
|
138
|
+
if str(parent) != "/":
|
|
139
|
+
argv.extend(["--dir", str(parent)])
|
|
140
|
+
argv.extend(["--dir", str(allowed_root), "--bind",
|
|
141
|
+
str(allowed_root), str(allowed_root)])
|
|
142
|
+
argv.extend(["--chdir", str(cwd), "--", server["command"]]
|
|
143
|
+
+ list(server.get("args") or []))
|
|
144
|
+
return argv
|
|
145
|
+
|
|
146
|
+
|
|
77
147
|
class _Session:
|
|
78
148
|
"""一次性的 MCP 服务器会话:spawn → initialize → (list/call)→ 杀树。"""
|
|
79
149
|
|
|
80
|
-
def __init__(self, server):
|
|
150
|
+
def __init__(self, server, sandbox=None, workdir=None, timeout_s=None):
|
|
81
151
|
self.server = server
|
|
152
|
+
self.sandbox = sandbox
|
|
153
|
+
self.workdir = workdir
|
|
154
|
+
self.timeout_s = timeout_s
|
|
155
|
+
self.deadline = None
|
|
82
156
|
self.proc = None
|
|
83
157
|
self.lines = None # reader 线程产出的行队列
|
|
84
158
|
self.err = None
|
|
159
|
+
self._reader_threads = []
|
|
85
160
|
|
|
86
161
|
def _pump_err(self):
|
|
87
162
|
try:
|
|
@@ -89,6 +164,11 @@ class _Session:
|
|
|
89
164
|
pass
|
|
90
165
|
except Exception:
|
|
91
166
|
pass
|
|
167
|
+
finally:
|
|
168
|
+
try:
|
|
169
|
+
self.proc.stderr.close()
|
|
170
|
+
except Exception:
|
|
171
|
+
pass
|
|
92
172
|
|
|
93
173
|
def _pump_out(self):
|
|
94
174
|
try:
|
|
@@ -97,25 +177,48 @@ class _Session:
|
|
|
97
177
|
except Exception:
|
|
98
178
|
pass
|
|
99
179
|
finally:
|
|
180
|
+
try:
|
|
181
|
+
self.proc.stdout.close()
|
|
182
|
+
except Exception:
|
|
183
|
+
pass
|
|
100
184
|
self.lines.put(None) # EOF 哨兵
|
|
101
185
|
|
|
102
186
|
def __enter__(self):
|
|
187
|
+
if self.timeout_s is not None:
|
|
188
|
+
self.deadline = time.monotonic() + max(0.0, float(self.timeout_s))
|
|
103
189
|
try:
|
|
190
|
+
argv, env, cwd = _sandbox_launch(self.server, self.sandbox, self.workdir)
|
|
191
|
+
if self.deadline is not None and time.monotonic() >= self.deadline:
|
|
192
|
+
raise RuntimeError("MCP 任务时限已到,拒绝启动")
|
|
104
193
|
self.proc = subprocess.Popen(
|
|
105
|
-
|
|
194
|
+
argv,
|
|
106
195
|
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
|
107
196
|
stderr=subprocess.PIPE, text=False,
|
|
108
|
-
env=
|
|
197
|
+
env=env, cwd=cwd, start_new_session=True)
|
|
109
198
|
except Exception as e:
|
|
110
199
|
raise RuntimeError("MCP 服务器启动失败: %s" % e)
|
|
111
200
|
import queue as _queue
|
|
112
201
|
self.lines = _queue.Queue()
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
202
|
+
self._reader_threads = [
|
|
203
|
+
threading.Thread(target=self._pump_out, daemon=True),
|
|
204
|
+
threading.Thread(target=self._pump_err, daemon=True),
|
|
205
|
+
]
|
|
206
|
+
for thread in self._reader_threads:
|
|
207
|
+
thread.start()
|
|
208
|
+
try:
|
|
209
|
+
init_timeout = _INIT_TIMEOUT
|
|
210
|
+
if self.deadline is not None:
|
|
211
|
+
init_timeout = min(init_timeout, self.deadline - time.monotonic())
|
|
212
|
+
if init_timeout <= 0:
|
|
213
|
+
raise RuntimeError("MCP 任务时限已到,初始化未执行")
|
|
214
|
+
self._request("initialize", {
|
|
215
|
+
"protocolVersion": "2024-11-05", "capabilities": {},
|
|
216
|
+
"clientInfo": _CLIENT_INFO}, timeout=init_timeout)
|
|
217
|
+
self._notify("notifications/initialized")
|
|
218
|
+
except Exception:
|
|
219
|
+
# Context manager __exit__ is not called when __enter__ raises.
|
|
220
|
+
self.__exit__(None, None, None)
|
|
221
|
+
raise
|
|
119
222
|
return self
|
|
120
223
|
|
|
121
224
|
def __exit__(self, *exc):
|
|
@@ -125,12 +228,44 @@ class _Session:
|
|
|
125
228
|
self.proc.stdin.close()
|
|
126
229
|
except Exception:
|
|
127
230
|
pass
|
|
128
|
-
finally:
|
|
129
231
|
try:
|
|
130
|
-
if self.proc:
|
|
232
|
+
if self.proc and self.proc.poll() is None:
|
|
233
|
+
# bwrap runs in its own process group; terminate descendants
|
|
234
|
+
# as well as the launcher so timed-out MCP servers cannot
|
|
235
|
+
# leave background children holding pipes or doing work.
|
|
236
|
+
try:
|
|
237
|
+
from . import runner
|
|
238
|
+
runner._kill_tree(self.proc.pid)
|
|
239
|
+
except Exception:
|
|
240
|
+
pass
|
|
131
241
|
self.proc.kill()
|
|
132
242
|
except Exception:
|
|
133
243
|
pass
|
|
244
|
+
try:
|
|
245
|
+
if self.proc:
|
|
246
|
+
self.proc.wait(timeout=1)
|
|
247
|
+
except Exception:
|
|
248
|
+
pass
|
|
249
|
+
finally:
|
|
250
|
+
# Close all parent-side pipe handles even if initialization failed.
|
|
251
|
+
# Do not close a stream while its reader is blocked in read(): the
|
|
252
|
+
# buffered stream lock can make close wait forever if an escaped
|
|
253
|
+
# descendant still holds the pipe open. Let daemon readers finish
|
|
254
|
+
# on EOF and close only streams no thread currently owns.
|
|
255
|
+
for thread in self._reader_threads:
|
|
256
|
+
try:
|
|
257
|
+
thread.join(timeout=0.2)
|
|
258
|
+
except Exception:
|
|
259
|
+
pass
|
|
260
|
+
for name in ("stdout", "stderr"):
|
|
261
|
+
pipe = getattr(self.proc, name, None) if self.proc else None
|
|
262
|
+
readers_alive = any(
|
|
263
|
+
thread.is_alive() for thread in self._reader_threads)
|
|
264
|
+
if pipe and not readers_alive:
|
|
265
|
+
try:
|
|
266
|
+
pipe.close()
|
|
267
|
+
except Exception:
|
|
268
|
+
pass
|
|
134
269
|
return False
|
|
135
270
|
|
|
136
271
|
def _send(self, obj):
|
|
@@ -143,12 +278,17 @@ class _Session:
|
|
|
143
278
|
|
|
144
279
|
def _request(self, method, params, timeout):
|
|
145
280
|
"""单请求单响应;忽略通知与未知 id 的服务端请求。"""
|
|
281
|
+
duration = max(0.0, float(timeout))
|
|
282
|
+
if self.deadline is not None:
|
|
283
|
+
duration = min(duration, self.deadline - time.monotonic())
|
|
284
|
+
if duration <= 0:
|
|
285
|
+
raise RuntimeError("%s 超时(任务时限已到)" % method)
|
|
146
286
|
rid = id({})
|
|
147
287
|
self._send({"jsonrpc": "2.0", "id": 1 if method == "initialize" else rid,
|
|
148
288
|
"method": method, "params": params or {}})
|
|
149
|
-
deadline = time.
|
|
289
|
+
deadline = time.monotonic() + duration
|
|
150
290
|
while True:
|
|
151
|
-
remain = deadline - time.
|
|
291
|
+
remain = deadline - time.monotonic()
|
|
152
292
|
if remain <= 0:
|
|
153
293
|
raise RuntimeError("%s 超时(%.0fs)" % (method, timeout))
|
|
154
294
|
try:
|
|
@@ -174,10 +314,10 @@ class _Session:
|
|
|
174
314
|
return msg.get("result") or {}
|
|
175
315
|
|
|
176
316
|
|
|
177
|
-
def list_tools(server):
|
|
317
|
+
def list_tools(server, *, sandbox=None, workdir=None):
|
|
178
318
|
"""发现服务器工具。返回 {"ok", "tools":[{"name","description","input_schema"}], "error"}。"""
|
|
179
319
|
try:
|
|
180
|
-
with _Session(server) as sess:
|
|
320
|
+
with _Session(server, sandbox=sandbox, workdir=workdir) as sess:
|
|
181
321
|
res = sess._request("tools/list", {}, timeout=_INIT_TIMEOUT)
|
|
182
322
|
tools = []
|
|
183
323
|
for t in (res.get("tools") or [])[:16]:
|
|
@@ -192,11 +332,13 @@ def list_tools(server):
|
|
|
192
332
|
return {"ok": False, "tools": [], "error": str(e)[:200]}
|
|
193
333
|
|
|
194
334
|
|
|
195
|
-
def call_tool(server, tool_name, arguments, timeout_s=_CALL_TIMEOUT
|
|
335
|
+
def call_tool(server, tool_name, arguments, timeout_s=_CALL_TIMEOUT,
|
|
336
|
+
*, sandbox=None, workdir=None):
|
|
196
337
|
"""调用一个工具。返回 {"ok", "text", "error", "is_error"}。"""
|
|
197
338
|
try:
|
|
198
|
-
timeout = min(_CALL_TIMEOUT_MAX, max(
|
|
199
|
-
with _Session(server
|
|
339
|
+
timeout = min(_CALL_TIMEOUT_MAX, max(0.001, float(timeout_s or _CALL_TIMEOUT)))
|
|
340
|
+
with _Session(server, sandbox=sandbox, workdir=workdir,
|
|
341
|
+
timeout_s=timeout) as sess:
|
|
200
342
|
res = sess._request("tools/call",
|
|
201
343
|
{"name": tool_name,
|
|
202
344
|
"arguments": arguments if isinstance(arguments, dict) else {}},
|
|
@@ -216,46 +358,67 @@ def call_tool(server, tool_name, arguments, timeout_s=_CALL_TIMEOUT):
|
|
|
216
358
|
|
|
217
359
|
# ---- 面向 builtin_agent 的合并视图(带缓存) ----
|
|
218
360
|
|
|
219
|
-
def tool_specs_cached(force=False):
|
|
361
|
+
def tool_specs_cached(force=False, *, sandbox=None, workdir=None):
|
|
220
362
|
"""全部服务器的工具合并清单:[{server, name(原名), full_name, description,
|
|
221
363
|
input_schema}]。TTL 内走缓存;单个服务器失败跳过(error 挂在条目外不打断)。"""
|
|
364
|
+
global _TOOLS_CONFIG_SHA
|
|
365
|
+
if not sandbox or not workdir:
|
|
366
|
+
return []
|
|
367
|
+
config_text = _settings_text()
|
|
368
|
+
config_sha = hashlib.sha256(config_text.encode("utf-8")).hexdigest()
|
|
369
|
+
scope_sha = hashlib.sha256(json.dumps({
|
|
370
|
+
"workdir": os.path.realpath(workdir), "sandbox": sandbox,
|
|
371
|
+
}, sort_keys=True, default=str).encode("utf-8")).hexdigest()
|
|
222
372
|
with _LOCK:
|
|
373
|
+
if config_sha != _TOOLS_CONFIG_SHA:
|
|
374
|
+
_TOOLS_CACHE.clear()
|
|
375
|
+
_TOOLS_CONFIG_SHA = config_sha
|
|
223
376
|
if not force:
|
|
224
377
|
hit = True
|
|
225
|
-
|
|
378
|
+
scoped = [(key, value) for key, value in _TOOLS_CACHE.items()
|
|
379
|
+
if isinstance(key, tuple) and key[0] == scope_sha]
|
|
380
|
+
for key, (ts, _t) in scoped:
|
|
226
381
|
if time.time() - ts > _TOOLS_TTL:
|
|
227
382
|
hit = False
|
|
228
383
|
break
|
|
229
|
-
if hit and
|
|
384
|
+
if hit and scoped:
|
|
230
385
|
out = []
|
|
231
|
-
for _key, (_ts, tools) in
|
|
386
|
+
for _key, (_ts, tools) in scoped:
|
|
232
387
|
out.extend(tools)
|
|
233
388
|
return out[:MAX_MCP_TOOLS]
|
|
234
|
-
servers, err = parse_servers(
|
|
389
|
+
servers, err = parse_servers(config_text)
|
|
235
390
|
if err or not servers:
|
|
236
391
|
return []
|
|
392
|
+
from . import policy
|
|
393
|
+
disabled = set(policy.normalize_disabled_tools(
|
|
394
|
+
(sandbox or {}).get("disabled_tools")))
|
|
237
395
|
out = []
|
|
238
396
|
with _LOCK:
|
|
239
397
|
_TOOLS_CACHE.clear()
|
|
240
398
|
for srv in servers:
|
|
241
|
-
res = list_tools(srv)
|
|
399
|
+
res = list_tools(srv, sandbox=sandbox, workdir=workdir)
|
|
242
400
|
if not res.get("ok"):
|
|
243
401
|
continue
|
|
244
402
|
specs = []
|
|
245
403
|
for t in res["tools"]:
|
|
404
|
+
full_name = "mcp__%s__%s" % (srv["name"], t["name"])
|
|
405
|
+
if (t["name"] in srv.get("disabled_tools", [])
|
|
406
|
+
or t["name"] in disabled or full_name in disabled):
|
|
407
|
+
continue
|
|
246
408
|
specs.append({"server": srv["name"], "name": t["name"],
|
|
247
|
-
"full_name":
|
|
409
|
+
"full_name": full_name,
|
|
248
410
|
"description": t["description"],
|
|
249
411
|
"input_schema": t["input_schema"]})
|
|
250
412
|
with _LOCK:
|
|
251
|
-
_TOOLS_CACHE[srv["name"]] = (time.time(), specs)
|
|
413
|
+
_TOOLS_CACHE[(scope_sha, srv["name"])] = (time.time(), specs)
|
|
252
414
|
out.extend(specs)
|
|
253
415
|
if len(out) >= MAX_MCP_TOOLS:
|
|
254
416
|
break
|
|
255
417
|
return out[:MAX_MCP_TOOLS]
|
|
256
418
|
|
|
257
419
|
|
|
258
|
-
def dispatch_full_name(full_name, arguments, timeout_s=_CALL_TIMEOUT
|
|
420
|
+
def dispatch_full_name(full_name, arguments, timeout_s=_CALL_TIMEOUT, *,
|
|
421
|
+
sandbox=None, workdir=None, disabled_tools=None):
|
|
259
422
|
"""mcp__<server>__<tool> → 找服务器配置并调用。返回 {"ok","text","error"}。"""
|
|
260
423
|
m = re.match(r"^mcp__([a-z0-9_-]{1,24})__(.+)$", str(full_name or ""))
|
|
261
424
|
if not m:
|
|
@@ -267,7 +430,15 @@ def dispatch_full_name(full_name, arguments, timeout_s=_CALL_TIMEOUT):
|
|
|
267
430
|
srv = next((s for s in servers if s["name"] == sname), None)
|
|
268
431
|
if not srv:
|
|
269
432
|
return {"ok": False, "text": "", "error": "MCP 服务器 %s 未配置" % sname}
|
|
270
|
-
|
|
433
|
+
if tool in (srv.get("disabled_tools") or []):
|
|
434
|
+
return {"ok": False, "text": "", "error": "MCP 工具已禁用: %s" % full_name}
|
|
435
|
+
if (full_name in set(str(x) for x in (disabled_tools or []))
|
|
436
|
+
or tool in set(str(x) for x in (disabled_tools or []))):
|
|
437
|
+
return {"ok": False, "text": "", "error": "任务策略已禁用 MCP 工具: %s" % full_name}
|
|
438
|
+
if sandbox is None or not workdir:
|
|
439
|
+
return {"ok": False, "text": "", "error": "MCP 调用缺少任务沙箱策略或工作目录,拒绝启动"}
|
|
440
|
+
return call_tool(srv, tool, arguments, timeout_s=timeout_s,
|
|
441
|
+
sandbox=sandbox, workdir=workdir)
|
|
271
442
|
|
|
272
443
|
|
|
273
444
|
_SETTINGS_TEXT = None # main.py 启动注入(读 settings.mcp_servers)——本模块
|