Skip to content

The agent that grows with you

refactor(tools): MCP handlers/errors/transport/config/health/registration/oauth-manager compaction — shared _dispatch, folded utility factory, auth-type cache tuple

Teknium760ac0b609ba
diff --git a/tools/mcp_oauth_manager.py b/tools/mcp_oauth_manager.py
index c0141159a85..2ca0fe2cd19 100644
--- a/tools/mcp_oauth_manager.py
+++ b/tools/mcp_oauth_manager.py
@@ -1,12 +1,10 @@
-"""Central manager for per-server MCP OAuth state (one instance per process).
-
-Holds per-server providers and coordinates cross-process token reload (mtime-based disk watch,
-so tokens refreshed by cron/another CLI are picked up without a restart), 401 deduplication
-(N concurrent 401s with the same access_token trigger one recovery) and reconnect signalling
-(``MCPServerTask`` drives the reconnect; the manager decides when). The ONLY place that
-instantiates the SDK's ``OAuthClientProvider`` for runtime use. We rely on the SDK's lazy
-refresh: one ``stat()`` per tool call is cheaper than an await + refresh round-trip.
-"""
+"""Central manager for per-server MCP OAuth state (one instance per process): per-server
+providers, cross-process token reload (mtime-based disk watch so tokens refreshed by cron/another
+CLI are picked up without a restart), 401 deduplication (N concurrent 401s with the same
+access_token trigger one recovery) and reconnect signalling (``MCPServerTask`` drives the
+reconnect; the manager decides when). The ONLY place that instantiates the SDK's
+``OAuthClientProvider`` for runtime use; refresh stays lazy in the SDK — one ``stat()`` per tool
+call is cheaper than an await + refresh round-trip."""
from __future__ import annotations
@@ -67,20 +65,18 @@ class HermesMCPOAuthProvider(HermesProviderMixin, *_SDK_BASES):
def _hermes_storage(self):
"""The context storage when it is a ``HermesTokenStorage``, else None."""
from tools.mcp_oauth import HermesTokenStorage
- storage = self.context.storage
- return storage if isinstance(storage, HermesTokenStorage) else None
+ return self.context.storage if isinstance(self.context.storage, HermesTokenStorage) else None
def _log_nonfatal(self, what: str, exc: BaseException) -> None:
logger.debug("MCP OAuth '%s': %s failed (non-fatal): %s", self._hermes_server_name, what, exc)
async def _initialize(self) -> None:
"""Load stored state, seed ``token_expiry_time``, restore/prefetch metadata. The SDK's
- ``_initialize`` never calls ``update_token_expiry``, so ``is_token_valid()`` is True for
- any loaded token regardless of age and a restarted process ships stale Bearer tokens;
- seeding the expiry (``HermesTokenStorage`` persists absolute ``expires_at``) makes the SDK
- refresh first. Metadata is restored from disk, else discovered pre-flight when we hold
- tokens but no metadata: otherwise ``_refresh_token`` guesses ``{server_url}/token``
- (wrong for split-origin providers), 404s, and we fall through to browser reauth."""
+ ``_initialize`` never calls ``update_token_expiry``, so a restarted process would ship stale
+ Bearer tokens as "valid"; seeding the expiry (``HermesTokenStorage`` persists absolute
+ ``expires_at``) makes the SDK refresh first. Metadata is restored from disk, else discovered
+ pre-flight when we hold tokens but no metadata: otherwise ``_refresh_token`` guesses
+ ``{server_url}/token`` (wrong for split-origin providers), 404s, and we fall to browser reauth."""
await super()._initialize()
tokens = self.context.current_tokens
if tokens is not None and tokens.expires_in is not None:
@@ -160,8 +156,7 @@ class HermesMCPOAuthProvider(HermesProviderMixin, *_SDK_BASES):
async def _is_invalid_client_at_token_endpoint(self, response: Any) -> bool:
"""True when *response* is the token endpoint (same scheme/host/path, query ignored)
rejecting our client_id with ``invalid_client`` — whole word, so RFC 7591's
- ``invalid_client_metadata`` does not trip it. The body is read only after the endpoint
- matches."""
+ ``invalid_client_metadata`` does not trip it. The body is read only after the endpoint matches."""
from urllib.parse import urlsplit
token_endpoint = getattr(getattr(self.context, "oauth_metadata", None), "token_endpoint", None)
req = getattr(response, "request", None)
@@ -171,11 +166,9 @@ class HermesMCPOAuthProvider(HermesProviderMixin, *_SDK_BASES):
pa, pb = urlsplit(str(req.url)), urlsplit(str(token_endpoint))
except ValueError: # pragma: no cover — malformed URL
return False
- if not (pa.scheme == pb.scheme and pa.netloc.lower() == pb.netloc.lower()
- and pa.path.rstrip("/") == pb.path.rstrip("/")):
+ if (pa.scheme, pa.netloc.lower(), pa.path.rstrip("/")) != (pb.scheme, pb.netloc.lower(), pb.path.rstrip("/")):
return False
- body = await response.aread()
- return re.search(rb"\binvalid_client\b", body.lower()) is not None
+ return re.search(rb"\binvalid_client\b", (await response.aread()).lower()) is not None
async def _maybe_flag_poisoned_client(self, response: Any) -> None:
"""An ``invalid_client`` rejection of our ``client_id`` at the token endpoint proves the
@@ -185,15 +178,13 @@ class HermesMCPOAuthProvider(HermesProviderMixin, *_SDK_BASES):
in the body; pre-registered clients are never poisoned; any failure is swallowed. The
browser-side "Redirect URI Mismatch" case has no HTTP signal (``hermes mcp reauth``)."""
try:
- if self._hermes_preregistered or getattr(response, "status_code", None) not in (400, 401):
- return
- if not await self._is_invalid_client_at_token_endpoint(response):
+ if (self._hermes_preregistered or getattr(response, "status_code", None) not in (400, 401)
+ or not await self._is_invalid_client_at_token_endpoint(response)):
return
storage = self._hermes_storage()
- # If the rejected client_id was our CIMD URL, re-presenting it would loop (the
- # server already fetched and refused it). Drop the URL so the retry takes DCR, and
- # mark it on disk so the next process doesn't walk back into the same refusal
- # (`hermes mcp login` clears the marker).
+ # A rejected CIMD URL would loop if re-presented (the server already fetched and refused
+ # it): drop it so the retry takes DCR, and mark it on disk so the next process doesn't walk
+ # back into the same refusal (`hermes mcp login` clears the marker).
cimd_url = getattr(self.context, "client_metadata_url", None)
if cimd_url and getattr(self.context.client_info, "client_id", None) == cimd_url:
logger.warning("MCP OAuth '%s': authorization server rejected our Client ID Metadata Document (%s) "
@@ -211,18 +202,15 @@ class HermesMCPOAuthProvider(HermesProviderMixin, *_SDK_BASES):
self._log_nonfatal("invalid_client detection", exc)
async def async_auth_flow(self, request): # type: ignore[override]
- # Pre-flow hook: reload from disk if it changed (non-fatal on error).
- try:
+ try: # pre-flow hook: reload from disk if it changed (non-fatal on error)
await get_manager().invalidate_if_disk_changed(self._hermes_server_name, hermes_home=self._hermes_home)
except Exception as exc: # pragma: no cover — defensive
self._log_nonfatal("pre-flow disk-watch", exc)
-
# Bridge the bidirectional generator by hand: a naive ``async for item in inner: yield
# item`` DISCARDS the responses httpx sends back via ``asend``, and the SDK crashes on None.
inner = super().async_auth_flow(request)
- resource_lock_released = False
+ resource_lock_released = retry_after_concurrent_auth = False
sent_access_token = None
- retry_after_concurrent_auth = False
try:
outgoing = await inner.__anext__()
while True:
@@ -252,8 +240,8 @@ class HermesMCPOAuthProvider(HermesProviderMixin, *_SDK_BASES):
self._persist_oauth_metadata_if_changed() # metadata discovered lazily in the 401 branch
finally:
if resource_lock_released:
- # Balance the SDK's surrounding ``async with`` even when HTTPX cancels/closes
- # the flow mid-request. Shield only this local bookkeeping.
+ # Balance the SDK's surrounding ``async with`` even when HTTPX cancels/closes the
+ # flow mid-request; shield only this local bookkeeping.
import anyio
with anyio.CancelScope(shield=True):
await self.context.lock.acquire()
@@ -274,8 +262,7 @@ class MCPOAuthManager:
def __init__(self) -> None:
self._entries: dict[tuple[str, str], _ProviderEntry] = {}
self._entries_lock = threading.Lock()
- # Strong refs to in-flight 401 tasks so the loop's weak bookkeeping cannot GC them
- # mid-run and leave `await pending` hanging forever.
+ # Strong refs to in-flight 401 tasks so the loop's weak bookkeeping cannot GC them mid-run.
self._inflight_tasks: set[asyncio.Task] = set()
def get_or_build_provider(self, server_name: str, server_url: str, oauth_config: Optional[dict]) -> Optional[Any]:
@@ -306,8 +293,7 @@ class MCPOAuthManager:
if _HERMES_PROVIDER_CLS is None:
logger.warning("MCP OAuth '%s': SDK auth module unavailable", server_name)
return None
- # Local imports avoid circular deps at module import time.
- from tools.mcp_dashboard_oauth import get_dashboard_oauth_flow
+ from tools.mcp_dashboard_oauth import get_dashboard_oauth_flow # lazy: circular at import time
from tools.mcp_oauth import _OAUTH_AVAILABLE, OAuthNonInteractiveError, _is_interactive
from tools.mcp_oauth_provider import build_provider_kwargs, prepare_oauth_config
if not _OAUTH_AVAILABLE:
@@ -350,16 +336,14 @@ class MCPOAuthManager:
if entry is None or entry.provider is None:
return False
async with entry.lock:
- tokens_path = _get_token_dir(hermes_home) / f"{_safe_filename(server_name)}.json"
try:
- mtime_ns = tokens_path.stat().st_mtime_ns
- except (FileNotFoundError, OSError):
+ mtime_ns = (_get_token_dir(hermes_home) / f"{_safe_filename(server_name)}.json").stat().st_mtime_ns
+ except OSError:
return False
if mtime_ns == entry.last_mtime_ns:
return False
old, entry.last_mtime_ns = entry.last_mtime_ns, mtime_ns
- # `_initialized` is private SDK API but stable across the versions we pin
- # (>=1.26.0); resetting it forces a reload.
+ # `_initialized` is private SDK API but stable across the pinned versions (>=1.26.0).
if hasattr(entry.provider, "_initialized"):
entry.provider._initialized = False # noqa: SLF001
logger.info("MCP OAuth '%s': tokens file changed (mtime %d -> %d), forcing reload", server_name, old, mtime_ns)
@@ -367,22 +351,22 @@ class MCPOAuthManager:
async def _recover_401(self, server_name: str, entry: _ProviderEntry, key: str, pending: asyncio.Future) -> None:
"""Single recovery attempt behind *pending*; always clears the dedup slot."""
+ can_refresh = False
try:
# Disk changed (external refresh)? Else: if the SDK can refresh in place, let the
# caller retry (the httpx.Auth flow refreshes on the next request).
- can_refresh = True
- if not await self.invalidate_if_disk_changed(server_name):
+ if await self.invalidate_if_disk_changed(server_name):
+ can_refresh = True
+ else:
try:
can_refresh = bool(entry.provider.context.can_refresh_token())
except Exception: # no context / not callable / probe failed
can_refresh = False
- if not pending.done():
- pending.set_result(can_refresh)
except Exception as exc: # pragma: no cover — defensive
logger.warning("MCP OAuth '%s': 401 handler failed: %s", server_name, exc)
- if not pending.done():
- pending.set_result(False)
finally:
+ if not pending.done():
+ pending.set_result(can_refresh)
entry.pending_401.pop(key, None)
async def handle_401(self, server_name: str, failed_access_token: Optional[str] = None) -> bool:
@@ -394,11 +378,10 @@ class MCPOAuthManager:
if entry is None or entry.provider is None:
return False
key = failed_access_token or "<unknown>"
- loop = asyncio.get_running_loop()
async with entry.lock:
pending = entry.pending_401.get(key)
if pending is None:
- pending = entry.pending_401[key] = loop.create_future()
+ pending = entry.pending_401[key] = asyncio.get_running_loop().create_future()
task = asyncio.create_task(self._recover_401(server_name, entry, key, pending))
self._inflight_tasks.add(task)
task.add_done_callback(self._inflight_tasks.discard)
diff --git a/tools/mcp_tool_config.py b/tools/mcp_tool_config.py
index 0e39bf1a50f..34ae1a716bc 100644
--- a/tools/mcp_tool_config.py
+++ b/tools/mcp_tool_config.py
@@ -19,27 +19,25 @@ _mcp_stderr_log_lock = threading.Lock()
def _get_mcp_stderr_log() -> Any:
- """Shared append-mode handle for MCP subprocess stderr, opened once per process. Must
- expose a real fd (``fileno()``) because asyncio wires the child's stderr directly to it.
- Falls back to ``/dev/null``, then real stderr."""
+ """Shared append-mode handle for MCP subprocess stderr, opened once per process. Must expose a
+ real fd (asyncio wires the child's stderr to it); falls back to ``/dev/null``, then real stderr."""
global _mcp_stderr_log_fh
with _mcp_stderr_log_lock:
- if _mcp_stderr_log_fh is not None:
- return _mcp_stderr_log_fh
- try:
- from hermes_constants import get_hermes_home
- log_dir = get_hermes_home() / "logs"
- log_dir.mkdir(parents=True, exist_ok=True)
- # Line-buffered so output lands promptly; errors="replace" tolerates garbled binary.
- fh = open(log_dir / "mcp-stderr.log", "a", encoding="utf-8", errors="replace", buffering=1)
- fh.fileno() # confirm a real fd before committing
- _mcp_stderr_log_fh = fh
- except Exception as exc: # pragma: no cover — best-effort fallback
- logger.debug("Failed to open MCP stderr log, using devnull: %s", exc)
+ if _mcp_stderr_log_fh is None:
try:
- _mcp_stderr_log_fh = open(os.devnull, "w", encoding="utf-8")
- except Exception:
- _mcp_stderr_log_fh = sys.stderr
+ from hermes_constants import get_hermes_home
+ log_dir = get_hermes_home() / "logs"
+ log_dir.mkdir(parents=True, exist_ok=True)
+ # Line-buffered so output lands promptly; errors="replace" tolerates garbled binary.
+ fh = open(log_dir / "mcp-stderr.log", "a", encoding="utf-8", errors="replace", buffering=1)
+ fh.fileno() # confirm a real fd before committing
+ _mcp_stderr_log_fh = fh
+ except Exception as exc: # pragma: no cover — best-effort fallback
+ logger.debug("Failed to open MCP stderr log, using devnull: %s", exc)
+ try:
+ _mcp_stderr_log_fh = open(os.devnull, "w", encoding="utf-8")
+ except Exception:
+ _mcp_stderr_log_fh = sys.stderr
return _mcp_stderr_log_fh
@@ -48,8 +46,7 @@ def _write_stderr_log_header(server_name: str) -> None:
(per-line prefixes would need a pipe + reader thread)."""
fh = _core._get_mcp_stderr_log()
try:
- ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
- fh.write(f"\n===== [{ts}] starting MCP server '{server_name}' =====\n")
+ fh.write(f"\n===== [{datetime.now():%Y-%m-%d %H:%M:%S}] starting MCP server '{server_name}' =====\n")
fh.flush()
except Exception:
pass
@@ -58,16 +55,15 @@ def _write_stderr_log_header(server_name: str) -> None:
# Env vars safe to pass to stdio subprocesses (no secrets).
_SAFE_ENV_KEYS = frozenset({"PATH", "HOME", "USER", "LANG", "LC_ALL", "TERM", "SHELL", "TMPDIR"})
-# Windows process/location vars needed by launcher-style tools (e.g. Docker
-# Desktop's MCP plugin discovery); none carry secrets.
+# Windows process/location vars needed by launcher-style tools (e.g. Docker Desktop's MCP plugin
+# discovery); none carry secrets.
_SAFE_ENV_KEYS_CASE_INSENSITIVE = frozenset({
"ALLUSERSPROFILE", "APPDATA", "COMMONPROGRAMFILES", "COMMONPROGRAMFILES(X86)",
"COMMONPROGRAMW6432", "COMPUTERNAME", "COMSPEC", "HOMEDRIVE", "HOMEPATH",
"LOCALAPPDATA", "NUMBER_OF_PROCESSORS", "OS", "PATHEXT", "PROCESSOR_ARCHITECTURE",
"PROGRAMDATA", "PROGRAMFILES", "PROGRAMFILES(X86)", "PROGRAMW6432", "PUBLIC",
"SYSTEMDRIVE", "SYSTEMROOT", "TEMP", "TMP", "USERDOMAIN", "USERNAME",
- "USERPROFILE", "WINDIR",
-})
+ "USERPROFILE", "WINDIR"})
# ${VAR_NAME} interpolation; any non-} chars allowed so MY-VAR / my.var work.
_ENV_VAR_PATTERN = re.compile(r"\$\{([^}]+)\}")
@@ -79,11 +75,9 @@ def _workspace_folder() -> str:
try:
from tools.file_tools import _authoritative_workspace_root
root = _authoritative_workspace_root()
- if root:
- return root
except Exception:
- pass
- return os.getcwd()
+ root = None
+ return root or os.getcwd()
def _workspace_basename() -> str:
@@ -93,12 +87,8 @@ def _workspace_basename() -> str:
# Cursor's case-sensitive context vars -> resolver.
_CONTEXT_VAR_RESOLVERS = {
- "userHome": lambda: os.path.expanduser("~"),
- "workspaceFolder": lambda: _core._workspace_folder(),
- "workspaceFolderBasename": _workspace_basename,
- "pathSeparator": lambda: os.sep,
- "/": lambda: os.sep,
-}
+ "userHome": lambda: os.path.expanduser("~"), "workspaceFolder": lambda: _core._workspace_folder(),
+ "workspaceFolderBasename": _workspace_basename, "pathSeparator": lambda: os.sep, "/": lambda: os.sep}
def _build_safe_env(user_env: Optional[dict]) -> dict:
@@ -140,16 +130,11 @@ def _node_fallback(command: str) -> str:
failed; *command* unchanged when none is executable."""
home = os.path.expanduser("~")
hermes_home = os.path.expanduser(os.getenv("HERMES_HOME", os.path.join(home, ".hermes")))
- candidates = [
- os.path.join(hermes_home, "node", "bin", command),
- os.path.join(home, ".local", "bin", command),
- # Canonical Node location (from-source Linux, Hermes Docker image, Intel Homebrew). Needed
- # when a hand-authored env.PATH omits it: npx's shebang re-execs /usr/bin/env node.
- os.path.join(os.sep, "usr", "local", "bin", command)]
- for candidate in candidates:
- if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
- return candidate
- return command
+ # /usr/local/bin: canonical Node location (from-source Linux, Hermes Docker image, Intel Homebrew),
+ # needed when a hand-authored env.PATH omits it — npx's shebang re-execs /usr/bin/env node.
+ candidates = (os.path.join(hermes_home, "node", "bin", command), os.path.join(home, ".local", "bin", command),
+ os.path.join(os.sep, "usr", "local", "bin", command))
+ return next((c for c in candidates if os.path.isfile(c) and os.access(c, os.X_OK)), command)
def _resolve_stdio_command(command: str, env: dict) -> tuple[str, dict]:
@@ -157,7 +142,6 @@ def _resolve_stdio_command(command: str, env: dict) -> tuple[str, dict]:
``npx``/``npm``/``node`` work under a filtered PATH."""
resolved_command = os.path.expanduser(str(command).strip())
resolved_env = dict(env or {})
-
if os.sep not in resolved_command:
path_arg = resolved_env.get("PATH")
which_hit = shutil.which(resolved_command, path=path_arg)
@@ -178,9 +162,9 @@ def _wrap_command_with_watchdog(command: str, args: list) -> tuple[str, list]:
"""Wrap a stdio command in the parent-death watchdog (POSIX only — it relies on process
groups, same scope as the killpg-based orphan cleanup). Unchanged on non-POSIX or if the
PID cannot be read — watchdog bookkeeping must never block a connection."""
- if os.name != "posix":
- return command, args
try:
+ if os.name != "posix":
+ return command, args
my_pid = os.getpid()
except Exception:
return command, args
@@ -205,15 +189,15 @@ def _interpolate_env_vars(value):
return value
-# (server_name, dotted key path) pairs already warned about; config loads
-# happen on every discovery pass, so warn once per process.
+# (server_name, dotted key path) pairs already warned about: config loads happen on every discovery
+# pass, so warn once per process.
_whitespace_warned: Set[Tuple[str, str]] = set()
def _warn_hidden_whitespace(server_name: str, config: dict) -> List[str]:
"""Warn once per (server, key path) about string values with leading/trailing whitespace (a
- pasted newline causes opaque auth failures, invisible in config.yaml). Advisory only: values
- are never mutated (could be intentional) nor logged (often secrets). Returns flagged paths."""
+ pasted newline causes opaque auth failures). Advisory only: values are never mutated (could be
+ intentional) nor logged (often secrets). Returns flagged paths."""
flagged: List[str] = []
def _walk(value: Any, path: str) -> None:
@@ -228,15 +212,12 @@ def _warn_hidden_whitespace(server_name: str, config: dict) -> List[str]:
_walk(config, "")
for key_path in flagged:
- if (server_name, key_path) in _whitespace_warned:
- continue
- _whitespace_warned.add((server_name, key_path))
- logger.warning(
- "MCP server '%s': config value '%s' has hidden leading or "
- "trailing whitespace — this often causes authentication or "
- "connection failures. Check for stray spaces/newlines in "
- "config.yaml (or the referenced env var).",
- server_name, key_path)
+ if (server_name, key_path) not in _whitespace_warned:
+ _whitespace_warned.add((server_name, key_path))
+ logger.warning(
+ "MCP server '%s': config value '%s' has hidden leading or trailing whitespace — this often "
+ "causes authentication or connection failures. Check for stray spaces/newlines in config.yaml "
+ "(or the referenced env var).", server_name, key_path)
return flagged
@@ -246,14 +227,13 @@ def _filter_suspicious_mcp_servers(servers: Dict[str, dict]) -> Dict[str, dict]:
from hermes_cli.mcp_security import validate_mcp_server_entry
except Exception:
return servers
-
safe_servers = {}
for name, cfg in servers.items():
issues = validate_mcp_server_entry(name, cfg) if isinstance(cfg, dict) else None
if issues:
logger.warning("Skipping suspicious MCP server '%s': %s", name, "; ".join(issues))
- continue
- safe_servers[name] = cfg
+ else:
+ safe_servers[name] = cfg
return safe_servers
@@ -267,8 +247,8 @@ def _portable_mcp_servers(safe_servers: Dict[str, dict]) -> None:
for name, cfg in _core._filter_suspicious_mcp_servers(portable).items():
if name in safe_servers:
logger.warning("Portable MCP server '%s' conflicts with native config; skipping", name)
- continue
- safe_servers[name] = dict(cfg)
+ else:
+ safe_servers[name] = dict(cfg)
except Exception:
logger.debug("Failed to load portable MCP servers", exc_info=True)
diff --git a/tools/mcp_tool_errors.py b/tools/mcp_tool_errors.py
index 91ff0395187..9ab2e50e891 100644
--- a/tools/mcp_tool_errors.py
+++ b/tools/mcp_tool_errors.py
@@ -19,24 +19,20 @@ logger = logging.getLogger("tools.mcp_tool")
_JSONRPC_UNSUPPORTED_PROTOCOL_VERSION = -32022
-def _jsonrpc_code(exc: BaseException):
- """Structural ``MCPError.error.code`` (None when absent)."""
- return getattr(getattr(exc, "error", None), "code", None)
-
-
-def _jsonrpc_matches(exc: BaseException, code, codes: tuple, markers: tuple) -> bool:
- """Structural *code* in *codes*, else any *marker* in ``str(exc).lower()``. Never ``isinstance``
- on SDK exception types: they arrive wrapped in ExceptionGroups and drift across generations."""
+def _jsonrpc_matches(exc: BaseException, codes: tuple, markers: tuple, code=None) -> bool:
+ """Structural ``MCPError.error.code`` (or *code*) in *codes*, else any *marker* in
+ ``str(exc).lower()``. Never ``isinstance`` on SDK exception types: they arrive wrapped in
+ ExceptionGroups and drift across generations."""
+ code = getattr(getattr(exc, "error", None), "code", None) or code
return code in codes or any(marker in str(exc).lower() for marker in markers)
def _handshake_rejected_as_modern(exc: BaseException) -> bool:
"""True when a failed ``initialize`` signals a stateless-only (2026-07-28) server."""
return _jsonrpc_matches(
- exc, _jsonrpc_code(exc) or getattr(exc, "code", None),
- (_JSONRPC_UNSUPPORTED_PROTOCOL_VERSION, _core._JSONRPC_METHOD_NOT_FOUND),
+ exc, (_JSONRPC_UNSUPPORTED_PROTOCOL_VERSION, _core._JSONRPC_METHOD_NOT_FOUND),
("unsupported protocol version", str(_JSONRPC_UNSUPPORTED_PROTOCOL_VERSION)),
- ) or _is_method_not_found_error(exc)
+ code=getattr(exc, "code", None)) or _is_method_not_found_error(exc)
def _is_method_not_found_error(exc: BaseException) -> bool:
@@ -44,7 +40,7 @@ def _is_method_not_found_error(exc: BaseException) -> bool:
substring fallback includes "Unknown method: <name>" — without it the ping→list_tools keepalive
fallback never latches and reconnect-loops."""
return _jsonrpc_matches(
- exc, _jsonrpc_code(exc), (_core._JSONRPC_METHOD_NOT_FOUND,),
+ exc, (_core._JSONRPC_METHOD_NOT_FOUND,),
(str(_core._JSONRPC_METHOD_NOT_FOUND), "method not found", "unknown method", "not found: ping"))
@@ -138,8 +134,7 @@ def _resolve_client_cert(server_name: str, config: dict):
cert_path = _expand(raw_cert, "client_cert")
return (cert_path, _expand(raw_key, "client_key")) if raw_key is not None else cert_path # combined PEM
if raw_key is not None:
- raise ValueError(f"{prefix}specify either client_cert as a list [cert, key] OR "
- f"client_cert + client_key, not both")
+ raise ValueError(f"{prefix}specify either client_cert as a list [cert, key] OR client_cert + client_key, not both")
if len(raw_cert) not in (2, 3):
raise ValueError(f"{prefix}client_cert list form must have 2 or 3 elements (got {len(raw_cert)})")
pair = (_expand(raw_cert[0], "client_cert[0]"), _expand(raw_cert[1], "client_cert[1]"))
@@ -248,11 +243,6 @@ def _format_connect_error(exc: BaseException) -> str:
return _sanitize_error(message)
-# Lazily-built caches so this module imports without the SDK OAuth module.
-_AUTH_ERROR_TYPES: tuple = ()
-_HTTP_STATUS_ERROR_TYPES: Optional[tuple] = None
-
-
def _optional_types(module: str, *names: str) -> list:
"""``[module.name, ...]`` or ``[]`` when the module/attribute is unavailable."""
try:
@@ -262,35 +252,33 @@ def _optional_types(module: str, *names: str) -> list:
return []
-def _http_status_error_types() -> tuple:
- """``HTTPStatusError`` from both httpx flavours: a 401 may come from the SDK's own stack
- (``httpx2`` on mcp >= 2.0) or Hermes' pinned ``httpx``; the classes are unrelated."""
- global _HTTP_STATUS_ERROR_TYPES
- if _HTTP_STATUS_ERROR_TYPES is None:
- sdk_mod = _core.sdk_httpx()
- _HTTP_STATUS_ERROR_TYPES = tuple(dict.fromkeys(
- ([sdk_mod.HTTPStatusError] if sdk_mod is not None else []) + _optional_types("httpx", "HTTPStatusError")))
- return _HTTP_STATUS_ERROR_TYPES
+# Lazily-built ``(auth_types, http_status_types)`` so this module imports without the SDK OAuth module.
+_AUTH_ERROR_TYPES: Optional[tuple] = None
def _get_auth_error_types() -> tuple:
- """Cached MCP OAuth failure types: SDK ``OAuthFlowError``/``OAuthTokenError`` (+ legacy
- ``UnauthorizedError``), our ``OAuthNonInteractiveError``, and both ``HTTPStatusError`` flavours
- (which still need the 401 check in :func:`_is_auth_error`)."""
+ """Cached ``(auth_types, http_status_types)``: SDK ``OAuthFlowError``/``OAuthTokenError`` (+ legacy
+ ``UnauthorizedError``), our ``OAuthNonInteractiveError``, and ``HTTPStatusError`` from both httpx
+ flavours — a 401 may come from the SDK's own stack (``httpx2`` on mcp >= 2.0) or Hermes' pinned
+ ``httpx``; the classes are unrelated and still need the 401 check in :func:`_is_auth_error`."""
global _AUTH_ERROR_TYPES
- if not _AUTH_ERROR_TYPES:
- _AUTH_ERROR_TYPES = (*_optional_types("mcp.client.auth", "OAuthFlowError", "OAuthTokenError"),
- *_optional_types("mcp.client.auth", "UnauthorizedError"), # older SDKs
- *_optional_types("tools.mcp_oauth", "OAuthNonInteractiveError"),
- *_http_status_error_types())
+ if not (_AUTH_ERROR_TYPES and _AUTH_ERROR_TYPES[0]): # retry while empty (SDK may import later)
+ sdk_mod = _core.sdk_httpx()
+ http_types = tuple(dict.fromkeys(
+ ([sdk_mod.HTTPStatusError] if sdk_mod is not None else []) + _optional_types("httpx", "HTTPStatusError")))
+ auth_types = (*_optional_types("mcp.client.auth", "OAuthFlowError", "OAuthTokenError"),
+ *_optional_types("mcp.client.auth", "UnauthorizedError"), # older SDKs
+ *_optional_types("tools.mcp_oauth", "OAuthNonInteractiveError"), *http_types)
+ _AUTH_ERROR_TYPES = (auth_types, http_types)
return _AUTH_ERROR_TYPES
def _is_auth_error(exc: BaseException) -> bool:
"""True if ``exc`` indicates an MCP OAuth failure; ``HTTPStatusError`` counts only with status 401."""
- if not isinstance(exc, _get_auth_error_types()):
+ auth_types, http_types = _get_auth_error_types()
+ if not isinstance(exc, auth_types):
return False
- return getattr(exc.response, "status_code", None) == 401 if isinstance(exc, _http_status_error_types()) else True
+ return getattr(exc.response, "status_code", None) == 401 if isinstance(exc, http_types) else True
# Lower-cased substrings meaning the transport session expired / was GC'd (OAuth token still valid).
diff --git a/tools/mcp_tool_handlers.py b/tools/mcp_tool_handlers.py
index 1a5695800c8..832d0c7066c 100644
--- a/tools/mcp_tool_handlers.py
+++ b/tools/mcp_tool_handlers.py
@@ -20,6 +20,16 @@ from tools.mcp_tool_content import (
from tools.mcp_tool_errors import _is_session_expired_error
logger = logging.getLogger("tools.mcp_tool")
+_MISSING = object()
+
+_NEEDS_REAUTH_MSG = ("MCP server '{s}' requires re-authentication. Run `hermes mcp login {s}` (or delete the tokens "
+ "file under ~/.hermes/mcp-tokens/ and restart). Do NOT retry this tool — ask the user to re-authenticate.")
+_STDIO_NO_RESPAWN_MSG = ("MCP server '{s}' stdio subprocess had exited (this is not a timeout — the call never reached the "
+ "server). A respawn was requested but no fresh session came back within {t:.0f}s. Wait a few "
+ "seconds before retrying; if it keeps failing the server is not starting and needs the user.")
+_STDIO_DIED_AGAIN_MSG = ("MCP server '{s}' respawned its stdio subprocess and it exited again immediately. The server is not "
+ "starting cleanly — do NOT retry this tool; ask the user to check the server's command and its "
+ "stderr log.")
# --------------------------------------------------------------- pre-call gates
@@ -30,8 +40,7 @@ def _trust_gate_check(server_name: str, tool_name: str) -> Optional[str]:
trust = _core._server_trust_levels.get(server_name, _core._TRUST_FULL)
if trust != _core._TRUST_UNTRUSTED or _core._tool_read_only_hints.get(server_name, {}).get(tool_name) is True:
return None
- # Lazy import: tools.approval routes the prompt to whichever surface owns the session.
- try:
+ try: # lazy: tools.approval routes the prompt to whichever surface owns the session
from tools.approval import request_elicitation_consent
answer = request_elicitation_consent(
f"MCP tool '{tool_name}' on UNTRUSTED server '{server_name}' wants to run. This tool is write-capable "
@@ -55,15 +64,12 @@ def _check_circuit_breaker(server_name: str) -> Optional[str]:
"""Open-breaker error, or None when calls may proceed. After the cooldown the breaker is
half-open: the next call probes; success resets, failure re-bumps and re-arms the cooldown."""
failures = _core._server_error_counts.get(server_name, 0)
- if failures < _core._CIRCUIT_BREAKER_THRESHOLD:
- return None
age = time.monotonic() - _core._server_breaker_opened_at.get(server_name, 0.0)
- if age >= _core._CIRCUIT_BREAKER_COOLDOWN_SEC:
+ if failures < _core._CIRCUIT_BREAKER_THRESHOLD or age >= _core._CIRCUIT_BREAKER_COOLDOWN_SEC:
return None
- remaining = max(1, int(_core._CIRCUIT_BREAKER_COOLDOWN_SEC - age))
return tool_error(f"MCP server '{server_name}' is unreachable after {failures} consecutive failures. "
- f"Auto-retry available in ~{remaining}s. Do NOT retry this tool yet — use alternative "
- f"approaches or ask the user to check the MCP server.")
+ f"Auto-retry available in ~{max(1, int(_core._CIRCUIT_BREAKER_COOLDOWN_SEC - age))}s. Do NOT retry "
+ f"this tool yet — use alternative approaches or ask the user to check the MCP server.")
def _acquire_call_server(server_name: str, tool_timeout: float):
@@ -72,13 +78,10 @@ def _acquire_call_server(server_name: str, tool_timeout: float):
server task to rebuild (probing a dead transport would re-arm the breaker forever)."""
not_connected = tool_error(f"MCP server '{server_name}' is not connected")
server = _core._get_connected_server_for_call(server_name)
- if not server:
- _core._bump_server_error(server_name)
- return None, not_connected
- if server.session or _core._wait_for_server_session_ready(server, timeout=min(5.0, float(tool_timeout or 5.0))):
+ if server and (server.session or _core._wait_for_server_session_ready(server, timeout=min(5.0, float(tool_timeout or 5.0)))):
return server, None
_core._bump_server_error(server_name)
- if _core._signal_reconnect(server):
+ if server and _core._signal_reconnect(server):
return None, tool_error(f"MCP server '{server_name}' transport is down; reconnect requested. Do NOT retry this "
f"tool immediately — give it a few seconds to come back.")
return None, not_connected
@@ -96,10 +99,7 @@ def _result_is_error(result) -> bool:
def _record_call_outcome(server_name: str, result) -> Any:
"""Breaker bookkeeping: an error payload from the tool itself still counts as a strike."""
- if _result_is_error(result):
- _core._bump_server_error(server_name)
- else:
- _core._reset_server_error(server_name)
+ (_core._bump_server_error if _result_is_error(result) else _core._reset_server_error)(server_name)
return result
@@ -109,18 +109,17 @@ def _strike(server_name: str, message: str, **extra) -> str:
return tool_error(message, **extra)
+def _mcp_loop_running() -> bool:
+ return _core._mcp_loop is not None and _core._mcp_loop.is_running()
+
+
def _lookup_reconnectable_server(server_name: str, require_loop: bool = False):
"""The registered server object when it can be signalled to reconnect, else None.
With *require_loop*, also None unless the MCP loop is running (nothing to wait on)."""
with _core._lock:
srv = _core._servers.get(server_name)
- if srv is None or not hasattr(srv, "_reconnect_event") or (require_loop and not _mcp_loop_running()):
- return None
- return srv
-
-
-def _mcp_loop_running() -> bool:
- return _core._mcp_loop is not None and _core._mcp_loop.is_running()
+ ok = srv is not None and hasattr(srv, "_reconnect_event") and (_mcp_loop_running() or not require_loop)
+ return srv if ok else None
def _retry_once(server_name: str, retry_call, op_description: str, what: str):
@@ -146,9 +145,8 @@ def _handle_auth_error_and_retry(server_name: str, exc: BaseException, retry_cal
if not _core._is_auth_error(exc):
return None
from tools.mcp_oauth_manager import get_manager
- manager = get_manager()
try:
- recovered = _core._run_on_mcp_loop(lambda: manager.handle_401(server_name, None), timeout=10)
+ recovered = _core._run_on_mcp_loop(lambda: get_manager().handle_401(server_name, None), timeout=10)
except Exception as rec_exc:
logger.warning("MCP OAuth '%s': recovery attempt failed: %s", server_name, rec_exc)
recovered = False
@@ -162,20 +160,13 @@ def _handle_auth_error_and_retry(server_name: str, exc: BaseException, retry_cal
result = _retry_once(server_name, retry_call, op_description, "auth recovery")
if result is not None:
return result
- return _strike(
- server_name,
- f"MCP server '{server_name}' requires re-authentication. Run `hermes mcp login "
- f"{server_name}` (or delete the tokens file under ~/.hermes/mcp-tokens/ and restart). Do "
- f"NOT retry this tool — ask the user to re-authenticate.",
- needs_reauth=True, server=server_name)
+ return _strike(server_name, _NEEDS_REAUTH_MSG.format(s=server_name), needs_reauth=True, server=server_name)
def _handle_session_expired_and_retry(server_name: str, exc: BaseException, retry_call, op_description: str):
"""Transport reconnect + one retry on session expiry; None to fall through. Skips
``handle_401``: the token is valid, only the server-side session is stale."""
- if not _is_session_expired_error(exc):
- return None
- srv = _lookup_reconnectable_server(server_name, require_loop=True)
+ srv = _lookup_reconnectable_server(server_name, require_loop=True) if _is_session_expired_error(exc) else None
if srv is None:
return None
logger.info("MCP server '%s': %s failed with session-expired error (%s); signalling transport reconnect "
@@ -205,27 +196,17 @@ def _handle_stdio_child_exited_and_retry(server_name: str, exc: Exception, retry
if _mcp_loop_running():
reconnected = _core._signal_reconnect_and_wait(
server_name, srv, op_description=op_description, timeout=_core._STDIO_RESPAWN_WAIT_SEC)
- else:
- # No MCP loop to wait on (non-async adapters, tests): still request the respawn.
+ else: # No MCP loop to wait on (non-async adapters, tests): still request the respawn.
_core._signal_reconnect(srv)
if not reconnected:
- return _strike(
- server_name,
- f"MCP server '{server_name}' stdio subprocess had exited (this is not a timeout — the "
- f"call never reached the server). A respawn was requested but no fresh session came "
- f"back within {_core._STDIO_RESPAWN_WAIT_SEC:.0f}s. Wait a few seconds before retrying; "
- f"if it keeps failing the server is not starting and needs the user.")
+ return _strike(server_name, _STDIO_NO_RESPAWN_MSG.format(s=server_name, t=_core._STDIO_RESPAWN_WAIT_SEC))
try:
return _record_call_outcome(server_name, retry_call())
except _StdioChildExited as retry_exc:
# Died again right after respawn: broken server; run()'s budget takes it to the park.
logger.warning("MCP server '%s': %s stdio subprocess exited again right after respawn (%s); not retrying "
"further.", server_name, op_description, retry_exc)
- return _strike(
- server_name,
- f"MCP server '{server_name}' respawned its stdio subprocess and it exited again "
- f"immediately. The server is not starting cleanly — do NOT retry this tool; ask the "
- f"user to check the server's command and its stderr log.")
+ return _strike(server_name, _STDIO_DIED_AGAIN_MSG.format(s=server_name))
except Exception as retry_exc:
logger.warning("MCP %s/%s retry after stdio respawn failed: %s", server_name, op_description, retry_exc)
return _strike(server_name, _sanitize_error(
@@ -254,13 +235,17 @@ def _invoke_with_recovery(server_name: str, call_once: Callable[[], str], op: st
return tool_error(_sanitize_error(f"MCP call failed: {type(exc).__name__}: {_exc_str(exc)}"))
-# ------------------------------------------------------------- the RPC itself
-
-def _mark_server_call_started(server: Any) -> None:
- """Record a user-visible MCP operation when the server supports it."""
+def _dispatch(server_name: str, server: Any, op: str, call, tool_timeout: float, recoverers,
+ on_final_failure: Callable[[BaseException], None], record_outcome: bool = False) -> str:
+ """Mark the call started on *server* (doubles may lack ``mark_tool_call``), run coroutine
+ function *call* on the MCP loop and walk the recovery ladder (:func:`_invoke_with_recovery`)."""
if callable(getattr(server, "mark_tool_call", None)):
server.mark_tool_call()
+ return _invoke_with_recovery(server_name, lambda: _core._run_on_mcp_loop(call, timeout=tool_timeout), op,
+ recoverers, on_final_failure, record_outcome=record_outcome)
+
+# ------------------------------------------------------------- the RPC itself
@asynccontextmanager
async def _track_inflight_rpc(server: Any, server_name: str, op: str):
@@ -285,10 +270,9 @@ async def _track_inflight_rpc(server: Any, server_name: str, op: str):
async def _call_tool_racing_stdio_death(server, server_name: str, tool_name: str, args: dict):
"""``session.call_tool`` that fails fast when the stdio child is/gets dead: pre-call (a dead
- child must not hold the slot for the full timeout; ``server.session`` is stale) and mid-call
- (race against ``_watch_stdio_children``). Both raise :class:`_StdioChildExited` for the
- respawn path, which owns the reconnect signal. callable()/``is True`` because MagicMock
- attributes are truthy."""
+ child must not hold the slot for the full timeout) and mid-call (race against
+ ``_watch_stdio_children``). Both raise :class:`_StdioChildExited` for the respawn path, which
+ owns the reconnect signal. callable()/``is True`` because MagicMock attributes are truthy."""
_stdio_dead = getattr(server, "_stdio_children_dead", None)
if callable(_stdio_dead) and _stdio_dead() is True:
raise _StdioChildExited(f"MCP stdio subprocess for '{server_name}' had already exited when the call was dispatched")
@@ -339,8 +323,7 @@ def _render_content_blocks(result, server_name: str) -> str:
logger.debug("MCP %s: content block type %r rendered empty", server_name, block_type)
else:
logger.warning("MCP %s: dropping unsupported content block type %r", server_name, block_type)
- # Hard-cap pathological payloads; ordinary large results pass to spillover.
- return _truncate_mcp_text_result("\n".join(parts))
+ return _truncate_mcp_text_result("\n".join(parts)) # hard-cap pathological payloads; spillover handles the rest
def _capped_structured_content(result):
@@ -374,8 +357,7 @@ def _render_call_tool_result(result, server_name: str) -> str:
payload.setdefault("result", text_result)
try:
return json.dumps(payload, ensure_ascii=False)
- except (TypeError, ValueError):
- # Non-serializable metadata: drop the extras, keep the call.
+ except (TypeError, ValueError): # Non-serializable metadata: drop the extras, keep the call.
return json.dumps({"result": text_result}, ensure_ascii=False)
@@ -386,8 +368,7 @@ def _make_tool_handler(server_name: str, tool_name: str, tool_timeout: float):
op = f"tools/call {tool_name}"
def _handler(args: dict, **kwargs) -> str:
- # Security boundary: untrusted-server write tools need approval before ANY transport work
- # (including the lazy first-use spawn).
+ # Security boundary: untrusted-server write tools need approval before ANY transport work (incl. lazy spawn).
error = _trust_gate_check(server_name, tool_name) or _check_circuit_breaker(server_name)
if error is not None:
return error
@@ -396,16 +377,13 @@ def _make_tool_handler(server_name: str, tool_name: str, tool_timeout: float):
return error
async def _call():
- _mark_server_call_started(server)
async with server._rpc_lock, _track_inflight_rpc(server, server_name, op):
- # Snapshot contextvars for the elicitation callback (MCP recv loop doesn't inherit them).
- server._pending_call_context = contextvars.copy_context()
+ server._pending_call_context = contextvars.copy_context() # for the elicitation callback
try:
result = await _call_tool_racing_stdio_death(server, server_name, tool_name, args)
finally:
server._pending_call_context = None
- # Round-trip completed: transport is healthy even if the tool returned isError.
- if getattr(server, "_mark_session_proven", None) is not None:
+ if getattr(server, "_mark_session_proven", None) is not None: # round-trip done: transport healthy
server._mark_session_proven()
return _render_call_tool_result(result, server_name)
@@ -413,39 +391,39 @@ def _make_tool_handler(server_name: str, tool_name: str, tool_timeout: float):
_core._bump_server_error(server_name)
logger.error("MCP tool %s/%s call failed: %s", server_name, tool_name, exc)
- return _invoke_with_recovery(
- server_name, lambda: _core._run_on_mcp_loop(_call, timeout=tool_timeout), op,
+ return _dispatch(
+ server_name, server, op, _call, tool_timeout,
(_handle_stdio_child_exited_and_retry, _handle_auth_error_and_retry, _handle_session_expired_and_retry),
_on_failure, record_outcome=True)
return _handler
-def _make_utility_handler(server_name: str, tool_timeout: float, op: str, log_label: str,
- rpc, render, required: Optional[str] = None):
- """Shared shape of the four utility handlers: ``rpc(session, args, server_name)`` awaited
- under ``_rpc_lock``, ``render(result, server_name)`` -> JSON-able payload, ``required``
- validated before any transport work; owns the connected check and recovery ladder."""
+def _make_utility_handler(op: str, log_label: str, rpc, render, required: Optional[str] = None):
+ """``(server_name, tool_timeout) -> sync handler`` for one utility tool: ``rpc(session, args,
+ server_name)`` awaited under ``_rpc_lock``, ``render(result, server_name)`` -> JSON-able
+ payload, ``required`` validated before any transport work."""
+ def _factory(server_name: str, tool_timeout: float):
+ def _handler(args: dict, **kwargs) -> str:
+ server = _core._get_connected_server_for_call(server_name)
+ if not server or not server.session:
+ return tool_error(f"MCP server '{server_name}' is not connected")
+ if required and not args.get(required):
+ return tool_error(f"Missing required parameter '{required}'")
- def _handler(args: dict, **kwargs) -> str:
- server = _core._get_connected_server_for_call(server_name)
- if not server or not server.session:
- return tool_error(f"MCP server '{server_name}' is not connected")
- if required and not args.get(required):
- return tool_error(f"Missing required parameter '{required}'")
+ async def _call():
+ async with server._rpc_lock:
+ result = await rpc(server.session, args, server_name)
+ return json.dumps(render(result, server_name), ensure_ascii=False)
- async def _call():
- _mark_server_call_started(server)
- async with server._rpc_lock:
- result = await rpc(server.session, args, server_name)
- return json.dumps(render(result, server_name), ensure_ascii=False)
+ return _dispatch(
+ server_name, server, op, _call, tool_timeout,
+ (_handle_auth_error_and_retry, _handle_session_expired_and_retry),
+ lambda exc: logger.error("MCP %s/%s failed: %s", server_name, log_label, exc))
- return _invoke_with_recovery(
- server_name, lambda: _core._run_on_mcp_loop(_call, timeout=tool_timeout), op,
- (_handle_auth_error_and_retry, _handle_session_expired_and_retry),
- lambda exc: logger.error("MCP %s/%s failed: %s", server_name, log_label, exc))
+ return _handler
- return _handler
+ return _factory
def _pick(obj, *specs) -> dict:
@@ -453,10 +431,8 @@ def _pick(obj, *specs) -> dict:
so SDK models and stubs behave alike; ``truthy`` also skips falsy). Key order = spec order."""
entry = {}
for out_key, attr, *truthy in specs:
- if not hasattr(obj, attr):
- continue
- value = getattr(obj, attr)
- if value or not (truthy and truthy[0]):
+ value = getattr(obj, attr, _MISSING)
+ if value is not _MISSING and (value or not (truthy and truthy[0])):
entry[out_key] = value
return entry
@@ -479,8 +455,7 @@ def _render_read_resource(result, server_name: str) -> dict:
for block in getattr(result, "contents", []):
if getattr(block, "text", None) is not None:
parts.append(strip_unicode_tags(block.text))
- elif getattr(block, "blob", None) is not None:
- # Binary contents go to the document cache (same contract as EmbeddedResource blocks).
+ elif getattr(block, "blob", None) is not None: # binary -> document cache, like EmbeddedResource blocks
rendered = _render_mcp_resource_block(SimpleNamespace(type="resource", resource=block), server_name)
parts.append(rendered or f"[binary data, {len(block.blob)} bytes]")
return {"result": "\n".join(parts)}
@@ -507,41 +482,28 @@ def _render_get_prompt(result, server_name: str) -> dict:
return {"messages": messages, **_pick(result, ("description", "description", True))}
-def _utility_factory(op: str, log_label: str, rpc, render, required: Optional[str] = None):
- """``(server_name, tool_timeout) -> sync handler`` for one utility tool."""
- def _factory(server_name: str, tool_timeout: float):
- return _make_utility_handler(server_name, tool_timeout, op, log_label, rpc, render, required)
-
- return _factory
-
-
-_make_list_resources_handler = _utility_factory(
+_make_list_resources_handler = _make_utility_handler(
"resources/list", "list_resources",
- lambda session, args, sn: _core._paginate_full_list(session.list_resources, "resources", sn),
- _render_resource_list)
-_make_read_resource_handler = _utility_factory(
+ lambda session, args, sn: _core._paginate_full_list(session.list_resources, "resources", sn), _render_resource_list)
+_make_read_resource_handler = _make_utility_handler(
"resources/read", "read_resource",
lambda session, args, sn: session.read_resource(args["uri"]), _render_read_resource, required="uri")
-_make_list_prompts_handler = _utility_factory(
+_make_list_prompts_handler = _make_utility_handler(
"prompts/list", "list_prompts",
- lambda session, args, sn: _core._paginate_full_list(session.list_prompts, "prompts", sn),
- _render_prompt_list)
-_make_get_prompt_handler = _utility_factory(
+ lambda session, args, sn: _core._paginate_full_list(session.list_prompts, "prompts", sn), _render_prompt_list)
+_make_get_prompt_handler = _make_utility_handler(
"prompts/get", "get_prompt",
lambda session, args, sn: session.get_prompt(args["name"], arguments=args.get("arguments", {})),
_render_get_prompt, required="name")
def _make_check_fn(server_name: str):
- """Check function that verifies the MCP connection is alive."""
-
+ """Check function that verifies the MCP connection is alive. Lazy (schema-cache registered)
+ servers count as available: the first real call spawns/connects them."""
def _check() -> bool:
with _core._lock:
server = _core._servers.get(server_name)
- if server is not None and (server.session is not None or server._is_recycled_stdio()):
- return True
- # Lazy (schema-cache registered) servers count as available: the first real
- # call spawns/connects them.
- return server_name in _core._lazy_server_configs
+ return ((server is not None and (server.session is not None or server._is_recycled_stdio()))
+ or server_name in _core._lazy_server_configs)
return _check
diff --git a/tools/mcp_tool_health.py b/tools/mcp_tool_health.py
index d213d7df0ed..c90db405b24 100644
--- a/tools/mcp_tool_health.py
+++ b/tools/mcp_tool_health.py
@@ -1,6 +1,6 @@
"""Session health for MCPServerTask: dynamic tool refresh on list_changed notifications, server
log forwarding, keepalive probes, suspect-mark / lazy-verify, in-flight call fail-fast, stdio
-child liveness and stdio idle/lifetime recycling. Split from tools/mcp_tool.py."""
+child liveness and stdio idle/lifetime recycling."""
import asyncio
import json
@@ -88,8 +88,7 @@ class MCPServerHealthMixin:
if len(data) > 2000: # cap payloads so a chatty server can't flood agent.log
data = data[:2000] + "... [truncated]"
logger_name = getattr(params, "logger", None)
- origin = f"{self.name}/{logger_name}" if logger_name else self.name
- logger.log(level, "MCP server log [%s]: %s", origin, data)
+ logger.log(level, "MCP server log [%s]: %s", f"{self.name}/{logger_name}" if logger_name else self.name, data)
except Exception:
logger.debug("Failed to handle MCP log notification from '%s'", self.name, exc_info=True)
return _on_log
@@ -125,12 +124,10 @@ class MCPServerHealthMixin:
"""Deregister *tool_names* this server's toolset still owns. Never removes a colliding
name currently owned by another server."""
from tools.registry import registry
- toolset_name = f"mcp-{self.name}"
for tool_name in tool_names:
- if registry.get_toolset_for_tool(tool_name) != toolset_name:
- continue
- registry.deregister(tool_name, scope=_core._server_registry_scope(self.name))
- _forget_mcp_tool_server(tool_name)
+ if registry.get_toolset_for_tool(tool_name) == f"mcp-{self.name}":
+ registry.deregister(tool_name, scope=_core._server_registry_scope(self.name))
+ _forget_mcp_tool_server(tool_name)
async def _refresh_tools(self):
"""Re-fetch tools on ``tools/list_changed`` and update the registry. The lock serializes
@@ -165,6 +162,9 @@ class MCPServerHealthMixin:
"""Exercise the session; raise on a genuine connection failure. ``ping`` first (cheap,
OPTIONAL); on -32601 latch ``_ping_unsupported`` (reset per transport connection) and fall
back to ``list_tools`` when the server advertises tools, else the -32601 propagates."""
+ async def list_tools():
+ await asyncio.wait_for(self.session.list_tools(), timeout=_KEEPALIVE_RPC_TIMEOUT)
+
if not self._ping_unsupported:
try:
await asyncio.wait_for(self.session.send_ping(), timeout=_KEEPALIVE_RPC_TIMEOUT)
@@ -180,7 +180,7 @@ class MCPServerHealthMixin:
# A server that silently drops ping looks like a dead transport: confirm with
# list_tools before declaring it dead, else propagate the original failure.
try:
- await asyncio.wait_for(self.session.list_tools(), timeout=_KEEPALIVE_RPC_TIMEOUT)
+ await list_tools()
except Exception:
raise exc from None
self._ping_unsupported = True # latch so later keepalives skip the 30s wait
@@ -189,7 +189,7 @@ class MCPServerHealthMixin:
return
else:
raise # closed transport, expired session, etc. — real failure
- await asyncio.wait_for(self.session.list_tools(), timeout=_KEEPALIVE_RPC_TIMEOUT)
+ await list_tools()
def _mark_session_proven(self) -> None:
"""Record that the session demonstrated real health (keepalive or tool-call success).
@@ -204,8 +204,7 @@ class MCPServerHealthMixin:
logger.warning("MCP server '%s': revived — session healthy again after "
"parking (state: parked → connected)", self.name)
# A proven fresh transport clears the one-time permanent-failure grace and any race bookkeeping.
- self._permanent_grace_used = False
- self._teardown_race = False
+ self._permanent_grace_used = self._teardown_race = False
def mark_suspect(self, reason: str) -> None:
"""Latch a suspicion (no I/O). The NEXT call verifies via :meth:`ensure_healthy` and
@@ -253,8 +252,7 @@ class MCPServerHealthMixin:
victims = [t for t in self._inflight_tasks if not t.done()]
if not victims:
return
- self._reconnecting = True
- self._teardown_race = True
+ self._reconnecting = self._teardown_race = True
self.mark_suspect(f"{reason} tore down {len(victims)} in-flight call(s)")
for task in victims:
task.cancel()
diff --git a/tools/mcp_tool_registration.py b/tools/mcp_tool_registration.py
index b9c994df5af..75958736561 100644
--- a/tools/mcp_tool_registration.py
+++ b/tools/mcp_tool_registration.py
@@ -1,8 +1,7 @@
"""Registering a connected (or schema-cached) MCP server's tools into the tool registry:
-include/exclude filtering, trust-tier metadata capture, utility-tool selection,
-name-collision resolution and the schema-cache write-through. Both entry points
-(``_register_server_tools`` live, ``_register_from_cache_sync`` lazy) build ``_Candidate``
-records and feed the single ``_register_candidates`` loop."""
+include/exclude filtering, trust-tier metadata capture, utility-tool selection, name-collision
+resolution and the schema-cache write-through. Both entry points (``_register_server_tools``
+live, ``_register_from_cache_sync`` lazy) build ``_Candidate`` records for ``_register_candidates``."""
import logging
from dataclasses import dataclass
@@ -34,8 +33,7 @@ def _normalize_server_trust(value: Any) -> str:
text = str(value).strip().lower()
if text in (_core._TRUST_FULL, _core._TRUST_UNTRUSTED):
return text
- logger.warning("MCP trust: unrecognized trust value %r — treating as 'untrusted' (valid values: full, untrusted)",
- value)
+ logger.warning("MCP trust: unrecognized trust value %r — treating as 'untrusted' (valid values: full, untrusted)", value)
return _core._TRUST_UNTRUSTED
@@ -43,9 +41,8 @@ def _annotation_read_only_hint(mcp_tool: Any) -> bool:
"""True only when annotations (SDK object or schema-cache dict) carry ``readOnlyHint is
True``; unknown metadata means write-capable."""
annotations = getattr(mcp_tool, "annotations", None)
- if isinstance(annotations, dict):
- return annotations.get("readOnlyHint") is True
- return getattr(annotations, "readOnlyHint", None) is True
+ hint = annotations.get("readOnlyHint") if isinstance(annotations, dict) else getattr(annotations, "readOnlyHint", None)
+ return hint is True
def _record_tool_trust_metadata(server_name: str, config: dict, tools: List[Any]) -> None:
@@ -55,10 +52,7 @@ def _record_tool_trust_metadata(server_name: str, config: dict, tools: List[Any]
with _core._lock:
_core._server_trust_levels[server_name] = _normalize_server_trust((config or {}).get("trust"))
hints = _core._tool_read_only_hints.setdefault(server_name, {})
- for tool in tools:
- name = getattr(tool, "name", None)
- if name:
- hints[name] = _annotation_read_only_hint(tool)
+ hints.update({t.name: _annotation_read_only_hint(t) for t in tools if getattr(t, "name", None)})
def _track_mcp_tool_server(tool_name: str, server_name: str) -> None:
@@ -80,17 +74,14 @@ def _select_utility_schemas(server_name: str, server: "MCPServerTask", config: d
filters anything since ClientSession defines all four methods."""
tools_filter = config.get("tools") or {}
enabled = {f: _parse_boolish(tools_filter.get(f), default=True) for f in ("resources", "prompts")}
- init_result = getattr(server, "initialize_result", None)
- advertised = getattr(init_result, "capabilities", None) if init_result is not None else None
+ advertised = getattr(getattr(server, "initialize_result", None), "capabilities", None)
def _skip_reason(handler_key: str) -> Optional[str]:
family = _UTILITY_CAPABILITY_ATTRS[handler_key]
if not enabled[family]:
return f"{family} disabled"
if advertised is not None:
- if getattr(advertised, family, None) is None:
- return f"server does not advertise '{family}' capability"
- return None
+ return None if getattr(advertised, family, None) is not None else f"server does not advertise '{family}' capability"
# Legacy gate (no initialize_result): the ClientSession method shares the handler key.
return None if hasattr(server.session, handler_key) else f"session lacks {handler_key}"
@@ -176,8 +167,7 @@ def _tool_candidates(name: str, tools: Iterable[Any], should_register: Callable[
continue
_core._scan_mcp_description(name, t.name, t.description or "")
schema = _core._convert_mcp_schema(name, t)
- handler = _core._make_tool_handler(name, t.name, tool_timeout)
- out.append(_Candidate(schema["name"], f"tool {t.name!r}", schema, handler))
+ out.append(_Candidate(schema["name"], f"tool {t.name!r}", schema, _core._make_tool_handler(name, t.name, tool_timeout)))
return out
@@ -187,8 +177,8 @@ def _utility_candidates(name: str, entries: Iterable[Any], tool_timeout) -> List
for raw in entries:
schema, key = (raw.get("schema"), raw.get("handler_key")) if isinstance(raw, dict) else (None, None)
if isinstance(schema, dict) and key in _UTILITY_HANDLER_FACTORIES and schema.get("name"):
- handler = _UTILITY_HANDLER_FACTORIES[key](name, tool_timeout)
- out.append(_Candidate(schema["name"], f"{_UTILITY_ORIGIN_PREFIX}{key!r}", schema, handler))
+ out.append(_Candidate(schema["name"], f"{_UTILITY_ORIGIN_PREFIX}{key!r}", schema,
+ _UTILITY_HANDLER_FACTORIES[key](name, tool_timeout)))
return out
@@ -197,16 +187,15 @@ def _resolve_name_collisions(name: str, candidates: List[_Candidate]) -> List[_C
a native tool's name is shadowed (native wins); any other multi-origin collision skips every
colliding entry (fail closed). Returns survivors in order."""
unique: List[_Candidate] = []
- seen: set[tuple[str, str]] = set()
origins_by_name: Dict[str, set[str]] = {}
for c in candidates:
- if (c.registry_name, c.origin) in seen:
+ origins = origins_by_name.setdefault(c.registry_name, set())
+ if c.origin in origins:
logger.debug("MCP server '%s': duplicate registration candidate %s for '%s'; keeping one",
name, c.origin, c.registry_name)
continue
- seen.add((c.registry_name, c.origin))
+ origins.add(c.origin)
unique.append(c)
- origins_by_name.setdefault(c.registry_name, set()).add(c.origin)
ambiguous: Dict[str, List[str]] = {}
shadowed: set[tuple[str, str]] = set()
for registry_name, origins in origins_by_name.items():
@@ -220,8 +209,8 @@ def _resolve_name_collisions(name: str, candidates: List[_Candidate]) -> List[_C
"MCP server '%s': generated utility %s normalizes onto server-native %s — keeping the native tool "
"and dropping the utility (the utility only applies when the server has no such tool of its own)",
name, ", ".join(utility_origins), native_origins[0])
- continue
- ambiguous[registry_name] = sorted(origins)
+ else:
+ ambiguous[registry_name] = sorted(origins)
for registry_name, origins in sorted(ambiguous.items()):
logger.error("MCP server '%s': name normalization collision for '%s' from %s; skipping every colliding "
"entry instead of choosing an arbitrary handler", name, registry_name, ", ".join(origins))
@@ -234,8 +223,7 @@ def _log_foreign_owner(name: str, c: _Candidate, existing_toolset: str, lazy: bo
if not c.is_utility:
logger.warning("MCP server '%s' (lazy): cached tool '%s' collides with toolset '%s' — skipping",
name, c.registry_name, existing_toolset)
- return
- if existing_toolset.startswith("mcp-"):
+ elif existing_toolset.startswith("mcp-"):
logger.error("MCP server '%s': %s normalizes to '%s', already owned by MCP toolset '%s' — skipping to "
"preserve the existing owner", name, c.origin, c.registry_name, existing_toolset)
else:
@@ -259,13 +247,12 @@ def _register_candidates(name: str, candidates: List[_Candidate], *, check_fn: C
registry.register(
name=c.registry_name, toolset=toolset_name, schema=c.schema, handler=c.handler, check_fn=check_fn,
is_async=False, description=c.schema.get("description") or "", scope=scope())
- if registry.get_toolset_for_tool(c.registry_name) != toolset_name:
- if not lazy:
- logger.error("MCP server '%s': registration of %s as '%s' was rejected by the registry; "
- "skipping provenance/count updates", name, c.origin, c.registry_name)
- continue
- _core._track_mcp_tool_server(c.registry_name, name)
- registered.append(c.registry_name)
+ if registry.get_toolset_for_tool(c.registry_name) == toolset_name:
+ _core._track_mcp_tool_server(c.registry_name, name)
+ registered.append(c.registry_name)
+ elif not lazy:
+ logger.error("MCP server '%s': registration of %s as '%s' was rejected by the registry; "
+ "skipping provenance/count updates", name, c.origin, c.registry_name)
if registered:
registry.register_toolset_alias(name, toolset_name)
return registered
@@ -279,8 +266,7 @@ def _write_schema_cache(name: str, server: "MCPServerTask", config: dict, should
tools_payload = [{
"name": t.name, "description": t.description or "",
"inputSchema": t.inputSchema if isinstance(getattr(t, "inputSchema", None), dict) else {},
- # Persisted so the lazy path trust-gates identically next startup.
- "annotations": {"readOnlyHint": _annotation_read_only_hint(t)},
+ "annotations": {"readOnlyHint": _annotation_read_only_hint(t)}, # lazy path trust-gates identically
} for t in server._tools if should_register(t.name)]
utility_payload = [{"schema": e["schema"], "handler_key": e["handler_key"]}
for e in _select_utility_schemas(name, server, config)]
diff --git a/tools/mcp_tool_transport.py b/tools/mcp_tool_transport.py
index 99eef3fd389..29721bb977a 100644
--- a/tools/mcp_tool_transport.py
+++ b/tools/mcp_tool_transport.py
@@ -1,6 +1,6 @@
"""Transport bring-up for MCPServerTask: stdio spawn (OSV preflight, watchdog wrap, child PID
ledger), Streamable HTTP / SSE connect (preflight, identity header, client certs, OAuth),
-protocol negotiation and initial tool discovery. Split from tools/mcp_tool.py."""
+protocol negotiation and initial tool discovery."""
import logging
import asyncio
@@ -29,15 +29,17 @@ def _is_2xx(resp) -> bool:
return 200 <= resp.status_code < 300
+def _present(**kwargs) -> dict:
+ """*kwargs* minus the ``None`` values (optional httpx client arguments)."""
+ return {k: v for k, v in kwargs.items() if v is not None}
+
+
def _pgroup_alive(pgid: Optional[int]) -> bool:
"""Signal 0 to the group succeeds iff any member is alive (POSIX only)."""
- _killpg = getattr(os, "killpg", None)
- if pgid is None or _killpg is None:
- return False
try:
- _killpg(pgid, 0)
+ os.killpg(pgid, 0)
return True
- except (ProcessLookupError, PermissionError, OSError):
+ except (AttributeError, TypeError, OSError): # non-POSIX / pgid None / gone
return False
@@ -63,16 +65,17 @@ class MCPServerTransportMixin:
__slots__ = ()
def _advertises_tools(self) -> bool:
- """Whether the server advertises ``tools`` (prompt-/resource-only servers omit it and
- ``tools/list`` raises -32601). True when no capability info was captured (legacy fallback)."""
+ """False only when captured capabilities omit ``tools`` (prompt-/resource-only servers,
+ where ``tools/list`` raises -32601); True without capability info (legacy fallback)."""
caps = getattr(self.initialize_result, "capabilities", None)
return caps is None or getattr(caps, "tools", None) is not None
def _session_kwargs(self) -> dict:
"""ClientSession kwargs: sampling, elicitation, notification + logging callbacks."""
- kwargs = self._sampling.session_kwargs() if self._sampling else {}
- if self._elicitation:
- kwargs.update(self._elicitation.session_kwargs())
+ kwargs = {}
+ for handler in (self._sampling, self._elicitation):
+ if handler:
+ kwargs.update(handler.session_kwargs())
if _core._MCP_NOTIFICATION_TYPES and _core._MCP_MESSAGE_HANDLER_SUPPORTED:
kwargs["message_handler"] = self._make_message_handler()
if _core._MCP_LOGGING_CALLBACK_SUPPORTED:
@@ -80,12 +83,11 @@ class MCPServerTransportMixin:
return kwargs
async def _negotiate_session(self, session, connect_timeout: float):
- """Negotiate the protocol era (``initialize`` vs ``server/discover``); both results expose
- ``.capabilities``. ``protocol: auto`` (default) tries the legacy handshake FIRST and falls back
- to discover only on a modern-only signal (-32022 / initialize -32601) — deliberately the
- reverse of the SDK's discover-first mode: zero extra round-trips for the handshake-era
- servers that dominate today. ``stateless`` probes discover first (one legacy retry on any
- error); ``legacy`` is handshake only. A handshake TIMEOUT never falls back — it propagates."""
+ """Negotiate the protocol era (``initialize`` vs ``server/discover``; both expose
+ ``.capabilities``). ``auto`` tries the legacy handshake FIRST, falling back to discover only
+ on a modern-only signal (-32022 / initialize -32601) — the reverse of the SDK's discover-first
+ mode, so handshake-era servers pay zero extra round-trips. ``stateless`` probes discover first
+ (one legacy retry on any error); ``legacy`` is handshake only. A TIMEOUT never falls back."""
def call(method: str):
return asyncio.wait_for(getattr(session, method)(), timeout=connect_timeout)
@@ -111,14 +113,13 @@ class MCPServerTransportMixin:
# mcp 1.x has no server/discover client — nothing to fall back to.
return await attempt(
"initialize", "discover", lambda exc: _handshake_rejected_as_modern(exc) and hasattr(session, "discover"),
- "MCP server '%s': legacy handshake rejected (%s) — "
- "retrying via server/discover (2026-07-28 stateless server)")
+ "MCP server '%s': legacy handshake rejected (%s) — retrying via server/discover (2026-07-28 stateless server)")
async def _serve_session(self, session, connect_timeout: float,
label: str = "", mark_lifecycle: bool = False) -> str:
"""Handshake, discover, publish readiness, then serve until a lifecycle event. Clears stale
breaker state but leaves the session UNPROVEN: flapping transports handshake fine and drop
- moments later, so only keepalive or tool-call success clears the reconnect budget."""
+ moments later, so only keepalive/tool-call success clears the reconnect budget."""
self.initialize_result = await self._negotiate_session(session, connect_timeout)
self.session = session
if mark_lifecycle:
@@ -135,8 +136,7 @@ class MCPServerTransportMixin:
async def _serve_transport(self, transport_cm, label: str, connect_timeout: float) -> str:
"""Open *transport_cm*, wrap its streams in a ClientSession and serve it. Streams are indexed,
- not unpacked: mcp 1.x yields ``(read, write, get_session_id)``, 2.x ``(read, write)``.
- A transport TaskGroup drop maps to ``"reconnect"`` instead of backoff/park."""
+ not unpacked (mcp 1.x yields a 3-tuple, 2.x a pair); a TaskGroup drop maps to ``"reconnect"``."""
try:
async with transport_cm as _streams:
async with _core.ClientSession(_streams[0], _streams[1], **self._session_kwargs()) as session:
@@ -148,12 +148,12 @@ class MCPServerTransportMixin:
def _track_spawned_children(self, new_pids: Set[int]) -> None:
"""Ledger the freshly spawned stdio children (pids, pgids, machine spawn ledger). pgids are
- captured while alive (getpgid fails once it exits; the sweep needs it for reparented descendants)."""
+ captured while alive (getpgid fails after exit; the sweep needs them for reparented descendants)."""
new_pgids: Dict[int, int] = {}
for pid in new_pids:
try:
new_pgids[pid] = os.getpgid(pid)
- except (AttributeError, ProcessLookupError, OSError): # Windows / already exited
+ except (AttributeError, OSError): # Windows / already exited
pass
with _core._lock:
_stdio_pids.update(dict.fromkeys(new_pids, self.name))
@@ -173,8 +173,7 @@ class MCPServerTransportMixin:
with _core._lock:
for pid in new_pids:
_stdio_pids.pop(pid, None)
- # ``os.kill(pid, 0)`` is NOT a no-op on Windows; the child may be gone while
- # descendants remain in its pgroup.
+ # Windows-safe pid probe; the child may be gone while descendants remain in its pgroup.
if _pid_exists(pid) or _pgroup_alive(_stdio_pgids.get(pid)):
_orphan_stdio_pids.add(pid)
_orphan_stdio_pid_servers[pid] = self.name
@@ -183,8 +182,7 @@ class MCPServerTransportMixin:
async def _run_stdio(self, config: dict):
"""Run the server using stdio transport."""
- if config.get("identity_header") is not None:
- # No headers on stdio — warn so a copy-pasted HTTP block doesn't mislead.
+ if config.get("identity_header") is not None: # copy-pasted HTTP block: warn, don't mislead
logger.warning("MCP server '%s': identity_header is only supported on "
"HTTP/SSE transports — ignored for stdio servers", self.name)
if not _core._ensure_mcp_sdk():
@@ -195,39 +193,34 @@ class MCPServerTransportMixin:
raise ValueError(f"MCP server '{self.name}' has no 'command' in config")
command, safe_env = _core._resolve_stdio_command(command, _core._build_safe_env(config.get("env")))
await _osv_malware_preflight(self.name, command, config.get("args", []))
- # Parent-death watchdog so kill -9 / crash can't leave the child tree running (POSIX-only).
- # AFTER the OSV preflight so the check inspects the real package.
+ # Parent-death watchdog (POSIX) so kill -9 can't leave the child tree running; AFTER the
+ # OSV preflight so the check inspects the real package.
command, args = _wrap_command_with_watchdog(command, config.get("args", []))
server_params = _core.StdioServerParameters(
command=command, args=args, env=safe_env or None, cwd=config.get("cwd"),
# Windows pipes can split non-UTF-8 bytes at chunk boundaries; substitute, don't raise.
encoding_error_handler="replace")
- session_kwargs = self._session_kwargs()
- # Reap orphans of prior attempts first, else each retry piles up zombie pairs. Unscoped on
- # purpose (also reaps servers that never reconnect). Off-loop: the reaper blocks up to 2s.
+ # Reap orphans of prior attempts first (else retries pile up zombie pairs); unscoped on purpose;
+ # off-loop because the reaper blocks up to 2s.
await asyncio.to_thread(_core._kill_orphaned_mcp_children)
pids_before = _core._snapshot_child_pids() # so the new child can be identified after spawn
new_pids: set = set()
# Subprocess stderr goes to ~/.hermes/logs/mcp-stderr.log so banners can't corrupt the TUI.
_core._write_stderr_log_header(self.name)
try:
- errlog = _core._get_mcp_stderr_log()
- async with _core.stdio_client(server_params, errlog=errlog) as (read_stream, write_stream):
- # New PIDs for force-kill cleanup, minus non-MCP children (slash_worker, LSP) that
- # race into the window: they share the TUI's pgid, so leaking them into _stdio_pgids
- # would make the shutdown killpg() kill the TUI itself.
+ async with _core.stdio_client(server_params, errlog=_core._get_mcp_stderr_log()) as (read_stream, write_stream):
+ # New PIDs for force-kill cleanup, minus non-MCP children (slash_worker, LSP) racing
+ # into the window: they share the TUI's pgid — leaking them would killpg() the TUI.
new_pids = _filter_mcp_children(_core._snapshot_child_pids() - pids_before)
if new_pids:
self._track_spawned_children(new_pids)
self._stdio_child_pids = set(new_pids) # so in-flight calls fail fast when the child dies
- async with _core.ClientSession(read_stream, write_stream, **session_kwargs) as session:
- # Bound the handshake here: ``connect_timeout`` only bounds the caller's ``.result()``.
- # A server that never answers ``initialize`` would otherwise hang forever, skip the
- # ``finally`` and leak child + pipes on every retry until EMFILE.
+ async with _core.ClientSession(read_stream, write_stream, **self._session_kwargs()) as session:
+ # Bound the handshake here (``connect_timeout`` only bounds the caller's ``.result()``):
+ # a server that never answers ``initialize`` would leak child + pipes per retry until EMFILE.
connect_timeout = float(config.get("connect_timeout", _core._DEFAULT_CONNECT_TIMEOUT))
return await self._serve_session(session, connect_timeout, mark_lifecycle=True)
- finally:
- # Runs on clean exit, exceptions AND cancellation.
+ finally: # clean exit, exceptions AND cancellation
if new_pids:
self._release_spawned_children(new_pids)
@@ -235,29 +228,33 @@ class MCPServerTransportMixin:
async def _preflight_content_type(self, url: str, *, headers: Optional[dict] = None,
ssl_verify: bool = True, client_cert=None, timeout: float = 5.0) -> None:
- """Probe *url* before the SDK connects: a plain web page makes the SDK sit out the full
+ """Probe *url* before the SDK connects: a plain web page would make the SDK sit out the full
``connect_timeout`` before an opaque ``CancelledError``; this raises NonMcpEndpointError within
- ``timeout`` instead. Allow-list based: only a 2xx with a definite non-MCP content type is
- rejected, and only after a JSON-RPC ``initialize`` POST also fails to look like MCP (some
- servers serve a UI on GET but speak MCP via POST). Missing content type, non-2xx or transport
- errors pass silently — the real handshake stays the source of truth. Own httpx client, OUTSIDE
- the SDK's anyio task group, so the error isn't wrapped in an ExceptionGroup."""
+ ``timeout``. Allow-list based: only a 2xx with a definite non-MCP content type is rejected, and
+ only after a JSON-RPC ``initialize`` POST also fails to look like MCP (some servers serve a UI
+ on GET but speak MCP via POST). Anything else passes — the handshake stays the source of truth.
+ Own httpx client, OUTSIDE the SDK's anyio task group, so the error isn't group-wrapped."""
try:
import httpx as _httpx
except ImportError:
return # No httpx → skip probe; SDK import would have failed first.
+ def _non_mcp_2xx(resp) -> bool:
+ # Only judge 2xx (4xx/5xx may be an auth challenge the handshake handles); no content
+ # type advertised → don't second-guess the SDK.
+ ct = _content_type_base(resp)
+ return _is_2xx(resp) and bool(ct) and ct not in self._MCP_CONTENT_TYPES
+
probe_headers = dict(headers) if headers else {}
try:
async with _httpx.AsyncClient(verify=ssl_verify, follow_redirects=True, timeout=_httpx.Timeout(timeout),
- **({"cert": client_cert} if client_cert is not None else {})) as client:
+ **_present(cert=client_cert)) as client:
# HEAD is cheapest; fall back to GET on 405/501.
resp = await client.head(url, headers=probe_headers)
if resp.status_code in (405, 501):
resp = await client.get(url, headers=probe_headers)
# Non-MCP content type on HEAD/GET: try a JSON-RPC POST so POST-only servers pass.
- ct = _content_type_base(resp)
- if ct and ct not in self._MCP_CONTENT_TYPES and _is_2xx(resp):
+ if _non_mcp_2xx(resp):
post_resp = await client.post(
url, content=_PROBE_INITIALIZE_BODY,
headers={**probe_headers, "Content-Type": "application/json",
@@ -266,12 +263,9 @@ class MCPServerTransportMixin:
resp = post_resp
except _httpx.HTTPError:
return # DNS/connect/timeout/transport error — let the SDK try.
-
- # Only judge 2xx (4xx/5xx may be an auth challenge the handshake handles); no content type
- # advertised → don't second-guess the SDK.
- ct_base = _content_type_base(resp)
- if not _is_2xx(resp) or not ct_base or ct_base in self._MCP_CONTENT_TYPES:
+ if not _non_mcp_2xx(resp):
return
+ ct_base = _content_type_base(resp)
raise NonMcpEndpointError(
f"MCP server '{self.name}' at {url} returned Content-Type '{ct_base}', not an MCP "
f"response (expected one of: {', '.join(self._MCP_CONTENT_TYPES)}). The URL most likely "
@@ -281,10 +275,10 @@ class MCPServerTransportMixin:
def _reconnect_or_reraise_group(self, eg: BaseExceptionGroup) -> str:
"""Map an SDK transport TaskGroup failure to a clean ``"reconnect"``: HTTP/SSE stream pumps
run in an anyio TaskGroup, so a transient drop escapes as a ``BaseExceptionGroup`` that would
- otherwise back off and park the server for 300s over a sub-second glitch. Re-raise when it is
- not a transient drop: shutdown in progress (``_shutdown_event`` is set before cancel), the
- group carries KeyboardInterrupt/SystemExit or a real CancelledError, or no live session was
- reached this attempt (``_ready`` unset — connect failures must back off, not hot-loop)."""
+ otherwise park the server for 300s over a sub-second glitch. Re-raise when it is not one:
+ shutdown in progress (``_shutdown_event`` is set before cancel), KeyboardInterrupt/SystemExit
+ or a real CancelledError in the group, or no live session this attempt (``_ready`` unset —
+ connect failures must back off, not hot-loop)."""
if (self._shutdown_event.is_set()
or eg.split((KeyboardInterrupt, SystemExit))[0] is not None
or eg.split(asyncio.CancelledError)[0] is not None
@@ -296,8 +290,7 @@ class MCPServerTransportMixin:
def _build_oauth_auth(self, url: str, config: dict):
"""OAuth 2.1 PKCE via the central MCPOAuthManager (one provider reused across reconnects and
- CLI paths). Setup failures (e.g. non-interactive without cached tokens) re-raise so only this
- server is reported failed."""
+ CLI paths). Setup failures re-raise (after a warning) so only this server is reported failed."""
if self._auth_type != "oauth":
return None
try:
@@ -310,28 +303,25 @@ class MCPServerTransportMixin:
def _sse_transport(self, url: str, headers: dict, connect_timeout: float,
ssl_verify, client_cert, oauth_auth, strict_cfg_headers: bool):
"""``sse_client`` context manager for ``transport: sse`` entries."""
- if strict_cfg_headers:
- # Fail closed: SSE cannot enforce the redirect boundary.
+ if strict_cfg_headers: # fail closed: SSE cannot enforce the redirect boundary
raise ValueError(f"MCP server '{self.name}': strict_redirect_headers is "
"not supported on the SSE transport.")
if _core.sse_client is None:
raise ImportError(f"MCP server '{self.name}' requires SSE transport but "
"mcp.client.sse.sse_client is not available. "
"Upgrade the mcp package to get SSE support.")
- # sse_read_timeout bounds the gap between events: SSE servers idle for minutes, so 300s
- # (matching the Streamable HTTP read timeout), not tool_timeout. ``auth`` must be forwarded
- # or OAuth SSE servers 401 silently.
+ # sse_read_timeout bounds the gap between events: SSE servers idle for minutes, so 300s (the
+ # Streamable HTTP read timeout), not tool_timeout. ``auth`` must be forwarded or OAuth SSE 401s silently.
sse_kwargs: dict = {"url": url, "headers": headers or None, "timeout": float(connect_timeout),
- "sse_read_timeout": 300.0, **({"auth": oauth_auth} if oauth_auth is not None else {})}
+ "sse_read_timeout": 300.0, **_present(auth=oauth_auth)}
if client_cert is not None or ssl_verify is not True:
- # sse_client has no verify/cert kwargs: an httpx_client_factory forwards the SDK's
- # (headers, auth, timeout) and layers TLS on top. The client MUST come from the SDK's
- # own httpx module (httpx2 on mcp >= 2.0) — see sdk_httpx().
+ # sse_client has no verify/cert kwargs: an httpx_client_factory forwards the SDK's (headers,
+ # auth, timeout) and layers TLS on top. Client MUST come from the SDK's httpx (httpx2 on mcp >= 2.0).
_httpx_mod = _core.sdk_httpx()
sse_kwargs["httpx_client_factory"] = lambda headers=None, timeout=None, auth=None: _httpx_mod.AsyncClient(
follow_redirects=True, verify=ssl_verify,
timeout=timeout if timeout is not None else _httpx_mod.Timeout(30.0, read=300.0),
- **{k: v for k, v in (("headers", headers), ("auth", auth), ("cert", client_cert)) if v is not None})
+ **_present(headers=headers, auth=auth, cert=client_cert))
return _core.sse_client(**sse_kwargs)
def _streamable_http_transport(self, url: str, headers: dict, connect_timeout: float,
@@ -340,26 +330,24 @@ class MCPServerTransportMixin:
"""Streamable HTTP context manager: mcp >= 1.24.0 gets a caller-owned httpx client; on the
deprecated API (mcp < 1.24.0) the SDK owns the client."""
if not _core._MCP_NEW_HTTP:
- if strict_cfg_headers:
- # Fail closed: without an owned client redirects can't be hooked.
+ if strict_cfg_headers: # fail closed: without an owned client redirects can't be hooked
raise ImportError(f"MCP server '{self.name}' requires mcp >= 1.24.0 to "
"enforce the portable redirect-header boundary "
"(strict_redirect_headers). Upgrade the mcp package.")
return _core.streamablehttp_client(url, headers=headers, timeout=float(connect_timeout), verify=ssl_verify,
- **({"auth": oauth_auth} if oauth_auth is not None else {}))
- # Explicit AsyncClient matching the SDK's create_mcp_http_client defaults; MUST come from
- # the SDK's httpx module (httpx2 on mcp >= 2.0) since the SDK sends its own Requests through it.
+ **_present(auth=oauth_auth))
+ # Explicit AsyncClient matching the SDK's create_mcp_http_client defaults; MUST come from the
+ # SDK's httpx (httpx2 on mcp >= 2.0) since the SDK sends its own Requests through it.
httpx = _core.sdk_httpx()
_strip_auth_on_cross_origin_redirect = _make_redirect_header_stripper(
httpx.URL(url), strict=strict_cfg_headers, configured_header_names=configured_header_names)
client_kwargs: dict = {"follow_redirects": True, "timeout": httpx.Timeout(float(connect_timeout), read=300.0),
"verify": ssl_verify, **({"headers": headers} if headers else {}),
"event_hooks": {"response": [_strip_auth_on_cross_origin_redirect]},
- **{k: v for k, v in (("auth", oauth_auth), ("cert", client_cert)) if v is not None}}
+ **_present(auth=oauth_auth, cert=client_cert)}
@asynccontextmanager
- async def _owned_client_streams():
- # Caller owns the client lifecycle — the SDK skips cleanup when http_client is provided.
+ async def _owned_client_streams(): # the SDK skips cleanup when http_client is provided
async with httpx.AsyncClient(**client_kwargs) as http_client:
async with _core.streamable_http_client(url, http_client=http_client) as streams:
yield streams
@@ -376,13 +364,11 @@ class MCPServerTransportMixin:
url = config["url"]
headers = dict(config.get("headers") or {})
# Agent Plugins v1 strict_redirect_headers: configured headers MUST NOT follow a cross-origin
- # redirect. Capture their names BEFORE client-generated headers are merged in.
+ # redirect — capture their names BEFORE client-generated headers are merged in.
configured_header_names = {key.lower() for key in headers}
- # Optional per-user identity header; explicit headers of the same name win.
- headers = _apply_identity_header(self.name, config, headers)
- # Some servers require MCP-Protocol-Version on the first request; seed it (user override
- # wins) from the HANDSHAKE version, not the latest: a 2026-07-28 header would route the
- # handshake-era ``initialize()`` body onto the per-request-envelope ladder, which rejects it.
+ headers = _apply_identity_header(self.name, config, headers) # explicit same-name headers win
+ # Seed MCP-Protocol-Version (user override wins) from the HANDSHAKE version, not the latest: a
+ # 2026-07-28 header routes the handshake-era ``initialize()`` onto the envelope ladder, which rejects it.
if not any(key.lower() == "mcp-protocol-version" for key in headers):
headers["mcp-protocol-version"] = _core.LATEST_HANDSHAKE_VERSION
connect_timeout = config.get("connect_timeout", _core._DEFAULT_CONNECT_TIMEOUT)
@@ -400,8 +386,7 @@ class MCPServerTransportMixin:
async def _discover_tools(self):
"""Discover tools from the connected session. Capability-gated: prompt-/resource-only
servers raise ``MCPError(-32601)`` on ``tools/list``, which would abort the connection."""
- # Fresh transport: re-probe ``ping`` in case the server gained support across the reconnect.
- self._ping_unsupported = False
+ self._ping_unsupported = False # fresh transport: re-probe ``ping`` across the reconnect
if self.session is None:
return
if not self._advertises_tools():
@@ -416,19 +401,18 @@ class MCPServerTransportMixin:
self._register_discovered_tools_if_needed()
def _register_discovered_tools_if_needed(self) -> None:
- """Publish freshly discovered tools for a registry-owned server if none are registered
- (initial registration normally happens in ``_discover_and_register_server``). On reconnect,
- outage handling may clear ``_ready`` and deregister stale tools; ownership via ``_servers``
- authorizes publishing before readiness is restored so a revival never comes back with zero
- tools — likewise a server retained after a recoverable initial failure."""
+ """Publish freshly discovered tools when none are registered (initial registration normally
+ happens in ``_discover_and_register_server``). Outage handling may clear ``_ready`` and
+ deregister stale tools; ownership via ``_servers`` authorizes publishing before readiness is
+ restored so a revival (or a server retained after a recoverable initial failure) never comes
+ back with zero tools."""
if self._registered_tool_names:
return
- if not self._ready.is_set():
- with _core._lock:
- if _core._servers.get(self.name) is not self:
- return
- self._registered_tool_names = _core._register_server_tools(self.name, self, self._config)
- # A retained initial-failure server that just published tools has recovered.
with _core._lock:
+ owned = _core._servers.get(self.name) is self
+ if not owned and not self._ready.is_set():
+ return
+ self._registered_tool_names = _core._register_server_tools(self.name, self, self._config)
+ with _core._lock: # a retained initial-failure server that just published tools has recovered
if _core._servers.get(self.name) is self:
_core._server_connect_errors.pop(self.name, None)