Skip to content

The agent that grows with you

refactor(tools): flatten identity-header/loop-stop control flow, inline SSE client factory

Tekniumf7a4ccc081ad
diff --git a/tools/mcp_tool_errors.py b/tools/mcp_tool_errors.py
index 5f3d95853f0..91ff0395187 100644
--- a/tools/mcp_tool_errors.py
+++ b/tools/mcp_tool_errors.py
@@ -64,9 +64,8 @@ def _unwrap_exception_group(exc: BaseException) -> BaseException:
``KeyboardInterrupt``/``SystemExit`` leaf anywhere is re-raised, never flattened into a loggable
error; a non-cancellation leaf is preferred over the ``CancelledError`` noise anyio sprays on siblings."""
while isinstance(exc, BaseExceptionGroup) and exc.exceptions:
- fatal, _rest = exc.split((KeyboardInterrupt, SystemExit))
- if fatal is not None:
- leaf: BaseException = fatal
+ leaf: BaseException = exc.split((KeyboardInterrupt, SystemExit))[0]
+ if leaf is not None:
while isinstance(leaf, BaseExceptionGroup) and leaf.exceptions:
leaf = leaf.exceptions[0]
raise leaf
@@ -85,12 +84,11 @@ def _classify_mcp_failure(exc: BaseException) -> str:
"""``'permanent'`` (``run()`` parks instead of burning the retry ladder: auth 401/403,
NonMcpEndpointError, InvalidMcpUrlError, missing stdio command) or ``'transient'`` (backoff retry)."""
root = _unwrap_exception_group(exc)
- permanent = (
- _core._is_auth_error(root)
- or isinstance(root, (NonMcpEndpointError, InvalidMcpUrlError, FileNotFoundError))
- or (isinstance(root, OSError) and getattr(root, "errno", None) == errno.ENOENT)
- # 401/403 HTTPStatusError that _is_auth_error's type-gate missed (auth types not importable here).
- or getattr(getattr(root, "response", None), "status_code", None) in (401, 403))
+ permanent = (_core._is_auth_error(root)
+ or isinstance(root, (NonMcpEndpointError, InvalidMcpUrlError, FileNotFoundError))
+ or (isinstance(root, OSError) and getattr(root, "errno", None) == errno.ENOENT)
+ # 401/403 HTTPStatusError that _is_auth_error's type-gate missed (auth types not importable here)
+ or getattr(getattr(root, "response", None), "status_code", None) in (401, 403))
return "permanent" if permanent else "transient"
@@ -170,24 +168,23 @@ def _resolve_identity_header(server_name: str, config: dict):
if not isinstance(name, str) or not name.strip():
return _ignore("requires a non-empty 'name'")
value_from = (raw.get("value_from") or "static").strip().lower()
- if value_from == "static":
- value = raw.get("value")
- if not isinstance(value, str) or not value.strip():
- return _ignore("with value_from: static requires a non-empty string 'value'")
- return (name.strip(), value)
if value_from == "profile":
from hermes_cli.profiles import get_active_profile_name
return (name.strip(), get_active_profile_name())
- return _ignore("value_from must be 'static' or 'profile' (got %r)", value_from)
+ if value_from != "static":
+ return _ignore("value_from must be 'static' or 'profile' (got %r)", value_from)
+ value = raw.get("value")
+ if not isinstance(value, str) or not value.strip():
+ return _ignore("with value_from: static requires a non-empty string 'value'")
+ return (name.strip(), value)
def _apply_identity_header(server_name: str, config: dict, headers: dict) -> dict:
"""Merge the identity header into ``headers`` in place; an explicit entry of the same name (any
casing) wins — never silently override user config."""
- resolved = _resolve_identity_header(server_name, config)
- if resolved is None:
+ name, value = _resolve_identity_header(server_name, config) or (None, None)
+ if name is None:
return headers
- name, value = resolved
if any(key.lower() == name.lower() for key in headers):
logger.debug("MCP server '%s': identity_header '%s' already set via explicit "
"headers config — keeping the explicit value", server_name, name)
@@ -210,10 +207,9 @@ def _make_redirect_header_stripper(original_url, *, strict: bool = False,
headers = response.next_request.headers
headers.pop("authorization", None)
headers.pop("Authorization", None)
- if strict:
- for _name in configured_header_names:
- while _name in headers:
- del headers[_name]
+ for _name in configured_header_names if strict else ():
+ while _name in headers:
+ del headers[_name]
return _strip_on_cross_origin_redirect
diff --git a/tools/mcp_tool_loop.py b/tools/mcp_tool_loop.py
index 4cb6e56a5f3..ff1b69903f7 100644
--- a/tools/mcp_tool_loop.py
+++ b/tools/mcp_tool_loop.py
@@ -202,8 +202,7 @@ def _wait_for_server_session_ready(srv: Any, *, old_session: Any = None, timeout
"""Poll until the server exposes a usable, ready session (during a reconnect ``srv.session`` is
briefly None or stale; retrying blindly burns breaker strikes). With ``old_session`` the observed
session must differ. Iteration-bounded, not deadline-bounded: tests freeze ``time.monotonic``."""
- poll_interval = 0.25
- iterations = max(1, int(max(float(timeout), 0.0) / poll_interval))
+ iterations = max(1, int(max(float(timeout), 0.0) / 0.25))
for i in range(iterations):
session = getattr(srv, "session", None)
ready = getattr(srv, "_ready", None)
@@ -214,7 +213,7 @@ def _wait_for_server_session_ready(srv: Any, *, old_session: Any = None, timeout
if session is not None and session is not old_session and is_ready:
return True
if i < iterations - 1:
- time.sleep(poll_interval)
+ time.sleep(0.25)
return False
@@ -224,11 +223,11 @@ def _signal_reconnect_and_wait(server_name: str, srv: Any, *, op_description: st
loop = _core._mcp_loop
if loop is None or not loop.is_running():
return False
+
def _request_reconnect() -> None:
- ready = getattr(srv, "_ready", None)
+ ready, reconnect_event = getattr(srv, "_ready", None), getattr(srv, "_reconnect_event", None)
if hasattr(ready, "clear"):
ready.clear()
- reconnect_event = getattr(srv, "_reconnect_event", None)
if hasattr(reconnect_event, "set"):
reconnect_event.set()
@@ -245,10 +244,9 @@ def _ensure_mcp_loop():
with _core._lock:
if _origin._mcp_loop is not None and _origin._mcp_loop.is_running():
return
- _origin._mcp_loop = asyncio.new_event_loop()
- _origin._mcp_loop.set_exception_handler(_core._mcp_loop_exception_handler)
- _origin._mcp_thread = threading.Thread(
- target=_origin._mcp_loop.run_forever, name="mcp-event-loop", daemon=True)
+ loop = _origin._mcp_loop = asyncio.new_event_loop()
+ loop.set_exception_handler(_core._mcp_loop_exception_handler)
+ _origin._mcp_thread = threading.Thread(target=loop.run_forever, name="mcp-event-loop", daemon=True)
_origin._mcp_thread.start()
@@ -259,43 +257,41 @@ def _stop_mcp_loop(*, only_if_idle: bool = False) -> bool:
if only_if_idle and (_core._servers or _core._server_connecting):
logger.debug("Leaving MCP event loop running; active servers are registered or connecting")
return False
- loop = _origin._mcp_loop
- thread = _origin._mcp_thread
- _origin._mcp_loop = None
- _origin._mcp_thread = None
- if loop is not None:
- # Drain before stopping: tasks still suspended when the loop closes get resumed by the GC
- # against a closed loop. shutdown_mcp_servers only reaps _servers; everything else ends here.
- future = None
- if loop.is_running():
- from agent.async_utils import safe_schedule_threadsafe
-
- future = safe_schedule_threadsafe(
- _core._drain_and_stop_mcp_loop(), loop, logger=logger,
- log_message="MCP loop drain: failed to schedule", log_level=logging.WARNING)
- if future is not None:
- try:
- future.result(timeout=_core._MCP_LOOP_DRAIN_TIMEOUT + 1)
- except TimeoutError:
- logger.warning("Timed out waiting for MCP loop drain after %.1fs",
- _core._MCP_LOOP_DRAIN_TIMEOUT + 1)
- except BaseException as exc:
- logger.warning("Error draining MCP loop tasks: %s", exc)
- elif not loop.is_closed():
+ loop, thread = _origin._mcp_loop, _origin._mcp_thread
+ _origin._mcp_loop = _origin._mcp_thread = None
+ if loop is None:
+ return True
+ # Drain before stopping: tasks still suspended when the loop closes get resumed by the GC
+ # against a closed loop. shutdown_mcp_servers only reaps _servers; everything else ends here.
+ future = None
+ if loop.is_running():
+ from agent.async_utils import safe_schedule_threadsafe
+
+ future = safe_schedule_threadsafe(
+ _core._drain_and_stop_mcp_loop(), loop, logger=logger,
+ log_message="MCP loop drain: failed to schedule", log_level=logging.WARNING)
+ if future is not None:
try:
- loop.run_until_complete(_core._drain_mcp_loop_tasks(timeout=_core._MCP_LOOP_DRAIN_TIMEOUT))
+ future.result(timeout=_core._MCP_LOOP_DRAIN_TIMEOUT + 1)
+ except TimeoutError:
+ logger.warning("Timed out waiting for MCP loop drain after %.1fs", _core._MCP_LOOP_DRAIN_TIMEOUT + 1)
except BaseException as exc:
- logger.warning("Error draining stopped MCP loop tasks: %s", exc)
- if future is None and loop.is_running(): # drain-and-stop wasn't scheduled: stop it ourselves
- loop.call_soon_threadsafe(loop.stop)
- if thread is not None:
- thread.join(timeout=5)
- if thread.is_alive():
- logger.warning("MCP event loop thread did not stop within 5.0s")
+ logger.warning("Error draining MCP loop tasks: %s", exc)
+ elif not loop.is_closed():
try:
- loop.close()
- except Exception as exc:
- logger.warning("Unable to close MCP event loop cleanly: %s", exc)
- # The loop is gone, so no session can be in flight: reap active too.
- _core._kill_orphaned_mcp_children(include_active=True)
+ loop.run_until_complete(_core._drain_mcp_loop_tasks(timeout=_core._MCP_LOOP_DRAIN_TIMEOUT))
+ except BaseException as exc:
+ logger.warning("Error draining stopped MCP loop tasks: %s", exc)
+ if future is None and loop.is_running(): # drain-and-stop wasn't scheduled: stop it ourselves
+ loop.call_soon_threadsafe(loop.stop)
+ if thread is not None:
+ thread.join(timeout=5)
+ if thread.is_alive():
+ logger.warning("MCP event loop thread did not stop within 5.0s")
+ try:
+ loop.close()
+ except Exception as exc:
+ logger.warning("Unable to close MCP event loop cleanly: %s", exc)
+ # The loop is gone, so no session can be in flight: reap active too.
+ _core._kill_orphaned_mcp_children(include_active=True)
return True
diff --git a/tools/mcp_tool_sampling.py b/tools/mcp_tool_sampling.py
index 0d2797618da..a9ea21ba8c9 100644
--- a/tools/mcp_tool_sampling.py
+++ b/tools/mcp_tool_sampling.py
@@ -175,8 +175,7 @@ class SamplingHandler:
logger.warning("MCP server '%s' sampling rate limit exceeded (%d/min)", self.server_name, self.max_rpm)
return None, self._fail(
f"Sampling rate limit exceeded for server '{self.server_name}' ({self.max_rpm} requests/minute)")
- model = self._resolve_model(mcp_field(params, "model_preferences", "modelPreferences"))
- resolved_model = model or self.model_override or ""
+ resolved_model = self._resolve_model(mcp_field(params, "model_preferences", "modelPreferences")) or ""
if self.allowed_models and resolved_model and resolved_model not in self.allowed_models:
logger.warning("MCP server '%s' requested model '%s' not in allowed_models",
self.server_name, resolved_model)
@@ -208,7 +207,7 @@ class SamplingHandler:
resolved_model, err = self._admit(params)
if err is not None:
return err
- sync_call = self._build_llm_call(params, resolved_model)
+ sync_call = self._build_llm_call(params, resolved_model) # outside the try: its errors propagate, not _fail
try:
response = await asyncio.wait_for(asyncio.to_thread(sync_call), timeout=self.timeout)
except asyncio.TimeoutError:
diff --git a/tools/mcp_tool_transport.py b/tools/mcp_tool_transport.py
index b87e618d8f9..d313555636f 100644
--- a/tools/mcp_tool_transport.py
+++ b/tools/mcp_tool_transport.py
@@ -207,8 +207,7 @@ class MCPServerTransportMixin:
# 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.
await asyncio.to_thread(_core._kill_orphaned_mcp_children)
- # Snapshot child PIDs before spawning so the new one can be identified.
- pids_before = _core._snapshot_child_pids()
+ 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)
@@ -331,14 +330,10 @@ class MCPServerTransportMixin:
# (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().
_httpx_mod = _core.sdk_httpx()
-
- def _mcp_http_client_factory(headers=None, timeout=None, auth=None):
- return _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})
-
- sse_kwargs["httpx_client_factory"] = _mcp_http_client_factory
+ 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})
return _core.sse_client(**sse_kwargs)
def _streamable_http_transport(self, url: str, headers: dict, connect_timeout: float,