refactor(mcp): join short multi-line statements across the transport/handlers subset (AST-identical)

This commit is contained in:
Teknium
2026-09-02 16:29:53 -07:00
parent 7916d8e41c
commit 304118797b
5 changed files with 14 additions and 50 deletions

View File

@@ -64,8 +64,7 @@ def _strip_reserved_meta_keys(meta) -> Optional[Dict[str, Any]]:
remains or the input wasn't a mapping."""
if not isinstance(meta, dict):
return None
out = {k: v for k, v in meta.items()
if isinstance(k, str) and not _is_reserved_mcp_meta_key(k)}
out = {k: v for k, v in meta.items() if isinstance(k, str) and (not _is_reserved_mcp_meta_key(k))}
return out or None

View File

@@ -92,10 +92,7 @@ def _unwrap_exception_group(exc: BaseException) -> BaseException:
while isinstance(leaf, BaseExceptionGroup) and leaf.exceptions:
leaf = leaf.exceptions[0]
raise leaf
exc = next(
(sub for sub in exc.exceptions if not _contains_only_cancellation(sub)),
exc.exceptions[0],
)
exc = next((sub for sub in exc.exceptions if not _contains_only_cancellation(sub)), exc.exceptions[0])
return exc
@@ -174,9 +171,7 @@ def _resolve_client_cert(server_name: str, config: dict):
def _expand(path: Any, label: str) -> str:
if not isinstance(path, str) or not path.strip():
raise ValueError(
f"{prefix}{label} must be a non-empty string path (got {type(path).__name__})"
)
raise ValueError(f"{prefix}{label} must be a non-empty string path (got {type(path).__name__})")
expanded = os.path.expanduser(path.strip())
if not os.path.isfile(expanded):
raise FileNotFoundError(f"{prefix}{label} not found at {expanded!r}")
@@ -189,9 +184,7 @@ def _resolve_client_cert(server_name: str, config: dict):
f"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)})"
)
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]"))
if len(raw_cert) == 2:
return pair
@@ -293,10 +286,7 @@ def _make_redirect_header_stripper(
def _exc_causes(exc: BaseException) -> List[BaseException]:
"""``__cause__`` then ``__context__`` of *exc*, when they are exceptions."""
return [
nested for nested in (exc.__cause__, exc.__context__)
if isinstance(nested, BaseException)
]
return [nested for nested in (exc.__cause__, exc.__context__) if isinstance(nested, BaseException)]
def _format_connect_error(exc: BaseException) -> str:

View File

@@ -169,10 +169,7 @@ def _retry_once(server_name: str, retry_call, op_description: str, what: str):
try:
result = retry_call()
except Exception as retry_exc:
logger.warning(
"MCP %s/%s retry after %s failed: %s",
server_name, op_description, what, retry_exc,
)
logger.warning("MCP %s/%s retry after %s failed: %s", server_name, op_description, what, retry_exc)
return None
if _result_is_error(result):
return None
@@ -394,9 +391,7 @@ def _invoke_with_recovery(server_name: str, call_once: Callable[[], str], op: st
if recovered is not None:
return recovered
on_final_failure(exc)
return tool_error(_sanitize_error(
f"MCP call failed: {type(exc).__name__}: {_exc_str(exc)}"
))
return tool_error(_sanitize_error(f"MCP call failed: {type(exc).__name__}: {_exc_str(exc)}"))
# ------------------------------------------------------------- the RPC itself
@@ -466,10 +461,7 @@ async def _call_tool_racing_stdio_death(server, server_name: str, tool_name: str
rpc_task = asyncio.ensure_future(_call_coro)
watch_task = asyncio.ensure_future(_watch_children())
try:
done, _pending = await asyncio.wait(
{rpc_task, watch_task},
return_when=asyncio.FIRST_COMPLETED,
)
done, _pending = await asyncio.wait({rpc_task, watch_task}, return_when=asyncio.FIRST_COMPLETED)
if watch_task in done and not rpc_task.done():
rpc_task.cancel()
raise _StdioChildExited(f"MCP stdio subprocess for '{server_name}' exited mid-call")

View File

@@ -126,10 +126,7 @@ class MCPServerHealthMixin:
origin = f"{self.name}/{logger_name}" if logger_name else self.name
logger.log(level, "MCP server log [%s]: %s", origin, data)
except Exception:
logger.debug(
"Failed to handle MCP log notification from '%s'",
self.name, exc_info=True,
)
logger.debug("Failed to handle MCP log notification from '%s'", self.name, exc_info=True)
return _on_log
def _make_message_handler(self):
@@ -196,9 +193,7 @@ class MCPServerHealthMixin:
# 1. Fetch the current tool list (follow nextCursor).
async with self._rpc_lock:
new_mcp_tools = await _core._paginate_full_list(
self.session.list_tools, "tools", self.name
)
new_mcp_tools = await _core._paginate_full_list(self.session.list_tools, "tools", self.name)
# 2. Remove only stale names first — no nuke-and-repave: live agent
# turns may hold tool-call IDs pointing at existing handlers, and

View File

@@ -181,10 +181,7 @@ class MCPServerTransportMixin:
self._session_proven = False
reason = await self._wait_for_lifecycle_event()
if label and reason == "reconnect":
logger.info(
"MCP server '%s': reconnect requested — tearing down %s session",
self.name, label,
)
logger.info("MCP server '%s': reconnect requested — tearing down %s session", self.name, label)
return reason
async def _serve_transport(self, transport_cm, label: str, connect_timeout: float) -> str:
@@ -230,10 +227,7 @@ class MCPServerTransportMixin:
register_child(_pid, "mcp-helper")
except Exception:
logger.debug(
"spawn-ledger register_child failed for MCP helper pid %s",
_pid, exc_info=True,
)
logger.debug("spawn-ledger register_child failed for MCP helper pid %s", _pid, exc_info=True)
def _release_spawned_children(self, new_pids: Set[int]) -> None:
"""Drop the ledger entries; any child (or its pgroup) still alive means SDK
@@ -323,9 +317,7 @@ class MCPServerTransportMixin:
# never answers ``initialize`` would otherwise hang here forever,
# the ``finally`` below would never run, and the child + pipes
# would leak on every retry until EMFILE.
connect_timeout = float(
config.get("connect_timeout", _core._DEFAULT_CONNECT_TIMEOUT)
)
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.
@@ -553,11 +545,7 @@ class MCPServerTransportMixin:
"enforce the portable redirect-header boundary "
"(strict_redirect_headers). Upgrade the mcp package."
)
http_kwargs: dict = {
"headers": headers,
"timeout": float(connect_timeout),
"verify": ssl_verify,
}
http_kwargs: dict = {"headers": headers, "timeout": float(connect_timeout), "verify": ssl_verify}
if oauth_auth is not None:
http_kwargs["auth"] = oauth_auth
return _core.streamablehttp_client(url, **http_kwargs)