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: reconnect a chat's MCP session after the server restarts (#16209)

Nilay8af61f267302
diff --git a/studio/backend/core/inference/mcp_client.py b/studio/backend/core/inference/mcp_client.py
index bfc1e4a11e1..7ca0a1bf013 100644
--- a/studio/backend/core/inference/mcp_client.py
+++ b/studio/backend/core/inference/mcp_client.py
@@ -861,6 +861,21 @@ def _is_protocol_error(exc: BaseException) -> bool:
return False
+# HTTP 404 for an unknown Mcp-Session-Id, so the request never ran: the client SDK's "Session terminated"
+# stand-in, or the server body mcp 2.x relays (Python SDK -32600 / TypeScript SDK -32001 "Session not found").
+_SESSION_GONE_MESSAGES = ("Session terminated", "Session not found")
+_SESSION_GONE_CODES = (32600, -32600, -32001)
+
+
+def _is_session_terminated(exc: BaseException) -> bool:
+ error = getattr(exc, "error", None)
+ return (
+ _is_protocol_error(exc)
+ and getattr(error, "message", None) in _SESSION_GONE_MESSAGES
+ and getattr(error, "code", None) in _SESSION_GONE_CODES
+ )
+
+
def _transport_dead(session) -> bool:
"""Only stdio can prove a transport dead; HTTP always reads unknown, so this returns False there."""
client = getattr(session, "client", None)
@@ -918,7 +933,7 @@ def _session_responsive(
return not timeout_is_fatal
except Exception as exc: # noqa: BLE001
# A JSON-RPC error means the transport works; reconnecting would lose session state.
- if not _is_protocol_error(exc):
+ if _is_session_terminated(exc) or not _is_protocol_error(exc):
return False
session.dirty = False
session.proved_at = time.monotonic()
@@ -2233,13 +2248,18 @@ def _call_session_tool(
# Intentional close may look like a transport error or AttributeError; do not treat as crash
discard_session = True
raise RuntimeError("MCP server was updated or removed during the call")
+ if _is_session_terminated(exc):
+ # A 404 means the server never processed the request, so reconnect and replay once.
+ discard_session = True
+ retry = attempt == 0
# Protocol error = server alive, keep session. Transport error: evict but DO NOT replay.
- if _is_protocol_error(exc):
+ elif _is_protocol_error(exc):
# A protocol error means the server replied, so keep the session but probe it before the next call.
session.dirty = True
elif not _is_tool_error(exc):
discard_session = True
- raise
+ if not retry:
+ raise
finally:
if slot is not None:
session.posts.settle(slot, abandoned = False)
diff --git a/studio/backend/tests/test_mcp_http_sessions.py b/studio/backend/tests/test_mcp_http_sessions.py
index 91e4f66aded..28c072b8396 100644
--- a/studio/backend/tests/test_mcp_http_sessions.py
+++ b/studio/backend/tests/test_mcp_http_sessions.py
@@ -870,6 +870,106 @@ def test_a_json_rpc_error_from_the_probe_keeps_the_session(monkeypatch, clients)
assert clients[0].probes == 1
+class RestartedServer(RecordingClient):
+ """Answers like a server that no longer knows the Mcp-Session-Id (HTTP 404)."""
+
+ terminated = False
+ gone = (32600, "Session terminated")
+
+ async def list_tools_mcp(self):
+ if self.terminated:
+ self.probes += 1
+ raise _protocol_error(*self.gone)
+ return await super().list_tools_mcp()
+
+ async def call_tool(
+ self,
+ name: str,
+ args: dict,
+ raise_on_error: bool = True,
+ ):
+ if self.terminated:
+ raise _protocol_error(*self.gone)
+ return await super().call_tool(name, args, raise_on_error)
+
+
+ params = [
+ (32600, "Session terminated"), # mcp 1.x client stand-in
+ (-32600, "Session terminated"), # mcp 2.x client stand-in
+ (-32600, "Session not found"), # Python SDK server body, relayed by mcp 2.x
+ (-32001, "Session not found"), # TypeScript SDK server body, relayed by mcp 2.x
+ ]
+)
+def restarted(request, monkeypatch, clients):
+ monkeypatch.setattr(RestartedServer, "gone", request.param)
+ monkeypatch.setattr(
+ mcp_client,
+ "_client",
+ lambda url, headers, use_oauth = False: RestartedServer(url, headers, use_oauth),
+ )
+ return clients
+
+
+def test_a_terminated_session_reconnects_and_replays_once(restarted):
+ _call(HTTP_URL, scope = SCOPE)
+ restarted[0].terminated = True
+ assert _call(HTTP_URL, scope = SCOPE) == "call-1"
+ assert len(restarted) == 2
+ assert _settled(restarted[0]) == 1, "the terminated session was kept"
+ assert [s.client for s in mcp_client._mcp_sessions.values()] == [restarted[1]]
+
+
+def test_a_terminated_idle_session_is_replaced_before_dispatch(monkeypatch, restarted):
+ monkeypatch.setattr(mcp_client, "_HTTP_IDLE_RECHECK", 0.0)
+ _call(HTTP_URL, scope = SCOPE)
+ restarted[0].terminated = True
+ assert _call(HTTP_URL, scope = SCOPE) == "call-1"
+ assert restarted[0].probes == 1 and len(restarted[0].calls) == 1
+ assert len(restarted) == 2
+ assert _settled(restarted[0]) == 1
+
+
+def test_a_terminated_session_is_replayed_only_once(monkeypatch, restarted):
+ _call(HTTP_URL, scope = SCOPE)
+ monkeypatch.setattr(RestartedServer, "terminated", True)
+ out = _call(HTTP_URL, scope = SCOPE)
+ assert RestartedServer.gone[1] in out, out
+ assert len(restarted) == 2, f"reconnected {len(restarted) - 1} times"
+ assert mcp_client._mcp_sessions == {}
+
+
+ "code, message",
+ [(-32602, "Unknown tool: t"), (-32600, "Invalid Request"), (32600, "Session expired soon")],
+)
+def test_other_json_rpc_errors_still_keep_the_session(monkeypatch, clients, code, message):
+ class ProtocolError(RecordingClient):
+ fail = False
+
+ async def call_tool(
+ self,
+ name: str,
+ args: dict,
+ raise_on_error: bool = True,
+ ):
+ if self.fail:
+ self.fail = False
+ raise _protocol_error(code, message)
+ 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)
+ clients[0].fail = True
+ assert _call(HTTP_URL, scope = SCOPE).startswith("Error:")
+ assert _call(HTTP_URL, scope = SCOPE) == "call-2"
+ assert len(clients) == 1, "a protocol error discarded the session"
+
+
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