The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools): mcp_oauth storage path partialmethods; lazy_deps contextlib.suppress ladders; gateway scheme guard
Teknium37ea7fe36a92
diff --git a/tools/lazy_deps.py b/tools/lazy_deps.pyindex 7f0f5ffb316..d73a88b1418 100644--- a/tools/lazy_deps.py+++ b/tools/lazy_deps.py@@ -11,6 +11,7 @@ package can only add modules, never shadow core; PyPI-by-name specs only (``_spefrom __future__ import annotations+import contextlibimport loggingimport osimport re@@ -260,18 +261,13 @@ def _ensure_target_ready(target: Path) -> Optional[str]:except OSError: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.",- target, have, want,- )+ logger.info("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():if child.is_dir() and not child.is_symlink():shutil.rmtree(child, ignore_errors=True)else:- try:+ with contextlib.suppress(OSError):child.unlink()- except OSError:- passtarget.mkdir(parents=True, exist_ok=True)stamp.write_text(want, encoding="utf-8")except OSError as e:@@ -295,14 +291,12 @@ def _activate_target_on_syspath(target: Path) -> None:def _invalidate_import_caches() -> None:"""Make just-installed dists visible to importers and importlib.metadata in this process."""- try:+ with contextlib.suppress(Exception):import importlibimportlib.invalidate_caches()import importlib.metadata as _mdif hasattr(_md, "_cache_clear"):_md._cache_clear() # type: ignore[attr-defined]- except Exception:- passdef activate_durable_lazy_target() -> None:@@ -322,11 +316,10 @@ def _allow_lazy_installs() -> bool:"""Whether lazy installs are permitted: (1) ``security.allow_lazy_installs: false`` blocksin BOTH modes; (2) the sealed venv (``HERMES_DISABLE_LAZY_INSTALLS=1``) blocks only without adurable target to redirect into. Unreadable config fails OPEN — blocking is an explicit opt-in."""- try:+ cfg = None+ with contextlib.suppress(Exception):from hermes_cli.config import load_configcfg = load_config()- except Exception:- cfg = Noneif 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":@@ -562,10 +555,8 @@ def _venv_pip_install(specs: tuple[str, ...], *, timeout: int = 300) -> _Installreturn _InstallResult(False, "", f"pip install failed: {e}")finally:if constraints is not None:- try:+ with contextlib.suppress(OSError):constraints.unlink()- except OSError:- pass# ---- Public API ---------------------------------------------------------------@@ -635,10 +626,7 @@ def ensure(feature: str, *, prompt: bool = True) -> None:if prompt and not _prompt_toolkit_active() and sys.stdin.isatty() and sys.stdout.isatty():spec_list = ", ".join(missing)try:- answer = input(- f"\nFeature {feature!r} requires: {spec_list}\n"- f"Install into the active venv now? [Y/n] "- ).strip().lower()+ answer = input(f"\nFeature {feature!r} requires: {spec_list}\nInstall into the active venv now? [Y/n] ").strip().lower()except (EOFError, KeyboardInterrupt):answer = "n"if answer and answer not in {"y", "yes"}:diff --git a/tools/managed_tool_gateway.py b/tools/managed_tool_gateway.pyindex fa48aa9d243..ff76ba33912 100644--- a/tools/managed_tool_gateway.py+++ b/tools/managed_tool_gateway.py@@ -118,12 +118,10 @@ def read_nous_access_token() -> Optional[str]:def get_tool_gateway_scheme() -> str:"""Return configured shared gateway URL scheme."""- scheme = os.getenv("TOOL_GATEWAY_SCHEME", "").strip().lower()- if not scheme:- return _DEFAULT_TOOL_GATEWAY_SCHEME- if scheme in {"http", "https"}:- return scheme- raise ValueError("TOOL_GATEWAY_SCHEME must be 'http' or 'https'")+ scheme = os.getenv("TOOL_GATEWAY_SCHEME", "").strip().lower() or _DEFAULT_TOOL_GATEWAY_SCHEME+ if scheme not in {"http", "https"}:+ raise ValueError("TOOL_GATEWAY_SCHEME must be 'http' or 'https'")+ return schemedef build_vendor_gateway_url(vendor: str) -> str:diff --git a/tools/mcp_oauth.py b/tools/mcp_oauth.pyindex b8466cc93dd..9b17bb11044 100644--- a/tools/mcp_oauth.py+++ b/tools/mcp_oauth.py@@ -24,6 +24,7 @@ import sysimport threadingimport timeimport webbrowser+from functools import partialmethodfrom http.server import BaseHTTPRequestHandler, HTTPServerfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any@@ -261,17 +262,10 @@ class HermesTokenStorage:def _path(self, suffix: str) -> Path:return _get_token_dir(self._hermes_home) / f"{self._server_name}{suffix}"- def _tokens_path(self) -> Path:- return self._path(".json")-- def _client_info_path(self) -> Path:- return self._path(".client.json")-- def _meta_path(self) -> Path:- return self._path(".meta.json")-- def _cimd_rejected_path(self) -> Path:- return self._path(".cimd-off")+ _tokens_path = partialmethod(_path, ".json")+ _client_info_path = partialmethod(_path, ".client.json")+ _meta_path = partialmethod(_path, ".meta.json")+ _cimd_rejected_path = partialmethod(_path, ".cimd-off")def _state_paths(self) -> tuple[Path, Path, Path]:return self._tokens_path(), self._client_info_path(), self._meta_path()@@ -669,8 +663,7 @@ def _get_hermes_oauth_provider_class() -> type | None:HermesOAuthClientProvider = type("HermesOAuthClientProvider", (HermesProviderMixin, base), {"__doc__": "SDK provider plus Hermes' token-endpoint fixes (see ``HermesProviderMixin``).",- "__module__": __name__,- "_hermes_logger": logger})+ "__module__": __name__, "_hermes_logger": logger})return HermesOAuthClientProvider@@ -960,9 +953,7 @@ def build_oauth_auth(server_name: str, server_url: str, oauth_config: dict | NonLegacy API — new code uses :func:`tools.mcp_oauth_manager.get_manager` so state is sharedacross config-time, runtime and reconnect paths."""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)+ logger.warning("MCP OAuth requested for '%s' but SDK auth types are not available. Install with: pip install 'mcp>=1.26.0'", server_name)return Nonefrom tools.mcp_oauth_provider import build_provider_kwargs, prepare_oauth_config