Skip to content

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.

Studio: let HTTP/SSE MCP tool calls run for the whole Max Tool Call Duration (#14308)

Sunny B6950c1ef4ff6
diff --git a/studio/backend/core/inference/mcp_client.py b/studio/backend/core/inference/mcp_client.py
index ea85b1be562..751309ceb69 100644
--- a/studio/backend/core/inference/mcp_client.py
+++ b/studio/backend/core/inference/mcp_client.py
@@ -6,6 +6,7 @@ from __future__ import annotations
import asyncio
import atexit
import concurrent.futures
+import contextvars
import hashlib
import importlib
import ipaddress
@@ -140,6 +141,155 @@ def _public_http_client_factory(**kwargs):
return client_type(**kwargs)
+def _tool_http_client_factory(**kwargs):
+ """No read cap: _race_tool_call enforces each call's budget, which the SDK's 300s read timeout would cut short."""
+ if _managed_mcp_restricted():
+ client = _public_http_client_factory(**kwargs)
+ else:
+ from mcp.shared._httpx_utils import create_mcp_http_client
+ kwargs.pop("follow_redirects", None) # create_mcp_http_client sets its own redirect policy
+ client = create_mcp_http_client(**kwargs)
+ t = client.timeout
+ client.timeout = type(t)(connect = t.connect, read = None, write = t.write, pool = t.pool)
+ tracker = _SESSION_POSTS.get()
+ if tracker is not None:
+ tracker.install(client)
+ return client
+
+
+class _PostSlot:
+ __slots__ = ("key", "token", "rid")
+
+ def __init__(self, key):
+ self.key, self.token, self.rid = key, None, None
+
+
+class _PostTracker:
+ """Open POSTs of a cached session, each bound to its call, so only an abandoned call's open reply counts."""
+
+ def __init__(self):
+ self.lock = threading.Lock()
+ self.open: set = set()
+ self.waiting: list = [] # dispatches whose POST is not sent yet, FIFO per (method, target)
+ self.abandoned: dict = {} # open POST token -> when its call was abandoned
+ self.bound: dict = {} # JSON-RPC id -> slot, so a redirected POST stays with its call
+ self.installed = False
+
+ def enqueue(self, slot: _PostSlot) -> None:
+ # Called on the session loop as the call starts, so the FIFO follows the order the SDK sends in.
+ if slot.key is not None:
+ with self.lock:
+ self.waiting.append(slot)
+
+ def settle(self, slot: _PostSlot, abandoned: bool) -> None:
+ with self.lock:
+ if slot in self.waiting:
+ self.waiting.remove(slot)
+ if abandoned and slot.token in self.open:
+ self.abandoned[slot.token] = time.monotonic()
+ elif not abandoned and self.bound.get(slot.rid) is slot:
+ del self.bound[slot.rid]
+
+ def pending(self) -> Optional[tuple]:
+ """(oldest abandonment time, count) of abandoned replies still open, else None."""
+ with self.lock:
+ if not self.abandoned:
+ return None
+ return min(self.abandoned.values()), len(self.abandoned)
+
+ def _sent(self, token, key, rid) -> None:
+ with self.lock:
+ self.open.add(token)
+ slot = self.bound.get(rid)
+ if slot is not None and slot.key == key:
+ slot.token = token
+ return
+ for slot in self.waiting:
+ if slot.key == key:
+ slot.token, slot.rid = token, rid
+ self.waiting.remove(slot)
+ self.bound[rid] = slot
+ break
+
+ def _closed(self, token) -> None:
+ with self.lock:
+ self.open.discard(token)
+ self.abandoned.pop(token, None)
+
+ def install(self, client) -> None:
+ http = sys.modules[
+ type(client).__module__.split(".")[0]
+ ] # already imported: it built ``client``
+ tracker = self
+
+ class Stream(http.AsyncByteStream):
+ def __init__(self, inner, token):
+ self.inner, self.token = inner, token
+
+ async def __aiter__(self):
+ async for chunk in self.inner:
+ yield chunk
+
+ async def aclose(self):
+ try:
+ await self.inner.aclose()
+ finally:
+ tracker._closed(self.token)
+
+ class Transport(http.AsyncBaseTransport):
+ def __init__(self, inner):
+ self.inner = inner
+
+ async def handle_async_request(self, request):
+ if request.method != "POST":
+ return await self.inner.handle_async_request(request)
+ token, (key, rid) = object(), _rpc_target(request)
+ if key is None or key[0] not in ("tools/call", "resources/read"):
+ # Only a call's reply may outlive the SDK's old read cap; probes and handshakes keep it.
+ request.extensions["timeout"] = {
+ **request.extensions.get("timeout", {}),
+ "read": _ABANDONED_REPLY_TIMEOUT,
+ }
+ tracker._sent(token, key, rid)
+ try:
+ response = await self.inner.handle_async_request(request)
+ except BaseException:
+ tracker._closed(token)
+ raise
+ response.stream = Stream(response.stream, token)
+ return response
+
+ async def aclose(self):
+ await self.inner.aclose()
+
+ # httpx has no public hook for a request ending without a response; unwrappable clients keep the deadline.
+ if not hasattr(client, "_transport") or not isinstance(
+ getattr(client, "_mounts", None), dict
+ ):
+ return
+ client._transport = Transport(client._transport)
+ client._mounts = {k: (v if v is None else Transport(v)) for k, v in client._mounts.items()}
+ self.installed = True
+
+
+def _rpc_target(request) -> tuple:
+ """((JSON-RPC method, tool name or URI), id) of a request POST, else (None, None)."""
+ try:
+ msg = json.loads(request.content)
+ if "id" not in msg or "method" not in msg:
+ return None, None
+ params = msg.get("params") or {}
+ return (msg["method"], params.get("name") or params.get("uri")), msg["id"]
+ except Exception: # noqa: BLE001
+ return None, None
+
+
+# Set by _McpSession.connect so _tool_http_client_factory can hook the client the SDK builds for that session.
+_SESSION_POSTS: contextvars.ContextVar[Optional[_PostTracker]] = contextvars.ContextVar(
+ "mcp_session_posts", default = None
+)
+
+
def is_stdio(address: str) -> bool:
"""A non-HTTP address is a local stdio command, e.g. 'npx -y
@modelcontextprotocol/server-filesystem /path'."""
@@ -627,12 +777,16 @@ def _client(
transport_cls = (
SSETransport if infer_transport_type_from_url(url) == "sse" else StreamableHttpTransport
)
- kwargs = {}
- if _managed_mcp_restricted():
- kwargs["httpx_client_factory"] = _public_http_client_factory
- if auth is not None:
- auth.httpx_client_factory = _public_http_client_factory
- return Client(transport_cls(url = url, headers = headers or None, auth = auth, **kwargs))
+ if _managed_mcp_restricted() and auth is not None:
+ auth.httpx_client_factory = _public_http_client_factory
+ return Client(
+ transport_cls(
+ url = url,
+ headers = headers or None,
+ auth = auth,
+ httpx_client_factory = _tool_http_client_factory,
+ )
+ )
def oauth_client_kwargs(row: dict) -> dict:
@@ -652,6 +806,9 @@ _SESSION_CLOSE_TIMEOUT = 10.0
_SESSION_WEDGE_MARGIN = 15.0
_SESSION_LIVENESS_TIMEOUT = 5.0
_CANCEL_UNWIND_TIMEOUT = 2.0
+# With no read cap, a still-open abandoned reply is bounded by retiring its session after the old cap or a pile-up.
+_ABANDONED_REPLY_TIMEOUT = 300.0
+_MAX_ABANDONED_REPLIES = 8
# 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.
@@ -854,6 +1011,9 @@ class _McpSession:
self.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 reuse
+ self.abandoned_at: Optional[float] = None
+ self.abandoned = 0
+ self.posts = _PostTracker()
self._close_lock = threading.Lock()
self.call_lock = threading.Lock()
# One stdio subprocess is one ordered byte stream, so overlapping calls must not interleave on it. HTTP has no
@@ -875,6 +1035,31 @@ class _McpSession:
self._thread = account_thread(target = self._run_loop, name = "mcp-session", daemon = True)
self._thread.start()
+ def note_abandoned(self, slot: _PostSlot) -> None:
+ """Record a call abandoned mid-flight on an HTTP transport (stdio has no reply socket to leak)."""
+ if is_stdio(self.url):
+ return
+ if self.posts.installed:
+ self.posts.settle(slot, abandoned = True)
+ return
+ if self.abandoned_at is None:
+ self.abandoned_at = time.monotonic()
+ self.abandoned += 1
+
+ def abandoned_overdue(self, now: Optional[float] = None) -> bool:
+ """Whether still-open abandoned replies require closing the session rather than probing it."""
+ now = time.monotonic() if now is None else now
+ if self.posts.installed:
+ pending = self.posts.pending()
+ if pending is None:
+ return False
+ oldest, count = pending
+ elif self.abandoned_at is None:
+ return False
+ else:
+ oldest, count = self.abandoned_at, self.abandoned
+ return count >= _MAX_ABANDONED_REPLIES or now - oldest >= _ABANDONED_REPLY_TIMEOUT
+
def _run_loop(self) -> None:
asyncio.set_event_loop(self.loop)
try:
@@ -884,6 +1069,7 @@ class _McpSession:
def connect(self, timeout: Optional[float], cancel_event) -> None:
async def _open():
+ _SESSION_POSTS.set(self.posts)
client = _client(self.url, self.headers)
await client.__aenter__()
# Publish on the loop thread with no await in between: if an abort races a just-completed connect, close()
@@ -1460,7 +1646,8 @@ def _reap_idle_sessions(now: Optional[float] = None) -> None:
expired = [
key
for key, session in _mcp_sessions.items()
- if session.in_flight == 0 and now - session.last_used >= _SESSION_IDLE_TTL
+ if session.in_flight == 0
+ and (now - session.last_used >= _SESSION_IDLE_TTL or session.abandoned_overdue(now))
]
sessions = [_mcp_sessions.pop(key) for key in expired]
for key in expired:
@@ -2040,6 +2227,11 @@ async def _race_tool_call(
raise _MCPCancelled
+async def _enqueued(tracker: _PostTracker, slot: _PostSlot, call) -> Any:
+ tracker.enqueue(slot)
+ return await call
+
+
def _call_session_tool(
url: str,
headers: Optional[dict],
@@ -2051,9 +2243,12 @@ def _call_session_tool(
config_check,
use_oauth: bool = False,
dispatch = None,
+ rpc: Optional[tuple] = None,
) -> Any:
if cancel_event is not None and cancel_event.is_set():
raise _MCPCancelled
+ if dispatch is None:
+ rpc = ("tools/call", name)
# One deadline covers the key-lock wait, connect, call-lock wait, and the 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
@@ -2102,6 +2297,7 @@ def _call_session_tool(
_drop_session(key, session)
raise
discard_session = ephemeral
+ slot = None
retry = False
try:
# We may have waited on the call lock while another caller's timeout retired this session, a server
@@ -2129,6 +2325,13 @@ def _call_session_tool(
retry = True
else:
raise RuntimeError("MCP server connection is not available")
+ elif session.abandoned_overdue():
+ # A probe would prove the server is up, not that the abandoned POSTs closed.
+ discard_session = True
+ if attempt == 0:
+ retry = True
+ else:
+ raise RuntimeError("MCP server session was retired during the call")
elif (
session.dirty or _needs_idle_recheck(session, idle_for, _remaining())
) and not _session_responsive(
@@ -2144,11 +2347,16 @@ def _call_session_tool(
raise RuntimeError("MCP server is not responding")
else:
rem = _remaining()
+ slot = _PostSlot(rpc)
# raise_on_error=False for the same reason as the one-shot path.
coro = _race_tool_call(
- dispatch(session.client)
- if dispatch is not None
- else session.client.call_tool(name, args, raise_on_error = False),
+ _enqueued(
+ session.posts,
+ slot,
+ dispatch(session.client)
+ if dispatch is not None
+ else session.client.call_tool(name, args, raise_on_error = False),
+ ),
rem,
cancel_event,
# Only a cached session is worth waiting on.
@@ -2163,6 +2371,8 @@ def _call_session_tool(
# 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 = True
+ if not ephemeral and slot is not None:
+ session.note_abandoned(slot)
raise
except _SessionWedged:
discard_session = True
@@ -2191,6 +2401,8 @@ def _call_session_tool(
discard_session = True
raise
finally:
+ if slot is not None:
+ session.posts.settle(slot, abandoned = False)
# 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
@@ -2317,9 +2529,10 @@ def _ui_request_sync(
cancel_event = None,
scope = None,
config_check = None,
+ rpc = None,
**oauth,
) -> Any:
- """``dispatch(client)`` on the transport call_tool_sync would pick for this scope."""
+ """``dispatch(client)`` on the transport call_tool_sync picks for this scope; ``rpc`` = (method, name or URI)."""
async def _one_shot() -> Any:
# As the session branch: an edit during discovery must not reach the old endpoint.
@@ -2334,7 +2547,7 @@ def _ui_request_sync(
session_args = (url, headers, label, {}, timeout, cancel_event, scope, config_check, use_oauth)
try:
if is_stdio(url) or (scope and not use_oauth):
- return _call_session_tool(*session_args, dispatch = dispatch)
+ return _call_session_tool(*session_args, dispatch = dispatch, rpc = rpc)
return asyncio.run(_race_tool_call(_one_shot(), timeout, cancel_event))
except _MCPCancelled as exc:
raise TimeoutError(f"{label} was cancelled") from exc
@@ -2344,13 +2557,19 @@ def call_tool_structured_sync(
url: str, headers: Optional[dict], name: str, args: dict, **kw
) -> dict:
dispatch = lambda client: client.call_tool(name, args, raise_on_error = False) # noqa: E731
- return _structured_result(_ui_request_sync(url, headers, f"MCP tool '{name}'", dispatch, **kw))
+ label = f"MCP tool '{name}'"
+ return _structured_result(
+ _ui_request_sync(url, headers, label, dispatch, rpc = ("tools/call", name), **kw)
+ )
def read_resource_sync(url: str, headers: Optional[dict], uri: str, **kw) -> dict:
dispatch = lambda client: client.read_resource(uri) # noqa: E731
return _resource_contents(
- _ui_request_sync(url, headers, f"MCP resource '{uri}'", dispatch, **kw), uri
+ _ui_request_sync(
+ url, headers, f"MCP resource '{uri}'", dispatch, rpc = ("resources/read", uri), **kw
+ ),
+ uri,
)
diff --git a/studio/backend/tests/test_account_tool_isolation.py b/studio/backend/tests/test_account_tool_isolation.py
index 04506674bf3..f82001c1da4 100644
--- a/studio/backend/tests/test_account_tool_isolation.py
+++ b/studio/backend/tests/test_account_tool_isolation.py
@@ -556,10 +556,11 @@ def test_managed_transport_and_oauth_use_public_http_factory(monkeypatch):
oauth = SimpleNamespace(httpx_client_factory = None)
monkeypatch.setattr(mcp_client, "_oauth", lambda url: oauth)
result = run_as(ALICE, mcp_client._client, "https://public.example/mcp", None, True)
- assert result["httpx_client_factory"] is mcp_client._public_http_client_factory
assert oauth.httpx_client_factory is mcp_client._public_http_client_factory
+ managed = run_as(ALICE, result["httpx_client_factory"])
+ assert type(managed._transport).__name__ == "PublicTransport"
owner = mcp_client._client("http://127.0.0.1/mcp", None)
- assert "httpx_client_factory" not in owner
+ assert type(owner["httpx_client_factory"]()._transport).__name__ != "PublicTransport"
def test_workspace_cleanup_thread_retains_account(monkeypatch):
diff --git a/studio/backend/tests/test_mcp_http_read_timeout.py b/studio/backend/tests/test_mcp_http_read_timeout.py
new file mode 100644
index 00000000000..765ba9f10ae
--- /dev/null
+++ b/studio/backend/tests/test_mcp_http_read_timeout.py
@@ -0,0 +1,291 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""#14298: an HTTP/SSE MCP tool call must run for the whole Max Tool Call Duration, not stop at the
+SDK's 300s httpx read timeout. The e2e test shrinks that SDK default to 1s and runs a 2s tool against
+a real local server, so it fails in seconds without the fix instead of after five minutes."""
+
+from __future__ import annotations
+
+import asyncio
+import importlib
+import json
+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)
+
+from core.inference import mcp_client
+
+_SERVER = textwrap.dedent(
+ """
+ import asyncio, sys
+ from fastmcp import FastMCP
+
+ mcp = FastMCP("slow")
+
+ @mcp.tool
+ async def slow(seconds: float) -> str:
+ await asyncio.sleep(seconds)
+ return f"slept {seconds}"
+
+ mcp.run(transport = "http", host = "127.0.0.1", port = int(sys.argv[1]), show_banner = False)
+ """
+)
+
+
+def slow_server():
+ with socket.socket() as s:
+ s.bind(("127.0.0.1", 0))
+ port = s.getsockname()[1]
+ proc = subprocess.Popen([sys.executable, "-c", _SERVER, str(port)])
+ try:
+ for _ in range(100):
+ try:
+ socket.create_connection(("127.0.0.1", port), timeout = 0.2).close()
+ break
+ except OSError:
+ time.sleep(0.1)
+ yield f"http://127.0.0.1:{port}/mcp"
+ finally:
+ proc.terminate()
+ proc.wait(timeout = 10)
+
+
[email protected]("restricted", [False, True])
+def test_factory_lifts_only_the_read_cap(monkeypatch, restricted):
+ monkeypatch.setattr(mcp_client, "_managed_mcp_restricted", lambda: restricted)
+ from mcp.shared._httpx_utils import create_mcp_http_client
+
+ timeout = type(create_mcp_http_client().timeout)(5.0, read = 300.0) # what sse_client passes
+ for kwargs in ({}, {"timeout": timeout, "follow_redirects": True}):
+ t = mcp_client._tool_http_client_factory(**kwargs).timeout
+ assert t.read is None
+ assert t.connect == (5.0 if kwargs else 30.0)
+
+
[email protected]("scope", [None, "chat-1"]) # one-shot client and cached session
+def test_tool_call_outlives_sdk_read_timeout(slow_server, monkeypatch, scope):
+ import mcp.shared._httpx_utils as httpx_utils
+
+ monkeypatch.setattr(httpx_utils, "MCP_DEFAULT_SSE_READ_TIMEOUT", 1.0)
+ out = mcp_client.call_tool_sync(
+ slow_server, None, "slow", {"seconds": 2}, timeout = 30, scope = scope
+ )
+ assert "slept 2" in out, out
+
+
+def test_call_budget_still_enforced(slow_server):
+ out = mcp_client.call_tool_sync(slow_server, None, "slow", {"seconds": 10}, timeout = 2)
+ assert out.startswith("Error") and "2s" in out, out
+
+
+# With the read cap lifted, a reply abandoned by a timed-out or stopped call stays open on the transport until the
+# server closes it (SDKs that abort the POST leave nothing open). These pin the bounded cleanup that replaces the cap.
+
+
+def cached_scope():
+ scope = f"test-{time.monotonic_ns()}"
+ yield scope
+ mcp_client.close_mcp_sessions()
+
+
+def _cached_session(url, scope):
+ return mcp_client._mcp_sessions[mcp_client._session_key(url, None, scope)]
+
+
+def _call(
+ url,
+ scope,
+ seconds,
+ timeout = 30,
+):
+ return mcp_client.call_tool_sync(
+ url, None, "slow", {"seconds": seconds}, timeout = timeout, scope = scope
+ )
+
+
+def _warm(url, scope):
+ assert "slept 0" in _call(url, scope, 0)
+ return _cached_session(url, scope)
+
+
+def _open_post(
+ session,
+ age = 0.0,
+ abandoned = True,
+):
+ token, tracker = object(), session.posts
+ with tracker.lock:
+ tracker.open.add(token)
+ if abandoned:
+ tracker.abandoned[token] = time.monotonic() - age
+ return token
+
+
+def _slot(tracker, key):
+ slot = mcp_client._PostSlot(key)
+ tracker.enqueue(slot)
+ return slot
+
+
+def test_redirected_post_stays_with_its_call(slow_server, cached_scope):
+ # A 307/308 resends the same JSON-RPC request: the slot follows it to the final POST.
+ tracker, key = _warm(slow_server, cached_scope).posts, ("tools/call", "slow")
+ slot, hop, final = _slot(tracker, key), object(), object()
+ tracker._sent(hop, key, 41)
+ tracker._closed(hop)
+ tracker._sent(final, key, 41)
+ tracker.settle(slot, abandoned = True)
+ assert list(tracker.abandoned) == [final]
+ tracker.settle(slot, abandoned = False)
+ tracker._closed(final)
+ assert tracker.pending() is None and not tracker.bound
+
+
+def test_only_call_replies_lose_the_read_cap():
+ from mcp.shared._httpx_utils import create_mcp_http_client
+
+ client = create_mcp_http_client()
+ http = importlib.import_module(type(client).__module__.split(".")[0])
+ seen = {}
+
+ def handler(request):
+ seen[json.loads(request.content)["method"]] = request.extensions["timeout"]["read"]
+ return http.Response(200, json = {})
+
+ client._transport, client._mounts = http.MockTransport(handler), {}
+ client.timeout = type(client.timeout)(30.0, read = None)
+ mcp_client._PostTracker().install(client)
+
+ async def post(method):
+ await client.post("http://mcp.test/mcp", json = {"jsonrpc": "2.0", "id": 1, "method": method})
+
+ for method in ("tools/call", "resources/read", "tools/list", "initialize"):
+ asyncio.run(post(method))
+ assert seen["tools/call"] is None and seen["resources/read"] is None
+ assert seen["tools/list"] == seen["initialize"] == mcp_client._ABANDONED_REPLY_TIMEOUT
+
+
+def test_abandoned_call_is_bound_to_its_own_post(slow_server, cached_scope):
+ # Call A is abandoned while a later call B to the same tool is still running: only A's POST may count.
+ session = _warm(slow_server, cached_scope)
+ assert session.posts.installed
+ sent, real_sent = [], session.posts._sent
+ session.posts._sent = lambda token, *a: (sent.append(token), real_sent(token, *a))
+ a = threading.Thread(target = _call, args = (slow_server, cached_scope, 30, 1.0))
+ a.start()
+ time.sleep(0.3)
+ b = threading.Thread(target = _call, args = (slow_server, cached_scope, 3))
+ b.start()
+ a.join()
+ time.sleep(0.3)
+ assert len(sent) == 2 and sent[1] in session.posts.open # B is still running
+ assert set(session.posts.abandoned) <= {sent[0]}
+ b.join()
+
+
+def test_retirement_deadline_starts_at_abandonment(slow_server, cached_scope, monkeypatch):
+ # A reply that ran past the deadline before it was abandoned still gets the full cleanup window.
+ monkeypatch.setattr(mcp_client, "_ABANDONED_REPLY_TIMEOUT", 0.5)
+ session = _warm(slow_server, cached_scope)
+ tracker, key = session.posts, ("tools/call", "slow")
+ slot, token = _slot(tracker, key), object()
+ tracker._sent(token, key, 1)
+ time.sleep(0.6)
+ session.note_abandoned(slot)
+ assert not session.abandoned_overdue()
+ time.sleep(0.6)
+ assert session.abandoned_overdue()
+ tracker._closed(token)
+ assert not session.abandoned_overdue()
+
+
+def test_abandonment_bookkeeping_is_thread_safe(slow_server, cached_scope):
+ session = _warm(slow_server, cached_scope)
+ tracker, key, errors = session.posts, ("tools/call", "slow"), []
+
+ def churn():
+ try:
+ for _ in range(2000):
+ slot, token = _slot(tracker, key), object()
+ tracker._sent(token, key, id(token))
+ session.note_abandoned(slot)
+ session.abandoned_overdue()
+ tracker._closed(token)
+ tracker.settle(slot, abandoned = False)
+ except Exception as exc: # noqa: BLE001
+ errors.append(exc)
+
+ threads = [threading.Thread(target = churn) for _ in range(4)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+ assert not errors and not tracker.abandoned and not tracker.waiting and not tracker.bound
+
+
+def test_overdue_abandoned_reply_retires_the_session_without_probing(
+ slow_server, cached_scope, monkeypatch
+):
+ monkeypatch.setattr(mcp_client, "_ABANDONED_REPLY_TIMEOUT", 0.2)
+ stale = _warm(slow_server, cached_scope)
+ _open_post(stale, age = 1)
+ assert stale.abandoned_overdue()
+
+ def _no_probe(*args, **kwargs):
+ raise AssertionError("an overdue session must be closed, not probed")
+
+ stale.dirty = True
+ monkeypatch.setattr(mcp_client, "_session_responsive", _no_probe)
+ assert "slept 0" in _call(slow_server, cached_scope, 0)
+ assert stale.closed.is_set() and stale.client is None
+ fresh = _cached_session(slow_server, cached_scope)
+ assert fresh is not stale and fresh.posts.pending() is None
+
+
+def test_too_many_abandoned_replies_retire_the_session(slow_server, cached_scope, monkeypatch):
+ monkeypatch.setattr(mcp_client, "_MAX_ABANDONED_REPLIES", 2)
+ stale = _warm(slow_server, cached_scope)
+ _open_post(stale)
+ assert not stale.abandoned_overdue()
+ _open_post(stale)
+ assert "slept 0" in _call(slow_server, cached_scope, 0)
+ assert stale.closed.is_set()
+ assert _cached_session(slow_server, cached_scope) is not stale
+
+
+def test_reaper_closes_an_idle_session_with_an_overdue_reply(
+ slow_server, cached_scope, monkeypatch
+):
+ monkeypatch.setattr(mcp_client, "_ABANDONED_REPLY_TIMEOUT", 0.2)
+ stale = _warm(slow_server, cached_scope)
+ token = _open_post(stale)
+ mcp_client._reap_idle_sessions() # not overdue yet, and far inside the idle TTL
+ assert not stale.closed.is_set()
+ stale.posts.abandoned[token] -= 1
+ mcp_client._reap_idle_sessions()
+ assert stale.closed.is_set()
+ assert mcp_client._session_key(slow_server, None, cached_scope) not in mcp_client._mcp_sessions
+
+
+def test_finished_abandoned_reply_keeps_the_session(slow_server, cached_scope, monkeypatch):
+ # A Stop whose reply the server then finished leaks nothing, so the chat keeps its session (and server state).
+ monkeypatch.setattr(mcp_client, "_ABANDONED_REPLY_TIMEOUT", 0.2)
+ session = _warm(slow_server, cached_scope)
+ assert _call(slow_server, cached_scope, 1, timeout = 0.3).startswith("Error")
+ time.sleep(1.5)
+ assert not session.abandoned_overdue() and session.posts.pending() is None
+ assert "slept 0" in _call(slow_server, cached_scope, 0)
+ assert _cached_session(slow_server, cached_scope) is session and not session.closed.is_set()