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: MCP agents upload datasets, load what they trained, and download models ahead of time (#14107)
Etherl21f02a8da7d0
diff --git a/studio/MCP.md b/studio/MCP.mdindex d6c71f0d79e..7f3a855a0de 100644--- a/studio/MCP.md+++ b/studio/MCP.md@@ -279,6 +279,7 @@ api_key_format = "Bearer {token}"| `load_model` | Load a chat, image, video or speech-to-text model, downloading it first if needed. Reports progress, waits up to `wait_s` (240 s by default) and lists what it unloaded. || `unload_model` | Unload a model, or every chat, speech, image, video and speech-to-text model with `kind="all"`. The embedding model stays. || `plan_load` | Preview a load without loading anything: GGUF variants and sizes, bytes to download, and the models it would unload. |+| `download_model` | Download a model ahead of time without loading it. Follow it with `get_job`; `load_model` waits for it. || `chat` | Ask the loaded model, with optional images, thinking controls and a `response_format`. Reports progress and returns a `cancel_id`. || `embed` | Embed up to 2048 texts, or rank them against a `query` and return the `top_k` best matches. || `system_one` | Ask the Decision API typed questions. The Decision API must be on. |@@ -291,8 +292,8 @@ api_key_format = "Bearer {token}"| `list_media` | Earlier images, audio clips, videos, transcripts and saved voices, a page at a time. || `voices` | List, save, rename and delete saved voices. || `run_recipe` | Validate, preview or run a Data Recipe. |-| `datasets` | List, check, download and follow training datasets. |-| `start_training` | Start LLM or image LoRA training. Follow it with `studio_status`. |+| `datasets` | List, check, upload, download and follow training datasets, and upload image datasets for image LoRA training. |+| `start_training` | Start LLM, text-to-speech or image LoRA training. Follow it with `get_job`. || `list_training_runs` | Past runs and their checkpoints, by name. || `export_model` | Export a checkpoint to GGUF, merged weights, a LoRA adapter or the base model. || `cancel` | Stop running work of a given kind; the kinds are listed in the tool's schema. |@@ -371,7 +372,5 @@ for the job.unload route does not resolve it. Unload it in the Unsloth Studio UI.- Unsloth Studio runs one Data Recipe job at a time, and a recipe job id is not tied toan account. Anyone with a key who knows the id can read that job's status.-- Image LoRA training takes a dataset that is already in Unsloth Studio. There is no- upload tool.- Models can be unloaded between calls when an idle timeout is set. Tools thensay to load the model again.diff --git a/studio/backend/studio_mcp/forward.py b/studio/backend/studio_mcp/forward.pyindex a918a65454b..3df6a688a68 100644--- a/studio/backend/studio_mcp/forward.py+++ b/studio/backend/studio_mcp/forward.py@@ -29,6 +29,7 @@ ALLOWED_PREFIXES = ("/api/export/","/api/data-recipe/","/api/hub/datasets/",+ "/api/hub/download","/api/hub/gguf-variants",# Read only: load_model and plan_load check whether Unsloth Studio is still downloading a variant."/api/hub/download-status",diff --git a/studio/backend/studio_mcp/loading.py b/studio/backend/studio_mcp/loading.pyindex 7de58a55a7d..bda68236759 100644--- a/studio/backend/studio_mcp/loading.py+++ b/studio/backend/studio_mcp/loading.py@@ -127,7 +127,7 @@ def _same(left: Optional[str], right: Optional[str]) -> bool:def _repo(name: str) -> str:# A GGUF is listed as repo:variant in one place and the bare repo in another. A local path- # (C:\models\a.gguf) has a drive letter there, not a variant; a ref:<digest> handle is one local model.+ # (C:\models\a.gguf) has a drive letter there, not a variant, and a ref: handle is one opaque id.if name.startswith("ref:"):return namehead, sep, tail = name.partition(":")@@ -240,6 +240,17 @@ async def start_load():return await _watch_llm(caller, slot, model, before, job)# K16, after the attach: M5 waits on a download of the same model here, then M7 refuses a partial one.+ from studio_mcp import model_downloads++ # Inside the job, so the wait outlives wait_s: the load starts once the download ends.+ await model_downloads.wait_for_managed(+ caller,+ job,+ model = model,+ kind = slot,+ variant = variant,+ budget_s = model_downloads.MAX_LOAD_WAIT_S,+ )await place.refuse_partial_variant(caller, model, slot, variant)return await run(job, before)@@ -341,7 +352,7 @@ def _llm_poll(caller: Caller, model: str) -> Callable[[], Awaitable[Progress]]:fraction = number(loading.get("fraction")) if isinstance(loading, dict) else Noneif fraction and opt_text(loading.get("phase")):return min(fraction, 1.0), f"Loading into memory ({loading['phase']})"- if model.startswith(("/", "\\")) or ":" in model[:3]:+ if model.startswith(("/", "\\", "ref:")) or ":" in model[:3]:return Nonedownload = await route_json("GET",diff --git a/studio/backend/studio_mcp/model_downloads.py b/studio/backend/studio_mcp/model_downloads.pynew file mode 100644index 00000000000..9cd036953c8--- /dev/null+++ b/studio/backend/studio_mcp/model_downloads.py@@ -0,0 +1,429 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Download models ahead of time through Unsloth Studio's download manager, follow and stop those downloads, and wait for one before a load."""++from __future__ import annotations++import asyncio+import dataclasses+import time+from collections import OrderedDict+from typing import Any, Optional++from fastmcp import Context+from fastmcp.exceptions import ToolError++from studio_mcp import loading+from studio_mcp import placement as place+from studio_mcp.caller import Caller+from studio_mcp.errors import raise_for_route, tool_error+from studio_mcp.forward import forward+from studio_mcp.outputs import DownloadRef, JobStatus+from studio_mcp.tools import as_dict, number, opt_text, route_json, strings, try_json++START = "/api/hub/download"+STATUS = "/api/hub/download-status"+PROGRESS = "/api/hub/download-progress"+CANCEL = "/api/hub/download/cancel"+SCOPED = "@diffusion"+AUDIO_SCOPED = "@audio"+# Native text-to-speech plans add the companion codec repos the load reads; the Audio page stages them the same way.+AUDIO_PLAN = "/api/inference/audio/download-plan"+MAX_PARTS = 16+WAIT_INTERVAL_S = 2.0+ACTIVE = ("running", "cancelling")+# Worst first: one failed part fails the whole download.+PRECEDENCE = ("failed", "cancelling", "running", "cancelled", "idle", "completed")+STATES = {"complete": "completed", "error": "failed"}+WAITING = "Waiting for Unsloth Studio's download"+# How long a load job waits on a download before it fails and names the download to follow.+MAX_LOAD_WAIT_S = 3600.0+READ_TIMEOUT_S = 30.0++Part = tuple[str, Optional[str]]++# (account, kind, model) -> parts of the last download_model, so a load waits on the files it staged.+_remembered: "OrderedDict[tuple[str, str, str], list[Part]]" = OrderedDict()+_REMEMBER_MAX = 256+++def _key(caller: Caller, kind: str, model: str) -> tuple[str, str, str]:+ # tts and audio load the same native speech repos, so a prefetch under either serves both.+ return (caller.account_id, "tts" if kind == "audio" else kind, model.lower())+++def _remember(caller: Caller, kind: str, model: str, parts: list[Part]) -> None:+ key = _key(caller, kind, model)+ # Prefetches with other options stage other files; a load waits on all of them, newest last.+ merged = [part for part in _remembered.get(key, []) if part not in parts] + parts+ _remembered[key] = merged[-MAX_PARTS:]+ _remembered.move_to_end(key)+ while len(_remembered) > _REMEMBER_MAX:+ _remembered.popitem(last = False)+++def format_id(parts: list[Part], generations: Optional[list[Optional[int]]] = None) -> str:+ """``repo[::variant][#generation]`` per part; the generation scopes a cancel to the run download_model started."""+ pieces = []+ for index, (repo, variant) in enumerate(parts):+ piece = repo if variant is None else f"{repo}::{variant}"+ generation = generations[index] if generations else None+ pieces.append(piece if generation is None else f"{piece}#{generation}")+ return ",".join(pieces)+++def _parse(download_id: str) -> list[tuple[Part, Optional[int]]]:+ pieces = [p.strip() for p in str(download_id or "").split(",")]+ if len(pieces) > MAX_PARTS:+ raise ToolError(f"A download id names at most {MAX_PARTS} downloads")+ parsed: list[tuple[Part, Optional[int]]] = []+ for piece in pieces:+ head, _hash, tail = piece.rpartition("#")+ generation = int(tail) if head and tail.strip().isdigit() else None+ repo, _sep, variant = (head if generation is not None else piece).partition("::")+ if not repo.strip():+ raise ToolError("Pass the id download_model returned")+ parsed.append(((repo.strip(), variant.strip() or None), generation))+ return parsed+++def parse_id(download_id: str) -> list[Part]:+ return [part for part, _generation in _parse(download_id)]+++def _state(answer: Any) -> str:+ state = opt_text(as_dict(answer).get("state")) or "idle"+ return STATES.get(state, state)+++def _worst(states: list[str]) -> str:+ ranked = [s for s in PRECEDENCE if s in states]+ return ranked[0] if ranked else (states[0] if states else "idle")+++def _looks_local(model: str) -> bool:+ # A host path, or the ref: handle a checkpoint or export load sends.+ return model.startswith(("/", "\\", ".", "ref:")) or ":" in model[:3]+++def _split(model: str, variant: Optional[str]) -> tuple[str, Optional[str]]:+ """``repo:variant`` shorthand, as load_model reads it, into the repo and the variant."""+ if variant is None and ":" in model and not _looks_local(model):+ model, _sep, variant = model.partition(":")+ return model, variant or None+++async def _default_variant(+ caller: Caller,+ model: str,+ required: bool = True,+) -> Optional[str]:+ """The repo's recommended GGUF variant from its listing; None for a repo that lists none, unless ``required``."""+ try:+ listing = as_dict(+ await route_json(+ "GET",+ "/api/hub/gguf-variants",+ caller = caller,+ params = {"repo_id": model},+ hub_header = True,+ )+ )+ except ToolError:+ if required:+ raise+ return None+ quants = [+ q for q in (opt_text(as_dict(v).get("quant")) for v in listing.get("variants") or []) if q+ ]+ chosen = opt_text(listing.get("default_variant")) or (quants[0] if quants else None)+ if chosen is None and not required:+ return None+ if chosen is None:+ raise ToolError(+ f"Unsloth Studio found no GGUF variant of {model} to download. "+ f"Pass variant (one of: {', '.join(quants) or 'none listed'})."+ )+ return chosen+++def _native_audio(kind: str, model: str, variant: Optional[str]) -> bool:+ # GGUF and audio.cpp speech models download as a GGUF variant instead.+ return kind in ("tts", "audio") and variant is None and "gguf" not in model.lower()+++async def _plan_parts(+ caller: Caller,+ kind: str,+ model: str,+ variant: Optional[str],+ token: Optional[str],+ knobs: dict[str, str],+) -> list[tuple[str, list[str]]]:+ # The same plan body the load sends, so the files are the ones the load reads.+ body: dict[str, Any] = {"model_path": model}+ if token:+ body["hf_token"] = token+ if kind not in loading.MEDIA_ROUTES:+ route = AUDIO_PLAN+ else:+ route = loading.MEDIA_ROUTES[kind]["plan"]+ if variant or "gguf" in model.lower():+ entry = await loading._gguf_filename(caller, model, variant)+ if entry:+ body["gguf_filename"] = entry["filename"]+ body["model_kind"] = "gguf"+ plan = as_dict(await place.post_plan(caller, route, body, knobs))+ if opt_text(plan.get("incompatible_reason")):+ raise tool_error(plan["incompatible_reason"])+ if plan.get("plan_failed"):+ raise ToolError(+ f"Unsloth Studio could not list the files {model} needs, so it can't download them ahead of time. "+ "Call load_model, which downloads while it loads."+ )+ entries = [as_dict(e) for e in plan.get("entries") or []]+ return [+ (e["repo_id"], strings(e.get("files")))+ for e in entries+ if opt_text(e.get("repo_id")) and strings(e.get("files"))+ ]+++async def start(+ caller: Caller,+ ctx: Optional[Context],+ *,+ model: str,+ kind: str,+ variant: Optional[str],+ hf_token: Optional[str],+ knobs: Optional[dict[str, str]] = None,+) -> DownloadRef:+ if hf_token:+ caller = dataclasses.replace(caller, hf_token = hf_token)+ if kind == "stt":+ status = await loading.stt_status(caller, model)+ engine = loading.stt_engine(status, model)+ wanted = f"{model}:{variant}" if variant and ":" not in model else model+ if wanted not in strings(as_dict(status.get(engine)).get("downloaded_models")):+ await loading.download_stt(+ caller, ctx, model = model, engine = engine, hf_token = hf_token, variant = variant+ )+ return DownloadRef(model = model, kind = kind, variant = variant, status = "completed")++ model, variant = _split(model, variant)+ if variant is None and _native_audio(kind, model, variant):+ # A speech repo with GGUF variants downloads one of them, not every file through the audio plan.+ variant = await _default_variant(caller, model, required = False)+ if kind in loading.MEDIA_ROUTES or _native_audio(kind, model, variant):+ scope = SCOPED if kind in loading.MEDIA_ROUTES else AUDIO_SCOPED+ staged = await _plan_parts(caller, kind, model, variant, caller.hf_token, knobs or {})+ bodies = [+ {"repo_id": repo, "scope_id": scope[1:], "files": files, "transport_mode": "auto"}+ for repo, files in staged+ ]+ parts: list[Part] = [(repo, scope) for repo, _files in staged]+ else:+ if variant is None:+ # A GGUF repo is one the listing has variants for, whatever it is called.+ variant = await _default_variant(caller, model, required = "gguf" in model.lower())+ bodies = [{"repo_id": model, "transport_mode": "auto"}]+ if variant:+ bodies[0]["gguf_variant"] = variant+ parts = [(model, variant)]+ if not parts:+ # The plan lists nothing left to fetch.+ return DownloadRef(model = model, kind = kind, variant = variant, status = "completed")++ states, attached, generations = [], False, []+ started: list[tuple[Part, Optional[int]]] = []+ # Recorded first, so a load that starts meanwhile waits on every planned part.+ key = _key(caller, kind, model)+ before = set(_remembered.get(key, []))+ _remember(caller, kind, model, parts)+ try:+ for part, body in zip(parts, bodies):+ answer = as_dict(+ await route_json("POST", START, caller = caller, json_body = body, hub_header = True)+ )+ if answer.get("accepted") is False and answer.get("attached") is not True:+ raise ToolError(+ f"Unsloth Studio did not start downloading {body['repo_id']}: "+ f"another download of it is {opt_text(answer.get('state')) or 'in progress'}."+ )+ generation = answer.get("generation")+ generation = generation if isinstance(generation, int) else None+ if answer.get("attached") is not True:+ started.append((part, generation))+ attached = attached or answer.get("attached") is True+ states.append(_state(answer))+ generations.append(generation)+ except BaseException:+ # Stop the parts this call started, so a failed plan leaves nothing running without an id.+ # Only this call's own parts: an overlapping prefetch may have added its plan meanwhile.+ kept = [p for p in _remembered.get(key, []) if p in before or p not in parts]+ if kept:+ _remembered[key] = kept+ else:+ _remembered.pop(key, None)+ await _stop(caller, started)+ raise+ return DownloadRef(+ id = format_id(parts, generations),+ model = model,+ kind = kind,+ variant = variant,+ status = _worst(states),+ attached = attached,+ )+++async def _read(caller: Caller, part: Part) -> Optional[dict]:+ """One part's status; None when it is another account's job (404)."""+ repo, variant = part+ response = await forward(+ caller, "GET", STATUS, params = {"repo_id": repo, "gguf_variant": variant or ""}+ )+ if response.status_code == 404:+ return None+ return as_dict(raise_for_route(response))+++async def status(caller: Caller, download_id: str) -> JobStatus:+ parsed = _parse(download_id)+ parts = [part for part, _generation in parsed]+ answers, stale = [], None+ for part, generation in parsed:+ answer = await _read(caller, part)+ current = answer.get("generation") if answer is not None else None+ # Another run, newer or after a restart; a registry that pruned the run reads 0.+ if generation is not None and isinstance(current, int) and current not in (0, generation):+ # A newer run of the same repo replaced the one this id names: report that, not its state.+ stale = stale or (+ f"Unsloth Studio started a newer download of {part[0]} after this one; "+ f'follow it with get_job(kind="download", id="{format_id([part], [current])}").'+ )+ answer = None+ answers.append(answer)+ # A part that is not this account's reads as idle: there is nothing of yours to follow.+ states = [_state(a) if a is not None else "idle" for a in answers]+ error = stale or next(+ (opt_text(a.get("error")) for a in answers if a and opt_text(a.get("error"))), None+ )+ aggregate = _worst(states)+ percent = None+ if len(parts) == 1 and parts[0][1] is None and aggregate == "running":+ progress = await try_json(+ caller, PROGRESS, params = {"repo_id": parts[0][0]}, hub_header = True+ )+ fraction = number(as_dict(progress).get("progress"))+ percent = round(min(fraction, 1.0) * 100, 1) if fraction is not None else None+ single = parts[0][1] if len(parts) == 1 and not str(parts[0][1]).startswith("@") else None+ ref = DownloadRef(+ id = download_id, model = parts[0][0], variant = single, status = aggregate, error = error+ )+ return JobStatus(+ kind = "download",+ id = download_id,+ status = aggregate,+ progress_percent = percent,+ error = error,+ download = ref,+ )+++def _cancel_body(part: Part, generation: Optional[int]) -> dict[str, Any]:+ repo, variant = part+ body: dict[str, Any] = {"repo_id": repo}+ if variant:+ body["gguf_variant"] = variant+ if generation is not None:+ body["generation"] = generation+ return body+++async def _stop(caller: Caller, started: list[tuple[Part, Optional[int]]]) -> None:+ for part, generation in started:+ try:+ await forward(caller, "POST", CANCEL, json_body = _cancel_body(part, generation))+ except Exception:+ pass+++async def cancel_parts(caller: Caller, download_id: str) -> tuple[bool, Optional[str]]:+ """Stop every part; returns whether any was stopped and the overall state the answers report.+ A part that refuses (a load owns it) doesn't keep the others running: its error is raised after them."""+ states, refused = [], None+ for part, generation in _parse(download_id):+ response = await forward(caller, "POST", CANCEL, json_body = _cancel_body(part, generation))+ if response.status_code == 404:+ continue+ try:+ answer = raise_for_route(response)+ except ToolError as exc:+ refused = refused or exc+ continue+ states.append(opt_text(as_dict(answer).get("state")) or "idle")+ if refused is not None:+ raise refused+ return "cancelling" in states, (_worst([STATES.get(s, s) for s in states]) if states else None)+++def keys_for(caller: Caller, kind: str, model: str, variant: Optional[str]) -> list[Part]:+ """The manager jobs a load of ``model`` would read. A GGUF part with variant None still needs the repo's default."""+ if kind == "stt" or not model or _looks_local(model):+ return []+ if kind in loading.MEDIA_ROUTES:+ model = _split(model, variant)[0]+ remembered = _remembered.get(_key(caller, kind, model))+ return list(remembered or [(model, SCOPED)])+ model, variant = _split(model, variant)+ if _native_audio(kind, model, variant):+ # The plan's parts, codecs included; without a prefetch, the repo or the Audio page's staged download of it.+ remembered = _remembered.get(_key(caller, kind, model))+ return list(remembered or [(model, None), (model, AUDIO_SCOPED)])+ # A load without a variant reads the repo's default, not the variant download_model last staged.+ return [(model, variant)]+++async def wait_for_managed(+ caller: Caller,+ ctx: Optional[Context],+ *,+ model: str,+ kind: str,+ variant: Optional[str],+ budget_s: Optional[float],+) -> None:+ """Wait while Unsloth Studio's download manager is fetching ``model`` for this account. A read that fails proceeds."""+ keys = keys_for(caller, kind, model, variant)+ if len(keys) == 1 and keys[0][1] is None:+ try:+ default = await _default_variant(caller, keys[0][0], required = False)+ except Exception:+ return+ keys = [(keys[0][0], default)] if default else keys+ deadline = None if budget_s is None else time.monotonic() + max(budget_s, 0.0)+ while keys:+ active = []+ for part in keys:+ try:+ # A stalled read must not hold the load past its cap; an unreadable part is no wait.+ answer = await asyncio.wait_for(_read(caller, part), READ_TIMEOUT_S)+ except Exception:+ answer = None+ if answer is not None and opt_text(answer.get("state")) in ACTIVE:+ active.append(part)+ if not active:+ return+ left = None if deadline is None else deadline - time.monotonic()+ if left is not None and left <= 0:+ raise ToolError(+ f"Unsloth Studio is still downloading {model}. "+ f'Follow it with get_job(kind="download", id="{format_id(keys)}"), then call load_model again.'+ )+ if ctx is not None:+ follow = f'get_job(kind="download", id="{format_id(keys)}")'+ await ctx.report_progress(0.0, None, f"{WAITING}; follow it with {follow}")+ await asyncio.sleep(WAIT_INTERVAL_S if left is None else min(WAIT_INTERVAL_S, left))diff --git a/studio/backend/studio_mcp/outputs.py b/studio/backend/studio_mcp/outputs.pyindex 7e295a64b2e..ea89ade6e43 100644--- a/studio/backend/studio_mcp/outputs.py+++ b/studio/backend/studio_mcp/outputs.py@@ -634,6 +634,17 @@ class RecipeInfo(ToolOutput):data_rows: Optional[list[dict[str, Any]]] = None+class DownloadRef(ToolOutput):+ # What get_job(kind="download") and cancel(kind="model_download") take; None for a speech-to-text download.+ id: Optional[RouteText] = None+ model: Optional[RouteText] = None+ kind: Optional[RouteText] = None+ variant: Optional[RouteText] = None+ status: RouteText+ attached: bool = False+ error: Optional[RouteText] = None++class ExportInfo(ToolOutput):format: RouteText# Relative to Studio's exports folder, or only a name; never a host path.@@ -658,6 +669,7 @@ class JobStatus(ToolOutput):error_code: Optional[RouteText] = Nonevideo: Optional[VideoInfo] = Nonerecipe: Optional[RecipeInfo] = None+ download: Optional[DownloadRef] = Noneexport: Optional[ExportInfo] = Nonejobs: Optional[list[Union[ExportJobSummary, JobSummary]]] = None@@ -667,6 +679,8 @@ class LocalDataset(ToolOutput):label: RouteTextsource: RouteText = "local"rows: Optional[int] = None+ # What config.local_datasets takes for any account; ``id`` alone works for the owner only.+ ref: Optional[RouteText] = Noneclass CachedDataset(ToolOutput):@@ -691,11 +705,32 @@ class DatasetDownload(ToolOutput):error: Optional[RouteText] = None+class DatasetUpload(ToolOutput):+ id: RouteText+ filename: RouteText+ # The handle config.local_datasets takes; never the stored path.+ ref: RouteText+++class ImageDatasetUpload(ToolOutput):+ # What start_training kind "diffusion" takes as config.data_dir.+ name: RouteText+ image_count: Optional[int] = None+ caption_count: Optional[int] = None+ uploaded: Optional[int] = None++class DatasetsResult(ToolOutput):local: Optional[list[LocalDataset]] = Nonecached: Optional[list[CachedDataset]] = Noneformat: Optional[DatasetFormat] = Nonedownload: Optional[DatasetDownload] = None+ uploaded: Optional[DatasetUpload] = None+ image_dataset: Optional[ImageDatasetUpload] = None+++ConfigScalar = Union[StrictBool, StrictInt, StrictFloat, RouteText]+ConfigValue = Union[ConfigScalar, list[ConfigScalar], dict[str, ConfigScalar]]class TrainingStarted(ToolOutput):@@ -703,6 +738,8 @@ class TrainingStarted(ToolOutput):job_id: Optional[RouteText] = Nonestatus: RouteTextmessage: Optional[RouteText] = None+ # validate_only: the config as the route will read it, without paths or secrets.+ config: Optional[dict[str, ConfigValue]] = None# What cancel(kind="training_start") takes while the job has not begun.start_request_id: Optional[RouteText] = Nonediff --git a/studio/backend/studio_mcp/placement.py b/studio/backend/studio_mcp/placement.pyindex 2a57328465c..e69e080d894 100644--- a/studio/backend/studio_mcp/placement.py+++ b/studio/backend/studio_mcp/placement.py@@ -56,7 +56,7 @@ def media_knobs(kind: str, **knobs: Optional[str]) -> dict[str, str]:def is_local(model: str) -> bool:- # `ref:<digest>` is the handle an API-key caller gets for a local model: whole, never repo:variant.+ # A host path, or the ref:<digest> handle of a local model (API-key callers, checkpoint and export loads): whole, never repo:variant.return model.startswith(("/", "\\", ".", "~", "ref:")) or ":" in model[:3]@@ -101,6 +101,9 @@ async def listed_gguf(caller: Caller, model: str, variant: Optional[str]) -> Optrepo, variant = _split(model, variant)if repo.lower().startswith(AUDIO_CPP_PREFIX):return False+ if repo.startswith("ref:") and variant:+ # A trained GGUF export's handle carries its quantization; any other ref: the listing decides.+ return Trueif repo.lower().endswith(".gguf"):return Truelisting = await _variants(caller, repo)diff --git a/studio/backend/studio_mcp/tools/cancel.py b/studio/backend/studio_mcp/tools/cancel.pyindex eab7505b451..20484fedd05 100644--- a/studio/backend/studio_mcp/tools/cancel.py+++ b/studio/backend/studio_mcp/tools/cancel.py@@ -10,7 +10,7 @@ from urllib.parse import quotefrom fastmcp.exceptions import ToolError-from studio_mcp import export_jobs, job_store, video_queue+from studio_mcp import export_jobs, job_store, model_downloads, video_queuefrom studio_mcp.caller import current_callerfrom studio_mcp.outputs import CancelResultfrom studio_mcp.tools import DESTRUCTIVE, EXPORT_STATUS, as_dict, opt_text, route_json@@ -27,6 +27,7 @@ CancelKind = Literal["audio","chat","dataset_download",+ "model_download",]START_CANCELLED = "training_start_cancelled"NEEDS_ID = {@@ -35,6 +36,7 @@ NEEDS_ID = {"chat": "the chat's cancel_id","audio": "the run's cancel_id (generate_audio returns it)","dataset_download": "the dataset's repo_id",+ "model_download": "the id download_model returned",}# The route each other kind posts to, and the body field that carries its id (or ``save``), if any.ROUTES = {@@ -118,6 +120,7 @@ async def cancel("chat" stops the reply with cancel_id ``id``."audio" stops the generate_audio run whose cancel_id is ``id``; takes it already finished stay in Audio history."dataset_download" stops downloading the dataset ``id`` (its repo id).+ "model_download" stops the model download ``id`` that download_model returned; a speech-to-text download can't be stopped here.``cancelled`` says whether this call stopped something."""caller = current_caller()@@ -169,6 +172,11 @@ async def cancel(return done(True, "The export was stopped and its checkpoint unloaded.")elif kind == "video" and id and video_queue.is_queue_id(id):return done(*video_queue.cancel(caller.account_id, id))+ elif kind == "model_download":+ stopped, state = await model_downloads.cancel_parts(caller, id)+ if stopped:+ return done(True, "Unsloth Studio is stopping the download.")+ return done(False, f"Nothing to stop: the download is {state or 'not found'}.")else:path, id_field = ROUTES[kind]answer = await route_json(diff --git a/studio/backend/studio_mcp/tools/data.py b/studio/backend/studio_mcp/tools/data.pyindex fc93276290f..31f84b4fec6 100644--- a/studio/backend/studio_mcp/tools/data.py+++ b/studio/backend/studio_mcp/tools/data.py@@ -6,33 +6,103 @@from __future__ import annotationsimport dataclasses-from typing import Literal, Optional+import json+import secrets+from pathlib import PurePath+from typing import Annotated, Any, Literal, Optionalfrom fastmcp.exceptions import ToolError+from pydantic import Field-from studio_mcp.caller import current_caller+from studio_mcp.caller import Caller, current_caller+from studio_mcp.gate import MAX_REQUEST_BYTES+from studio_mcp.inputs import ImageInput, decode_base64, resolve_imagefrom studio_mcp.outputs import (CachedDataset,DatasetDownload,DatasetFormat,DatasetsResult,+ DatasetUpload,+ ImageDatasetUpload,LocalDataset,)-from studio_mcp.tools import WRITES, as_dict, opt_text, route_json+from studio_mcp.tools import WRITES, as_dict, leaf_name, opt_text, route_jsonHUB_DATASETS = "/api/hub/datasets"+# The training upload route's own list; anything else it answers with a 400.+UPLOAD_EXTS = (".csv", ".json", ".jsonl", ".parquet")+IMAGE_EXTS = {"image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp"}+# The caption route's limit, which sidecars sent with an upload would skip.+MAX_CAPTION_CHARS = 2000+# What one upload_images call holds in memory before it sends; the route's own limit can be gigabytes.+MAX_IMAGE_UPLOAD_BYTES = 64 * 1024 * 1024+++def _ref(path: Any) -> Optional[str]:+ from hub.utils.host_paths import cache_reference+ return cache_reference(path) if isinstance(path, str) and path else None+++def _upload_file(+ filename: Optional[str], data_base64: Optional[str], rows: Optional[list[dict[str, Any]]]+) -> tuple[str, bytes]:+ """The upload's file name and bytes, refused before any call the route would refuse."""+ if (data_base64 is None) == (rows is None):+ raise ToolError("upload needs exactly one of data_base64 (with filename) or rows.")+ if rows is not None:+ name = f"{PurePath(leaf_name(filename or '').strip()).stem or 'rows'}.jsonl"+ return name, "\n".join(json.dumps(row, ensure_ascii = False) for row in rows).encode()+ name = leaf_name(filename or "").strip()+ if not name:+ raise ToolError("upload with data_base64 needs filename, e.g. chats.jsonl.")+ ext = PurePath(name).suffix.lower()+ if ext not in UPLOAD_EXTS:+ raise ToolError(f"Unsupported file type: {ext or name}. Allowed: {', '.join(UPLOAD_EXTS)}")+ data = decode_base64(data_base64, MAX_REQUEST_BYTES, "data_base64")+ if not data:+ raise ToolError("data_base64 is empty.")+ return name, dataasync def datasets(- action: Literal["list", "check_format", "download", "status"],+ action: Literal["list", "check_format", "download", "status", "upload", "upload_images"],name: Optional[str] = None,repo_id: Optional[str] = None,is_vlm: bool = False,subset: Optional[str] = None,train_split: str = "train",hf_token: Optional[str] = None,+ filename: Annotated[+ Optional[str],+ Field(description = "upload: the file's name; its extension picks the format."),+ ] = None,+ data_base64: Annotated[+ Optional[str],+ Field(description = "upload: the file's bytes, base64; at most about 3 MiB."),+ ] = None,+ rows: Annotated[+ Optional[list[dict[str, Any]]],+ Field(min_length = 1, description = "upload: examples as JSON objects, saved as JSONL."),+ ] = None,+ images: Annotated[+ Optional[list[ImageInput]],+ Field(max_length = 64, description = "upload_images: PNG, JPEG or WebP images to add."),+ ] = None,+ captions: Annotated[+ Optional[list[str]],+ Field(description = "upload_images: one caption per image, in order; empty for none."),+ ] = None,) -> DatasetsResult:- """Training datasets. "list": datasets uploaded to Unsloth Studio and Hugging Face datasets already downloaded. "check_format" (``name``: a Hub repo id or a listed dataset): the detected format, columns and a suggested column mapping. "download" (``repo_id``): start downloading a Hub dataset; "status" (``repo_id``): how that download is going. ``hf_token`` is for gated datasets."""+ """Training datasets.+ "list": datasets uploaded to Unsloth Studio and Hugging Face datasets already downloaded.+ "check_format" (``name``: a Hub repo id or a listed dataset's id): the detected format, columns and a suggested column mapping.+ "download" (``repo_id``): start downloading a Hub dataset; "status" (``repo_id``): how that download is going.+ "upload": save a .csv, .json, .jsonl or .parquet file sent as ``data_base64`` with its ``filename``, or ``rows`` as JSONL.+ Put a listed or uploaded dataset's ``ref`` in start_training's config.local_datasets.+ "upload_images" (``name``, ``images``, optional ``captions``): add captioned images to the image dataset ``name``, creating it if needed.+ Pass that ``name`` as config.data_dir to start_training kind "diffusion".+ A ref lasts until Unsloth Studio restarts; after a restart, list or upload again for a new one.+ ``hf_token`` is for gated datasets."""caller = current_caller()if hf_token:caller = dataclasses.replace(caller, hf_token = hf_token)@@ -42,7 +112,10 @@ async def datasets(return DatasetsResult(local = [LocalDataset.from_route(- row, label = opt_text(row.get("label")) or row["id"], source = "local"+ row,+ label = opt_text(row.get("label")) or row["id"],+ source = "local",+ ref = _ref(row.get("path")),)for row in as_dict(local).get("datasets") or []if isinstance(row, dict) and opt_text(row.get("id"))@@ -53,6 +126,28 @@ async def datasets(if isinstance(row, dict) and opt_text(row.get("repo_id"))],)+ if action == "upload":+ upload_name, data = _upload_file(filename, data_base64, rows)+ saved = as_dict(+ await route_json(+ "POST",+ f"{HUB_DATASETS}/upload",+ caller = caller,+ files = {"file": (upload_name, data, "application/octet-stream")},+ )+ )+ stored = saved.get("stored_path")+ if not isinstance(stored, str) or not stored:+ raise ToolError("Unsloth Studio did not say where it saved the upload.")+ return DatasetsResult(+ uploaded = DatasetUpload(+ id = leaf_name(stored),+ filename = opt_text(saved.get("filename")) or upload_name,+ ref = _ref(stored),+ )+ )+ if action == "upload_images":+ return await _upload_images(caller, name, images or [], captions)if action == "check_format":if not name:raise ToolError(@@ -100,4 +195,45 @@ async def datasets()+async def _upload_images(+ caller: Caller, name: Optional[str], images: list[ImageInput], captions: Optional[list[str]]+) -> DatasetsResult:+ if not (name or "").strip() or not images:+ raise ToolError("upload_images needs name (the image dataset) and images.")+ if captions is not None and len(captions) != len(images):+ raise ToolError(f"captions has {len(captions)} entries for {len(images)} images.")+ if any(len(caption) > MAX_CAPTION_CHARS for caption in captions or []):+ raise ToolError(f"A caption is longer than {MAX_CAPTION_CHARS} characters.")+ from utils.upload_limits import get_upload_limit_bytes++ budget = min(MAX_IMAGE_UPLOAD_BYTES, get_upload_limit_bytes())+ # Fresh stems each call: a same-named file in a later upload would replace the earlier one.+ batch, files, total = secrets.token_hex(4), [], 0+ for i, image in enumerate(images):+ data, mime = await resolve_image(caller, image)+ # Stop before holding more than one call may send, captions included.+ total += len(data) + len(captions[i].encode() if captions else b"")+ if total > budget:+ raise ToolError(+ f"These images pass {budget // (1024 * 1024)} MB at image {i + 1}, more than one upload_images call takes. "+ "Send them in several calls with the same name; each one adds to the dataset."+ )+ stem = f"mcp-{batch}-{i:03d}"+ files.append(("files", (stem + IMAGE_EXTS[mime], data, mime)))+ if captions and captions[i].strip():+ files.append(("files", (f"{stem}.txt", captions[i].encode(), "text/plain")))+ saved = as_dict(+ await route_json(+ "POST",+ "/api/train/diffusion/dataset",+ caller = caller,+ data = {"name": name, "create_only": "false"},+ files = files,+ )+ )+ return DatasetsResult(+ image_dataset = ImageDatasetUpload.from_route(saved, name = opt_text(saved.get("name")) or name)+ )++TOOLS = ((datasets, WRITES),)diff --git a/studio/backend/studio_mcp/tools/jobs.py b/studio/backend/studio_mcp/tools/jobs.pyindex 9151f86864f..e1e9353b6d1 100644--- a/studio/backend/studio_mcp/tools/jobs.py+++ b/studio/backend/studio_mcp/tools/jobs.py@@ -16,7 +16,7 @@ from fastmcp.tools import ToolResultfrom pydantic import Fieldfrom studio_mcp import checkpoints as named-from studio_mcp import export_jobs, loading, video_queue+from studio_mcp import export_jobs, loading, model_downloads, video_queuefrom studio_mcp.caller import Caller, current_callerfrom studio_mcp.errors import raise_for_routefrom studio_mcp.forward import forward@@ -302,6 +302,10 @@ async def _read_once(return await _load_job(caller, job_id)if kind in ("training", "diffusion_training"):return await _training_job(caller, kind, job_id)+ if kind == "download":+ if not job_id:+ raise ToolError('get_job(kind="download") needs id: the id download_model returned.')+ return media_result([], await model_downloads.status(caller, job_id))if job_id is None:return await _video_jobs(caller)if video_queue.is_queue_id(job_id):@@ -330,7 +334,9 @@ def _moment(structured: Any) -> tuple[Any, Any, Any]:async def get_job(- kind: Literal["video", "recipe", "export", "training", "diffusion_training", "load"],+ kind: Literal[+ "video", "recipe", "export", "training", "diffusion_training", "load", "download"+ ],id: Optional[str] = None,wait_s: Annotated[int,@@ -365,7 +371,8 @@ async def get_job(Unsloth Studio runs one recipe at a time; a recipe job id is not tied to an account.kind "export": an export_model job by its id (without ``id``, this key's export jobs), with its output named relative to Unsloth Studio's exports folder.kind "training" or "diffusion_training": the current run started by start_training (``id`` is its job id), and once completed its run folder and checkpoint names; ``loss_history`` names the list_training_runs call with the full loss curve.- kind "load": a load_model call that returned ``status`` "loading", by its ``job_id``; once completed, ``load`` is the load's result with what it unloaded."""+ kind "load": a load_model call that returned ``status`` "loading", by its ``job_id``; once completed, ``load`` is the load's result with what it unloaded.+ kind "download": a download_model download by the id it returned."""caller = current_caller()deadline = time.monotonic() + min(wait_s, loading.MAX_WAIT_S)# Forwarded reads have no HTTP timeout, so each one here is bounded: the first by the wait (at@@ -427,6 +434,7 @@ POLL_AFTER_S = {"training": 30,"diffusion_training": 30,"load": 10,+ "download": 15,}diff --git a/studio/backend/studio_mcp/tools/models.py b/studio/backend/studio_mcp/tools/models.pyindex 212745a0212..2a0b646331e 100644--- a/studio/backend/studio_mcp/tools/models.py+++ b/studio/backend/studio_mcp/tools/models.py@@ -14,10 +14,11 @@ from fastmcp.exceptions import ToolErrorfrom fastmcp.tools import ToolResultfrom pydantic import Field-from studio_mcp import loading, placement+from studio_mcp import loading, model_downloads, placement, trained_modelsfrom studio_mcp.caller import current_callerfrom studio_mcp.media import media_resultfrom studio_mcp.outputs import (+ DownloadRef,HardwareSlot,LoadResult,ModelEntry,@@ -326,7 +327,25 @@ async def list_models(async def load_model(- model: str,+ model: Optional[str] = None,+ checkpoint: Annotated[+ Optional[str],+ Field(+ description = "Load a training checkpoint instead of model: a name from "+ 'list_training_runs(include_checkpoints=true), "<run folder>" or "<run folder>/checkpoint-N". '+ "It becomes the active model: chat with it by leaving chat's model unset."+ ),+ ] = None,+ export: Annotated[+ Optional[str],+ Field(+ description = "Load an export instead of model: its output name as export_model and "+ 'get_job(kind="export") report it, relative to Unsloth Studio\'s exports folder. A merged or '+ 'LoRA export is found when its save_directory has two levels, such as "<run>/<name>"; '+ "variant picks a GGUF export's quantization. "+ "It becomes the active model: chat with it by leaving chat's model unset."+ ),+ ] = None,kind: ModelKind = "llm",variant: Optional[str] = None,memory_mode: MemoryMode = None,@@ -364,6 +383,15 @@ async def load_model(Loading may unload other models to make room, for example a chat model to fit an image model; ``evicted`` lists them and ``evicted_slots`` gives each one's kind."""caller = current_caller()deadline = loading.deadline_after(wait_s)+ trained = await trained_models.resolve_by(+ deadline,+ caller,+ model = model,+ checkpoint = checkpoint,+ export = export,+ kind = kind,+ variant = variant,+ )knobs = placement.media_knobs(kind,memory_mode = memory_mode,@@ -378,6 +406,15 @@ async def load_model("kv_cache_type": kv_cache_type,"gpu_layers": gpu_layers,}+ if trained:+ # The export listing knows the type: a GGUF export is placed by its variant, not the Hub's listing.+ variant = trained.gguf_variant or variant+ if trained.unplaced_gguf and (device is not None or gpu_layers is not None):+ raise ToolError(+ f"Pass variant (the export's quantization, such as Q4_K_M) to load {trained.name} with device or gpu_layers."+ )+ if kind == "llm" and device == "cpu" and not trained.gguf_variant:+ raise ToolError(placement.CPU_NEEDS_GGUF)placement.check_placement(kind, **where)if kind == "stt":@@ -407,18 +444,26 @@ async def load_model(deadline = deadline,knobs = knobs,)- return await loading.load_llm(+ result = await loading.load_llm(caller,ctx,- model = model,+ model = trained.ref if trained else model,variant = variant,max_seq_length = max_seq_length,load_in_4bit = load_in_4bit,hf_token = hf_token,kind = kind,+ is_lora = trained.is_lora if trained else False,deadline = deadline,**where,)+ # The route echoes the minted ref; the agent gets the name it asked for.+ if not trained:+ trained_models.forget_load(caller, model)+ return result+ trained_models.remember_load(caller, trained)+ trained_models.rename_job(caller, result.job_id, trained)+ return trained.renamed(result)async def unload_model(kind: UnloadKind = "llm", model: Optional[str] = None) -> ToolResult:@@ -436,7 +481,13 @@ async def unload_model(kind: UnloadKind = "llm", model: Optional[str] = None) ->return media_result([], await loading.unload_stt(current_caller(), model))if kind in loading.MEDIA_ROUTES:return media_result([], await loading.unload_media(current_caller(), kind))- return media_result([], await loading.unload_llm(current_caller(), model, kind))+ caller = current_caller()+ # A checkpoint or export is resident under its ref: handle, not the name load_model reported.+ target = trained_models.loaded_ref(caller, model)+ result = await loading.unload_llm(caller, target, kind)+ if target != model:+ result = result.model_copy(update = {"model": model})+ return media_result([], result)def _unload_schema() -> dict[str, Any]:@@ -497,9 +548,48 @@ async def plan_load(raise ToolError(f"Unsloth Studio did not answer within {PLAN_S} s; try plan_load again.")+async def download_model(+ model: str,+ kind: ModelKind = "llm",+ variant: Optional[str] = None,+ hf_token: Optional[str] = None,+ memory_mode: MemoryMode = None,+ speed_mode: SpeedMode = None,+ transformer_quant: TransformerQuant = None,+ text_encoder_quant: TextEncoderQuant = None,+ h3_task: H3Task = None,+ ctx: Optional[Context] = None,+) -> DownloadRef:+ """Download a model ahead of time without loading it, so a later load_model starts sooner.+ The download keeps running in Unsloth Studio's download manager after this returns.+ ``kind`` is the kind load_model takes: "llm", "tts" and "audio" fetch the repo (for a GGUF repo only ``variant``, by default the recommended one), "image" and "video" the files their load reads, and "stt" a speech-to-text model.+ Follow it with get_job(kind="download", id=<the returned id>) and stop it with cancel(kind="model_download", id=<the same id>).+ A speech-to-text download finishes before this returns, so it has no id.+ load_model waits for a running download of the same model.+ ``hf_token`` is for gated repos. For image and video, pass the options the later load_model will take: they pick the files it reads, such as a pre-cast text encoder."""+ knobs = placement.media_knobs(+ kind,+ memory_mode = memory_mode,+ speed_mode = speed_mode,+ transformer_quant = transformer_quant,+ text_encoder_quant = text_encoder_quant,+ h3_task = h3_task,+ )+ return await model_downloads.start(+ current_caller(),+ ctx,+ model = model,+ kind = kind,+ variant = variant,+ hf_token = hf_token,+ knobs = knobs,+ )++TOOLS = ((list_models, READ_ONLY),(load_model, WRITES),(unload_model, DESTRUCTIVE, _unload_schema()),(plan_load, READ_ONLY),+ (download_model, WRITES),)diff --git a/studio/backend/studio_mcp/tools/training.py b/studio/backend/studio_mcp/tools/training.pyindex b69bdcffd49..19926ba0c94 100644--- a/studio/backend/studio_mcp/tools/training.py+++ b/studio/backend/studio_mcp/tools/training.py@@ -5,6 +5,8 @@from __future__ import annotations+import asyncio+import reimport secretsfrom typing import Any, Literal, Optionalfrom urllib.parse import quote@@ -22,7 +24,7 @@ from studio_mcp.outputs import (TrainingRuns,TrainingStarted,)-from studio_mcp.tools import READ_ONLY, WRITES, as_dict, integer, opt_text, route_json+from studio_mcp.tools import READ_ONLY, WRITES, as_dict, integer, leaf_name, opt_text, route_jsonTRAINING_ROUTES = {"llm": "/api/train/start", "diffusion": "/api/train/diffusion/start"}@@ -30,7 +32,7 @@ TRAINING_ROUTES = {"llm": "/api/train/start", "diffusion": "/api/train/diffusionFORMAT_TYPES = ("auto", "alpaca", "chatml", "sharegpt", "conversational", "raw")-def _checked_config(config: dict[str, Any], kind: str) -> None:+def _checked_config(config: dict[str, Any], kind: str) -> Any:"""Validate the config the way the route will, so a mistake is reported before any GPU work."""from pydantic import ValidationError@@ -40,7 +42,7 @@ def _checked_config(config: dict[str, Any], kind: str) -> None:raise ToolError(f"format_type must be one of {', '.join(FORMAT_TYPES)}.")model = TrainingStartRequest if kind == "llm" else DiffusionTrainingStartRequesttry:- model.model_validate(config)+ return model.model_validate(config)except ValidationError as exc:problems = "; ".join(f"{'.'.join(str(part) for part in error['loc'])}: {error['msg']}"@@ -49,24 +51,175 @@ def _checked_config(config: dict[str, Any], kind: str) -> None:raise ToolError(f"Invalid training config: {problems}") from None+TRAINABLE_TTS = (+ "Trainable text-to-speech models: unsloth/orpheus-3b-0.1-ft, sesame/csm-1b, "+ "unsloth/Spark-TTS-0.5B, unsloth/Llama-OuteTTS-1.0-1B."+)+# Never echoed by validate_only: secrets, and the host paths the request validators resolve refs into.+HIDDEN_CONFIG_KEYS = {+ "llm": frozenset(+ {+ "hf_token",+ "wandb_token",+ "s3_config",+ "approved_remote_code_fingerprint",+ "model_local_path",+ "model_snapshot_path",+ "dataset_local_path",+ "dataset_snapshot_path",+ "local_datasets",+ "local_eval_datasets",+ "tensorboard_dir",+ "resume_from_checkpoint",+ "model_subfolder",+ }+ ),+ "diffusion": frozenset(+ {"hf_token", "data_dir", "output_dir", "cond_cache_dir", "resume_from_checkpoint"}+ ),+}+++def _hidden_key(key: str, kind: str) -> bool:+ return (+ key in HIDDEN_CONFIG_KEYS[kind]+ or key.endswith(("_path", "_dir", "_token"))+ or "secret" in key+ )+++def _shown_scalar(value: Any) -> bool:+ if not isinstance(value, str):+ return isinstance(value, (bool, int, float))+ text = value.strip()+ # A host path or a ref: handle in any field, such as a model_name given as a local folder.+ return not (+ text.startswith(("/", "\\", "~", "ref:", "file:"))+ or (len(text) > 2 and text[1] == ":" and text[2] in "\\/")+ )+++def _shown_config(validated: Any, kind: str) -> dict[str, Any]:+ """The config as the route will read it: scalars, lists of scalars and flat dicts, no paths or secrets."""+ shown: dict[str, Any] = {}+ for key, value in validated.model_dump(mode = "json", exclude_none = True).items():+ if _hidden_key(key, kind):+ continue+ if isinstance(value, list) and all(_shown_scalar(v) for v in value):+ shown[key] = value+ elif isinstance(value, dict) and all(+ _shown_scalar(v) and not _hidden_key(str(k), kind) for k, v in value.items()+ ):+ shown[key] = value+ elif _shown_scalar(value):+ shown[key] = value+ return shown+++def _asked_name(asked: Any, name: str) -> str:+ """The model as the caller named it: the validator turns a ref: handle into a host path, which must not come back."""+ asked = str(asked or "").strip()+ if asked and not asked.startswith(("/", "\\", "~")) and ":" not in asked[1:3]:+ return asked+ return leaf_name(name.rstrip("/\\")) or "This model"+++async def _checked_trainable(+ validated: Any,+ caller: Caller,+ asked: Any = None,+) -> tuple[Any, Optional[str]]:+ """Refuse a model the trainer can't train; a codec text-to-speech model gets is_dataset_audio."""+ from core.inference.audio_cpp_models import AUDIO_CPP_AUDIO_TYPES, looks_like_audio_cpp+ from core.inference.native_audio import NATIVE_AUDIO_MODEL_IDS+ from utils.audio_tokens import NATIVE_OUTPUT_AUDIO_TYPES, TTS_AUDIO_TYPES++ name = str(validated.model_name or "").strip()+ shown = _asked_name(asked, name)+ leaf = re.split(r"[\\/]", name.rstrip("/\\"))[-1].lower()+ # audio.cpp rows are GGUF folders too; their refusal says more.+ if looks_like_audio_cpp(name):+ raise ToolError(+ f"{shown} runs on audio.cpp, which Unsloth Studio can run but not train. {TRAINABLE_TTS}"+ )+ if validated.model_format == "gguf" or leaf.endswith(("-gguf", ".gguf")):+ raise ToolError(f"GGUF models are inference-only and cannot be trained. {TRAINABLE_TTS}")+ audio_type = NATIVE_AUDIO_MODEL_IDS.get(name.lower())+ if audio_type is None:+ # Imported here so a test can patch the module attribute; any failure is no verdict.+ from utils.models import model_config+ try:+ audio_type, _known = await asyncio.to_thread(+ model_config.detect_audio_type_checked,+ name,+ hf_token = validated.hf_token or caller.hf_token,+ )+ except Exception:+ audio_type = None+ if audio_type in AUDIO_CPP_AUDIO_TYPES:+ raise ToolError(+ f"{shown} runs on audio.cpp, which Unsloth Studio can run but not train. {TRAINABLE_TTS}"+ )+ if audio_type in NATIVE_OUTPUT_AUDIO_TYPES:+ raise ToolError(+ f"{shown} is a text-to-speech model Unsloth Studio can run but not train. {TRAINABLE_TTS}"+ )+ if audio_type in TTS_AUDIO_TYPES and not validated.is_dataset_audio:+ return validated.model_copy(update = {"is_dataset_audio": True}), (+ f"{shown} is a text-to-speech model, so is_dataset_audio is set to true in the returned "+ "config; start training with that config."+ )+ return validated, None++async def start_training(config: dict[str, Any],kind: Literal["llm", "diffusion"] = "llm",validate_only: bool = False,) -> TrainingStarted:- """Start a training job and return at once; follow it with studio_status. This starts real GPU work, so build the config first and check it with ``validate_only`` true, which starts nothing, for example {"kind": "llm", "config": {...}, "validate_only": true}.+ """Start a training job and return at once.+ This starts real GPU work, so build the config first and check it with ``validate_only`` true, which starts nothing and returns the resolved config without paths or secrets, for example {"kind": "llm", "config": {...}, "validate_only": true}.+ Training keeps running after this returns; follow it with get_job(kind="training", wait_s=50) (kind "diffusion_training" for kind "diffusion"), and an export with get_job(kind="export", wait_s=50).++ kind "llm": ``config`` is the Unsloth Studio training request.+ The minimum is {"model_name": a Hugging Face model repo id (not a GGUF; it is downloaded when training starts), "training_type": "LoRA/QLoRA" | "Full Finetuning" | "Continued Pretraining", "format_type": "auto" | "alpaca" | "chatml" | "sharegpt" | "conversational" | "raw", "hf_dataset": a Hugging Face dataset repo id}.+ Instead of hf_dataset, "local_datasets" takes the ref values datasets(action="upload") and datasets(action="list") return.+ Common options: max_steps or num_epochs, learning_rate (a string such as "2e-4"), batch_size, gradient_accumulation_steps, max_seq_length, load_in_4bit, lora_r, lora_alpha, train_split.+ list_models with ``model`` returns that model's defaults to start from, and datasets(action="check_format") detects the dataset's format: use it when it is one of the format_type values above, otherwise "auto" (image and audio datasets included).+ hf_token for a gated model goes in the config.- kind "llm": ``config`` is the Unsloth Studio training request. The minimum is {"model_name": a Hugging Face model repo id (not a GGUF; it is downloaded when training starts), "training_type": "LoRA/QLoRA" | "Full Finetuning" | "Continued Pretraining", "format_type": "auto" | "alpaca" | "chatml" | "sharegpt" | "conversational" | "raw", "hf_dataset": a Hugging Face dataset repo id}. Common options: max_steps or num_epochs, learning_rate (a string such as "2e-4"), batch_size, gradient_accumulation_steps, max_seq_length, load_in_4bit, lora_r, lora_alpha, train_split. list_models with ``model`` returns that model's defaults to start from, and datasets(action="check_format") detects the dataset's format: use it when it is one of the format_type values above, otherwise "auto" (image and audio datasets included). hf_token for a gated model goes in the config.+ Text-to-speech: Unsloth Studio trains unsloth/orpheus-3b-0.1-ft, sesame/csm-1b, unsloth/Spark-TTS-0.5B and unsloth/Llama-OuteTTS-1.0-1B, on a CUDA GPU only (not on Apple Silicon).+ The dataset needs an audio column ("audio" or "speech") and a text column ("text", "sentence", "transcript" or "transcription"), plus an optional speaker column ("source" or "speaker_id"); name other columns with "custom_format_mapping": {"<column>": "audio" | "text" | "speaker_id"}.+ Set "is_dataset_audio": true and "format_type": "auto"; validate_only sets is_dataset_audio for these models and refuses GGUF, audio.cpp and other text-to-speech models it can't train.+ GGUF and audio.cpp text-to-speech models, such as Qwen3-TTS and Breeze, can't be trained.+ An audio dataset comes in through hf_dataset; uploads take CSV, JSON, JSONL and Parquet files only.- kind "diffusion": an image LoRA; ``config`` is the image training request, and ``data_dir`` names an image dataset already in Unsloth Studio (there is no upload tool).+ kind "diffusion": an image LoRA; ``config`` is the image training request, and ``data_dir`` names an image dataset in Unsloth Studio, such as the name datasets(action="upload_images") returns.- Unsloth Studio refuses while another training run or an API inference request is active. The result's ``start_request_id`` cancels a start that has not begun (cancel kind "training_start"); ``job_id`` stops a running job (cancel kind "training", or "diffusion_training" for kind "diffusion", whose progress is studio_status's ``diffusion_training``)."""+ One GPU: Unsloth Studio refuses (409) while another training run or an API inference request is in flight, so wait for it to finish.+ Starting training unloads the image and video models, and unloads chat, text-to-speech and speech-to-text models only when they don't fit beside it (speech-to-text first).+ When it finishes, load the result with load_model(checkpoint=…), or export_model it and load that with load_model(export=…), then chat or generate_audio with it.+ The result's ``start_request_id`` cancels a start that has not begun (cancel kind "training_start"); ``job_id`` stops a running job (cancel kind "training", or "diffusion_training" for kind "diffusion", whose progress is studio_status's ``diffusion_training``).+ """config = dict(config)- if kind == "llm" and not config.get("start_request_id"):+ # validate_only echoes the config, and an id it made up would cancel nothing.+ if kind == "llm" and not validate_only and not config.get("start_request_id"):config["start_request_id"] = f"mcp-{secrets.token_hex(8)}"- _checked_config(config, kind)+ validated = _checked_config(config, kind)+ note = None+ if kind == "llm":+ # A real start gets the same refusals, and a codec TTS model the audio dataset setting it needs.+ validated, note = await _checked_trainable(+ validated, current_caller(), config.get("model_name")+ )+ if validated.is_dataset_audio:+ config["is_dataset_audio"] = Trueif validate_only:- return TrainingStarted(status = "valid", message = "The config is valid; nothing was started.")+ return TrainingStarted(+ status = "valid",+ message = " ".join(filter(None, ("The config is valid; nothing was started.", note))),+ config = _shown_config(validated, kind),+ )start_request_id = opt_text(config.get("start_request_id"))try:payload = await route_json("POST", TRAINING_ROUTES[kind], json_body = config)diff --git a/studio/backend/studio_mcp/trained_models.py b/studio/backend/studio_mcp/trained_models.pynew file mode 100644index 00000000000..ef55e2adb2e--- /dev/null+++ b/studio/backend/studio_mcp/trained_models.py@@ -0,0 +1,215 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Load a checkpoint or an export by name. The listing routes give host paths; the load goes out with a ``ref:`` handle minted from that path, and the agent only ever sees the name it asked for."""++from __future__ import annotations++import asyncio+import time+from collections import OrderedDict+from dataclasses import dataclass, field+from typing import Optional++from hub.utils.host_paths import cache_reference, redact_paths_in_text+from studio_mcp import checkpoints+from studio_mcp.caller import Caller+from studio_mcp.errors import tool_error+from studio_mcp.outputs import LoadResult+from studio_mcp.tools import as_dict, leaf_name, opt_text, route_json++NOT_LLM_KINDS = ("image", "video", "stt")+# The name must resolve before a load job can exist, so even wait_s=0 gives the listing reads this long.+RESOLVE_TIMEOUT_S = 5.0+++@dataclass(frozen = True)+class TrainedModel:+ name: str+ ref: str = field(repr = False)+ is_lora: bool+ gguf_variant: Optional[str] = None+ # A GGUF export whose quantization its file name doesn't give; the load can't place it by device.+ unplaced_gguf: bool = False+ # Every listed path or ref -> its name, to name models the load evicted.+ known: dict[str, str] = field(default_factory = dict, repr = False)++ def renamed(self, result: LoadResult) -> LoadResult:+ evicted = [self.known.get(entry, entry) for entry in result.evicted]+ slots = [+ slot.model_copy(update = {"model": self.known.get(slot.model, slot.model)})+ for slot in result.evicted_slots+ ]+ return result.model_copy(+ update = {"model": self.name, "evicted": evicted, "evicted_slots": slots}+ )+++# (account, name) -> the ref: handle it was loaded under, so unload_model(model=<name>) finds it.+_loaded_as: "OrderedDict[tuple[str, str], str]" = OrderedDict()+++def remember_load(caller: Caller, trained: TrainedModel) -> None:+ key = (caller.account_id, trained.name)+ _loaded_as[key] = trained.ref+ _loaded_as.move_to_end(key)+ while len(_loaded_as) > 256:+ _loaded_as.popitem(last = False)+++def forget_load(caller: Caller, model: str) -> None:+ # A plain model loaded under the same name is not the trained one any more.+ _loaded_as.pop((caller.account_id, model), None)+++def loaded_ref(caller: Caller, model: Optional[str]) -> Optional[str]:+ """The ref: handle a checkpoint or export name was loaded under, else the model as given."""+ return _loaded_as.get((caller.account_id, model), model) if model else model+++def rename_job(caller: Caller, job_id: Optional[str], trained: TrainedModel) -> None:+ """Name a load that outlasted wait_s in its job result too. The callback is added before any get_job waiter, so it runs first."""+ from studio_mcp import loading++ job = loading.LOADS.jobs.get(f"{caller.account_id}:{job_id}") if job_id else None+ if job is None:+ return++ def rename(_task: object = None) -> None:+ if isinstance(job.result, LoadResult):+ job.result = trained.renamed(job.result)++ if job.task is None or job.task.done():+ rename()+ else:+ job.task.add_done_callback(rename)+++def _known(rows: list[tuple[str, str]]) -> dict[str, str]:+ known = {}+ for path, name in rows:+ known[path] = name+ known[cache_reference(path)] = name+ return known+++def _parent(path: str) -> str:+ trimmed = path.rstrip("\\/")+ return trimmed[: len(trimmed) - len(leaf_name(trimmed))].rstrip("\\/") or trimmed+++async def _export_rows(caller: Caller) -> list[tuple[str, str, Optional[str]]]:+ listing = await route_json("GET", "/api/models/loras", caller = caller, hub_header = True)+ rows = []+ for row in as_dict(listing).get("loras") or []:+ row = as_dict(row)+ label, path = opt_text(row.get("display_name")), opt_text(row.get("adapter_path"))+ if row.get("source") == "exported" and label and path:+ # The scan names a two-level export "run / name"; export_model reports "run/name".+ rows.append((label.replace(" / ", "/"), path, row.get("export_type")))+ return rows+++def _export_known(rows: list[tuple[str, str, Optional[str]]]) -> dict[str, str]:+ # A GGUF export loads as its folder, so a later eviction names the folder.+ return _known(+ [(r[1], r[0]) for r in rows] + [(_parent(r[1]), r[0]) for r in rows if r[2] == "gguf"]+ )+++async def _other_known(caller: Caller, of: str) -> dict[str, str]:+ """Names for the other kind of trained model, so a load that evicts one names it too."""+ try:+ if of == "checkpoint":+ return _export_known(await _export_rows(caller))+ found, _folders = await checkpoints.list_checkpoints(caller)+ return _known([(c.path, c.name) for c in found])+ except Exception:+ return {}+++async def resolve_checkpoint(caller: Caller, name: str) -> TrainedModel:+ found, _folders = await checkpoints.list_checkpoints(caller)+ match = next((c for c in found if c.name == name), None)+ if match is None:+ available = ", ".join(sorted(c.name for c in found)[:20]) or "none"+ raise tool_error(f"No checkpoint named {name}. Available: {available}")+ # The load route detects LoRA on disk; a full finetune has no peft_type.+ return TrainedModel(+ name = name,+ ref = cache_reference(match.path),+ is_lora = match.peft_type is not None,+ known = {+ **await _other_known(caller, "checkpoint"),+ **_known([(c.path, c.name) for c in found]),+ },+ )+++async def resolve_export(caller: Caller, name: str, variant: Optional[str]) -> TrainedModel:+ rows = await _export_rows(caller)+ match = [r for r in rows if r[0] == name] or [+ r for r in rows if r[0].casefold() == name.casefold()+ ]+ if len(match) != 1:+ available = ", ".join(sorted({r[0] for r in rows})[:20]) or "none"+ # A hint, since the scrub would read "<run>/<name>" as a path; the names are scrubbed here.+ raise tool_error(+ f"No export named {name}.",+ hint = "A merged or LoRA export is found when its save_directory has two levels, "+ f'such as "<run>/<name>". Available: {redact_paths_in_text(available)}',+ )+ _label, path, export_type = match[0]+ gguf_variant = None+ if export_type == "gguf":+ from hub.utils.gguf import extract_quant_token++ # The scan picks one .gguf file; the folder plus a variant picks the quantization, and a+ # variant is what makes the load (and device="cpu") treat it as GGUF.+ gguf_variant = variant or extract_quant_token(leaf_name(path))+ if gguf_variant:+ path = _parent(path)+ return TrainedModel(+ name = name,+ ref = cache_reference(path),+ is_lora = export_type == "lora",+ gguf_variant = gguf_variant,+ unplaced_gguf = export_type == "gguf" and not gguf_variant,+ known = {**await _other_known(caller, "export"), **_export_known(rows)},+ )+++async def resolve(+ caller: Caller,+ *,+ model: Optional[str],+ checkpoint: Optional[str],+ export: Optional[str],+ kind: str,+ variant: Optional[str],+) -> Optional[TrainedModel]:+ """None for a plain ``model`` load; refusals come before any route call."""+ if sum(value is not None for value in (model, checkpoint, export)) != 1:+ raise tool_error("load_model needs exactly one of model, checkpoint or export.")+ if model is not None:+ return None+ if kind in NOT_LLM_KINDS:+ raise tool_error(+ 'checkpoint and export load chat and text-to-speech models; use kind "llm", "tts" or "audio".'+ )+ if checkpoint is not None:+ return await resolve_checkpoint(caller, checkpoint)+ return await resolve_export(caller, export, variant)+++async def resolve_by(+ deadline: float, caller: Caller, **kwargs: Optional[str]+) -> Optional[TrainedModel]:+ """resolve, bounded: the listing reads run before the load job, so a stalled one must not hold the call."""+ timeout = max(deadline - time.monotonic(), RESOLVE_TIMEOUT_S)+ try:+ return await asyncio.wait_for(resolve(caller, **kwargs), timeout)+ except asyncio.TimeoutError:+ raise tool_error(+ "Unsloth Studio did not list its training runs and exports in time; call load_model again."+ ) from Nonediff --git a/studio/backend/tests/test_mcp_forward.py b/studio/backend/tests/test_mcp_forward.pyindex c1930e69bbc..90736f32d4a 100644--- a/studio/backend/tests/test_mcp_forward.py+++ b/studio/backend/tests/test_mcp_forward.py@@ -193,6 +193,12 @@ def test_a_streamed_upload_is_refused():"/api/inference/../../api/auth/api-keys","/v1/videos/%2e%2e/%2e%2e/api/auth/api-keys","/api/inference",+ "/api/hub/active-downloads",+ "/api/hub/gguf-download-progress",+ "/api/hub/token/validate",+ "/api/hub/transport-status",+ "/api/hub/cached-gguf",+ "/api/hub/download/../token",],)def test_a_path_outside_the_allowlist_raises(path):@@ -208,6 +214,10 @@ def test_a_path_outside_the_allowlist_raises(path):"/api/inference/status","/api/hub/gguf-variants","/api/settings/embedding-model",+ "/api/hub/download",+ "/api/hub/download-status",+ "/api/hub/download-progress",+ "/api/hub/download/cancel",],)def test_allowlisted_paths_pass_the_check(path):diff --git a/studio/backend/tests/test_mcp_k16_guard_order.py b/studio/backend/tests/test_mcp_k16_guard_order.pynew file mode 100644index 00000000000..51d726bbb19--- /dev/null+++ b/studio/backend/tests/test_mcp_k16_guard_order.py@@ -0,0 +1,107 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""load_model's pre-load guards in their fixed order: a managed download is waited on, never refused, and only a partial variant Unsloth Studio is not downloading is refused. Checkpoint and export loads skip both and carry is_lora."""++import pytest++from studio_mcp import loading, model_downloads++from .mcp_harness import bodies, fast_polls, make_caller, queries, run_tool, sequence # noqa: F401+from .test_mcp_tools_loading import PAYLOADS, STATUS_ROUTE+from .test_mcp_train_to_use import _routes as trained_routes++QWEN = "unsloth/Qwen3-0.6B-GGUF"+STATUS = "/api/hub/download-status"+PARTIAL = {+ "default_variant": "Q4_K_M",+ "variants": [{"quant": "Q4_K_M", "filename": "q.gguf", "downloaded": False, "partial": True}],+}+DONE = {+ "default_variant": "Q4_K_M",+ "variants": [{"quant": "Q4_K_M", "filename": "q.gguf", "downloaded": True, "partial": False}],+}++[email protected](autouse = True)+def quick_waits(monkeypatch, fast_polls):+ monkeypatch.setattr(model_downloads, "WAIT_INTERVAL_S", 0.01)+ # download_model calls elsewhere in the run remember what they staged; start clean.+ monkeypatch.setattr(model_downloads, "_remembered", model_downloads.OrderedDict())+++def _load(+ monkeypatch,+ variants,+ states,+ args = None,+):+ routes = {+ **PAYLOADS,+ ("GET", "/api/hub/gguf-variants"): sequence(*variants),+ ("GET", STATUS): sequence(*({"state": s} for s in states)),+ }+ result, studio = run_tool(monkeypatch, routes, "load_model", {"model": QWEN, **(args or {})})+ return result, studio, bodies(studio, "/api/inference/load")+++def test_an_attach_to_a_load_in_flight_comes_before_any_download_wait(monkeypatch):+ # Guard 1 (attach) wins: a chat load of the same model already running is followed, and the+ # download it may still be finishing is never read, waited on or refused.+ loading_now = {"loading": [QWEN], "serving": [], "loaded": []}+ loaded = {+ "loading": [],+ "serving": [QWEN],+ "loaded": [QWEN],+ "serving_checkpoints": ["/m/q.gguf"],+ }+ routes = {+ **PAYLOADS,+ STATUS_ROUTE: sequence(loading_now, loading_now, loaded),+ ("GET", "/api/hub/gguf-variants"): PARTIAL,+ ("GET", STATUS): {"state": "running"},+ }+ result, studio = run_tool(monkeypatch, routes, "load_model", {"model": QWEN})+ assert result.get("isError") is not True, result+ assert result["structuredContent"]["model"] == QWEN+ assert queries(studio, STATUS) == [] and bodies(studio, "/api/inference/load") == []+++def test_a_managed_download_is_waited_on_then_loaded_not_refused(monkeypatch):+ # The variant reads partial while the manager writes it, then complete.+ result, studio, sent = _load(monkeypatch, [PARTIAL, DONE], ["running", "running", "complete"])+ assert result.get("isError") is not True, result+ assert len(sent) == 1+ reads = queries(studio, STATUS)+ assert len(reads) >= 3 and reads[0] == {"repo_id": QWEN, "gguf_variant": "Q4_K_M"}+++def test_an_unmanaged_partial_variant_is_still_refused(monkeypatch):+ result, _studio, sent = _load(monkeypatch, [PARTIAL], ["idle"])+ assert result["isError"] is True+ assert "still downloading or incomplete" in result["content"][0]["text"]+ assert sent == []+++def test_a_download_that_outlasts_the_wait_is_reported_with_its_id(monkeypatch):+ # The wait runs inside the load job: wait_s ends the call, not the wait, and the job names the download.+ result, _studio, sent = _load(monkeypatch, [PARTIAL], ["running"], {"wait_s": 1})+ out = result["structuredContent"]+ assert result.get("isError") is not True and sent == []+ assert out["status"] == "loading" and out["job_id"]+ job = loading.LOADS.lookup(make_caller().account_id, out["job_id"])+ # The loop the test ran in has closed and cancelled the job; its progress marks remain.+ follow = f'get_job(kind="download", id="{QWEN}::Q4_K_M")'+ assert any(follow in phase for _fraction, phase in job.marks)++[email protected]("name,lora", [("qwen-lora", True), ("qwen-lora-2/checkpoint-30", False)])+def test_a_checkpoint_skips_both_guards_and_carries_is_lora(monkeypatch, name, lora):+ # The fallback records every call, so a Hub lookup for the ref: handle would show up here.+ result, studio = run_tool(+ monkeypatch, trained_routes(), "load_model", {"checkpoint": name}, fallback = {}+ )+ assert result.get("isError") is not True, result+ (body,) = bodies(studio, "/api/inference/load")+ assert body.get("is_lora", False) is lora+ assert queries(studio, STATUS) == [] and queries(studio, "/api/hub/gguf-variants") == []diff --git a/studio/backend/tests/test_mcp_no_host_paths.py b/studio/backend/tests/test_mcp_no_host_paths.pyindex ffb900f5e20..c74fad65c45 100644--- a/studio/backend/tests/test_mcp_no_host_paths.py+++ b/studio/backend/tests/test_mcp_no_host_paths.py@@ -22,6 +22,7 @@ from studio_mcp.outputs import RouteText, ToolOutputfrom .mcp_harness import (OUT,+ PNG_URL,RUN_CHECKPOINTS,SENTINEL_ROOTS,WAV_INPUT,@@ -35,6 +36,10 @@ from .test_mcp_tools_audio import PAYLOADS as AUDIO_PAYLOADSfrom .test_mcp_tools_audio import TRANSCRIPT, VERBOSEfrom .test_mcp_tools_cancel import PAYLOADS as CANCEL_PAYLOADSfrom .test_mcp_tools_datasets import PAYLOADS as DATASETS_PAYLOADS+from .test_mcp_tools_datasets_images import PAYLOADS as IMAGE_DATASET_PAYLOADS+from .test_mcp_tools_download import TOOL_PAYLOADS as DOWNLOAD_PAYLOADS+from .test_mcp_train_to_use import _routes as TRAIN_TO_USE_ROUTES+from .test_mcp_tools_datasets_upload import PAYLOADS as UPLOAD_PAYLOADSfrom .test_mcp_tools_images import PAYLOADS as IMAGES_PAYLOADSfrom .test_mcp_tools_library import PAYLOADS as LIBRARY_PAYLOADSfrom .test_mcp_tools_library import VOICE_PAYLOADS@@ -76,12 +81,17 @@ CASES: dict[str, Any] = {(MODELS_PAYLOADS, {"model": "unsloth/Qwen3-0.6B"}),(MODELS_PAYLOADS, {"source": "catalog"}),],- "load_model": (LOADING_PAYLOADS, {"model": "unsloth/Llama-3.2-1B-Instruct-GGUF"}),+ "load_model": [+ (LOADING_PAYLOADS, {"model": "unsloth/Llama-3.2-1B-Instruct-GGUF"}),+ (TRAIN_TO_USE_ROUTES([f"{OUT}/qwen-lora"]), {"checkpoint": "qwen-lora"}),+ (TRAIN_TO_USE_ROUTES([f"{OUT}/qwen-lora"]), {"export": "qwen-GGUF", "variant": "Q4_K_M"}),+ ],"unload_model": (LOADING_PAYLOADS, {}),"plan_load": (plan_world("off", ["unsloth/Qwen3-0.6B-GGUF"]),{"model": "unsloth/Qwen3-0.6B-GGUF"},),+ "download_model": (DOWNLOAD_PAYLOADS, {"model": "unsloth/Qwen3-0.6B-GGUF"}),"chat": (TEXT_PAYLOADS, {"prompt": "hi"}),"embed": (TEXT_PAYLOADS, {"texts": ["a", "b"]}),"system_one": (TEXT_PAYLOADS, {"state": "x", "questions": {"urgent": {"type": "noul"}}}),@@ -91,6 +101,7 @@ CASES: dict[str, Any] = {(VIDEO_PAYLOADS, {"kind": "video"}),(VIDEO_PAYLOADS, {"kind": "video", "id": "video-1"}),(RECIPE_PAYLOADS, {"kind": "recipe", "id": "job-1", "rows": 2}),+ (DOWNLOAD_PAYLOADS, {"kind": "download", "id": "a/b::Q4_K_M"}),],"start_training": [(TRAINING_PAYLOADS, {"config": {"model_name": "m"}}),@@ -104,12 +115,19 @@ CASES: dict[str, Any] = {"cancel": [(CANCEL_PAYLOADS, {"kind": "training"}),(CANCEL_PAYLOADS, {"kind": "recipe", "id": "rec-1"}),+ (DOWNLOAD_PAYLOADS, {"kind": "model_download", "id": "a/b::Q4_K_M"}),],"run_recipe": (RECIPE_PAYLOADS, {"recipe": {"columns": [{"name": "q"}]}}),"datasets": [(DATASETS_PAYLOADS, {"action": "list"}),(DATASETS_PAYLOADS, {"action": "check_format", "name": "a/b"}),(DATASETS_PAYLOADS, {"action": "status", "repo_id": "a/b"}),+ (UPLOAD_PAYLOADS, {"action": "upload", "rows": [{"text": "hi"}]}),+ (UPLOAD_PAYLOADS, {"action": "upload", "data_base64": "YSxi", "filename": "a.csv"}),+ (+ IMAGE_DATASET_PAYLOADS,+ {"action": "upload_images", "name": "p", "images": [PNG_URL], "captions": ["c"]},+ ),],"analyze_audio": (ANALYZE_PAYLOADS, {"audio": WAV_INPUT, "expected_text": "hello"}),"transcribe": (TRANSCRIBE_PAYLOADS, {"audio": WAV_INPUT, "timestamps": True, "language": "en"}),diff --git a/studio/backend/tests/test_mcp_server.py b/studio/backend/tests/test_mcp_server.pyindex 32d4f534922..7441a6a39c1 100644--- a/studio/backend/tests/test_mcp_server.py+++ b/studio/backend/tests/test_mcp_server.py@@ -26,6 +26,7 @@ OTHERS = {"analyze_audio","chat","datasets",+ "download_model","export_model","generate_audio","generate_image",diff --git a/studio/backend/tests/test_mcp_tool_contract.py b/studio/backend/tests/test_mcp_tool_contract.pyindex 71eb90501dd..c53d6683ffb 100644--- a/studio/backend/tests/test_mcp_tool_contract.py+++ b/studio/backend/tests/test_mcp_tool_contract.py@@ -424,6 +424,13 @@ PATH_CALLS = [["/v1/videos"],None,),+ (+ "datasets",+ lambda path: {"action": "upload_images", "name": "my-photos", "images": [{"path": path}]},+ {("POST", "/api/train/diffusion/dataset"): {"name": "my-photos", "uploaded": 1}},+ ["/api/train/diffusion/dataset"],+ None,+ ),]diff --git a/studio/backend/tests/test_mcp_tools_cancel.py b/studio/backend/tests/test_mcp_tools_cancel.pyindex 1557fe1f7b1..4b5bb75f8b6 100644--- a/studio/backend/tests/test_mcp_tools_cancel.py+++ b/studio/backend/tests/test_mcp_tools_cancel.py@@ -14,6 +14,7 @@ from .mcp_harness import bodies, register_export_job, run_tool, sequenceSTART = "/api/train/start-requests/req-1/cancel"RECIPE = "/api/data-recipe/jobs/rec-1/cancel"DOWNLOAD = "/api/hub/datasets/download/cancel"+MODEL_DOWNLOAD = "/api/hub/download/cancel"VIDEO = "/api/inference/video/generate/cancel"STOPPING = "Stop requested. Training will stop at the next safe step."PAYLOADS = {@@ -32,6 +33,7 @@ PAYLOADS = {("POST", "/api/inference/video/generate/cancel"): {"cancelled": True},("POST", "/api/inference/cancel"): {"cancelled": 1},("POST", DOWNLOAD): {"repo_id": "a/b", "state": "cancelling"},+ ("POST", MODEL_DOWNLOAD): {"job_key": "a/b::q4_k_m", "state": "cancelling"},}@@ -71,6 +73,11 @@ def _call(({"kind": "video", "id": "vid-1"}, VIDEO, {"video_id": "vid-1"}),({"kind": "chat", "id": "mcp-abc"}, "/api/inference/cancel", {"cancel_id": "mcp-abc"}),({"kind": "dataset_download", "id": "a/b"}, DOWNLOAD, {"repo_id": "a/b"}),+ (+ {"kind": "model_download", "id": "a/b::Q4_K_M"},+ MODEL_DOWNLOAD,+ {"repo_id": "a/b", "gguf_variant": "Q4_K_M"},+ ),],)def test_each_kind_reaches_its_route(monkeypatch, args, route, body):@@ -252,6 +259,7 @@ IDLE_ANSWERS = [("chat", "/api/inference/cancel", {"cancelled": 0}),("dataset_download", DOWNLOAD, {"repo_id": "a/b", "state": "completed"}),("dataset_download", DOWNLOAD, {"repo_id": "a/b", "state": "cancelled"}),+ ("model_download", MODEL_DOWNLOAD, {"job_key": "a/b::", "state": "idle"}),]IDS = {"training": "job-7",@@ -259,6 +267,7 @@ IDS = {"recipe": "rec-1","chat": "mcp-abc","dataset_download": "a/b",+ "model_download": "a/b",}diff --git a/studio/backend/tests/test_mcp_tools_datasets.py b/studio/backend/tests/test_mcp_tools_datasets.pyindex 6afc58babd4..523879c57df 100644--- a/studio/backend/tests/test_mcp_tools_datasets.py+++ b/studio/backend/tests/test_mcp_tools_datasets.py@@ -5,6 +5,8 @@ import jsonfrom fastapi.responses import JSONResponse+from hub.utils.host_paths import cache_reference+from .mcp_harness import call_to, queries, run_toolPAYLOADS = {@@ -65,10 +67,20 @@ def _call(def test_list_names_datasets_without_their_paths(monkeypatch):result, _studio = _call(monkeypatch, {"action": "list"})assert result["structuredContent"] == {- "local": [{"id": "my-chats", "label": "My chats", "source": "local", "rows": 120}],+ "local": [+ {+ "id": "my-chats",+ "label": "My chats",+ "source": "local",+ "rows": 120,+ "ref": cache_reference("/srv/unsloth/datasets/my-chats"),+ }+ ],"cached": [{"repo_id": "mlabonne/FineTome-100k", "size_bytes": 1024}],"format": None,"download": None,+ "uploaded": None,+ "image_dataset": None,}assert "/srv" not in json.dumps(result)diff --git a/studio/backend/tests/test_mcp_tools_datasets_images.py b/studio/backend/tests/test_mcp_tools_datasets_images.pynew file mode 100644index 00000000000..b604382d164--- /dev/null+++ b/studio/backend/tests/test_mcp_tools_datasets_images.py@@ -0,0 +1,109 @@+# 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 json+import re+from email.parser import BytesParser+from email.policy import default++import pytest++from .mcp_harness import JPEG, PNG, PNG_URL, call_to, data_url, run_tool++DATASET = "/api/train/diffusion/dataset"+SAVED = {+ "name": "my-photos",+ "path": "/srv/unsloth/assets/datasets/my-photos",+ "image_count": 2,+ "clip_count": 0,+ "caption_count": 1,+ "uploaded": 3,+}+PAYLOADS = {("POST", DATASET): SAVED}+JPEG_URL = {"data_url": data_url(JPEG, "image/jpeg")}+++def _parts(studio) -> list[tuple[str, str, bytes]]:+ # Every multipart part in order; the harness form() keeps only the last per field.+ _m, _p, headers, body = call_to(studio, DATASET)+ message = BytesParser(policy = default).parsebytes(+ b"Content-Type: " + headers["content-type"].encode() + b"\r\n\r\n" + body+ )+ return [+ (+ part.get_param("name", header = "content-disposition"),+ part.get_filename(),+ part.get_payload(decode = True),+ )+ for part in message.iter_parts()+ ]+++def _upload(monkeypatch, **args):+ args = {"action": "upload_images", "name": "my-photos", **args}+ return run_tool(monkeypatch, PAYLOADS, "datasets", args)+++def test_images_and_captions_go_up_as_files_with_fresh_stems(monkeypatch):+ result, studio = _upload(monkeypatch, images = [PNG_URL, JPEG_URL], captions = ["a fox", ""])+ assert result["structuredContent"]["image_dataset"] == {+ "name": "my-photos",+ "image_count": 2,+ "caption_count": 1,+ "uploaded": 3,+ }+ assert "/srv" not in json.dumps(result)+ parts = _parts(studio)+ fields = {name: value for name, filename, value in parts if filename is None}+ assert fields == {"name": b"my-photos", "create_only": b"false"}+ files = [(filename, value) for name, filename, value in parts if name == "files"]+ stem = files[0][0].removesuffix(".png")+ assert re.fullmatch(r"mcp-[0-9a-f]{8}-000", stem)+ assert files == [+ (f"{stem}.png", PNG),+ (f"{stem}.txt", b"a fox"),+ (f"{stem[:-3]}001.jpg", JPEG),+ ]+++def test_a_second_upload_never_reuses_the_first_ones_names(monkeypatch):+ names = []+ for _ in range(2):+ _result, studio = _upload(monkeypatch, images = [PNG_URL])+ names += [filename for _n, filename, _v in _parts(studio) if filename]+ assert len(set(names)) == 2+++ "args,message",+ [+ ({"name": ""}, "needs name"),+ ({"images": []}, "needs name"),+ ({"captions": ["a", "b"]}, "captions has 2 entries for 1 images"),+ ({"captions": ["x" * 2001]}, "longer than 2000"),+ ({"images": [{"data_url": "data:image/gif;base64,R0lGODlh"}]}, None),+ ({"images": [{"data_url": data_url(b"GIF89a" + b"\x00" * 8, "image/png")}]}, "Images must"),+ ({"images": [PNG_URL] * 65}, None),+ ],+)+def test_a_refused_image_upload_never_reaches_a_route(monkeypatch, args, message):+ args = {"action": "upload_images", "name": "my-photos", "images": [PNG_URL], **args}+ result, studio = run_tool(monkeypatch, {}, "datasets", args, fallback = {})+ assert result["isError"] is True+ assert message is None or message in result["content"][0]["text"]+ assert studio.state.calls == []+++def test_images_past_the_upload_limit_are_refused_before_any_upload(monkeypatch):+ monkeypatch.setattr("utils.upload_limits.get_upload_limit_bytes", lambda: len(PNG) + 1)+ result, studio = _upload(monkeypatch, images = [PNG_URL, PNG_URL])+ assert result["isError"] is True+ assert "at image 2, more than one upload_images call takes" in result["content"][0]["text"]+ assert studio.state.calls == []+++def test_one_call_holds_at_most_the_mcp_budget(monkeypatch):+ monkeypatch.setattr("studio_mcp.tools.data.MAX_IMAGE_UPLOAD_BYTES", len(PNG) + 1)+ result, studio = _upload(monkeypatch, images = [PNG_URL, PNG_URL])+ assert "at image 2" in result["content"][0]["text"]+ assert studio.state.calls == []diff --git a/studio/backend/tests/test_mcp_tools_datasets_upload.py b/studio/backend/tests/test_mcp_tools_datasets_upload.pynew file mode 100644index 00000000000..11a80838074--- /dev/null+++ b/studio/backend/tests/test_mcp_tools_datasets_upload.py@@ -0,0 +1,73 @@+# 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 json++import pytest++from hub.utils.host_paths import resolve_host_path_reference+from models.training import TrainingStartRequest++from .mcp_harness import CONFIG, b64, form, run_tool++UPLOAD = "/api/hub/datasets/upload"+STORED = "/srv/unsloth/assets/datasets/uploads/0123abcd_chats.jsonl"+PAYLOADS = {("POST", UPLOAD): {"filename": "chats.jsonl", "stored_path": STORED}}+ROWS = [{"text": "héllo"}, {"text": "bye", "n": 2}]+++def test_rows_upload_as_jsonl_and_come_back_as_a_ref_training_resolves(monkeypatch):+ args = {"action": "upload", "rows": ROWS, "filename": "../chats.csv"}+ result, studio = run_tool(monkeypatch, PAYLOADS, "datasets", args)+ uploaded = result["structuredContent"]["uploaded"]+ assert uploaded["id"] == "0123abcd_chats.jsonl"+ assert uploaded["filename"] == "chats.jsonl"+ assert uploaded["ref"].startswith("ref:")+ assert resolve_host_path_reference(uploaded["ref"]) == STORED+ request = TrainingStartRequest.model_validate({**CONFIG, "local_datasets": [uploaded["ref"]]})+ assert request.local_datasets == [STORED]+ expected = '{"text": "héllo"}\n{"text": "bye", "n": 2}'.encode()+ assert form(studio, UPLOAD)["file"] == ("chats.jsonl", expected)+ assert "/srv" not in json.dumps(result)+++def test_rows_default_to_rows_jsonl_and_base64_keeps_its_name(monkeypatch):+ args = {"action": "upload", "rows": ROWS}+ _result, studio = run_tool(monkeypatch, PAYLOADS, "datasets", args)+ assert form(studio, UPLOAD)["file"][0] == "rows.jsonl"+ args = {"action": "upload", "data_base64": b64(b"a,b\n1,2\n"), "filename": "C:\\x\\t.CSV"}+ result, studio = run_tool(monkeypatch, PAYLOADS, "datasets", args)+ assert result["isError"] is False+ assert form(studio, UPLOAD)["file"] == ("t.CSV", b"a,b\n1,2\n")+++ "args,message",+ [+ ({}, "exactly one of"),+ ({"rows": ROWS, "data_base64": b64(b"x"), "filename": "a.csv"}, "exactly one of"),+ ({"rows": []}, None),+ ({"rows": ["not an object"]}, None),+ ({"data_base64": b64(b"x")}, "needs filename"),+ ({"data_base64": b64(b"x"), "filename": "a.txt"}, "Unsupported file type: .txt"),+ ({"data_base64": b64(b"x"), "filename": "noext"}, "Unsupported file type"),+ ({"data_base64": "@@@", "filename": "a.csv"}, "not valid base64"),+ ({"data_base64": "", "filename": "a.csv"}, "is empty"),+ ],+)+def test_a_refused_upload_never_reaches_a_route(monkeypatch, args, message):+ args = {"action": "upload", **args}+ result, studio = run_tool(monkeypatch, {}, "datasets", args, fallback = {})+ assert result["isError"] is True+ assert message is None or message in result["content"][0]["text"]+ assert studio.state.calls == []+++def test_list_gives_each_local_dataset_a_ref(monkeypatch):+ path = "/srv/unsloth/assets/datasets/uploads/ff_chats.jsonl"+ local = {"datasets": [{"id": "ff_chats.jsonl", "path": path}, {"id": "no-path"}]}+ routes = {("GET", "/api/hub/datasets/local"): local, ("GET", "/api/hub/datasets/cached"): {}}+ result, _studio = run_tool(monkeypatch, routes, "datasets", {"action": "list"})+ first, second = result["structuredContent"]["local"]+ assert resolve_host_path_reference(first["ref"]) == path+ assert second["ref"] is Nonediff --git a/studio/backend/tests/test_mcp_tools_download.py b/studio/backend/tests/test_mcp_tools_download.pynew file mode 100644index 00000000000..76b8e3dfc9b--- /dev/null+++ b/studio/backend/tests/test_mcp_tools_download.py@@ -0,0 +1,469 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""download_model's logic against a fake Unsloth Studio: start bodies, ids, status, cancel and the pre-load wait."""++from __future__ import annotations++import asyncio++import pytest+from fastapi.responses import JSONResponse+from fastmcp.exceptions import ToolError++from studio_mcp import loading, model_downloads++from .mcp_harness import (+ WHISPER,+ bodies,+ fake_studio,+ make_caller,+ queries,+ run_tool,+ sequence,+ stt_state,+)++GGUF = "unsloth/Qwen3-0.6B-GGUF"+VARIANTS = {"default_variant": "Q4_K_M", "variants": [{"quant": "Q8_0"}, {"quant": "Q4_K_M"}]}+STARTED = {"state": "running", "accepted": True, "attached": False}+START, STATUS, CANCEL = "/api/hub/download", "/api/hub/download-status", "/api/hub/download/cancel"+NOT_YOURS = JSONResponse({"detail": "Download not found"}, status_code = 404)+FLUX, VAE = "unsloth/FLUX.1-dev-GGUF", "black-forest-labs/FLUX.1-dev"+PLAN = {+ "entries": [+ {"repo_id": FLUX, "files": ["flux-q4.gguf"], "checkpoint": True},+ {"repo_id": VAE, "files": ["vae/a.safetensors"]},+ {"repo_id": "empty/companion", "files": []},+ ],+}+FLUX_ID = f"{FLUX}::@diffusion,{VAE}::@diffusion"+++class Ctx:+ def __init__(self):+ self.messages = []++ async def report_progress(+ self,+ progress,+ total = None,+ message = None,+ ):+ self.messages.append(message)++[email protected](autouse = True)+def fresh_memory(monkeypatch):+ monkeypatch.setattr(model_downloads, "_remembered", model_downloads.OrderedDict())+ monkeypatch.setattr(model_downloads, "WAIT_INTERVAL_S", 0.01)+ monkeypatch.setattr(loading, "POLL_INTERVAL_S", 0.01)+++def run(studio, fn, *args, **kwargs):+ return asyncio.run(fn(make_caller(studio_app = studio), *args, **kwargs))+++def start(studio, **kwargs):+ return run(studio, model_downloads.start, None, **{"variant": None, "hf_token": None, **kwargs})+++def test_safetensors_sends_the_repo_auto_transport_and_the_hub_header():+ studio = fake_studio({("POST", START): STARTED})+ ref = start(studio, model = "unsloth/Qwen3-0.6B", kind = "llm", hf_token = "hf_x")+ assert bodies(studio, START) == [{"repo_id": "unsloth/Qwen3-0.6B", "transport_mode": "auto"}]+ assert studio.state.calls[0][2]["x-unsloth-hf-token"] == "hf_x"+ assert (ref.id, ref.status, ref.attached) == ("unsloth/Qwen3-0.6B", "running", False)++[email protected]("kind", ["llm", "tts", "audio"])+def test_a_gguf_repo_downloads_only_one_variant(kind):+ studio = fake_studio({("GET", "/api/hub/gguf-variants"): VARIANTS, ("POST", START): STARTED})+ ref = start(studio, model = GGUF, kind = kind)+ assert bodies(studio, START) == [+ {"repo_id": GGUF, "transport_mode": "auto", "gguf_variant": "Q4_K_M"}+ ]+ assert (ref.id, ref.variant) == (f"{GGUF}::Q4_K_M", "Q4_K_M")+ assert start(studio, model = "org/repo", kind = kind, variant = "Q8_0").id == "org/repo::Q8_0"+ # No recommended variant: the first one listed.+ first = {"variants": [{"quant": "Q2_K"}]}+ studio = fake_studio({("GET", "/api/hub/gguf-variants"): first, ("POST", START): STARTED})+ assert start(studio, model = GGUF, kind = kind).variant == "Q2_K"+++def test_a_gguf_repo_with_no_variant_is_refused_before_any_download():+ studio = fake_studio({("GET", "/api/hub/gguf-variants"): {"variants": []}}, fallback = STARTED)+ with pytest.raises(ToolError, match = "no GGUF variant"):+ start(studio, model = GGUF, kind = "llm")+ assert bodies(studio, START) == []+++def test_a_busy_repo_names_the_other_download_and_an_attach_is_fine():+ busy = {"accepted": False, "attached": False, "state": "cancelling"}+ with pytest.raises(ToolError, match = "another download of it is cancelling"):+ start(fake_studio({("POST", START): busy}), model = "org/repo", kind = "llm")+ joined = {"accepted": False, "attached": True, "state": "running"}+ assert start(fake_studio({("POST", START): joined}), model = "org/repo", kind = "llm").attached++[email protected]("kind, prefix", [("image", "images"), ("video", "video")])+def test_diffusion_stages_each_plan_entry_scoped(kind, prefix):+ listing = {+ "default_variant": "Q4_0",+ "variants": [{"quant": "Q4_0", "filename": "flux-q4.gguf"}],+ }+ studio = fake_studio(+ {+ ("GET", "/api/hub/gguf-variants"): listing,+ ("POST", f"/api/inference/{prefix}/download-plan"): PLAN,+ ("POST", START): STARTED,+ }+ )+ ref = start(studio, model = FLUX, kind = kind, hf_token = "hf_x")+ assert bodies(studio, f"/api/inference/{prefix}/download-plan") == [+ {+ "model_path": FLUX,+ "hf_token": "hf_x",+ "gguf_filename": "flux-q4.gguf",+ "model_kind": "gguf",+ }+ ]+ scoped = {"scope_id": "diffusion", "transport_mode": "auto"}+ assert bodies(studio, START) == [+ {"repo_id": FLUX, **scoped, "files": ["flux-q4.gguf"]},+ {"repo_id": VAE, **scoped, "files": ["vae/a.safetensors"]},+ ]+ assert ref.id == FLUX_ID+ assert model_downloads.parse_id(ref.id) == [(FLUX, "@diffusion"), (VAE, "@diffusion")]+++ "plan, match",+ [+ ({"incompatible_reason": "FLUX.2 GGUF needs the matching base"}, "matching base"),+ ({**PLAN, "plan_failed": True}, "could not list the files"),+ ],+)+def test_a_refused_plan_never_downloads(plan, match):+ studio = fake_studio({("POST", "/api/inference/images/download-plan"): plan}, fallback = STARTED)+ with pytest.raises(ToolError, match = match):+ start(studio, model = "org/flux", kind = "image")+ assert bodies(studio, START) == []+++def test_stt_downloads_through_its_own_route_and_has_no_id():+ done = {"downloading": False, "completed_download_ids": ["d1"]}+ status = sequence(+ {"transformers": stt_state()},+ {"transformers": stt_state(downloaded = [WHISPER], download = done)},+ )+ studio = fake_studio(+ {+ ("GET", "/api/inference/audio/stt/status"): status,+ ("POST", "/api/inference/audio/stt/download"): {"download_id": "d1"},+ }+ )+ ref = start(studio, model = WHISPER, kind = "stt")+ assert (ref.id, ref.status) == (None, "completed")+ assert bodies(studio, "/api/inference/audio/stt/download") == [+ {"model": WHISPER, "engine": "transformers"}+ ]+ cached = {"transformers": stt_state(downloaded = [WHISPER])}+ studio = fake_studio({("GET", "/api/inference/audio/stt/status"): cached})+ assert start(studio, model = WHISPER, kind = "stt").status == "completed"+ assert bodies(studio, "/api/inference/audio/stt/download") == []+++def test_parse_id_limits():+ assert model_downloads.parse_id("a/b,a/b::Q4_K_M") == [("a/b", None), ("a/b", "Q4_K_M")]+ assert len(model_downloads.parse_id(",".join(["a/b"] * 16))) == 16+ for bad in (",".join(["a/b"] * 17), "", "::Q4", "a/b,", " , a/b"):+ with pytest.raises(ToolError):+ model_downloads.parse_id(bad)+++ "states, expected",+ [+ (["complete", "error", "cancelling"], "failed"),+ (["running", "cancelling"], "cancelling"),+ (["complete", "running", "cancelled"], "running"),+ (["complete", "cancelled", "idle"], "cancelled"),+ (["complete", "idle"], "idle"),+ (["complete", "complete"], "completed"),+ ],+)+def test_status_aggregates_every_part(states, expected):+ answers = {+ f"org/r{i}": {"state": s, "error": s == "error" and "disk full" or None}+ for i, s in enumerate(states)+ }+ studio = fake_studio({("GET", STATUS): lambda r, b: answers[r.query_params["repo_id"]]})+ job = run(studio, model_downloads.status, ",".join(f"{r}::@diffusion" for r in answers))+ assert (job.kind, job.status, job.download.status) == ("download", expected, expected)+ assert job.error == ("disk full" if "error" in states else None)+ assert job.progress_percent is None+ assert {q["gguf_variant"] for q in queries(studio, STATUS)} == {"@diffusion"}+++def test_a_single_safetensors_part_reports_percent_and_a_404_reads_idle():+ studio = fake_studio(+ {+ ("GET", STATUS): {"state": "running"},+ ("GET", "/api/hub/download-progress"): {"progress": 0.25},+ }+ )+ job = run(studio, model_downloads.status, "unsloth/Qwen3-0.6B")+ assert (job.status, job.progress_percent) == ("running", 25.0)+ assert queries(studio, STATUS) == [{"repo_id": "unsloth/Qwen3-0.6B", "gguf_variant": ""}]+ assert (+ run(fake_studio({("GET", STATUS): NOT_YOURS}), model_downloads.status, "o/r").status+ == "idle"+ )+++def test_cancel_posts_every_part_and_only_cancelling_counts_as_stopped():+ studio = fake_studio({("POST", CANCEL): sequence({"state": "idle"}, {"state": "cancelling"})})+ assert run(studio, model_downloads.cancel_parts, FLUX_ID) == (True, "cancelling")+ assert bodies(studio, CANCEL) == [+ {"repo_id": FLUX, "gguf_variant": "@diffusion"},+ {"repo_id": VAE, "gguf_variant": "@diffusion"},+ ]+ studio = fake_studio({("POST", CANCEL): {"job_key": "k", "state": "idle"}})+ assert run(studio, model_downloads.cancel_parts, "a/x") == (False, "idle")+ assert bodies(studio, CANCEL) == [{"repo_id": "a/x"}]+++def test_the_id_keeps_each_start_generation_and_cancel_sends_it():+ studio = fake_studio({("POST", START): {**STARTED, "generation": 7}})+ ref = start(studio, model = "org/repo", kind = "llm", variant = "Q8_0")+ assert ref.id == "org/repo::Q8_0#7"+ assert model_downloads.parse_id(ref.id) == [("org/repo", "Q8_0")]+ studio = fake_studio({("POST", CANCEL): {"state": "cancelling"}})+ run(studio, model_downloads.cancel_parts, f"{ref.id},{VAE}::@diffusion")+ assert bodies(studio, CANCEL) == [+ {"repo_id": "org/repo", "gguf_variant": "Q8_0", "generation": 7},+ {"repo_id": VAE, "gguf_variant": "@diffusion"},+ ]+++def test_status_of_a_replaced_run_names_the_newer_one():+ studio = fake_studio({("GET", STATUS): {"state": "running", "generation": 8}})+ job = run(studio, model_downloads.status, "org/repo::Q8_0#7")+ assert job.status == "idle"+ assert 'id="org/repo::Q8_0#8"' in job.error+ assert run(studio, model_downloads.status, "org/repo::Q8_0#8").status == "running"+ # After a restart the numbers start again: a lower generation is another run too.+ studio = fake_studio({("GET", STATUS): {"state": "running", "generation": 1}})+ assert run(studio, model_downloads.status, "org/repo::Q8_0#7").status == "idle"+ # A registry that pruned the run reads generation 0: that is not another run.+ studio = fake_studio({("GET", STATUS): {"state": "idle", "generation": 0}})+ job = run(studio, model_downloads.status, "org/repo::Q8_0#7")+ assert (job.status, job.error) == ("idle", None)+++def test_image_options_go_into_the_staged_plan():+ plan = "/api/inference/images/download-plan"+ studio = fake_studio({("POST", plan): PLAN, ("POST", START): STARTED})+ start(studio, model = "org/FLUX", kind = "image", knobs = {"text_encoder_quant": "fp8"})+ assert bodies(studio, plan)[0]["text_encoder_quant"] == "fp8"+++def test_native_tts_stages_its_audio_plan_with_the_codec_repos():+ higgs, codec = "bosonai/higgs-audio-v2", "bosonai/higgs-audio-v2-tokenizer"+ plan = {+ "entries": [+ {"repo_id": higgs, "files": ["model.safetensors"], "checkpoint": True},+ {"repo_id": codec, "files": ["model.pth"]},+ ]+ }+ audio_plan = "/api/inference/audio/download-plan"+ studio = fake_studio({("POST", audio_plan): plan, ("POST", START): STARTED})+ ref = start(studio, model = higgs, kind = "tts")+ assert bodies(studio, audio_plan) == [{"model_path": higgs}]+ assert [(b["repo_id"], b["scope_id"]) for b in bodies(studio, START)] == [+ (higgs, "audio"),+ (codec, "audio"),+ ]+ assert ref.id == f"{higgs}::@audio,{codec}::@audio"+ staged = [(higgs, "@audio"), (codec, "@audio")]+ # tts and audio load the same native repos, so either kind waits on the prefetch.+ assert model_downloads.keys_for(make_caller(), "tts", higgs, None) == staged+ assert model_downloads.keys_for(make_caller(), "audio", higgs, None) == staged+ # Without one, the repo or the Audio page's staged download of it.+ assert model_downloads.keys_for(make_caller(), "tts", "org/other-tts", None) == [+ ("org/other-tts", None),+ ("org/other-tts", "@audio"),+ ]+++def test_a_failed_part_stops_the_parts_this_call_started():+ refused = JSONResponse({"detail": "scope_file_mismatch"}, status_code = 409)+ studio = fake_studio(+ {+ ("POST", "/api/inference/images/download-plan"): PLAN,+ ("POST", START): sequence({**STARTED, "generation": 3}, refused),+ ("POST", CANCEL): {"state": "cancelling"},+ }+ )+ with pytest.raises(ToolError):+ start(studio, model = "org/FLUX", kind = "image")+ assert bodies(studio, CANCEL) == [+ {"repo_id": FLUX, "gguf_variant": "@diffusion", "generation": 3}+ ]+ assert model_downloads._remembered == {}+++def test_cancel_stops_every_part_before_raising_a_refusal():+ owned = JSONResponse({"detail": "A load owns this download"}, status_code = 409)+ studio = fake_studio({("POST", CANCEL): sequence(owned, {"state": "cancelling"})})+ with pytest.raises(ToolError, match = "A load owns"):+ run(studio, model_downloads.cancel_parts, FLUX_ID)+ assert len(bodies(studio, CANCEL)) == 2+++def test_repo_variant_shorthand_downloads_and_waits_on_the_variant():+ studio = fake_studio({("POST", START): STARTED})+ assert start(studio, model = f"{GGUF}:Q8_0", kind = "llm").id == f"{GGUF}::Q8_0"+ assert bodies(studio, START)[0]["repo_id"] == GGUF+ caller = make_caller()+ assert model_downloads.keys_for(caller, "llm", f"{GGUF}:Q8_0", None) == [(GGUF, "Q8_0")]+ # A plain load reads the default variant, not the one download_model staged last.+ assert model_downloads.keys_for(caller, "llm", GGUF, None) == [(GGUF, None)]+++def wait(studio, **kwargs):+ ctx = Ctx()+ args = {"kind": "llm", "variant": None, "budget_s": 5.0, **kwargs}+ run(studio, model_downloads.wait_for_managed, ctx, **args)+ return ctx+++def test_wait_returns_once_the_download_finishes():+ states = sequence({"state": "running"}, {"state": "running"}, {"state": "complete"})+ studio = fake_studio({("GET", STATUS): states})+ ctx = wait(studio, model = "org/repo", variant = "Q4_K_M")+ assert queries(studio, STATUS) == [{"repo_id": "org/repo", "gguf_variant": "Q4_K_M"}] * 3+ follow = 'get_job(kind="download", id="org/repo::Q4_K_M")'+ assert ctx.messages == [f"Waiting for Unsloth Studio's download; follow it with {follow}"] * 2+++def test_wait_with_no_budget_left_tells_the_agent_to_follow_the_download():+ studio = fake_studio(+ {("GET", STATUS): {"state": "running"}, ("GET", "/api/hub/gguf-variants"): VARIANTS}+ )+ with pytest.raises(ToolError) as raised:+ wait(studio, model = GGUF, budget_s = 0)+ assert str(raised.value) == (+ f"Unsloth Studio is still downloading {GGUF}. "+ f'Follow it with get_job(kind="download", id="{GGUF}::Q4_K_M"), then call load_model again.'+ )++[email protected]("answer", [NOT_YOURS, JSONResponse({"detail": "boom"}, status_code = 500)])+def test_wait_proceeds_when_the_download_is_not_readable(answer):+ wait(fake_studio({("GET", STATUS): answer}), model = "org/repo", budget_s = 0)+++def test_wait_skips_stt_and_local_paths():+ studio = fake_studio(fallback = {"state": "running"})+ wait(studio, model = WHISPER, kind = "stt", budget_s = 0)+ wait(studio, model = "/srv/outputs/qwen-lora", budget_s = 0)+ assert studio.state.calls == []+++def test_wait_reads_the_parts_download_model_staged_for_this_account():+ studio = fake_studio(+ {+ ("POST", "/api/inference/images/download-plan"): PLAN,+ ("POST", START): STARTED,+ ("GET", STATUS): {"state": "complete"},+ }+ )+ start(studio, model = "org/FLUX", kind = "image")+ staged = [(FLUX, "@diffusion"), (VAE, "@diffusion")]+ keys_for = model_downloads.keys_for+ assert keys_for(make_caller(), "image", "ORG/flux", None) == staged+ assert keys_for(make_caller(account_id = "b"), "image", "org/FLUX", None) == [+ ("org/FLUX", "@diffusion")+ ]+ wait(studio, model = "org/FLUX", kind = "image", budget_s = 0)+ assert [q["repo_id"] for q in queries(studio, STATUS)] == [FLUX, VAE]+++# The tools over MCP: download_model, get_job(kind="download") and cancel(kind="model_download").+TOOL_PAYLOADS = {+ ("GET", "/api/hub/gguf-variants"): VARIANTS,+ ("POST", START): STARTED,+ ("GET", STATUS): {"state": "error", "error": "401 gated repo", "generation": 1, "attempt": 1},+ ("POST", CANCEL): {"job_key": "unsloth/qwen3-0.6b-gguf::q4_k_m", "state": "cancelling"},+}+++def test_download_model_returns_the_id_get_job_and_cancel_take(monkeypatch):+ result, studio = run_tool(monkeypatch, TOOL_PAYLOADS, "download_model", {"model": GGUF})+ ref = result["structuredContent"]+ assert ref["id"] == f"{GGUF}::Q4_K_M" and ref["status"] == "running"+ assert bodies(studio, START) == [+ {"repo_id": GGUF, "transport_mode": "auto", "gguf_variant": "Q4_K_M"}+ ]+ job, studio = run_tool(+ monkeypatch, TOOL_PAYLOADS, "get_job", {"kind": "download", "id": ref["id"]}+ )+ assert job["structuredContent"]["status"] == "failed"+ assert job["structuredContent"]["error"] == "401 gated repo"+ assert queries(studio, STATUS) == [{"repo_id": GGUF, "gguf_variant": "Q4_K_M"}]+ stopped, studio = run_tool(+ monkeypatch, TOOL_PAYLOADS, "cancel", {"kind": "model_download", "id": ref["id"]}+ )+ assert stopped["structuredContent"]["cancelled"] is True+ assert bodies(studio, CANCEL) == [{"repo_id": GGUF, "gguf_variant": "Q4_K_M"}]+++def test_get_job_download_needs_the_id(monkeypatch):+ result, studio = run_tool(monkeypatch, TOOL_PAYLOADS, "get_job", {"kind": "download"})+ assert result["isError"] is True and "download_model" in result["content"][0]["text"]+ assert studio.state.calls == []+++def test_a_second_media_prefetch_keeps_the_first_ones_parts():+ plan = "/api/inference/images/download-plan"+ second = {"entries": [{"repo_id": "org/te-int8", "files": ["te.safetensors"]}]}+ studio = fake_studio({("POST", plan): sequence(PLAN, second), ("POST", START): STARTED})+ start(studio, model = "org/FLUX", kind = "image", knobs = {"text_encoder_quant": "fp8"})+ start(studio, model = "org/FLUX", kind = "image", knobs = {"text_encoder_quant": "int8"})+ assert model_downloads.keys_for(make_caller(), "image", "org/FLUX", None) == [+ (FLUX, "@diffusion"),+ (VAE, "@diffusion"),+ ("org/te-int8", "@diffusion"),+ ]+++def test_two_ref_handles_are_two_models():+ assert not loading._same_id("ref:aaa", "ref:bbb")+ assert loading._same_id("ref:aaa", "ref:aaa")+++def test_a_stalled_status_read_is_no_wait(monkeypatch):+ from .mcp_harness import slow++ monkeypatch.setattr(model_downloads, "READ_TIMEOUT_S", 0.05)+ studio = fake_studio({("GET", STATUS): slow({"state": "running"}, 2.0)})+ ctx = wait(studio, model = "org/repo", variant = "Q4_K_M", budget_s = 5.0)+ assert ctx.messages == []+++def test_repo_variant_shorthand_for_speech_waits_on_the_variant():+ assert model_downloads.keys_for(make_caller(), "tts", "org/speech:Q4_K_M", None) == [+ ("org/speech", "Q4_K_M")+ ]+++def test_a_gguf_repo_is_known_by_its_listing_not_its_name():+ studio = fake_studio({("GET", "/api/hub/gguf-variants"): VARIANTS, ("POST", START): STARTED})+ assert start(studio, model = "org/quants", kind = "llm").id == "org/quants::Q4_K_M"+++def test_a_speech_repo_with_variants_downloads_one():+ studio = fake_studio({("GET", "/api/hub/gguf-variants"): VARIANTS, ("POST", START): STARTED})+ assert start(studio, model = "org/speech", kind = "tts").id == "org/speech::Q4_K_M"diff --git a/studio/backend/tests/test_mcp_tools_jobs.py b/studio/backend/tests/test_mcp_tools_jobs.pyindex a4981c451d5..bf877c77aa1 100644--- a/studio/backend/tests/test_mcp_tools_jobs.py+++ b/studio/backend/tests/test_mcp_tools_jobs.py@@ -190,7 +190,7 @@ SCHEMA = [("parameters/properties/wait_s/maximum", 240),("parameters/properties/kind/enum",- ["video", "recipe", "export", "training", "diffusion_training", "load"],+ ["video", "recipe", "export", "training", "diffusion_training", "load", "download"],),("output_schema/type", "object"),]diff --git a/studio/backend/tests/test_mcp_tools_placement.py b/studio/backend/tests/test_mcp_tools_placement.pyindex cfc0a6a0582..743349b499d 100644--- a/studio/backend/tests/test_mcp_tools_placement.py+++ b/studio/backend/tests/test_mcp_tools_placement.py@@ -8,7 +8,7 @@ import asyncioimport pytestfrom fastapi.responses import JSONResponse-from studio_mcp import forward+from studio_mcp import forward, model_downloadsfrom .mcp_harness import ( # noqa: F401bodies,@@ -259,7 +259,21 @@ def test_a_partial_variant_is_refused(monkeypatch):def test_a_variant_unsloth_studio_is_downloading_is_not_refused(monkeypatch):# The real allowlist: download-status is forwarded, so a managed download in flight is seen.- result, _studio, sent = _load(monkeypatch, {"model": QWEN}, _partial_routes("running"))+ # load_model waits for that download first (K16 guard 2), so let it finish.+ monkeypatch.setattr(model_downloads, "WAIT_INTERVAL_S", 0.01)+ monkeypatch.setattr(model_downloads, "_remembered", model_downloads.OrderedDict())+ routes = _partial_routes("running")+ routes[("GET", "/api/hub/download-status")] = sequence(+ {"state": "running"}, {"state": "complete"}+ )+ # Once it finishes, the variant is on disk.+ partial = routes[("GET", "/api/hub/gguf-variants")]+ done = {+ **partial,+ "variants": [{**partial["variants"][0], "downloaded": True, "partial": False}],+ }+ routes[("GET", "/api/hub/gguf-variants")] = sequence(partial, done)+ result, _studio, sent = _load(monkeypatch, {"model": QWEN}, routes)assert result.get("isError") is not Trueassert len(sent) == 1@@ -402,9 +416,16 @@ def test_unload_all_still_frees_media_when_chat_status_cannot_be_read(monkeypatcassert ("POST", "/api/inference/images/unload") in [call[:2] for call in studio.state.calls]-def test_only_the_download_status_read_joins_the_allowlist():- assert "/api/hub/download-status" in forward.ALLOWED_PREFIXES- for path in ("/api/hub/download", "/api/hub/download/cancel", "/api/hub/download-progress"):+def test_only_the_download_manager_joins_the_allowlist():+ # download_model (#14107) forwards the whole download manager; nothing else under /api/hub.+ for path in (+ "/api/hub/download",+ "/api/hub/download-status",+ "/api/hub/download/cancel",+ "/api/hub/download-progress",+ ):+ assert path.startswith(forward.ALLOWED_PREFIXES)+ for path in ("/api/hub/cache", "/api/hub/models", "/api/hub/token"):assert not path.startswith(forward.ALLOWED_PREFIXES)diff --git a/studio/backend/tests/test_mcp_tools_plan_load.py b/studio/backend/tests/test_mcp_tools_plan_load.pyindex fd50592cbca..e1737bd45a6 100644--- a/studio/backend/tests/test_mcp_tools_plan_load.py+++ b/studio/backend/tests/test_mcp_tools_plan_load.py@@ -58,7 +58,13 @@ def _world(},("GET", "/api/hub/gguf-variants"): VARIANTS,# The partial Q8_0 is one Unsloth Studio is still downloading, so a load waits on it.- ("GET", "/api/hub/download-status"): {"state": "running"},+ # Only that one: load_model waits on any other running download of what it loads.+ ("GET", "/api/hub/download-status"): lambda request, body: {+ "state": "running"+ if (request.query_params.get("repo_id"), request.query_params.get("gguf_variant"))+ == (QWEN, "Q8_0")+ else "idle"+ },("POST", "/api/inference/estimate-memory"): {"available": True, "gpu_bytes": 1234},("POST", "/api/inference/images/download-plan"): {"entries": [], "total_bytes": 9000},}diff --git a/studio/backend/tests/test_mcp_tools_training.py b/studio/backend/tests/test_mcp_tools_training.pyindex 3de42c36fb9..3233fc49a2e 100644--- a/studio/backend/tests/test_mcp_tools_training.py+++ b/studio/backend/tests/test_mcp_tools_training.py@@ -56,6 +56,7 @@ def test_start_forwards_the_config_as_sent_and_acknowledges_nothing(monkeypatch,"job_id": "job-7","status": "queued","message": "Queued",+ "config": None,"start_request_id": sent_id,}assert "x-unsloth-hf-token" not in studio.state.calls[0][2]@@ -79,6 +80,9 @@ def test_a_refused_start_is_acknowledged(monkeypatch, answer):def test_validate_only_starts_nothing(monkeypatch):+ monkeypatch.setattr(+ "utils.models.model_config.detect_audio_type_checked", lambda *a, **k: (None, True)+ )result, studio = _start(monkeypatch, {"config": CONFIG, "validate_only": True})assert result["structuredContent"]["status"] == "valid"assert result["structuredContent"]["job_id"] is None@@ -91,6 +95,7 @@ def test_kind_routes_to_the_matching_start_route(monkeypatch):"job_id": "diff-1","status": "queued","message": None,+ "config": None,"start_request_id": None,}assert "/srv" not in json.dumps(result)diff --git a/studio/backend/tests/test_mcp_tools_training_validate.py b/studio/backend/tests/test_mcp_tools_training_validate.pynew file mode 100644index 00000000000..2d39d3aa18b--- /dev/null+++ b/studio/backend/tests/test_mcp_tools_training_validate.py@@ -0,0 +1,202 @@+# 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 json++import pytest++from core.inference.audio_cpp_models import AUDIO_CPP_REPO+from core.inference.native_audio import NATIVE_AUDIO_MODEL_IDS++from .mcp_harness import CONFIG, DIFFUSION, SENTINEL_ROOTS, poison, run_tool++TRAINABLE = "Trainable text-to-speech models: unsloth/orpheus-3b-0.1-ft, sesame/csm-1b"+++def _detect(monkeypatch, answer):+ seen = []++ def detect(+ name,+ hf_token = None,+ **_kw,+ ):+ seen.append((name, hf_token))+ if isinstance(answer, Exception):+ raise answer+ return answer++ monkeypatch.setattr("utils.models.model_config.detect_audio_type_checked", detect)+ return seen+++def _validate(+ monkeypatch,+ config,+ kind = "llm",+):+ result, studio = run_tool(+ monkeypatch, {}, "start_training", {"config": config, "kind": kind, "validate_only": True}+ )+ assert studio.state.calls == []+ return result+++def test_a_text_model_passes_with_its_resolved_config(monkeypatch):+ seen = _detect(monkeypatch, (None, True))+ result = _validate(monkeypatch, CONFIG)+ out = result["structuredContent"]+ assert out["status"] == "valid" and out["job_id"] is None+ assert out["message"] == "The config is valid; nothing was started."+ config = out["config"]+ assert config["model_name"] == "unsloth/Qwen3-0.6B"+ assert config["max_steps"] == 30 and config["is_dataset_audio"] is False+ # The config's hf_token is used for detection, and never echoed; no start id is made up.+ assert seen == [("unsloth/Qwen3-0.6B", "hf_cfg")]+ assert "hf_token" not in config and "start_request_id" not in config+ assert "hf_cfg" not in json.dumps(result)+++def test_the_echo_carries_no_poisoned_path_or_secret(monkeypatch):+ _detect(monkeypatch, (None, True))+ config = {+ **CONFIG,+ "project_name": "demo",+ "wandb_token": "wandb-secret",+ "custom_format_mapping": poison({"question": "user"}),+ "tensorboard_dir": f"{SENTINEL_ROOTS[0]}/tb",+ "resume_from_checkpoint": f"{SENTINEL_ROOTS[1]}\\ckpt",+ "wandb_project": poison("proj"),+ }+ result = _validate(monkeypatch, config)+ text = json.dumps(result)+ for root in SENTINEL_ROOTS:+ assert root not in text and root.replace("\\", "\\\\") not in text+ assert "wandb-secret" not in text and "hf_cfg" not in text+ shown = result["structuredContent"]["config"]+ assert "tensorboard_dir" not in shown and "resume_from_checkpoint" not in shown+ assert shown["project_name"] == "demo"+ assert shown["wandb_project"].startswith("proj")+++def test_a_local_model_path_is_not_echoed(monkeypatch):+ _detect(monkeypatch, (None, True))+ result = _validate(monkeypatch, {**CONFIG, "model_name": f"{SENTINEL_ROOTS[0]}/models/qwen"})+ assert "model_name" not in result["structuredContent"]["config"]+ assert SENTINEL_ROOTS[0] not in json.dumps(result)+++def test_a_codec_tts_model_gets_is_dataset_audio(monkeypatch):+ _detect(monkeypatch, ("snac", True))+ result = _validate(monkeypatch, {**CONFIG, "model_name": "unsloth/orpheus-3b-0.1-ft"})+ out = result["structuredContent"]+ assert out["config"]["is_dataset_audio"] is True+ assert "is_dataset_audio is set to true" in out["message"]+++def test_an_explicit_is_dataset_audio_needs_no_note(monkeypatch):+ _detect(monkeypatch, ("csm", True))+ result = _validate(+ monkeypatch, {**CONFIG, "model_name": "sesame/csm-1b", "is_dataset_audio": True}+ )+ out = result["structuredContent"]+ assert out["config"]["is_dataset_audio"] is True+ assert out["message"] == "The config is valid; nothing was started."+++ "model_name, extra, answer, message",+ [+ ("unsloth/Qwen3-0.6B-GGUF", {}, None, "GGUF models are inference-only"),+ ("unsloth/Qwen3-0.6B", {"model_format": "gguf"}, None, "GGUF models are inference-only"),+ (+ f"{AUDIO_CPP_REPO}/Qwen3-TTS-12Hz-1.7B-CustomVoice-GGUF",+ {},+ None,+ "runs on audio.cpp, which Unsloth Studio can run but not train.",+ ),+ (+ "someone/audio-cpp-tts",+ {},+ ("audiocpp_tts", True),+ "runs on audio.cpp, which Unsloth Studio can run but not train.",+ ),+ (+ next(iter(NATIVE_AUDIO_MODEL_IDS)),+ {},+ RuntimeError("no network"),+ "is a text-to-speech model Unsloth Studio can run but not train.",+ ),+ (+ "someone/higgs-finetune",+ {},+ ("higgs_tts2", True),+ "is a text-to-speech model Unsloth Studio can run but not train.",+ ),+ ],+)+def test_untrainable_models_are_refused(monkeypatch, model_name, extra, answer, message):+ seen = _detect(monkeypatch, answer or AssertionError("detection should not run"))+ result = _validate(monkeypatch, {**CONFIG, "model_name": model_name, **extra})+ assert result["isError"] is True+ text = result["content"][0]["text"]+ assert message in text and TRAINABLE in text+ # Names and curated ids are refused without asking the Hub.+ if answer is None or isinstance(answer, Exception):+ assert seen == []+++def test_a_failed_detection_is_no_verdict(monkeypatch):+ seen = _detect(monkeypatch, OSError("hub unreachable"))+ result = _validate(monkeypatch, CONFIG)+ assert result.get("isError") is not True+ assert result["structuredContent"]["status"] == "valid"+ assert result["structuredContent"]["config"]["is_dataset_audio"] is False+ assert seen == [("unsloth/Qwen3-0.6B", "hf_cfg")]+++def test_diffusion_echo_drops_folders(monkeypatch):+ _detect(monkeypatch, AssertionError("diffusion runs no detection"))+ result = _validate(monkeypatch, {**DIFFUSION, "hf_token": "hf_x"}, kind = "diffusion")+ out = result["structuredContent"]+ assert out["status"] == "valid"+ shown = out["config"]+ assert shown["base_model"] == DIFFUSION["base_model"] and shown["train_steps"] == 500+ assert not {"data_dir", "output_dir", "hf_token"} & set(shown)++[email protected]("answer", [("higgs_tts2", True), ("snac", True)])+def test_a_ref_model_name_never_comes_back_as_its_path(monkeypatch, answer):+ from hub.utils.host_paths import cache_reference++ seen = _detect(monkeypatch, answer)+ ref = cache_reference(f"{SENTINEL_ROOTS[0]}/models/my-tts")+ result = _validate(monkeypatch, {**CONFIG, "model_name": ref})+ # The validator resolved the ref for detection, but the text names the ref.+ assert seen and seen[0][0] == f"{SENTINEL_ROOTS[0]}/models/my-tts"+ text = json.dumps(result)+ assert SENTINEL_ROOTS[0] not in text and "my-tts" not in text+ assert ref in text+++def test_a_real_start_sets_is_dataset_audio_for_codec_tts(monkeypatch):+ _detect(monkeypatch, ("snac", True))+ started = {"job_id": "job_1", "status": "queued"}+ # "false" validates to False, so the raw value can't decide whether to send the flag.+ config = {**CONFIG, "model_name": "unsloth/orpheus-3b-0.1-ft", "is_dataset_audio": "false"}+ result, studio = run_tool(+ monkeypatch, {("POST", "/api/train/start"): started}, "start_training", {"config": config}+ )+ assert result.get("isError") is not True, result+ (_method, _path, _headers, body) = next(+ c for c in studio.state.calls if c[1] == "/api/train/start"+ )+ assert json.loads(body)["is_dataset_audio"] is True+++def test_a_real_start_refuses_an_untrainable_tts_model_before_posting(monkeypatch):+ _detect(monkeypatch, ("higgs_tts2", True))+ config = {**CONFIG, "model_name": "someone/higgs-finetune"}+ result, studio = run_tool(monkeypatch, {}, "start_training", {"config": config}, fallback = {})+ assert result["isError"] is True and TRAINABLE in result["content"][0]["text"]+ assert [c for c in studio.state.calls if c[1] == "/api/train/start"] == []diff --git a/studio/backend/tests/test_mcp_tools_video.py b/studio/backend/tests/test_mcp_tools_video.pyindex a8d91ed23cd..70dcd0e6723 100644--- a/studio/backend/tests/test_mcp_tools_video.py+++ b/studio/backend/tests/test_mcp_tools_video.py@@ -126,6 +126,7 @@ def test_a_completed_job_returns_its_thumbnail_and_a_link_never_the_mp4(monkeypa"thumbnail_inline": True,},"recipe": None,+ "download": None,"export": None,"jobs": None,}diff --git a/studio/backend/tests/test_mcp_train_to_use.py b/studio/backend/tests/test_mcp_train_to_use.pynew file mode 100644index 00000000000..2070995f73c--- /dev/null+++ b/studio/backend/tests/test_mcp_train_to_use.py@@ -0,0 +1,328 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""load_model(checkpoint=...) and load_model(export=...): the load goes out with a ref minted from the listed path, and the agent sees only the name it asked for."""++import asyncio+import json++import pytest++from hub.utils.host_paths import cache_reference, resolve_host_path_reference+from studio_mcp import checkpoints, trained_models++from .mcp_harness import OUT, RUN_CHECKPOINTS, bodies, make_caller, run_tool, sequence++EXPORTS = "/srv/unsloth/exports"+LORAS = {+ "outputs_dir": OUT,+ "loras": [+ {"display_name": "qwen-lora", "adapter_path": f"{OUT}/qwen-lora", "source": "training"},+ {+ "display_name": "qwen-lora / adapter",+ "adapter_path": f"{EXPORTS}/qwen-lora/adapter",+ "source": "exported",+ "export_type": "lora",+ },+ {+ "display_name": "qwen-lora / merged",+ "adapter_path": f"{EXPORTS}/qwen-lora/merged",+ "source": "exported",+ "export_type": "merged",+ },+ {+ "display_name": "qwen-GGUF",+ "adapter_path": f"{EXPORTS}/qwen-GGUF/qwen-Q8_0.gguf",+ "source": "exported",+ "export_type": "gguf",+ },+ ],+}+++def _routes(evicted = ()):+ def load(request, body):+ sent = json.loads(body)["model_path"]+ return {"status": "loaded", "model": sent, "display_name": "leaf", "evicted": list(evicted)}++ return {+ ("GET", "/api/models/checkpoints"): RUN_CHECKPOINTS,+ ("GET", "/api/models/loras"): LORAS,+ ("POST", "/api/inference/load"): load,+ ("GET", "/api/inference/load-progress"): {},+ ("GET", "/api/models/download-progress"): {},+ ("GET", "/api/inference/status"): {"loaded": [], "serving": [], "serving_checkpoints": []},+ }+++def _load(+ monkeypatch,+ args,+ evicted = (),+):+ result, studio = run_tool(monkeypatch, _routes(evicted), "load_model", args)+ assert result.get("isError") is not True, result+ text = json.dumps(result)+ assert "/srv" not in text and "ref:" not in text+ (body,) = bodies(studio, "/api/inference/load")+ return result["structuredContent"], body, studio+++ "name,path",+ [+ ("qwen-lora", f"{OUT}/qwen-lora"),+ ("qwen-lora/checkpoint-30", f"{OUT}/qwen-lora/checkpoint-30"),+ ],+)+def test_a_checkpoint_loads_by_ref_and_reports_its_name(monkeypatch, name, path):+ output, body, _studio = _load(monkeypatch, {"checkpoint": name})+ assert body["model_path"] == cache_reference(path)+ assert resolve_host_path_reference(body["model_path"]) == path+ assert output["model"] == name and output["kind"] == "llm"+++def test_an_evicted_checkpoint_is_named(monkeypatch):+ evicted = [cache_reference(f"{OUT}/qwen-lora"), "unsloth/Qwen3-0.6B"]+ output, _body, _studio = _load(+ monkeypatch, {"checkpoint": "qwen-lora-2/checkpoint-30"}, evicted+ )+ assert output["evicted"] == ["qwen-lora", "unsloth/Qwen3-0.6B"]+++ "args,path,variant",+ [+ ({"export": "qwen-lora/adapter"}, f"{EXPORTS}/qwen-lora/adapter", None),+ ({"export": "QWEN-LORA/merged"}, f"{EXPORTS}/qwen-lora/merged", None),+ # The file name gives the quantization, so the folder loads with it as the variant.+ ({"export": "qwen-GGUF"}, f"{EXPORTS}/qwen-GGUF", "Q8_0"),+ ({"export": "qwen-GGUF", "variant": "Q4_K_M"}, f"{EXPORTS}/qwen-GGUF", "Q4_K_M"),+ ],+)+def test_an_export_loads_by_ref_and_reports_its_name(monkeypatch, args, path, variant):+ output, body, _studio = _load(monkeypatch, args)+ assert resolve_host_path_reference(body["model_path"]) == path+ assert body.get("gguf_variant") == variant+ assert output["model"] == args["export"]+++def test_is_lora_follows_the_listing(monkeypatch):+ async def fake_route(method, path, **kwargs):+ return RUN_CHECKPOINTS if path == "/api/models/checkpoints" else LORAS++ monkeypatch.setattr(checkpoints, "route_json", fake_route)+ monkeypatch.setattr(trained_models, "route_json", fake_route)+ caller = make_caller()++ async def resolved():+ return [+ await trained_models.resolve_checkpoint(caller, "qwen-lora/checkpoint-30"),+ await trained_models.resolve_checkpoint(caller, "qwen-lora-2/checkpoint-30"),+ *[+ await trained_models.resolve_export(caller, name, "Q4_K_M")+ for name in ("qwen-lora/adapter", "qwen-lora/merged", "qwen-GGUF")+ ],+ ]++ found = asyncio.run(resolved())+ # qwen-lora-2 has no peft_type: a full finetune, not a LoRA.+ assert [t.is_lora for t in found] == [True, False, True, False, False]+ assert [t.gguf_variant for t in found] == [None, None, None, None, "Q4_K_M"]+++ "args,message",+ [+ ({"checkpoint": "nope"}, "No checkpoint named nope. Available: qwen-lora, qwen-lora-2/"),+ (+ {"export": "nope"},+ 'has two levels, such as "<run>/<name>". Available: qwen-GGUF, qwen-lora/',+ ),+ ({"export": "qwen-lora"}, "No export named qwen-lora."),+ ],+)+def test_an_unknown_name_lists_what_there_is(monkeypatch, args, message):+ result, studio = run_tool(monkeypatch, _routes(), "load_model", args)+ assert result["isError"] is True+ assert message in result["content"][0]["text"]+ assert "/srv" not in result["content"][0]["text"]+ assert bodies(studio, "/api/inference/load") == []+++ "args,message",+ [+ ({}, "load_model needs exactly one of model, checkpoint or export."),+ ({"model": "m", "checkpoint": "qwen-lora"}, "needs exactly one of"),+ ({"checkpoint": "qwen-lora", "export": "qwen-GGUF"}, "needs exactly one of"),+ *[+ ({key: "qwen-lora", "kind": kind}, 'use kind "llm", "tts" or "audio".')+ for key in ("checkpoint", "export")+ for kind in ("image", "video", "stt")+ ],+ ],+)+def test_a_refused_load_reaches_no_route(monkeypatch, args, message):+ result, studio = run_tool(monkeypatch, {}, "load_model", args, fallback = {})+ assert result["isError"] is True+ assert message in result["content"][0]["text"]+ assert studio.state.calls == []++[email protected]("kind", ["tts", "audio"])+def test_a_checkpoint_keeps_the_audio_kind(monkeypatch, kind):+ output, _body, _studio = _load(monkeypatch, {"checkpoint": "qwen-lora", "kind": kind})+ assert output["kind"] == kind and output["model"] == "qwen-lora"+++def test_a_plain_model_load_lists_nothing(monkeypatch):+ output, body, studio = _load(monkeypatch, {"model": "unsloth/Qwen3-0.6B"})+ assert body["model_path"] == "unsloth/Qwen3-0.6B" and output["model"] == "unsloth/Qwen3-0.6B"+ assert not {"/api/models/checkpoints", "/api/models/loras"} & {c[1] for c in studio.state.calls}+++def test_a_gguf_export_loads_on_the_cpu_as_gguf(monkeypatch):+ _output, body, _studio = _load(monkeypatch, {"export": "qwen-GGUF", "device": "cpu"})+ assert body["gguf_variant"] == "Q8_0"+ assert (body["gpu_layers"], body["speculative_type"]) == (0, "off")+++def test_a_gguf_export_with_no_quant_in_its_name_needs_a_variant_to_place(monkeypatch):+ unnamed = {+ "display_name": "assistant",+ "adapter_path": f"{EXPORTS}/assistant/model.gguf",+ "source": "exported",+ "export_type": "gguf",+ }+ routes = {**_routes(), ("GET", "/api/models/loras"): {**LORAS, "loras": [unnamed]}}+ args = {"export": "assistant", "device": "cpu"}+ result, studio = run_tool(monkeypatch, routes, "load_model", args)+ assert result["isError"] is True+ assert "Pass variant" in result["content"][0]["text"]+ assert bodies(studio, "/api/inference/load") == []+++def test_a_checkpoint_is_not_placed_on_the_cpu(monkeypatch):+ result, studio = run_tool(+ monkeypatch, _routes(), "load_model", {"checkpoint": "qwen-lora", "device": "cpu"}+ )+ assert result["isError"] is True+ assert "device='cpu' needs a GGUF model" in result["content"][0]["text"]+ assert bodies(studio, "/api/inference/load") == []+++def test_a_load_that_outlasts_wait_s_is_named_in_its_job_result():+ from studio_mcp import loading+ from studio_mcp.outputs import LoadResult++ ref = cache_reference(f"{OUT}/qwen-lora")+ trained = trained_models.TrainedModel(+ name = "qwen-lora", ref = ref, is_lora = True, known = {ref: "qwen-lora"}+ )+ caller = make_caller()++ async def go():+ gate = asyncio.Event()++ async def run(_job):+ await gate.wait()+ return LoadResult(kind = "llm", model = ref, evicted = [ref])++ job = loading.LOADS.start(+ loading.LoadJob(job_id = "j-rename", account_id = caller.account_id), run+ )+ trained_models.rename_job(caller, "j-rename", trained)+ gate.set()+ await asyncio.wait({job.task})+ return job.result++ result = asyncio.run(go())+ assert (result.model, result.evicted) == ("qwen-lora", ["qwen-lora"])+++def test_an_evicted_gguf_export_is_named_by_its_folder(monkeypatch):+ async def resolved():+ caller = make_caller()+ return await trained_models.resolve_export(caller, "qwen-lora/adapter", None)++ async def fake_route(method, path, **kwargs):+ return LORAS++ monkeypatch.setattr(trained_models, "route_json", fake_route)+ trained = asyncio.run(resolved())+ assert trained.known[cache_reference(f"{EXPORTS}/qwen-GGUF")] == "qwen-GGUF"+++def test_a_checkpoint_load_names_an_evicted_export_and_back(monkeypatch):+ async def fake_route(method, path, **kwargs):+ return RUN_CHECKPOINTS if path == "/api/models/checkpoints" else LORAS++ monkeypatch.setattr(checkpoints, "route_json", fake_route)+ monkeypatch.setattr(trained_models, "route_json", fake_route)+ caller = make_caller()+ loaded = asyncio.run(trained_models.resolve_checkpoint(caller, "qwen-lora"))+ assert loaded.known[cache_reference(f"{EXPORTS}/qwen-lora/adapter")] == "qwen-lora/adapter"+ loaded = asyncio.run(trained_models.resolve_export(caller, "qwen-lora/adapter", None))+ assert loaded.known[cache_reference(f"{OUT}/qwen-lora")] == "qwen-lora"+++def test_a_stalled_listing_does_not_hold_the_call(monkeypatch):+ async def stalled(method, path, **kwargs):+ await asyncio.sleep(5)++ monkeypatch.setattr(checkpoints, "route_json", stalled)+ monkeypatch.setattr(trained_models, "RESOLVE_TIMEOUT_S", 0.05)++ async def go():+ import time+ return await trained_models.resolve_by(+ time.monotonic(),+ make_caller(),+ model = None,+ checkpoint = "qwen-lora",+ export = None,+ kind = "llm",+ variant = None,+ )++ with pytest.raises(Exception, match = "did not list its training runs"):+ asyncio.run(go())+++def test_a_trained_load_unloads_by_its_name(monkeypatch):+ ref = cache_reference(f"{OUT}/qwen-lora/checkpoint-30")+ unloaded = []++ def unload(request, body):+ unloaded.append(json.loads(body)["model_path"])+ return {"status": "unloaded"}++ status = sequence(+ {"loaded": [ref], "serving": [ref], "serving_checkpoints": [ref]},+ {"loaded": [], "serving": [], "serving_checkpoints": []},+ )+ routes = {+ **_routes(),+ ("GET", "/api/inference/status"): status,+ ("POST", "/api/inference/unload"): unload,+ }+ trained_models.remember_load(+ make_caller(),+ trained_models.TrainedModel(name = "qwen-lora/checkpoint-30", ref = ref, is_lora = True),+ )+ args = {"kind": "llm", "model": "qwen-lora/checkpoint-30"}+ result, _studio = run_tool(monkeypatch, routes, "unload_model", args)+ assert unloaded == [ref]+ out = result["structuredContent"]+ assert (out["model"], out["unloaded"]) == ("qwen-lora/checkpoint-30", True)+ assert "ref:" not in json.dumps(result)+++def test_a_plain_load_of_the_same_name_forgets_the_trained_one():+ caller = make_caller()+ trained = trained_models.TrainedModel(name = "gpt2", ref = "ref:abc", is_lora = True)+ trained_models.remember_load(caller, trained)+ assert trained_models.loaded_ref(caller, "gpt2") == "ref:abc"+ trained_models.forget_load(caller, "gpt2")+ assert trained_models.loaded_ref(caller, "gpt2") == "gpt2"