Skip to content

The agent that grows with you

refactor(mcp): extract atomic snapshot publish from refresh_agent_mcp_tools; compact docstrings by hand

Tekniumade852f1d559
diff --git a/tools/mcp_schema_cache.py b/tools/mcp_schema_cache.py
index 48ce08c12f2..1218a23593c 100644
--- a/tools/mcp_schema_cache.py
+++ b/tools/mcp_schema_cache.py
@@ -58,23 +58,17 @@ def _load_all() -> Dict[str, Any]:
def _save_all(data: Dict[str, Any]) -> None:
from utils import atomic_json_write
- # Cache dir + 0o600: sibling precedent in tools/registry.py
- # _save_discovery_cache; the cache file is trusted input on the lazy
- # registration path, so keep it user-only.
+ # 0o600 (as tools/registry.py _save_discovery_cache): the cache file is
+ # trusted input on the lazy registration path, so keep it user-only.
atomic_json_write(_cache_path(), data, mode=0o600)
def get_cached_entry(server_name: str, fingerprint: str) -> Optional[dict]:
"""Return cached entry when fingerprint matches (and TTL holds), else None.
-
- MCP 2026-07-28 (SEP-2549): ``tools/list`` results carry ``ttlMs`` as a
- freshness hint. When the live discovery path recorded one, an entry
- older than its TTL is treated as a miss so the next startup re-probes
- the server instead of serving a stale manifest forever. Entries without
- a recorded TTL (pre-2026 servers) keep the old never-expires behavior.
- ``cacheScope`` is irrelevant here: this cache is per-user local disk,
- which satisfies even ``private``.
- """
+ ``tools/list`` results may carry ``ttlMs`` (SEP-2549); an entry older than a
+ recorded TTL is a miss so the next startup re-probes instead of serving a
+ stale manifest forever. Entries without a TTL never expire. ``cacheScope``
+ is irrelevant: this cache is per-user local disk, satisfying even ``private``."""
with _cache_lock:
entry = _load_all().get(server_name)
if not isinstance(entry, dict) or entry.get("fingerprint") != fingerprint:
@@ -98,12 +92,9 @@ def write_cache_entry(
ttl_ms: Optional[float] = None,
cache_scope: Optional[str] = None,
) -> None:
- """Persist tool schemas after a successful live connect.
-
- ``ttl_ms``/``cache_scope`` are the SEP-2549 hints from the server's
- ``tools/list`` result (2026-07-28 servers). ``written_at`` anchors TTL
- expiry in :func:`get_cached_entry`.
- """
+ """Persist tool schemas after a successful live connect. ``ttl_ms`` /
+ ``cache_scope`` are the server's ``tools/list`` SEP-2549 hints;
+ ``written_at`` anchors TTL expiry in :func:`get_cached_entry`."""
entry = {"fingerprint": fingerprint, "tools": tools, "utility_tools": utility_tools or []}
if isinstance(ttl_ms, (int, float)):
entry["ttl_ms"] = ttl_ms
@@ -112,12 +103,10 @@ def write_cache_entry(
entry["cache_scope"] = cache_scope
with _cache_lock:
data = _load_all()
- # Write-through fires on every registration (reconnects,
- # list_changed refreshes); skip the load-all+rewrite churn when the
- # entry is byte-identical to what is already on disk. TTL'd entries
- # always rewrite: written_at must advance or the entry would expire
- # at its ORIGINAL write time no matter how many live reconnects
- # confirmed it since.
+ # Write-through fires on every registration (reconnects, list_changed);
+ # skip the load-all+rewrite churn when the entry is byte-identical on
+ # disk. TTL'd entries always rewrite: written_at must advance or the
+ # entry would expire at its ORIGINAL write time regardless of reconnects.
if "written_at" not in entry and data.get(server_name) == entry:
return
data[server_name] = entry
diff --git a/tools/mcp_stdio_watchdog.py b/tools/mcp_stdio_watchdog.py
index fa0570f9cdc..e7b29a105b0 100644
--- a/tools/mcp_stdio_watchdog.py
+++ b/tools/mcp_stdio_watchdog.py
@@ -1,21 +1,18 @@
#!/usr/bin/env python3
"""Parent-death watchdog supervisor for stdio MCP subprocesses.
-If Hermes dies hard (kill -9, crash, force-quit), its graceful teardown never
-runs and the stdio child plus its descendants are orphaned; macOS has no
-``PR_SET_PDEATHSIG`` equivalent. Piled-up orphans then race the legitimate new
-connection for the same upstream session. So the MCP command is spawned via
-this supervisor, which:
- 1. runs the real command as its own child in a new process group (so the
- whole tree can be killpg'd);
- 2. passes stdin/stdout/stderr straight through — the MCP stdio protocol
- talks over those pipes, so this must be a no-op relay, not a proxy;
- 3. polls ``getppid()`` against the recorded parent PID and, when the parent
- is gone, SIGTERMs the child's group, waits, then SIGKILLs.
-
-Standard-library only so it starts fast and cannot itself leak.
-
-Usage (see ``tools/mcp_tool.py::_run_stdio``)::
+If Hermes dies hard (kill -9, crash, force-quit) its graceful teardown never
+runs and the stdio child plus its descendants are orphaned (macOS has no
+``PR_SET_PDEATHSIG``); piled-up orphans then race the legitimate new connection
+for the same upstream session. So the MCP command is spawned via this
+supervisor, which (1) runs the real command as its own child in a new process
+group so the whole tree can be killpg'd, (2) passes stdin/stdout/stderr straight
+through — the MCP stdio protocol talks over those pipes, so this must be a
+no-op relay, not a proxy — and (3) polls ``getppid()`` against the recorded
+parent PID and, once the parent is gone, SIGTERMs the child's group, waits,
+then SIGKILLs. Standard-library only so it starts fast and cannot itself leak.
+
+Usage (see ``_wrap_command_with_watchdog``)::
python3 -m tools.mcp_stdio_watchdog \\
--ppid <original_parent_pid> -- <real_command> <arg1> <arg2> ...
@@ -41,9 +38,9 @@ def _is_orphaned(original_ppid: int, getppid=os.getppid) -> bool:
def _terminate_process_group(proc: subprocess.Popen) -> None:
- """Best-effort SIGTERM-then-SIGKILL of the child's process group. Only runs
- on POSIX in practice, but guards the POSIX-only primitives so an accidental
- Windows run degrades to a plain child kill instead of AttributeError."""
+ """Best-effort SIGTERM-then-SIGKILL of the child's process group; guards the
+ POSIX-only primitives so an accidental Windows run degrades to a plain child
+ kill instead of AttributeError."""
killpg = getattr(os, "killpg", None)
if killpg is None: # windows-footgun: ok — non-POSIX fallback
try:
@@ -90,14 +87,13 @@ def main(argv: list[str] | None = None) -> int:
print("mcp_stdio_watchdog: no command given after '--'", file=sys.stderr)
return 2
- # New process group so we can killpg() the whole tree the real command may
- # spawn, without touching our own group or the original parent's.
+ # New process group: killpg() reaches the whole tree the real command may
+ # spawn without touching our own group or the original parent's.
proc = subprocess.Popen(real_argv, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr, start_new_session=True)
- # The server lives in its OWN group, so the parent's shutdown killpg of
- # *our* group no longer reaches it. Forward SIGTERM/SIGINT to the child's
- # group so graceful teardown still kills a wedged server that ignores stdin
- # EOF — otherwise the wrap would invert the bug it fixes.
+ # The server lives in its OWN group, so the parent's shutdown killpg of *our*
+ # group no longer reaches it: forward SIGTERM/SIGINT to the child's group so
+ # graceful teardown still kills a wedged server that ignores stdin EOF.
def _forward_shutdown(signum, frame): # noqa: ARG001
_terminate_process_group(proc)
sys.exit(128 + signum)
diff --git a/tools/mcp_tool_agent.py b/tools/mcp_tool_agent.py
index 2722d1b35bb..7e921ca5738 100644
--- a/tools/mcp_tool_agent.py
+++ b/tools/mcp_tool_agent.py
@@ -5,6 +5,7 @@ and re-injecting post-build tools."""
import logging
import json
import threading
+from typing import Optional
from tools.mcp_tool_common import _core
logger = logging.getLogger("tools.mcp_tool")
@@ -48,6 +49,39 @@ def _tool_defs_content_changed(agent, new_defs: list) -> bool:
return False
+def _publish_tool_snapshot(agent, new_defs: list, new_names: set, *, snapshot_generation: int,
+ staged_engine_names: set, content_aware: bool, prefix_registered: Optional[set]) -> Optional[set]:
+ """Single atomic read-diff-publish under ``_agent_tools_lock`` so ``added``
+ matches what was published and a stale (older-generation) rebuild can't
+ overwrite a newer one. Returns the added names, or None when nothing was
+ published (unchanged, or a newer snapshot already won)."""
+ with _agent_tools_lock:
+ # Tolerate an agent that never set the generation (or a non-int mock)
+ # rather than failing the whole refresh on the comparison.
+ published_gen = getattr(agent, "_tool_snapshot_generation", -1)
+ published_gen = published_gen if isinstance(published_gen, int) else -1
+ if snapshot_generation < published_gen:
+ return None # a newer snapshot already won
+ current_defs = _agent_tool_defs(agent)
+ current = {_def_name(t) for t in current_defs}
+ if prefix_registered is not None:
+ new_defs, new_names = _merge_preserving_prefix(current_defs, new_defs, prefix_registered)
+ # Record the generation even when unchanged so an in-flight older caller can't clobber.
+ agent._tool_snapshot_generation = max(published_gen, snapshot_generation)
+ # Same NAME set: no change for MCP-reload callers. Content-aware callers
+ # (compaction boundary) also diff serialized bytes.
+ if new_names == current and not (content_aware and _tool_defs_content_changed(agent, new_defs)):
+ return None
+ agent.tools = new_defs
+ agent.valid_tool_names = new_names
+ # Publish context-engine routing names atomically with the snapshot.
+ engine_names = getattr(agent, "_context_engine_tool_names", None)
+ if isinstance(engine_names, set):
+ engine_names.clear()
+ engine_names.update(staged_engine_names)
+ return new_names - current
+
+
def refresh_agent_mcp_tools(
agent,
*,
@@ -57,85 +91,55 @@ def refresh_agent_mcp_tools(
content_aware: bool = False,
preserve_prefix: bool = False,
) -> set:
- """Re-derive an already-built agent's tool snapshot from the live registry.
-
- The agent snapshots ``agent.tools`` once at build time; servers that connect
- later (slow OAuth server, ``/reload-mcp``) are invisible until rebuilt. This
- is the single shared rebuild for the TUI RPC, gateway reload, late-binding
- thread and between-turns refresh. It respects the agent's own toolset
- filter, diffs by tool NAME (a count compare misses an equal-size swap), and
- is additive-preserving: memory-provider and context-engine (``lcm_*``) tools
- that ``agent_init`` appends after ``get_tool_definitions`` are re-injected,
- since a naive rebuild would silently delete them. ``(tools, valid_tool_names)``
- are published together under ``_agent_tools_lock``.
+ """Re-derive an already-built agent's tool snapshot from the live registry;
+ returns the newly-added tool names (empty when unchanged).
+
+ The agent snapshots ``agent.tools`` once at build time, so servers that
+ connect later (slow OAuth server, ``/reload-mcp``) are invisible until
+ rebuilt. Single shared rebuild for the TUI RPC, gateway reload, late-binding
+ thread and between-turns refresh: respects the agent's toolset filter, diffs
+ by tool NAME (a count compare misses an equal-size swap), re-injects the
+ memory-provider / context-engine (``lcm_*``) tools ``agent_init`` appends
+ after ``get_tool_definitions`` (a naive rebuild would drop them), and
+ publishes ``(tools, valid_tool_names)`` together under ``_agent_tools_lock``.
``preserve_prefix`` is for rebuilds inside a live conversation, where the
tool array is a cached request prefix and any moved byte re-prefills the
whole history: existing tools keep their slot (schemas still refresh), a
still-registered tool whose ``check_fn`` merely flapped is carried forward,
- a tool that left the registry is dropped, and new tools append at the tail.
- Carrying an unavailable tool forward is safe: ``check_fn`` gates exposure,
- never invocation, and every handler owns its own unavailability error.
-
- Returns the newly-added tool names (empty when unchanged). The caller owns
- the prompt-cache contract (turn-boundary policy differs per caller).
- """
+ a deregistered tool is dropped, new tools append at the tail. Carrying an
+ unavailable tool forward is safe: ``check_fn`` gates exposure, never
+ invocation. The caller owns the prompt-cache contract (turn-boundary policy
+ differs per caller)."""
from model_tools import get_tool_definitions
from tools.registry import registry
enabled, disabled = _resolve_refresh_toolsets(agent, enabled_override, disabled_override)
-
# Capture the registry generation BEFORE the slow get_tool_definitions call;
# at publish time a slower caller holding an OLDER set must not clobber a
# newer set another caller already published.
snapshot_generation = registry._generation
-
# Computed OUTSIDE the lock (can be slow); diff + publish happen together in
# one critical section so concurrent callers can't torn-publish.
new_defs = list(get_tool_definitions(enabled_toolsets=enabled, disabled_toolsets=disabled, quiet_mode=quiet_mode) or [])
new_names = {_def_name(t) for t in new_defs}
-
# Re-append the post-build families on LOCALS only; live agent attributes
- # are untouched until the single atomic publish below.
+ # are untouched until the single atomic publish.
staged_engine_names = _core._reinject_post_build_tools(agent, new_defs, new_names)
-
# Registry membership is read OUTSIDE ``_agent_tools_lock``: taking
# ``registry._lock`` under the tools lock would be the first nesting of the two.
- registered_names: set = set()
+ prefix_registered: Optional[set] = None
if preserve_prefix:
try:
- registered_names = {entry.name for entry in registry.get_all_entries()}
+ prefix_registered = {entry.name for entry in registry.get_all_entries()}
except Exception: # noqa: BLE001
- preserve_prefix = False # fail open to the plain rebuild
-
- # Single atomic read-diff-publish so ``added`` matches what was published
- # and a stale (older-generation) rebuild can't overwrite a newer one.
- with _agent_tools_lock:
- # Tolerate an agent that never set the generation (or a non-int mock)
- # rather than failing the whole refresh on the comparison.
- published_gen_raw = getattr(agent, "_tool_snapshot_generation", -1)
- published_gen = published_gen_raw if isinstance(published_gen_raw, int) else -1
- if snapshot_generation < published_gen:
- return set() # a newer snapshot already won
- current_defs = _agent_tool_defs(agent)
- current = {_def_name(t) for t in current_defs}
- if preserve_prefix:
- new_defs, new_names = _merge_preserving_prefix(current_defs, new_defs, registered_names)
- # Same NAME set: no change for MCP-reload callers. Content-aware callers
- # (compaction boundary) also diff serialized bytes.
- if new_names == current and not (content_aware and _tool_defs_content_changed(agent, new_defs)):
- # Record the generation so an in-flight older caller can't clobber.
- agent._tool_snapshot_generation = max(published_gen, snapshot_generation)
- return set()
- agent.tools = new_defs
- agent.valid_tool_names = new_names
- # Publish context-engine routing names atomically with the snapshot.
- engine_names = getattr(agent, "_context_engine_tool_names", None)
- if isinstance(engine_names, set):
- engine_names.clear()
- engine_names.update(staged_engine_names)
- agent._tool_snapshot_generation = max(published_gen, snapshot_generation)
- added = new_names - current
+ pass # fail open to the plain rebuild
+ added = _publish_tool_snapshot(
+ agent, new_defs, new_names, snapshot_generation=snapshot_generation,
+ staged_engine_names=staged_engine_names, content_aware=content_aware, prefix_registered=prefix_registered,
+ )
+ if added is None:
+ return set()
# Re-pin the session's tool order so a rebuild-for-existing-session
# (gateway agent-cache eviction) restores exactly these names.
persist_agent_tool_names(agent)
@@ -166,14 +170,12 @@ def persist_agent_tool_names(agent) -> None:
def restore_agent_tool_prefix(agent, saved_names: list) -> bool:
- """Fold a freshly built agent's ``tools`` onto the session's saved order.
-
- The gateway rebuilds a NEW AIAgent for an existing session after agent-cache
- eviction, with no predecessor to preserve; the saved name list stands in:
- a saved tool still registered but failing its probe is carried forward from
- the registry schema, a deregistered one is dropped, new tools append at the
- tail (same rule as ``_merge_preserving_prefix``). Returns True if changed.
- """
+ """Fold a freshly built agent's ``tools`` onto the session's saved order;
+ True if changed. The gateway rebuilds a NEW AIAgent for an existing session
+ after agent-cache eviction, with no predecessor to preserve, so the saved
+ name list stands in: a saved tool still registered but failing its probe is
+ carried forward from the registry schema, a deregistered one is dropped, new
+ tools append at the tail (same rule as ``_merge_preserving_prefix``)."""
if not saved_names:
return False
from tools.registry import registry
@@ -203,12 +205,10 @@ def restore_agent_tool_prefix(agent, saved_names: list) -> bool:
def _merge_preserving_prefix(current_defs: list, new_defs: list, registered_names: set) -> tuple[list, set]:
"""Fold a fresh tool snapshot into a live one without moving existing bytes.
-
- Ordered by ``current_defs`` (the cached request prefix): a name in both
- keeps its slot but takes the fresh schema; a name only in the live list is
- kept if still registered (``check_fn`` flapped) and dropped if not; a name
- only in the fresh list is appended at the tail.
- """
+ Ordered by ``current_defs`` (the cached request prefix): a name in both keeps
+ its slot but takes the fresh schema; a name only in the live list is kept if
+ still registered (``check_fn`` flapped), else dropped; a name only in the
+ fresh list is appended at the tail."""
fresh = {_def_name(entry): entry for entry in new_defs if _def_name(entry)}
merged = []
for entry in current_defs:
@@ -225,11 +225,9 @@ def _merge_preserving_prefix(current_defs: list, new_defs: list, registered_name
def _reinject_post_build_tools(agent, tools_list: list, name_set: set) -> set:
"""Append memory-provider and context-engine tools onto the caller's staged
``tools_list`` / ``name_set`` (never the live agent attributes), mirroring
- ``agent_init``'s post-build injection. Idempotent and fail-soft.
-
- Returns the context-engine routing names THIS rebuild appended: a name
- already owned by a registry/plugin tool is not claimed, matching agent_init.
- """
+ ``agent_init``'s post-build injection. Idempotent and fail-soft. Returns the
+ context-engine routing names THIS rebuild appended: a name already owned by
+ a registry/plugin tool is not claimed, matching agent_init."""
def _add(schema) -> bool:
name = schema.get("name", "") if isinstance(schema, dict) else ""
if not name or name in name_set:
diff --git a/tools/mcp_tool_common.py b/tools/mcp_tool_common.py
index e127e9154f2..0e96d04200a 100644
--- a/tools/mcp_tool_common.py
+++ b/tools/mcp_tool_common.py
@@ -13,13 +13,11 @@ logger = logging.getLogger("tools.mcp_tool")
class _OriginProxy:
- """Attribute proxy for ``tools.mcp_tool`` resolved at access time.
-
- The split modules read origin state (``_servers``, ``_lock``, SDK symbols,
- patchable helpers) through this so ``mock.patch("tools.mcp_tool.X")`` and
- origin-side rebinds stay effective, and so no split module needs the origin
- imported first (the origin imports them while it is still initialising).
- """
+ """Attribute proxy for ``tools.mcp_tool`` resolved at access time. The split
+ modules read origin state (``_servers``, ``_lock``, SDK symbols, patchable
+ helpers) through this so ``mock.patch("tools.mcp_tool.X")`` and origin-side
+ rebinds stay effective, and so no split module needs the origin imported
+ first (the origin imports them while it is still initialising)."""
__slots__ = ()
@@ -30,19 +28,15 @@ class _OriginProxy:
_core = _OriginProxy()
-
-
_MISSING = object()
def mcp_field(obj, snake: str, camel: str, default=None):
"""Read an MCP model field across the 1.x -> 2.x rename to snake_case.
-
Pydantic aliases don't apply to attribute access, so ``getattr(result,
"isError", False)`` silently returns the default on 2.x — failed calls read
as successful, schemas as empty. Trying both spellings stays correct on
- either SDK generation (``mcp`` is an optional extra at the user's version).
- """
+ either SDK generation (``mcp`` is an optional extra at the user's version)."""
value = getattr(obj, snake, _MISSING)
if value is _MISSING:
value = getattr(obj, camel, _MISSING)
diff --git a/tools/mcp_tool_config.py b/tools/mcp_tool_config.py
index c3205ac1cb9..4bf532814c8 100644
--- a/tools/mcp_tool_config.py
+++ b/tools/mcp_tool_config.py
@@ -20,11 +20,9 @@ _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 the real stderr.
- """
+ """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."""
global _mcp_stderr_log_fh
with _mcp_stderr_log_lock:
if _mcp_stderr_log_fh is not None:
@@ -114,12 +112,10 @@ def _context_var_value(ref: str) -> Optional[str]:
def _build_safe_env(user_env: Optional[dict]) -> dict:
- """Filtered env for stdio subprocesses so API keys/tokens don't leak.
-
- Passes only the safe baseline keys, ``XDG_*``, vars injected by an external
- secret source (users configured that backend precisely so subprocesses can
- consume them), plus the server config's own ``env``.
- """
+ """Filtered env for stdio subprocesses so API keys/tokens don't leak: only
+ the safe baseline keys, ``XDG_*``, vars injected by an external secret
+ source (users configured that backend precisely so subprocesses can consume
+ them), plus the server config's own ``env``."""
try:
from hermes_cli.env_loader import get_secret_source
except Exception: # pragma: no cover — early bootstrap/import fallback
@@ -140,10 +136,7 @@ def _build_safe_env(user_env: Optional[dict]) -> dict:
def _which_with_config_pathext(command: str, path_arg, env: dict):
"""``shutil.which`` retried under the config env's PATHEXT (Windows only):
``which(path=...)`` uses the PARENT's PATHEXT, not the config env's."""
- cfg_pathext = next(
- (v for k, v in env.items() if k.upper() == "PATHEXT" and isinstance(v, str) and v.strip()),
- None,
- )
+ cfg_pathext = next((v for k, v in env.items() if k.upper() == "PATHEXT" and isinstance(v, str) and v.strip()), None)
if not cfg_pathext or cfg_pathext == os.environ.get("PATHEXT"):
return None
saved = os.environ.get("PATHEXT")
@@ -215,13 +208,11 @@ def _wrap_command_with_watchdog(command: str, args: list) -> tuple[str, list]:
def _interpolate_env_vars(value):
- """Recursively resolve ``${VAR}`` / Cursor ``${env:VAR}`` placeholders plus the
- Cursor context vars (see ``_context_var_value``).
-
- Env refs resolve from the active profile's secret scope when multiplexing
- (so ``${API_KEY}`` picks up the routed profile's value, not another
- profile's in ``os.environ``). Unset vars keep the literal placeholder.
- """
+ """Recursively resolve ``${VAR}`` / Cursor ``${env:VAR}`` placeholders plus
+ the Cursor context vars (``_context_var_value``). Env refs resolve from the
+ active profile's secret scope when multiplexing (so ``${API_KEY}`` picks up
+ the routed profile's value, not another profile's in ``os.environ``). Unset
+ vars keep the literal placeholder."""
from agent.secret_scope import get_secret as _get_secret
if isinstance(value, str):
@@ -245,12 +236,10 @@ _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 trailing newline or leading space causes opaque
- auth/connect failures and is invisible in config.yaml.
-
- Advisory only: values are never mutated (whitespace could be intentional)
- and never logged (often secrets). Returns the flagged key paths.
- """
+ whitespace — a pasted newline or leading space causes opaque auth/connect
+ failures and is invisible in config.yaml. Advisory only: values are never
+ mutated (whitespace could be intentional) and never logged (often secrets).
+ Returns the flagged key paths."""
flagged: List[str] = []
def _walk(value: Any, path: str) -> None:
diff --git a/tools/mcp_tool_lifecycle.py b/tools/mcp_tool_lifecycle.py
index 023179edc83..b8e799697a5 100644
--- a/tools/mcp_tool_lifecycle.py
+++ b/tools/mcp_tool_lifecycle.py
@@ -73,12 +73,9 @@ _NON_MCP_CHILD_CMDLINE_MARKERS: tuple[str, ...] = (
def _filter_mcp_children(pids: set) -> set:
- """Drop non-MCP children from a PID snapshot delta.
-
- Tracking a stray child in _stdio_pgids is catastrophic if it lacks
- start_new_session: its pgid can be the TUI parent's, so the shutdown
- killpg() would kill the TUI itself.
- """
+ """Drop non-MCP children from a PID snapshot delta. Tracking a stray child in
+ _stdio_pgids is catastrophic if it lacks start_new_session: its pgid can be
+ the TUI parent's, so the shutdown killpg() would kill the TUI itself."""
if not pids:
return pids
try:
@@ -107,18 +104,13 @@ def _clear_connect_cooldowns() -> None:
def shutdown_mcp_servers(*, scope: Optional[str] = None):
"""Close MCP server connections (in parallel) and stop the background loop.
-
Each server Task is signalled to exit its own ``async with`` so the anyio
cancel-scope cleanup runs in the Task that opened it. ``scope`` restricts
teardown to one multiplexed profile's servers (its ``/reload-mcp`` must not
- kill other profiles') and leaves the shared loop running if anything else
- is still connected.
- """
+ kill other profiles') and leaves the shared loop running if anything else is
+ still connected."""
with _core._lock:
- selected = [
- name for name in _core._servers
- if scope is None or _core._server_scope_keys.get(name) == scope
- ]
+ selected = [name for name in _core._servers if scope is None or _core._server_scope_keys.get(name) == scope]
servers_snapshot = [_core._servers[name] for name in selected]
# Fast path: nothing to shut down. Still clear the connect-cooldown maps —
@@ -131,10 +123,7 @@ def shutdown_mcp_servers(*, scope: Optional[str] = None):
return
async def _shutdown():
- results = await asyncio.gather(
- *(server.shutdown() for server in servers_snapshot),
- return_exceptions=True,
- )
+ results = await asyncio.gather(*(server.shutdown() for server in servers_snapshot), return_exceptions=True)
for server, result in zip(servers_snapshot, results):
if isinstance(result, Exception):
logger.debug("Error closing MCP server '%s': %s", server.name, result)
@@ -218,13 +207,11 @@ def _signal_mcp_process(pid: int, sig: int, server_name: str, pgid: Optional[int
def _kill_orphaned_mcp_children(include_active: bool = False, server_name: Optional[str] = None) -> None:
"""Best-effort reap of stdio MCP subprocesses: SIGTERM, wait 2s, SIGKILL survivors.
-
By default only ``_orphan_stdio_pids`` (PIDs that outlived their session
context) are reaped so concurrent cron jobs / live sessions are untouched;
``include_active=True`` also kills every ``_stdio_pids`` entry and is only
- for final shutdown after the MCP loop has stopped. ``server_name`` limits
- the sweep to one server (stdio reconnects cleaning up their old transport).
- """
+ for final shutdown after the MCP loop has stopped. ``server_name`` limits the
+ sweep to one server (stdio reconnects cleaning up their old transport)."""
import signal as _signal
pids, pgids = _take_reapable_pids(include_active, server_name)
@@ -256,23 +243,18 @@ def _kill_orphaned_mcp_children(include_active: bool = False, server_name: Optio
def _stop_mcp_loop_if_idle() -> bool:
- """Stop the MCP loop only when no registered server still owns it.
-
- Probe paths create temporary MCPServerTasks not placed in ``_servers``;
- they may clean up an idle loop but must not tear down the process-global
- loop under live agent tools, or later calls fail with
- ``MCP event loop is not running``.
- """
+ """Stop the MCP loop only when no registered server still owns it. Probe
+ paths create temporary MCPServerTasks not placed in ``_servers``; they may
+ clean up an idle loop but must not tear down the process-global loop under
+ live agent tools, or later calls fail with ``MCP event loop is not running``."""
return _core._stop_mcp_loop(only_if_idle=True)
async def _drain_mcp_loop_tasks(*, timeout: Optional[float] = None) -> None:
"""Cancel every task still pending on the MCP loop and reap it.
-
``Task.cancel()`` only schedules the throw, so tasks need a cancellation
cycle before the loop goes away; wait for them here, on their owning loop,
- bounded so a task that suppresses cancellation cannot hang process exit.
- """
+ bounded so a task that suppresses cancellation cannot hang process exit."""
if timeout is None:
timeout = _core._MCP_LOOP_DRAIN_TIMEOUT
current = asyncio.current_task()
@@ -285,10 +267,9 @@ async def _drain_mcp_loop_tasks(*, timeout: Optional[float] = None) -> None:
done, still_pending = await asyncio.wait(pending, timeout=timeout)
for task in done:
- if task.cancelled():
- continue
try:
- task.exception()
+ if not task.cancelled():
+ task.exception()
except asyncio.CancelledError:
pass
except Exception as exc:
@@ -299,12 +280,10 @@ async def _drain_mcp_loop_tasks(*, timeout: Optional[float] = None) -> None:
async def _drain_and_stop_mcp_loop() -> None:
- """Drain pending tasks, then stop the loop from its owning thread.
-
- Both must run as one loop-owned sequence: a ``loop.stop`` queued separately
- by a timed-out caller can overtake the scheduled drain, leaving the drain
- coroutine itself pending when the loop is closed.
- """
+ """Drain pending tasks, then stop the loop from its owning thread. Both must
+ run as one loop-owned sequence: a ``loop.stop`` queued separately by a
+ timed-out caller can overtake the scheduled drain, leaving the drain
+ coroutine itself pending when the loop is closed."""
loop = asyncio.get_running_loop()
try:
await _drain_mcp_loop_tasks(timeout=_core._MCP_LOOP_DRAIN_TIMEOUT)
diff --git a/tools/mcp_tool_sampling.py b/tools/mcp_tool_sampling.py
index 91c3492e226..a1aa99c2c5a 100644
--- a/tools/mcp_tool_sampling.py
+++ b/tools/mcp_tool_sampling.py
@@ -65,10 +65,7 @@ def _convert_sampling_message(msg) -> List[dict]:
tool_uses = [b for b in blocks if _is_tool_use(b) and _tool_use_id(b) is _MISSING]
content_blocks = [b for b in blocks if _tool_use_id(b) is _MISSING and not _is_tool_use(b)]
- out = [
- {"role": "tool", "tool_call_id": _tool_use_id(tr), "content": _tool_result_text(tr)}
- for tr in tool_results
- ]
+ out = [{"role": "tool", "tool_call_id": _tool_use_id(tr), "content": _tool_result_text(tr)} for tr in tool_results]
if tool_uses:
msg_dict: dict = {"role": msg.role, "tool_calls": [_tool_call_dict(tu, i) for i, tu in enumerate(tool_uses)]}
text_parts = [b.text for b in content_blocks if hasattr(b, "text")]
diff --git a/tools/mcp_tool_schema.py b/tools/mcp_tool_schema.py
index 9afe0ad9539..ce3c62c1888 100644
--- a/tools/mcp_tool_schema.py
+++ b/tools/mcp_tool_schema.py
@@ -50,12 +50,10 @@ _EMPTY_OBJECT_SCHEMA = {"type": "object", "properties": {}}
def _rewrite_local_refs(node):
"""Promote legacy ``definitions`` to ``$defs`` (Moonshot rejects the draft-07
- form) — but ONLY where it is a JSON Schema meta-keyword, never as a property
- NAME inside ``properties``/``patternProperties``. A tool parameter
- legitimately named ``definitions`` rewritten to ``$defs`` would 400 the whole
- tool array (Anthropic/OpenAI forbid ``$`` in property names). Property names
- are kept verbatim and recursion resumes ordinary semantics inside each
- property's schema."""
+ form) — ONLY where it is a JSON Schema meta-keyword, never as a property NAME
+ inside ``properties``/``patternProperties``: a parameter legitimately named
+ ``definitions`` rewritten to ``$defs`` would 400 the whole tool array
+ (Anthropic/OpenAI forbid ``$`` in property names)."""
if isinstance(node, list):
return [_rewrite_local_refs(item) for item in node]
if not isinstance(node, dict):
@@ -100,15 +98,12 @@ def _repair_object_shape(node):
def _normalize_mcp_input_schema(schema: dict | None) -> dict:
"""Normalize MCP input schemas so one form is valid on OpenAI, Anthropic,
- Gemini and Moonshot.
-
- Order matters: ``definitions`` -> ``$defs`` rewrite; nullable ``anyOf``
- unions collapsed to the non-null branch (Anthropic rejects nullable
- branches; optionality lives solely in the parent's ``required``, the
- ``nullable: true`` hint is kept so runtime coercion can still map a
- model-emitted ``"null"`` string to ``None``); same-typed const unions ->
- enum (must run AFTER the nullable strip); then object-shape repair.
- """
+ Gemini and Moonshot. Order matters: ``definitions`` -> ``$defs``; nullable
+ ``anyOf`` unions collapsed to the non-null branch (Anthropic rejects nullable
+ branches; optionality lives in the parent's ``required``; the ``nullable:
+ true`` hint is kept so runtime coercion can map a model-emitted ``"null"``
+ string to ``None``); same-typed const unions -> enum (AFTER the nullable
+ strip); then object-shape repair."""
if not schema:
return dict(_EMPTY_OBJECT_SCHEMA)
from tools.schema_sanitizer import collapse_const_unions, strip_nullable_unions