Skip to content

The agent that grows with you

refactor(tools): MCP group L docstring rewrap

Teknium9458f4c27a42
diff --git a/tools/mcp_oauth_manager.py b/tools/mcp_oauth_manager.py
index 2ca0fe2cd19..f5cb5f52ea4 100644
--- a/tools/mcp_oauth_manager.py
+++ b/tools/mcp_oauth_manager.py
@@ -1,10 +1,9 @@
-"""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."""
+"""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
@@ -171,12 +170,11 @@ class HermesMCPOAuthProvider(HermesProviderMixin, *_SDK_BASES):
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
- cached registration is dead server-side: delete ``client.json`` (+ stale metadata) so the
- SDK re-runs DCR next flow. Conservative: acts ONLY on 400/401 at the discovered
- ``token_endpoint`` (the only request carrying our ``client_id``) with ``invalid_client``
- 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``)."""
+ """An ``invalid_client`` rejection of our ``client_id`` at the token endpoint proves the cached registration
+ is dead server-side: delete ``client.json`` (+ stale metadata) so the SDK re-runs DCR next flow.
+ Conservative: acts ONLY on 400/401 at the discovered ``token_endpoint`` (the only request carrying our
+ ``client_id``) with ``invalid_client`` 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)
or not await self._is_invalid_client_at_token_endpoint(response)):
@@ -370,10 +368,9 @@ class MCPOAuthManager:
entry.pending_401.pop(key, None)
async def handle_401(self, server_name: str, failed_access_token: Optional[str] = None) -> bool:
- """Handle a 401 from a tool call. True: a (possibly new) token is available — reconnect
- and retry. False: no recovery path — surface ``needs_reauth`` so the model stops
- hallucinating manual refreshes. Concurrent 401s with the same ``failed_access_token``
- fire one recovery attempt; the rest await its future."""
+ """Handle a 401 from a tool call. True: a (possibly new) token is available — reconnect and retry. False: no
+ recovery path — surface ``needs_reauth`` so the model stops hallucinating manual refreshes. Concurrent 401s
+ with the same ``failed_access_token`` fire one recovery attempt; the rest await its future."""
entry = self._entries.get(self._key(server_name))
if entry is None or entry.provider is None:
return False
diff --git a/tools/mcp_tool_errors.py b/tools/mcp_tool_errors.py
index 9ab2e50e891..e56bd4cc88a 100644
--- a/tools/mcp_tool_errors.py
+++ b/tools/mcp_tool_errors.py
@@ -20,9 +20,8 @@ _JSONRPC_UNSUPPORTED_PROTOCOL_VERSION = -32022
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."""
+ """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)
@@ -293,12 +292,11 @@ _EXC_TRAVERSAL_MAX_NODES = 10_000
def _is_session_expired_error(exc: BaseException) -> bool:
- """True if ``exc`` looks like a transport session expiry (Streamable-HTTP servers GC session
- state on idle TTL / restart / pod rotation while the OAuth token stays valid) — the fix is a
- transport reconnect, not an OAuth refresh. Iterative walk over ``exceptions`` / ``__cause__`` /
- ``__context__`` with a visited set AND a node budget; every reachable node is inspected so an
- InterruptedError anywhere overrides transport markers, and the chain walk matters because SDK
- wrappers raise a generic RuntimeError *from* a message-less ClosedResourceError."""
+ """True if ``exc`` looks like a transport session expiry (Streamable-HTTP servers GC session state on idle TTL /
+ restart / pod rotation while the OAuth token stays valid) — the fix is a transport reconnect, not an OAuth
+ refresh. Iterative walk over ``exceptions`` / ``__cause__`` / ``__context__`` with a visited set AND a node
+ budget; every reachable node is inspected so an InterruptedError anywhere overrides transport markers, and the
+ chain walk matters because SDK wrappers raise a generic RuntimeError *from* a message-less ClosedResourceError."""
# AnyIO stream exceptions are often message-less, so type checks complement marker matching.
transport_error_types = tuple(_optional_types("anyio", "BrokenResourceError", "ClosedResourceError", "EndOfStream"))
stack: "list[BaseException | None]" = [exc]
diff --git a/tools/mcp_tool_handlers.py b/tools/mcp_tool_handlers.py
index 832d0c7066c..69b5c40341a 100644
--- a/tools/mcp_tool_handlers.py
+++ b/tools/mcp_tool_handlers.py
@@ -1,6 +1,5 @@
-"""Registry-facing sync handlers for MCP tools and utility tools (resources/prompts), plus
-the per-call recovery ladder: trust gating, circuit breaker, auth (401) refresh,
-session-expired reconnect and dead-stdio respawn retry."""
+"""Registry-facing sync handlers for MCP tools and utility tools (resources/prompts), plus the per-call recovery
+ladder: trust gating, circuit breaker, auth (401) refresh, session-expired reconnect and dead-stdio respawn retry."""
import logging
import asyncio
diff --git a/tools/mcp_tool_health.py b/tools/mcp_tool_health.py
index c90db405b24..93d8576af30 100644
--- a/tools/mcp_tool_health.py
+++ b/tools/mcp_tool_health.py
@@ -130,9 +130,8 @@ class MCPServerHealthMixin:
_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
- rapid-fire notifications; after the list_tools ``await`` all mutations are synchronous —
- atomic on the event loop."""
+ """Re-fetch tools on ``tools/list_changed`` and update the registry. The lock serializes rapid-fire
+ notifications; after the list_tools ``await`` all mutations are synchronous — atomic on the event loop."""
if not self._advertises_tools():
return # tools/list would raise MCPError(-32601)
async with self._refresh_lock:
diff --git a/tools/mcp_tool_registration.py b/tools/mcp_tool_registration.py
index 75958736561..a09f393107c 100644
--- a/tools/mcp_tool_registration.py
+++ b/tools/mcp_tool_registration.py
@@ -46,9 +46,8 @@ def _annotation_read_only_hint(mcp_tool: Any) -> bool:
def _record_tool_trust_metadata(server_name: str, config: dict, tools: List[Any]) -> None:
- """Capture per-server trust and per-tool readOnlyHint at discovery — the security
- boundary: the call-time gate classifies from data we control, never re-read
- server-supplied state."""
+ """Capture per-server trust and per-tool readOnlyHint at discovery — the security boundary: the call-time gate
+ classifies from data we control, never re-read server-supplied state."""
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, {})
@@ -109,9 +108,8 @@ def _existing_tool_names() -> List[str]:
def _make_tool_filter(name: str, config: dict) -> Callable[[str], bool]:
- """Include/exclude predicate for a server's tool names: ``tools.include`` is a whitelist
- (``[]`` = register nothing), ``tools.exclude`` a blacklist; entries are exact names or
- fnmatch globs; include wins over exclude."""
+ """Include/exclude predicate for a server's tool names: ``tools.include`` is a whitelist (``[]`` = register
+ nothing), ``tools.exclude`` a blacklist; entries are exact names or fnmatch globs; include wins over exclude."""
tools_filter = config.get("tools") or {}
include_raw = tools_filter.get("include")
include_set = _normalize_name_filter(include_raw, f"mcp_servers.{name}.tools.include")
diff --git a/tools/mcp_tool_transport.py b/tools/mcp_tool_transport.py
index 29721bb977a..5eb98b14818 100644
--- a/tools/mcp_tool_transport.py
+++ b/tools/mcp_tool_transport.py
@@ -1,6 +1,5 @@
-"""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."""
+"""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."""
import logging
import asyncio
@@ -273,12 +272,11 @@ class MCPServerTransportMixin:
"HTTP / SSE endpoint (e.g. https://host/mcp, not https://host/).")
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 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)."""
+ """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 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
@@ -401,11 +399,10 @@ class MCPServerTransportMixin:
self._register_discovered_tools_if_needed()
def _register_discovered_tools_if_needed(self) -> None:
- """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."""
+ """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
with _core._lock: