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: let the chat model use the Decision API through MCP (#12232)
Nilaye3dced149067
diff --git a/studio/MCP.md b/studio/MCP.mdindex d9e8238e481..6ddc3e31ed6 100644--- a/studio/MCP.md+++ b/studio/MCP.md@@ -35,6 +35,17 @@ Downloads are staged and verified before activation; failures leave the serverdisabled and can be retried with **Enable Blender MCP**. Merely opening the dialogor launching Unsloth Studio does not download anything.+## Unsloth Decisions MCP++When the Decision API is on (**Settings → API**), the chat's MCP menu lists+**Unsloth Decisions**. Enable it and a tool-capable chat model can call `decide`,+which asks the local Laya model the same typed questions `POST /v1/systemone`+answers (`noul`, `choice` and `score`), with the model chosen in Settings.++Other MCP clients reach the same tool at `http://127.0.0.1:8888/mcp/decisions/`+(use the actual Unsloth port). It takes the credentials `/v1/systemone` takes, so+send an Unsloth API key as `Authorization: Bearer sk-unsloth-...`.+<a id="studios-own-mcp-server"></a>## Unsloth Studio's own MCP serverdiff --git a/studio/backend/core/inference/mcp_client.py b/studio/backend/core/inference/mcp_client.pyindex bda78139472..fc81d06b266 100644--- a/studio/backend/core/inference/mcp_client.py+++ b/studio/backend/core/inference/mcp_client.py@@ -90,7 +90,8 @@ def _public_mcp_address(url: str) -> str:def validate_mcp_address(url: str) -> None:- if not _managed_mcp_restricted():+ # Studio's own Decisions server is answered in process, so no request leaves this machine.+ if not _managed_mcp_restricted() or is_studio_decisions(url):returnif is_stdio(url):from fastapi import HTTPException@@ -555,6 +556,18 @@ def _stdio_argv(parts: list, env: Optional[dict]) -> list:return [executable, *parts[1:]]+def is_studio_decisions(url: str) -> bool:+ from routes.systemone import MCP_PATH+ from utils.host_policy import is_loopback_host++ parts = urlsplit(url)+ return (+ parts.scheme == "http"+ and is_loopback_host(parts.hostname or "")+ and parts.path.rstrip("/") == MCP_PATH+ )++def _client(url: str,headers: Optional[dict],@@ -563,6 +576,10 @@ def _client(validate_mcp_address(url)from fastmcp import Client+ if is_studio_decisions(url):+ from routes.systemone import decisions_mcp+ return Client(decisions_mcp)+if is_stdio(url):# Belt-and-suspenders: never spawn unless stdio is enabled on this host.if not stdio_mcp_enabled():diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex 0e5c4ea2007..d6cb7fecb72 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -66,6 +66,7 @@ from core.inference.mcp_client import (call_tool_sync,get_cached_tools,in_failure_cooloff,+ is_studio_decisions,is_stdio,list_tools_async,parse_server_headers,@@ -13314,6 +13315,19 @@ def _mcp_specs_for_server(server: dict, mcp_tools: list[dict]) -> list[dict]:return specs+def _enabled_mcp_servers(servers: list[dict]) -> list[dict]:+ enabled = [server for server in servers if server.get("is_enabled")]+ if not any(is_studio_decisions(server["url"]) for server in enabled):+ return enabled+ from utils import systemone_settings++ return (+ enabled+ if systemone_settings.get_enabled()+ else [server for server in enabled if not is_studio_decisions(server["url"])]+ )++def cached_mcp_tools() -> tuple[list[dict], bool]:"""The MCP schemas already in cache, and whether that is the whole set.@@ -13327,7 +13341,7 @@ def cached_mcp_tools() -> tuple[list[dict], bool]:server renders nothing on the completion path either, so skipping that one is exact rather thanshort. Callers that must not undercount should decline on False."""- servers = [s for s in mcp_servers_db.list_servers() if s.get("is_enabled")]+ servers = _enabled_mcp_servers(mcp_servers_db.list_servers())if not stdio_mcp_enabled():servers = [s for s in servers if not is_stdio(s["url"])]@@ -13345,9 +13359,7 @@ def cached_mcp_tools() -> tuple[list[dict], bool]:async def get_enabled_mcp_tools() -> list[dict]:# Keep the SQLite-backed server list off the event loop.- servers = [- s for s in await asyncio.to_thread(mcp_servers_db.list_servers) if s.get("is_enabled")- ]+ servers = await asyncio.to_thread(lambda: _enabled_mcp_servers(mcp_servers_db.list_servers()))# Never spawn stdio servers when stdio is disabled on this host.if not stdio_mcp_enabled():servers = [s for s in servers if not is_stdio(s["url"])]diff --git a/studio/backend/main.py b/studio/backend/main.pyindex 5195592c9ee..581dae8f438 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -365,6 +365,7 @@ from hub.utils.download_registry import (terminate_active_downloads as terminate_hub_downloads,)from routes.settings import router as settings_router+from routes.systemone import MCP_PATH as DECISIONS_MCP_PATH, RequireStudioAuth, decisions_mcpfrom routes.systemone import router as systemone_routerfrom routes.prompts import router as prompts_routerfrom routes.library import router as library_router@@ -999,10 +1000,15 @@ app = FastAPI()app.state.secure = os.environ.get("UNSLOTH_SECURE") == "1"+from fastmcp.utilities.lifespan import combine_lifespans # noqa: E402++# Mounted ahead of /mcp, which would otherwise swallow this path.+_decisions_mcp_app = decisions_mcp.http_app(path = "/", stateless_http = True, json_response = True)+app.router.lifespan_context = combine_lifespans(lifespan, _decisions_mcp_app.lifespan)+app.mount(DECISIONS_MCP_PATH, RequireStudioAuth(_decisions_mcp_app))+# The MCP surface is opt-in: it can start GPU jobs and write model artifacts.if os.environ.get("UNSLOTH_STUDIO_ENABLE_MCP") == "1":- from fastmcp.utilities.lifespan import combine_lifespans-from mcp_server import BearerTokenMiddleware, create_studio_mcp_studio_mcp_app = create_studio_mcp().http_app(path = "/")@@ -1011,7 +1017,9 @@ if os.environ.get("UNSLOTH_STUDIO_ENABLE_MCP") == "1":if not _mcp_token:raise RuntimeError("UNSLOTH_STUDIO_MCP_TOKEN is required when MCP is enabled")_studio_mcp_app = BearerTokenMiddleware(_studio_mcp_app, _mcp_token)- app.router.lifespan_context = combine_lifespans(lifespan, _studio_mcp_lifespan)+ app.router.lifespan_context = combine_lifespans(+ app.router.lifespan_context, _studio_mcp_lifespan+ )app.mount("/mcp", _studio_mcp_app)from loggers.config import LogConfigdiff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex a61587f4195..cf91d5b0639 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -647,6 +647,7 @@ class SystemOneSettingsResponse(BaseModel):loading_model: Optional[str] = Noneinstalling: bool = Falseerror: Optional[str] = None+ mcp_url: strclass SystemOneSettingsPayload(BaseModel):@@ -1375,8 +1376,9 @@ def update_helper_precache(return _helper_precache_response(enabled)-def _systemone_response() -> SystemOneSettingsResponse:+def _systemone_response(request: Request) -> SystemOneSettingsResponse:from core.systemone import catalog, laya_runtime+ from routes.systemone import MCP_PATHenabled = systemone_settings.get_enabled()runtime = laya_runtime.status()@@ -1384,6 +1386,7 @@ def _systemone_response() -> SystemOneSettingsResponse:error = runtime["error"]if runtime["error_model"] not in (None, model):error = None+ port = getattr(request.app.state, "server_port", None) or request.scope["server"][1]return SystemOneSettingsResponse(enabled = enabled,enabled_locked = systemone_settings.enabled_locked(),@@ -1403,6 +1406,7 @@ def _systemone_response() -> SystemOneSettingsResponse:loading_model = runtime["loading_model"],installing = runtime["installing"],error = error,+ mcp_url = f"http://127.0.0.1:{port}{MCP_PATH}/",)@@ -1439,14 +1443,16 @@ def _check_systemone_expectations(payload: SystemOneSettingsPayload) -> None:@_shared_settings_router.get("/systemone", response_model = SystemOneSettingsResponse)def get_systemone_settings(- current_subject: str = Depends(get_current_subject),+ request: Request, current_subject: str = Depends(get_current_subject)) -> SystemOneSettingsResponse:- return _systemone_response()+ return _systemone_response(request)@_owner_settings_router.put("/systemone", response_model = SystemOneSettingsResponse)def update_systemone_settings(- payload: SystemOneSettingsPayload, current_subject: str = Depends(get_current_subject)+ payload: SystemOneSettingsPayload,+ request: Request,+ current_subject: str = Depends(get_current_subject),) -> SystemOneSettingsResponse:from core.systemone import laya_runtimewith _SYSTEMONE_SETTINGS_LOCK:@@ -1459,7 +1465,7 @@ def update_systemone_settings(except laya_runtime.Unavailable as exc:raise HTTPException(status_code = 409, detail = exc.message) from Nonesystemone_settings.save(values)- return _systemone_response()+ return _systemone_response(request)@_owner_settings_router.post("/systemone/validate", status_code = 204)@@ -1491,14 +1497,14 @@ def resolve_systemone_download(@_owner_settings_router.post("/systemone/unload", response_model = SystemOneSettingsResponse)def unload_systemone_model(- current_subject: str = Depends(get_current_subject),+ request: Request, current_subject: str = Depends(get_current_subject)) -> SystemOneSettingsResponse:from core.systemone import laya_runtimetry:laya_runtime.unload()except laya_runtime.Unavailable as exc:raise HTTPException(status_code = 409, detail = exc.message) from None- return _systemone_response()+ return _systemone_response(request)@_shared_settings_router.get("/download-transport", response_model = DownloadTransportResponse)diff --git a/studio/backend/routes/systemone.py b/studio/backend/routes/systemone.pyindex 20a2b19efc6..a95ba417e12 100644--- a/studio/backend/routes/systemone.py+++ b/studio/backend/routes/systemone.py@@ -12,9 +12,12 @@ from uuid import uuid4from fastapi import APIRouter, Depends, HTTPException, Requestfrom fastapi.responses import JSONResponse+from fastmcp import FastMCP+from fastmcp.exceptions import ToolError+from fastmcp.server.middleware import Middlewarefrom pydantic import BaseModel, ConfigDict, Field-from auth.authentication import get_current_subject+from auth.authentication import get_current_subject, securityfrom core.systemone import catalog, laya_runtimefrom utils import systemone_settings@@ -24,6 +27,7 @@ MAX_SCORE_LEVELS = 10MAX_STATE_CHARS = 200_000MAX_QUESTION_CHARS = 20_000_TYPES = ("noul", "choice", "score")+MCP_PATH = "/mcp/decisions"router = APIRouter()@@ -115,12 +119,7 @@ def system_one(request: Request,current_subject: str = Depends(get_current_subject),):- if not systemone_settings.get_enabled():- raise _error(- 404,- "api_usage_error",- "The Decision API is off. The Studio owner can turn it on in Settings > API.",- )+ _require_enabled()if payload.model_extra:raise _error(400,@@ -139,23 +138,40 @@ def system_one("permission_error","Keyless requests can only use the configured Decision API model; send an API key to pick another.",)+ result = _decide(checkpoint, payload.state, payload.questions)+ return JSONResponse(result, headers = {"x-typesafe-request-id": str(uuid4())})+++def _require_enabled() -> None:+ if not systemone_settings.get_enabled():+ raise _error(+ 404,+ "api_usage_error",+ "The Decision API is off. The Studio owner can turn it on in Settings > API.",+ )+++def _decide(+ checkpoint: catalog.Checkpoint, state: JSONContent, questions: dict[str, QuestionIn]+) -> dict:+ if not questions:+ raise _error(422, "invalid_request_error", "At least one question is required")state_chars = (- len(payload.state)- if isinstance(payload.state, str)- else len(json.dumps(payload.state, ensure_ascii = False))+ len(state) if isinstance(state, str) else len(json.dumps(state, ensure_ascii = False)))if state_chars > MAX_STATE_CHARS:raise _error(422, "invalid_request_error", f"State is longer than {MAX_STATE_CHARS} characters")- if len(payload.questions) > MAX_QUESTIONS:+ if len(questions) > MAX_QUESTIONS:raise _error(422, "invalid_request_error", f"At most {MAX_QUESTIONS} questions per request")- for name, question in payload.questions.items():+ for name, question in questions.items():_validate(name, question)- questions = {name: q.model_dump() for name, q in payload.questions.items()}try:- result = laya_runtime.decide(checkpoint, payload.state, questions)+ result = laya_runtime.decide(+ checkpoint, state, {name: q.model_dump() for name, q in questions.items()}+ )except laya_runtime.Unavailable as exc:raise _error(exc.status, exc.error_type, exc.message, exc.retry_after) from Noneif result.pop("truncated"):@@ -165,4 +181,45 @@ def system_one("State and questions exceed the Laya context window. ""Shorten the state or use fewer/shorter criteria.",)- return JSONResponse(result, headers = {"x-typesafe-request-id": str(uuid4())})+ return result+++class DecisionsAvailability(Middleware):+ async def on_list_tools(self, context, call_next):+ if not systemone_settings.get_enabled():+ return []+ return await call_next(context)+++decisions_mcp = FastMCP("Unsloth Decisions")+decisions_mcp.add_middleware(DecisionsAvailability())+++@decisions_mcp.tool+def decide(state: JSONContent, questions: dict[str, QuestionIn]) -> dict[str, Any]:+ """Ask Unsloth's local Laya decision model typed questions about a state (text or JSON).+ questions maps a name you pick to {"type", "instructions", "criteria"}, for example+ {"urgent": {"type": "noul", "instructions": "Does this need a reply within the hour?"}}.+ "noul" is yes/no and answers a probability; "choice" needs criteria mapping each option name+ to a description; "score" needs criteria listing 1 to 10 levels, lowest first."""+ try:+ _require_enabled()+ return _decide(catalog.default_checkpoint(), state, questions)+ except HTTPException as exc:+ raise ToolError(exc.detail["message"]) from None+++class RequireStudioAuth:+ def __init__(self, app: Any) -> None:+ self.app = app++ async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> None:+ if scope["type"] == "http":+ auth_scope = {**scope, "path": MCP_PATH, "root_path": ""}+ try:+ await get_current_subject(await security(Request(auth_scope)))+ except HTTPException as exc:+ response = JSONResponse({"detail": exc.detail}, exc.status_code, exc.headers)+ await response(scope, receive, send)+ return+ await self.app(scope, receive, send)diff --git a/studio/backend/tests/test_bind_host_policy.py b/studio/backend/tests/test_bind_host_policy.pyindex 394b5f85b49..22b7d08ba24 100644--- a/studio/backend/tests/test_bind_host_policy.py+++ b/studio/backend/tests/test_bind_host_policy.py@@ -42,6 +42,13 @@ def test_specific_bind_hosts_are_not_wildcards(host):assert is_wildcard_host(host) is False+ "host", ["127.0.0.1", "::1", "::ffff:127.0.0.1", "::ffff:7f00:1", "localhost"]+)+def test_loopback_hosts_include_ipv4_mapped_spellings(host):+ assert host_policy.is_loopback_host(host) is True++@pytest.mark.parametrize("host,expected",[diff --git a/studio/backend/tests/test_desktop_auth.py b/studio/backend/tests/test_desktop_auth.pyindex c4d750d6d50..c18507b9fce 100644--- a/studio/backend/tests/test_desktop_auth.py+++ b/studio/backend/tests/test_desktop_auth.py@@ -829,6 +829,12 @@ def test_health_response_reports_desktop_capability_fields(monkeypatch):library_module.router = APIRouter()systemone_module = ModuleType("routes.systemone")systemone_module.router = APIRouter()+ # main.py mounts the Decisions MCP app from these at import.+ from fastmcp import FastMCP++ systemone_module.MCP_PATH = "/mcp/decisions"+ systemone_module.RequireStudioAuth = lambda app: app+ systemone_module.decisions_mcp = FastMCP("Unsloth Decisions")# Derived from main.py's import block, not hand-listed: the old hardcoded dict went stale# twice (#8511's openai_codex_auth_router, #8648's youtube_router), each time killing everydiff --git a/studio/backend/tests/test_keyless_api_access.py b/studio/backend/tests/test_keyless_api_access.pyindex 5e6572068be..c74ec779d14 100644--- a/studio/backend/tests/test_keyless_api_access.py+++ b/studio/backend/tests/test_keyless_api_access.py@@ -14,7 +14,11 @@ from types import SimpleNamespaceimport pytestfrom fastapi import HTTPException+from fastapi.testclient import TestClientfrom starlette.requests import Request+from starlette.responses import PlainTextResponse+from starlette.routing import Mount+from starlette.applications import Starlettefrom auth import storagefrom auth.authentication import (@@ -170,6 +174,61 @@ def test_resident_model_discovery_preserves_keyless_inference_access(token):subject_of(discovery_request())[email protected]("token", [None, "not-needed"])+def test_decisions_mcp_preserves_keyless_inference_access(token):+ seed_user()+ set_keyless_api_access("inference", tools = False)++ def decisions_request():+ if token is None:+ return request_for(path = "/mcp/decisions/", method = "POST")+ return bearer_request(token, path = "/mcp/decisions/", method = "POST")++ assert subject_of(decisions_request()) == storage.DEFAULT_ADMIN_USERNAME+ assert not scope_covers("inference", "GET", "/mcp/decisions/")++ set_keyless_api_access("off")+ with pytest.raises(HTTPException):+ subject_of(decisions_request())+++def test_mounted_decisions_mcp_preserves_keyless_inference_access(monkeypatch):+ from routes import systemone++ seen = []+ real_security = systemone.security++ async def capture_security(request):+ seen.append(+ (+ request.scope["path"],+ request.scope["root_path"],+ keyless_request_allowed(request),+ )+ )+ return await real_security(request)++ monkeypatch.setattr(systemone, "security", capture_security)++ async def endpoint(scope, receive, send):+ await PlainTextResponse("ok")(scope, receive, send)++ app = Starlette(+ routes = [Mount(systemone.MCP_PATH, app = systemone.RequireStudioAuth(endpoint))]+ )+ for name, value in vars(app_state()).items():+ setattr(app.state, name, value)++ seed_user()+ set_keyless_api_access("inference", tools = False)+ with TestClient(+ app, base_url = "http://127.0.0.1", client = ("127.0.0.1", 50000)+ ) as client:+ response = client.post(f"{systemone.MCP_PATH}/")+ assert response.status_code == 200, (response.text, seen)+ assert seen == [(systemone.MCP_PATH, "", True)]++def test_settings_are_immediate_and_fail_closed(monkeypatch):import storage.studio_db as studio_dbdiff --git a/studio/backend/tests/test_mcp_servers.py b/studio/backend/tests/test_mcp_servers.pyindex cccac1a30c4..f7c73d1b946 100644--- a/studio/backend/tests/test_mcp_servers.py+++ b/studio/backend/tests/test_mcp_servers.py@@ -1362,6 +1362,32 @@ def test_get_enabled_mcp_tools_caches_discovery(tmp_path, monkeypatch):assert first == second+def test_disabled_decision_api_hides_saved_decisions_tools(tmp_path, monkeypatch):+ from core.inference import mcp_client+ from core.inference import tools as tools_mod+ from utils import systemone_settings+ import asyncio++ _reset_db(tmp_path, monkeypatch)+ monkeypatch.setattr(mcp_client, "_tool_cache", {})+ mcp_servers_db.create_server(+ id = "decisions",+ display_name = "Unsloth Decisions",+ url = "http://127.0.0.1:8888/mcp/decisions/",+ is_enabled = True,+ )+ mcp_client.cache_tools("decisions", _one_tool("decide"))+ monkeypatch.setattr(systemone_settings, "get_enabled", lambda: False)++ assert tools_mod.cached_mcp_tools() == ([], True)+ assert asyncio.run(tools_mod.get_enabled_mcp_tools()) == []++ monkeypatch.setattr(systemone_settings, "get_enabled", lambda: True)+ cached, complete = tools_mod.cached_mcp_tools()+ assert complete is True+ assert [tool["function"]["name"] for tool in cached] == ["mcp__decisions__decide"]++def test_get_enabled_mcp_tools_does_not_cache_failures(tmp_path, monkeypatch):"""A failed probe isn't cached: once the cool-off elapses, it's retried."""from core.inference import mcp_clientdiff --git a/studio/backend/tests/test_systemone.py b/studio/backend/tests/test_systemone.pyindex f3404dd1e38..a56c0229694 100644--- a/studio/backend/tests/test_systemone.py+++ b/studio/backend/tests/test_systemone.py@@ -1,6 +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+import asyncioimport osimport sysimport threading@@ -8,7 +9,7 @@ import weakreffrom types import SimpleNamespaceimport pytest-from fastapi import FastAPI+from fastapi import FastAPI, HTTPExceptionfrom fastapi.testclient import TestClientfrom auth.authentication import get_current_subject@@ -1754,3 +1755,105 @@ def test_rocm_never_builds_cuda_graphs(tmp_path, monkeypatch):batch = dict(zip(laya_runtime._INPUTS, _tiny_decision_batch(torch, rows = 3, tokens = 40)))laya_runtime._run_model(agent, batch)assert "_unsloth_graphs" not in agent.__dict__+++def _mcp_decide(arguments):+ from fastmcp import Client+ async def call():+ async with Client(systemone.decisions_mcp) as mcp:+ return await mcp.call_tool("decide", arguments, raise_on_error = False)++ return asyncio.run(call())+++def test_decisions_mcp_answers_like_the_route(client):+ route = _post(client).json()+ result = _mcp_decide(+ {"state": "Everything is down and we have a demo at noon.", "questions": QUESTIONS}+ )+ assert not result.is_error+ assert result.structured_content == route+++def test_decisions_mcp_reports_the_route_errors(monkeypatch, runtime):+ result = _mcp_decide({"state": "x", "questions": {}})+ assert result.is_error and "At least one question" in result.content[0].text+ long_state = "x" * (systemone.MAX_STATE_CHARS + 1)+ result = _mcp_decide({"state": long_state, "questions": QUESTIONS})+ assert result.is_error and "State is longer than" in result.content[0].text+ monkeypatch.setattr(systemone_settings, "_owner_setting", {}.get)+ result = _mcp_decide({"state": "x", "questions": QUESTIONS})+ assert result.is_error and "Settings > API" in result.content[0].text+ assert runtime == []+++def test_chat_calls_studio_decisions_without_a_server_or_key(client):+ import json++ from core.inference.mcp_client import call_tool_sync, close_mcp_sessions, list_tools_async++ url = client.get("/api/settings/systemone").json()["mcp_url"]+ assert url == f"http://127.0.0.1:80{systemone.MCP_PATH}/"+ tools = asyncio.run(list_tools_async(url, timeout = 10))+ assert [tool["name"] for tool in tools] == ["decide"]+ text = call_tool_sync(url, None, "decide", {"state": "x", "questions": QUESTIONS}, scope = "chat")+ close_mcp_sessions(url, None)+ assert json.loads(text)["answers"]["urgent"] == {"type": "noul", "noul": 0.9}+++def test_decisions_mcp_endpoint_needs_studio_auth(monkeypatch):+ from main import app+ from starlette.applications import Starlette+ from starlette.routing import Mount++ call = {+ "jsonrpc": "2.0",+ "id": 1,+ "method": "tools/call",+ "params": {"name": "decide", "arguments": {"state": "x", "questions": QUESTIONS}},+ }+ listing = {"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}+ headers = {"Accept": "application/json, text/event-stream"}+ assert (+ TestClient(app).post(f"{systemone.MCP_PATH}/", json = call, headers = headers).status_code+ == 401+ )++ async def signed_in(credentials):+ return "tester"++ monkeypatch.setattr(systemone, "get_current_subject", signed_in)+ mcp_app = systemone.decisions_mcp.http_app(path = "/", stateless_http = True, json_response = True)+ served = Starlette(+ routes = [Mount(systemone.MCP_PATH, systemone.RequireStudioAuth(mcp_app))],+ lifespan = mcp_app.lifespan,+ )+ with TestClient(served) as http:+ listed = http.post(+ f"{systemone.MCP_PATH}/",+ json = listing,+ headers = {**headers, "Authorization": "Bearer t"},+ )+ answered = http.post(+ f"{systemone.MCP_PATH}/", json = call, headers = {**headers, "Authorization": "Bearer t"}+ )+ monkeypatch.setattr(systemone_settings, "_owner_setting", {}.get)+ hidden = http.post(+ f"{systemone.MCP_PATH}/",+ json = listing,+ headers = {**headers, "Authorization": "Bearer t"},+ )+ assert answered.status_code == 200, answered.text+ assert answered.json()["result"]["structuredContent"]["answers"]["urgent"]["noul"] == 0.9+ assert [tool["name"] for tool in listed.json()["result"]["tools"]] == ["decide"]+ assert hidden.json()["result"]["tools"] == []+++def test_managed_accounts_can_add_studio_decisions_but_not_other_loopback():+ from core.inference.mcp_client import validate_mcp_address+ from utils.account_context import AccountContext, run_as++ alice = AccountContext("alice-id", "alice")+ run_as(alice, validate_mcp_address, f"http://127.0.0.1:8888{systemone.MCP_PATH}/")+ with pytest.raises(HTTPException):+ run_as(alice, validate_mcp_address, "http://127.0.0.1:8888/mcp")diff --git a/studio/backend/utils/host_policy.py b/studio/backend/utils/host_policy.pyindex 6ca4902cfb3..70b9b18141a 100644--- a/studio/backend/utils/host_policy.py+++ b/studio/backend/utils/host_policy.py@@ -182,10 +182,8 @@ LOOPBACK_FALLBACK_HOST = "127.0.0.1"def is_loopback_host(host: str) -> bool:- try:- return ipaddress.ip_address(host.split("%", 1)[0]).is_loopback- except ValueError:- return host.lower() == "localhost"+ literal = _normalized_ip(host.split("%", 1)[0])+ return literal.is_loopback if literal is not None else host.lower() == "localhost"def scope_request_host(server) -> "str | None":diff --git a/studio/backend/utils/keyless_api_access.py b/studio/backend/utils/keyless_api_access.pyindex 8e354865d31..839db8abf2f 100644--- a/studio/backend/utils/keyless_api_access.py+++ b/studio/backend/utils/keyless_api_access.py@@ -36,6 +36,7 @@ _INFERENCE_ROUTES = frozenset(("POST", "/v1/embeddings"),("POST", "/v1/messages"),("POST", "/v1/messages/count_tokens"),+ ("POST", "/mcp/decisions"),("GET", "/v1/models"),("GET", "/api/inference/loaded-models"),("POST", "/v1/responses"),diff --git a/studio/frontend/src/features/chat/mcp-composer-button.tsx b/studio/frontend/src/features/chat/mcp-composer-button.tsxindex 27de94a9dcd..a6fe06c9abf 100644--- a/studio/frontend/src/features/chat/mcp-composer-button.tsx+++ b/studio/frontend/src/features/chat/mcp-composer-button.tsx@@ -24,7 +24,11 @@ import {TooltipContent,TooltipTrigger,} from "@/components/ui/tooltip";-import { useShortcut } from "@/features/settings";+import {+ loadSystemOneSettings,+ subscribeSystemOneSettings,+ useShortcut,+} from "@/features/settings";import { subscribeToMcpServerMutationSettlements } from "./api/mcp-server-mutation-tracker";import {@@ -34,6 +38,7 @@ import {updateMcpServer,} from "./api/mcp-servers-api";import { ChatMcpServersDialog } from "./chat-mcp-servers-dialog";+import { normalizeMcpUrl } from "./mcp-server-url";import { useChatActive } from "./runtime-provider";import { useChatRuntimeStore } from "./stores/chat-runtime-store";import { useMcpServersDialogStore } from "./stores/mcp-servers-dialog-store";@@ -69,14 +74,6 @@ const MCP_PRESETS: readonly McpPreset[] = [},] as const;-// mcp_servers has no UNIQUE(url); dedupe by normalized URL so a preset toggle reuses its row instead of duplicating.-function normalizeMcpUrl(url: string): string {- return (url || "").trim().toLowerCase().replace(/\/+$/, "");-}--// Static, so it is not rebuilt on every render.-const PRESET_URLS = new Set(MCP_PRESETS.map((p) => normalizeMcpUrl(p.url)));-export function McpComposerButton({side = "bottom",}: {@@ -102,6 +99,8 @@ export function McpComposerButton({);const pendingUrlsRef = useRef(new Set<string>());const [hintKey, setHintKey] = useState<string | null>(null);+ const [decisionsUrl, setDecisionsUrl] = useState<string | null>(null);+ const decisionsRefreshGenerationRef = useRef(0);const listRefreshGenerationRef = useRef(0);const hasLoadedServerSnapshotRef = useRef(false);@@ -113,7 +112,21 @@ export function McpComposerButton({async (waitForPendingMutations = true, minimumMutationEpoch = 0) => {const generation = listRefreshGenerationRef.current + 1;listRefreshGenerationRef.current = generation;+ const decisionsGeneration = decisionsRefreshGenerationRef.current + 1;+ decisionsRefreshGenerationRef.current = decisionsGeneration;setServersLoaded(false);+ loadSystemOneSettings().then(+ (settings) => {+ if (decisionsRefreshGenerationRef.current !== decisionsGeneration)+ return;+ setDecisionsUrl(settings.enabled ? settings.mcpUrl : null);+ },+ () => {+ if (decisionsRefreshGenerationRef.current !== decisionsGeneration)+ return;+ setDecisionsUrl(null);+ },+ );try {const rows = await listMcpServers({waitForPendingMutations,@@ -135,6 +148,15 @@ export function McpComposerButton({[],);+ useEffect(+ () =>+ subscribeSystemOneSettings((settings) => {+ decisionsRefreshGenerationRef.current += 1;+ setDecisionsUrl(settings.enabled ? settings.mcpUrl : null);+ }),+ [],+ );+const applyServer = useCallback((server: McpServerConfig) => {setServers((current) => {const index = current.findIndex(@@ -153,6 +175,7 @@ export function McpComposerButton({});return () => {unsubscribe();+ decisionsRefreshGenerationRef.current += 1;listRefreshGenerationRef.current += 1;};}, [refresh]);@@ -170,17 +193,34 @@ export function McpComposerButton({};}, [refresh, dialogOpen]);+ const presets: readonly McpPreset[] = decisionsUrl+ ? [+ ...MCP_PRESETS,+ {+ id: "unsloth-decisions",+ displayName: "Unsloth Decisions",+ url: decisionsUrl,+ },+ ]+ : MCP_PRESETS;const enabledUrls = new Set(servers.filter((s) => s.is_enabled).map((s) => normalizeMcpUrl(s.url)),);// Non-preset servers, shown below the presets so they stay toggleable.const customServers = servers.filter(- (s) => !s.builtin_id && !PRESET_URLS.has(normalizeMcpUrl(s.url)),+ (s) =>+ !s.builtin_id &&+ normalizeMcpUrl(s.url) !== "studio:decisions" &&+ !presets.some((p) => normalizeMcpUrl(p.url) === normalizeMcpUrl(s.url)),);const blenderEnabled = servers.some((server) => server.builtin_id === "blender" && server.is_enabled,);- const enabledCount = servers.filter((s) => s.is_enabled).length;+ const enabledCount = servers.filter(+ (s) =>+ s.is_enabled &&+ (decisionsUrl !== null || normalizeMcpUrl(s.url) !== "studio:decisions"),+ ).length;const active = usable && mcpEnabledForChat && enabledCount > 0;async function toggleServer(args: {@@ -346,7 +386,7 @@ export function McpComposerButton({The loaded model cannot use MCP tools</DropdownMenuLabel>)}- {MCP_PRESETS.map((preset) => {+ {presets.map((preset) => {const norm = normalizeMcpUrl(preset.url);return renderRow({key: preset.id,diff --git a/studio/frontend/src/features/chat/mcp-server-url.ts b/studio/frontend/src/features/chat/mcp-server-url.tsnew file mode 100644index 00000000000..8bea43c097c--- /dev/null+++ b/studio/frontend/src/features/chat/mcp-server-url.ts@@ -0,0 +1,52 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++const HTTP_AUTHORITY =+ /^[hH][tT][tT][pP]:\/\/(?:[^/?#]*@)?(\[[^\]]+\]|[^/:?#]+)(?::[^/?#]*)?(?=\/|[?#]|$)/;++function isStudioLoopbackHost(host: string): boolean {+ const lower = host.toLowerCase();+ if (lower === "localhost") return true;+ if (!lower.startsWith("[") || !lower.endsWith("]")) {+ const octets = lower.split(".");+ return (+ octets.length === 4 &&+ octets[0] === "127" &&+ octets.every(+ (octet) =>+ /^\d{1,3}$/.test(octet) &&+ Number(octet) <= 255 &&+ String(Number(octet)) === octet,+ )+ );+ }++ const literal = lower.slice(1, -1).replace(/%25/i, "%").split("%", 1)[0];+ try {+ const canonical = new URL(`http://[${literal}]/`).hostname.toLowerCase();+ return (+ canonical === "[::1]" ||+ /^\[::ffff:7f[0-9a-f]{2}:[0-9a-f]{1,4}\]$/.test(canonical)+ );+ } catch {+ return false;+ }+}++// mcp_servers has no UNIQUE(url); normalize Studio's in-process Decisions endpoint so a preset+// toggle reuses rows saved under older ports and every backend-accepted loopback spelling.+export function normalizeMcpUrl(url: string): string {+ const trimmed = (url || "").trim().replace(/\/+$/, "");+ const comparable = trimmed.replace(/[\t\n\r]/g, "");+ const authority = HTTP_AUTHORITY.exec(comparable);+ if (authority && isStudioLoopbackHost(authority[1])) {+ const rawPath = comparable+ .slice(authority[0].length)+ .split(/[?#]/, 1)[0]+ .replace(/\/+$/, "");+ if (rawPath === "/mcp/decisions") {+ return "studio:decisions";+ }+ }+ return trimmed.toLowerCase();+}diff --git a/studio/frontend/src/features/settings/api/systemone.ts b/studio/frontend/src/features/settings/api/systemone.tsindex 5821fa55796..6feef03311d 100644--- a/studio/frontend/src/features/settings/api/systemone.ts+++ b/studio/frontend/src/features/settings/api/systemone.ts@@ -26,6 +26,7 @@ export type SystemOneSettings = {loadingModel: string | null;installing: boolean;error: string | null;+ mcpUrl: string;};export type SystemOneDownloadPlan = {@@ -66,6 +67,8 @@ type ApiSystemOneSettings = {loading_model: string | null;installing: boolean;error: string | null;+ // biome-ignore lint/style/useNamingConvention: API schema+ mcp_url: string;};type ApiSystemOneDownloadPlan = {@@ -78,6 +81,24 @@ type ApiSystemOneDownloadPlan = {};const SETTINGS_PATH = "/api/settings/systemone";+const SYSTEMONE_SETTINGS_EVENT = "unsloth-systemone-settings-change";++export function subscribeSystemOneSettings(+ listener: (settings: SystemOneSettings) => void,+) {+ const handleChange = (event: Event) => {+ listener((event as CustomEvent<SystemOneSettings>).detail);+ };+ window.addEventListener(SYSTEMONE_SETTINGS_EVENT, handleChange);+ return () => window.removeEventListener(SYSTEMONE_SETTINGS_EVENT, handleChange);+}++function publishSystemOneSettings(settings: SystemOneSettings) {+ window.dispatchEvent(+ new CustomEvent(SYSTEMONE_SETTINGS_EVENT, { detail: settings }),+ );+ return settings;+}function toApiPatch(patch: SystemOneSettingsPatch) {const { expectedEnabled, expectedModel, ...settings } = patch;@@ -109,6 +130,7 @@ function fromApi(settings: ApiSystemOneSettings): SystemOneSettings {loadingModel: settings.loading_model,installing: settings.installing,error: settings.error,+ mcpUrl: settings.mcp_url,};}@@ -129,13 +151,15 @@ export async function loadSystemOneSettings(): Promise<SystemOneSettings> {export async function updateSystemOneSettings(patch: SystemOneSettingsPatch,): Promise<SystemOneSettings> {- return readSettings(- await authFetch(SETTINGS_PATH, {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(toApiPatch(patch)),- }),- "Failed to save Decision API settings",+ return publishSystemOneSettings(+ await readSettings(+ await authFetch(SETTINGS_PATH, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(toApiPatch(patch)),+ }),+ "Failed to save Decision API settings",+ ),);}diff --git a/studio/frontend/src/features/settings/index.ts b/studio/frontend/src/features/settings/index.tsindex 9da154e4237..84294356066 100644--- a/studio/frontend/src/features/settings/index.ts+++ b/studio/frontend/src/features/settings/index.ts@@ -12,6 +12,10 @@ export {export { loadEmbeddingModelSettings } from "./api/embedding-model";export { updateHubSource } from "./api/hub-settings";export { loadOpenAIAutoSwitchSettings } from "./api/openai-auto-switch";+export {+ loadSystemOneSettings,+ subscribeSystemOneSettings,+} from "./api/systemone";export {loadHuggingFaceCacheSettings,updateHuggingFaceCacheSettings,diff --git a/studio/frontend/tests/mcp-server-arguments.test.ts b/studio/frontend/tests/mcp-server-arguments.test.tsindex 48f40676c4b..37e8123d36f 100644--- a/studio/frontend/tests/mcp-server-arguments.test.ts+++ b/studio/frontend/tests/mcp-server-arguments.test.ts@@ -11,6 +11,7 @@ import {createMcpStdioSnapshot,resolveMcpStdioUrl,} from "../src/features/chat/mcp-server-form.ts";+import { normalizeMcpUrl } from "../src/features/chat/mcp-server-url.ts";import {readAfterPendingMcpServerMutations,readMcpServerMutationSnapshot,@@ -26,6 +27,7 @@ const CHAT_MCP_SERVERS_DIALOG = readSrc("features/chat/chat-mcp-servers-dialog.tsx",);const MCP_COMPOSER_BUTTON = readSrc("features/chat/mcp-composer-button.tsx");+const SYSTEMONE_API = readSrc("features/settings/api/systemone.ts");function deferred<T>() {let resolve!: (value: T | PromiseLike<T>) => void;@@ -809,3 +811,72 @@ test("every list consumer uses the shared pending-mutation read barrier", () =>assert.doesNotMatch(CHAT_MCP_SERVERS_DIALOG, /await refresh\(\)/);assert.doesNotMatch(MCP_COMPOSER_BUTTON, /await refresh\(\)/);});++test("the Decisions preset matches a row saved under another port", () => {+ for (const url of [+ "http://127.0.0.1:8888/mcp/decisions",+ "http://127.0.0.1:8889/mcp/decisions",+ "http://localhost:8888/mcp/decisions",+ "http://[::1]:8888/mcp/decisions",+ "http://[0:0:0:0:0:0:0:1]:8888/mcp/decisions",+ "http://[::1%25lo0]:8888/mcp/decisions",+ "http://[::ffff:127.0.0.1]:8888/mcp/decisions",+ "http://[::1]:8888/mcp/decisions/?scope=chat",+ "HTTP://LOCALHOST:8888/mcp/decisions",+ "http://[email protected]:8888/mcp/decisions",+ "http://user:pass@[::1]:8888/mcp/decisions",+ "http://127.0.0.1:/mcp/decisions",+ "http://127.0.0.1:99999/mcp/decisions",+ "http://127.0.0.1:abc/mcp/decisions",+ "http://127.0.0.1\n:8888/mcp/decisions",+ ]) {+ assert.equal(normalizeMcpUrl(url), "studio:decisions", url);+ }+ for (const url of [+ "https://127.0.0.1:8888/mcp/decisions",+ "http://example.com/mcp/decisions",+ "http://128.0.0.1:8888/mcp/decisions",+ "http://127.0.0.01:8888/mcp/decisions",+ "http://[::2]:8888/mcp/decisions",+ "http://127.0.0.1:8888/MCP/DECISIONS",+ "http://127.0.0.1:8888/mcp",+ "http://127.0.0.1:8888/mcp/decisions/extra",+ "http://127.0.0.1:8888/mcp/x/../decisions",+ "http://127.0.0.1:8888/mcp/./decisions",+ ]) {+ assert.notEqual(normalizeMcpUrl(url), "studio:decisions", url);+ }+});++test("the Decisions row stays hidden while the Decision API is off", () => {+ assert.match(+ MCP_COMPOSER_BUTTON,+ /const customServers = servers\.filter\([\s\S]*normalizeMcpUrl\(s\.url\) !== "studio:decisions"/,+ );+ assert.match(+ MCP_COMPOSER_BUTTON,+ /const enabledCount = servers\.filter\([\s\S]*decisionsUrl !== null \|\| normalizeMcpUrl\(s\.url\) !== "studio:decisions"/,+ );+});++test("an older Decision API settings response cannot replace a newer one", () => {+ const refresh = MCP_COMPOSER_BUTTON.match(+ /const refresh = useCallback\(([\s\S]*?)\n \},\n \[\],\n \);/,+ )?.[1];+ assert.ok(refresh);+ const settingsRequest = refresh.match(+ /loadSystemOneSettings\(\)\.then\(([\s\S]*?)\n \);/,+ )?.[1];+ assert.ok(settingsRequest);+ assert.equal(+ settingsRequest.match(+ /decisionsRefreshGenerationRef\.current !== decisionsGeneration/g,+ )?.length,+ 2,+ );+ assert.match(MCP_COMPOSER_BUTTON, /subscribeSystemOneSettings\(\(settings\) =>/);+ assert.match(+ SYSTEMONE_API,+ /new CustomEvent\(SYSTEMONE_SETTINGS_EVENT, \{ detail: settings \}\)/,+ );+});