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 the stdio MCP session alive when a tool call is cancelled (#7625)
Nilay2a8ed1a7a5f9
diff --git a/studio/backend/core/inference/mcp_client.py b/studio/backend/core/inference/mcp_client.pyindex 488e34e5d09..09f9a62b8e2 100644--- a/studio/backend/core/inference/mcp_client.py+++ b/studio/backend/core/inference/mcp_client.py@@ -262,6 +262,8 @@ _STDIO_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+_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.@@ -308,6 +310,35 @@ def _transport_dead(session) -> bool:return False+def _session_responsive(+ session,+ budget: Optional[float] = None,+ cancel_event = None,+) -> bool:+ """Whether a session left dirty by an abandoned call can be reused: the+ server must answer inside ``budget`` (the caller's remaining deadline).+ Proves the server is alive, not that the abandoned call finished -- MCP+ requests are concurrent. Probes with a raw single-page tools/list: ping+ answers "Method not found" on a modern-era connection, and list_tools()+ auto-paginates up to 250 pages."""+ client = session.client+ if client is None:+ return False+ window = _STDIO_LIVENESS_TIMEOUT if budget is None else min(_STDIO_LIVENESS_TIMEOUT, budget)+ if window <= 0:+ return False+ probe = getattr(client, "list_tools_mcp", None) or client.list_tools+ try:+ # 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+ session.dirty = False+ return True++class _SessionWedged(Exception):pass@@ -332,6 +363,7 @@ class _StdioSession:self.client = Noneself.closed = threading.Event()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 sessionself.last_used = time.monotonic()@@ -394,14 +426,20 @@ class _StdioSession:except Exception:return False- def run(self, coro, timeout: Optional[float]):+ def run(+ self,+ coro,+ timeout: Optional[float],+ margin: float = _STDIO_WEDGE_MARGIN,+ ):self.last_used = time.monotonic()future = asyncio.run_coroutine_threadsafe(coro, self.loop)# The coroutine enforces the tool timeout; the margin only catches a# wedged loop. No deadline at all when the caller set none -- but poll# so a session closed under us (server update/delete) can't hang the- # request thread forever on a stopped loop.- deadline = None if timeout is None else time.monotonic() + timeout + _STDIO_WEDGE_MARGIN+ # request thread forever on a stopped loop. Callers whose whole budget is+ # the timeout (the liveness probe) pass margin=0.+ deadline = None if timeout is None else time.monotonic() + timeout + margintry:while True:try:@@ -854,9 +892,26 @@ def _flatten_result(result: Any) -> str:return body-async def _race_tool_call(call_coro, timeout: Optional[float], cancel_event) -> Any:+def _unwind_budget(unwind_timeout: float, timeout: Optional[float], elapsed: float) -> float:+ """How long a cancelled call may take to unwind: whatever is left of the+ caller's window, so the wait is never charged on top of an expired deadline."""+ if not unwind_timeout:+ return 0.0+ if timeout is None:+ return unwind_timeout+ return min(unwind_timeout, max(0.0, timeout - elapsed))+++async def _race_tool_call(+ call_coro,+ timeout: Optional[float],+ cancel_event,+ unwind_timeout: float = 0.0,+) -> Any:"""Await ``call_coro`` under ``timeout``, polling ``cancel_event`` so a- /cancel POST interrupts even mid-network-read."""+ /cancel POST interrupts even mid-network-read. ``unwind_timeout`` waits up to+ that long for a cancelled call to finish unwinding; only callers that hand the+ client back to a cache need it (one-shot clients are discarded anyway)."""async def _watch_cancel() -> None:while cancel_event is not None and not cancel_event.is_set():@@ -865,6 +920,7 @@ async def _race_tool_call(call_coro, timeout: Optional[float], cancel_event) ->if cancel_event is not None and cancel_event.is_set():call_coro.close()raise _MCPCancelled+ started = time.monotonic()call_task = asyncio.create_task(call_coro)if cancel_event is None:return await asyncio.wait_for(call_task, timeout = timeout)@@ -879,6 +935,11 @@ async def _race_tool_call(call_coro, timeout: Optional[float], cancel_event) ->for t in (call_task, watch_task):if not t.done():t.cancel()+ # Let a cancelled call unwind before its session is reused, out of the+ # caller's remaining budget. Outlasting it just leaves the session dirty.+ left = _unwind_budget(unwind_timeout, timeout, time.monotonic() - started)+ if left:+ await asyncio.wait({call_task, watch_task}, timeout = left)if not done:raise asyncio.TimeoutErrorif call_task in done:@@ -969,6 +1030,13 @@ 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.+ discard_session = True+ if attempt == 0:+ retry = True+ else:+ raise RuntimeError("MCP server is not responding")else:rem = _remaining()# raise_on_error=False for the same reason as the one-shot path.@@ -976,13 +1044,14 @@ def _call_stdio_tool(session.client.call_tool(name, args, raise_on_error = False),rem,cancel_event,+ # Only a cached session is worth waiting on.+ 0.0 if ephemeral else _CANCEL_UNWIND_TIMEOUT,)return session.run(coro, rem)except (_MCPCancelled, asyncio.TimeoutError):- # _race_tool_call cancels the pending call but cancellation is- # cooperative. Never return this client to the cache while the- # timed-out/cancelled operation might still run on its transport.- discard_session = True+ # 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.+ session.dirty = Trueraiseexcept _SessionWedged:discard_session = Truediff --git a/studio/backend/tests/test_mcp_stdio_sessions.py b/studio/backend/tests/test_mcp_stdio_sessions.pyindex 37c812677af..e9a63c3ac17 100644--- a/studio/backend/tests/test_mcp_stdio_sessions.py+++ b/studio/backend/tests/test_mcp_stdio_sessions.py@@ -45,9 +45,24 @@ class FakeClient:# Models a dead stdio transport: real Client.is_connected() stays True# after the subprocess dies, so liveness is probed via the transport.self.dead = False+ # A server still stuck on an abandoned call fails the liveness probe.+ self.probe_ok = True+ self.probe_error = False+ self.probes = 0self.transport = SimpleNamespace(_is_session_dead = lambda: self.dead)FakeClient.instances.append(self)+ async def list_tools_mcp(self) -> SimpleNamespace:+ self.probes += 1+ if self.probe_error:+ raise RuntimeError("probe failed")+ if not self.probe_ok:+ await asyncio.sleep(30)+ return SimpleNamespace(tools = [])++ async def list_tools(self) -> list:+ raise AssertionError("the liveness probe must use the single-page tools/list")+async def __aenter__(self):self.entered += 1self.connected = True@@ -150,10 +165,33 @@ def test_http_stays_one_shot(fake_clients):assert all(c.entered == 1 and c.exited == 1 for c in fake_clients)-def test_timeout_discards_stdio_session(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")+ fake_clients[0].call_delay = 0.5+ out = call_tool_sync(+ STDIO_URL,+ None,+ "slow",+ {},+ timeout = 0.05,+ cancel_event = threading.Event(),+ scope = "chat",+ )+ assert "timed out" in out+ fake_clients[0].call_delay = 0.0+ assert call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat") == "call-2"+ assert len(fake_clients) == 1+ assert fake_clients[0].exited == 0+++def test_timeout_replaces_a_wedged_stdio_session(fake_clients):+ # A server that never answers the probe is wedged, so it is replaced rather+ # than reused.call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat")key = mcp_client._session_key(STDIO_URL, None, "chat")fake_clients[0].call_delay = 0.5+ fake_clients[0].probe_ok = Falseout = call_tool_sync(STDIO_URL,None,@@ -164,10 +202,187 @@ def test_timeout_discards_stdio_session(fake_clients):scope = "chat",)assert "timed out" in out+ assert call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat") == "call-1"+ assert len(fake_clients) == 2assert fake_clients[0].exited == 1- assert key not in mcp_client._stdio_key_locks+ assert key in mcp_client._stdio_sessions+++def test_dirty_session_probe_stays_inside_the_caller_timeout(fake_clients):+ # The probe that gates reuse shares the call's deadline; it must not add a+ # window of its own on top of it.+ call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat")+ fake_clients[0].call_delay = 0.5+ fake_clients[0].probe_ok = False # probe hangs for 30s+ call_tool_sync(+ STDIO_URL,+ None,+ "slow",+ {},+ timeout = 0.05,+ cancel_event = threading.Event(),+ scope = "chat",+ )+ started = time.monotonic()+ call_tool_sync(STDIO_URL, None, "t", {}, timeout = 0.2, scope = "chat")+ assert time.monotonic() - started < mcp_client._STDIO_LIVENESS_TIMEOUT+++def test_failed_probe_replaces_the_session(fake_clients):+ # Only a completed round-trip proves the abandoned call is done, so a probe+ # that errors is not enough to reuse the session.+ call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat")+ fake_clients[0].call_delay = 0.5+ fake_clients[0].probe_error = True+ call_tool_sync(+ STDIO_URL,+ None,+ "slow",+ {},+ timeout = 0.05,+ cancel_event = threading.Event(),+ scope = "chat",+ )+ 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+++def test_successful_probe_is_not_repeated(fake_clients):+ # Once a round-trip clears the flag, later calls dispatch without probing.+ call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat")+ fake_clients[0].call_delay = 0.5+ call_tool_sync(+ STDIO_URL,+ None,+ "slow",+ {},+ timeout = 0.05,+ cancel_event = threading.Event(),+ scope = "chat",+ )+ fake_clients[0].call_delay = 0.0+ assert call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat") == "call-2"+ assert call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat") == "call-3"+ assert fake_clients[0].probes == 1+++def test_stop_interrupts_a_hanging_dirty_probe(fake_clients):+ # The recovery probe honors Stop like connect and the call itself do.+ call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat")+ fake_clients[0].call_delay = 0.5+ fake_clients[0].probe_ok = False # probe hangs for 30s+ call_tool_sync(+ STDIO_URL,+ None,+ "slow",+ {},+ timeout = 0.05,+ cancel_event = threading.Event(),+ scope = "chat",+ )+ cancel = threading.Event()+ threading.Timer(0.1, cancel.set).start()+ started = time.monotonic()+ out = call_tool_sync(+ STDIO_URL,+ None,+ "t",+ {},+ scope = "chat",+ cancel_event = cancel,+ timeout = 30,+ )+ assert out == "Error: MCP tool 't' cancelled"+ assert time.monotonic() - started < mcp_client._STDIO_LIVENESS_TIMEOUT+++def test_unwind_budget_comes_out_of_the_caller_deadline():+ budget = mcp_client._unwind_budget+ assert budget(2.0, 0.05, 0.05) == 0.0 # deadline already spent+ assert budget(2.0, 300.0, 2.0) == 2.0 # Stop early in a long call+ assert budget(2.0, 3.0, 2.5) == pytest.approx(0.5) # only the remainder+ assert budget(2.0, None, 99.0) == 2.0 # no deadline at all+ assert budget(0.0, 300.0, 1.0) == 0.0 # one-shot callers never wait+++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++ def spy(+ self,+ coro,+ timeout,+ margin = mcp_client._STDIO_WEDGE_MARGIN,+ ):+ margins.append(margin)+ return real_run(self, coro, timeout, margin)++ monkeypatch.setattr(mcp_client._StdioSession, "run", spy)+ call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat")+ fake_clients[0].call_delay = 0.5+ call_tool_sync(+ STDIO_URL,+ None,+ "slow",+ {},+ timeout = 0.05,+ cancel_event = threading.Event(),+ scope = "chat",+ )+ fake_clients[0].call_delay = 0.0+ 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]+++def test_unwind_wait_only_for_cached_sessions(fake_clients, monkeypatch):+ # Only a cached session needs the cancelled call to finish unwinding. HTTP+ # and scope-less stdio clients are discarded either way, so a Stop on those+ # must return without waiting for one.+ seen = []+ real = mcp_client._race_tool_call++ async def spy(+ coro,+ timeout,+ cancel_event,+ unwind_timeout = 0.0,+ ):+ seen.append(unwind_timeout)+ return await real(coro, timeout, cancel_event, unwind_timeout)++ monkeypatch.setattr(mcp_client, "_race_tool_call", spy)+ call_tool_sync(HTTP_URL, None, "t", {})+ call_tool_sync(STDIO_URL, None, "t", {}) # no scope: ephemeral, closed after+ call_tool_sync(STDIO_URL, None, "t", {}, scope = "chat")+ assert seen == [0.0, 0.0, mcp_client._CANCEL_UNWIND_TIMEOUT]+++def test_cancel_preserves_stateful_session(fake_clients):+ # Pressing Stop must not tear down the server and its state.+ call_tool_sync(STDIO_URL, None, "browser_navigate", {}, scope = "chat")+ fake_clients[0].call_delay = 1.0+ cancel = threading.Event()+ threading.Timer(0.1, cancel.set).start()+ out = call_tool_sync(+ STDIO_URL,+ None,+ "browser_snapshot",+ {},+ scope = "chat",+ cancel_event = cancel,+ timeout = 5,+ )+ assert out == "Error: MCP tool 'browser_snapshot' cancelled"+ fake_clients[0].call_delay = 0.0+ assert call_tool_sync(STDIO_URL, None, "browser_snapshot", {}, scope = "chat") == "call-2"+ assert len(fake_clients) == 1def test_no_timeout_allows_long_call(fake_clients):