The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools): inline pgid capture, merge tool-loop guard branches, drop single-use locals
Tekniuma8f0249a3127
diff --git a/tools/mcp_tool_loop.py b/tools/mcp_tool_loop.pyindex 4b86022c3bb..4cb6e56a5f3 100644--- a/tools/mcp_tool_loop.py+++ b/tools/mcp_tool_loop.py@@ -89,9 +89,8 @@ def _mcp_loop_exception_handler(loop, context):"""Suppress the benign 'Event loop is closed' RuntimeError httpx finalizers raise against thedead loop during shutdown; forward the rest."""exc = context.get("exception")- if isinstance(exc, RuntimeError) and "Event loop is closed" in str(exc):- return- loop.default_exception_handler(context)+ if not (isinstance(exc, RuntimeError) and "Event loop is closed" in str(exc)):+ loop.default_exception_handler(context)def _wrap_with_home_override(coro: "Coroutine") -> "Coroutine":diff --git a/tools/mcp_tool_sampling.py b/tools/mcp_tool_sampling.pyindex f58867c3646..aa8854597db 100644--- a/tools/mcp_tool_sampling.py+++ b/tools/mcp_tool_sampling.py@@ -133,9 +133,9 @@ class SamplingHandler:@staticmethoddef _error(message: str, code: int = -1):"""Return ErrorData (MCP spec) or raise as fallback."""- if _core._MCP_SAMPLING_TYPES:- return _core.ErrorData(code=code, message=message)- raise Exception(message)+ if not _core._MCP_SAMPLING_TYPES:+ raise Exception(message)+ return _core.ErrorData(code=code, message=message)def _fail(self, message: str):"""Count an error and return the ErrorData for it."""@@ -149,14 +149,12 @@ class SamplingHandler:def _build_tool_use_result(self, choice, response):"""CreateMessageResultWithTools from a tool_calls response, under ``max_tool_rounds`` (0 disables)."""self.metrics["tool_use_count"] += 1- if self.max_tool_rounds == 0:- self._tool_loop_count = 0- return self._error(f"Tool loops disabled for server '{self.server_name}' (max_tool_rounds=0)")self._tool_loop_count += 1- if self._tool_loop_count > self.max_tool_rounds:+ if self.max_tool_rounds == 0 or self._tool_loop_count > self.max_tool_rounds:self._tool_loop_count = 0return self._error(- f"Tool loop limit exceeded for server '{self.server_name}' (max {self.max_tool_rounds} rounds)")+ f"Tool loops disabled for server '{self.server_name}' (max_tool_rounds=0)" if self.max_tool_rounds == 0+ else f"Tool loop limit exceeded for server '{self.server_name}' (max {self.max_tool_rounds} rounds)")content_blocks = [_core.ToolUseContent(type="tool_use", id=tc.id, name=tc.function.name,input=_parse_tool_call_arguments(self.server_name, tc.function.arguments))for tc in choice.message.tool_calls]@@ -202,7 +200,6 @@ class SamplingHandler:if system_prompt:messages.insert(0, {"role": "system", "content": system_prompt})max_tokens = min(mcp_field(params, "max_tokens", "maxTokens", self.max_tokens_cap), self.max_tokens_cap)- temperature = getattr(params, "temperature", None)server_tools = getattr(params, "tools", None)tools = [{"type": "function", "function": {"name": getattr(t, "name", ""), "description": getattr(t, "description", "") or "",@@ -210,8 +207,8 @@ class SamplingHandler:for t in server_tools] if server_tools else Nonelogger.log(self.audit_level, "MCP server '%s' sampling request: model=%s, max_tokens=%d, messages=%d",self.server_name, resolved_model, max_tokens, len(messages))- return lambda: call_llm(task="mcp", model=resolved_model or None, messages=messages, temperature=temperature,- max_tokens=max_tokens, tools=tools, timeout=self.timeout)+ return lambda: call_llm(task="mcp", model=resolved_model or None, messages=messages, max_tokens=max_tokens,+ temperature=getattr(params, "temperature", None), tools=tools, timeout=self.timeout)async def __call__(self, context, params):"""SDK ``SamplingFnT``: CreateMessageResult, CreateMessageResultWithTools, or ErrorData."""@@ -303,11 +300,10 @@ class ElicitationHandler:# ``requestedSchema`` on mcp 1.x, ``requested_schema`` on 2.0 (aliases don't apply to attribute# access) — read both or the user approves without seeing the fields.schema = getattr(params, "requestedSchema", None) or getattr(params, "requested_schema", None) or {}- description = _format_elicitation_schema_summary(schema, self.server_name)logger.info("MCP server '%s' elicitation request: %s", self.server_name, _sanitize_error(message)[:200])# Lazy import avoids import-order coupling with early-bootstrap tools.approval.try:- invoke_consent = self._consent_thunk(message, description)+ invoke_consent = self._consent_thunk(message, _format_elicitation_schema_summary(schema, self.server_name))except Exception as exc: # pragma: no cover -- defensivelogger.error("MCP server '%s' elicitation: approval system unavailable: %s", self.server_name, exc)return self._result("decline", "errors")diff --git a/tools/mcp_tool_transport.py b/tools/mcp_tool_transport.pyindex b25c103184c..cf77b6c6efc 100644--- a/tools/mcp_tool_transport.py+++ b/tools/mcp_tool_transport.py@@ -29,18 +29,6 @@ def _is_2xx(resp) -> bool:return 200 <= resp.status_code < 300-def _capture_pgids(pids: Set[int]) -> Dict[int, int]:- """pgid per live pid, captured while alive (getpgid fails once it exits; the sweep needs it- to reach reparented descendants)."""- pgids: Dict[int, int] = {}- for pid in pids:- try:- pgids[pid] = os.getpgid(pid)- except (AttributeError, ProcessLookupError, OSError): # Windows / already exited- pass- return pgids--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)@@ -159,8 +147,14 @@ class MCPServerTransportMixin:# ------------------------------------------------------------------ stdiodef _track_spawned_children(self, new_pids: Set[int]) -> None:- """Ledger the freshly spawned stdio children (pids, pgids, machine spawn ledger)."""- new_pgids = _capture_pgids(new_pids)+ """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)."""+ new_pgids: Dict[int, int] = {}+ for pid in new_pids:+ try:+ new_pgids[pid] = os.getpgid(pid)+ except (AttributeError, ProcessLookupError, OSError): # Windows / already exited+ passwith _core._lock:_stdio_pids.update(dict.fromkeys(new_pids, self.name))_stdio_pgids.update(new_pgids)@@ -256,11 +250,10 @@ class MCPServerTransportMixin:except ImportError:return # No httpx → skip probe; SDK import would have failed first.- client_kwargs: dict = {"verify": ssl_verify, "follow_redirects": True, "timeout": _httpx.Timeout(timeout),- **({"cert": client_cert} if client_cert is not None else {})}probe_headers = dict(headers) if headers else {}try:- async with _httpx.AsyncClient(**client_kwargs) as client:+ 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:# 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):