The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools): mcp_oauth SDK loader -> _sdk_class, fold cached-redirect lookups and callback poll; lazy_deps installer helpers; managed_tool_gateway _clean
Teknium556f31e49648
diff --git a/tools/lazy_deps.py b/tools/lazy_deps.pyindex 86b308d2801..1ec140bcf9e 100644--- a/tools/lazy_deps.py+++ b/tools/lazy_deps.py@@ -1,27 +1,12 @@"""Lazy dependency installer for opt-in Hermes backends.-Backends call :func:`ensure(feature)` on first import; missing packages are-pip-installed into the active venv (or the durable target) unless the user set-``security.allow_lazy_installs: false``, in which case :class:`FeatureUnavailable`-carries a remediation hint. Eager ``[all]`` extras were both fragile (one yanked-transitive broke every extra) and bloated; lazy installs fix both.--Security model:-* Venv-scoped: installs target ``sys.executable``'s venv, never system Python.-* Durable-target mode (sealed images): ``HERMES_LAZY_INSTALL_TARGET`` redirects- installs to a writable volume that is APPENDED to ``sys.path`` — never- prepended, never via PYTHONPATH — so core site-packages wins every collision.- A lazily installed package can only add modules, never shadow or break core;- that guarantee is what made sealing the venv safe. An ABI stamp on the target- wipes stale compiled wheels across interpreter rebuilds.-* PyPI by name only: no ``--index-url``, ``git+``, or file specs (``_spec_is_safe``).-* Allowlist: only specs in :data:`LAZY_DEPS` flow into pip via ``ensure``.-* Opt-out ``security.allow_lazy_installs: false`` disables installs in both modes.-* Install failures surface pip's stderr as FeatureUnavailable — no retries, no cache.--Adding a backend: add a :data:`LAZY_DEPS` entry, then call ``ensure("ns.name")``-at the top of the backend's import path, converting FeatureUnavailable to a-useful runtime error.+Backends call :func:`ensure(feature)` on first import; missing packages are installed into the+active venv (or the durable target) unless ``security.allow_lazy_installs: false``, in which+case :class:`FeatureUnavailable` carries a remediation hint. Security model: venv-scoped+(never system Python); durable-target mode (``HERMES_LAZY_INSTALL_TARGET``, sealed images)+APPENDS the target to ``sys.path`` so core site-packages wins every collision and a lazy+package can only add modules, never shadow core; PyPI-by-name specs only (``_spec_is_safe``);+``ensure`` accepts only the :data:`LAZY_DEPS` allowlist; failures surface pip's stderr, no retry."""from __future__ import annotations@@ -43,12 +28,11 @@ from hermes_cli._subprocess_compat import windows_hide_flagslogger = logging.getLogger(__name__)-# Allowlist: "namespace.backend" -> pip specs matching the pyproject extra.-# Pins are exact (no ranges, security posture); bump here AND in pyproject.-# Shared patched floors, spelled out as literals in every feature because-# tests/test_packaging_metadata.py checks them by AST: aiohttp==3.14.3 (prior-# CVEs + GHSA-cq5v-8q36-5273/GHSA-mfx4-hv73-q22v/GHSA-mq44-7p77-q5h7) and-# starlette==1.3.1 (CVE-2026-48710 BadHost) — keep in sync with pyproject.+# Allowlist: "namespace.backend" -> pip specs matching the pyproject extra. Pins are exact+# (security posture); bump here AND in pyproject. Shared patched floors are spelled out as+# literals in every feature because tests/test_packaging_metadata.py checks them by AST:+# aiohttp==3.14.3 (GHSA-cq5v-8q36-5273/GHSA-mfx4-hv73-q22v/GHSA-mq44-7p77-q5h7) and+# starlette==1.3.1 (CVE-2026-48710 BadHost).LAZY_DEPS: dict[str, tuple[str, ...]] = {# ─── Inference providers ───────────────────────────────────────────────@@ -229,12 +213,9 @@ class FeatureUnavailable(RuntimeError):self.feature = featureself.missing = missingself.reason = reason- super().__init__(self._format())-- def _format(self) -> str:- spec_list = " ".join(repr(s) for s in self.missing)- return (- f"Feature {self.feature!r} unavailable: {self.reason}. "+ spec_list = " ".join(repr(s) for s in missing)+ super().__init__(+ f"Feature {feature!r} unavailable: {reason}. "f"To enable manually: uv pip install {spec_list} "f"(or: pip install {spec_list}).")@@ -256,16 +237,13 @@ _LAZY_TARGET_ENV = "HERMES_LAZY_INSTALL_TARGET"# after an image rebuild wipes the store so stale .so files are never imported._TARGET_STAMP_NAME = ".python-abi"-_SUBPROCESS_KW = dict(capture_output=True, text=True, encoding="utf-8", errors="replace",- stdin=subprocess.DEVNULL)+_SUBPROCESS_KW = dict(capture_output=True, text=True, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL)def _python_abi_tag() -> str:"""X.Y version + EXT_SUFFIX (ABI tag + platform); interpreters that canshare compiled wheels produce the same token."""- ver = f"{sys.version_info.major}.{sys.version_info.minor}"- ext = sysconfig.get_config_var("EXT_SUFFIX") or ""- return f"{ver}:{ext}"+ return f"{sys.version_info.major}.{sys.version_info.minor}:{sysconfig.get_config_var('EXT_SUFFIX') or ''}"def _lazy_install_target() -> Optional[Path]:@@ -289,8 +267,7 @@ def _ensure_target_ready(target: Path) -> Optional[str]:have = ""if have and have != want:logger.info(- "Lazy install target %s was built for ABI %r but running "- "ABI is %r; wiping stale packages.",+ "Lazy install target %s was built for ABI %r but running ABI is %r; wiping stale packages.",target, have, want,)for child in target.iterdir():@@ -360,11 +337,8 @@ def _allow_lazy_installs() -> bool:cfg = load_config()except Exception:cfg = None- if cfg is not None:- sec = cfg.get("security") or {}- if not bool(sec.get("allow_lazy_installs", True)):- return False-+ if cfg is not None and not bool((cfg.get("security") or {}).get("allow_lazy_installs", True)):+ return Falseif os.environ.get("HERMES_DISABLE_LAZY_INSTALLS") == "1":return _lazy_install_target() is not Nonereturn True@@ -384,13 +358,12 @@ def _unsupported_feature_reason(feature: str) -> Optional[str]:def _spec_is_safe(spec: str) -> bool:"""Reject pip specs that contain URLs, paths, or shell metacharacters."""- if not spec or len(spec) > 200:- return False- if any(ch in spec for ch in (";", "|", "&", "`", "$", "\n", "\r", "\t", "\\")):- return False- if spec.startswith(("-", "/", ".")) or "://" in spec or "@" in spec:- return False- return bool(_SAFE_SPEC.match(spec))+ return bool(+ spec and len(spec) <= 200+ and not any(ch in spec for ch in (";", "|", "&", "`", "$", "\n", "\r", "\t", "\\"))+ and not spec.startswith(("-", "/", ".")) and "://" not in spec and "@" not in spec+ and _SAFE_SPEC.match(spec)+ )def _pkg_name_from_spec(spec: str) -> str:@@ -451,20 +424,16 @@ def _core_constraints_file() -> Optional[Path]:import tempfilefrom importlib.metadata import distributions- lines = []- seen = set()+ pins: dict[str, str] = {}for dist in distributions():name = dist.metadata["Name"] if dist.metadata else None- ver = dist.version- if not name or not ver or name.lower() in seen:- continue- seen.add(name.lower())- lines.append(f"{name}=={ver}")- if not lines:+ if name and dist.version and name.lower() not in pins:+ pins[name.lower()] = f"{name}=={dist.version}"+ if not pins:return Nonefd, path = tempfile.mkstemp(prefix="hermes-core-constraints-", suffix=".txt")with os.fdopen(fd, "w", encoding="utf-8") as f:- f.write("\n".join(sorted(lines)) + "\n")+ f.write("\n".join(sorted(pins.values())) + "\n")return Path(path)except Exception as e:logger.debug("Could not build core constraints file: %s", e)@@ -475,26 +444,20 @@ def _installed_dist_roots(spec: str, target: Optional[Path]) -> set[Path]:"""Package directories a freshly installed *spec* owns, from the dist's ownfile list (``python-telegram-bot`` ships ``telegram``; some ship several)."""name = _pkg_name_from_spec(spec)+ roots: set[Path] = set()try:import importlib.metadata as _mdif target is not None:- dists = list(_md.distributions(name=name, path=[str(target)]))- dist = dists[0] if dists else None+ dist = next(iter(_md.distributions(name=name, path=[str(target)])), None)else:dist = _md.distribution(name)- except Exception:- return set()- if dist is None:- return set()-- roots: set[Path] = set()- try:+ if dist is None:+ return rootsfor entry in dist.files or ():parts = entry.parts- if not parts or parts[0].startswith(".") or parts[0] == "__pycache__":- continue- if parts[0].endswith((".dist-info", ".egg-info")): # no importable code+ # Skip hidden entries, __pycache__ and metadata dirs (no importable code).+ if not parts or parts[0].startswith(".") or parts[0] == "__pycache__" or parts[0].endswith((".dist-info", ".egg-info")):continueroot = Path(dist.locate_file(parts[0]))if root.is_dir():@@ -516,7 +479,6 @@ def _warm_installed_bytecode(specs: tuple[str, ...], target: Optional[Path]) ->import compileallexcept Exception: # pragma: no cover — stdlib, but never break an installreturn-for spec in specs:try:roots = _installed_dist_roots(spec, target)@@ -530,6 +492,23 @@ def _warm_installed_bytecode(specs: tuple[str, ...], target: Optional[Path]) ->logger.debug("Bytecode warm skipped for %s: %s", root, exc)+def _run_installer(cmd: list[str], **kw) -> subprocess.CompletedProcess:+ # _SUBPROCESS_KW carries stdin=DEVNULL # noqa: subprocess-stdin+ return subprocess.run(cmd, **_SUBPROCESS_KW, creationflags=windows_hide_flags(), **kw)+++def _uv_binary() -> Optional[str]:+ """Managed uv first ($HERMES_HOME/bin is never on PATH), then PATH. A lookup, not+ ensure_uv(): downloading uv mid-turn is far more than the caller asked for; the pip tier+ covers the no-uv case."""+ try:+ from hermes_cli.managed_uv import resolve_uv++ return resolve_uv() or shutil.which("uv")+ except Exception:+ return shutil.which("uv")++def _venv_pip_install(specs: tuple[str, ...], *, timeout: int = 300) -> _InstallResult:"""Install ``specs`` via the uv -> pip -> ensurepip ladder, venv-scoped bydefault or into the durable ``--target`` (constrained to core versions, see@@ -541,21 +520,15 @@ def _venv_pip_install(specs: tuple[str, ...], *, timeout: int = 300) -> _Installtarget = _lazy_install_target()constraints: Optional[Path] = None+ extra_args: list[str] = []if target is not None:err = _ensure_target_ready(target)if err:return _InstallResult(False, "", err)constraints = _core_constraints_file()-- extra_args: list[str] = []- if target is not None:extra_args += ["--target", str(target)]- if constraints is not None:- extra_args += ["--constraint", str(constraints)]-- def _run(cmd: list[str], **kw) -> subprocess.CompletedProcess:- # _SUBPROCESS_KW carries stdin=DEVNULL # noqa: subprocess-stdin- return subprocess.run(cmd, **_SUBPROCESS_KW, creationflags=windows_hide_flags(), **kw)+ if constraints is not None:+ extra_args += ["--constraint", str(constraints)]def _finish(r: subprocess.CompletedProcess) -> _InstallResult:if r.returncode == 0:@@ -569,23 +542,15 @@ def _venv_pip_install(specs: tuple[str, ...], *, timeout: int = 300) -> _Installuv_env = hermes_subprocess_env(inherit_credentials=False)uv_env["VIRTUAL_ENV"] = str(Path(sys.executable).parent.parent)- # Tier 1: uv. Managed uv first ($HERMES_HOME/bin is never on PATH). A- # lookup, not ensure_uv(): downloading uv mid-turn is far more than the- # caller asked for; the pip tier covers the no-uv case.- try:- from hermes_cli.managed_uv import resolve_uv-- uv_bin = resolve_uv() or shutil.which("uv")- except Exception:- uv_bin = shutil.which("uv")+ # Tier 1: uv.+ uv_bin = _uv_binary()if uv_bin:try:# --compile-bytecode: uv writes no __pycache__ by default, so the# first import would recompile the backend AND its transitives.# Covers the whole install; _warm_installed_bytecode is the# belt-and-braces pass for the spec's own roots on any tier.- r = _run([uv_bin, "pip", "install", "--compile-bytecode", *extra_args, *specs],- timeout=timeout, env=uv_env)+ r = _run_installer([uv_bin, "pip", "install", "--compile-bytecode", *extra_args, *specs], timeout=timeout, env=uv_env)if r.returncode != 0:logger.debug("uv pip install failed: %s", r.stderr)# A uv resolver failure is authoritative: falling through to pip@@ -603,18 +568,16 @@ def _venv_pip_install(specs: tuple[str, ...], *, timeout: int = 300) -> _Install# Tier 2: python -m pip (ensurepip bootstrap if needed)pip_cmd = [sys.executable, "-m", "pip"]try:- if _run(pip_cmd + ["--version"], timeout=15).returncode != 0:+ if _run_installer(pip_cmd + ["--version"], timeout=15).returncode != 0:raise FileNotFoundError("pip not in venv")except (subprocess.TimeoutExpired, FileNotFoundError):try:- _run([sys.executable, "-m", "ensurepip", "--upgrade", "--default-pip"],- timeout=120, check=True)+ _run_installer([sys.executable, "-m", "ensurepip", "--upgrade", "--default-pip"], timeout=120, check=True)except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:- return _InstallResult(False, "",- f"pip not available and ensurepip failed: {e}")+ return _InstallResult(False, "", f"pip not available and ensurepip failed: {e}")try:- return _finish(_run(pip_cmd + ["install", *extra_args, *specs], timeout=timeout))+ return _finish(_run_installer(pip_cmd + ["install", *extra_args, *specs], timeout=timeout))except subprocess.TimeoutExpired as e:return _InstallResult(False, "", f"pip install timed out: {e}")except Exception as e:@@ -630,16 +593,11 @@ def _venv_pip_install(specs: tuple[str, ...], *, timeout: int = 300) -> _Install# ---- Public API ----------------------------------------------------------------def feature_specs(feature: str) -> tuple[str, ...]:- """Return the registered specs for a feature, or raise KeyError."""- if feature not in LAZY_DEPS:- raise KeyError(f"Unknown lazy feature: {feature!r}")- return LAZY_DEPS[feature]--def feature_missing(feature: str) -> tuple[str, ...]:"""Return the subset of specs for ``feature`` not currently installed."""- return tuple(s for s in feature_specs(feature) if not _is_satisfied(s))+ if feature not in LAZY_DEPS:+ raise KeyError(f"Unknown lazy feature: {feature!r}")+ return tuple(s for s in LAZY_DEPS[feature] if not _is_satisfied(s))def _prompt_toolkit_active() -> bool:@@ -662,9 +620,7 @@ def ensure(feature: str, *, prompt: bool = True) -> None:``prompt``: confirm on a TTY first; non-interactive callers pass False andrely on the config flag as the gate."""if feature not in LAZY_DEPS:- raise FeatureUnavailable(- feature, (), f"feature {feature!r} not in LAZY_DEPS allowlist"- )+ raise FeatureUnavailable(feature, (), f"feature {feature!r} not in LAZY_DEPS allowlist")missing = feature_missing(feature)if not missing:@@ -696,16 +652,10 @@ def ensure(feature: str, *, prompt: bool = True) -> None:for spec in missing: # belt and braces on top of the allowlistif not _spec_is_safe(spec):- raise FeatureUnavailable(- feature, missing,- f"refusing to install unsafe spec {spec!r}"- )+ raise FeatureUnavailable(feature, missing, f"refusing to install unsafe spec {spec!r}")if not _allow_lazy_installs():- raise FeatureUnavailable(- feature, missing,- "lazy installs disabled (security.allow_lazy_installs=false)"- )+ raise FeatureUnavailable(feature, missing, "lazy installs disabled (security.allow_lazy_installs=false)")if prompt and not _prompt_toolkit_active() and sys.stdin.isatty() and sys.stdout.isatty():spec_list = ", ".join(missing)@@ -717,9 +667,7 @@ def ensure(feature: str, *, prompt: bool = True) -> None:except (EOFError, KeyboardInterrupt):answer = "n"if answer and answer not in {"y", "yes"}:- raise FeatureUnavailable(- feature, missing, "user declined install at prompt"- )+ raise FeatureUnavailable(feature, missing, "user declined install at prompt")logger.info("Lazy-installing %s for feature %r", " ".join(missing), feature)result = _venv_pip_install(missing)@@ -727,18 +675,14 @@ def ensure(feature: str, *, prompt: bool = True) -> None:# Surface pip's own error (quarantine 404, network) — tail-clipped,# since pip can dump pages of resolution traces.snippet = (result.stderr or result.stdout or "").strip()[-2000:]- raise FeatureUnavailable(- feature, missing,- f"pip install failed: {snippet or 'no error output'}"- )+ raise FeatureUnavailable(feature, missing, f"pip install failed: {snippet or 'no error output'}")_invalidate_import_caches()still_missing = feature_missing(feature)if still_missing:raise FeatureUnavailable(feature, still_missing,- "install reported success but packages still not importable "- "(may require Python restart)"+ "install reported success but packages still not importable (may require Python restart)")logger.info("Lazy install complete for feature %r", feature)@@ -746,9 +690,7 @@ def ensure(feature: str, *, prompt: bool = True) -> None:def is_available(feature: str) -> bool:"""Return True if the feature's deps are already satisfied."""- if feature not in LAZY_DEPS:- return False- return not feature_missing(feature)+ return feature in LAZY_DEPS and not feature_missing(feature)def feature_install_command(feature: str, *, venv_pip: bool = False) -> Optional[str]:@@ -765,14 +707,10 @@ def feature_install_command(feature: str, *, venv_pip: bool = False) -> Optional@dataclassclass InstallSpecsResult:- """Outcome of :func:`install_specs` for one batch of pip specs.-- ``ok`` — install succeeded (or nothing was missing).- ``blocked`` — installs are gated off (config kill switch, sealed venv- without a durable target) or a spec failed validation;- nothing was executed. ``reason`` explains why.- ``command`` — human-readable description of what ran (for UIs/logs).- """+ """Outcome of :func:`install_specs` for one batch of pip specs. ``blocked`` means installs+ are gated off (config kill switch, sealed venv without a durable target) or a spec failed+ validation — nothing was executed, ``reason`` says why. ``command`` is the human-readable+ description of what ran (for UIs/logs)."""ok: boolblocked: bool = Falsereason: str = ""@@ -793,13 +731,10 @@ def install_specs(specs: list[str] | tuple[str, ...], *, timeout: int = 300) ->for spec in cleaned:if not _spec_is_safe(spec):- return InstallSpecsResult(- ok=False, blocked=True,- reason=f"refusing to install unsafe spec {spec!r}",- )+ return InstallSpecsResult(ok=False, blocked=True, reason=f"refusing to install unsafe spec {spec!r}")+ target = _lazy_install_target()if not _allow_lazy_installs():- target = _lazy_install_target()if os.environ.get("HERMES_DISABLE_LAZY_INSTALLS") == "1" and target is None:reason = ("runtime installs are disabled on this deployment: the agent "@@ -810,27 +745,17 @@ def install_specs(specs: list[str] | tuple[str, ...], *, timeout: int = 300) ->reason = "runtime installs disabled (security.allow_lazy_installs=false)"return InstallSpecsResult(ok=False, blocked=True, reason=reason)- target = _lazy_install_target()- display = "uv pip install " + (- f"--target {target} " if target is not None else ""- ) + " ".join(cleaned)+ display = "uv pip install " + (f"--target {target} " if target is not None else "") + " ".join(cleaned)logger.info("Installing pip specs %s (target=%s)", " ".join(cleaned), target or "venv")try:result = _venv_pip_install(cleaned, timeout=timeout)except Exception as exc:logger.warning("install_specs failed unexpectedly: %s", exc)- return InstallSpecsResult(- ok=False, command=display, stderr=f"install failed: {exc}"- )+ return InstallSpecsResult(ok=False, command=display, stderr=f"install failed: {exc}")_invalidate_import_caches() # dashboard rechecks availability inline- return InstallSpecsResult(- ok=result.success,- command=display,- stdout=result.stdout,- stderr=result.stderr,- )+ return InstallSpecsResult(ok=result.success, command=display, stdout=result.stdout, stderr=result.stderr)def active_features() -> list[str]:@@ -853,34 +778,25 @@ def restore_features(features: list[str]) -> dict[str, str]:return _refresh_features(features, prompt=False, restoring=True)-def _refresh_features(- features: list[str], *, prompt: bool, restoring: bool-) -> dict[str, str]:+def _refresh_features(features: list[str], *, prompt: bool, restoring: bool) -> dict[str, str]:"""Refresh or restore a known set of allowlisted lazy features."""results: dict[str, str] = {}for feature in features:if feature not in LAZY_DEPS:continue- missing = feature_missing(feature)- if not missing:+ if not feature_missing(feature):results[feature] = "current"continue-unsupported = _unsupported_feature_reason(feature)if unsupported:results[feature] = f"skipped: {unsupported}"continue-try:ensure(feature, prompt=False if restoring else prompt)results[feature] = "restored" if restoring else "refreshed"except FeatureUnavailable as e:# Opt-outs and platform-incompatible features are skips, not failures.- if (- "lazy installs disabled" in str(e)- or "declined" in str(e)- or e.reason.startswith("unsupported ")- ):+ if "lazy installs disabled" in str(e) or "declined" in str(e) or e.reason.startswith("unsupported "):results[feature] = f"skipped: {e.reason}"else:results[feature] = f"failed: {e.reason}"@@ -889,13 +805,7 @@ def _refresh_features(return results-def ensure_and_bind(- feature: str,- importer: Callable[[], dict[str, Any]],- target_globals: dict,- *,- prompt: bool = False,-) -> bool:+def ensure_and_bind(feature: str, importer: Callable[[], dict[str, Any]], target_globals: dict, *, prompt: bool = False) -> bool:""":func:`ensure` the feature, then ``target_globals.update(importer())`` somodule-level names are rebound after a lazy install without hand-listingthem. ``importer`` runs only after ensure succeeds. Returns False (and@@ -916,12 +826,10 @@ def ensure_and_bind(except Exception as exc:logger.warning("Failed to ensure feature %r: %s", feature, exc)return False-try:bindings = importer()except ImportError as exc:logger.warning("Failed to import feature %r after install: %s", feature, exc)return False-target_globals.update(bindings)return Truediff --git a/tools/managed_tool_gateway.py b/tools/managed_tool_gateway.pyindex 1a6bce3b8a1..529cdaa0a32 100644--- a/tools/managed_tool_gateway.py+++ b/tools/managed_tool_gateway.py@@ -27,6 +27,11 @@ class ManagedToolGatewayConfig:managed_mode: bool+def _clean(value: object) -> Optional[str]:+ """*value* stripped when it is a non-blank string, else None."""+ return value.strip() if isinstance(value, str) and value.strip() else None++def auth_json_path():"""Return the Hermes auth store path, respecting HERMES_HOME overrides."""return get_hermes_home() / "auth.json"@@ -37,11 +42,8 @@ def _read_nous_provider_state() -> Optional[dict]:path = auth_json_path()if not path.is_file():return None- data = json.loads(path.read_text(encoding="utf-8-sig"))- providers = data.get("providers", {})- if not isinstance(providers, dict):- return None- nous_provider = providers.get("nous", {})+ providers = json.loads(path.read_text(encoding="utf-8-sig")).get("providers", {})+ nous_provider = providers.get("nous", {}) if isinstance(providers, dict) else Noneif isinstance(nous_provider, dict):return nous_providerexcept Exception:@@ -50,9 +52,9 @@ def _read_nous_provider_state() -> Optional[dict]:def _parse_timestamp(value: object) -> Optional[datetime]:- if not isinstance(value, str) or not value.strip():+ normalized = _clean(value)+ if normalized is None:return None- normalized = value.strip()if normalized.endswith("Z"):normalized = normalized[:-1] + "+00:00"try:@@ -68,16 +70,13 @@ def _access_token_is_expiring(expires_at: object, skew_seconds: int) -> bool:expires = _parse_timestamp(expires_at)if expires is None:return True- remaining = (expires - datetime.now(timezone.utc)).total_seconds()- return remaining <= max(0, int(skew_seconds))+ return (expires - datetime.now(timezone.utc)).total_seconds() <= max(0, int(skew_seconds))def _read_user_token_override() -> Optional[str]:- """Read the TOOL_GATEWAY_USER_TOKEN override through the secret scope.-- Scope verdict is authoritative when installed (a scoped miss must NOT- borrow the process env under multiplex); ``os.environ`` only when unscoped.- """+ """Read the TOOL_GATEWAY_USER_TOKEN override through the secret scope. Scope verdict is+ authoritative when installed (a scoped miss must NOT borrow the process env under+ multiplex); ``os.environ`` only when unscoped."""try:from agent.secret_scope import UnscopedSecretError, get_secret@@ -87,24 +86,14 @@ def _read_user_token_override() -> Optional[str]:explicit = os.getenv("TOOL_GATEWAY_USER_TOKEN")except Exception:explicit = os.getenv("TOOL_GATEWAY_USER_TOKEN")- if isinstance(explicit, str) and explicit.strip():- return explicit.strip()- return None+ return _clean(explicit)def peek_nous_access_token() -> Optional[str]:- """Cheap token probe: env override or cached auth-store token, no expiry- check and no network — availability scans must stay off the synchronous- OAuth refresh path (that lives in :func:`read_nous_access_token`)."""- explicit = _read_user_token_override()- if explicit:- return explicit-- nous_provider = _read_nous_provider_state() or {}- access_token = nous_provider.get("access_token")- if isinstance(access_token, str) and access_token.strip():- return access_token.strip()- return None+ """Cheap token probe: env override or cached auth-store token, no expiry check and no+ network — availability scans must stay off the synchronous OAuth refresh path (that lives+ in :func:`read_nous_access_token`)."""+ return _read_user_token_override() or _clean((_read_nous_provider_state() or {}).get("access_token"))def read_nous_access_token() -> Optional[str]:@@ -114,24 +103,16 @@ def read_nous_access_token() -> Optional[str]:return explicitnous_provider = _read_nous_provider_state() or {}cached_token = peek_nous_access_token()-- if cached_token and not _access_token_is_expiring(- nous_provider.get("expires_at"),- _NOUS_ACCESS_TOKEN_REFRESH_SKEW_SECONDS,- ):+ if cached_token and not _access_token_is_expiring(nous_provider.get("expires_at"), _NOUS_ACCESS_TOKEN_REFRESH_SKEW_SECONDS):return cached_token-try:from hermes_cli.auth import resolve_nous_access_token- refreshed_token = resolve_nous_access_token(- refresh_skew_seconds=_NOUS_ACCESS_TOKEN_REFRESH_SKEW_SECONDS,- )- if isinstance(refreshed_token, str) and refreshed_token.strip():- return refreshed_token.strip()+ refreshed_token = _clean(resolve_nous_access_token(refresh_skew_seconds=_NOUS_ACCESS_TOKEN_REFRESH_SKEW_SECONDS))+ if refreshed_token:+ return refreshed_tokenexcept Exception as exc:logger.debug("Nous access token refresh failed: %s", exc)-return cached_token@@ -147,14 +128,11 @@ def get_tool_gateway_scheme() -> str:def build_vendor_gateway_url(vendor: str) -> str:"""Return the gateway origin for a specific vendor."""- vendor_key = f"{vendor.upper().replace('-', '_')}_GATEWAY_URL"- explicit_vendor_url = os.getenv(vendor_key, "").strip().rstrip("/")+ explicit_vendor_url = os.getenv(f"{vendor.upper().replace('-', '_')}_GATEWAY_URL", "").strip().rstrip("/")if explicit_vendor_url:return explicit_vendor_url-- shared_scheme = get_tool_gateway_scheme()shared_domain = os.getenv("TOOL_GATEWAY_DOMAIN", "").strip().strip("/") or _DEFAULT_TOOL_GATEWAY_DOMAIN- return f"{shared_scheme}://{vendor}-gateway.{shared_domain}"+ return f"{get_tool_gateway_scheme()}://{vendor}-gateway.{shared_domain}"def resolve_managed_tool_gateway(@@ -165,21 +143,11 @@ def resolve_managed_tool_gateway("""Resolve shared managed-tool gateway config for a vendor."""if not managed_nous_tools_enabled():return None-- resolved_gateway_builder = gateway_builder or build_vendor_gateway_url- resolved_token_reader = token_reader or read_nous_access_token-- gateway_origin = resolved_gateway_builder(vendor)- nous_user_token = resolved_token_reader()+ gateway_origin = (gateway_builder or build_vendor_gateway_url)(vendor)+ nous_user_token = (token_reader or read_nous_access_token)()if not gateway_origin or not nous_user_token:return None-- return ManagedToolGatewayConfig(- vendor=vendor,- gateway_origin=gateway_origin,- nous_user_token=nous_user_token,- managed_mode=True,- )+ return ManagedToolGatewayConfig(vendor=vendor, gateway_origin=gateway_origin, nous_user_token=nous_user_token, managed_mode=True)def is_managed_tool_gateway_ready(@@ -187,13 +155,7 @@ def is_managed_tool_gateway_ready(gateway_builder: Optional[Callable[[str], str]] = None,token_reader: Optional[Callable[[], Optional[str]]] = None,) -> bool:- """True when a gateway URL and a likely-usable Nous token are present.-- Defaults to :func:`peek_nous_access_token` (no OAuth refresh); callers about- to make a real request use :func:`resolve_managed_tool_gateway` instead.- """- return resolve_managed_tool_gateway(- vendor,- gateway_builder=gateway_builder,- token_reader=token_reader or peek_nous_access_token,- ) is not None+ """True when a gateway URL and a likely-usable Nous token are present. Defaults to+ :func:`peek_nous_access_token` (no OAuth refresh); callers about to make a real request+ use :func:`resolve_managed_tool_gateway` instead."""+ return resolve_managed_tool_gateway(vendor, gateway_builder=gateway_builder, token_reader=token_reader or peek_nous_access_token) is not Nonediff --git a/tools/mcp_dashboard_oauth.py b/tools/mcp_dashboard_oauth.pyindex fba7b299778..ec837ceb1b1 100644--- a/tools/mcp_dashboard_oauth.py+++ b/tools/mcp_dashboard_oauth.py@@ -66,13 +66,9 @@ class DashboardOAuthFlow:self.status = "authorization_required"self._authorization_ready.set()- @staticmethod- async def _await_event(event: threading.Event, timeout: float, message: str) -> None:- if not await asyncio.to_thread(event.wait, timeout):- raise TimeoutError(message)-async def wait_for_authorization_url(self, timeout: float = 30.0) -> str:- await self._await_event(self._authorization_ready, timeout, "Timed out waiting for MCP authorization URL")+ if not await asyncio.to_thread(self._authorization_ready.wait, timeout):+ raise TimeoutError("Timed out waiting for MCP authorization URL")if not self.authorization_url:raise RuntimeError(self.error or "MCP OAuth flow ended before authorization")return self.authorization_url@@ -93,7 +89,8 @@ class DashboardOAuthFlow:self._callback_ready.set()async def wait_for_callback(self, timeout: float = 300.0) -> tuple[str, str | None]:- await self._await_event(self._callback_ready, timeout, "Timed out waiting for MCP OAuth callback")+ if not await asyncio.to_thread(self._callback_ready.wait, timeout):+ raise TimeoutError("Timed out waiting for MCP OAuth callback")if self._callback_error:raise RuntimeError(f"OAuth authorization failed: {self._callback_error}")if self._callback is None:@@ -134,9 +131,7 @@ class DashboardOAuthFlow:return self._worker_done.is_set()-_current_dashboard_flow: contextvars.ContextVar[DashboardOAuthFlow | None] = (- contextvars.ContextVar("mcp_dashboard_oauth_flow", default=None)-)+_current_dashboard_flow: contextvars.ContextVar[DashboardOAuthFlow | None] = contextvars.ContextVar("mcp_dashboard_oauth_flow", default=None)def dashboard_oauth_flow(flow: DashboardOAuthFlow):diff --git a/tools/mcp_oauth.py b/tools/mcp_oauth.pyindex d3c6ba8d3d6..fa70221adf3 100644--- a/tools/mcp_oauth.py+++ b/tools/mcp_oauth.py@@ -31,64 +31,45 @@ import timeimport webbrowserfrom http.server import BaseHTTPRequestHandler, HTTPServerfrom pathlib import Path-from typing import Any+from typing import TYPE_CHECKING, Anyfrom urllib.parse import parse_qs, urlparsefrom hermes_constants import secure_parent_dirfrom tools.mcp_dashboard_oauth import contextvar_set as _contextvar_set, get_dashboard_oauth_flow+if TYPE_CHECKING: # annotations only; the SDK is imported lazily at runtime+ from mcp.client.auth import OAuthClientProvider+ from mcp.shared.auth import OAuthClientInformationFull, OAuthClientMetadata, OAuthMetadata, OAuthToken+logger = logging.getLogger(__name__)-# Lazy SDK imports: availability is detected WITHOUT importing mcp (~170 ms). Module-level-# names stay None placeholders so tests can patch.object them; _ensure_sdk_loaded() binds the-# real classes on first use and _SDK_CLASSES caches them so a test that patches a name and-# restores it to None afterwards doesn't strand the module in a broken state.+# SDK availability is detected WITHOUT importing mcp (~170 ms); the classes bind lazily on+# first use via _sdk_class()._OAUTH_AVAILABLE = _importlib_util.find_spec("mcp") is not Noneif not _OAUTH_AVAILABLE:logger.debug("MCP OAuth types not available -- OAuth MCP auth disabled")-OAuthClientProvider: Any = None-OAuthClientInformationFull: Any = None-OAuthClientMetadata: Any = None-OAuthMetadata: Any = None-OAuthToken: Any = None-+_SDK_CLASS_NAMES = ("OAuthClientProvider", "OAuthClientInformationFull", "OAuthClientMetadata", "OAuthMetadata", "OAuthToken")_SDK_CLASSES: dict[str, Any] = {}-_SDK_LOAD_FAILED = False-def _ensure_sdk_loaded() -> bool:- """Bind the SDK OAuth classes into module globals; True when available. Only names- currently ``None`` are (re)bound, so test patches stay intact."""- global _SDK_LOAD_FAILED, _OAUTH_AVAILABLE- if _SDK_LOAD_FAILED:- return False+def _sdk_class(name: str) -> Any:+ """Return the SDK OAuth class *name*, importing the SDK on first call; None when unavailable+ (the failure is remembered so a broken SDK is probed once)."""+ global _OAUTH_AVAILABLEif not _SDK_CLASSES:try:from mcp.client import auth as _client_authfrom mcp.shared import auth as _shared_auth_SDK_CLASSES["OAuthClientProvider"] = _client_auth.OAuthClientProvider- for _name in ("OAuthClientInformationFull", "OAuthClientMetadata", "OAuthMetadata", "OAuthToken"):+ for _name in _SDK_CLASS_NAMES[1:]:_SDK_CLASSES[_name] = getattr(_shared_auth, _name)except (ImportError, AttributeError):- _SDK_CLASSES.clear()- _SDK_LOAD_FAILED = True+ _SDK_CLASSES.update(dict.fromkeys(_SDK_CLASS_NAMES))_OAUTH_AVAILABLE = Falselogger.debug("MCP OAuth types not available -- OAuth MCP auth disabled")- return False- g = globals()- for _name, _cls in _SDK_CLASSES.items():- if g.get(_name) is None:- g[_name] = _cls- return True---def _sdk_class(name: str) -> Any:- """Return the (possibly test-patched) SDK class bound under *name*, or None."""- if globals().get(name) is None and not _ensure_sdk_loaded():- return None- return globals().get(name)+ return _SDK_CLASSES.get(name)try:@@ -144,22 +125,11 @@ _reserved_sockets: "dict[int, socket.socket]" = {}_MAX_RESERVED_SOCKETS = 8-def _park_reserved_socket(port: int, sock: socket.socket) -> None:- """Hold *sock* bound to *port* until the callback waiter adopts it. Pinned CIMD sockets- are never evicted: the published document only declares the pinned ports, so losing one- mid-flow would reopen the race the parking prevents. The FIFO cap applies to ephemeral- ports only."""- while len(_reserved_sockets) >= _MAX_RESERVED_SOCKETS:- stale_port = next((p for p in _reserved_sockets if p not in _CIMD_PORTS), None)- if stale_port is None:- break # only pinned sockets remain — never evict those- with contextlib.suppress(OSError):- _reserved_sockets.pop(stale_port).close()- _reserved_sockets[port] = sock--def _bind_reserved(port: int) -> int | None:- """Bind ``127.0.0.1:port`` (0 = ephemeral) and park it; None if taken."""+ """Bind ``127.0.0.1:port`` (0 = ephemeral) and park it until the waiter adopts it; None if+ taken. Pinned CIMD sockets are never evicted: the published document only declares the+ pinned ports, so losing one mid-flow would reopen the race the parking prevents. The FIFO+ cap applies to ephemeral ports only."""sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)try:sock.bind(("127.0.0.1", port))@@ -169,7 +139,13 @@ def _bind_reserved(port: int) -> int | None:return Noneraisebound = sock.getsockname()[1]- _park_reserved_socket(bound, sock)+ while len(_reserved_sockets) >= _MAX_RESERVED_SOCKETS:+ stale_port = next((p for p in _reserved_sockets if p not in _CIMD_PORTS), None)+ if stale_port is None:+ break # only pinned sockets remain — never evict those+ with contextlib.suppress(OSError):+ _reserved_sockets.pop(stale_port).close()+ _reserved_sockets[bound] = sockreturn bound@@ -187,31 +163,21 @@ def _cached_client_info(storage: "HermesTokenStorage | None") -> dict | None:return None-def _cached_redirect_uris(storage: "HermesTokenStorage | None"):- """Yield ``(raw_uri, parsed)`` for each redirect URI in the cached registration."""- for uri in (_cached_client_info(storage) or {}).get("redirect_uris") or []:+def _cached_redirect(storage: "HermesTokenStorage | None") -> "tuple[str | None, int | None]":+ """``(https proxy URI, loopback callback port)`` from the cached client registration (each+ None when absent). Providers bind a dynamically-registered ``client_id`` to the exact+ redirect URI registered with it; a new random port under the stored ``client_id`` gets+ ``redirect_uri does not match any registered URIs``."""+ uri = port = None+ for raw in (_cached_client_info(storage) or {}).get("redirect_uris") or []:with contextlib.suppress(TypeError, ValueError):- yield str(uri), urlparse(str(uri))---def _cached_redirect_port(storage: "HermesTokenStorage | None") -> int | None:- """Loopback callback port from the cached client registration. Providers bind a- dynamically-registered ``client_id`` to the exact redirect URI registered with it; a new- random port under the stored ``client_id`` gets ``redirect_uri does not match any- registered URIs``."""- for _uri, parsed in _cached_redirect_uris(storage):- is_loopback_callback = parsed.scheme == "http" and parsed.path == "/callback" and parsed.hostname in {"127.0.0.1", "localhost"}- if is_loopback_callback and parsed.port is not None:- return int(parsed.port)- return None---def _cached_redirect_uri(storage: "HermesTokenStorage | None") -> str | None:- """A cached non-loopback (https) redirect URI, if one was registered."""- for uri, parsed in _cached_redirect_uris(storage):- if parsed.scheme == "https" and parsed.netloc:- return uri- return None+ parsed = urlparse(str(raw))+ if uri is None and parsed.scheme == "https" and parsed.netloc:+ uri = str(raw)+ is_loopback_callback = parsed.scheme == "http" and parsed.path == "/callback" and parsed.hostname in {"127.0.0.1", "localhost"}+ if port is None and is_loopback_callback and parsed.port is not None:+ port = int(parsed.port)+ return uri, port# -- Interactivity -----------------------------------------------------------@@ -677,17 +643,6 @@ def _start_callback_server(port: int, handler_cls: type) -> HTTPServer:return server-async def _poll_callback_result(server: HTTPServer, result: dict, timeout: float) -> None:- """Poll *result* until filled or *timeout* elapses; always closes the listener."""- elapsed = 0.0- try:- while elapsed < timeout and not _result_taken(result):- await asyncio.sleep(0.5)- elapsed += 0.5- finally:- server.server_close()--def _callback_outcome(result: dict, cimd_url: str | None):"""Turn a filled/empty result dict into the SDK's callback value, or raise."""if result["error"] == _USER_SKIPPED_SENTINEL:@@ -739,7 +694,13 @@ def _make_callback_waiter(port: int, cimd_url: str | None = None, timeout: floatfile=sys.stderr, flush=True,)threading.Thread(target=_paste_callback_reader, args=(result,), daemon=True).start()- await _poll_callback_result(server, result, timeout)+ elapsed = 0.0+ try:+ while elapsed < timeout and not _result_taken(result):+ await asyncio.sleep(0.5)+ elapsed += 0.5+ finally:+ server.server_close()return _callback_outcome(result, cimd_url)return _wait@@ -752,10 +713,11 @@ HermesOAuthClientProvider: Any = Nonedef _get_hermes_oauth_provider_class() -> type | None:"""Build (once) and cache ``HermesOAuthClientProvider``; None without the SDK."""global HermesOAuthClientProvider- if HermesOAuthClientProvider is None and _ensure_sdk_loaded():+ base = _sdk_class("OAuthClientProvider")+ if HermesOAuthClientProvider is None and base is not None:from tools.mcp_oauth_provider import HermesProviderMixin- HermesOAuthClientProvider = type("HermesOAuthClientProvider", (HermesProviderMixin, OAuthClientProvider), {+ HermesOAuthClientProvider = type("HermesOAuthClientProvider", (HermesProviderMixin, base), {"__doc__": "SDK provider plus Hermes' token-endpoint fixes (see ``HermesProviderMixin``).","__module__": __name__,"_hermes_logger": logger,@@ -906,16 +868,16 @@ def _configure_callback_port(cfg: dict, storage: "HermesTokenStorage | None" = Ncfg["_resolved_port"] = 0cfg["redirect_uri"] = cfg.get("redirect_uri") or dashboard_flow.redirect_urireturn 0- cached_redirect_uri = None if cfg.get("redirect_uri") else _cached_redirect_uri(storage)- if cached_redirect_uri:- cfg["redirect_uri"] = cached_redirect_uri+ cached_uri, cached_port = _cached_redirect(storage)+ if cached_uri and not cfg.get("redirect_uri"):+ cfg["redirect_uri"] = cached_uricfg["_resolved_port"] = 0return 0cimd = _maybe_use_cimd(cfg, storage)if cimd is not None:cfg["_cimd_url"], port = cimdelse:- port = int(cfg.get("redirect_port", 0)) or _cached_redirect_port(storage) or _reserve_callback_port()+ port = int(cfg.get("redirect_port", 0)) or cached_port or _reserve_callback_port()# A cached port may be a pinned CIMD port left by an earlier CIMD login; claim it so a# sibling's _pick_cimd_port doesn't reuse it.if port in _CIMD_PORTS and port not in _assigned_cimd_ports:@@ -1094,7 +1056,7 @@ def build_oauth_auth(server_name: str, server_url: str, oauth_config: dict | Nonnew code should use :func:`tools.mcp_oauth_manager.get_manager` so OAuth state is sharedacross config-time, runtime, and reconnect paths. Returns None if the MCP SDK lacks OAuthsupport."""- if not _OAUTH_AVAILABLE or (OAuthClientProvider is None and not _ensure_sdk_loaded()):+ if not _OAUTH_AVAILABLE or _sdk_class("OAuthClientProvider") is None:logger.warning("MCP OAuth requested for '%s' but SDK auth types are not available. Install with: pip install 'mcp>=1.26.0'",server_name,