From 37ea7fe36a928e920a340cc4cf5148c5164e5ffc Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 22:27:21 -0700 Subject: [PATCH] refactor(tools): mcp_oauth storage path partialmethods; lazy_deps contextlib.suppress ladders; gateway scheme guard --- tools/lazy_deps.py | 28 ++++++++-------------------- tools/managed_tool_gateway.py | 10 ++++------ tools/mcp_oauth.py | 23 +++++++---------------- 3 files changed, 19 insertions(+), 42 deletions(-) diff --git a/tools/lazy_deps.py b/tools/lazy_deps.py index 7f0f5ffb31..d73a88b141 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 (``_spe from __future__ import annotations +import contextlib import logging import os import 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: - pass target.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 importlib importlib.invalidate_caches() import importlib.metadata as _md if hasattr(_md, "_cache_clear"): _md._cache_clear() # type: ignore[attr-defined] - except Exception: - pass def 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`` blocks in BOTH modes; (2) the sealed venv (``HERMES_DISABLE_LAZY_INSTALLS=1``) blocks only without a durable 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_config cfg = load_config() - except Exception: - cfg = None if cfg is not None and not bool((cfg.get("security") or {}).get("allow_lazy_installs", True)): return False if os.environ.get("HERMES_DISABLE_LAZY_INSTALLS") == "1": @@ -562,10 +555,8 @@ def _venv_pip_install(specs: tuple[str, ...], *, timeout: int = 300) -> _Install return _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.py index fa48aa9d24..ff76ba3391 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 scheme def build_vendor_gateway_url(vendor: str) -> str: diff --git a/tools/mcp_oauth.py b/tools/mcp_oauth.py index b8466cc93d..9b17bb1104 100644 --- a/tools/mcp_oauth.py +++ b/tools/mcp_oauth.py @@ -24,6 +24,7 @@ import sys import threading import time import webbrowser +from functools import partialmethod from http.server import BaseHTTPRequestHandler, HTTPServer from pathlib import Path from 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 | Non Legacy API — new code uses :func:`tools.mcp_oauth_manager.get_manager` so state is shared across 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 None from tools.mcp_oauth_provider import build_provider_kwargs, prepare_oauth_config