Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: keep one MCP connection per chat instead of reconnecting every call (#10095)
Nilay0c0e45e88c0f
diff --git a/studio/backend/core/inference/mcp_client.py b/studio/backend/core/inference/mcp_client.pyindex c8aedcd34fe..01f5a839b76 100644--- a/studio/backend/core/inference/mcp_client.py+++ b/studio/backend/core/inference/mcp_client.py@@ -18,6 +18,7 @@ import sysimport threadingimport timeimport uuid+from contextlib import contextmanagerfrom functools import wrapsfrom typing import Any, Optionalfrom urllib.parse import urlsplit, urlunsplit@@ -141,16 +142,24 @@ def _windows_batch_argument_is_unsafe(argument: str) -> bool:)-def _stdio_log_id(url: str) -> str:+def _session_log_id(url: str) -> str:"""A non-secret label for logs. stdio commands can embed credentials in argv- (e.g. ``npx server --token sk-...``), so never log the raw command; use the- executable basename plus a short digest of the full command instead."""+ (e.g. ``npx server --token sk-...``) and HTTP URLs in their query string, so+ never log the raw address; use the executable basename (or the host) plus a+ short digest of the full address instead."""+ digest = hashlib.sha256(url.encode()).hexdigest()[:12]+ if not is_stdio(url):+ try:+ label = urlsplit(url).hostname or "<url>"+ except Exception: # noqa: BLE001+ label = "<invalid>"+ return f"{label}#{digest}"try:parts = parse_stdio_command(url)exe = os.path.basename(parts[0]) if parts else "<empty>"except Exception: # noqa: BLE001exe = "<invalid>"- return f"{exe}#{hashlib.sha256(url.encode()).hexdigest()[:12]}"+ return f"{exe}#{digest}"def stdio_mcp_enabled() -> bool:@@ -450,24 +459,59 @@ def _client(return Client(transport_cls(url = url, headers = headers or None, auth = auth))-# Persistent stdio sessions: a stdio MCP server owns live state (a browser, a-# DB handle), so keep one connected client per (command, env, chat session) on-# a dedicated event-loop thread instead of respawning per call.--_STDIO_SESSION_IDLE_TTL = 300.0-_STDIO_SESSION_REAP_INTERVAL = 30.0+_SESSION_IDLE_TTL = 300.0+_SESSION_REAP_INTERVAL = 30.0_STDIO_CONNECT_TIMEOUT = 60.0 # allows first-run `npx -y ...` package download-_STDIO_CLOSE_TIMEOUT = 10.0-_STDIO_WEDGE_MARGIN = 15.0-_STDIO_LIVENESS_TIMEOUT = 5.0+_SESSION_CLOSE_TIMEOUT = 10.0+_SESSION_WEDGE_MARGIN = 15.0+_SESSION_LIVENESS_TIMEOUT = 5.0_CANCEL_UNWIND_TIMEOUT = 2.0-# Cap concurrent persistent sessions: each owns a subprocess + loop thread, and-# the scope includes a caller-supplied thread_id, so an unbounded cache is a-# resource-exhaustion surface. Overridable via env for large deployments.-try:- _STDIO_MAX_SESSIONS = max(1, int(os.environ.get("UNSLOTH_STUDIO_MAX_STDIO_MCP_SESSIONS", "32")))-except ValueError:- _STDIO_MAX_SESSIONS = 32+# An HTTP session idle this long is re-proved with tools/list before the next+# dispatch: the server may have expired it (MCP says a server MAY terminate a+# session at any time), and no HTTP transport exposes a liveness probe we can+# ask instead -- see _transport_dead.+_HTTP_IDLE_RECHECK = 30.0+_DEFAULT_MAX_SESSIONS = 32+++def _max_sessions_from_env() -> int:+ # The cap covers stdio and HTTP sessions alike now, so the stdio-specific+ # name is wrong; keep honouring it so deployments that already set it do not+ # silently jump back to the default.+ raw = os.environ.get("UNSLOTH_STUDIO_MAX_MCP_SESSIONS")+ if raw is None:+ raw = os.environ.get("UNSLOTH_STUDIO_MAX_STDIO_MCP_SESSIONS")+ if raw is None:+ return _DEFAULT_MAX_SESSIONS+ try:+ return max(1, int(raw))+ except ValueError:+ return _DEFAULT_MAX_SESSIONS+++_MAX_SESSIONS = _max_sessions_from_env()+++def _connect_window(url: str, timeout: Optional[float]) -> Optional[float]:+ """How long connecting may take, out of the caller's remaining budget.++ stdio keeps the cold-start cap: a first run may download a package before the+ server says anything. HTTP has no such phase, and capping it would reject+ connections the caller explicitly allowed time for -- which is what the+ one-shot path it replaced always did."""+ if timeout is None or not is_stdio(url):+ return timeout+ return min(timeout, _STDIO_CONNECT_TIMEOUT)+++class _ConnectTimeout(asyncio.TimeoutError):+ """Ran out of time before the transport was up. Carries the window that+ actually expired, which is not the caller's timeout when stdio's cold-start+ cap is the tighter bound."""++ def __init__(self, window: Optional[float]):+ super().__init__()+ self.window = windowdef _is_tool_error(exc: BaseException) -> bool:@@ -481,11 +525,43 @@ def _is_tool_error(exc: BaseException) -> bool:return isinstance(exc, ToolError)+def _is_protocol_error(exc: BaseException) -> bool:+ """A JSON-RPC error response, as opposed to a broken connection.++ A FastMCP server answers an unknown tool or bad arguments with a result+ carrying is_error, but the MCP spec also lets a server report those as a+ protocol error, and plenty of non-FastMCP servers do. fastmcp surfaces that+ as MCPError (McpError before the rename) carrying the ErrorData the server+ sent. Receiving it proves the connection is working, so retiring the session+ over it would throw away the chat's server-side state for a mistyped tool+ name. The caller still marks the session for a probe before reuse."""+ for module, name in (+ ("mcp.shared.exceptions", "MCPError"),+ ("mcp.shared.exceptions", "McpError"),+ ):+ try:+ cls = getattr(__import__(module, fromlist = [name]), name, None)+ except Exception: # noqa: BLE001+ continue+ if cls is not None and isinstance(exc, cls):+ # Only when the server actually sent an error object; a synthetic+ # MCPError with nothing behind it stays transport-level.+ return getattr(exc, "error", None) is not None+ return False++def _transport_dead(session) -> bool:- """Best-effort, version-adaptive liveness probe for a cached stdio client.+ """Best-effort, version-adaptive liveness probe for a cached client.``Client.is_connected()`` only checks a session object exists, not that the- subprocess is alive, so it is never used here. Returns True only when the- transport is positively gone; unknown returns False (the call surfaces it)."""+ subprocess (or the server's HTTP session) is alive, so it is never used here.+ Returns True only when the transport is positively gone; unknown returns+ False (the call surfaces it).++ Only the stdio transport answers: ``_is_session_dead``/``_connect_task`` are+ ``StdioTransport`` internals, and neither ``StreamableHttpTransport`` nor+ ``SSETransport`` has ever carried them (checked on fastmcp 3.0.2 and 4.0.0).+ For HTTP this returns "unknown" every time, which is why an idle HTTP session+ is re-proved with tools/list instead -- see _needs_idle_recheck."""client = getattr(session, "client", None)if client is None:return True@@ -507,32 +583,69 @@ def _transport_dead(session) -> bool:return False+def _needs_idle_recheck(session, idle_for: float, remaining: Optional[float]) -> bool:+ """Whether an idle HTTP session must prove itself before the next dispatch.++ A server MAY drop an HTTP session whenever it likes, and the client only+ learns on the next request -- which would surface as a failed tool call the+ user has to retry by hand. stdio is exempt: _transport_dead answers there, and+ a live subprocess does not expire on its own.++ Skipped when the caller cannot afford it. The probe exists to save someone a+ failed call, so spending their whole budget on it (tool_call_timeout goes down+ to 1s) would cause the very failure it is meant to avoid; dispatching straight+ away is the better bet with that little time left."""+ if is_stdio(session.url):+ return False+ # Negative means this borrower connected the session itself, so the handshake+ # it just completed is proof enough.+ if idle_for < 0.0 or idle_for < _HTTP_IDLE_RECHECK:+ return False+ return remaining is None or remaining > _SESSION_LIVENESS_TIMEOUT * 2++def _session_responsive(session,budget: Optional[float] = None,cancel_event = None,+ timeout_is_fatal: bool = True,) -> bool:"""Whether a session left dirty by an abandoned call can be reused: theserver must answer inside ``budget`` (the caller's remaining deadline).Proves the server is alive, not that the abandoned call finished -- MCPrequests are concurrent. Probes with a raw single-page tools/list: pinganswers "Method not found" on a modern-era connection, and list_tools()- auto-paginates up to 250 pages."""+ auto-paginates up to 250 pages.++ ``timeout_is_fatal`` separates the two callers. A dirty session is under+ suspicion, so silence within the window condemns it. An idle one is only+ being spot-checked: a slow answer says nothing about whether the transport+ is gone, and retiring it there would throw away the very state this cache+ exists to keep. Only a definite failure retires that one."""client = session.clientif client is None:return False- window = _STDIO_LIVENESS_TIMEOUT if budget is None else min(_STDIO_LIVENESS_TIMEOUT, budget)+ window = _SESSION_LIVENESS_TIMEOUT if budget is None else min(_SESSION_LIVENESS_TIMEOUT, budget)if window <= 0:- return False+ # No budget left to ask in; that is not evidence either way.+ return not timeout_is_fatalprobe = getattr(client, "list_tools_mcp", None) or client.list_toolstry:# margin=0: a wedged loop must fail inside the window, not 15s past it.session.run(_race_tool_call(probe(), window, cancel_event), window, margin = 0.0)except _MCPCancelled:raise- except Exception: # noqa: BLE001- return False+ except (asyncio.TimeoutError, _SessionWedged):+ return not timeout_is_fatal+ except Exception as exc: # noqa: BLE001+ # A JSON-RPC error (a rate limit, a permission rule on tools/list) is the+ # server answering on this very session, exactly as it is for call_tool.+ # Reconnecting would throw away the chat's state over a reply that proves+ # the transport works.+ if not _is_protocol_error(exc):+ return Falsesession.dirty = False+ session.proved_at = time.monotonic()return True@@ -553,8 +666,19 @@ def _abort_future(future) -> None:pass-class _StdioSession:- def __init__(self, url: str, headers: Optional[dict]):+class _McpSession:+ def __init__(+ self,+ url: str,+ headers: Optional[dict],+ use_oauth: bool = False,+ ):+ # A cached session is built by _client(url, headers) with no auth, so an+ # OAuth server must never reach here. call_tool_sync already routes it to+ # the one-shot path; this makes a future routing slip fail loudly rather+ # than quietly talk to an OAuth server unauthenticated.+ if use_oauth and not is_stdio(url):+ raise ValueError("OAuth MCP servers cannot use a shared session")self.url = urlself.headers = headersself.client = None@@ -562,9 +686,20 @@ class _StdioSession:self.defunct = False # discarded; close once in_flight drains (see _retire)self.dirty = False # a call was abandoned on it; ping before reuseself._close_lock = threading.Lock()- self.call_lock = threading.Lock() # serializes tool calls on this session+ self.call_lock = threading.Lock()+ # One stdio subprocess is one ordered byte stream, so overlapping calls+ # must not interleave on it. HTTP has no such constraint: every JSON-RPC+ # message is its own POST and the spec lets a client keep several streams+ # open at once, so serializing it would only undo the parallelism the+ # one-shot path had.+ self.serialize_calls = is_stdio(url)self.last_used = time.monotonic()- self.in_flight = 0 # guarded by _stdio_sessions_lock+ # When the transport was last shown to be alive, as opposed to merely+ # borrowed. Checkout refreshes last_used immediately, so the idle gap the+ # recheck needs has to be measured from here or a second borrower arriving+ # during the first one's probe would see no gap at all.+ self.proved_at = self.last_used+ self.in_flight = 0 # guarded by _mcp_sessions_lock# On Windows a bare new_event_loop() can be a SelectorEventLoop (if any# component set that policy), which cannot spawn subprocesses natively;# force a ProactorEventLoop so the stdio transport always works.@@ -572,9 +707,7 @@ class _StdioSession:self.loop = asyncio.ProactorEventLoop()else:self.loop = asyncio.new_event_loop()- self._thread = threading.Thread(- target = self._run_loop, name = "mcp-stdio-session", daemon = True- )+ self._thread = threading.Thread(target = self._run_loop, name = "mcp-session", daemon = True)self._thread.start()def _run_loop(self) -> None:@@ -596,8 +729,9 @@ class _StdioSession:future = asyncio.run_coroutine_threadsafe(_open(), self.loop)# timeout=None means unlimited (no connect deadline); a finite caller- # timeout still bounds connect by min(timeout, _STDIO_CONNECT_TIMEOUT).- window = None if timeout is None else min(timeout, _STDIO_CONNECT_TIMEOUT)+ # timeout bounds connect by _connect_window(), which caps stdio at its+ # cold-start limit and hands HTTP the whole remaining budget.+ window = _connect_window(self.url, timeout)deadline = None if window is None else time.monotonic() + windowwhile True:if cancel_event is not None and cancel_event.is_set():@@ -611,7 +745,7 @@ class _StdioSession:raise # the connect itself failed fast; don't wait out the windowif deadline is not None and time.monotonic() >= deadline:_abort_future(future)- raise asyncio.TimeoutError+ raise _ConnectTimeout(window)def is_connected(self) -> bool:client = self.client@@ -627,7 +761,7 @@ class _StdioSession:self,coro,timeout: Optional[float],- margin: float = _STDIO_WEDGE_MARGIN,+ margin: float = _SESSION_WEDGE_MARGIN,):self.last_used = time.monotonic()future = asyncio.run_coroutine_threadsafe(coro, self.loop)@@ -657,7 +791,6 @@ class _StdioSession:self.last_used = time.monotonic()def close(self) -> None:- # Idempotent: a discard racing close_stdio_sessions() may close twice.# Setting `closed` first also unblocks run() waiters (they poll it).with self._close_lock:if self.closed.is_set():@@ -680,11 +813,11 @@ class _StdioSession:task.cancel()try:- asyncio.run_coroutine_threadsafe(_shutdown(), loop).result(_STDIO_CLOSE_TIMEOUT)+ asyncio.run_coroutine_threadsafe(_shutdown(), loop).result(_SESSION_CLOSE_TIMEOUT)except Exception as exc: # noqa: BLE001logger.warning(- "MCP stdio session close failed for %s: %s",- _stdio_log_id(getattr(self, "url", "")),+ "MCP session close failed for %s: %s",+ _session_log_id(getattr(self, "url", "")),exc,)try:@@ -698,31 +831,41 @@ class _StdioSession:thread.join(timeout = 5.0)-_stdio_sessions: dict[tuple, _StdioSession] = {}+_mcp_sessions: dict[tuple, _McpSession] = {}# Per-key locks so a slow connect/close never blocks unrelated servers; the# global lock only guards the dicts.-class _StdioKeyLock:+class _McpKeyLock:"""A per-key lock that can be removed once nobody references it."""def __init__(self) -> None:self.lock = threading.Lock()- self.users = 0 # guarded by _stdio_sessions_lock---_stdio_key_locks: dict[tuple, _StdioKeyLock] = {}-_stdio_sessions_lock = threading.Lock()-_stdio_reaper_started = False-# close_stdio_sessions() can only close sessions already published in-# _stdio_sessions; one still inside connect() would be missed and cached+ self.users = 0 # guarded by _mcp_sessions_lock+++_mcp_key_locks: dict[tuple, _McpKeyLock] = {}+_mcp_sessions_lock = threading.Lock()+_mcp_reaper_started = False+# Sessions discarded while somebody else was mid-call, closed by one worker off+# the request path. See _close_detached.+_mcp_cleanup_lock = threading.Lock()+_mcp_cleanup_queue: list = []+# Depth past which an evicting caller closes the overflow itself. See+# _close_detached.+_MAX_PENDING_CLOSES = 8+# How wide close_mcp_sessions fans out. See _close_all.+_MAX_CLOSE_THREADS = 16+_mcp_cleanup_worker: Optional[threading.Thread] = None+# close_mcp_sessions() can only close sessions already published in _mcp_sessions;+# one still inside connect() would be missed and then cached already# stale. Bump a generation on every close so that connect discards its-# session instead of publishing it. Guarded by _stdio_sessions_lock.-_stdio_close_all_gen = 0-_stdio_url_close_gen: dict[str, int] = {}-_stdio_cfg_close_gen: dict[tuple, int] = {}+# session instead of publishing it. Guarded by _mcp_sessions_lock.+_mcp_close_all_gen = 0+_mcp_url_close_gen: dict[str, int] = {}+_mcp_cfg_close_gen: dict[tuple, int] = {}+_mcp_connects_in_flight = 0-# close_stdio_sessions(url): match any env for that command._ANY_HEADERS = object()@@ -741,11 +884,11 @@ def _cfg_close_key(url: str, headers: Optional[dict]) -> str:return hashlib.sha256(repr((url, _headers_key(headers))).encode()).hexdigest()-def _stdio_close_generation(url: str, headers: Optional[dict]) -> tuple[int, int, int]:+def _mcp_close_generation(url: str, headers: Optional[dict]) -> tuple[int, int, int]:return (- _stdio_close_all_gen,- _stdio_url_close_gen.get(_url_close_key(url), 0),- _stdio_cfg_close_gen.get(_cfg_close_key(url, headers), 0),+ _mcp_close_all_gen,+ _mcp_url_close_gen.get(_url_close_key(url), 0),+ _mcp_cfg_close_gen.get(_cfg_close_key(url, headers), 0),)@@ -753,120 +896,155 @@ def _session_key(url: str, headers: Optional[dict], scope: Optional[str]) -> tupreturn (url, _headers_key(headers), scope or "")-def _checkout_stdio_session(key: tuple) -> Optional[_StdioSession]:- session = _stdio_sessions.get(key)+def _checkout_session(key: tuple) -> tuple[Optional[_McpSession], float]:+ """Returns the session and how long it had been unused, measured before+ last_used is refreshed.++ The idle gap is returned rather than stored on the session because HTTP+ borrowers run concurrently: a second checkout would otherwise overwrite the+ first one's gap with a near-zero value and talk it out of proving a session+ that really had gone stale."""+ session = _mcp_sessions.get(key)if session is not None and session.is_connected():- session.last_used = time.monotonic()+ now = time.monotonic()+ idle_for = now - session.proved_at+ session.last_used = nowsession.in_flight += 1- return session- return None+ return session, idle_for+ return None, -1.0-def _borrow_stdio_key_lock(key: tuple) -> _StdioKeyLock:+def _borrow_key_lock(key: tuple) -> _McpKeyLock:"""Return a stable per-key lock while a caller waits for/connects it."""- key_lock = _stdio_key_locks.setdefault(key, _StdioKeyLock())+ key_lock = _mcp_key_locks.setdefault(key, _McpKeyLock())key_lock.users += 1return key_lock-def _discard_stdio_key_lock(key: tuple) -> None:- key_lock = _stdio_key_locks.get(key)- if key_lock is not None and key_lock.users == 0 and key not in _stdio_sessions:- _stdio_key_locks.pop(key, None)+def _discard_key_lock(key: tuple) -> None:+ key_lock = _mcp_key_locks.get(key)+ if key_lock is not None and key_lock.users == 0 and key not in _mcp_sessions:+ _mcp_key_locks.pop(key, None)-def _return_stdio_key_lock(key: tuple, key_lock: _StdioKeyLock) -> None:- with _stdio_sessions_lock:+def _return_key_lock(key: tuple, key_lock: _McpKeyLock) -> None:+ with _mcp_sessions_lock:key_lock.users -= 1- _discard_stdio_key_lock(key)+ _discard_key_lock(key)-def _get_stdio_session(- url: str, headers: Optional[dict], scope: Optional[str], deadline, cancel_event, config_check-) -> _StdioSession:+@contextmanager+def _connect_slot(url: str, headers: Optional[dict]):+ global _mcp_connects_in_flight+ with _mcp_sessions_lock:+ generation = _mcp_close_generation(url, headers)+ _mcp_connects_in_flight += 1+ try:+ yield generation+ finally:+ with _mcp_sessions_lock:+ _mcp_connects_in_flight -= 1+++def _get_session(+ url: str,+ headers: Optional[dict],+ scope: Optional[str],+ deadline,+ cancel_event,+ config_check,+ use_oauth: bool = False,+) -> tuple[_McpSession, float]:"""``deadline`` is the caller's absolute monotonic budget (None = no limit):the key-lock wait and the connect share it, so a slow startup can't stack- full timeout windows (see _call_stdio_tool)."""- global _stdio_reaper_started+ full timeout windows (see _call_session_tool).++ Returns the session and this borrower's idle gap (negative when we connected+ it ourselves), which only the borrower may act on -- see _checkout_session."""+ global _mcp_reaper_startedkey = _session_key(url, headers, scope)- with _stdio_sessions_lock:- session = _checkout_stdio_session(key)+ with _mcp_sessions_lock:+ session, idle_for = _checkout_session(key)if session is not None:- return session- key_lock = _borrow_stdio_key_lock(key)+ return session, idle_for+ key_lock = _borrow_key_lock(key)try:# Poll the acquire with connect()'s deadline/cancel semantics: a second# same-scope call must not block uncancellably behind another caller's# slow startup (e.g. a first-run npx download).remaining = None if deadline is None else max(0.0, deadline - time.monotonic())- # timeout=None means no key-lock deadline (only cancel unblocks it).- window = None if remaining is None else min(remaining, _STDIO_CONNECT_TIMEOUT)+ # timeout=None means no key-lock deadline (only cancel unblocks it). The+ # wait is bounded exactly like the connect it is queueing behind, so an+ # HTTP caller is not cut off at stdio's cold-start cap here either.+ window = _connect_window(url, remaining)lock_deadline = None if window is None else time.monotonic() + windowwhile not key_lock.lock.acquire(timeout = 0.05):if cancel_event is not None and cancel_event.is_set():raise _MCPCancelledif lock_deadline is not None and time.monotonic() >= lock_deadline:- raise asyncio.TimeoutError+ raise _ConnectTimeout(window)try:stale = None- with _stdio_sessions_lock:- session = _checkout_stdio_session(key)+ with _mcp_sessions_lock:+ session, idle_for = _checkout_session(key)if session is not None:- return session- if key in _stdio_sessions:- stale = _stdio_sessions.pop(key)- generation = _stdio_close_generation(url, headers)+ return session, idle_for+ if key in _mcp_sessions:+ stale = _mcp_sessions.pop(key)if stale is not None:- _retire_stdio_session(stale)- session = _StdioSession(url, headers)- try:- session.connect(- None if deadline is None else max(0.0, deadline - time.monotonic()),- cancel_event,- )- except Exception:- session.close()- raise- # A caller can read the server row, then lose to an update/delete whose close ran- # before our generation snapshot. Re-verify the row after connect; the generation check- # below covers a close landing between this check and publish.- if config_check is not None:+ _retire_session(stale)+ with _connect_slot(url, headers) as generation:+ session = _McpSession(url, headers, use_oauth)try:- current = bool(config_check())- except Exception: # noqa: BLE001- current = False- if not current:+ session.connect(+ None if deadline is None else max(0.0, deadline - time.monotonic()),+ cancel_event,+ )+ except Exception:+ session.close()+ raise+ if config_check is not None:+ try:+ current = bool(config_check())+ except Exception: # noqa: BLE001+ current = False+ if not current:+ session.close()+ raise RuntimeError("MCP server was updated or removed while connecting")+ evicted: list = []+ with _mcp_sessions_lock:+ closed_while_connecting = _mcp_close_generation(url, headers) != generation+ if not closed_while_connecting:+ session.in_flight = 1+ evicted = _evict_lru_locked() # bound the cache (LRU idle)+ _mcp_sessions[key] = session+ if not _mcp_reaper_started:+ _mcp_reaper_started = True+ threading.Thread(+ target = _session_reaper, name = "mcp-session-reaper", daemon = True+ ).start()+ atexit.register(close_mcp_sessions)+ for victim in evicted:+ logger.info("Evicting LRU idle MCP session: %s", _session_log_id(victim.url))+ if evicted:+ # Detached: these belong to other scopes and nobody is waiting+ # on them, but an unresponsive transport costs+ # _SESSION_CLOSE_TIMEOUT each. Charging that to this caller+ # would spend the deadline meant for their tool call.+ _close_detached(evicted)+ if closed_while_connecting:session.close()raise RuntimeError("MCP server was updated or removed while connecting")- evicted: list = []- with _stdio_sessions_lock:- closed_while_connecting = _stdio_close_generation(url, headers) != generation- if not closed_while_connecting:- session.in_flight = 1- evicted = _evict_stdio_lru_locked() # bound the cache (LRU idle)- _stdio_sessions[key] = session- if not _stdio_reaper_started:- _stdio_reaper_started = True- threading.Thread(- target = _stdio_session_reaper, name = "mcp-stdio-reaper", daemon = True- ).start()- atexit.register(close_stdio_sessions)- for victim in evicted:- logger.info("Evicting LRU idle stdio MCP session: %s", _stdio_log_id(victim.url))- victim.close()- if closed_while_connecting:- session.close()- raise RuntimeError("MCP server was updated or removed while connecting")- return session+ return session, -1.0finally:key_lock.lock.release()finally:- _return_stdio_key_lock(key, key_lock)+ _return_key_lock(key, key_lock)-def _release_stdio_session(session: _StdioSession) -> None:+def _release_session(session: _McpSession, defer_close: bool = False) -> None:victims: list = []- with _stdio_sessions_lock:+ with _mcp_sessions_lock:session.in_flight = max(0, session.in_flight - 1)session.last_used = time.monotonic()close_now = session.defunct and session.in_flight == 0@@ -874,114 +1052,262 @@ def _release_stdio_session(session: _StdioSession) -> None:# only trims idle sessions, so it can overshoot while every cached session# is busy; reclaim that overshoot here instead of waiting for the idle# reaper. Never evict the session we just used (its last_used is newest).- while len(_stdio_sessions) > _STDIO_MAX_SESSIONS:+ while len(_mcp_sessions) > _MAX_SESSIONS:idle = [(s.last_used, k)- for k, s in _stdio_sessions.items()+ for k, s in _mcp_sessions.items()if s.in_flight == 0 and s is not session]if not idle:break_, oldest = min(idle, key = lambda item: item[0])- victims.append(_stdio_sessions.pop(oldest))- _discard_stdio_key_lock(oldest)- if close_now:+ victims.append(_mcp_sessions.pop(oldest))+ _discard_key_lock(oldest)+ if close_now and defer_close:+ # This borrower was the last one on a session that has been discarded,+ # either by its own failure or by a sibling's. Either way the caller is+ # mid-request -- it may still have a reconnect and retry to do on the+ # same deadline -- and a transport that is being discarded because it+ # stopped answering is exactly the one whose close runs long. Only the+ # unscoped one-shot path closes inline (defer_close is False there),+ # because there the teardown is the call's own work and the caller+ # expects the subprocess gone by the time it returns.+ victims.append(session)+ elif close_now:session.close()- for victim in victims:- victim.close()+ if victims:+ _close_detached(victims)-def _retire_stdio_session(session: _StdioSession) -> None:+def _retire_session(session: _McpSession) -> None:"""Close a discarded session, but only once no other borrower is mid-callon it -- overlapping same-scope calls share one client, and one call'stimeout must not kill another's in-flight request. The last borrower's- _release_stdio_session() performs the deferred close."""- with _stdio_sessions_lock:+ _release_session() performs the deferred close."""+ with _mcp_sessions_lock:session.defunct = Truebusy = session.in_flight > 0if not busy:session.close()-def _drop_stdio_session(key: tuple, session: _StdioSession) -> None:- with _stdio_sessions_lock:- if _stdio_sessions.get(key) is session:- _stdio_sessions.pop(key)- _discard_stdio_key_lock(key)- _retire_stdio_session(session)+def _drop_session(key: tuple, session: _McpSession) -> None:+ with _mcp_sessions_lock:+ if _mcp_sessions.get(key) is session:+ _mcp_sessions.pop(key)+ _discard_key_lock(key)+ _retire_session(session)-def _evict_stdio_lru_locked() -> list:- """Caller holds _stdio_sessions_lock. Evict least-recently-used *idle*+def _evict_lru_locked() -> list:+ """Caller holds _mcp_sessions_lock. Evict least-recently-used *idle*sessions until the cache is under the cap. Returns the evicted sessions sothe caller can close them OUTSIDE the lock. If every session is busy thecache may transiently overshoot rather than kill an in-flight call."""victims: list = []- while len(_stdio_sessions) >= _STDIO_MAX_SESSIONS:- idle = [(s.last_used, k) for k, s in _stdio_sessions.items() if s.in_flight == 0]+ while len(_mcp_sessions) >= _MAX_SESSIONS:+ idle = [(s.last_used, k) for k, s in _mcp_sessions.items() if s.in_flight == 0]if not idle:break_, oldest = min(idle, key = lambda item: item[0])- victims.append(_stdio_sessions.pop(oldest))- _discard_stdio_key_lock(oldest)+ victims.append(_mcp_sessions.pop(oldest))+ _discard_key_lock(oldest)return victims-def close_stdio_sessions(url: Optional[str] = None, headers = _ANY_HEADERS) -> None:- """Close persistent stdio sessions: all of them (``url`` None), every env- for one command (``headers`` omitted), or one server config (url + headers).- Two server rows can share a command with different envs; editing one must- not kill the other's live state, so the routes pass the edited row's env."""- global _stdio_close_all_gen- # HTTP/SSE servers are never cached as stdio sessions, so a specific non-stdio- # url has nothing to close and must not accrue a close-generation entry.- if url is not None and not is_stdio(url):- return+def close_mcp_sessions(url: Optional[str] = None, headers = _ANY_HEADERS) -> None:+ global _mcp_close_all_genhk = None if headers is _ANY_HEADERS else _headers_key(headers)- with _stdio_sessions_lock:- if url is None:- _stdio_close_all_gen += 1- elif hk is None:- uk = _url_close_key(url)- _stdio_url_close_gen[uk] = _stdio_url_close_gen.get(uk, 0) + 1- else:- cfg = _cfg_close_key(url, headers)- _stdio_cfg_close_gen[cfg] = _stdio_cfg_close_gen.get(cfg, 0) + 1+ with _mcp_sessions_lock:keys = [- k- for k in _stdio_sessions- if (url is None or k[0] == url) and (hk is None or k[1] == hk)+ k for k in _mcp_sessions if (url is None or k[0] == url) and (hk is None or k[1] == hk)]- sessions = [_stdio_sessions.pop(k) for k in keys]+ sessions = [_mcp_sessions.pop(k) for k in keys]for key in keys:- _discard_stdio_key_lock(key)- for session in sessions:+ _discard_key_lock(key)+ if sessions or _mcp_connects_in_flight:+ if url is None:+ _mcp_close_all_gen += 1+ elif hk is None:+ uk = _url_close_key(url)+ _mcp_url_close_gen[uk] = _mcp_url_close_gen.get(uk, 0) + 1+ else:+ cfg = _cfg_close_key(url, headers)+ _mcp_cfg_close_gen[cfg] = _mcp_cfg_close_gen.get(cfg, 0) + 1+ pending, worker = _drain_cleanup_queue()+ _close_all(sessions + pending)+ if worker is not None and worker is not threading.current_thread():+ # Draining the queue does not recall the session the worker had already+ # popped, and this function promises its caller (a server edit, or+ # atexit) that the teardown has happened. The worker stops as soon as the+ # queue is empty, so this waits for that one close and no longer.+ worker.join(_SESSION_CLOSE_TIMEOUT + 5.0)+++def _close_all(sessions: list) -> None:+ """Close sessions in parallel.++ Serially, each unresponsive transport can burn _SESSION_CLOSE_TIMEOUT plus+ the thread join before the next one starts. This runs on the request thread+ when a server is edited or deleted, and a popular HTTP server now holds a+ session per chat rather than one overall, so a serial close could stall that+ route for minutes.++ Fanned out _MAX_CLOSE_THREADS wide rather than one thread per session. The+ cache is allowed to overshoot _MAX_SESSIONS while every session in it is+ busy, so the list handed here has no fixed length, and a shutdown is the+ worst moment to ask the process for an unbounded number of threads."""+ if not sessions:+ return+ if len(sessions) == 1:+ sessions[0].close()+ return++ pending = list(sessions)+ pending_lock = threading.Lock()++ def _drain() -> None:+ while True:+ with pending_lock:+ if not pending:+ return+ session = pending.pop()+ _close_quietly(session)++ # Bare threads, not a ThreadPoolExecutor: this also runs as the atexit+ # handler, and Python shuts the executor machinery down before normal atexit+ # callbacks, so submitting there raises ("can't register atexit after+ # shutdown") and the whole cleanup aborts with stdio subprocesses still up.+ width = min(len(pending), _MAX_CLOSE_THREADS)+ threads = [threading.Thread(target = _drain, name = "mcp-close", daemon = True) for _ in range(width)]+ for thread in threads:+ thread.start()+ # Each worker may take several sessions in turn, so the wait scales with the+ # rounds it has to make rather than with a single close.+ rounds = -(-len(sessions) // width)+ for thread in threads:+ thread.join(rounds * (_SESSION_CLOSE_TIMEOUT + 5.0))+++def _close_detached(sessions: list) -> None:+ """Hand sessions nobody is waiting on to the cleanup worker.++ Used for LRU victims and for the deferred close of a retired session: those+ belong to another scope or to a call that has already ended, while the thread+ holding them is in the middle of serving a tool call on its own deadline and+ an unresponsive transport costs _SESSION_CLOSE_TIMEOUT to shut down.++ One worker rather than a thread per session: nobody is waiting on these, so+ closing them one at a time is fine, and a run of new chat scopes against a+ server that hangs on shutdown then cannot spawn threads without bound.+ close_mcp_sessions stays synchronous and drains this queue, because its caller+ (a server edit, or atexit) does need the teardown to have happened.++ Past _MAX_PENDING_CLOSES the overflow is closed on the caller instead. A queue+ that keeps growing means the server is shutting down slower than chats are+ opening, and every waiting session still holds its own loop thread and+ connection, so the queue has to be bounded as well as the cache. Making the+ caller wait is the backpressure that stops it: unpleasant, but the same thing+ that happened before any of this was deferred, and only once the deferral has+ already failed to keep up."""+ global _mcp_cleanup_worker+ if not sessions:+ return+ with _mcp_cleanup_lock:+ room = max(0, _MAX_PENDING_CLOSES - len(_mcp_cleanup_queue))+ _mcp_cleanup_queue.extend(sessions[:room])+ overflow = sessions[room:]+ if _mcp_cleanup_queue and _mcp_cleanup_worker is None:+ _mcp_cleanup_worker = threading.Thread(+ target = _cleanup_worker, name = "mcp-cleanup", daemon = True+ )+ _mcp_cleanup_worker.start()+ _close_all(overflow)+++def _cleanup_worker() -> None:+ global _mcp_cleanup_worker+ while True:+ with _mcp_cleanup_lock:+ if not _mcp_cleanup_queue:+ _mcp_cleanup_worker = None # _close_detached starts the next one+ return+ session = _mcp_cleanup_queue.pop(0)+ _close_quietly(session)+++def _drain_cleanup_queue() -> tuple[list, Optional[threading.Thread]]:+ """Take back whatever the worker has not started on yet, plus the worker+ itself so the caller can wait out the one close already under way."""+ with _mcp_cleanup_lock:+ pending = list(_mcp_cleanup_queue)+ _mcp_cleanup_queue.clear()+ return pending, _mcp_cleanup_worker+++def _close_quietly(session) -> None:+ try:session.close()+ except Exception: # noqa: BLE001+ logger.exception("Closing a discarded MCP session failed")+++# The cache stopped being stdio-only, but an in-place upgrade can leave a caller+# holding the old name; it costs two lines to keep it working.+close_stdio_sessions = close_mcp_sessions++def _reset_after_fork() -> None:+ """Drop everything the child inherited from the parent's cache.-def _reap_idle_stdio_sessions(now: Optional[float] = None) -> None:+ Only the forking thread survives a fork, so every session's loop thread is+ gone while its client still reports connected. A child that checked one out+ would wait on a loop that will never run, and _transport_dead cannot see it+ for HTTP. Nothing here is closed: those objects belong to the parent, which+ is still using them."""+ global _mcp_reaper_started, _mcp_connects_in_flight, _mcp_sessions_lock+ global _mcp_cleanup_lock, _mcp_cleanup_worker+ # Replaced, not just cleared: a lock the fork caught held belongs to a thread+ # that no longer exists here, so the child would block on it forever.+ _mcp_sessions_lock = threading.Lock()+ _mcp_sessions.clear()+ _mcp_key_locks.clear()+ _mcp_connects_in_flight = 0+ _mcp_reaper_started = False+ # The cleanup worker did not survive the fork either, and its queue holds the+ # parent's sessions.+ _mcp_cleanup_lock = threading.Lock()+ _mcp_cleanup_queue.clear()+ _mcp_cleanup_worker = None+++if hasattr(os, "register_at_fork"):+ os.register_at_fork(after_in_child = _reset_after_fork)+++def _reap_idle_sessions(now: Optional[float] = None) -> None:now = time.monotonic() if now is None else now- with _stdio_sessions_lock:+ with _mcp_sessions_lock:expired = [key- for key, session in _stdio_sessions.items()- if session.in_flight == 0 and now - session.last_used >= _STDIO_SESSION_IDLE_TTL+ for key, session in _mcp_sessions.items()+ if session.in_flight == 0 and now - session.last_used >= _SESSION_IDLE_TTL]- sessions = [_stdio_sessions.pop(key) for key in expired]+ sessions = [_mcp_sessions.pop(key) for key in expired]for key in expired:- _discard_stdio_key_lock(key)+ _discard_key_lock(key)for session in sessions:- logger.info("Closing idle stdio MCP session: %s", _stdio_log_id(session.url))+ logger.info("Closing idle MCP session: %s", _session_log_id(session.url))session.close()-def _stdio_session_reaper() -> None:+def _session_reaper() -> None:while True:- time.sleep(_STDIO_SESSION_REAP_INTERVAL)+ time.sleep(_SESSION_REAP_INTERVAL)try:- _reap_idle_stdio_sessions()+ _reap_idle_sessions()except Exception as exc: # noqa: BLE001- logger.debug("stdio session reaper iteration failed: %s", exc)+ logger.debug("MCP session reaper iteration failed: %s", exc)async def list_tools_async(@@ -1269,7 +1595,7 @@ async def _race_tool_call(raise _MCPCancelled-def _call_stdio_tool(+def _call_session_tool(url: str,headers: Optional[dict],name: str,@@ -1278,11 +1604,12 @@ def _call_stdio_tool(cancel_event,scope: Optional[str],config_check,+ use_oauth: bool = False,) -> Any:if cancel_event is not None and cancel_event.is_set():raise _MCPCancelled# One deadline covers the key-lock wait, connect, call-lock wait, and the- # call itself, matching the one-shot/HTTP paths where the timeout wrapped+ # call itself, matching the one-shot path where the caller's timeout wrapped# connect plus call in a single window.deadline = None if timeout is None else time.monotonic() + timeout@@ -1308,21 +1635,28 @@ def _call_stdio_tool(# attempt 0 may find the cached session stale/dead *before* dispatch and# reconnect once (safe); attempt 1 is a freshly connected session.for attempt in (0, 1):- session = _get_stdio_session(url, headers, scope, deadline, cancel_event, config_check)+ session, idle_for = _get_session(+ url, headers, scope, deadline, cancel_event, config_check, use_oauth+ )+ locked = Falsetry:- # Serialize calls per session: overlapping same-scope calls must- # not interleave operations on one stateful server (browser, REPL).- while not session.call_lock.acquire(timeout = 0.05):- if cancel_event is not None and cancel_event.is_set():- raise _MCPCancelled- rem = _remaining()- if rem is not None and rem <= 0:- raise asyncio.TimeoutError+ # Serialize calls per session where the transport demands it:+ # overlapping same-scope calls must not interleave operations on one+ # stateful stdio server (browser, REPL). HTTP multiplexes by request+ # id, so its calls run in parallel as they did one-shot.+ if session.serialize_calls:+ while not session.call_lock.acquire(timeout = 0.05):+ if cancel_event is not None and cancel_event.is_set():+ raise _MCPCancelled+ rem = _remaining()+ if rem is not None and rem <= 0:+ raise asyncio.TimeoutError+ locked = Trueexcept BaseException:# Never touched the transport: keep the session for its borrower.- _release_stdio_session(session)+ _release_session(session)if ephemeral:- _drop_stdio_session(key, session)+ _drop_session(key, session)raisediscard_session = ephemeralretry = False@@ -1352,8 +1686,15 @@ def _call_stdio_tool(retry = Trueelse:raise RuntimeError("MCP server connection is not available")- elif session.dirty and not _session_responsive(session, _remaining(), cancel_event):- # Still stuck on the abandoned call; only now is a fresh one needed.+ elif (+ session.dirty or _needs_idle_recheck(session, idle_for, _remaining())+ ) and not _session_responsive(+ session, _remaining(), cancel_event, timeout_is_fatal = session.dirty+ ):+ # Dirty: still stuck on the abandoned call. Idle HTTP: the server+ # may have expired the session while nothing was using it, and no+ # HTTP transport lets us ask. Either way it failed to answer, so+ # reconnect BEFORE dispatch rather than losing the user's call.discard_session = Trueif attempt == 0:retry = True@@ -1369,7 +1710,11 @@ def _call_stdio_tool(# Only a cached session is worth waiting on.0.0 if ephemeral else _CANCEL_UNWIND_TIMEOUT,)- return session.run(coro, rem)+ out = session.run(coro, rem)+ # A completed round trip proves the transport better than any+ # probe could, so it resets the idle clock the recheck reads.+ session.proved_at = time.monotonic()+ return outexcept (_MCPCancelled, asyncio.TimeoutError):# Keep the session so a Stop doesn't destroy the server's state; the# SDK drops the abandoned reply, and reuse is gated on a live probe.@@ -1379,7 +1724,7 @@ def _call_stdio_tool(discard_session = Trueraise asyncio.TimeoutErrorexcept _SessionClosed:- # close_stdio_sessions() shut this session mid-call (server+ # close_mcp_sessions() shut this session mid-call (server# update/delete/shutdown); don't retry on the stale config.discard_session = Trueraise RuntimeError("MCP server was updated or removed during the call")@@ -1389,21 +1734,34 @@ def _call_stdio_tool(# error or AttributeError instead of _SessionClosed; don't mistake it for a crash.discard_session = Trueraise RuntimeError("MCP server was updated or removed during the call")- # ToolError leaves the transport alive -> keep the session so its state- # survives. Any other exception is transport-level (dead subprocess,- # broken pipe): evict so it can't poison the scope, but DO NOT replay- # (the tool may already have run); the next call opens a fresh session.- if not _is_tool_error(exc):+ # A ToolError or a JSON-RPC error response means the server answered,+ # so the transport is alive -> keep the session and its state.+ # Anything else is transport-level (dead subprocess, broken pipe,+ # dropped HTTP stream): evict so it can't poison the scope, but DO+ # NOT replay (the tool may already have run); the next call opens a+ # fresh session.+ if _is_protocol_error(exc):+ # The server replied, so the transport is fine and the session's+ # state is worth keeping. Probe it before the next call anyway,+ # in case the error was the server telling us the session is no+ # longer one it recognises.+ session.dirty = True+ elif not _is_tool_error(exc):discard_session = Trueraisefinally:- # Set defunct + remove from the cache BEFORE releasing the call lock,- # so a queued same-scope borrower observes the retirement and opens a- # fresh session instead of reusing this one.- _release_stdio_session(session)+ # Remove from the cache and mark defunct BEFORE giving up the borrow,+ # so no other caller can check this session out after it failed. The+ # order matters more now that HTTP callers do not queue on call_lock:+ # released first, a concurrent same-scope call could check out the+ # broken transport while it was still cached, and _release_session can+ # sit closing LRU victims for seconds first. in_flight is still held+ # here, so the close defers to the release below.if discard_session:- _drop_stdio_session(key, session)- session.call_lock.release()+ _drop_session(key, session)+ _release_session(session, defer_close = not ephemeral)+ if locked:+ session.call_lock.release()if not retry:breakraise RuntimeError("unreachable")@@ -1420,12 +1778,25 @@ def call_tool_sync(scope: Optional[str] = None,config_check = None,) -> str:- """Synchronously call an MCP tool. stdio servers reuse a persistent session- keyed by (command, env, scope) only when ``scope`` is provided; calls- without one stay one-shot. HTTP servers always stay one-shot.- ``cancel_event`` (threading.Event) cancels the in-flight call when set.- ``config_check`` (callable -> bool) re-validates the caller's server config- before a fresh stdio session is cached; False fails the call."""+ """Call one MCP tool and return its flattened text/image result.++ Never raises: every failure comes back as an "Error: ..." string for the model.++ Which transport path runs depends on ``scope`` (an opaque per-chat key) and+ ``use_oauth``:++ * stdio always goes through the session machinery. Without a scope it still+ gets a private ephemeral session that is closed afterwards, so no browser+ or cookie state leaks between requests.+ * HTTP reuses a cached session only when it has a scope AND OAuth is off, so+ a server that keeps state between calls keeps it for the whole chat.+ * OAuth HTTP, and HTTP without a scope, connect once and disconnect, exactly+ as before sessions were shared. Refreshing a token on a long-lived shared+ connection is not something this code can do safely yet.++ ``timeout`` is one budget covering connect and call together. ``cancel_event``+ aborts an in-flight call. ``config_check`` re-reads the server row so a call+ that raced an edit or delete cannot dispatch on the stale configuration."""async def _one_shot() -> Any:async with _client(url, headers, use_oauth) as client:@@ -1435,14 +1806,19 @@ def call_tool_sync(return await client.call_tool(name, args, raise_on_error = False)try:- if is_stdio(url):- result = _call_stdio_tool(- url, headers, name, args, timeout, cancel_event, scope, config_check+ if is_stdio(url) or (scope and not use_oauth):+ result = _call_session_tool(+ url, headers, name, args, timeout, cancel_event, scope, config_check, use_oauth)else:result = asyncio.run(_race_tool_call(_one_shot(), timeout, cancel_event))except _MCPCancelled:return f"Error: MCP tool '{name}' cancelled"+ except _ConnectTimeout as exc:+ # Report the window that actually expired: for stdio that is the+ # cold-start cap, not the (larger) caller timeout.+ suffix = f" after {round(exc.window, 1):g}s" if exc.window is not None else ""+ return f"Error: MCP tool '{name}' timed out connecting{suffix}"except asyncio.TimeoutError:suffix = f" after {timeout:g}s" if timeout is not None else ""return f"Error: MCP tool '{name}' timed out{suffix}"diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex 4612984c1e6..b501702bc7e 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -10500,16 +10500,22 @@ def execute_tool(mcp_scope = Noneheaders = parse_server_headers(server)url = server["url"]+ use_oauth = bool(server.get("use_oauth"))def _config_current() -> bool:- # Re-read before a stdio session is cached: this call may have read+ # Re-read before an MCP session is cached: this call may have read# the row just before an update/delete closed its sessions.+ # use_oauth belongs here with the rest: a row switched to OAuth after+ # we read it must not be reached through the unauthenticated client+ # this call is about to open, and a close cannot stop that on its own+ # (nothing is cached yet, so it has no generation to bump).row = mcp_servers_db.get_server(server_id)return (row is not Noneand bool(row.get("is_enabled"))and row.get("url") == urland parse_server_headers(row) == headers+ and bool(row.get("use_oauth")) == use_oauth)return _fit_result_to_room(@@ -10519,7 +10525,7 @@ def execute_tool(name = tool_name,args = arguments,timeout = effective_timeout,- use_oauth = bool(server.get("use_oauth")),+ use_oauth = use_oauth,cancel_event = cancel_event,scope = mcp_scope,config_check = _config_current,diff --git a/studio/backend/routes/mcp_servers.py b/studio/backend/routes/mcp_servers.pyindex 5b9117ed96b..9268f5f5c4c 100644--- a/studio/backend/routes/mcp_servers.py+++ b/studio/backend/routes/mcp_servers.py@@ -21,7 +21,7 @@ from core.inference.mcp_client import (TOOL_CACHE_INVALIDATING_FIELDS,cache_tools,clear_oauth_tokens_async,- close_stdio_sessions,+ close_mcp_sessions,invalidate_tool_cache,is_stdio,join_stdio_command,@@ -326,7 +326,7 @@ async def update_mcp_server(if invalidates_tools:# Narrow to this row's env: another server row sharing the command but# with a different env keeps its live sessions.- await asyncio.to_thread(close_stdio_sessions, old["url"], parse_server_headers(old))+ await asyncio.to_thread(close_mcp_sessions, old["url"], parse_server_headers(old))return _row_to_response(mcp_servers_db.get_server(server_id), include_headers = not no_credential)@@ -340,7 +340,7 @@ async def delete_mcp_server(server_id: str, current_subject: str = Depends(get_cawait clear_oauth_tokens_async(old["url"])mcp_servers_db.delete_server(server_id)invalidate_tool_cache(server_id)- await asyncio.to_thread(close_stdio_sessions, old["url"], parse_server_headers(old))+ await asyncio.to_thread(close_mcp_sessions, old["url"], parse_server_headers(old))@router.post("/{server_id}/refresh", response_model = McpServerProbeResult)diff --git a/studio/backend/tests/test_mcp_flatten_result.py b/studio/backend/tests/test_mcp_flatten_result.pyindex 522c4c93342..c6fdb187b01 100644--- a/studio/backend/tests/test_mcp_flatten_result.py+++ b/studio/backend/tests/test_mcp_flatten_result.py@@ -234,7 +234,7 @@ def test_stdio_session_call_also_passes_raise_on_error_false(monkeypatch):"npx fake-stdio-server", None, "take_screenshot", {}, scope = "s=p:t=thread1")finally:- mcp_client.close_stdio_sessions()+ mcp_client.close_mcp_sessions()assert seen["raise_on_error"] is Falseassert out.startswith("Error: boom")diff --git a/studio/backend/tests/test_mcp_http_integration.py b/studio/backend/tests/test_mcp_http_integration.pynew file mode 100644index 00000000000..3702f026e24--- /dev/null+++ b/studio/backend/tests/test_mcp_http_integration.py@@ -0,0 +1,392 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""End-to-end MCP session behaviour against a real server over Streamable HTTP.++Everything else in the MCP suite runs against a fake client that takes a url and+discards the headers, so nothing there observes a real HTTP request. These start+a real MCP server on 127.0.0.1 and ask it what it saw.++Oracle: fastmcp negotiates sessionless Streamable HTTP here, so there is no+Mcp-Session-Id to follow and Context.session_id is a fresh UUID per request+(checked with a held-open client). The server therefore keys its state on the+client's TCP connection, which is what a stateful server's per-connection state+behaves like: a held-open client sees its own notes, separate clients do not.+"""++from __future__ import annotations++import os+import socket+import subprocess+import sys+import textwrap+import threading+import time+from pathlib import Path++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++pytest.importorskip("fastmcp")+pytest.importorskip("uvicorn")++from core.inference import mcp_client+from core.inference.mcp_client import call_tool_sync, close_mcp_sessions++# Matches the scope tools.py builds: "s={session_id}:t={thread_id}".+SCOPE = "s=sess1:t=threadA"+SCOPE_B = "s=sess1:t=threadB"++_SERVER = '''+import contextvars, sys, threading+import uvicorn+from fastmcp import FastMCP+from fastmcp.server.dependencies import get_http_headers+from fastmcp.server.middleware import Middleware++mcp = FastMCP("notes")+_peer = contextvars.ContextVar("peer", default="unknown")+_lock = threading.Lock()+_notes, _peers = {}, []+_live = _max_live = 0+_expired = set()+++class Observe:+ """Raw ASGI: BaseHTTPMiddleware buffers the response and deadlocks the SSE+ stream Streamable HTTP replies on."""++ def __init__(self, app):+ self.app = app++ async def __call__(self, scope, receive, send):+ if scope["type"] != "http":+ await self.app(scope, receive, send)+ return+ client = scope.get("client")+ peer = f"{client[0]}:{client[1]}" if client else "unknown"+ _peer.set(peer)+ with _lock:+ if peer not in _peers:+ _peers.append(peer)+ expired = bool(_expired)+ _expired.clear()+ if expired:+ # What MCP requires of a server that terminated a session: the next+ # request gets 404 and the client must start a new one. One-shot and+ # keyed on nothing, because which socket a fastmcp client uses for a+ # given request is a pooling detail that varies by version.+ await send({+ "type": "http.response.start",+ "status": 404,+ "headers": [(b"content-type", b"text/plain")],+ })+ await send({"type": "http.response.body", "body": b"Session not found"})+ return+ await self.app(scope, receive, send)+++def _protocol_error(code, message):+ """mcp<2 names the class McpError and takes an ErrorData; mcp 2 renamed it+ MCPError and takes the fields. constraints.txt allows both."""+ import mcp.shared.exceptions as mcp_exceptions+ from mcp.types import ErrorData++ cls = getattr(mcp_exceptions, "MCPError", None) or mcp_exceptions.McpError+ try:+ return cls(code=code, message=message)+ except TypeError:+ return cls(ErrorData(code=code, message=message))+++class ProtocolErrors(Middleware):+ """Answer one tool with a JSON-RPC error instead of a result, the way the+ spec lets a server report an unknown tool. FastMCP itself returns a result+ carrying is_error for that, so this stands in for the servers that do not;+ raising from inside a tool would not reach the client as MCPError."""++ async def on_call_tool(self, context, call_next):+ if context.message.name == "protocol_error":+ raise _protocol_error(-32602, "Unknown tool: protocol_error")+ return await call_next(context)+++mcp.add_middleware(ProtocolErrors())+++def protocol_error() -> str:+ return "never reached"+++def save_note(text: str) -> str:+ peer = _peer.get()+ with _lock:+ _notes.setdefault(peer, []).append(text)+ return f"saved on connection {peer}"+++def list_notes() -> str:+ peer = _peer.get()+ with _lock:+ return f"connection={peer} notes={list(_notes.get(peer, []))}"+++def whoami() -> str:+ headers = get_http_headers()+ return f"connection={_peer.get()} credential={headers.get('x-test-credential', '<none>')}"+++def expire_me() -> str:+ """Make the next request 404, the way a server that dropped the session does."""+ with _lock:+ _expired.add("next")+ return "expired"+++async def delayed_call(delay: float) -> str:+ global _live, _max_live+ import asyncio+ peer = _peer.get()+ with _lock:+ _live += 1+ _max_live = max(_max_live, _live)+ try:+ await asyncio.sleep(delay)+ finally:+ with _lock:+ _live -= 1+ return f"connection={peer}"+++def stats() -> str:+ with _lock:+ return f"connections={len(_peers)} max_concurrency={_max_live}"+++def reset_stats() -> str:+ global _live, _max_live+ with _lock:+ _max_live = 0+ _peers.clear()+ _notes.clear()+ _expired.clear()+ return "reset"+++if __name__ == "__main__":+ uvicorn.run(+ Observe(mcp.http_app()), host=sys.argv[2], port=int(sys.argv[1]), log_level="warning"+ )+'''+++def _free_port(host: str) -> int:+ family = socket.AF_INET6 if ":" in host else socket.AF_INET+ with socket.socket(family) as s:+ s.bind((host, 0))+ return s.getsockname()[1]+++def _start(tmp_path: Path, host: str):+ script = tmp_path / "mcp_notes_server.py"+ script.write_text(textwrap.dedent(_SERVER))+ port = _free_port(host)+ proc = subprocess.Popen(+ [sys.executable, str(script), str(port), host],+ env = dict(os.environ, PYTHONUNBUFFERED = "1"),+ stdout = subprocess.PIPE,+ stderr = subprocess.STDOUT,+ text = True,+ )+ family = socket.AF_INET6 if ":" in host else socket.AF_INET+ deadline = time.monotonic() + 90+ while time.monotonic() < deadline:+ if proc.poll() is not None:+ raise RuntimeError(f"server died:\n{proc.stdout.read()}")+ try:+ with socket.socket(family) as s:+ s.settimeout(0.5)+ s.connect((host, port))+ break+ except OSError:+ time.sleep(0.2)+ else:+ proc.kill()+ raise RuntimeError("server never came up")+ label = f"[{host}]" if ":" in host else host+ return proc, f"http://{label}:{port}/mcp/"++[email protected](scope = "module")+def server(tmp_path_factory):+ proc, url = _start(tmp_path_factory.mktemp("mcp"), "127.0.0.1")+ try:+ yield url+ finally:+ close_mcp_sessions()+ proc.terminate()+ try:+ proc.wait(15)+ except subprocess.TimeoutExpired:+ proc.kill()++[email protected](autouse = True)+def clean_cache():+ yield+ close_mcp_sessions()+++def _call(+ url,+ name,+ args = None,+ *,+ scope = None,+ headers = None,+ use_oauth = False,+):+ return call_tool_sync(+ url,+ headers,+ name,+ args or {},+ timeout = 60.0,+ use_oauth = use_oauth,+ scope = scope,+ )+++def _conn(text: str) -> str:+ return text.split("connection=")[1].split(" ")[0]+++def test_a_note_survives_to_the_next_tool_call_in_one_chat(server):+ """The behaviour the shared session exists for. Reconnecting per call loses+ whatever the server kept."""+ saved = _call(server, "save_note", {"text": "buy milk"}, scope = SCOPE)+ listed = _call(server, "list_notes", scope = SCOPE)+ assert "buy milk" in listed, listed+ assert saved.split("connection ")[-1].strip() == _conn(listed)+++def test_a_second_chat_gets_its_own_connection(server):+ _call(server, "save_note", {"text": "chat-A-note"}, scope = SCOPE)+ other = _call(server, "list_notes", scope = SCOPE_B)+ assert "chat-A-note" not in other, other+++def test_unscoped_calls_keep_the_old_one_shot_isolation(server):+ _call(server, "save_note", {"text": "unscoped"}, scope = None)+ listed = _call(server, "list_notes", scope = None)+ assert "unscoped" not in listed, listed+++def test_credentials_reach_the_server_and_stay_apart(server):+ a = _call(server, "whoami", scope = SCOPE, headers = {"X-Test-Credential": "cred-A"})+ b = _call(server, "whoami", scope = SCOPE, headers = {"X-Test-Credential": "cred-B"})+ assert "cred-A" in a and "cred-B" in b+ assert "cred-A" not in b, f"credential A leaked into the B session: {b}"+ assert _conn(a) != _conn(b)+++def test_an_oauth_server_is_never_cached(server):+ _call(server, "list_notes", scope = SCOPE, use_oauth = True)+ assert mcp_client._mcp_sessions == {}+++def test_state_survives_a_long_run_of_calls_in_one_chat(server):+ """The property the shared session actually buys, held over many calls.++ Deliberately not asserted as a socket count: how many TCP connections a+ fastmcp client keeps open is a pooling detail that differs by version (3.0.2+ opens far more than 4.0.0 for the same work), and the MCP spec makes every+ JSON-RPC message its own POST regardless. Server-side state is the invariant."""+ _call(server, "save_note", {"text": "note-0"}, scope = SCOPE)+ for i in range(1, 10):+ _call(server, "save_note", {"text": f"note-{i}"}, scope = SCOPE)+ listed = _call(server, "list_notes", scope = SCOPE)+ for i in range(10):+ assert f"note-{i}" in listed, f"note-{i} was lost: {listed}"+++def test_parallel_calls_in_one_chat_are_not_serialized(server):+ """Regression: sharing a session must not cost the parallelism the one-shot+ path had. MCP Streamable HTTP posts each message separately, so there is+ nothing to interleave."""+ _call(server, "reset_stats", scope = "s=admin:t=admin")+ results: list[str] = []+ lock = threading.Lock()++ def run():+ r = _call(server, "delayed_call", {"delay": 1.0}, scope = SCOPE)+ with lock:+ results.append(r)++ started = time.monotonic()+ threads = [threading.Thread(target = run) for _ in range(2)]+ for t in threads:+ t.start()+ for t in threads:+ t.join(60)+ elapsed = time.monotonic() - started+ stats = _call(server, "stats", scope = "s=admin:t=admin")+ assert len(results) == 2+ assert "max_concurrency=2" in stats, stats+ assert elapsed < 1.8, f"the two calls were serialized: {elapsed:.2f}s ({stats})"+++def test_an_expired_session_is_replaced_before_the_users_call_fails(monkeypatch, server):+ """A server may drop an HTTP session at any time and no HTTP transport+ exposes a liveness probe, so without the idle recheck the user's next tool+ call is the thing that discovers it."""+ monkeypatch.setattr(mcp_client, "_HTTP_IDLE_RECHECK", 0.0)+ _call(server, "list_notes", scope = SCOPE)+ _call(server, "expire_me", scope = SCOPE)+ # The next request on that session gets 404, which is what the spec requires+ # of a server that terminated it. The recheck must absorb that and reconnect+ # rather than letting the user's tool call be the thing that discovers it.+ second = _call(server, "list_notes", scope = SCOPE)+ assert not second.startswith("Error:"), second+++def test_ipv6_loopback_works(tmp_path):+ if not socket.has_ipv6:+ pytest.skip("no IPv6 on this host")+ try:+ proc, url = _start(tmp_path, "::1")+ except OSError:+ pytest.skip("IPv6 loopback unavailable")+ try:+ saved = _call(url, "save_note", {"text": "v6"}, scope = SCOPE)+ assert "saved on connection" in saved, saved+ assert "v6" in _call(url, "list_notes", scope = SCOPE)+ finally:+ close_mcp_sessions()+ proc.terminate()+ try:+ proc.wait(15)+ except subprocess.TimeoutExpired:+ proc.kill()+++def test_a_json_rpc_error_does_not_cost_the_chat_its_state(server):+ """The server replied, so the connection is fine and the notes it is holding+ for this chat must survive."""+ _call(server, "save_note", {"text": "before-the-error"}, scope = SCOPE)+ failed = _call(server, "protocol_error", scope = SCOPE)+ assert failed.startswith("Error:"), failed+ listed = _call(server, "list_notes", scope = SCOPE)+ assert "before-the-error" in listed, f"the session was discarded: {listed}"diff --git a/studio/backend/tests/test_mcp_http_sessions.py b/studio/backend/tests/test_mcp_http_sessions.pynew file mode 100644index 00000000000..4436e9c3550--- /dev/null+++ b/studio/backend/tests/test_mcp_http_sessions.py@@ -0,0 +1,1072 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Shared HTTP MCP sessions: routing, identity, timeout budget, OAuth safety and+concurrency.++test_mcp_stdio_sessions.py owns the machinery these share; this file owns what is+specific to HTTP now that it is cached too, and the regressions that came with it.+Races use explicit barriers rather than sleeps so they cannot pass by luck.+"""++from __future__ import annotations++import asyncio+import sys+import threading+import time+from pathlib import Path+from types import SimpleNamespace++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++from core.inference import mcp_client+from core.inference.mcp_client import call_tool_sync, close_mcp_sessions++STDIO_URL = "npx fake-stateful-server"+HTTP_URL = "https://mcp.example.test/mcp"+HTTP_URL_2 = "https://other.example.test/mcp"+SSE_URL = "https://mcp.example.test/sse"+SCOPE = "s=sess1:t=threadA"+SCOPE_B = "s=sess1:t=threadB"+++def _protocol_error(code: int, message: str) -> Exception:+ """Build a JSON-RPC error exception for whichever mcp is installed.++ single-env/constraints.txt allows mcp>=1.24,<2, where the class is McpError+ and takes an ErrorData; mcp 2 renamed it MCPError and takes the fields+ directly. Production code reads whichever of the two names exists, so the+ tests have to be able to raise it under both."""+ import mcp.shared.exceptions as mcp_exceptions+ from mcp.types import ErrorData++ cls = getattr(mcp_exceptions, "MCPError", None) or mcp_exceptions.McpError+ try:+ return cls(code = code, message = message)+ except TypeError:+ return cls(ErrorData(code = code, message = message))+++def _settled(+ client,+ expected: int = 1,+ timeout: float = 10.0,+) -> int:+ """Wait out an asynchronous close.++ A discarded session is closed by the cleanup worker rather than on the+ request thread, so its close lands just after the call returns."""+ deadline = time.monotonic() + timeout+ while client.exited < expected and time.monotonic() < deadline:+ time.sleep(0.005)+ return client.exited+++def _result(text: str) -> SimpleNamespace:+ return SimpleNamespace(+ content = [SimpleNamespace(type = "text", text = text)],+ is_error = False,+ structured_content = None,+ )+++class RecordingClient:+ """Records what _client() was actually given. The stdio-session fixture drops+ headers and use_oauth, which is exactly where a credential bug would hide."""++ instances: list["RecordingClient"] = []++ def __init__(self, url: str, headers, use_oauth: bool):+ self.url = url+ self.headers = headers+ self.use_oauth = use_oauth+ self.entered = 0+ self.exited = 0+ self.calls: list[tuple[str, dict]] = []+ self.connected = False+ self.probes = 0+ self.probe_error = False+ self.probe_delay = 0.0+ self.connect_delay = 0.0+ self.call_delay = 0.0+ self.live = 0+ self.max_live = 0+ self._lock = threading.Lock()+ self.transport = SimpleNamespace() # no _is_session_dead: real HTTP has none+ RecordingClient.instances.append(self)++ async def list_tools_mcp(self):+ self.probes += 1+ if self.probe_error:+ raise RuntimeError("session expired")+ if self.probe_delay:+ await asyncio.sleep(self.probe_delay)+ return SimpleNamespace(tools = [])++ async def __aenter__(self):+ if self.connect_delay:+ await asyncio.sleep(self.connect_delay)+ self.entered += 1+ self.connected = True+ return self++ async def __aexit__(self, *exc):+ self.exited += 1+ self.connected = False++ def is_connected(self) -> bool:+ return self.connected++ async def call_tool(+ self,+ name: str,+ args: dict,+ raise_on_error: bool = True,+ ):+ with self._lock:+ self.live += 1+ self.max_live = max(self.max_live, self.live)+ try:+ if self.call_delay:+ await asyncio.sleep(self.call_delay)+ with self._lock:+ self.calls.append((name, args))+ return _result(f"call-{len(self.calls)}")+ finally:+ with self._lock:+ self.live -= 1+++def clients(monkeypatch):+ RecordingClient.instances = []+ monkeypatch.setattr(+ mcp_client,+ "_client",+ lambda url, headers, use_oauth = False: RecordingClient(url, headers, use_oauth),+ )+ yield RecordingClient.instances+ close_mcp_sessions()+++def _call(+ url,+ name = "t",+ args = None,+ **kw,+):+ kw.setdefault("timeout", 30.0)+ return call_tool_sync(url, kw.pop("headers", None), name, args or {}, **kw)+++# --------------------------------------------------------------------------+# Routing and identity+# --------------------------------------------------------------------------+++def test_scoped_http_reuses_one_client(clients):+ assert _call(HTTP_URL, scope = SCOPE) == "call-1"+ assert _call(HTTP_URL, scope = SCOPE) == "call-2"+ assert len(clients) == 1+ assert clients[0].entered == 1 and clients[0].exited == 0+++def test_sse_urls_are_cached_too(clients):+ _call(SSE_URL, scope = SCOPE)+ _call(SSE_URL, scope = SCOPE)+ assert len(clients) == 1+++def test_different_scopes_do_not_share(clients):+ _call(HTTP_URL, scope = SCOPE)+ _call(HTTP_URL, scope = SCOPE_B)+ assert len(clients) == 2+++def test_different_urls_do_not_share(clients):+ _call(HTTP_URL, scope = SCOPE)+ _call(HTTP_URL_2, scope = SCOPE)+ assert len(clients) == 2+++def test_different_header_values_do_not_share(clients):+ _call(HTTP_URL, scope = SCOPE, headers = {"Authorization": "Bearer a"})+ _call(HTTP_URL, scope = SCOPE, headers = {"Authorization": "Bearer b"})+ assert len(clients) == 2+ assert clients[0].headers != clients[1].headers+++def test_headers_reach_the_client_unchanged(clients):+ _call(HTTP_URL, scope = SCOPE, headers = {"Authorization": "Bearer a"})+ assert clients[0].headers == {"Authorization": "Bearer a"}+++def test_header_order_does_not_split_the_session(clients):+ _call(HTTP_URL, scope = SCOPE, headers = {"A": "1", "B": "2"})+ _call(HTTP_URL, scope = SCOPE, headers = {"B": "2", "A": "1"})+ assert len(clients) == 1+++def test_empty_headers_and_none_share_a_key(clients):+ _call(HTTP_URL, scope = SCOPE, headers = None)+ _call(HTTP_URL, scope = SCOPE, headers = {})+ assert len(clients) == 1+++def test_unscoped_http_stays_one_shot(clients):+ _call(HTTP_URL, scope = None)+ _call(HTTP_URL, scope = None)+ assert len(clients) == 2+ assert all(c.entered == 1 and _settled(c) == 1 for c in clients)+ assert mcp_client._mcp_sessions == {}+++def test_empty_scope_is_treated_as_unscoped(clients):+ _call(HTTP_URL, scope = "")+ _call(HTTP_URL, scope = "")+ assert len(clients) == 2+ assert mcp_client._mcp_sessions == {}+++def test_oauth_http_stays_one_shot(clients):+ _call(HTTP_URL, scope = SCOPE, use_oauth = True)+ _call(HTTP_URL, scope = SCOPE, use_oauth = True)+ assert len(clients) == 2+ assert all(c.use_oauth for c in clients)+ assert mcp_client._mcp_sessions == {}+++def test_a_shared_session_is_never_built_for_an_oauth_server():+ """Defence in depth: the routing above is what keeps OAuth out of the cache,+ so if that ever slips the session must refuse rather than talk to an OAuth+ server with no credentials."""+ with pytest.raises(ValueError):+ mcp_client._McpSession(HTTP_URL, None, use_oauth = True)+++# --------------------------------------------------------------------------+# Timeout budget+# --------------------------------------------------------------------------+++def test_http_connect_uses_the_whole_caller_budget(monkeypatch, clients):+ """Regression: routing HTTP through the shared cache must not import stdio's+ cold-start cap. Scaled down so the test costs a second, not a minute."""+ monkeypatch.setattr(mcp_client, "_STDIO_CONNECT_TIMEOUT", 0.3)+ monkeypatch.setattr(+ mcp_client,+ "_client",+ lambda url, headers, use_oauth = False: _slow_connect(url, headers, use_oauth, 0.8),+ )+ out = _call(HTTP_URL, scope = SCOPE, timeout = 5.0)+ assert out == "call-1", out+++def _slow_connect(url, headers, use_oauth, delay):+ client = RecordingClient(url, headers, use_oauth)+ client.connect_delay = delay+ return client+++def test_stdio_connect_keeps_its_cold_start_cap(monkeypatch, clients):+ monkeypatch.setattr(mcp_client, "_STDIO_CONNECT_TIMEOUT", 0.3)+ monkeypatch.setattr(+ mcp_client,+ "_client",+ lambda url, headers, use_oauth = False: _slow_connect(url, headers, use_oauth, 0.8),+ )+ out = _call(STDIO_URL, scope = SCOPE, timeout = 5.0)+ assert "timed out connecting" in out, out+++def test_connect_timeout_reports_the_window_that_expired(monkeypatch, clients):+ """It used to report the caller's timeout even when the much tighter connect+ cap was what fired, which sends anyone debugging it to the wrong knob."""+ monkeypatch.setattr(mcp_client, "_STDIO_CONNECT_TIMEOUT", 0.3)+ monkeypatch.setattr(+ mcp_client,+ "_client",+ lambda url, headers, use_oauth = False: _slow_connect(url, headers, use_oauth, 5.0),+ )+ out = _call(STDIO_URL, scope = SCOPE, timeout = 9.0)+ assert "0.3s" in out and "9s" not in out, out+++def test_total_deadline_still_bounds_a_slow_http_connect(clients):+ """The complement: giving HTTP the full budget must not remove the budget."""+ mcp_client._client = lambda url, headers, use_oauth = False: _slow_connect(+ url, headers, use_oauth, 1.0+ )+ out = _call(HTTP_URL, scope = SCOPE, timeout = 0.25)+ assert "timed out" in out, out+++def test_connect_and_call_share_one_deadline(monkeypatch, clients):+ def _client(+ url,+ headers,+ use_oauth = False,+ ):+ c = _slow_connect(url, headers, use_oauth, 0.25)+ c.call_delay = 0.25+ return c++ monkeypatch.setattr(mcp_client, "_client", _client)+ out = _call(HTTP_URL, scope = SCOPE, timeout = 0.35)+ assert "timed out" in out, out+++def test_unlimited_timeout_stays_unlimited(monkeypatch, clients):+ monkeypatch.setattr(mcp_client, "_STDIO_CONNECT_TIMEOUT", 0.05)+ monkeypatch.setattr(+ mcp_client,+ "_client",+ lambda url, headers, use_oauth = False: _slow_connect(url, headers, use_oauth, 0.3),+ )+ assert _call(HTTP_URL, scope = SCOPE, timeout = None) == "call-1"+++# --------------------------------------------------------------------------+# Concurrency+# --------------------------------------------------------------------------+++def _parallel(+ url,+ scopes,+ delay = 0.4,+):+ out: list[str] = []+ lock = threading.Lock()++ def run(scope):+ r = _call(url, "delayed", scope = scope)+ with lock:+ out.append(r)++ started = time.monotonic()+ threads = [threading.Thread(target = run, args = (s,)) for s in scopes]+ for t in threads:+ t.start()+ for t in threads:+ t.join(30)+ return out, time.monotonic() - started+++def test_two_http_calls_in_one_chat_run_concurrently(monkeypatch, clients):+ """Regression: the shared session must not serialize HTTP. Every JSON-RPC+ message is its own POST and responses carry request ids, so there is nothing+ to interleave; before this, a parallel tool batch took twice as long."""++ def _client(+ url,+ headers,+ use_oauth = False,+ ):+ c = RecordingClient(url, headers, use_oauth)+ c.call_delay = 0.4+ return c++ monkeypatch.setattr(mcp_client, "_client", _client)+ out, elapsed = _parallel(HTTP_URL, [SCOPE, SCOPE])+ assert len(out) == 2+ assert len(clients) == 1, "the two calls should share one client"+ assert clients[0].max_live == 2, "the server never saw them overlap"+ assert elapsed < 0.75, f"calls were serialized: {elapsed:.2f}s"+++def test_two_stdio_calls_in_one_chat_stay_serialized(monkeypatch, clients):+ """The counterpart that must not change: one subprocess is one ordered byte+ stream, so a browser or REPL must not see two calls interleaved."""++ def _client(+ url,+ headers,+ use_oauth = False,+ ):+ c = RecordingClient(url, headers, use_oauth)+ c.call_delay = 0.3+ return c++ monkeypatch.setattr(mcp_client, "_client", _client)+ out, _ = _parallel(STDIO_URL, [SCOPE, SCOPE], delay = 0.3)+ assert len(out) == 2+ assert len(clients) == 1+ assert clients[0].max_live == 1, "stdio calls overlapped on one subprocess"+++def test_calls_in_different_chats_run_concurrently(monkeypatch, clients):+ def _client(+ url,+ headers,+ use_oauth = False,+ ):+ c = RecordingClient(url, headers, use_oauth)+ c.call_delay = 0.4+ return c++ monkeypatch.setattr(mcp_client, "_client", _client)+ out, elapsed = _parallel(HTTP_URL, [SCOPE, SCOPE_B])+ assert len(out) == 2+ assert len(clients) == 2+ assert elapsed < 0.75, f"different chats were serialized: {elapsed:.2f}s"+++def test_concurrent_first_calls_publish_one_session(monkeypatch, clients):+ def _client(+ url,+ headers,+ use_oauth = False,+ ):+ return _slow_connect(url, headers, use_oauth, 0.3)++ monkeypatch.setattr(mcp_client, "_client", _client)+ out, _ = _parallel(HTTP_URL, [SCOPE, SCOPE])+ assert len(out) == 2+ assert len(clients) == 1, "a connect race opened two clients for one key"+ assert len(mcp_client._mcp_sessions) == 1+++# --------------------------------------------------------------------------+# Stale configuration+# --------------------------------------------------------------------------+++def test_oauth_flip_before_connect_blocks_dispatch(clients):+ """The window: the call read a non-OAuth row, the row flipped, and the route's+ close found nothing cached and no connect in flight, so it had no generation+ to bump. Only the config snapshot can reject this call."""+ row = {"is_enabled": 1, "url": HTTP_URL, "headers": None, "use_oauth": 0}++ def config_check() -> bool:+ return (+ bool(row["is_enabled"])+ and row["url"] == HTTP_URL+ and row["headers"] is None+ and bool(row["use_oauth"]) is False+ )++ reached = threading.Event()+ release = threading.Event()+ real_slot = mcp_client._connect_slot++ def paused_slot(url, headers):+ reached.set()+ release.wait(10)+ return real_slot(url, headers)++ mcp_client._connect_slot = paused_slot+ try:+ out: list[str] = []+ worker = threading.Thread(+ target = lambda: out.append(_call(HTTP_URL, scope = SCOPE, config_check = config_check))+ )+ worker.start()+ assert reached.wait(10)+ row["use_oauth"] = 1+ close_mcp_sessions(HTTP_URL, None)+ release.set()+ worker.join(20)+ finally:+ mcp_client._connect_slot = real_slot++ assert not [c for c in clients if c.calls], "dispatched on a stale non-OAuth client"+ assert mcp_client._mcp_sessions == {}+ assert "updated or removed" in out[0], out+++def test_oauth_flip_before_dispatch_blocks_a_cached_session(clients):+ row = {"use_oauth": 0}+ _call(HTTP_URL, scope = SCOPE, config_check = lambda: not row["use_oauth"])+ assert len(mcp_client._mcp_sessions) == 1+ row["use_oauth"] = 1+ out = _call(HTTP_URL, scope = SCOPE, config_check = lambda: not row["use_oauth"])+ assert "updated or removed" in out, out+ assert mcp_client._mcp_sessions == {}+++def test_url_change_blocks_a_cached_session(clients):+ row = {"url": HTTP_URL}+ _call(HTTP_URL, scope = SCOPE, config_check = lambda: row["url"] == HTTP_URL)+ row["url"] = HTTP_URL_2+ out = _call(HTTP_URL, scope = SCOPE, config_check = lambda: row["url"] == HTTP_URL)+ assert "updated or removed" in out, out+++def test_a_raising_config_check_fails_closed(clients):+ def boom() -> bool:+ raise RuntimeError("db gone")++ out = _call(HTTP_URL, scope = SCOPE, config_check = boom)+ assert "updated or removed" in out, out+ assert mcp_client._mcp_sessions == {}+++# --------------------------------------------------------------------------+# Failure handling+# --------------------------------------------------------------------------+++def test_a_transport_failure_is_never_replayed(clients):+ """The tool may already have run on the server, so a retry could double a+ side effect. Drop the session; the next call reconnects."""+ _call(HTTP_URL, scope = SCOPE)+ attempts = []++ async def _boom(+ name,+ args,+ raise_on_error = True,+ ):+ attempts.append(name)+ raise RuntimeError("stream closed")++ clients[0].call_tool = _boom+ out = _call(HTTP_URL, scope = SCOPE)+ assert out.startswith("Error:"), out+ assert len(attempts) == 1, f"the failed tool was dispatched {len(attempts)} times"+ assert mcp_client._mcp_sessions == {}+ # The session is gone, so the next call reconnects rather than reusing it.+ assert _call(HTTP_URL, scope = SCOPE) == "call-1"+ assert len(clients) == 2+++def test_a_tool_error_keeps_the_session(clients):+ from fastmcp.exceptions import ToolError++ _call(HTTP_URL, scope = SCOPE)++ async def _tool_error(+ name,+ args,+ raise_on_error = True,+ ):+ raise ToolError("nope")++ clients[0].call_tool = _tool_error+ assert _call(HTTP_URL, scope = SCOPE).startswith("Error:")+ assert len(mcp_client._mcp_sessions) == 1+ assert len(clients) == 1+++def test_an_expired_idle_http_session_is_replaced_before_dispatch(monkeypatch, clients):+ """A server may drop an HTTP session whenever it likes and no HTTP transport+ exposes a liveness probe, so the only honest check is to ask it."""+ monkeypatch.setattr(mcp_client, "_HTTP_IDLE_RECHECK", 0.0)+ _call(HTTP_URL, scope = SCOPE)+ clients[0].probe_error = True+ assert _call(HTTP_URL, scope = SCOPE) == "call-1"+ assert len(clients) == 2+ assert _settled(clients[0]) == 1+++def test_a_concurrent_checkout_cannot_cancel_another_borrowers_recheck(monkeypatch, clients):+ """Two HTTP borrowers now run at once, so the idle gap has to belong to the+ borrower. Held on the session, the second checkout would overwrite the first+ one's long gap with a near-zero one and talk it out of proving a session that+ really had gone stale."""+ monkeypatch.setattr(mcp_client, "_HTTP_IDLE_RECHECK", 0.0)++ def _client(+ url,+ headers,+ use_oauth = False,+ ):+ c = RecordingClient(url, headers, use_oauth)+ c.call_delay = 0.3+ return c++ monkeypatch.setattr(mcp_client, "_client", _client)+ _call(HTTP_URL, scope = SCOPE) # connect and publish+ out, _ = _parallel(HTTP_URL, [SCOPE, SCOPE])+ assert len(out) == 2+ # Both were reused after an idle gap, so both must have proved the session.+ assert clients[0].probes == 2, f"a borrower skipped its recheck: {clients[0].probes}"+++def test_a_second_borrower_still_proves_a_session_that_went_idle(monkeypatch, clients):+ """last_used is refreshed at checkout, so a borrower arriving while the first+ one's probe is still outstanding would see a near-zero gap and dispatch on a+ session nobody has proved yet. If the server expired it, that user's call is+ the thing that finds out, and it cannot be replayed."""+ monkeypatch.setattr(mcp_client, "_HTTP_IDLE_RECHECK", 0.2)+ _call(HTTP_URL, scope = SCOPE)+ client = clients[0]+ probes = {"n": 0}+ started = threading.Event()+ real_list = client.list_tools_mcp++ async def gated():+ probes["n"] += 1+ if probes["n"] == 1:+ started.set()+ await asyncio.sleep(0.5) # hold the first probe open+ return await real_list()++ client.list_tools_mcp = gated+ time.sleep(0.3) # past the recheck threshold+ out: list[str] = []+ first = threading.Thread(target = lambda: out.append(_call(HTTP_URL, scope = SCOPE)))+ first.start()+ assert started.wait(10), "the first borrower never began its probe"+ out.append(_call(HTTP_URL, scope = SCOPE))+ first.join(30)+ assert len(out) == 2 and not any(r.startswith("Error:") for r in out), out+ assert probes["n"] == 2, "the second borrower dispatched on an unproven session"+++def test_closing_many_sessions_does_not_run_serially(monkeypatch, clients):+ """A popular HTTP server holds a session per chat, and close runs on the+ request thread during an edit or delete."""+ closes = []++ class SlowExit(RecordingClient):+ async def __aexit__(self, *exc):+ closes.append(time.monotonic())+ await asyncio.sleep(0.4)+ return await super().__aexit__(*exc)++ monkeypatch.setattr(+ mcp_client,+ "_client",+ lambda url, headers, use_oauth = False: SlowExit(url, headers, use_oauth),+ )+ for i in range(6):+ _call(HTTP_URL, scope = f"chat-{i}")+ started = time.monotonic()+ close_mcp_sessions()+ elapsed = time.monotonic() - started+ assert len(closes) == 6+ assert elapsed < 6 * 0.4 * 0.75, f"closes ran serially: {elapsed:.2f}s"+++def test_a_slow_but_live_idle_session_survives_the_recheck(monkeypatch, clients):+ """The recheck exists to catch a session the server dropped. A server that is+ merely slow to answer tools/list has not dropped anything, and retiring it+ there would discard exactly the state this cache is for."""+ monkeypatch.setattr(mcp_client, "_HTTP_IDLE_RECHECK", 0.0)+ monkeypatch.setattr(mcp_client, "_SESSION_LIVENESS_TIMEOUT", 0.2)+ _call(HTTP_URL, scope = SCOPE)+ clients[0].probe_delay = 0.6 # answers, but well past the probe window+ assert _call(HTTP_URL, scope = SCOPE, timeout = 30.0) == "call-2"+ assert len(clients) == 1, "a slow probe retired a healthy session"+++def test_a_tight_deadline_skips_the_probe_and_still_runs_the_tool(monkeypatch, clients):+ """The recheck is there to save someone a failed call, so it must not become+ the reason one fails. tool_call_timeout goes down to 1s, and a probe that+ quietly eats the whole budget leaves nothing to dispatch with."""+ monkeypatch.setattr(mcp_client, "_HTTP_IDLE_RECHECK", 0.0)+ monkeypatch.setattr(mcp_client, "_SESSION_LIVENESS_TIMEOUT", 0.5)+ _call(HTTP_URL, scope = SCOPE)+ clients[0].probe_delay = 1.5+ clients[0].call_delay = 0.2+ assert _call(HTTP_URL, scope = SCOPE, timeout = 0.8) == "call-2"+ assert clients[0].probes == 0, "the probe ran with no budget left for the call"+++def test_evicting_another_scope_does_not_run_on_the_callers_deadline(monkeypatch, clients):+ """Whoever happens to trip the cap is mid tool call. The victim belongs to a+ different chat and nobody is waiting on it, so its teardown must not be+ charged to that caller's budget."""+ monkeypatch.setattr(mcp_client, "_MAX_SESSIONS", 1)+ closed = threading.Event()++ class SlowExit(RecordingClient):+ async def __aexit__(self, *exc):+ await asyncio.sleep(1.5)+ out = await super().__aexit__(*exc)+ closed.set()+ return out++ monkeypatch.setattr(+ mcp_client,+ "_client",+ lambda url, headers, use_oauth = False: SlowExit(url, headers, use_oauth),+ )+ _call(HTTP_URL, scope = SCOPE) # fills the cache+ started = time.monotonic()+ assert _call(HTTP_URL, scope = SCOPE_B) == "call-1"+ elapsed = time.monotonic() - started+ assert elapsed < 0.5, f"the caller paid for an unrelated eviction: {elapsed:.2f}s"+ assert closed.wait(10), "the evicted session was never closed"+++def test_a_json_rpc_error_keeps_the_chats_session(monkeypatch, clients):+ """A FastMCP server answers an unknown tool with a result carrying is_error,+ but the spec also lets a server report it as a protocol error and non-FastMCP+ servers do. Receiving that reply proves the connection works, so discarding+ the session would throw away the chat's server-side state over a tool name+ the model got wrong."""++ class ProtocolError(RecordingClient):+ async def call_tool(+ self,+ name: str,+ args: dict,+ raise_on_error: bool = True,+ ):+ if name == "nope":+ raise _protocol_error(-32602, "Unknown tool: nope")+ return await super().call_tool(name, args, raise_on_error)++ monkeypatch.setattr(+ mcp_client,+ "_client",+ lambda url, headers, use_oauth = False: ProtocolError(url, headers, use_oauth),+ )+ _call(HTTP_URL, scope = SCOPE)+ assert _call(HTTP_URL, "nope", scope = SCOPE).startswith("Error:")+ assert _call(HTTP_URL, scope = SCOPE) == "call-2"+ assert len(clients) == 1, "a protocol error discarded the session"+ # Kept, but no longer taken on trust: the next call proves it first, in case+ # the error was the server saying it no longer knows this session.+ assert clients[0].probes == 1+++def test_a_failed_session_is_not_closed_on_the_retry_budget(monkeypatch, clients):+ """The session that fails the pre-dispatch probe is the one most likely to+ hang on close, and the caller still has a reconnect and a retry to do on the+ same deadline. Paying for its teardown first is what leaves the retry with+ nothing."""+ monkeypatch.setattr(mcp_client, "_HTTP_IDLE_RECHECK", 0.0)++ class HangingExit(RecordingClient):+ async def __aexit__(self, *exc):+ if self.probe_error: # only the session that failed its probe+ await asyncio.sleep(1.5)+ return await super().__aexit__(*exc)++ monkeypatch.setattr(+ mcp_client,+ "_client",+ lambda url, headers, use_oauth = False: HangingExit(url, headers, use_oauth),+ )+ _call(HTTP_URL, scope = SCOPE)+ clients[0].probe_error = True # the server dropped it while it sat idle+ started = time.monotonic()+ assert _call(HTTP_URL, scope = SCOPE) == "call-1"+ elapsed = time.monotonic() - started+ assert len(clients) == 2+ assert elapsed < 1.0, f"the retry waited for the dead session to close: {elapsed:.2f}s"+ assert _settled(clients[0]) == 1+++def test_a_synchronous_close_waits_for_work_already_started(monkeypatch, clients):+ """close_mcp_sessions promises a server edit, and atexit, that the teardown+ has happened. Draining the queue does not recall the session the worker had+ already picked up."""+ monkeypatch.setattr(mcp_client, "_MAX_SESSIONS", 1)+ gate = threading.Event()++ class SlowExit(RecordingClient):+ slow = False++ async def __aexit__(self, *exc):+ if self.slow:+ gate.set()+ await asyncio.sleep(0.6)+ return await super().__aexit__(*exc)++ monkeypatch.setattr(+ mcp_client,+ "_client",+ lambda url, headers, use_oauth = False: SlowExit(url, headers, use_oauth),+ )+ _call(HTTP_URL, scope = SCOPE)+ victim = clients[0]+ # Only the evicted session is slow, so the assertion cannot be satisfied by+ # close_mcp_sessions happening to take just as long on the others.+ victim.slow = True+ _call(HTTP_URL, scope = SCOPE_B) # evicts the first, worker picks it up+ assert gate.wait(10), "the worker never started on the evicted session"+ close_mcp_sessions()+ assert victim.exited == 1, "close_mcp_sessions returned mid-teardown"+++def test_a_surviving_call_does_not_pay_for_the_retirement(monkeypatch, clients):+ """Parallel borrowers share one session, so one transport failure retires it+ while another call is still succeeding. That makes the survivor the last+ borrower, and its result is already waiting on this thread when the close+ would run."""+ closing = threading.Event()++ class SlowExit(RecordingClient):+ async def __aexit__(self, *exc):+ closing.set()+ await asyncio.sleep(1.5)+ return await super().__aexit__(*exc)++ monkeypatch.setattr(+ mcp_client,+ "_client",+ lambda url, headers, use_oauth = False: SlowExit(url, headers, use_oauth),+ )+ _call(HTTP_URL, scope = SCOPE)+ session = next(iter(mcp_client._mcp_sessions.values()))+ client = clients[0]+ client.call_delay = 0.3++ out: list[str] = []+ slow = threading.Thread(target = lambda: out.append(_call(HTTP_URL, scope = SCOPE)))+ slow.start()+ while session.in_flight < 1:+ time.sleep(0.01)+ # A sibling borrower's transport error retires the session under it.+ mcp_client._drop_session(next(iter(mcp_client._mcp_sessions)), session)+ started = time.monotonic()+ slow.join(30)+ elapsed = time.monotonic() - started+ assert out == ["call-2"], out+ assert elapsed < 1.0, f"the surviving call waited on the close: {elapsed:.2f}s"+ assert closing.wait(10), "the retired session was never closed"+++def test_evictions_do_not_spawn_a_thread_each(monkeypatch, clients):+ """A run of new chat scopes against a server that hangs on shutdown would+ otherwise leave a cleanup thread per eviction alive for the close timeout."""+ monkeypatch.setattr(mcp_client, "_MAX_SESSIONS", 1)+ release = threading.Event()++ class HangingExit(RecordingClient):+ async def __aexit__(self, *exc):+ await asyncio.get_running_loop().run_in_executor(None, release.wait, 30)+ return await super().__aexit__(*exc)++ monkeypatch.setattr(+ mcp_client,+ "_client",+ lambda url, headers, use_oauth = False: HangingExit(url, headers, use_oauth),+ )+ try:+ before = threading.active_count()+ for i in range(12): # 11 evictions, all of them stuck in __aexit__+ _call(HTTP_URL, scope = f"chat-{i}")+ # Not a total thread count: a transport stuck in __aexit__ keeps its own+ # session loop thread alive whatever closes it. What must stay bounded is+ # the cleanup machinery itself.+ cleanup = [t for t in threading.enumerate() if t.name in ("mcp-cleanup", "mcp-evict")]+ assert len(cleanup) <= 1, f"a cleanup thread per eviction: {len(cleanup)}"+ assert threading.active_count() >= before+ finally:+ release.set()+++def test_a_json_rpc_error_from_the_probe_keeps_the_session(monkeypatch, clients):+ """The probe asks whether the server is still there. A rate limit or a+ permission rule on tools/list answers that question with a yes, so treating+ it as a dead transport would lose the chat's state over a reply that proves+ the connection works."""+ monkeypatch.setattr(mcp_client, "_HTTP_IDLE_RECHECK", 0.0)++ class ProbeRefused(RecordingClient):+ async def list_tools_mcp(self):+ self.probes += 1+ raise _protocol_error(-32000, "Rate limit exceeded")++ monkeypatch.setattr(+ mcp_client,+ "_client",+ lambda url, headers, use_oauth = False: ProbeRefused(url, headers, use_oauth),+ )+ _call(HTTP_URL, scope = SCOPE)+ assert _call(HTTP_URL, scope = SCOPE) == "call-2"+ assert len(clients) == 1, "a protocol error on the probe replaced the session"+ assert clients[0].probes == 1+++def test_the_queue_of_pending_closes_is_bounded(monkeypatch, clients):+ """One worker bounds the cleanup threads but not the queue: a server that+ hangs on shutdown is closed slower than new chats evict, and every session+ waiting in the queue still holds its own loop thread and connection."""+ monkeypatch.setattr(mcp_client, "_MAX_SESSIONS", 1)+ monkeypatch.setattr(mcp_client, "_MAX_PENDING_CLOSES", 2)+ release = threading.Event()+ depths: list[int] = []++ class HangingExit(RecordingClient):+ async def __aexit__(self, *exc):+ await asyncio.get_running_loop().run_in_executor(None, release.wait, 30)+ return await super().__aexit__(*exc)++ monkeypatch.setattr(+ mcp_client,+ "_client",+ lambda url, headers, use_oauth = False: HangingExit(url, headers, use_oauth),+ )+ try:+ for i in range(6): # 5 evictions, none of which can finish closing+ threading.Thread(target = _call, args = (HTTP_URL,), kwargs = {"scope": f"c{i}"}).start()+ deadline = time.monotonic() + 5.0+ while len(mcp_client._mcp_cleanup_queue) < min(i, 2) and time.monotonic() < deadline:+ time.sleep(0.01)+ depths.append(len(mcp_client._mcp_cleanup_queue))+ assert max(depths) <= 2, f"the queue grew past the bound: {depths}"+ finally:+ release.set()+ for t in threading.enumerate():+ if t.name.startswith("mcp-") and t is not threading.current_thread():+ t.join(5)+++def test_closing_many_sessions_does_not_spawn_a_thread_each(monkeypatch, clients):+ """The cache is allowed to overshoot _MAX_SESSIONS while every session in it+ is busy, so the list close_mcp_sessions is handed has no fixed length, and a+ shutdown is the worst moment to ask for an unbounded number of threads."""+ monkeypatch.setattr(mcp_client, "_MAX_CLOSE_THREADS", 3)+ release = threading.Event()+ live = []+ lock = threading.Lock()++ class HangingExit(RecordingClient):+ async def __aexit__(self, *exc):+ with lock:+ live.append(len([t for t in threading.enumerate() if t.name == "mcp-close"]))+ await asyncio.get_running_loop().run_in_executor(None, release.wait, 30)+ return await super().__aexit__(*exc)++ monkeypatch.setattr(+ mcp_client,+ "_client",+ lambda url, headers, use_oauth = False: HangingExit(url, headers, use_oauth),+ )+ for i in range(9):+ _call(HTTP_URL, scope = f"chat-{i}")+ closer = threading.Thread(target = close_mcp_sessions)+ closer.start()+ deadline = time.monotonic() + 10.0+ while len(live) < 3 and time.monotonic() < deadline:+ time.sleep(0.01)+ try:+ assert max(live) <= 3, f"one close thread per session: {live}"+ assert len(live) == 3, f"only {len(live)} closes started; the fan-out stalled"+ finally:+ release.set()+ closer.join(60)+++def test_a_slow_probe_still_condemns_a_dirty_session(monkeypatch, clients):+ """The counterpart that must not change: a session whose last call was+ abandoned is under suspicion, so silence within the window condemns it."""+ monkeypatch.setattr(mcp_client, "_SESSION_LIVENESS_TIMEOUT", 0.2)+ _call(HTTP_URL, scope = SCOPE)+ clients[0].probe_delay = 0.6+ mcp_client._mcp_sessions[next(iter(mcp_client._mcp_sessions))].dirty = True+ assert _call(HTTP_URL, scope = SCOPE, timeout = 30.0) == "call-1"+ assert len(clients) == 2, "a wedged session was reused"+++def test_a_failed_session_is_uncached_before_the_borrow_is_released(clients):+ """HTTP callers do not queue on call_lock, so between releasing the borrow and+ dropping the key another same-scope call could check the broken transport out+ and dispatch on it."""+ _call(HTTP_URL, scope = SCOPE)+ key = next(iter(mcp_client._mcp_sessions))+ seen = {}+ real_release = mcp_client._release_session++ def watching_release(session, **kw):+ # Whatever a concurrent caller could observe at this instant.+ seen["cached"] = mcp_client._mcp_sessions.get(key) is session+ seen["defunct"] = session.defunct+ return real_release(session, **kw)++ async def _boom(+ name,+ args,+ raise_on_error = True,+ ):+ raise RuntimeError("stream closed")++ clients[0].call_tool = _boom+ mcp_client._release_session = watching_release+ try:+ assert _call(HTTP_URL, scope = SCOPE).startswith("Error:")+ finally:+ mcp_client._release_session = real_release+ assert seen["cached"] is False, "the failed session was still checkout-able"+ assert seen["defunct"] is True+++def test_closing_sessions_works_during_interpreter_exit():+ """close_mcp_sessions is the atexit handler. Python tears the+ ThreadPoolExecutor machinery down before normal atexit callbacks, so a pooled+ close raises there and the cleanup aborts with stdio subprocesses still up.++ Run in a child process: the failure only exists at real interpreter exit."""+ import subprocess+ import textwrap++ script = textwrap.dedent(+ """+ import sys+ sys.path.insert(0, %r)+ from types import SimpleNamespace+ from core.inference import mcp_client++ closed = []++ class S:+ def __init__(self, n): self.n = n+ def close(self): closed.append(self.n)++ # More than one, so the parallel path is taken.+ import atexit+ atexit.register(lambda: print("CLOSED:" + ",".join(sorted(closed))))+ atexit.register(mcp_client._close_all, [S("a"), S("b"), S("c")])+ """+ ) % (_BACKEND_DIR,)+ proc = subprocess.run(+ [sys.executable, "-c", script], capture_output = True, text = True, timeout = 120+ )+ assert "CLOSED:a,b,c" in proc.stdout, f"stdout={proc.stdout!r} stderr={proc.stderr[-2000:]!r}"+ assert "can't register atexit" not in proc.stderr, proc.stderr[-2000:]+ assert "cannot schedule new futures" not in proc.stderr, proc.stderr[-2000:]+++def test_a_fork_resets_the_inherited_cache(clients):+ """Only the forking thread survives, so every inherited session's loop thread+ is gone while its client still reports connected. A child that checked one+ out would wait on a loop that never runs."""+ if not hasattr(mcp_client.os, "register_at_fork"):+ pytest.skip("no register_at_fork on this platform")+ _call(HTTP_URL, scope = SCOPE)+ assert len(mcp_client._mcp_sessions) == 1+ # The real hook runs in a child that is about to exec or exit, so dropping the+ # entries is the whole point. Here it runs in the parent, where those objects+ # are live: hold on to them and close them by hand, or this test leaks a loop+ # thread and its descriptors into every test that follows.+ inherited = list(mcp_client._mcp_sessions.values())+ reaper_was_started = mcp_client._mcp_reaper_started+ try:+ mcp_client._reset_after_fork()+ assert mcp_client._mcp_sessions == {}+ assert mcp_client._mcp_key_locks == {}+ assert mcp_client._mcp_connects_in_flight == 0+ assert mcp_client._mcp_reaper_started is False+ finally:+ for session in inherited:+ session.close()+ # The parent's reaper thread outlived the call above; leaving the flag+ # False would start a second one on the next connect.+ mcp_client._mcp_reaper_started = reaper_was_started+++def test_transport_dead_is_unknown_for_http():+ """Documents why the idle recheck exists at all: _is_session_dead and+ _connect_task are StdioTransport internals, absent from both HTTP transports+ on every fastmcp this repo supports."""+ from fastmcp.client.transports import SSETransport, StreamableHttpTransport+ for cls in (StreamableHttpTransport, SSETransport):+ transport = cls(url = "https://x.test/mcp")+ assert not hasattr(transport, "_is_session_dead")+ assert not hasattr(transport, "_connect_task")+ assert (+ mcp_client._transport_dead(SimpleNamespace(client = SimpleNamespace(transport = transport)))+ is False+ )diff --git a/studio/backend/tests/test_mcp_servers.py b/studio/backend/tests/test_mcp_servers.pyindex f0beeee284a..dbaa8a08dc0 100644--- a/studio/backend/tests/test_mcp_servers.py+++ b/studio/backend/tests/test_mcp_servers.py@@ -168,7 +168,7 @@ def test_stdio_command_codec_windows_preserves_final_whitespace_argument_end_to_monkeypatch.setattr(sys, "platform", "win32")monkeypatch.setattr(routes_mcp, "stdio_mcp_enabled", lambda: True)monkeypatch.setattr(mcp_client, "stdio_mcp_enabled", lambda: True)- monkeypatch.setattr(routes_mcp, "close_stdio_sessions", lambda *args: None)+ monkeypatch.setattr(routes_mcp, "close_mcp_sessions", lambda *args: None)probed_urls: list[str] = []@@ -376,7 +376,7 @@ def test_stdio_raw_nul_is_rejected_before_route_side_effects(tmp_path, monkeypatroutes_mcp, "invalidate_tool_cache", lambda *args: side_effects.append("invalidate"))monkeypatch.setattr(- routes_mcp, "close_stdio_sessions", lambda *args: side_effects.append("close")+ routes_mcp, "close_mcp_sessions", lambda *args: side_effects.append("close"))with pytest.raises(HTTPException):@@ -1298,7 +1298,7 @@ def test_update_rename_keeps_stdio_session(tmp_path, monkeypatch):closed: list = []monkeypatch.setattr(routes_mcp, "stdio_mcp_enabled", lambda: True)- monkeypatch.setattr(routes_mcp, "close_stdio_sessions", lambda *a, **k: closed.append(a))+ monkeypatch.setattr(routes_mcp, "close_mcp_sessions", lambda *a, **k: closed.append(a))mcp_servers_db.create_server(id = "s1",display_name = "A",@@ -1332,7 +1332,7 @@ def test_update_stdio_command_change_closes_session(tmp_path, monkeypatch):closed: list = []monkeypatch.setattr(routes_mcp, "stdio_mcp_enabled", lambda: True)- monkeypatch.setattr(routes_mcp, "close_stdio_sessions", lambda *a, **k: closed.append(a))+ monkeypatch.setattr(routes_mcp, "close_mcp_sessions", lambda *a, **k: closed.append(a))mcp_servers_db.create_server(id = "s1",display_name = "A",@@ -1362,7 +1362,7 @@ def test_stdio_arguments_update_preserves_untouched_bytes_then_invalidates_once(invalidated: list[str] = []closed: list[tuple] = []monkeypatch.setattr(routes_mcp, "invalidate_tool_cache", invalidated.append)- monkeypatch.setattr(routes_mcp, "close_stdio_sessions", lambda *args: closed.append(args))+ monkeypatch.setattr(routes_mcp, "close_mcp_sessions", lambda *args: closed.append(args))cached = _one_tool()monkeypatch.setattr(mcp_client, "_tool_cache", {"s1": cached})diff --git a/studio/backend/tests/test_mcp_session_platforms.py b/studio/backend/tests/test_mcp_session_platforms.pynew file mode 100644index 00000000000..2293b1f7200--- /dev/null+++ b/studio/backend/tests/test_mcp_session_platforms.py@@ -0,0 +1,142 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Platform-dependent behaviour of the shared MCP session machinery.++What these can and cannot prove: Linux does not export asyncio.ProactorEventLoop+at all, so a win32 test has to supply one. That makes these honest tests of which+branch is *chosen*, and no test at all of IOCP, overlapped pipes or Windows handle+cleanup. Those need a Windows runner, and this repo runs studio/backend/tests on+ubuntu only. Do not read a pass here as Windows coverage.+"""++from __future__ import annotations++import asyncio+import os+import sys+from pathlib import Path++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++from core.inference import mcp_client++HTTP_URL = "https://mcp.example.test/mcp"+STDIO_URL = "npx fake-stateful-server"+++class _FakeProactorLoop(asyncio.SelectorEventLoop):+ """Stands in for the loop Linux cannot construct. Only its identity matters:+ the assertion is that the win32 branch asked for a Proactor, not that this+ object behaves like one."""+++def win32(monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setattr(asyncio, "ProactorEventLoop", _FakeProactorLoop, raising = False)+ monkeypatch.setattr(mcp_client, "_IS_WINDOWS", True)+++def posix(monkeypatch):+ """Pin the platform: these assert POSIX semantics and must not follow the runner."""+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.setattr(mcp_client, "_IS_WINDOWS", False)+++def test_windows_sessions_get_a_proactor_loop(win32):+ """A SelectorEventLoop cannot spawn subprocesses on Windows, so an stdio MCP+ server would fail outright if this branch regressed."""+ session = mcp_client._McpSession(STDIO_URL, None)+ try:+ assert isinstance(session.loop, _FakeProactorLoop)+ finally:+ session.close()+++def test_posix_sessions_get_the_default_loop(posix):+ session = mcp_client._McpSession(STDIO_URL, None)+ try:+ assert not isinstance(session.loop, _FakeProactorLoop)+ assert isinstance(session.loop, asyncio.AbstractEventLoop)+ finally:+ session.close()+++def test_the_loop_choice_does_not_depend_on_the_transport(win32):+ """HTTP sessions take the same branch; nothing about the fix made the loop+ choice transport-specific."""+ session = mcp_client._McpSession(HTTP_URL, None)+ try:+ assert isinstance(session.loop, _FakeProactorLoop)+ finally:+ session.close()++[email protected]("platform", ["win32", "darwin", "linux"])+def test_sessions_start_and_stop_cleanly_on_every_platform_branch(monkeypatch, platform):+ monkeypatch.setattr(sys, "platform", platform)+ monkeypatch.setattr(asyncio, "ProactorEventLoop", _FakeProactorLoop, raising = False)+ session = mcp_client._McpSession(HTTP_URL, None)+ session.close()+ assert session.closed.is_set()+ assert not session._thread.is_alive()++[email protected]("platform", ["win32", "darwin", "linux"])+def test_call_serialization_policy_is_platform_independent(monkeypatch, platform):+ """stdio serializes, HTTP does not, on every platform. A platform-dependent+ answer here would mean parallel tool calls behaved differently per OS."""+ monkeypatch.setattr(sys, "platform", platform)+ monkeypatch.setattr(asyncio, "ProactorEventLoop", _FakeProactorLoop, raising = False)+ stdio = mcp_client._McpSession(STDIO_URL, None)+ http = mcp_client._McpSession(HTTP_URL, None)+ try:+ assert stdio.serialize_calls is True+ assert http.serialize_calls is False+ finally:+ stdio.close()+ http.close()++[email protected]("platform", ["win32", "darwin", "linux"])+def test_connect_window_policy_is_platform_independent(monkeypatch, platform):+ monkeypatch.setattr(sys, "platform", platform)+ assert mcp_client._connect_window(HTTP_URL, 300.0) == 300.0+ assert mcp_client._connect_window(STDIO_URL, 300.0) == mcp_client._STDIO_CONNECT_TIMEOUT+ assert mcp_client._connect_window(HTTP_URL, None) is None+ assert mcp_client._connect_window(STDIO_URL, None) is None++[email protected](os.name == "nt", reason = "POSIX fork semantics")+def test_a_forked_child_does_not_inherit_a_usable_session():+ """Only the forking thread survives a fork, so an inherited session's loop+ thread is gone. The child must not believe the cache is usable.++ Asserted from the child by exit code: a child that touches the dead loop+ would hang, and the parent would not see a clean 0."""+ import multiprocessing++ ctx = multiprocessing.get_context("fork")+ session = mcp_client._McpSession(HTTP_URL, None)+ try:+ proc = ctx.Process(target = _child_checks_inherited_thread_is_dead)+ proc.start()+ proc.join(30)+ assert proc.exitcode == 0, f"child exited {proc.exitcode}"+ finally:+ session.close()+++def _child_checks_inherited_thread_is_dead():+ import threading++ # The parent's mcp-session thread does not exist here; anything that waits on+ # it would block forever, so the child must be able to see that.+ names = [t.name for t in threading.enumerate()]+ sys.exit(0 if "mcp-session" not in names else 1)diff --git a/studio/backend/tests/test_mcp_session_resources.py b/studio/backend/tests/test_mcp_session_resources.pynew file mode 100644index 00000000000..bae4252dd0c--- /dev/null+++ b/studio/backend/tests/test_mcp_session_resources.py@@ -0,0 +1,235 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Resource accounting for shared MCP sessions.++Every cached session owns an event loop on its own daemon thread, and the cache+now holds HTTP sessions too, so the count is driven by how many chats are open+rather than how many stdio servers are configured. These assert the threads and+descriptors come back, and that the cache stays inside its cap.++Counts settle rather than being sampled once: a session thread is stopped by the+loop, so it exits shortly after close() returns.+"""++from __future__ import annotations++import gc+import sys+import threading+import time+from pathlib import Path+from types import SimpleNamespace++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++from core.inference import mcp_client+from core.inference.mcp_client import call_tool_sync, close_mcp_sessions++HTTP_URL = "https://mcp.example.test/mcp"+STDIO_URL = "npx fake-stateful-server"+++def _settled(+ client,+ expected: int = 1,+ timeout: float = 10.0,+) -> int:+ """Wait out an asynchronous close.++ A discarded session is closed by the cleanup worker rather than on the+ request thread, so its close lands just after the call returns."""+ deadline = time.monotonic() + timeout+ while client.exited < expected and time.monotonic() < deadline:+ time.sleep(0.005)+ return client.exited+++def _result(text: str) -> SimpleNamespace:+ return SimpleNamespace(+ content = [SimpleNamespace(type = "text", text = text)],+ is_error = False,+ structured_content = None,+ )+++class TinyClient:+ instances: list["TinyClient"] = []++ def __init__(self, url: str):+ self.url = url+ self.connected = False+ self.exited = 0+ self.transport = SimpleNamespace()+ TinyClient.instances.append(self)++ async def list_tools_mcp(self):+ return SimpleNamespace(tools = [])++ async def __aenter__(self):+ self.connected = True+ return self++ async def __aexit__(self, *exc):+ self.exited += 1+ self.connected = False++ def is_connected(self) -> bool:+ return self.connected++ async def call_tool(+ self,+ name,+ args,+ raise_on_error = True,+ ):+ return _result("ok")+++def tiny(monkeypatch):+ TinyClient.instances = []+ monkeypatch.setattr(+ mcp_client, "_client", lambda url, headers, use_oauth = False: TinyClient(url)+ )+ yield TinyClient.instances+ close_mcp_sessions()+++def _session_threads() -> int:+ return sum(1 for t in threading.enumerate() if t.name == "mcp-session")+++def _settle(predicate, timeout = 10.0) -> bool:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if predicate():+ return True+ time.sleep(0.05)+ return predicate()+++def _open_fds() -> int:+ try:+ return len(list(Path("/proc/self/fd").iterdir()))+ except OSError:+ pytest.skip("no /proc on this platform")+++def test_a_closed_session_gives_its_thread_back(tiny):+ before = _session_threads()+ call_tool_sync(HTTP_URL, None, "t", {}, scope = "chat")+ assert _session_threads() > before+ close_mcp_sessions()+ assert _settle(lambda: _session_threads() <= before), "the session thread outlived close()"+++def test_repeated_open_close_does_not_accumulate_threads(tiny):+ before = _session_threads()+ for i in range(12):+ call_tool_sync(HTTP_URL, None, "t", {}, scope = f"chat-{i}")+ close_mcp_sessions()+ assert _settle(lambda: _session_threads() <= before), (+ f"leaked threads after 12 cycles: {_session_threads()} vs {before}"+ )+++def test_repeated_open_close_does_not_accumulate_descriptors(tiny):+ for i in range(5): # warm up: the first loops allocate lazily+ call_tool_sync(HTTP_URL, None, "t", {}, scope = f"warm-{i}")+ close_mcp_sessions()+ baseline = _session_threads()+ _settle(lambda: _session_threads() <= baseline)+ before = _open_fds()+ for i in range(12):+ call_tool_sync(HTTP_URL, None, "t", {}, scope = f"chat-{i}")+ close_mcp_sessions()+ _settle(lambda: _session_threads() <= baseline)+ gc.collect()+ # An event loop costs a couple of descriptors, so allow slack for scheduling+ # rather than demanding an exact match; a leak shows up as growth per cycle.+ assert _open_fds() <= before + 4, f"descriptors grew {before} -> {_open_fds()}"+++def test_every_cached_client_is_exited_on_close(tiny):+ for i in range(6):+ call_tool_sync(HTTP_URL, None, "t", {}, scope = f"chat-{i}")+ assert len(mcp_client._mcp_sessions) == 6+ close_mcp_sessions()+ assert all(_settled(c) == 1 for c in tiny), [c.exited for c in tiny]+++def test_the_cache_stays_within_its_cap(monkeypatch, tiny):+ # Thread counts are process-global and other modules in the run may still be+ # winding sessions down, so compare against a baseline rather than zero.+ before = _session_threads()+ monkeypatch.setattr(mcp_client, "_MAX_SESSIONS", 3)+ for i in range(10):+ call_tool_sync(HTTP_URL, None, "t", {}, scope = f"chat-{i}")+ assert len(mcp_client._mcp_sessions) <= 3+ assert _settle(lambda: _session_threads() - before <= 3), _session_threads() - before+++def test_http_and_stdio_sessions_share_one_cap(monkeypatch, tiny):+ """Worth pinning: the cap used to bound stdio subprocesses only, so a chat+ that talks to HTTP servers can now evict a stateful stdio session."""+ monkeypatch.setattr(mcp_client, "_MAX_SESSIONS", 2)+ call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat-1")+ for i in range(5):+ call_tool_sync(HTTP_URL, None, "t", {}, scope = f"http-{i}")+ assert len(mcp_client._mcp_sessions) <= 2+++def test_key_locks_do_not_pile_up(tiny):+ for i in range(20):+ call_tool_sync(HTTP_URL, None, "t", {}, scope = f"chat-{i}")+ close_mcp_sessions()+ assert mcp_client._mcp_key_locks == {}, mcp_client._mcp_key_locks+++def test_a_close_with_nothing_cached_leaves_no_tombstone(tiny):+ # Scoped to this url: the generation maps are module-global and earlier tests+ # in the same process legitimately leave entries for servers they did cache.+ url = "https://never-used.example.test/mcp"+ cfg = mcp_client._cfg_close_key(url, None)+ url_key = mcp_client._url_close_key(url)+ close_mcp_sessions(url, None)+ assert cfg not in mcp_client._mcp_cfg_close_gen+ assert url_key not in mcp_client._mcp_url_close_gen+++def test_idle_sessions_are_reaped(monkeypatch, tiny):+ before = _session_threads()+ call_tool_sync(HTTP_URL, None, "t", {}, scope = "chat")+ assert len(mcp_client._mcp_sessions) == 1+ mcp_client._reap_idle_sessions(now = time.monotonic() + mcp_client._SESSION_IDLE_TTL + 1)+ assert mcp_client._mcp_sessions == {}+ assert _settle(lambda: _session_threads() <= before)+ assert _settled(tiny[0]) == 1+++def test_shutdown_of_a_full_cache_is_bounded(monkeypatch, tiny):+ """close_mcp_sessions() runs on the request thread during a server edit, so a+ cache full of sessions must not stall it for minutes."""+ monkeypatch.setattr(mcp_client, "_MAX_SESSIONS", 16)+ for i in range(16):+ call_tool_sync(HTTP_URL, None, "t", {}, scope = f"chat-{i}")+ started = time.monotonic()+ close_mcp_sessions()+ assert time.monotonic() - started < 20.0, "closing a full cache took too long"+++def test_sessions_are_collectable_after_close(tiny):+ import weakref++ call_tool_sync(HTTP_URL, None, "t", {}, scope = "chat")+ ref = weakref.ref(next(iter(mcp_client._mcp_sessions.values())))+ threads = _session_threads()+ close_mcp_sessions()+ _settle(lambda: _session_threads() < threads)+ gc.collect()+ assert ref() is None, "a closed session is still referenced"diff --git a/studio/backend/tests/test_mcp_stdio_sessions.py b/studio/backend/tests/test_mcp_stdio_sessions.pyindex e9a63c3ac17..391568749c3 100644--- a/studio/backend/tests/test_mcp_stdio_sessions.py+++ b/studio/backend/tests/test_mcp_stdio_sessions.py@@ -17,12 +17,27 @@ if _BACKEND_DIR not in sys.path:sys.path.insert(0, _BACKEND_DIR)from core.inference import mcp_client-from core.inference.mcp_client import call_tool_sync, close_stdio_sessions+from core.inference.mcp_client import call_tool_sync, close_mcp_sessionsSTDIO_URL = "npx fake-stateful-server"HTTP_URL = "https://mcp.example.test/mcp"+def _settled(+ client,+ expected: int = 1,+ timeout: float = 10.0,+) -> int:+ """Wait out an asynchronous close.++ A discarded session is closed by the cleanup worker rather than on the+ request thread, so its close lands just after the call returns."""+ deadline = time.monotonic() + timeout+ while client.exited < expected and time.monotonic() < deadline:+ time.sleep(0.005)+ return client.exited++def _result(text: str) -> SimpleNamespace:return SimpleNamespace(content = [SimpleNamespace(type = "text", text = text)],@@ -98,7 +113,7 @@ def fake_clients(monkeypatch):mcp_client, "_client", lambda url, headers, use_oauth = False: FakeClient(url))yield FakeClient.instances- close_stdio_sessions()+ close_mcp_sessions()def test_stdio_call_without_scope_is_one_shot(fake_clients):@@ -107,7 +122,7 @@ def test_stdio_call_without_scope_is_one_shot(fake_clients):assert r1 == "call-1"assert r2 == "call-1"assert len(fake_clients) == 2- assert all(client.entered == 1 and client.exited == 1 for client in fake_clients)+ assert all(client.entered == 1 and _settled(client) == 1 for client in fake_clients)def test_stdio_sessions_keyed_by_url_and_env(fake_clients):@@ -133,7 +148,7 @@ def test_dead_stdio_session_recovers(fake_clients):fake_clients[0].dead = Trueassert call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat") == "call-1"assert len(fake_clients) == 2- assert fake_clients[0].exited == 1+ assert _settled(fake_clients[0]) == 1def test_tool_error_does_not_recycle_session(fake_clients, monkeypatch):@@ -158,13 +173,6 @@ def test_tool_error_does_not_recycle_session(fake_clients, monkeypatch):assert len(fake_clients) == 1-def test_http_stays_one_shot(fake_clients):- call_tool_sync(HTTP_URL, None, "t", {})- call_tool_sync(HTTP_URL, None, "t", {})- assert len(fake_clients) == 2- assert all(c.entered == 1 and c.exited == 1 for c in fake_clients)--def test_timeout_keeps_a_responsive_stdio_session(fake_clients):# A stateful server (browser, DB handle) must survive one slow call.call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat")@@ -204,8 +212,8 @@ def test_timeout_replaces_a_wedged_stdio_session(fake_clients):assert "timed out" in outassert call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat") == "call-1"assert len(fake_clients) == 2- assert fake_clients[0].exited == 1- assert key in mcp_client._stdio_sessions+ assert _settled(fake_clients[0]) == 1+ assert key in mcp_client._mcp_sessionsdef test_dirty_session_probe_stays_inside_the_caller_timeout(fake_clients):@@ -225,7 +233,7 @@ def test_dirty_session_probe_stays_inside_the_caller_timeout(fake_clients):)started = time.monotonic()call_tool_sync(STDIO_URL, None, "t", {}, timeout = 0.2, scope = "chat")- assert time.monotonic() - started < mcp_client._STDIO_LIVENESS_TIMEOUT+ assert time.monotonic() - started < mcp_client._SESSION_LIVENESS_TIMEOUTdef test_failed_probe_replaces_the_session(fake_clients):@@ -246,7 +254,7 @@ def test_failed_probe_replaces_the_session(fake_clients):fake_clients[0].call_delay = 0.0assert call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat") == "call-1"assert len(fake_clients) == 2- assert fake_clients[0].exited == 1+ assert _settled(fake_clients[0]) == 1def test_successful_probe_is_not_repeated(fake_clients):@@ -295,7 +303,7 @@ def test_stop_interrupts_a_hanging_dirty_probe(fake_clients):timeout = 30,)assert out == "Error: MCP tool 't' cancelled"- assert time.monotonic() - started < mcp_client._STDIO_LIVENESS_TIMEOUT+ assert time.monotonic() - started < mcp_client._SESSION_LIVENESS_TIMEOUTdef test_unwind_budget_comes_out_of_the_caller_deadline():@@ -311,18 +319,18 @@ def test_liveness_probe_runs_without_the_wedge_margin(fake_clients, monkeypatch)# The probe's whole budget is its window, so a wedged loop must not add the# 15s margin on top of the caller's timeout.margins = []- real_run = mcp_client._StdioSession.run+ real_run = mcp_client._McpSession.rundef spy(self,coro,timeout,- margin = mcp_client._STDIO_WEDGE_MARGIN,+ margin = mcp_client._SESSION_WEDGE_MARGIN,):margins.append(margin)return real_run(self, coro, timeout, margin)- monkeypatch.setattr(mcp_client._StdioSession, "run", spy)+ monkeypatch.setattr(mcp_client._McpSession, "run", spy)call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat")fake_clients[0].call_delay = 0.5call_tool_sync(@@ -338,7 +346,7 @@ def test_liveness_probe_runs_without_the_wedge_margin(fake_clients, monkeypatch)margins.clear()call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat")# The dirty session is probed first, then the call itself dispatches.- assert margins == [0.0, mcp_client._STDIO_WEDGE_MARGIN]+ assert margins == [0.0, mcp_client._SESSION_WEDGE_MARGIN]def test_unwind_wait_only_for_cached_sessions(fake_clients, monkeypatch):@@ -405,7 +413,7 @@ def test_connect_races_cancel_event(fake_clients, monkeypatch):out = call_tool_sync(STDIO_URL, None, "t", {}, cancel_event = ev)assert out == "Error: MCP tool 't' cancelled"assert time.monotonic() - start < 3.0- assert mcp_client._stdio_sessions == {}+ assert mcp_client._mcp_sessions == {}def test_connect_respects_caller_timeout(fake_clients, monkeypatch):@@ -419,7 +427,7 @@ def test_connect_respects_caller_timeout(fake_clients, monkeypatch):out = call_tool_sync(STDIO_URL, None, "t", {}, timeout = 0.2)assert "timed out" in outassert time.monotonic() - start < 3.0- assert mcp_client._stdio_sessions == {}+ assert mcp_client._mcp_sessions == {}def test_connect_failure_timeout_surfaces_immediately(fake_clients, monkeypatch):@@ -435,7 +443,7 @@ def test_connect_failure_timeout_surfaces_immediately(fake_clients, monkeypatch)assert "timed out" in out# Must fail fast, not wait out the 30s/60s connect window.assert time.monotonic() - start < 5.0- assert mcp_client._stdio_sessions == {}+ assert mcp_client._mcp_sessions == {}def test_key_lock_wait_honors_cancel_and_timeout(fake_clients, monkeypatch):@@ -450,7 +458,7 @@ def test_key_lock_wait_honors_cancel_and_timeout(fake_clients, monkeypatch):key = mcp_client._session_key(STDIO_URL, None, "chat")deadline = time.monotonic() + 5.0while time.monotonic() < deadline:- key_lock = mcp_client._stdio_key_locks.get(key)+ key_lock = mcp_client._mcp_key_locks.get(key)if key_lock is not None and key_lock.lock.locked():breaktime.sleep(0.01)@@ -481,12 +489,12 @@ def test_cancel_pre_set_spawns_nothing(fake_clients):def test_idle_reap_closes_session(fake_clients, monkeypatch):call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat")key = mcp_client._session_key(STDIO_URL, None, "chat")- assert key in mcp_client._stdio_key_locks- monkeypatch.setattr(mcp_client, "_STDIO_SESSION_IDLE_TTL", 0.0)- mcp_client._reap_idle_stdio_sessions()- assert fake_clients[0].exited == 1- assert mcp_client._stdio_sessions == {}- assert key not in mcp_client._stdio_key_locks+ assert key in mcp_client._mcp_key_locks+ monkeypatch.setattr(mcp_client, "_SESSION_IDLE_TTL", 0.0)+ mcp_client._reap_idle_sessions()+ assert _settled(fake_clients[0]) == 1+ assert mcp_client._mcp_sessions == {}+ assert key not in mcp_client._mcp_key_locks# Next call transparently opens a fresh session.assert call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat") == "call-1"assert len(fake_clients) == 2@@ -494,15 +502,15 @@ def test_idle_reap_closes_session(fake_clients, monkeypatch):def test_reap_skips_in_flight_session(fake_clients, monkeypatch):call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat")- monkeypatch.setattr(mcp_client, "_STDIO_SESSION_IDLE_TTL", 0.0)- session = next(iter(mcp_client._stdio_sessions.values()))- with mcp_client._stdio_sessions_lock:+ monkeypatch.setattr(mcp_client, "_SESSION_IDLE_TTL", 0.0)+ session = next(iter(mcp_client._mcp_sessions.values()))+ with mcp_client._mcp_sessions_lock:session.in_flight = 1try:- mcp_client._reap_idle_stdio_sessions()+ mcp_client._reap_idle_sessions()assert fake_clients[0].exited == 0finally:- with mcp_client._stdio_sessions_lock:+ with mcp_client._mcp_sessions_lock:session.in_flight = 0@@ -523,11 +531,11 @@ def test_close_during_connect_is_not_cached(fake_clients, monkeypatch):time.sleep(0.01)assert fake_clients # connect is in progress# Server deleted/updated mid-connect: the session must not be cached after.- close_stdio_sessions(STDIO_URL)+ close_mcp_sessions(STDIO_URL)worker.join(10.0)assert results and results[0].startswith("Error: MCP tool 't' failed")- assert mcp_client._stdio_sessions == {}- assert fake_clients[0].exited == 1+ assert mcp_client._mcp_sessions == {}+ assert _settled(fake_clients[0]) == 1def test_connect_abort_race_still_closes_client(fake_clients, monkeypatch):@@ -543,13 +551,13 @@ def test_connect_abort_race_still_closes_client(fake_clients, monkeypatch):out = call_tool_sync(STDIO_URL, None, "t", {}, timeout = 0.1)assert "timed out" in outassert fake_clients[0].entered == 1- assert fake_clients[0].exited == 1 # no orphaned subprocess- assert mcp_client._stdio_sessions == {}+ assert _settled(fake_clients[0]) == 1 # no orphaned subprocess+ assert mcp_client._mcp_sessions == {}def test_close_unblocks_no_limit_call(fake_clients):call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat")- session = next(iter(mcp_client._stdio_sessions.values()))+ session = next(iter(mcp_client._mcp_sessions.values()))fake_clients[0].call_delay = 30.0results: list[str] = []worker = threading.Thread(@@ -560,13 +568,13 @@ def test_close_unblocks_no_limit_call(fake_clients):worker.start()deadline = time.monotonic() + 5.0while time.monotonic() < deadline:- with mcp_client._stdio_sessions_lock:+ with mcp_client._mcp_sessions_lock:if session.in_flight >= 1:breaktime.sleep(0.01)# Server deleted while a no-limit call is in flight: the request thread# must not hang forever on the stopped session loop.- close_stdio_sessions(STDIO_URL)+ close_mcp_sessions(STDIO_URL)worker.join(5.0)assert not worker.is_alive()assert results and results[0].startswith("Error: MCP tool 'slow' failed")@@ -574,7 +582,7 @@ def test_close_unblocks_no_limit_call(fake_clients):def test_lock_wait_timeout_spares_the_borrowed_session(fake_clients):call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat")- session = next(iter(mcp_client._stdio_sessions.values()))+ session = next(iter(mcp_client._mcp_sessions.values()))fake_clients[0].call_delay = 1.0results: list[str] = []slow = threading.Thread(@@ -585,7 +593,7 @@ def test_lock_wait_timeout_spares_the_borrowed_session(fake_clients):slow.start()deadline = time.monotonic() + 5.0while time.monotonic() < deadline:- with mcp_client._stdio_sessions_lock:+ with mcp_client._mcp_sessions_lock:if session.in_flight >= 1:breaktime.sleep(0.01)@@ -597,12 +605,12 @@ def test_lock_wait_timeout_spares_the_borrowed_session(fake_clients):slow.join(10.0)assert results == ["call-2"]assert fake_clients[0].exited == 0- assert len(mcp_client._stdio_sessions) == 1+ assert len(mcp_client._mcp_sessions) == 1def test_stale_session_close_deferred_until_borrower_drains(fake_clients):call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat")- session = next(iter(mcp_client._stdio_sessions.values()))+ session = next(iter(mcp_client._mcp_sessions.values()))fake_clients[0].call_delay = 0.8results: list[str] = []slow = threading.Thread(@@ -613,7 +621,7 @@ def test_stale_session_close_deferred_until_borrower_drains(fake_clients):slow.start()deadline = time.monotonic() + 5.0while time.monotonic() < deadline:- with mcp_client._stdio_sessions_lock:+ with mcp_client._mcp_sessions_lock:if session.in_flight >= 1:breaktime.sleep(0.01)@@ -626,13 +634,15 @@ def test_stale_session_close_deferred_until_borrower_drains(fake_clients):assert fake_clients[0].exited == 0slow.join(10.0)assert results == ["call-2"]- assert fake_clients[0].exited == 1 # last borrower performed the deferred close- assert len(mcp_client._stdio_sessions) == 1+ # The last borrower hands the deferred close to the cleanup worker rather+ # than paying for it after its own result is ready.+ assert _settled(fake_clients[0]) == 1+ assert len(mcp_client._mcp_sessions) == 1def test_error_on_closed_session_does_not_retry(fake_clients):call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat")- session = next(iter(mcp_client._stdio_sessions.values()))+ session = next(iter(mcp_client._mcp_sessions.values()))# A close can surface at the borrower as a plain transport error instead# of _SessionClosed; that must not be treated as a crash and retried.fake_clients[0].fail_next = True@@ -647,15 +657,15 @@ def test_config_check_blocks_stale_publish(fake_clients):# the row re-check runs after connect and must block caching.out = call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat", config_check = lambda: False)assert out.startswith("Error: MCP tool 't' failed")- assert mcp_client._stdio_sessions == {}- assert fake_clients[0].exited == 1+ assert mcp_client._mcp_sessions == {}+ assert _settled(fake_clients[0]) == 1def test_close_generation_keys_hold_no_secrets(fake_clients):secret_url = "npx server --token sk-url-secret"- close_stdio_sessions(secret_url, {"API_KEY": "sk-env-secret"})- close_stdio_sessions(secret_url)- gen_keys = list(mcp_client._stdio_cfg_close_gen) + list(mcp_client._stdio_url_close_gen)+ close_mcp_sessions(secret_url, {"API_KEY": "sk-env-secret"})+ close_mcp_sessions(secret_url)+ gen_keys = list(mcp_client._mcp_cfg_close_gen) + list(mcp_client._mcp_url_close_gen)assert gen_keys# These maps are never pruned: neither command/URL nor env may persist.assert all("sk-url-secret" not in repr(k) and "sk-env-secret" not in repr(k) for k in gen_keys)@@ -726,24 +736,24 @@ def test_close_narrowed_by_headers_spares_other_env(fake_clients):call_tool_sync(STDIO_URL, {"ENV_VAR": "b"}, "t", {}, scope = "chat")# Two server rows can share a command with different envs; editing one# must only close its own sessions.- close_stdio_sessions(STDIO_URL, None)- assert fake_clients[0].exited == 1+ close_mcp_sessions(STDIO_URL, None)+ assert _settled(fake_clients[0]) == 1assert fake_clients[1].exited == 0- assert len(mcp_client._stdio_sessions) == 1- close_stdio_sessions(STDIO_URL) # headers omitted: any env for the command- assert fake_clients[1].exited == 1- assert mcp_client._stdio_sessions == {}+ assert len(mcp_client._mcp_sessions) == 1+ close_mcp_sessions(STDIO_URL) # headers omitted: any env for the command+ assert _settled(fake_clients[1]) == 1+ assert mcp_client._mcp_sessions == {}def test_close_stdio_sessions_by_url(fake_clients):call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat")call_tool_sync("npx other-server", None, "t", {}, scope = "chat")key = mcp_client._session_key(STDIO_URL, None, "chat")- close_stdio_sessions(STDIO_URL)- assert fake_clients[0].exited == 1+ close_mcp_sessions(STDIO_URL)+ assert _settled(fake_clients[0]) == 1assert fake_clients[1].exited == 0- assert len(mcp_client._stdio_sessions) == 1- assert key not in mcp_client._stdio_key_locks+ assert len(mcp_client._mcp_sessions) == 1+ assert key not in mcp_client._mcp_key_locksdef test_execute_tool_mcp_scope_is_per_thread(tmp_path, monkeypatch):@@ -824,7 +834,7 @@ def test_stdio_cache_trims_overshoot_after_burst(fake_clients, monkeypatch):# A concurrent burst of distinct-scope calls can overshoot the cap while every# session is busy (insert-time eviction only reclaims idle sessions). Once the# calls finish, release-time trimming must bring the cache back within cap.- monkeypatch.setattr(mcp_client, "_STDIO_MAX_SESSIONS", 2)+ monkeypatch.setattr(mcp_client, "_MAX_SESSIONS", 2)def slow_client(url,@@ -850,19 +860,127 @@ def test_stdio_cache_trims_overshoot_after_burst(fake_clients, monkeypatch):for thread in threads:thread.join(10.0)assert not errors, errors- assert len(mcp_client._stdio_sessions) <= 2+ assert len(mcp_client._mcp_sessions) <= 2-def test_close_http_server_creates_no_stdio_tombstone(fake_clients):- # HTTP/SSE servers are never cached as stdio sessions, so closing one on- # update/delete must not accrue a close-generation entry (an unbounded leak).- before_cfg = len(mcp_client._stdio_cfg_close_gen)- before_url = len(mcp_client._stdio_url_close_gen)+def test_close_with_nothing_cached_creates_no_tombstone(fake_clients):+ before_cfg = len(mcp_client._mcp_cfg_close_gen)+ before_url = len(mcp_client._mcp_url_close_gen)for i in range(50):- close_stdio_sessions(f"https://mcp-{i}.example/mcp", {"K": str(i)})- close_stdio_sessions(f"https://mcp-{i}.example/mcp")- assert len(mcp_client._stdio_cfg_close_gen) == before_cfg- assert len(mcp_client._stdio_url_close_gen) == before_url- # a real stdio command still registers a generation (the guard is non-stdio only)- close_stdio_sessions(STDIO_URL, {"K": "v"})- assert len(mcp_client._stdio_cfg_close_gen) == before_cfg + 1+ close_mcp_sessions(f"https://mcp-{i}.example/mcp", {"K": str(i)})+ close_mcp_sessions(f"https://mcp-{i}.example/mcp")+ assert len(mcp_client._mcp_cfg_close_gen) == before_cfg+ assert len(mcp_client._mcp_url_close_gen) == before_url+ cfg = mcp_client._cfg_close_key(STDIO_URL, None)+ before_gen = mcp_client._mcp_cfg_close_gen.get(cfg, 0)+ call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat")+ close_mcp_sessions(STDIO_URL, None)+ assert mcp_client._mcp_cfg_close_gen[cfg] == before_gen + 1+++def test_http_session_reused_across_calls_in_one_scope(fake_clients):+ save = call_tool_sync(HTTP_URL, None, "save_note", {"text": "buy milk"}, scope = "chat")+ assert save == "call-1"+ assert call_tool_sync(HTTP_URL, None, "list_notes", {}, scope = "chat") == "call-2"+ assert len(fake_clients) == 1+ assert fake_clients[0].entered == 1+ assert fake_clients[0].exited == 0+++def test_http_sessions_scoped_and_keyed(fake_clients):+ call_tool_sync(HTTP_URL, None, "t", {}, scope = "chat-a")+ call_tool_sync(HTTP_URL, None, "t", {}, scope = "chat-b")+ call_tool_sync(HTTP_URL, {"Authorization": "Bearer x"}, "t", {}, scope = "chat-a")+ call_tool_sync(HTTP_URL, None, "t", {}, scope = "chat-a")+ assert len(fake_clients) == 3+ assert len(fake_clients[0].calls) == 2+++def test_http_call_without_scope_is_one_shot(fake_clients):+ call_tool_sync(HTTP_URL, None, "t", {})+ call_tool_sync(HTTP_URL, None, "t", {})+ assert len(fake_clients) == 2+ assert all(client.entered == 1 and _settled(client) == 1 for client in fake_clients)+ assert mcp_client._mcp_sessions == {}+++def test_http_oauth_call_stays_one_shot(fake_clients):+ call_tool_sync(HTTP_URL, None, "t", {}, scope = "chat", use_oauth = True)+ call_tool_sync(HTTP_URL, None, "t", {}, scope = "chat", use_oauth = True)+ assert len(fake_clients) == 2+ assert mcp_client._mcp_sessions == {}+++def test_close_mcp_sessions_drops_http_session(fake_clients):+ call_tool_sync(HTTP_URL, None, "t", {}, scope = "chat")+ assert len(mcp_client._mcp_sessions) == 1+ close_mcp_sessions(HTTP_URL, None)+ assert mcp_client._mcp_sessions == {}+ assert _settled(fake_clients[0]) == 1+ call_tool_sync(HTTP_URL, None, "t", {}, scope = "chat")+ assert len(fake_clients) == 2+++def test_dead_http_session_recovers(monkeypatch, fake_clients):+ """An HTTP server that dropped the session while it sat idle is replaced+ before the next tool call, not after it fails.++ Deliberately not driven through FakeClient.dead: _is_session_dead is a+ StdioTransport internal, and no real HTTP transport has ever exposed it (see+ _transport_dead), so faking it here would test a mechanism that cannot fire+ in production. The idle recheck is what actually catches this."""+ monkeypatch.setattr(mcp_client, "_HTTP_IDLE_RECHECK", 0.0)+ assert call_tool_sync(HTTP_URL, None, "t", {}, scope = "chat") == "call-1"+ # The server forgot the session: the liveness probe is what notices.+ fake_clients[0].probe_error = True+ assert call_tool_sync(HTTP_URL, None, "t", {}, scope = "chat") == "call-1"+ assert len(fake_clients) == 2+ assert _settled(fake_clients[0]) == 1+++def test_live_idle_http_session_survives_the_recheck(monkeypatch, fake_clients):+ """The recheck costs one tools/list; a server that answers keeps its session+ and its state, otherwise the idle probe would defeat the whole PR."""+ monkeypatch.setattr(mcp_client, "_HTTP_IDLE_RECHECK", 0.0)+ assert call_tool_sync(HTTP_URL, None, "t", {}, scope = "chat") == "call-1"+ assert call_tool_sync(HTTP_URL, None, "t", {}, scope = "chat") == "call-2"+ assert len(fake_clients) == 1+ # Probed on the second call only: the first went through a fresh connect,+ # which needs no proving.+ assert fake_clients[0].probes == 1+++def test_recently_used_http_session_is_not_reprobed(fake_clients):+ """Back-to-back calls must not pay a probe each; only an idle gap triggers it."""+ call_tool_sync(HTTP_URL, None, "t", {}, scope = "chat")+ call_tool_sync(HTTP_URL, None, "t", {}, scope = "chat")+ assert fake_clients[0].probes == 0+++def test_idle_stdio_session_is_not_reprobed(monkeypatch, fake_clients):+ """stdio is exempt: _transport_dead answers there, and a live subprocess does+ not expire on its own the way a server-side HTTP session does."""+ monkeypatch.setattr(mcp_client, "_HTTP_IDLE_RECHECK", 0.0)+ call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat")+ call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat")+ assert fake_clients[0].probes == 0+ assert len(fake_clients) == 1+++def test_http_tool_error_keeps_session(fake_clients):+ from fastmcp.exceptions import ToolError++ call_tool_sync(HTTP_URL, None, "t", {}, scope = "chat")++ async def _tool_error(+ name,+ args,+ raise_on_error = True,+ ):+ raise ToolError("nope")++ session_client = fake_clients[0]+ session_client.call_tool = _tool_error+ assert call_tool_sync(HTTP_URL, None, "t", {}, scope = "chat").startswith("Error:")+ assert len(mcp_client._mcp_sessions) == 1+ assert len(fake_clients) == 1diff --git a/studio/backend/tests/test_mcp_tool_read_off_event_loop.py b/studio/backend/tests/test_mcp_tool_read_off_event_loop.pyindex 7897b00ca5b..c95643c735d 100644--- a/studio/backend/tests/test_mcp_tool_read_off_event_loop.py+++ b/studio/backend/tests/test_mcp_tool_read_off_event_loop.py@@ -151,7 +151,7 @@ def test_the_cached_row_and_tools_are_one_snapshot_during_an_edit(monkeypatch):)monkeypatch.setattr(mcp_routes.mcp_servers_db, "update_server", _update_server)monkeypatch.setattr(mcp_routes, "invalidate_tool_cache", _invalidate)- monkeypatch.setattr(mcp_routes, "close_stdio_sessions", lambda *_args, **_kwargs: None)+ monkeypatch.setattr(mcp_routes, "close_mcp_sessions", lambda *_args, **_kwargs: None)monkeypatch.setattr(mcp_routes, "_row_to_response", lambda row, **_kwargs: row)async def _read_snapshot():@@ -199,7 +199,7 @@ def test_queued_updates_recheck_the_stdio_api_key_gate(monkeypatch):monkeypatch.setattr(mcp_routes.mcp_servers_db, "get_server", lambda _id: dict(state["row"]))monkeypatch.setattr(mcp_routes.mcp_servers_db, "update_server", _update_server)monkeypatch.setattr(mcp_routes, "invalidate_tool_cache", lambda _server_id: None)- monkeypatch.setattr(mcp_routes, "close_stdio_sessions", lambda *_args, **_kwargs: None)+ monkeypatch.setattr(mcp_routes, "close_mcp_sessions", lambda *_args, **_kwargs: None)monkeypatch.setattr(mcp_routes, "_row_to_response", lambda row, **_kwargs: row)async def _drive():diff --git a/studio/backend/tests/test_mcp_upgrade_compat.py b/studio/backend/tests/test_mcp_upgrade_compat.pynew file mode 100644index 00000000000..4ef03ed9fe3--- /dev/null+++ b/studio/backend/tests/test_mcp_upgrade_compat.py@@ -0,0 +1,151 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""What an existing Studio install keeps when the MCP session cache stops being+stdio-only: the close entry point, the session-cap environment variable, and the+fastmcp surface this code actually depends on.++Studio declares fastmcp>=3.0.2 with no upper bound and no lockfile, so a released+install resolves to whatever is newest. Anything asserted about fastmcp here is+asserted against the installed version, not a mock.+"""++from __future__ import annotations++import importlib+import sys+from pathlib import Path++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++from core.inference import mcp_client++LEGACY_ENV = "UNSLOTH_STUDIO_MAX_STDIO_MCP_SESSIONS"+ENV = "UNSLOTH_STUDIO_MAX_MCP_SESSIONS"+++# --------------------------------------------------------------------------+# Entry points an old install may still call+# --------------------------------------------------------------------------+++def test_the_old_close_name_still_works():+ """close_stdio_sessions had no underscore, so treat it as callable from+ outside this module even though nothing in-repo does."""+ assert mcp_client.close_stdio_sessions is mcp_client.close_mcp_sessions+ mcp_client.close_stdio_sessions() # must not raise on an empty cache+++def test_the_old_close_name_takes_the_same_arguments():+ mcp_client.close_stdio_sessions("https://mcp.example.test/mcp", None)+++# --------------------------------------------------------------------------+# Session cap: the name changed, the setting must not+# --------------------------------------------------------------------------++[email protected](autouse = True)+def clean_env(monkeypatch):+ monkeypatch.delenv(ENV, raising = False)+ monkeypatch.delenv(LEGACY_ENV, raising = False)+++def test_unset_falls_back_to_the_default():+ assert mcp_client._max_sessions_from_env() == mcp_client._DEFAULT_MAX_SESSIONS+++def test_a_deployment_that_set_the_legacy_name_keeps_its_value(monkeypatch):+ """The cap now covers HTTP too, but silently reverting someone's tuning to 32+ would be a worse surprise than the name being stale."""+ monkeypatch.setenv(LEGACY_ENV, "7")+ assert mcp_client._max_sessions_from_env() == 7+++def test_the_new_name_works(monkeypatch):+ monkeypatch.setenv(ENV, "9")+ assert mcp_client._max_sessions_from_env() == 9+++def test_the_new_name_wins_when_both_are_set(monkeypatch):+ monkeypatch.setenv(LEGACY_ENV, "7")+ monkeypatch.setenv(ENV, "9")+ assert mcp_client._max_sessions_from_env() == 9++[email protected]("raw", ["", "abc", "1.5", " "])+def test_an_unparseable_value_falls_back_instead_of_crashing_startup(monkeypatch, raw):+ monkeypatch.setenv(ENV, raw)+ assert mcp_client._max_sessions_from_env() == mcp_client._DEFAULT_MAX_SESSIONS++[email protected]("raw,expected", [("0", 1), ("-5", 1), ("1", 1)])+def test_the_cap_never_drops_below_one(monkeypatch, raw, expected):+ monkeypatch.setenv(ENV, raw)+ assert mcp_client._max_sessions_from_env() == expected+++# --------------------------------------------------------------------------+# The fastmcp surface this module relies on+# --------------------------------------------------------------------------+++def test_the_transports_this_code_builds_still_exist():+ from fastmcp.client.transports import SSETransport, StdioTransport, StreamableHttpTransport+ for cls in (StdioTransport, SSETransport, StreamableHttpTransport):+ assert cls is not None+++def test_only_stdio_answers_the_liveness_probe():+ """_transport_dead is the reason the HTTP idle recheck exists. If a future+ fastmcp gives the HTTP transports a real probe, this test fails and the+ recheck can become cheaper."""+ from fastmcp.client.transports import SSETransport, StreamableHttpTransport+ for cls in (StreamableHttpTransport, SSETransport):+ transport = cls(url = "https://x.test/mcp")+ assert not hasattr(transport, "_is_session_dead"), (+ f"{cls.__name__} grew a liveness probe; _transport_dead can use it now"+ )+++def test_the_installed_fastmcp_meets_the_declared_floor():+ version = importlib.metadata.version("fastmcp")+ major, minor, *_ = (int(part) for part in version.split(".")[:2])+ assert (major, minor) >= (3, 0), f"fastmcp {version} is below the declared >=3.0.2"+++def test_tool_errors_are_still_distinguishable_from_transport_errors():+ """The whole keep-or-drop-the-session decision rests on this import."""+ from fastmcp.exceptions import ToolError++ assert mcp_client._is_tool_error(ToolError("nope")) is True+ assert mcp_client._is_tool_error(RuntimeError("stream closed")) is False+++# --------------------------------------------------------------------------+# Rows written by an older Studio+# --------------------------------------------------------------------------+++def test_a_row_without_use_oauth_is_treated_as_non_oauth():+ """The column was backfilled by an ALTER on an existing table, so old rows+ can read as None rather than 0."""+ assert bool({"url": "https://x.test/mcp"}.get("use_oauth")) is False+++def test_header_identity_survives_a_rewritten_headers_dict():+ """A row re-saved with the same headers in another key order must not look+ like a different server and drop the live session."""+ a = mcp_client._headers_key({"Authorization": "Bearer x", "X-Trace": "1"})+ b = mcp_client._headers_key({"X-Trace": "1", "Authorization": "Bearer x"})+ assert a == b+++def test_header_values_are_part_of_the_identity():+ a = mcp_client._headers_key({"Authorization": "Bearer x"})+ b = mcp_client._headers_key({"Authorization": "Bearer y"})+ assert a != b, "two credentials would have shared one session"