JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat: 支持sse/streamable-http/playwright/openapi类型的MCP协议
openJiuwen-botf0e961721708
diff --git a/jiuwenswarm/agents/harness/common/tools/mcp_toolkits.py b/jiuwenswarm/agents/harness/common/tools/mcp_toolkits.pyindex 205735980c..64e5bf656b 100644--- a/jiuwenswarm/agents/harness/common/tools/mcp_toolkits.py+++ b/jiuwenswarm/agents/harness/common/tools/mcp_toolkits.py@@ -10,6 +10,20 @@ from openjiuwen.core.foundation.tool import Toolfrom jiuwenswarm.agents.harness.common.tools.command_tools import mcp_exec_commandfrom jiuwenswarm.agents.harness.common.tools.search_tools import mcp_free_search, mcp_paid_searchfrom jiuwenswarm.agents.harness.common.tools.web_fetch_tools import mcp_fetch_webpage+from jiuwenswarm.common.mcp_config import ( # noqa: F401+ _check_dangerous_args,+ _is_blocked_host,+ _loopback_mcp_allowed,+ _normalize_mcp_client_type,+ _normalize_stdio_command_kind,+ _optional_auth_dict,+ _path_is_under_trusted_root,+ _pick_mcp_url,+ _trusted_cat_cafe_stdio_roots,+ _validate_cat_cafe_request_scoped_stdio,+ _validate_request_scoped_remote_mcp,+ create_mcp_tool,+)def _has_paid_search_api_key() -> bool:@@ -53,4 +67,16 @@ __all__ = ["mcp_fetch_webpage","mcp_exec_command","get_mcp_tools",+ "create_mcp_tool",+ "_check_dangerous_args",+ "_is_blocked_host",+ "_loopback_mcp_allowed",+ "_normalize_mcp_client_type",+ "_normalize_stdio_command_kind",+ "_optional_auth_dict",+ "_path_is_under_trusted_root",+ "_pick_mcp_url",+ "_trusted_cat_cafe_stdio_roots",+ "_validate_cat_cafe_request_scoped_stdio",+ "_validate_request_scoped_remote_mcp",]diff --git a/jiuwenswarm/common/mcp_config.py b/jiuwenswarm/common/mcp_config.pyindex b9789dba23..448e429c24 100644--- a/jiuwenswarm/common/mcp_config.py+++ b/jiuwenswarm/common/mcp_config.py@@ -6,14 +6,27 @@ from __future__ import annotationsimport asyncioimport hashlib+import ipaddressimport json+import osimport re+import sys+from pathlib import Pathfrom typing import Anyfrom urllib.parse import urlparsefrom openjiuwen.core.common.logging import loggerfrom openjiuwen.core.foundation.tool import McpServerConfig+try:+ from openjiuwen.core.foundation.tool.mcp.client import (+ sse_client as _sse_client, # noqa: F401+ stdio_client as _stdio_client, # noqa: F401+ streamable_http_client as _streamable_http_client, # noqa: F401+ )+except ImportError:+ pass+_HTTP_MCP_TRANSPORTS = frozenset({"sse", "http", "streamable-http", "streamable_http"})@@ -191,9 +204,452 @@ def _safe_id_part(value: str, *, default: str) -> str:return (normalized or default)[:48]+def _normalize_stdio_command_kind(command: str) -> str:+ """将 command 归一化为 'node'、'python'、'npx' 或 'uvx'。++ 支持绝对路径如 /usr/local/bin/node、C:\\Program Files\\node.exe 等。+ npx/uvx为包运行器,参数为包名而非本地脚本路径,安全模型与 node/python 不同。+ """+ raw = str(command or "").strip()+ if not raw:+ raise ValueError("工具配置缺少 'command' 字段")++ normalized = raw.replace("\\", "/").rsplit("/", 1)[-1].lower()+ if normalized in ("node", "node.exe"):+ return "node"+ if normalized.startswith("python"):+ return "python"+ if normalized in ("npx", "npx.exe", "npx.cmd", "npx.bat"):+ return "npx"+ if normalized in ("uvx", "uvx.exe"):+ return "uvx"+ raise ValueError(f"不支持的 command 类型: '{command}',目前仅支持 node/python/npx/uvx 及其绝对路径")+++def _normalize_mcp_client_type(raw_type: object) -> str:+ if raw_type is None:+ return "stdio"+ s = str(raw_type).strip().lower().replace("_", "-")+ if "streamable" in s:+ return "streamable-http"+ if s == "sse":+ return "sse"+ if s == "stdio":+ return "stdio"+ return s if s else "stdio"+++def _pick_mcp_url(tool_config: dict) -> str:+ v = tool_config.get("url")+ if isinstance(v, str) and v.strip():+ return v.strip()+ return ""+++def _optional_auth_dict(tool_config: dict, key: str) -> dict | None:+ raw = tool_config.get(key)+ if raw is None:+ return {}+ if not isinstance(raw, dict):+ raise ValueError(f"字段 {key!r} 必须是 JSON 对象")+ return dict(raw)+++_DANGEROUS_ARGS_PATTERN = frozenset({+ "-e", "--eval", "-c", "--command", "-i",+})+++def _check_dangerous_args(tool_name: str, args: list) -> None:+ if not isinstance(args, list):+ return+ for arg in args:+ arg_str = str(arg).strip()+ if arg_str in _DANGEROUS_ARGS_PATTERN:+ raise ValueError(+ f"安全拦截阻断:工具 '{tool_name}' 的 args 包含危险标志 '{arg_str}',"+ "禁止通过参数注入执行任意代码。"+ )+ for dangerous_prefix in ("-e=", "--eval=", "-c=", "--command="):+ if arg_str.lower().startswith(dangerous_prefix):+ raise ValueError(+ f"安全拦截阻断:工具 '{tool_name}' 的 args 包含危险标志 '{arg_str}',"+ "禁止通过参数注入执行任意代码。"+ )+++def _trusted_cat_cafe_stdio_roots() -> list[Path]:+ roots: list[Path] = []+ raw = (os.getenv("CAT_CAFE_MCP_CWD") or "").strip()+ if raw:+ try:+ roots.append(Path(raw).expanduser().resolve())+ except OSError:+ pass+ try:+ roots.append((Path.home() / ".office-claw").resolve())+ except OSError:+ pass+ try:+ roots.append(Path(sys.executable).resolve().parent)+ except OSError:+ pass+ lp = (os.getenv("LOCALAPPDATA") or "").strip()+ if lp:+ inst = Path(lp) / "Programs" / "OfficeClaw"+ try:+ if inst.exists():+ roots.append(inst.resolve())+ except OSError:+ pass+ for env_key in ("ProgramFiles", "ProgramFiles(x86)"):+ base = os.getenv(env_key, "").strip()+ if not base:+ continue+ inst = Path(base) / "OfficeClaw"+ try:+ if inst.exists():+ roots.append(inst.resolve())+ except OSError:+ pass+ seen: set[str] = set()+ out: list[Path] = []+ for r in roots:+ key = os.path.normcase(str(r))+ if key not in seen:+ seen.add(key)+ out.append(r)+ return out+++def _path_is_under_trusted_root(path: Path, roots: list[Path]) -> bool:+ try:+ rp = path.resolve()+ except OSError:+ return False+ for root in roots:+ try:+ rp.relative_to(root)+ return True+ except ValueError:+ continue+ return False+++def _validate_cat_cafe_request_scoped_stdio(params: dict[str, Any]) -> None:+ """限制请求级 stdio:禁止内联代码执行面,脚本路径须在受信根目录下。++ npx/uvx 为包运行器,参数为包名及其参数,不适用本地脚本路径受信根校验+ (代码来源为包仓库而非本地文件,信任决策在于包名而非路径)。+ """+ cmd = str(params.get("command") or "").strip()+ args = params.get("args") or []+ if not isinstance(args, list):+ raise ValueError("stdio MCP 的 args 须为列表")++ kind = _normalize_stdio_command_kind(cmd)+ flat = [str(a) for a in args]+ lowered = [a.strip().lower() for a in flat]+ if any(x == "-c" or x == "--command" for x in lowered):+ raise ValueError("请求级 cat_cafe_mcp 禁止使用 python -c / --command")+ if kind == "node" and any(x in ("-e", "--eval") for x in lowered):+ raise ValueError("请求级 cat_cafe_mcp 禁止使用 node -e / --eval")++ if kind in ("npx", "uvx"):+ return++ cwd_path: Path | None = None+ cwd_raw = params.get("cwd")+ if isinstance(cwd_raw, str) and cwd_raw.strip():+ try:+ cwd_path = Path(cwd_raw).expanduser().resolve()+ except OSError as exc:+ raise ValueError(f"请求级 cat_cafe_mcp cwd 无效: {cwd_raw}") from exc+ if not _path_is_under_trusted_root(cwd_path, _trusted_cat_cafe_stdio_roots()):+ raise ValueError(f"请求级 cat_cafe_mcp cwd 不在受信根目录下: {cwd_path}")++ roots = _trusted_cat_cafe_stdio_roots()+ for a in flat:+ s = a.strip()+ if not s or s.startswith("-"):+ continue+ path_like_suffix = s.lower().endswith((".js", ".mjs", ".cjs", ".py"))+ if "/" not in s and "\\" not in s and not path_like_suffix:+ continue+ candidate = Path(s).expanduser()+ if not candidate.is_absolute() and cwd_path is None:+ raise ValueError("请求级 cat_cafe_mcp 使用相对脚本路径时必须提供位于受信根下的 cwd")+ try:+ if cwd_path is not None and not candidate.is_absolute():+ resolved = (cwd_path / candidate).resolve()+ else:+ resolved = candidate.resolve()+ except OSError:+ continue+ if not _path_is_under_trusted_root(resolved, roots):+ raise ValueError(f"请求级 cat_cafe_mcp 参数路径不在受信根目录下: {resolved}")+++_REQUEST_REMOTE_BLOCKED_HOSTS = frozenset({+ "localhost",+ "metadata.google.internal",+ "metadata",+ "metadata.azure.com",+})++_REQUEST_REMOTE_METADATA_HOSTS = frozenset({+ "metadata.google.internal",+ "metadata",+ "metadata.azure.com",+})+++def _loopback_mcp_allowed() -> bool:+ return (os.getenv("JIUWENSWARM_ALLOW_LOOPBACK_MCP") or "").strip().lower() in ("1", "true", "yes")+++def _is_blocked_host(host: str) -> bool:+ if not host:+ return False+ host = host.lower().strip()+ allow_loopback = _loopback_mcp_allowed()+ if allow_loopback and host == "localhost":+ return False+ if host in _REQUEST_REMOTE_METADATA_HOSTS:+ return True+ if not allow_loopback and host in _REQUEST_REMOTE_BLOCKED_HOSTS:+ return True+ try:+ ip = ipaddress.ip_address(host)+ except ValueError:+ return False+ if allow_loopback and ip.is_loopback:+ return False+ return (+ ip.is_private+ or ip.is_loopback+ or ip.is_link_local+ or ip.is_multicast+ or ip.is_reserved+ or ip.is_unspecified+ )+++def _validate_request_scoped_remote_mcp(tool_name: str, cfg: dict) -> None:+ if not isinstance(cfg, dict):+ return+ if _loopback_mcp_allowed():+ logger.warning(+ "[mcp-config][WARN] JIUWENSWARM_ALLOW_LOOPBACK_MCP 已启用,"+ "loopback/localhost 地址放行(仅开发测试用,生产环境勿设此变量)"+ )+ url = cfg.get("url")+ if isinstance(url, str) and url:+ try:+ host = urlparse(url).hostname or ""+ except Exception:+ host = ""+ if _is_blocked_host(host):+ raise ValueError(+ f"安全拦截阻断:请求级 sse/http MCP ({tool_name!r}) 的 url 指向"+ f"内网/元数据地址 ({host}),疑似 SSRF 攻击。"+ )+ for field in ("auth_headers", "auth_query_params"):+ val = cfg.get(field)+ if not isinstance(val, dict):+ continue+ for k, v in val.items():+ if not isinstance(v, str):+ continue+ try:+ host = (urlparse(v).hostname or "") if "://" in v else v.strip()+ except Exception:+ host = v.strip()+ if _is_blocked_host(host):+ raise ValueError(+ f"安全拦截阻断:请求级 sse/http MCP ({tool_name!r}) 的 "+ f"{field}[{k!r}] 值指向内网/元数据地址,疑似凭证外泄/SSRF。"+ )+++def create_mcp_tool(config_str: str) -> McpServerConfig:+ """从 JSON 字符串解析并构造 ``McpServerConfig``。++ Args:+ 1.stdio类型:+ config_str: JSON 格式配置字符串,格式为:+ {+ "name": "tool_name",+ "command": "node" | "python" | "npx" | "uvx",+ "args": ["xxx.js"] | ["xxx.py"] | ["-y", "@scope/pkg"] | ["pkg"]+ }++ 2.streamable-http类型:+ {+ "type": "streamableHttp",+ "url": "http://127.0.0.1:3002/mcp",+ "env": {},+ "auth_headers": {+ "Authorization": "Bearer xxx"+ },+ "auth_query_params": {+ "token": "yyy"+ }+ }++ 3.sse类型:+ {+ "name": "my-sse-mcp",+ "type": "sse",+ "url": "http://127.0.0.1:3001/sse",+ "env": {},+ "auth_headers": {+ "Authorization": "Bearer xxx"+ },+ "auth_query_params": {+ "token": "yyy"+ }+ }+ 4.playwright类型:+ {+ "name": "my-playwright-mcp",+ "description": "可选说明",+ "type": "playwright",+ "url": "http://127.0.0.1:3003/sse",+ "env": {}+ }++ Returns:+ ``McpServerConfig``,由调用方通过 ``Runner.resource_mgr.add_mcp_server(..., tag=...)`` 注册。++ Raises:+ ValueError: JSON 解析失败或配置不合法时+ """+ try:+ config = json.loads(config_str)+ except json.JSONDecodeError as e:+ raise ValueError(f"无效的 JSON 配置") from e++ if isinstance(config, list):+ if len(config) == 0:+ raise ValueError("工具配置数组不能为空")+ tool_config = config[0]+ elif isinstance(config, dict):+ tool_config = config+ else:+ raise ValueError("配置必须是字典或数组类型")++ if not isinstance(tool_config, dict):+ raise ValueError("工具配置必须是字典类型")++ tool_name = tool_config.get("name")+ server_id = str(tool_config.get("server_id") or tool_name or "").strip()+ command = tool_config.get("command")+ args = tool_config.get("args", [])+ env = tool_config.get("env")+ cwd = tool_config.get("cwd")++ if not tool_name:+ raise ValueError("工具配置缺少 'name' 字段")++ url = _pick_mcp_url(tool_config)+ client_type = _normalize_mcp_client_type(tool_config.get("type"))+ params = {}+ if isinstance(env, dict) and env:+ params["env"] = {str(k): str(v) for k, v in env.items() if k is not None and v is not None}+ if client_type == "sse":+ if not url:+ raise ValueError(f"工具 '{tool_name}'('{client_type}')需要 url")+ headers = _optional_auth_dict(tool_config, "auth_headers")+ query = _optional_auth_dict(tool_config, "auth_query_params")+ return McpServerConfig(+ server_id=server_id or tool_name,+ server_name=tool_name,+ server_path=url,+ client_type="sse",+ auth_headers=headers,+ auth_query_params=query,+ params=params+ )++ if client_type == "streamable-http":+ if not url:+ raise ValueError(+ f"工具 '{tool_name}'('{client_type}')需要 url"+ )+ headers = _optional_auth_dict(tool_config, "auth_headers")+ query = _optional_auth_dict(tool_config, "auth_query_params")+ return McpServerConfig(+ server_id=server_id or tool_name,+ server_name=tool_name,+ server_path=url,+ client_type="streamable-http",+ auth_headers=headers,+ auth_query_params=query,+ params=params+ )++ if client_type == "playwright":+ if not url:+ raise ValueError(+ f"工具 '{tool_name}'('{client_type}')需要 url"+ )+ return McpServerConfig(+ server_id=server_id or tool_name,+ server_name=tool_name,+ server_path=url,+ client_type="playwright",+ params=params+ )++ if client_type == "openapi":+ if not url:+ raise ValueError(+ f"工具 '{tool_name}'('{client_type}')需要 url"+ )+ return McpServerConfig(+ server_id=server_id or tool_name,+ server_name=tool_name,+ server_path=url,+ client_type="openapi",+ params=params+ )++ if not isinstance(args, list):+ raise ValueError(f"工具 '{tool_name}' 的 args 必须是列表类型")++ _check_dangerous_args(tool_name, args)++ normalized_command = str(command or "").strip()+ _normalize_stdio_command_kind(normalized_command)+ params["command"] = normalized_command+ params["args"] = args+ if isinstance(cwd, str) and cwd.strip():+ params["cwd"] = cwd.strip()+ return McpServerConfig(+ server_id=server_id or tool_name,+ server_name=tool_name,+ server_path=f"stdio://{tool_name}",+ client_type="stdio",+ params=params+ )++__all__ = ["build_enabled_mcp_server_configs","build_mcp_server_config",+ "create_mcp_tool","extract_enabled_mcp_server_entries","preflight_mcp_server_reachable",+ "_check_dangerous_args",+ "_is_blocked_host",+ "_loopback_mcp_allowed",+ "_normalize_mcp_client_type",+ "_normalize_stdio_command_kind",+ "_optional_auth_dict",+ "_path_is_under_trusted_root",+ "_pick_mcp_url",+ "_trusted_cat_cafe_stdio_roots",+ "_validate_cat_cafe_request_scoped_stdio",+ "_validate_request_scoped_remote_mcp",]diff --git a/jiuwenswarm/common/utils.py b/jiuwenswarm/common/utils.pyindex 499da34c37..efe09f27d8 100644--- a/jiuwenswarm/common/utils.py+++ b/jiuwenswarm/common/utils.py@@ -1222,6 +1222,8 @@ def prepare_workspace(cumulative_diff=cumulative_diff,)+ _resolve_paths(force=True)+return cumulative_diff@@ -1358,11 +1360,11 @@ def init_user_workspace(return workspace_dir-def _resolve_paths() -> None:+def _resolve_paths(force=False) -> None:"""Resolve and cache all paths."""global _initialized, _config_dir, _workspace_dir, _root_dir- if _initialized:+ if not force and _initialized:returnworkspace_dir = get_user_workspace_dir()diff --git a/jiuwenswarm/resources/.env.template b/jiuwenswarm/resources/.env.templateindex 6205f2c1c1..c6738e3b17 100644--- a/jiuwenswarm/resources/.env.template+++ b/jiuwenswarm/resources/.env.template@@ -13,19 +13,19 @@ EMBED_MODEL=VIDEO_API_BASE=VIDEO_API_KEY=VIDEO_MODEL_NAME="your-video-model-name"-VIDEO_PROVIDER=+VIDEO_PROVIDER=OpenAI# Audio processing model selection.AUDIO_API_BASE=AUDIO_API_KEY=AUDIO_MODEL_NAME="your-audio-model-name"-AUDIO_PROVIDER=+AUDIO_PROVIDER=OpenAI# Vision/Image processing model selection.VISION_API_BASE=VISION_API_KEY=VISION_MODEL_NAME="your-vision-model-name"-VISION_PROVIDER=+VISION_PROVIDER=OpenAIGITHUB_TOKEN=diff --git a/tests/unit_tests/common/test_mcp_config_create_mcp_tool.py b/tests/unit_tests/common/test_mcp_config_create_mcp_tool.pynew file mode 100644index 0000000000..b87250c7d7--- /dev/null+++ b/tests/unit_tests/common/test_mcp_config_create_mcp_tool.py@@ -0,0 +1,657 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from __future__ import annotations++import json+from pathlib import Path++import pytest++from jiuwenswarm.common.mcp_config import (+ _check_dangerous_args,+ _is_blocked_host,+ _loopback_mcp_allowed,+ _normalize_mcp_client_type,+ _normalize_stdio_command_kind,+ _optional_auth_dict,+ _path_is_under_trusted_root,+ _pick_mcp_url,+ _trusted_cat_cafe_stdio_roots,+ _validate_cat_cafe_request_scoped_stdio,+ _validate_request_scoped_remote_mcp,+ create_mcp_tool,+)+from openjiuwen.core.foundation.tool import McpServerConfig+++class TestNormalizeMcpClientType:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ (None, "stdio"),+ ("", "stdio"),+ ("stdio", "stdio"),+ ("STDIO", "stdio"),+ ("sse", "sse"),+ ("SSE", "sse"),+ ("streamableHttp", "streamable-http"),+ ("streamable_http", "streamable-http"),+ ("streamable-http", "streamable-http"),+ ("StreamableHTTP", "streamable-http"),+ ("playwright", "playwright"),+ ("openapi", "openapi"),+ ],+ )+ def test_normalize(self, raw, expected):+ assert _normalize_mcp_client_type(raw) == expected+++class TestNormalizeStdioCommandKind:+ @pytest.mark.parametrize(+ "command, expected",+ [+ ("node", "node"),+ ("node.exe", "node"),+ ("python", "python"),+ ("python3", "python"),+ ("python3.11", "python"),+ ("C:\\Program Files\\node.exe", "node"),+ ("/usr/local/bin/node", "node"),+ ("npx", "npx"),+ ("npx.exe", "npx"),+ ("npx.cmd", "npx"),+ ("/usr/local/bin/npx", "npx"),+ ("uvx", "uvx"),+ ("uvx.exe", "uvx"),+ ("/home/u/.local/bin/uvx", "uvx"),+ ],+ )+ def test_valid_commands(self, command, expected):+ assert _normalize_stdio_command_kind(command) == expected++ def test_empty_command_raises(self):+ with pytest.raises(ValueError, match="缺少"):+ _normalize_stdio_command_kind("")++ def test_whitespace_command_raises(self):+ with pytest.raises(ValueError, match="缺少"):+ _normalize_stdio_command_kind(" ")++ def test_none_command_raises(self):+ with pytest.raises(ValueError, match="缺少"):+ _normalize_stdio_command_kind(None)++ @pytest.mark.parametrize("cmd", ["bash", "sh", "ruby", "cmd", "powershell", "deno"])+ def test_unsupported_command_raises(self, cmd):+ with pytest.raises(ValueError, match="不支持"):+ _normalize_stdio_command_kind(cmd)+++class TestPickMcpUrl:+ def test_valid_url(self):+ assert _pick_mcp_url({"url": " http://example.com "}) == "http://example.com"++ def test_missing_url(self):+ assert _pick_mcp_url({}) == ""++ def test_non_string_url(self):+ assert _pick_mcp_url({"url": 123}) == ""++ def test_empty_url(self):+ assert _pick_mcp_url({"url": " "}) == ""+++class TestOptionalAuthDict:+ def test_missing_key(self):+ assert _optional_auth_dict({}, "auth_headers") == {}++ def test_valid_dict(self):+ result = _optional_auth_dict({"auth_headers": {"Authorization": "Bearer x"}}, "auth_headers")+ assert result == {"Authorization": "Bearer x"}++ def test_invalid_type_raises(self):+ with pytest.raises(ValueError, match="必须是 JSON 对象"):+ _optional_auth_dict({"auth_headers": "not-a-dict"}, "auth_headers")+++class TestCheckDangerousArgs:+ def test_safe_args_pass(self):+ _check_dangerous_args("t", ["-y", "@scope/pkg", "/tmp"])++ def test_eval_flag_blocked(self):+ with pytest.raises(ValueError, match="危险标志"):+ _check_dangerous_args("t", ["-e", "code"])++ def test_command_flag_blocked(self):+ with pytest.raises(ValueError, match="危险标志"):+ _check_dangerous_args("t", ["-c", "print(1)"])++ def test_module_flag_allowed(self):+ _check_dangerous_args("t", ["-m", "os"])++ def test_eval_equals_blocked(self):+ with pytest.raises(ValueError, match="危险标志"):+ _check_dangerous_args("t", ["--eval=code"])++ def test_command_equals_blocked(self):+ with pytest.raises(ValueError, match="危险标志"):+ _check_dangerous_args("t", ["-c=print(1)"])++ def test_non_list_args_noop(self):+ _check_dangerous_args("t", "not-a-list")++ def test_empty_args_pass(self):+ _check_dangerous_args("t", [])+++class TestTrustedCatCafeStdioRoots:+ def test_returns_list_of_paths(self):+ roots = _trusted_cat_cafe_stdio_roots()+ assert isinstance(roots, list)+ for r in roots:+ assert isinstance(r, Path)++ def test_no_duplicates(self):+ roots = _trusted_cat_cafe_stdio_roots()+ keys = [str(r) for r in roots]+ assert len(keys) == len(set(keys))+++class TestPathIsUnderTrustedRoot:+ def test_subpath_is_under_root(self, tmp_path):+ root = tmp_path / "root"+ root.mkdir()+ child = root / "sub" / "file.py"+ assert _path_is_under_trusted_root(child, [root])++ def test_unrelated_path_is_not_under_root(self, tmp_path):+ root = tmp_path / "root"+ root.mkdir()+ other = tmp_path / "other" / "file.py"+ assert not _path_is_under_trusted_root(other, [root])++ def test_root_itself_is_under_root(self, tmp_path):+ root = tmp_path / "root"+ root.mkdir()+ assert _path_is_under_trusted_root(root, [root])+++class TestValidateCatCafeRequestScopedStdio:+ def test_npx_skips_path_check(self):+ _validate_cat_cafe_request_scoped_stdio({+ "command": "npx",+ "args": ["-y", "@modelcontextprotocol/server-filesystem", "/etc", "/tmp"],+ })++ def test_uvx_skips_path_check(self):+ _validate_cat_cafe_request_scoped_stdio({+ "command": "uvx",+ "args": ["mcp-server-fetch", "/var/data"],+ })++ def test_npx_untrusted_cwd_allowed(self):+ _validate_cat_cafe_request_scoped_stdio({+ "command": "npx",+ "args": ["-y", "pkg"],+ "cwd": "/untrusted/random/dir",+ })++ def test_npx_dangerous_command_arg_still_blocked(self):+ with pytest.raises(ValueError, match="python -c"):+ _validate_cat_cafe_request_scoped_stdio({+ "command": "npx",+ "args": ["-c", "code"],+ })++ def test_uvx_dangerous_command_arg_still_blocked(self):+ with pytest.raises(ValueError, match="python -c"):+ _validate_cat_cafe_request_scoped_stdio({+ "command": "uvx",+ "args": ["--command", "code"],+ })++ def test_node_path_check_still_active(self):+ with pytest.raises(ValueError, match="受信根"):+ _validate_cat_cafe_request_scoped_stdio({+ "command": "node",+ "args": ["/untrusted/script.js"],+ })++ def test_python_path_check_still_active(self):+ with pytest.raises(ValueError, match="受信根"):+ _validate_cat_cafe_request_scoped_stdio({+ "command": "python",+ "args": ["/untrusted/script.py"],+ })++ def test_node_eval_still_blocked(self):+ with pytest.raises(ValueError, match="node -e"):+ _validate_cat_cafe_request_scoped_stdio({+ "command": "node",+ "args": ["-e", "console.log(1)"],+ })++ def test_args_not_list_raises(self):+ with pytest.raises(ValueError, match="args 须为列表"):+ _validate_cat_cafe_request_scoped_stdio({+ "command": "npx",+ "args": "not-a-list",+ })+++class TestIsBlockedHost:+ def test_localhost_blocked(self):+ assert _is_blocked_host("localhost")++ def test_loopback_ipv4_blocked(self):+ for host in ("127.0.0.1", "127.1.2.3"):+ assert _is_blocked_host(host)++ def test_metadata_endpoint_blocked(self):+ assert _is_blocked_host("metadata.google.internal")+ assert _is_blocked_host("metadata.azure.com")++ def test_private_network_blocked(self):+ for host in ("10.0.0.1", "192.168.1.1", "172.16.0.1"):+ assert _is_blocked_host(host)++ def test_link_local_blocked(self):+ assert _is_blocked_host("169.254.169.254")++ def test_external_host_allowed(self):+ assert not _is_blocked_host("mcp.example.com")+ assert not _is_blocked_host("8.8.8.8")++ def test_empty_host_allowed(self):+ assert not _is_blocked_host("")++ def test_loopback_allowed_when_env_set(self, monkeypatch):+ monkeypatch.setenv("JIUWENSWARM_ALLOW_LOOPBACK_MCP", "1")+ assert not _is_blocked_host("127.0.0.1")+ assert not _is_blocked_host("localhost")++ def test_metadata_still_blocked_when_loopback_allowed(self, monkeypatch):+ monkeypatch.setenv("JIUWENSWARM_ALLOW_LOOPBACK_MCP", "1")+ assert _is_blocked_host("metadata.google.internal")+ assert _is_blocked_host("169.254.169.254")++ def test_private_still_blocked_when_loopback_allowed(self, monkeypatch):+ monkeypatch.setenv("JIUWENSWARM_ALLOW_LOOPBACK_MCP", "1")+ assert _is_blocked_host("10.0.0.1")+ assert _is_blocked_host("192.168.1.1")+++class TestLoopbackMcpAllowed:+ def test_default_false(self, monkeypatch):+ monkeypatch.delenv("JIUWENSWARM_ALLOW_LOOPBACK_MCP", raising=False)+ assert not _loopback_mcp_allowed()++ def test_env_true(self, monkeypatch):+ monkeypatch.setenv("JIUWENSWARM_ALLOW_LOOPBACK_MCP", "1")+ assert _loopback_mcp_allowed()++ def test_env_yes(self, monkeypatch):+ monkeypatch.setenv("JIUWENSWARM_ALLOW_LOOPBACK_MCP", "yes")+ assert _loopback_mcp_allowed()+++class TestValidateRequestScopedRemoteMcp:+ def test_external_url_allowed(self):+ _validate_request_scoped_remote_mcp("ok", {"url": "https://mcp.example.com/sse"})++ def test_loopback_ipv4_blocked(self):+ for host in ("127.0.0.1", "127.1.2.3"):+ with pytest.raises(ValueError, match="SSRF"):+ _validate_request_scoped_remote_mcp("t", {"url": f"http://{host}/sse"})++ def test_metadata_endpoint_blocked(self):+ with pytest.raises(ValueError, match="SSRF"):+ _validate_request_scoped_remote_mcp("t", {"url": "http://169.254.169.254/latest/meta-data/"})++ def test_private_network_blocked(self):+ for host in ("10.0.0.1", "192.168.1.1", "172.16.0.1"):+ with pytest.raises(ValueError, match="SSRF"):+ _validate_request_scoped_remote_mcp("t", {"url": f"http://{host}/mcp"})++ def test_localhost_blocked(self):+ with pytest.raises(ValueError, match="SSRF"):+ _validate_request_scoped_remote_mcp("t", {"url": "http://localhost:8080/sse"})++ def test_unspecified_address_blocked(self):+ with pytest.raises(ValueError, match="SSRF"):+ _validate_request_scoped_remote_mcp("t", {"url": "http://0.0.0.0/mcp"})++ def test_ipv6_loopback_blocked(self):+ with pytest.raises(ValueError, match="SSRF"):+ _validate_request_scoped_remote_mcp("t", {"url": "http://[::1]/mcp"})++ def test_no_url_allowed(self):+ _validate_request_scoped_remote_mcp("t", {"type": "sse"})++ def test_non_dict_cfg_noop(self):+ _validate_request_scoped_remote_mcp("t", "not-a-dict")++ def test_auth_headers_value_blocked(self):+ with pytest.raises(ValueError, match="凭证外泄"):+ _validate_request_scoped_remote_mcp("t", {+ "url": "https://mcp.example.com/sse",+ "auth_headers": {"X-Redirect": "http://169.254.169.254/"},+ })++ def test_auth_query_params_value_blocked(self):+ with pytest.raises(ValueError, match="凭证外泄"):+ _validate_request_scoped_remote_mcp("t", {+ "url": "https://mcp.example.com/mcp",+ "auth_query_params": {"target": "127.0.0.1"},+ })++ def test_auth_headers_external_value_allowed(self):+ _validate_request_scoped_remote_mcp("t", {+ "url": "https://mcp.example.com/sse",+ "auth_headers": {"Authorization": "Bearer valid-token"},+ "auth_query_params": {"token": "abc123"},+ })++ def test_loopback_allowed_when_env_set(self, monkeypatch):+ monkeypatch.setenv("JIUWENSWARM_ALLOW_LOOPBACK_MCP", "1")+ _validate_request_scoped_remote_mcp("t", {"url": "http://127.0.0.1:9999/sse"})+ _validate_request_scoped_remote_mcp("t", {"url": "http://localhost:8080/mcp"})+ _validate_request_scoped_remote_mcp("t", {"url": "http://[::1]/mcp"})++ def test_metadata_still_blocked_when_loopback_allowed(self, monkeypatch):+ monkeypatch.setenv("JIUWENSWARM_ALLOW_LOOPBACK_MCP", "1")+ with pytest.raises(ValueError, match="SSRF"):+ _validate_request_scoped_remote_mcp("t", {"url": "http://169.254.169.254/meta-data/"})+ with pytest.raises(ValueError, match="SSRF"):+ _validate_request_scoped_remote_mcp("t", {"url": "http://metadata.google.internal/"})++ def test_private_still_blocked_when_loopback_allowed(self, monkeypatch):+ monkeypatch.setenv("JIUWENSWARM_ALLOW_LOOPBACK_MCP", "1")+ with pytest.raises(ValueError, match="SSRF"):+ _validate_request_scoped_remote_mcp("t", {"url": "http://10.0.0.1/sse"})+ with pytest.raises(ValueError, match="SSRF"):+ _validate_request_scoped_remote_mcp("t", {"url": "http://192.168.1.1/mcp"})+++class TestCreateMcpToolStdio:+ def test_basic_stdio(self):+ cfg = json.dumps({"name": "my-tool", "command": "node", "args": ["server.js"]})+ result = create_mcp_tool(cfg)+ assert isinstance(result, McpServerConfig)+ assert result.client_type == "stdio"+ assert result.server_name == "my-tool"+ assert result.server_path == "stdio://my-tool"+ assert result.params["command"] == "node"+ assert result.params["args"] == ["server.js"]++ def test_stdio_with_python(self):+ cfg = json.dumps({"name": "py-tool", "command": "python", "args": ["-m", "mymod"]})+ result = create_mcp_tool(cfg)+ assert result.client_type == "stdio"+ assert result.params["command"] == "python"++ def test_stdio_with_env(self):+ cfg = json.dumps({+ "name": "env-tool",+ "command": "node",+ "args": ["s.js"],+ "env": {"KEY": "VAL"},+ })+ result = create_mcp_tool(cfg)+ assert result.params["env"] == {"KEY": "VAL"}++ def test_stdio_with_cwd(self):+ cfg = json.dumps({+ "name": "cwd-tool",+ "command": "node",+ "args": ["s.js"],+ "cwd": "/tmp/work",+ })+ result = create_mcp_tool(cfg)+ assert result.params["cwd"] == "/tmp/work"++ def test_stdio_with_server_id(self):+ cfg = json.dumps({+ "name": "sid-tool",+ "server_id": "custom-id",+ "command": "node",+ "args": ["s.js"],+ })+ result = create_mcp_tool(cfg)+ assert result.server_id == "custom-id"++ def test_missing_name_raises(self):+ with pytest.raises(ValueError, match="缺少 'name'"):+ create_mcp_tool(json.dumps({"command": "node", "args": ["s.js"]}))++ def test_missing_command_for_stdio_raises(self):+ with pytest.raises(ValueError, match="缺少"):+ create_mcp_tool(json.dumps({"name": "t", "command": "", "args": ["s.js"]}))++ def test_invalid_args_type_raises(self):+ with pytest.raises(ValueError, match="必须是列表"):+ create_mcp_tool(json.dumps({"name": "t", "command": "node", "args": "not-list"}))++ def test_unsupported_command_raises(self):+ with pytest.raises(ValueError, match="不支持"):+ create_mcp_tool(json.dumps({"name": "t", "command": "ruby", "args": ["s.rb"]}))++ def test_dangerous_eval_arg_blocked(self):+ with pytest.raises(ValueError, match="危险标志"):+ create_mcp_tool(json.dumps({"name": "t", "command": "node", "args": ["-e", "code"]}))++ def test_dangerous_command_arg_blocked(self):+ with pytest.raises(ValueError, match="危险标志"):+ create_mcp_tool(json.dumps({"name": "t", "command": "python", "args": ["-c", "print(1)"]}))++ def test_array_config(self):+ cfg = json.dumps([{"name": "arr-tool", "command": "node", "args": ["s.js"]}])+ result = create_mcp_tool(cfg)+ assert result.server_name == "arr-tool"++ def test_empty_array_raises(self):+ with pytest.raises(ValueError, match="不能为空"):+ create_mcp_tool("[]")++ def test_invalid_json_raises(self):+ with pytest.raises(ValueError, match="无效的 JSON"):+ create_mcp_tool("not-json")+++class TestCreateMcpToolNpxUvx:+ def test_npx_config(self):+ cfg = json.dumps({+ "name": "npx-tool",+ "command": "npx",+ "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],+ })+ result = create_mcp_tool(cfg)+ assert result.client_type == "stdio"+ assert result.params["command"] == "npx"+ assert result.params["args"] == ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]++ def test_uvx_config(self):+ cfg = json.dumps({"name": "uvx-tool", "command": "uvx", "args": ["mcp-server-fetch"]})+ result = create_mcp_tool(cfg)+ assert result.client_type == "stdio"+ assert result.params["command"] == "uvx"+ assert result.params["args"] == ["mcp-server-fetch"]++ def test_npx_with_env_and_cwd(self):+ cfg = json.dumps({+ "name": "npx-env",+ "command": "npx",+ "args": ["-y", "@scope/pkg"],+ "env": {"API_KEY": "secret"},+ "cwd": "/some/dir",+ })+ result = create_mcp_tool(cfg)+ assert result.params["env"] == {"API_KEY": "secret"}+ assert result.params["cwd"] == "/some/dir"++ def test_npx_absolute_path(self):+ cfg = json.dumps({"name": "npx-abs", "command": "/usr/local/bin/npx", "args": ["-y", "pkg"]})+ result = create_mcp_tool(cfg)+ assert result.params["command"] == "/usr/local/bin/npx"++ def test_uvx_absolute_path(self):+ cfg = json.dumps({"name": "uvx-abs", "command": r"C:\Users\me\.local\bin\uvx.exe", "args": ["pkg"]})+ result = create_mcp_tool(cfg)+ assert result.params["command"] == r"C:\Users\me\.local\bin\uvx.exe"++ def test_npx_dangerous_eval_arg_blocked(self):+ with pytest.raises(ValueError, match="危险标志"):+ create_mcp_tool(json.dumps({"name": "t", "command": "npx", "args": ["-e", "code"]}))++ def test_uvx_dangerous_command_arg_blocked(self):+ with pytest.raises(ValueError, match="危险标志"):+ create_mcp_tool(json.dumps({"name": "t", "command": "uvx", "args": ["-c", "print(1)"]}))+++class TestCreateMcpToolSse:+ def test_basic_sse(self):+ cfg = json.dumps({+ "name": "sse-tool",+ "type": "sse",+ "url": "http://127.0.0.1:3001/sse",+ })+ result = create_mcp_tool(cfg)+ assert result.client_type == "sse"+ assert result.server_path == "http://127.0.0.1:3001/sse"+ assert result.server_name == "sse-tool"++ def test_sse_with_auth(self):+ cfg = json.dumps({+ "name": "sse-auth",+ "type": "sse",+ "url": "http://127.0.0.1:3001/sse",+ "auth_headers": {"Authorization": "Bearer xxx"},+ "auth_query_params": {"token": "yyy"},+ })+ result = create_mcp_tool(cfg)+ assert result.auth_headers == {"Authorization": "Bearer xxx"}+ assert result.auth_query_params == {"token": "yyy"}++ def test_sse_missing_url_raises(self):+ with pytest.raises(ValueError, match="需要 url"):+ create_mcp_tool(json.dumps({"name": "sse-no-url", "type": "sse"}))++ def test_sse_with_server_id(self):+ cfg = json.dumps({+ "name": "sse-tool",+ "server_id": "custom-sse-id",+ "type": "sse",+ "url": "http://127.0.0.1:3001/sse",+ })+ result = create_mcp_tool(cfg)+ assert result.server_id == "custom-sse-id"++ def test_sse_default_server_id(self):+ cfg = json.dumps({+ "name": "sse-tool",+ "type": "sse",+ "url": "http://127.0.0.1:3001/sse",+ })+ result = create_mcp_tool(cfg)+ assert result.server_id == "sse-tool"+++class TestCreateMcpToolStreamableHttp:+ def test_basic_streamable_http(self):+ cfg = json.dumps({+ "name": "sh-tool",+ "type": "streamableHttp",+ "url": "http://127.0.0.1:3002/mcp",+ })+ result = create_mcp_tool(cfg)+ assert result.client_type == "streamable-http"+ assert result.server_path == "http://127.0.0.1:3002/mcp"++ def test_streamable_http_with_auth(self):+ cfg = json.dumps({+ "name": "sh-auth",+ "type": "streamable_http",+ "url": "http://127.0.0.1:3002/mcp",+ "auth_headers": {"Authorization": "Bearer z"},+ "auth_query_params": {"token": "w"},+ })+ result = create_mcp_tool(cfg)+ assert result.auth_headers == {"Authorization": "Bearer z"}+ assert result.auth_query_params == {"token": "w"}++ def test_streamable_http_missing_url_raises(self):+ with pytest.raises(ValueError, match="需要 url"):+ create_mcp_tool(json.dumps({"name": "sh-no-url", "type": "streamableHttp"}))++ def test_streamable_http_with_server_id(self):+ cfg = json.dumps({+ "name": "sh-tool",+ "server_id": "custom-sh-id",+ "type": "streamableHttp",+ "url": "http://127.0.0.1:3002/mcp",+ })+ result = create_mcp_tool(cfg)+ assert result.server_id == "custom-sh-id"+++class TestCreateMcpToolPlaywright:+ def test_basic_playwright(self):+ cfg = json.dumps({+ "name": "pw-tool",+ "type": "playwright",+ "url": "http://127.0.0.1:3003/sse",+ })+ result = create_mcp_tool(cfg)+ assert result.client_type == "playwright"+ assert result.server_path == "http://127.0.0.1:3003/sse"++ def test_playwright_missing_url_raises(self):+ with pytest.raises(ValueError, match="需要 url"):+ create_mcp_tool(json.dumps({"name": "pw-no-url", "type": "playwright"}))++ def test_playwright_with_server_id(self):+ cfg = json.dumps({+ "name": "pw-tool",+ "server_id": "custom-pw-id",+ "type": "playwright",+ "url": "http://127.0.0.1:3003/sse",+ })+ result = create_mcp_tool(cfg)+ assert result.server_id == "custom-pw-id"+++class TestCreateMcpToolOpenapi:+ def test_basic_openapi(self):+ cfg = json.dumps({+ "name": "oa-tool",+ "type": "openapi",+ "url": "http://127.0.0.1:3004/api",+ })+ result = create_mcp_tool(cfg)+ assert result.client_type == "openapi"+ assert result.server_path == "http://127.0.0.1:3004/api"++ def test_openapi_missing_url_raises(self):+ with pytest.raises(ValueError, match="需要 url"):+ create_mcp_tool(json.dumps({"name": "oa-no-url", "type": "openapi"}))++ def test_openapi_with_server_id(self):+ cfg = json.dumps({+ "name": "oa-tool",+ "server_id": "custom-oa-id",+ "type": "openapi",+ "url": "http://127.0.0.1:3004/api",+ })+ result = create_mcp_tool(cfg)+ assert result.server_id == "custom-oa-id"+++class TestCreateMcpToolDefaultType:+ def test_no_type_defaults_to_stdio(self):+ cfg = json.dumps({+ "name": "default-tool",+ "command": "node",+ "args": ["s.js"],+ })+ result = create_mcp_tool(cfg)+ assert result.client_type == "stdio"