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: honor a request's enable_tools: false instead of overriding it (#8547)
Daniel Han098a6a0957c9
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex d18726304c1..27aa4a3ba35 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -2663,12 +2663,49 @@ def _effective_enable_tools(payload) -> Optional[bool]:"""Resolve `payload.enable_tools` against the process-level tool policy.Returns the policy value when set (CLI hard-override from `unsloth run`),- else the per-request value.+ else the per-request value, else the launcher's default (tools on) for a+ request that never mentions tools. An explicit `enable_tools: false` is the+ caller asking for no tools, so it wins over that default -- only the+ `--enable-tools` override outranks it."""- from state.tool_policy import get_tool_policy+ from state.tool_policy import get_tool_policy, get_tool_policy_defaultpolicy = get_tool_policy()- return policy if policy is not None else payload.enable_tools+ if policy is not None:+ return policy+ if payload.enable_tools is None:+ return get_tool_policy_default()+ return payload.enable_tools+++def _tools_on_by_launcher_default_only(payload) -> bool:+ """True when tools are on ONLY because of the launcher's tools-on default:+ no CLI override is installed and the request itself asked for nothing."""+ from state.tool_policy import get_tool_policy+ return (+ get_tool_policy() is None+ and payload.enable_tools is None+ and not getattr(payload, "mcp_enabled", False)+ )+++def _request_states_tool_intent(payload) -> bool:+ """True when a request states its own tool intent through the standard+ OpenAI fields: a `tool_choice: "none"` withdrawal, its own tool catalog,+ tool-result history to continue, or a `response_format` contract the tool+ loop would break. Such a request did not omit the question, so the launcher+ default must not answer it.++ Mirrors what `_takes_tool_passthrough` already withholds from the policy on+ the GGUF router, including its `bool(payload.tools)` reading of the catalog:+ an empty `tools: []` reads the same as an omitted one on both paths."""+ if getattr(payload, "tool_choice", None) == "none":+ return True+ if payload.tools:+ return True+ if _extract_response_format(payload) is not None:+ return True+ return any(m.role == "tool" or m.tool_calls for m in payload.messages)def _explicit_studio_tool_loop_requested(payload) -> bool:@@ -13808,12 +13845,35 @@ async def openai_chat_completions(# Classify capability flags from the loaded template._sf_model_info = backend.models.get(backend.active_model_name, {})_sf_tpl = (_sf_model_info.get("chat_template_info") or {}).get("template")+ # Resolve the tool policy BEFORE the protocol is classified: the template+ # branch chosen here must be the one generation renders. Reading the raw+ # policy and withdrawing it later would classify with the ``tool_use``+ # branch and then generate on the plain one, so a model whose reasoning+ # markers live only in the tool template starts in the wrong reasoning mode.+ from state.tool_policy import get_tool_policy as _get_tool_policy_sf++ _sf_cli_policy = _get_tool_policy_sf()+ _sf_tools_on = _effective_enable_tools(payload)+ # The launcher's tools-on default answers a request that said nothing about+ # tools. A request carrying tool_choice: "none", its own tool catalog,+ # tool-result history, or a response_format contract did say something, so+ # the default must not withdraw that opt-out or take the catalog from the+ # client-tool passthrough below. The GGUF router draws the same line with+ # _client_disabled_tool_calls and _takes_tool_passthrough; an explicit+ # enable_tools/mcp_enabled ask, or a CLI --enable-tools, still claims the+ # request as before.+ if (+ _sf_tools_on+ and _tools_on_by_launcher_default_only(payload)+ and _request_states_tool_intent(payload)+ ):+ _sf_tools_on = False+ _sf_mcp_allowed = bool(payload.mcp_enabled) and _sf_cli_policy is not False+# Named templates may expose native reasoning only in their ``tool_use``# branch. Use a truthy placeholder for Unsloth-managed tools, whose concrete# schemas are selected below, and the request schemas for client passthrough.- _sf_server_tool_intent = bool(- _effective_enable_tools(payload) or _explicit_studio_tool_loop_requested(payload)- )+ _sf_server_tool_intent = bool(_sf_tools_on or _explicit_studio_tool_loop_requested(payload))_sf_template_tools = payload.tools if payload.tool_choice != "none" else Noneif not _sf_template_tools and _sf_server_tool_intent:_sf_template_tools = ({},)@@ -13872,13 +13932,8 @@ async def openai_chat_completions(payload.max_tool_calls_per_message if payload.max_tool_calls_per_message is not None else 25)- # Match the GGUF path: mcp_enabled also opens the tool loop on its own- # but must still honor a CLI `--disable-tools` policy.- from state.tool_policy import get_tool_policy as _get_tool_policy_sf-- _sf_cli_policy = _get_tool_policy_sf()- _sf_tools_on = _effective_enable_tools(payload)- _sf_mcp_allowed = bool(payload.mcp_enabled) and _sf_cli_policy is not False+ # _sf_cli_policy / _sf_tools_on / _sf_mcp_allowed are resolved above, before+ # the response protocol is classified, so both use the same decision._sf_use_tools = ((_sf_tools_on or _sf_mcp_allowed)and _sf_features.get("supports_tools", False)@@ -14352,7 +14407,10 @@ async def openai_chat_completions(# Gate on _sf_use_tools (did the server-side path claim the request?), not# raw mcp_enabled: an empty MCP registry must not silently drop client tools._sf_client_tools = (- not _effective_enable_tools(payload)+ # Read the resolved value, not a fresh _effective_enable_tools: the gate+ # above withdraws the launcher default for exactly these requests, and+ # recomputing here would hide that and drop the client catalog.+ not _sf_tools_onand not _sf_use_toolsand image is Noneand not _sf_is_gptossdiff --git a/studio/backend/run.py b/studio/backend/run.pyindex a04a1d7bc7d..90bb22a8211 100644--- a/studio/backend/run.py+++ b/studio/backend/run.py@@ -537,11 +537,15 @@ def _tool_policy_notice(host: str, secure: bool, enable_tools: "Optional[bool]")network-reachable launch is never silent about code execution."""if enable_tools is False:return "Server-side tools are DISABLED (--disable-tools)."- state = (- "ENABLED (--enable-tools)"- if enable_tools- else "ENABLED by default (per-request setting honored)"- )+ if enable_tools is None:+ # This launcher installs no tools-on default (that is `unsloth studio+ # run`), so the request decides and the Studio UI sends its pills.+ return (+ "Server-side tools follow each request's enable_tools; the Studio UI's "+ "tool toggles decide. Pass --enable-tools to force them on for every "+ "request."+ )+ state = "ENABLED (--enable-tools)"if secure:return (f"Server-side tools are {state}, reachable via the authenticated "@@ -2119,8 +2123,15 @@ def _apply_supplied_password(password_value: "Optional[str]") -> None:def _apply_cli_tool_policy(enable_tools: "Optional[bool]") -> None:"""Honor an explicit --enable-tools/--disable-tools; None leaves the policy- unset (tools default on, per-request enable_tools honored). Host is never- inspected here."""+ unset, so each request's own enable_tools decides. Host is never inspected+ here.++ The tools-on default for an omitted `enable_tools` belongs to `unsloth studio+ run`, which installs it itself (that is the launcher that has always forced+ tools on). Installing it here too would extend it to `unsloth studio`, the+ desktop app and Colab, where paths built around "omitted means off" -- n > 1,+ max_tool_calls_per_message: 0, the pre-switch passthrough guard -- would+ start seeing it."""if enable_tools is None:returnfrom state.tool_policy import set_tool_policy@@ -2201,7 +2212,7 @@ def run_server(bind. Tri-state: None (unset) and False both mean off; True enables it.--secure implies it (True) and rejects an explicit False.enable_tools: explicit --enable-tools/--disable-tools policy; None leaves- the default (tools on, per-request enable_tools honored)+ the default (tools on, a request's own enable_tools: false honored)emit_tauri_port: print the machine-readable TAURI_PORT line the desktopapp parses from stdout; the headless `run --api-only` path turns itoff so it does not pollute the documented URL/API-key banner@@ -2788,7 +2799,8 @@ def _build_arg_parser():default = argparse.SUPPRESS,help = argparse.SUPPRESS,)- # Tri-state tool policy: no flag -> None (tools on, per-request honored);+ # Tri-state tool policy: no flag -> None (tools default on, a request's own+ # enable_tools: false honored);# --enable-tools/--disable-tools force on/off.parser.add_argument("--enable-tools",@@ -2796,7 +2808,9 @@ def _build_arg_parser():action = "store_true",default = None,help = "Force server-side tools (web search, code execution) on for "- "every request. Default: on for every bind, per-request setting honored. "+ "every request. Default: no server-wide policy, so each request's own "+ "enable_tools decides (`unsloth studio run` is the launcher that defaults "+ "them on). ""/v1/messages takes the on direction per request (enable_tools) because it has ""no confirmation channel; the off direction still applies everywhere.",)diff --git a/studio/backend/state/tool_policy.py b/studio/backend/state/tool_policy.pyindex de770155e17..aa6cbac9fbd 100644--- a/studio/backend/state/tool_policy.py+++ b/studio/backend/state/tool_policy.py@@ -3,13 +3,27 @@"""Process-level server-side tool policy.-Set by `unsloth run` at startup; consulted by the inference route gates.+Two slots, both set at startup and consulted by the inference route gates.++The OVERRIDE (`set_tool_policy`) comes from an explicit `--enable-tools`/+`--disable-tools` and beats the request:None -> no CLI override (default). Per-request `enable_tools` is honored.True -> CLI forced tools on for every request. Not on /v1/messages: that channelcannot present a confirmation prompt, so it takes the on direction from therequest itself (see _anthropic_selects_server_tools).False -> CLI forced tools off for every request, /v1/messages included.++The DEFAULT (`set_tool_policy_default`) is what an omitted `enable_tools` falls+back to. `unsloth studio run` installs True for every bind, `--secure` included,+so a plain request to a tool-capable model can use tools. It is only a default:+a request that says `enable_tools: false` (what the Studio UI sends with its tool+pills off) turns them off, which the override deliberately would not.++No other launcher installs it. `unsloth studio`, the desktop app and Colab leave+it unset, so an omitted `enable_tools` still means no tools there, which is what+paths like `n > 1`, `max_tool_calls_per_message: 0` and the pre-switch+passthrough guard are built around."""import contextvars@@ -17,6 +31,7 @@ from contextlib import contextmanagerfrom typing import Iterator, Optional_tool_policy: Optional[bool] = None+_tool_policy_default: Optional[bool] = None# Per-request hard-off so public surfaces refuse tools even under a CLI `--enable-tools`._force_disabled: contextvars.ContextVar[bool] = contextvars.ContextVar(@@ -30,6 +45,15 @@ def get_tool_policy() -> Optional[bool]:return _tool_policy+def get_tool_policy_default() -> Optional[bool]:+ """Fallback for a request that omits `enable_tools`; None unless `unsloth+ studio run` installed one (every other launcher, embedder and library caller+ keeps the omitted-is-off read)."""+ if _force_disabled.get():+ return False+ return _tool_policy_default++@contextmanagerdef tools_force_disabled() -> Iterator[None]:"""Hard-disable server-side tools for the current async context."""@@ -47,6 +71,14 @@ def set_tool_policy(value: Optional[bool]) -> None:_tool_policy = value+def set_tool_policy_default(value: Optional[bool]) -> None:+ if value is not None and not isinstance(value, bool):+ raise TypeError(f"tool_policy_default must be Optional[bool], got {type(value).__name__}")+ global _tool_policy_default+ _tool_policy_default = value++def reset_tool_policy() -> None:- global _tool_policy+ global _tool_policy, _tool_policy_default_tool_policy = None+ _tool_policy_default = Nonediff --git a/studio/backend/tests/test_secure_tunnel_gate.py b/studio/backend/tests/test_secure_tunnel_gate.pyindex 2852fc3f2dd..451913e531e 100644--- a/studio/backend/tests/test_secure_tunnel_gate.py+++ b/studio/backend/tests/test_secure_tunnel_gate.py@@ -148,15 +148,21 @@ def test_run_server_accepts_enable_tools_kwarg():def test_tool_policy_not_auto_disabled_by_bind():- # Tools default on for every bind; the backend only changes the policy from- # an explicit --enable-tools/--disable-tools, never from host/secure.+ # No flag installs neither an override nor a tools-on default on any bind: the+ # default belongs to `unsloth studio run`, which installs it itself. The+ # backend never changes the policy from host/secure.import run- from state.tool_policy import get_tool_policy, reset_tool_policy+ from state.tool_policy import (+ get_tool_policy,+ get_tool_policy_default,+ reset_tool_policy,+ )for host in ("127.0.0.1", "localhost", "0.0.0.0"):reset_tool_policy()run._apply_cli_tool_policy(None) # no flag, on any bind- assert get_tool_policy() is None, host # untouched: per-request honored+ assert get_tool_policy() is None, host # no override: request off honored+ assert get_tool_policy_default() is None, host # no default from this pathreset_tool_policy()run._apply_cli_tool_policy(True) # --enable-tools: forced on@@ -168,18 +174,29 @@ def test_tool_policy_not_auto_disabled_by_bind():reset_tool_policy()-def test_tool_policy_notice_wording():- # The plain-server startup banner states the resolved policy for every bind.+def test_apply_cli_tool_policy_is_idempotent():+ # Both the CLI and run_server() apply the pair; re-applying must not drift.import run+ from state.tool_policy import get_tool_policy, get_tool_policy_default, reset_tool_policy- loopback = run._tool_policy_notice("127.0.0.1", False, None)- assert "ENABLED by default" in loopback and "loopback" in loopback+ for flag in (None, True, False):+ reset_tool_policy()+ run._apply_cli_tool_policy(flag)+ first = (get_tool_policy(), get_tool_policy_default())+ run._apply_cli_tool_policy(flag)+ assert (get_tool_policy(), get_tool_policy_default()) == first, flag+ reset_tool_policy()- network = run._tool_policy_notice("0.0.0.0", False, None)- assert "ENABLED by default" in network and "network-reachable" in network- secure = run._tool_policy_notice("127.0.0.1", True, None)- assert "Cloudflare HTTPS tunnel" in secure+def test_tool_policy_notice_wording():+ # The plain-server startup banner states the resolved policy for every bind.+ import run++ # No flag on this launcher: no tools-on default, so the request decides.+ for host, secure_mode in (("127.0.0.1", False), ("0.0.0.0", False), ("127.0.0.1", True)):+ notice = run._tool_policy_notice(host, secure_mode, None)+ assert "follow each request's enable_tools" in notice, notice+ assert "--enable-tools to force them on" in notice, noticeassert run._tool_policy_notice("0.0.0.0", False, False) == ("Server-side tools are DISABLED (--disable-tools)."@@ -198,7 +215,7 @@ def test_startup_output_emits_tool_notice_on_network_bind(capsys, monkeypatch):run._emit_startup_output("0.0.0.0", 8000, "0.0.0.0", secure = False, enable_tools = None)out = capsys.readouterr().outassert "Server-side tools" in out- assert "network-reachable" in out+ assert "follow each request's enable_tools" in outdef test_startup_output_emits_disabled_notice(capsys, monkeypatch):diff --git a/studio/backend/tests/test_tool_policy_gates.py b/studio/backend/tests/test_tool_policy_gates.pyindex fad121a4a10..5329ac8b3e6 100644--- a/studio/backend/tests/test_tool_policy_gates.py+++ b/studio/backend/tests/test_tool_policy_gates.py@@ -5,12 +5,14 @@Tests for `_effective_enable_tools` -- folds the process-level `tool_policy`over a request's `enable_tools` field.-Truth table (policy x payload.enable_tools -> effective):- policy=None + payload=None -> None- policy=None + payload=True -> True- policy=None + payload=False -> False- policy=True + payload=* -> True- policy=False + payload=* -> False+Truth table (override x default x payload.enable_tools -> effective):+ override=None + default=None + payload=None -> None+ override=None + default=True + payload=None -> True (launcher default)+ override=None + default=True + payload=False -> False (request opts out)+ override=None + payload=True -> True+ override=None + payload=False -> False+ override=True + payload=* -> True (--enable-tools)+ override=False + payload=* -> False (--disable-tools)"""import os@@ -22,8 +24,12 @@ sys.path.insert(0, _backend)import pytest-from routes.inference import _effective_enable_tools-from state.tool_policy import reset_tool_policy, set_tool_policy+from routes.inference import (+ _effective_enable_tools,+ _request_states_tool_intent,+ _tools_on_by_launcher_default_only,+)+from state.tool_policy import reset_tool_policy, set_tool_policy, set_tool_policy_default@pytest.fixture(autouse = True)@@ -54,3 +60,152 @@ class TestEffectiveEnableTools:def test_policy_false_overrides_any_payload(self, payload_value):set_tool_policy(False)assert _effective_enable_tools(_payload(payload_value)) is False+++class TestLauncherDefault:+ """`unsloth studio [run]` installs a tools-on default (not an override), so a+ request that never mentions tools gets them and one that says false does not."""++ def test_omitted_falls_back_to_default(self):+ set_tool_policy_default(True)+ assert _effective_enable_tools(_payload(None)) is True++ def test_explicit_false_beats_default(self):+ set_tool_policy_default(True)+ assert _effective_enable_tools(_payload(False)) is False++ def test_explicit_true_matches_default(self):+ set_tool_policy_default(True)+ assert _effective_enable_tools(_payload(True)) is True++ @pytest.mark.parametrize("payload_value", [None, True, False])+ def test_disable_tools_override_beats_default(self, payload_value):+ set_tool_policy_default(True)+ set_tool_policy(False)+ assert _effective_enable_tools(_payload(payload_value)) is False++ @pytest.mark.parametrize("payload_value", [None, True, False])+ def test_enable_tools_override_beats_default(self, payload_value):+ set_tool_policy_default(True)+ set_tool_policy(True)+ assert _effective_enable_tools(_payload(payload_value)) is True++ def test_force_disabled_context_beats_default(self):+ from state.tool_policy import tools_force_disabled+ set_tool_policy_default(True)+ with tools_force_disabled():+ assert _effective_enable_tools(_payload(None)) is False+++def _msg(role = "user", tool_calls = None):+ return SimpleNamespace(role = role, tool_calls = tool_calls, content = "hi")+++def _req(**kw):+ fields = dict(+ enable_tools = None,+ mcp_enabled = None,+ tool_choice = None,+ tools = None,+ messages = [_msg()],+ model_extra = {},+ )+ fields.update(kw)+ return SimpleNamespace(**fields)+++def _sf_tools_on(payload):+ """The safetensors gate's resolution, as routes.inference applies it."""+ on = _effective_enable_tools(payload)+ if on and _tools_on_by_launcher_default_only(payload) and _request_states_tool_intent(payload):+ on = False+ return on+++class TestRequestStatesToolIntent:+ """A request that uses the standard OpenAI tool fields has stated its intent,+ so the launcher default must not answer for it."""++ def test_plain_chat_states_nothing(self):+ assert _request_states_tool_intent(_req()) is False++ def test_tool_choice_none_is_a_withdrawal(self):+ assert _request_states_tool_intent(_req(tool_choice = "none")) is True++ def test_client_catalog_is_intent(self):+ assert _request_states_tool_intent(_req(tools = [{"function": {"name": "f"}}])) is True++ def test_tool_result_history_is_intent(self):+ assert _request_states_tool_intent(_req(messages = [_msg(role = "tool")])) is True+ assert _request_states_tool_intent(_req(messages = [_msg(tool_calls = [{}])])) is True++ def test_response_format_is_a_contract(self):+ # The tool loop would break structured output; the GGUF passthrough+ # already exempts these requests from the policy.+ payload = _req(model_extra = {"response_format": {"type": "json_object"}})+ assert _request_states_tool_intent(payload) is True++ def test_empty_tools_reads_as_omitted(self):+ # bool(payload.tools) is the GGUF router's own reading in+ # _takes_tool_passthrough; both paths treat [] like an absent catalog.+ assert _request_states_tool_intent(_req(tools = [])) is False+++class TestLauncherDefaultOnly:+ def test_true_when_nothing_asked_and_no_override(self):+ set_tool_policy_default(True)+ assert _tools_on_by_launcher_default_only(_req()) is True++ @pytest.mark.parametrize("payload", [_req(enable_tools = True), _req(mcp_enabled = True)])+ def test_false_when_the_request_asked(self, payload):+ set_tool_policy_default(True)+ assert _tools_on_by_launcher_default_only(payload) is False++ @pytest.mark.parametrize("override", [True, False])+ def test_false_under_a_cli_override(self, override):+ set_tool_policy_default(True)+ set_tool_policy(override)+ assert _tools_on_by_launcher_default_only(_req()) is False+++class TestSafetensorsGateHonorsStatedIntent:+ """The safetensors path has no llama-server passthrough to fall back on, so+ the launcher default must not withdraw tool_choice: "none" or take a client+ catalog into Unsloth's own loop."""++ def test_plain_chat_still_gets_the_default(self):+ set_tool_policy_default(True)+ assert _sf_tools_on(_req()) is True++ def test_tool_choice_none_is_honored(self):+ set_tool_policy_default(True)+ assert _sf_tools_on(_req(tool_choice = "none")) is False++ def test_client_catalog_keeps_the_passthrough(self):+ set_tool_policy_default(True)+ assert _sf_tools_on(_req(tools = [{"function": {"name": "f"}}])) is False++ def test_tool_result_history_keeps_the_passthrough(self):+ set_tool_policy_default(True)+ assert _sf_tools_on(_req(messages = [_msg(role = "tool")])) is False++ def test_response_format_keeps_structured_output(self):+ set_tool_policy_default(True)+ payload = _req(model_extra = {"response_format": {"type": "json_object"}})+ assert _sf_tools_on(payload) is False++ def test_explicit_ask_still_claims_a_catalog(self):+ set_tool_policy_default(True)+ payload = _req(enable_tools = True, tools = [{"function": {"name": "f"}}])+ assert _sf_tools_on(payload) is True++ def test_cli_enable_tools_is_unchanged(self):+ # Pre-existing --enable-tools behavior on this path is untouched.+ set_tool_policy_default(True)+ set_tool_policy(True)+ assert _sf_tools_on(_req(tools = [{"function": {"name": "f"}}])) is True++ def test_cli_disable_tools_still_wins(self):+ set_tool_policy_default(True)+ set_tool_policy(False)+ assert _sf_tools_on(_req()) is Falsediff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 7275100838b..9f486e98cc1 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -1675,7 +1675,9 @@ export async function buildLocalTokenCountExtras(!mcpEnabledForChat &&!ragOn) {- return {};+ // Explicit false, not an omitted field: the server defaults tools on for a+ // request that never mentions them, so every pill being off has to say so.+ return { enable_tools: false };}return {@@ -5091,7 +5093,10 @@ export function createOpenAIStreamAdapter(: []),],}- : {}),+ : // Explicit false: an omitted field falls back to the+ // server's tools-on default, which would bill provider+ // server tools.+ { enable_tools: false }),provider_id: externalProvider.id,provider_type: externalBackendProviderType,external_model: externalSelection.modelId,@@ -5271,7 +5276,10 @@ export function createOpenAIStreamAdapter(return mins >= 9999 ? 9999 : mins * 60;})(),}- : {}),+ : // Explicit false, not an omitted field: the server defaults tools+ // on for a request that never mentions them, so a model with no+ // tool pill lit has to say so.+ { enable_tools: false }),};};diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex 0443bdf71f2..a07caa4f66a 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -567,6 +567,10 @@ async function generateTitleWithModel(payload: {repetition_penalty: 1.0,enable_thinking: false,reasoning_effort: "none",+ // Titling is a one-shot summarisation: never let it enter the tool loop.+ // Omitting the field would inherit the server's tools-on default and put+ // python/terminal schemas in a 24-token prompt.+ enable_tools: false,messages: [{role: "system",diff --git a/tests/python/test_unsloth_run_tool_policy_resolver.py b/tests/python/test_unsloth_run_tool_policy_resolver.pyindex 2f13a17b693..11772cc739c 100644--- a/tests/python/test_unsloth_run_tool_policy_resolver.py+++ b/tests/python/test_unsloth_run_tool_policy_resolver.py@@ -1,8 +1,10 @@# Copyright 2025-present the Unsloth AI Inc. team. All rights reserved.-"""Truth-table tests for `resolve_tool_policy`: tools default on for every bind-(loopback, --secure tunnel, raw network), explicit on/off wins, and the resolver-never prompts (yes/silent/prompt kept for compatibility)."""+"""Truth-table tests for `resolve_tool_policy`: no flag installs no process-wide+OVERRIDE on any bind (loopback, --secure tunnel, raw network), so a request's own+`enable_tools: false` is honored -- tools still default on for a request that+omits the field, via the backend's separate tool-policy default. Explicit on/off+wins, and the resolver never prompts (yes/silent/prompt kept for compatibility)."""import pytest@@ -24,9 +26,9 @@ class TestLocalhostHost:silent = False,prompt = _never_prompt,)- assert result is (True if flag in (None, True) else False)+ assert result is flag- def test_default_is_on(self):+ def test_default_is_unset(self):assert (resolve_tool_policy(host = "127.0.0.1",@@ -35,7 +37,7 @@ class TestLocalhostHost:silent = False,prompt = _never_prompt,)- is True+ is None)def test_explicit_off(self):@@ -52,8 +54,9 @@ class TestLocalhostHost:class TestZeroHost:- def test_default_is_on(self):- # Network bind defaults ON now (operator owns network security).+ def test_default_is_unset(self):+ # A network bind installs no override, so the Studio UI's tool pills (which+ # send enable_tools: false when all off) are honored rather than overridden.assert (resolve_tool_policy(host = "0.0.0.0",@@ -62,7 +65,7 @@ class TestZeroHost:silent = False,prompt = _never_prompt,)- is True+ is None)def test_explicit_off_no_prompt(self):@@ -99,7 +102,7 @@ class TestZeroHost:silent = True,prompt = _never_prompt,)- is True+ is None)@@ -116,9 +119,9 @@ class TestIsExternalHost:class TestSpecificNetworkIP:- """Binding to a specific LAN IP follows the same default-on rules as 0.0.0.0."""+ """Binding to a specific LAN IP follows the same rules as 0.0.0.0."""- def test_default_is_on(self):+ def test_default_is_unset(self):assert (resolve_tool_policy(host = "192.168.1.5",@@ -127,7 +130,7 @@ class TestSpecificNetworkIP:silent = False,prompt = _never_prompt,)- is True+ is None)def test_explicit_on_no_prompt(self):diff --git a/unsloth_cli/_tool_policy.py b/unsloth_cli/_tool_policy.pyindex 5d854c0837c..21f92f7bd6b 100644--- a/unsloth_cli/_tool_policy.py+++ b/unsloth_cli/_tool_policy.py@@ -27,9 +27,14 @@ def resolve_tool_policy(yes: bool,silent: bool,prompt: Callable[[str], bool] = typer.confirm,-) -> bool:- """Resolve the server-side tool policy. Tools default on for every bind;- an explicit --enable-tools/--disable-tools (`flag`) forces on/off. `host`,- `yes`, `silent`, `prompt` are kept for signature compatibility and no longer- affect the result (network binds no longer prompt)."""- return True if flag is None else flag+) -> Optional[bool]:+ """Resolve the process-wide server-side tool OVERRIDE.++ An explicit --enable-tools/--disable-tools (`flag`) forces tools on/off for+ every request. With no flag the result is None: tools still default on for+ every bind (the backend installs that default in `_apply_cli_tool_policy`),+ but as a default rather than an override, so a request's own+ `enable_tools: false` is honored -- which is what the Studio UI sends with+ its tool pills off. `host`, `yes`, `silent`, `prompt` are kept for signature+ compatibility; no bind prompts."""+ return flagdiff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.pyindex 97500723397..5b6e983367c 100644--- a/unsloth_cli/commands/studio.py+++ b/unsloth_cli/commands/studio.py@@ -1571,9 +1571,11 @@ def studio_default(None,"--enable-tools/--disable-tools",help = "Force server-side tools (web search, code execution) on or off for "- "every request. Default: on for every bind, with the per-chat UI toggle honored. "- "/v1/messages takes the on direction per request (enable_tools) because it has no "- "confirmation channel; the off direction still applies everywhere.",+ "every request. Default: no server-wide policy, so the per-chat UI toggle "+ "(the request's own enable_tools) decides; `unsloth studio run` is the "+ "launcher that defaults them on. /v1/messages takes the on direction per "+ "request (enable_tools) because it has no confirmation channel; the off "+ "direction still applies everywhere.",),disable_dns_pinning: bool = typer.Option(False,@@ -2093,9 +2095,10 @@ def run(rich_help_panel = _RUN_PANEL_TOOLS,help = ("Force server-side tools (web search, code execution) on or off for "- "every request. Default: on for every bind. /v1/messages takes the on "- "direction per request (enable_tools) because it has no confirmation "- "channel; the off direction still applies everywhere."+ "every request. Default: on for every bind, with a request's own "+ "enable_tools: false (what the Studio UI sends) honored. /v1/messages "+ "takes the on direction per request (enable_tools) because it has no "+ "confirmation channel; the off direction still applies everywhere."),),disable_dns_pinning: bool = typer.Option(@@ -2380,9 +2383,11 @@ def run()host = "127.0.0.1"- # Tool policy no longer depends on the bind: tools default on everywhere- # (--secure is a loopback tunnel; the operator owns a raw bind). Resolve here- # so the re-exec'd child inherits a concrete decision.+ # Tool policy does not depend on the bind: tools default on everywhere+ # (--secure is a loopback tunnel; the operator owns a raw bind). With no flag+ # this stays None, so the default applies without becoming an override and a+ # request's own enable_tools: false is honored. Resolve here so the re-exec'd+ # child inherits the same decision.from unsloth_cli._tool_policy import is_external_host, resolve_tool_policyenable_tools = resolve_tool_policy(@@ -2500,10 +2505,11 @@ def run(args.append("--api-only")if silent:args.append("--silent")- # Forward the resolved tool policy so the child doesn't re-resolve.- if enable_tools:+ # Forward the resolved tool policy so the child doesn't re-resolve. None+ # forwards neither flag: the child then leaves the policy unset too.+ if enable_tools is True:args.append("--enable-tools")- else:+ elif enable_tools is False:args.append("--disable-tools")# Forward --yes only if the user passed it; resolution no longer prompts.if yes:@@ -2554,8 +2560,10 @@ def run(# Match the route handlers' import path: run.py adds studio/backend/ to# sys.path, so they import as `state.tool_policy`. Set this before# run_server() starts uvicorn; once sockets are bound, routes can be hit.- from state.tool_policy import set_tool_policy+ # run_server() applies the same pair; both calls are idempotent.+ from state.tool_policy import set_tool_policy, set_tool_policy_default+ set_tool_policy_default(True)set_tool_policy(enable_tools)run_kwargs = dict(@@ -2643,7 +2651,7 @@ def run(# --silent / --yes too so the policy is never invisible._tool_notice_fg = (217, 119, 87)_is_external = is_external_host(host)- if not enable_tools:+ if enable_tools is False:_tool_notice = "Server-side tools are DISABLED (--disable-tools)."elif secure:_tool_notice = (diff --git a/unsloth_cli/tests/conftest.py b/unsloth_cli/tests/conftest.pyindex 2f823be432d..92c3a2f2c15 100644--- a/unsloth_cli/tests/conftest.py+++ b/unsloth_cli/tests/conftest.py@@ -38,6 +38,7 @@ def stub_tool_policy_state(monkeypatch):state_mod = types.ModuleType("state")tp_mod = types.ModuleType("state.tool_policy")tp_mod.set_tool_policy = lambda *a, **k: None+ tp_mod.set_tool_policy_default = lambda *a, **k: Nonestate_mod.tool_policy = tp_modmonkeypatch.setitem(sys.modules, "state", state_mod)monkeypatch.setitem(sys.modules, "state.tool_policy", tp_mod)diff --git a/unsloth_cli/tests/test_studio_cloudflare_flag.py b/unsloth_cli/tests/test_studio_cloudflare_flag.pyindex d242f326dee..4d51b3d44b0 100644--- a/unsloth_cli/tests/test_studio_cloudflare_flag.py+++ b/unsloth_cli/tests/test_studio_cloudflare_flag.py@@ -252,6 +252,7 @@ def test_run_in_venv_passes_cloudflare_to_run_server(monkeypatch, user_flag, expstate_mod = types.ModuleType("state")tp_mod = types.ModuleType("state.tool_policy")tp_mod.set_tool_policy = lambda *a, **k: None+ tp_mod.set_tool_policy_default = lambda *a, **k: Nonestate_mod.tool_policy = tp_modmonkeypatch.setitem(sys.modules, "state", state_mod)monkeypatch.setitem(sys.modules, "state.tool_policy", tp_mod)@@ -354,6 +355,7 @@ def test_run_silent_emits_cloudflare_notice_for_external_bind(monkeypatch):state_mod = types.ModuleType("state")tp_mod = types.ModuleType("state.tool_policy")tp_mod.set_tool_policy = lambda *a, **k: None+ tp_mod.set_tool_policy_default = lambda *a, **k: Nonestate_mod.tool_policy = tp_modmonkeypatch.setitem(sys.modules, "state", state_mod)monkeypatch.setitem(sys.modules, "state.tool_policy", tp_mod)@@ -439,6 +441,7 @@ def test_run_in_venv_shuts_down_on_startup_abort(monkeypatch):state_mod = sys.modules.setdefault("state", types.ModuleType("state"))tp_mod = sys.modules.setdefault("state.tool_policy", types.ModuleType("state.tool_policy"))tp_mod.set_tool_policy = lambda *a, **k: None+ tp_mod.set_tool_policy_default = lambda *a, **k: Nonestate_mod.tool_policy = tp_mod# Force the health check to fail so startup aborts after run_server().@@ -494,6 +497,7 @@ def test_run_in_venv_sets_tool_policy_before_server_start(monkeypatch):state_mod = types.ModuleType("state")tp_mod = types.ModuleType("state.tool_policy")tp_mod.set_tool_policy = lambda value: calls.append(("policy", value))+ tp_mod.set_tool_policy_default = lambda value: calls.append(("policy_default", value))state_mod.tool_policy = tp_modmonkeypatch.setitem(sys.modules, "state", state_mod)monkeypatch.setitem(sys.modules, "state.tool_policy", tp_mod)@@ -509,4 +513,5 @@ def test_run_in_venv_sets_tool_policy_before_server_start(monkeypatch):result = CliRunner().invoke(app, _BASE + ["--disable-tools"], catch_exceptions = True)assert result.exit_code == 1, result.output- assert calls[:2] == [("policy", False), ("run_server", None)]+ # Default first, then the explicit override, both before the server starts.+ assert calls[:3] == [("policy_default", True), ("policy", False), ("run_server", None)]diff --git a/unsloth_cli/tests/test_studio_secure_flag.py b/unsloth_cli/tests/test_studio_secure_flag.pyindex 118f2279498..70f579a9bf5 100644--- a/unsloth_cli/tests/test_studio_secure_flag.py+++ b/unsloth_cli/tests/test_studio_secure_flag.py@@ -327,12 +327,13 @@ def test_studio_default_rejects_secure_with_subcommand():assert "--secure" in combined, combined-# ── secure resolves tools against the loopback bind (tools stay ON) ──+# ── secure resolves tools against the loopback bind (no flag -> no override) ──def test_run_secure_resolves_tools_against_loopback(monkeypatch):# --secure is a loopback bind behind an authenticated tunnel, so tools resolve- # against 127.0.0.1 (ON): the child gets --enable-tools, not --disable-tools.+ # against 127.0.0.1. With no flag the resolver returns None, and the child gets+ # neither --enable-tools nor --disable-tools (per-request enable_tools decides).studio_mod = _studio()monkeypatch.setattr(sys, "prefix", "/nonexistent/outer/venv")fake_venv = Path("/fake/studio/venv/unsloth_studio")@@ -357,7 +358,7 @@ def test_run_secure_resolves_tools_against_loopback(monkeypatch):def rec(host, flag, yes, silent):calls.append(host)- return True if flag is None else bool(flag) # default ON everywhere+ return flag # no flag -> None -> no process-wide overridemonkeypatch.setattr(_tp_mod, "resolve_tool_policy", rec)@@ -380,7 +381,8 @@ def test_run_secure_resolves_tools_against_loopback(monkeypatch):# Resolved against the forced-loopback bind, not the public 0.0.0.0 exposure.assert calls and calls[0] == "127.0.0.1", callsassert len(captured) == 1, captured- assert "--enable-tools" in captured[0] and "--disable-tools" not in captured[0], captured[0]+ assert "--enable-tools" not in captured[0], captured[0]+ assert "--disable-tools" not in captured[0], captured[0]def test_run_secure_enable_tools_no_auto_yes(monkeypatch):@@ -437,12 +439,13 @@ def test_studio_default_rejects_enable_tools_with_subcommand():def test_run_tool_help_reflects_default_on_everywhere():- # Help must match the new policy (tools on everywhere, no prompt).+ # Help must match the policy (tools on by default everywhere, no prompt).import inspectparams = inspect.signature(_studio().run).parameterstools_help = params["enable_tools"].default.help or ""assert "on for every bind" in tools_help, tools_help+ assert "enable_tools: false" in tools_help, tools_helpassert "0.0.0.0" not in tools_help, tools_helpyes_help = params["yes"].default.help or ""