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
hide app-only MCP tools from the model and explain why local commands are disabled (#8739)
Nilaybc652cb747df
diff --git a/studio/backend/core/inference/mcp_client.py b/studio/backend/core/inference/mcp_client.pyindex 09f9a62b8e2..e865723d8bf 100644--- a/studio/backend/core/inference/mcp_client.py+++ b/studio/backend/core/inference/mcp_client.py@@ -155,6 +155,35 @@ def stdio_mcp_enabled() -> bool:return True+def stdio_mcp_disabled_reason() -> str:+ """User-facing reason local commands are off, mirroring stdio_mcp_enabled().++ Telling a user whose gate is suspended by an active tunnel to set+ UNSLOTH_STUDIO_ALLOW_STDIO_MCP=1 would re-enable local command execution on+ a published API, so the suspended cases must name their actual cause."""+ from state.tool_policy import get_tool_policy+ from utils.host_policy import loopback_default_active, remote_connector_active++ if os.environ.get("UNSLOTH_STUDIO_ALLOW_STDIO_MCP") == "1" and loopback_default_active():+ if remote_connector_active():+ return (+ "Local commands are disabled while Remote Access is on, because the "+ "server is reachable from outside this machine. Turn off Remote Access "+ "to use local MCP servers, or use an http:// or https:// URL instead."+ )+ if get_tool_policy() is False:+ return (+ "Local commands are disabled because tools are disabled for this "+ "server. Restart without --disable-tools, or use an http:// or "+ "https:// URL instead."+ )+ return (+ "Local commands aren't enabled on this server. To allow them, set "+ "UNSLOTH_STUDIO_ALLOW_STDIO_MCP=1 and restart Unsloth, or use an "+ "http:// or https:// URL instead."+ )++# Probe timeouts for discovering a server's tool list. OAuth needs minutes for# first-connect/expired-token browser sign-in; stdio allows for first-run# package download (e.g. `npx -y ...`); HTTP fails fast.diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex a73691d6741..823932c4722 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -9255,6 +9255,24 @@ ALL_TOOLS = [_OPENAI_FN_NAME_RE = re.compile(r"^[a-zA-Z0-9_-]{1,64}$")+def _mcp_tool_model_visible(tool: dict) -> bool:+ """False for MCP Apps tools marked app-only (_meta.ui.visibility without+ "model"): those exist for a server-rendered widget to call, not the LLM."""+ # model_dump() gives "meta", the wire "_meta"; unrelated keys in one must not mask the other.+ for key in ("meta", "_meta"):+ meta = tool.get(key)+ if not isinstance(meta, dict):+ continue+ ui = meta.get("ui")+ visibility = ui.get("visibility") if isinstance(ui, dict) else None+ if visibility is None:+ # Tolerated, not spec: only flat "ui/resourceUri" is deprecated.+ visibility = meta.get("ui/visibility")+ if isinstance(visibility, (list, tuple)):+ return "model" in visibility+ return True++def _mcp_specs_for_server(server: dict, mcp_tools: list[dict]) -> list[dict]:"""Convert an MCP server's tool list into OpenAI function specs."""display = server.get("display_name") or server["id"]@@ -9265,6 +9283,9 @@ def _mcp_specs_for_server(server: dict, mcp_tools: list[dict]) -> list[dict]:if not raw_name:logger.warning("Skipping MCP tool on '%s': empty name.", display)continue+ if not _mcp_tool_model_visible(tool):+ logger.debug("Skipping app-only MCP tool '%s' on '%s'.", raw_name, display)+ continuename = f"{MCP_TOOL_PREFIX}{server['id']}__{raw_name}"# Bad chars or oversized names would 400 the whole request; skip + warn# so the rest of the tools still ship.@@ -9288,7 +9309,10 @@ def _mcp_specs_for_server(server: dict, mcp_tools: list[dict]) -> list[dict]:"function": {"name": name,"description": f"[{display}] {tool.get('description') or ''}".strip(),- "parameters": tool.get("inputSchema") or {"type": "object", "properties": {}},+ # mcp<2 dumps "inputSchema", 2.x "input_schema"; accept both.+ "parameters": tool.get("inputSchema")+ or tool.get("input_schema")+ or {"type": "object", "properties": {}},},})diff --git a/studio/backend/routes/mcp_servers.py b/studio/backend/routes/mcp_servers.pyindex 2653d902a49..ef1f0dd4a6a 100644--- a/studio/backend/routes/mcp_servers.py+++ b/studio/backend/routes/mcp_servers.py@@ -27,6 +27,7 @@ from core.inference.mcp_client import (parse_stdio_command,probe_timeout,record_probe_failure,+ stdio_mcp_disabled_reason,stdio_mcp_enabled,)from core.inference.mcp_config_import import parse_mcp_config@@ -90,11 +91,7 @@ def _validate_url(url: str) -> str:parsed = urlparse(trimmed)if parsed.scheme not in ("http", "https"):if _looks_like_command(trimmed):- detail = (- "Local commands aren't enabled on this server. To allow them, "- "set UNSLOTH_STUDIO_ALLOW_STDIO_MCP=1 and restart Unsloth, or use "- "an http:// or https:// URL instead."- )+ detail = stdio_mcp_disabled_reason()else:detail = ("MCP server address must start with http:// or https:// "@@ -282,9 +279,7 @@ async def refresh_mcp_server_tools(if is_stdio(server["url"]):require_ui_session_for_local_commands(via_api_key)if not stdio_mcp_enabled():- raise HTTPException(- status_code = 400, detail = "stdio MCP servers are disabled on this host"- )+ raise HTTPException(status_code = 400, detail = stdio_mcp_disabled_reason())use_oauth = bool(server.get("use_oauth"))try:diff --git a/studio/backend/tests/test_mcp_servers.py b/studio/backend/tests/test_mcp_servers.pyindex 731823c2929..8b3572ab510 100644--- a/studio/backend/tests/test_mcp_servers.py+++ b/studio/backend/tests/test_mcp_servers.py@@ -175,6 +175,85 @@ def test_mcp_specs_skip_empty_tool_name():assert specs == []+def test_mcp_specs_skip_app_only_tools():+ """MCP Apps tools marked _meta.ui.visibility without "model" are for the+ server's rendered widget, not the LLM; keep them out of the schema set."""+ from core.inference.tools import _mcp_specs_for_server++ server = {"id": "srv", "display_name": "S"}+ tools = [+ {"name": "shown"},+ {"name": "widget_only", "meta": {"ui": {"visibility": ["app"]}}},+ {"name": "both", "meta": {"ui": {"visibility": ["app", "model"]}}},+ {"name": "flat_key", "meta": {"ui/visibility": ["app"]}},+ {"name": "underscore_meta", "_meta": {"ui": {"visibility": ["app"]}}},+ {"name": "unrelated_meta", "meta": {"ui": {"resourceUri": "ui://x"}}},+ ]+ specs = _mcp_specs_for_server(server, tools)+ names = {s["function"]["name"] for s in specs}+ assert names == {"mcp__srv__shown", "mcp__srv__both", "mcp__srv__unrelated_meta"}+++def test_mcp_specs_read_visibility_from_either_meta_spelling():+ """A "meta" holding unrelated keys must not mask an app-only "_meta"."""+ from core.inference.tools import _mcp_specs_for_server++ server = {"id": "srv", "display_name": "S"}+ tools = [+ {+ "name": "widget_only",+ "meta": {"vendor": "x"},+ "_meta": {"ui": {"visibility": ["app"]}},+ },+ {"name": "shown", "meta": {"vendor": "x"}, "_meta": {"ui": {"visibility": ["model"]}}},+ ]+ specs = _mcp_specs_for_server(server, tools)+ assert {s["function"]["name"] for s in specs} == {"mcp__srv__shown"}+++ "visibility, visible",+ [+ (["model"], True),+ (["app"], False),+ ([], False), # "visible to nobody" reads as hidden+ ("model", True), # not a list: unrecognised shape stays visible+ (None, True),+ (["Model"], False), # spec values are lowercase+ ],+)+def test_mcp_specs_visibility_shapes(visibility, visible):+ from core.inference.tools import _mcp_specs_for_server++ tool = {"name": "t", "meta": {"ui": {"visibility": visibility}}}+ specs = _mcp_specs_for_server({"id": "srv", "display_name": "S"}, [tool])+ assert bool(specs) is visible++[email protected]("schema_key", ["inputSchema", "input_schema"])+def test_mcp_specs_keep_the_tool_arguments(schema_key):+ """Reading one spelling only would leave every tool argument-less after an+ mcp 2.x bump."""+ from core.inference.tools import _mcp_specs_for_server++ schema = {"type": "object", "properties": {"q": {"type": "string"}}}+ tool = {"name": "search", "description": "d", schema_key: schema}+ specs = _mcp_specs_for_server({"id": "srv", "display_name": "S"}, [tool])+ assert specs[0]["function"]["parameters"] == schema+++def test_mcp_specs_match_the_installed_sdk_dump():+ """Whichever spelling the pinned SDK emits, the arguments must survive."""+ from mcp.types import Tool++ from core.inference.tools import _mcp_specs_for_server++ schema = {"type": "object", "properties": {"q": {"type": "string"}}}+ dumped = Tool(name = "search", description = "d", inputSchema = schema).model_dump(exclude_none = True)+ specs = _mcp_specs_for_server({"id": "srv", "display_name": "S"}, [dumped])+ assert specs[0]["function"]["parameters"] == schema++def test_mcp_specs_drops_duplicate_names():"""Duplicate tool names from one server -> OpenAI rejects; drop before forwarding."""from core.inference.tools import _mcp_specs_for_serverdiff --git a/studio/backend/tests/test_mcp_stdio_pr5863.py b/studio/backend/tests/test_mcp_stdio_pr5863.pyindex f80a377428f..80322139aa7 100644--- a/studio/backend/tests/test_mcp_stdio_pr5863.py+++ b/studio/backend/tests/test_mcp_stdio_pr5863.py@@ -207,6 +207,40 @@ def test_stdio_enabled_only_for_exact_one(monkeypatch):assert mcp_client.stdio_mcp_enabled() is True+def test_disabled_reason_generic(monkeypatch):+ _disable(monkeypatch)+ assert "UNSLOTH_STUDIO_ALLOW_STDIO_MCP=1" in mcp_client.stdio_mcp_disabled_reason()+++def test_disabled_reason_remote_access(monkeypatch):+ _disable(monkeypatch)+ host_policy.apply_stdio_mcp_loopback_default("127.0.0.1")+ host_policy.set_remote_connector_active(True)+ assert mcp_client.stdio_mcp_enabled() is False+ reason = mcp_client.stdio_mcp_disabled_reason()+ assert "Remote Access" in reason+ assert "UNSLOTH_STUDIO_ALLOW_STDIO_MCP" not in reason+++def test_disabled_reason_tools_disabled(monkeypatch):+ from state import tool_policy++ _disable(monkeypatch)+ host_policy.apply_stdio_mcp_loopback_default("127.0.0.1")+ tool_policy.set_tool_policy(False)+ assert mcp_client.stdio_mcp_enabled() is False+ reason = mcp_client.stdio_mcp_disabled_reason()+ assert "disable-tools" in reason+ assert "UNSLOTH_STUDIO_ALLOW_STDIO_MCP" not in reason+++def test_disabled_reason_explicit_optin_not_suspended(monkeypatch):+ # An explicit operator =1 is not the loopback auto-default, so no tunnel suspension.+ monkeypatch.setenv("UNSLOTH_STUDIO_ALLOW_STDIO_MCP", "1")+ host_policy.set_remote_connector_active(True)+ assert mcp_client.stdio_mcp_enabled() is True++# ── 3b. loopback bind defaults the gate on ──────────────────────────