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: move to mcp 2 and fastmcp 4 (#16475)

Nilay38fa6c1cdc64
diff --git a/pyproject.toml b/pyproject.toml
index 98413ce219c..9e1cb54b26c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -161,7 +161,7 @@ studio = [
# Windows on ARM: 46.0.7 publishes no win_arm64 wheel and the sdist needs Rust.
"cryptography>=42.0.0,<=46.0.3; sys_platform == 'win32' and platform_machine == 'ARM64'",
"httpx>=0.27.0",
- "fastmcp>=3.0.2",
+ "fastmcp>=4.1.5,<5",
"gguf==0.19.0 ; python_version >= '3.10'",
"gguf==0.18.0 ; python_version < '3.10'",
"safetensors>=0.8.0 ; sys_platform == 'win32' and python_version >= '3.10'",
diff --git a/studio/backend/core/data_recipe/__init__.py b/studio/backend/core/data_recipe/__init__.py
index ebc27983757..adb29a1fb02 100644
--- a/studio/backend/core/data_recipe/__init__.py
+++ b/studio/backend/core/data_recipe/__init__.py
@@ -4,5 +4,8 @@
"""Data Recipe core (DataDesigner wrapper + job runner)."""
from .jobs import JobManager, get_job_manager
+from .mcp_compat import install_streamablehttp_alias
+
+install_streamablehttp_alias()
__all__ = ["JobManager", "get_job_manager"]
diff --git a/studio/backend/core/data_recipe/mcp_compat.py b/studio/backend/core/data_recipe/mcp_compat.py
new file mode 100644
index 00000000000..800e830fe0c
--- /dev/null
+++ b/studio/backend/core/data_recipe/mcp_compat.py
@@ -0,0 +1,82 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import importlib.abc
+import importlib.machinery
+import sys
+from contextlib import asynccontextmanager
+
+_DATA_DESIGNER_MCP_IO = "data_designer.engine.mcp.io"
+
+
+@asynccontextmanager
+async def _streamablehttp_client(url, headers = None):
+ from mcp.client.streamable_http import streamable_http_client
+ from mcp.shared._httpx_utils import create_mcp_http_client
+ async with create_mcp_http_client(headers = headers) as client:
+ async with streamable_http_client(url, http_client = client) as streams:
+ yield streams
+
+
+def _negotiating_session(session_cls):
+ try:
+ from mcp.client._probe import negotiate_auto
+ except ImportError:
+ return session_cls
+
+ class _NegotiatingClientSession(session_cls):
+ # data-designer only calls initialize(), which a modern-only server rejects.
+ async def initialize(self):
+ if getattr(self, "_negotiating", False):
+ return await super().initialize()
+ self._negotiating = True
+ try:
+ await negotiate_auto(self)
+ finally:
+ self._negotiating = False
+ return self.initialize_result
+
+ return _NegotiatingClientSession
+
+
+class _PatchingLoader(importlib.abc.Loader):
+ def __init__(self, inner):
+ self._inner = inner
+
+ def __getattr__(self, name):
+ return getattr(self._inner, name)
+
+ def create_module(self, spec):
+ return self._inner.create_module(spec)
+
+ def exec_module(self, module):
+ self._inner.exec_module(module)
+ module.ClientSession = _negotiating_session(module.ClientSession)
+
+
+class _DataDesignerMcpFinder(importlib.abc.MetaPathFinder):
+ def find_spec(
+ self,
+ fullname,
+ path,
+ target = None,
+ ):
+ if fullname != _DATA_DESIGNER_MCP_IO:
+ return None
+ import mcp.client.streamable_http as streamable_http
+
+ alias = getattr(streamable_http, "streamablehttp_client", _streamablehttp_client)
+ mcp2 = alias is _streamablehttp_client
+ streamable_http.streamablehttp_client = alias
+ spec = importlib.machinery.PathFinder.find_spec(fullname, path)
+ if mcp2 and spec is not None and spec.loader is not None:
+ spec.loader = _PatchingLoader(spec.loader)
+ return spec
+
+
+# data-designer targets mcp 1; a hook avoids importing mcp at startup.
+def install_streamablehttp_alias() -> None:
+ if not any(isinstance(f, _DataDesignerMcpFinder) for f in sys.meta_path):
+ sys.meta_path.insert(0, _DataDesignerMcpFinder())
diff --git a/studio/backend/core/inference/mcp_client.py b/studio/backend/core/inference/mcp_client.py
index 7ca0a1bf013..2b22fbc81c7 100644
--- a/studio/backend/core/inference/mcp_client.py
+++ b/studio/backend/core/inference/mcp_client.py
@@ -1568,7 +1568,8 @@ class McpToolList(list):
def _capabilities(client) -> Any:
- return getattr(getattr(client, "initialize_result", None), "capabilities", None)
+ # initialize_result stays None on a modern connection, which has no initialize handshake.
+ return getattr(client, "server_capabilities", None)
async def _list_resources(client) -> Optional[list[dict]]:
@@ -1581,7 +1582,7 @@ async def _list_resources(client) -> Optional[list[dict]]:
while len(listed) < MAX_MCP_RESOURCES:
page = await client.list_resources_mcp(cursor = cursor)
listed.extend(getattr(page, "resources", None) or ())
- cursor = getattr(page, "nextCursor", None) or getattr(page, "next_cursor", None)
+ cursor = getattr(page, "next_cursor", None)
# A repeated cursor would loop forever.
if not cursor or cursor in cursors:
break
@@ -1872,9 +1873,8 @@ def _image_mime(mime: Any) -> Optional[str]:
def _resource_mime(obj: Any) -> Any:
- # mcp 2.x renames mimeType to mime_type, keeping camelCase only as an alias
- mime = getattr(obj, "mimeType", None)
- return mime if mime is not None else getattr(obj, "mime_type", None)
+ # mcp 2.x exposes mime_type; mimeType is only a constructor alias there
+ return obj.mime_type if hasattr(obj, "mime_type") else getattr(obj, "mimeType", None)
def _block_image(block: Any) -> Optional[tuple[str, str]]:
diff --git a/studio/backend/requirements/single-env/constraints.txt b/studio/backend/requirements/single-env/constraints.txt
index 4c94e9dedb0..1be54180427 100644
--- a/studio/backend/requirements/single-env/constraints.txt
+++ b/studio/backend/requirements/single-env/constraints.txt
@@ -20,8 +20,8 @@ pyarrow==23.0.1; sys_platform != "win32" or platform_machine != "ARM64"
pyarrow>=21.0.0; sys_platform == "win32" and platform_machine == "ARM64"
# FastMCP compat
-fastmcp>=3.0.2
-mcp>=1.24,<2
+fastmcp>=4.1.5,<5
+mcp>=2.3,<3
websockets>=15.0.1
# Cap anyio <4.14: 4.14's new asyncio per-task cancel scope (TaskHandle/_run_coro)
diff --git a/studio/backend/requirements/single-env/data-designer-deps.txt b/studio/backend/requirements/single-env/data-designer-deps.txt
index 6210129c094..c84e0f6d6a5 100644
--- a/studio/backend/requirements/single-env/data-designer-deps.txt
+++ b/studio/backend/requirements/single-env/data-designer-deps.txt
@@ -12,7 +12,7 @@ jsonpath-rust-bindings<2,>=1.0
jsonschema<5,>=4.0.0
lxml<7,>=6.0.2
marko<3,>=2.1.2
-mcp<2,>=1.26.0
+mcp<3,>=2.3
networkx<4,>=3.0
python-json-logger>=3,<4
ruff<1,>=0.14.10
diff --git a/studio/backend/requirements/single-env/patch_metadata.py b/studio/backend/requirements/single-env/patch_metadata.py
index ce97d540d5b..2d57f038aeb 100644
--- a/studio/backend/requirements/single-env/patch_metadata.py
+++ b/studio/backend/requirements/single-env/patch_metadata.py
@@ -25,6 +25,10 @@ PATCHES: tuple[tuple[re.Pattern[str], str], ...] = (
re.compile(r"^Requires-Dist: pyarrow<20,>=19\.0\.1$", re.MULTILINE),
"Requires-Dist: pyarrow>=21.0.0",
),
+ (
+ re.compile(r"^Requires-Dist: mcp<2,>=1\.26\.0$", re.MULTILINE),
+ "Requires-Dist: mcp<3,>=2.3",
+ ),
)
diff --git a/studio/backend/requirements/studio.txt b/studio/backend/requirements/studio.txt
index 9097b90ab5c..5ec4073bd7b 100644
--- a/studio/backend/requirements/studio.txt
+++ b/studio/backend/requirements/studio.txt
@@ -48,7 +48,7 @@ cryptography>=42.0.0; sys_platform != "win32" or platform_machine != "ARM64"
# constraints.txt, which a plain pip install of the extra never reaches.
cryptography>=42.0.0,<=46.0.3; sys_platform == "win32" and platform_machine == "ARM64"
httpx>=0.27.0
-fastmcp>=3.0.2
+fastmcp>=4.1.5,<5
# Local image generation (Images page): diffusers' GGUFQuantizationConfig needs
# the gguf reader. diffusers itself is torch-bound and comes via the ML stack;
# gguf is torch-free so it lives here, where it's installed in every mode.
diff --git a/studio/backend/tests/test_data_recipe_mcp_compat.py b/studio/backend/tests/test_data_recipe_mcp_compat.py
new file mode 100644
index 00000000000..e9accc0bc02
--- /dev/null
+++ b/studio/backend/tests/test_data_recipe_mcp_compat.py
@@ -0,0 +1,131 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import importlib.util
+import os
+import re
+import socket
+import subprocess
+import sys
+import textwrap
+import time
+from pathlib import Path
+
+import pytest
+
+_BACKEND_DIR = Path(__file__).resolve().parent.parent
+_SINGLE_ENV = _BACKEND_DIR / "requirements" / "single-env"
+
+pytest.importorskip("fastmcp")
+pytest.importorskip("packaging")
+
+from packaging.requirements import Requirement # noqa: E402
+
+_SERVER = """
+import sys
+from fastmcp import FastMCP
+
+mcp = FastMCP("recipe")
+
+def add(a: int, b: int) -> int:
+ return a + b
+
+mcp.run(transport = "http", host = "127.0.0.1", port = int(sys.argv[1]), show_banner = False)
+"""
+
+_RECIPE_WORKER = """
+import asyncio
+import sys
+import core.data_recipe
+from data_designer.engine.mcp.io import ClientSession, streamablehttp_client
+
+async def main():
+ async with streamablehttp_client(sys.argv[1], headers = {"x-recipe": "1"}) as streams:
+ async with ClientSession(streams[0], streams[1]) as session:
+ await session.initialize()
+ print([tool.name for tool in (await session.list_tools()).tools])
+ print("modern" if session.discover_result is not None else "legacy")
+
+asyncio.run(main())
+"""
+
+
+def _free_port() -> int:
+ with socket.socket() as sock:
+ sock.bind(("127.0.0.1", 0))
+ return sock.getsockname()[1]
+
+
+def _wait_for_port(port: int) -> None:
+ deadline = time.monotonic() + 30
+ while time.monotonic() < deadline:
+ with socket.socket() as sock:
+ if sock.connect_ex(("127.0.0.1", port)) == 0:
+ return
+ time.sleep(0.1)
+ raise AssertionError("MCP server did not start")
+
+
+def _mcp_requirement(path: Path) -> Requirement:
+ lines = path.read_text(encoding = "utf-8").splitlines()
+ return next(Requirement(line) for line in lines if re.match(r"mcp\b[<>=]", line))
+
+
[email protected]("name", ["constraints.txt", "data-designer-deps.txt"])
+def test_single_env_installs_the_mcp_that_speaks_the_modern_protocol(name):
+ requirement = _mcp_requirement(_SINGLE_ENV / name)
+ assert requirement.specifier.contains("2.3.0")
+ assert not requirement.specifier.contains("1.30.0")
+
+
+def test_data_designer_mcp_pin_is_relaxed_for_pip_check(tmp_path):
+ spec = importlib.util.spec_from_file_location(
+ "patch_metadata", _SINGLE_ENV / "patch_metadata.py"
+ )
+ patch_metadata = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(patch_metadata)
+ metadata = tmp_path / "METADATA"
+ metadata.write_text("Requires-Dist: mcp<2,>=1.26.0\n", encoding = "utf-8")
+
+ assert patch_metadata.patch_file(metadata) is True
+
+ relaxed = Requirement(metadata.read_text(encoding = "utf-8").split(": ", 1)[1].strip())
+ assert relaxed.specifier.contains("2.3.0")
+
+
+def test_recipe_worker_reaches_mcp_through_data_designers_client_import(tmp_path):
+ package = tmp_path / "data_designer" / "engine" / "mcp"
+ package.mkdir(parents = True)
+ for folder in (package, package.parent, package.parent.parent):
+ (folder / "__init__.py").write_text("", encoding = "utf-8")
+ (package / "io.py").write_text(
+ "from mcp import ClientSession\n"
+ "from mcp.client.streamable_http import streamablehttp_client\n",
+ encoding = "utf-8",
+ )
+ port = _free_port()
+ server = subprocess.Popen(
+ [sys.executable, "-c", textwrap.dedent(_SERVER), str(port)],
+ stdout = subprocess.DEVNULL,
+ stderr = subprocess.DEVNULL,
+ )
+ try:
+ _wait_for_port(port)
+ worker = subprocess.run(
+ [sys.executable, "-c", textwrap.dedent(_RECIPE_WORKER), f"http://127.0.0.1:{port}/mcp"],
+ cwd = _BACKEND_DIR,
+ env = {**os.environ, "PYTHONPATH": os.pathsep.join([str(tmp_path), str(_BACKEND_DIR)])},
+ capture_output = True,
+ text = True,
+ timeout = 120,
+ )
+ finally:
+ server.kill()
+ server.wait()
+ assert worker.returncode == 0, worker.stderr
+ assert "['add']" in worker.stdout
+ # A modern-only server rejects the bare initialize handshake data-designer sends.
+ assert "modern" in worker.stdout.split()
diff --git a/studio/backend/tests/test_mcp_resources.py b/studio/backend/tests/test_mcp_resources.py
index 9e0622ee521..296fbd31ab1 100644
--- a/studio/backend/tests/test_mcp_resources.py
+++ b/studio/backend/tests/test_mcp_resources.py
@@ -228,9 +228,8 @@ def test_a_resource_only_server_without_a_tools_capability_is_discovered(monkeyp
class _Client:
def __init__(self, tools):
- self.initialize_result = SimpleNamespace(
- capabilities = SimpleNamespace(tools = tools, resources = {})
- )
+ self.initialize_result = None
+ self.server_capabilities = SimpleNamespace(tools = tools, resources = {})
async def __aenter__(self):
return self
diff --git a/studio/backend/tests/test_mcp_upgrade_compat.py b/studio/backend/tests/test_mcp_upgrade_compat.py
index 8ee599e9974..1f7c3174248 100644
--- a/studio/backend/tests/test_mcp_upgrade_compat.py
+++ b/studio/backend/tests/test_mcp_upgrade_compat.py
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Studio's fastmcp>=3.0.2 has no upper bound or lockfile, so these check the installed version."""
+"""Studio's fastmcp>=4.1.5,<5 has no lockfile, so these check the installed version."""
from __future__ import annotations
@@ -93,7 +93,7 @@ def test_only_stdio_answers_the_liveness_probe():
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"
+ assert (major, minor) >= (4, 1), f"fastmcp {version} is below the declared >=4.1.5"
def test_tool_errors_are_still_distinguishable_from_transport_errors():