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: build the MCP apps on first use instead of at backend import (#15814)
Daniel Han559c69d637e9
diff --git a/studio/backend/main.py b/studio/backend/main.pyindex f83853dffc0..852fac1a680 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -431,7 +431,7 @@ from hub.utils.download_registry import ()from routes.settings import router as settings_routerfrom routes.sandbox_capability import router as sandbox_capability_router-from routes.systemone import MCP_PATH as DECISIONS_MCP_PATH, RequireStudioAuth, decisions_mcp+from routes.systemone import MCP_PATH as DECISIONS_MCP_PATH, RequireStudioAuthfrom routes.systemone import router as systemone_routerfrom routes.prompts import router as prompts_routerfrom routes.scheduled_tasks import router as scheduled_tasks_router@@ -1136,18 +1136,38 @@ app = FastAPI(app.openapi_url = "/openapi.json"app.state.secure = os.environ.get("UNSLOTH_SECURE") == "1"-from fastmcp.utilities.lifespan import combine_lifespans # noqa: E402+from utils.lazy_asgi_app import LazyLifespanApp, combine_lifespans # noqa: E402++def _build_decisions_mcp_app():+ from routes.systemone import decisions_mcp+ return decisions_mcp.http_app(path = "/", stateless_http = True, json_response = True)+++def _decisions_on_at_startup() -> bool:+ from utils import systemone_settings+ return systemone_settings.get_enabled()+++# Built on first request, or at startup when switched on: fastmcp is most of a second of import.# Mounted ahead of /mcp, which would otherwise swallow this path.-_decisions_mcp_app = decisions_mcp.http_app(path = "/", stateless_http = True, json_response = True)+_decisions_mcp_app = LazyLifespanApp(+ _build_decisions_mcp_app, wanted_at_startup = _decisions_on_at_startup+)app.router.lifespan_context = combine_lifespans(lifespan, _decisions_mcp_app.lifespan)app.mount(DECISIONS_MCP_PATH, RequireStudioAuth(_decisions_mcp_app))# Always mounted; the gate answers 404 until the owner turns agent access on.-from mcp_server import create_studio_mcp # noqa: E402from studio_mcp.gate import StudioMcpGate # noqa: E402+from utils.mcp_access import is_mcp_enabled # noqa: E402+++def _build_studio_mcp_app():+ from mcp_server import create_studio_mcp+ return create_studio_mcp().http_app(path = "/", stateless_http = True)+-_studio_mcp_app = create_studio_mcp().http_app(path = "/", stateless_http = True)+_studio_mcp_app = LazyLifespanApp(_build_studio_mcp_app, wanted_at_startup = is_mcp_enabled)app.router.lifespan_context = combine_lifespans(app.router.lifespan_context, _studio_mcp_app.lifespan)diff --git a/studio/backend/routes/systemone.py b/studio/backend/routes/systemone.pyindex 446427975f1..5e481671b15 100644--- a/studio/backend/routes/systemone.py+++ b/studio/backend/routes/systemone.py@@ -10,6 +10,7 @@ import base64import binasciiimport jsonimport math+import threadingimport timefrom typing import Any, Optional, Unionfrom uuid import uuid4@@ -18,9 +19,6 @@ import httpxfrom fastapi import APIRouter, Depends, HTTPException, Requestfrom fastapi.responses import JSONResponsefrom starlette.concurrency import run_in_threadpool-from fastmcp import FastMCP-from fastmcp.exceptions import ToolError-from fastmcp.server.middleware import Middlewarefrom pydantic import BaseModel, ConfigDict, Fieldfrom auth.authentication import get_current_subject, security@@ -471,18 +469,6 @@ def _upstream_error(name: str, response: httpx.Response) -> HTTPException:return _error(502, "api_error", message)-class DecisionsAvailability(Middleware):- async def on_list_tools(self, context, call_next):- if not await asyncio.to_thread(systemone_settings.get_enabled):- return []- return await call_next(context)---decisions_mcp = FastMCP("Unsloth Decisions")-decisions_mcp.add_middleware(DecisionsAvailability())---@decisions_mcp.toolasync def decide(state: JSONContent, questions: dict[str, QuestionIn]) -> dict[str, Any]:"""Ask Unsloth's decision model typed questions about a state (text or JSON).questions maps a name you pick to {"type", "instructions", "criteria"}, for example@@ -496,9 +482,40 @@ async def decide(state: JSONContent, questions: dict[str, QuestionIn]) -> dict[sresult.pop("_backend", None)return resultexcept HTTPException as exc:+ from fastmcp.exceptions import ToolErrorraise ToolError(exc.detail["message"]) from None+def _build_decisions_mcp():+ from fastmcp import FastMCP+ from fastmcp.server.middleware import Middleware++ class DecisionsAvailability(Middleware):+ async def on_list_tools(self, context, call_next):+ if not await asyncio.to_thread(systemone_settings.get_enabled):+ return []+ return await call_next(context)++ mcp = FastMCP("Unsloth Decisions")+ mcp.add_middleware(DecisionsAvailability())+ mcp.tool(decide)+ return mcp+++_decisions_mcp_lock = threading.Lock()+++def __getattr__(name: str) -> Any:+ if name != "decisions_mcp":+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ with _decisions_mcp_lock:+ mcp = globals().get("decisions_mcp")+ if mcp is None:+ mcp = _build_decisions_mcp()+ globals()["decisions_mcp"] = mcp+ return mcp++class RequireStudioAuth:def __init__(self, app: Any) -> None:self.app = appdiff --git a/studio/backend/tests/test_mcp_lazy_mount.py b/studio/backend/tests/test_mcp_lazy_mount.pynew file mode 100644index 00000000000..c99aa00b3e5--- /dev/null+++ b/studio/backend/tests/test_mcp_lazy_mount.py@@ -0,0 +1,261 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The /mcp and /mcp/decisions apps are built on first use, not at import: same routes, same+answers, one build under concurrent first requests, and the MCP lifespan still runs."""++import json+import os+import subprocess+import sys+import threading+from pathlib import Path++import anyio+import httpx+import pytest+from fastapi.testclient import TestClient+from starlette.applications import Starlette+from starlette.responses import PlainTextResponse+from starlette.routing import Mount, Route++from auth import storage+from utils.lazy_asgi_app import LazyLifespanApp++from . import mcp_harness+from .mcp_harness import MCP_HEADERS, seed_owner++isolated_auth = mcp_harness.isolated_auth++LISTING = {"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}+BACKEND = Path(__file__).resolve().parent.parent+pytestmark = pytest.mark.usefixtures("isolated_auth")+++def test_import_main_builds_no_mcp_app():+ env = {+ name: value+ for name, value in os.environ.items()+ if name not in ("UNSLOTH_STUDIO_ENABLE_MCP", "UNSLOTH_STUDIO_MCP_TOKEN")+ }+ probe = (+ "import json, sys, main\n"+ "from starlette.routing import Mount\n"+ "mods = sorted(m for m in sys.modules if m.split('.')[0] in ('fastmcp', 'mcp_server'))\n"+ "mounts = [r.path for r in main.app.routes if isinstance(r, Mount)]\n"+ "print('PROBE ' + json.dumps({'mods': mods, 'mounts': mounts}))\n"+ )+ result = subprocess.run(+ [sys.executable, "-c", probe],+ cwd = BACKEND,+ env = env,+ capture_output = True,+ text = True,+ timeout = 600,+ )+ assert result.returncode == 0, result.stderr[-2000:]+ line = [l for l in result.stdout.splitlines() if l.startswith("PROBE ")][-1]+ seen = json.loads(line[len("PROBE ") :])+ assert seen["mods"] == []+ assert "/mcp/decisions" in seen["mounts"] and "/mcp" in seen["mounts"]+ assert seen["mounts"].index("/mcp/decisions") < seen["mounts"].index("/mcp")+++class Counting:+ """A built app whose builds, lifespan entries and exits are counted."""++ def __init__(self, fail = False):+ self.builds = 0+ self.entered = 0+ self.exited = 0+ self.fail = fail+ self._lock = threading.Lock()++ def build(self):+ with self._lock:+ self.builds += 1+ if self.fail:+ raise ValueError("cannot build")+ started = {}++ async def endpoint(request):+ return PlainTextResponse("up" if started.get("on") else "not started")++ from contextlib import asynccontextmanager++ @asynccontextmanager+ async def lifespan(app):+ self.entered += 1+ started["on"] = True+ try:+ yield+ finally:+ started["on"] = False+ self.exited += 1++ return Starlette(routes = [Route("/", endpoint, methods = ["GET", "POST"])], lifespan = lifespan)+++def parent(lazy):+ return Starlette(routes = [Mount("/m", lazy)], lifespan = lazy.lifespan)+++def test_nothing_is_built_until_the_first_request_then_once_for_concurrent_ones():+ counting = Counting()+ lazy = LazyLifespanApp(counting.build)+ app = parent(lazy)+ with TestClient(app) as client:+ assert counting.builds == 0 and counting.entered == 0++ async def burst():+ transport = httpx.ASGITransport(app = app)+ async with httpx.AsyncClient(transport = transport, base_url = "http://t") as http:+ results = []++ async def one():+ results.append((await http.get("/m/")).text)++ async with anyio.create_task_group() as tg:+ for _ in range(16):+ tg.start_soon(one)+ return results++ assert client.portal.call(burst) == ["up"] * 16+ assert counting.builds == 1 and counting.entered == 1 and counting.exited == 0+ assert counting.exited == 1+++def test_wanted_at_startup_starts_before_the_first_request_and_restarts_each_cycle():+ counting = Counting()+ lazy = LazyLifespanApp(counting.build, wanted_at_startup = lambda: True)+ for cycle in (1, 2):+ with TestClient(parent(lazy)) as client:+ assert (counting.builds, counting.entered) == (1, cycle)+ assert client.get("/m/").text == "up"+ assert counting.exited == cycle+++def test_a_built_app_is_started_with_later_lifespans():+ counting = Counting()+ lazy = LazyLifespanApp(counting.build)+ with TestClient(parent(lazy)) as client:+ assert client.get("/m/").text == "up"+ with TestClient(parent(lazy)) as client:+ assert counting.entered == 2+ assert (counting.builds, counting.exited) == (1, 2)+++def test_without_a_parent_lifespan_the_app_is_served_unstarted():+ counting = Counting()+ client = TestClient(parent(LazyLifespanApp(counting.build)))+ assert client.get("/m/").text == "not started"+ assert counting.entered == 0+++def test_build_failures_fail_the_request_or_the_startup_that_wanted_it():+ counting = Counting(fail = True)+ with TestClient(+ parent(LazyLifespanApp(counting.build)), raise_server_exceptions = False+ ) as client:+ assert client.get("/m/").status_code == 500+ assert client.get("/m/").status_code == 500+ assert counting.builds == 1+ with pytest.raises(ValueError, match = "cannot build"):+ with TestClient(parent(LazyLifespanApp(counting.build, wanted_at_startup = lambda: True))):+ pass+++def test_threads_share_one_build():+ counting = Counting()+ lazy = LazyLifespanApp(counting.build)+ barrier = threading.Barrier(8)+ built = []++ def go():+ barrier.wait()+ built.append(lazy.build())++ threads = [threading.Thread(target = go) for _ in range(8)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()+ assert counting.builds == 1 and len({id(app) for app in built}) == 1+++def _studio_mcp(on_at_startup):+ import main+ from studio_mcp.gate import StudioMcpGate+ from utils.mcp_access import set_mcp_enabled++ builds = []++ def build():+ builds.append(1)+ return main._build_studio_mcp_app()++ seed_owner()+ raw_key, _row = storage.create_api_key(storage.DEFAULT_ADMIN_USERNAME, name = "agent")+ set_mcp_enabled(on_at_startup)+ from utils.mcp_access import is_mcp_enabled++ lazy = LazyLifespanApp(build, wanted_at_startup = is_mcp_enabled)+ app = Starlette(routes = [Mount("/mcp", StudioMcpGate(lazy))], lifespan = lazy.lifespan)+ app.state.server_port = 8888+ app.state.cloudflare_url = None+ return app, raw_key, builds, set_mcp_enabled++[email protected]("on_at_startup", [False, True])+def test_studio_mcp_answers_whether_switched_on_at_startup_or_later(on_at_startup):+ app, raw_key, builds, set_mcp_enabled = _studio_mcp(on_at_startup)+ headers = {**MCP_HEADERS, "Authorization": f"Bearer {raw_key}"}+ with TestClient(app, base_url = "http://127.0.0.1:8888") as http:+ assert len(builds) == int(on_at_startup)+ if not on_at_startup:+ assert http.post("/mcp/", json = LISTING, headers = headers).status_code == 404+ assert builds == []+ set_mcp_enabled(True)+ assert http.post("/mcp/", json = LISTING, headers = MCP_HEADERS).status_code == 401+ response = http.post("/mcp/", json = LISTING, headers = headers)+ assert response.status_code == 200, response.text+ assert "studio_status" in response.text+ assert len(builds) == 1+++def test_decisions_mcp_is_built_by_its_first_signed_in_request(monkeypatch):+ import main+ from routes import systemone++ async def signed_in(credentials):+ return "tester"++ lazy = LazyLifespanApp(main._build_decisions_mcp_app)+ app = Starlette(+ routes = [Mount(systemone.MCP_PATH, systemone.RequireStudioAuth(lazy))],+ lifespan = lazy.lifespan,+ )+ with TestClient(app) as http:+ assert (+ http.post(f"{systemone.MCP_PATH}/", json = LISTING, headers = MCP_HEADERS).status_code+ == 401+ )+ assert not lazy.built+ monkeypatch.setattr(systemone, "get_current_subject", signed_in)+ response = http.post(+ f"{systemone.MCP_PATH}/",+ json = LISTING,+ headers = {**MCP_HEADERS, "Authorization": "Bearer t"},+ )+ assert response.status_code == 200, response.text+ assert lazy.built+++def test_main_mounts_the_lazy_apps():+ import main+ from starlette.routing import Mount as StarletteMount++ mounts = {r.path: r.app for r in main.app.routes if isinstance(r, StarletteMount)}+ assert mounts["/mcp"].app is main._studio_mcp_app+ assert mounts["/mcp/decisions"].app is main._decisions_mcp_app+ assert isinstance(main._studio_mcp_app, LazyLifespanApp)diff --git a/studio/backend/utils/lazy_asgi_app.py b/studio/backend/utils/lazy_asgi_app.pynew file mode 100644index 00000000000..0cebe3ceeec--- /dev/null+++ b/studio/backend/utils/lazy_asgi_app.py@@ -0,0 +1,138 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A mounted ASGI app built on its first request instead of at import. Its lifespan runs inside the+parent app's lifespan: entered at startup when the app is already built or wanted then, otherwise+by the first request, always in one host task (anyio task groups must exit in the task that entered+them) and exited at the parent's shutdown. Concurrent first requests share one build."""++from __future__ import annotations++import threading+from contextlib import AsyncExitStack, asynccontextmanager+from typing import Any, AsyncIterator, Callable, Optional++import anyio+import anyio.to_thread+++def combine_lifespans(*lifespans: Callable[[Any], Any]) -> Callable[[Any], Any]:+ """Enter lifespans in order, exit in reverse, merge the dicts they yield (later wins)."""++ @asynccontextmanager+ async def combined(app: Any) -> AsyncIterator[dict]:+ merged: dict = {}+ async with AsyncExitStack() as stack:+ for lifespan in lifespans:+ result = await stack.enter_async_context(lifespan(app))+ if result is not None:+ merged.update(result)+ yield merged++ return combined+++class _Cycle:+ def __init__(self) -> None:+ self.wanted = anyio.Event()+ self.ready = anyio.Event()+ self.stopping = anyio.Event()+ self.app: Any = None+ self.error: Optional[BaseException] = None+++class LazyLifespanApp:+ def __init__(+ self,+ build: Callable[[], Any],+ *,+ wanted_at_startup: Callable[[], bool] = lambda: False,+ ) -> None:+ self._build = build+ self._wanted_at_startup = wanted_at_startup+ self._built: Any = None+ self._build_lock = threading.Lock()+ self._cycle: Optional[_Cycle] = None++ @property+ def built(self) -> bool:+ return self._built is not None++ def build(self) -> Any:+ """The inner app, built once whatever thread or event loop asks first."""+ built = self._built+ if built is not None:+ return built+ with self._build_lock:+ if self._built is None:+ self._built = self._build()+ return self._built++ def _startup_wants(self) -> bool:+ try:+ return bool(self._wanted_at_startup())+ except Exception:+ return False++ async def _host(self, cycle: _Cycle) -> None:+ await cycle.wanted.wait()+ if cycle.stopping.is_set():+ cycle.error = RuntimeError("The parent app is shutting down")+ cycle.ready.set()+ return+ entered = False+ try:+ app = self._built+ if app is None:+ app = await anyio.to_thread.run_sync(self.build)+ async with app.router.lifespan_context(app):+ entered = True+ cycle.app = app+ cycle.ready.set()+ await cycle.stopping.wait()+ except Exception as exc:+ # A failure while shutting down propagates like the eager lifespan's did.+ if entered:+ raise+ cycle.error = exc+ cycle.ready.set()++ async def _ready(self, cycle: _Cycle) -> Any:+ cycle.wanted.set()+ await cycle.ready.wait()+ if cycle.error is not None:+ raise RuntimeError("The mounted app failed to start") from cycle.error+ return cycle.app++ @asynccontextmanager+ async def lifespan(self, app: Any) -> AsyncIterator[None]:+ cycle = _Cycle()+ # Built already (an earlier lifespan cycle) or on at startup: build and start it now, as an+ # eagerly built app would, so startup still fails if it cannot.+ start_now = self._built is not None or await anyio.to_thread.run_sync(self._startup_wants)+ if start_now and self._built is None:+ await anyio.to_thread.run_sync(self.build)+ async with anyio.create_task_group() as tg:+ tg.start_soon(self._host, cycle)+ self._cycle = cycle+ try:+ if start_now:+ await self._ready(cycle)+ yield+ finally:+ if self._cycle is cycle:+ self._cycle = None+ cycle.stopping.set()+ cycle.wanted.set()++ async def __call__(self, scope: dict, receive: Any, send: Any) -> None:+ cycle = self._cycle+ if scope["type"] == "lifespan" or cycle is None or cycle.stopping.is_set():+ # No parent lifespan running: hand the request to the app as it stands, unstarted,+ # which is what an eagerly built app sees too.+ app = self._built+ if app is None:+ app = await anyio.to_thread.run_sync(self.build)+ else:+ app = await self._ready(cycle)+ await app(scope, receive, send)