Skip to content

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.

Studio: let coding agents use Unsloth Studio over MCP with API keys (#13118)

Etherlaa7f76dcb953
diff --git a/studio/MCP.md b/studio/MCP.md
index 4f57bc43f47..c227dee8380 100644
--- a/studio/MCP.md
+++ b/studio/MCP.md
@@ -69,35 +69,242 @@ send an Unsloth API key as `Authorization: Bearer sk-unsloth-...`.
## Unsloth Studio's own MCP server
-Unsloth can expose a local MCP server so an MCP client can inspect models and
-GPU state, validate recipes, start or stop training, inspect recipe output, and
-export a loaded model.
+Unsloth Studio has its own MCP server at `/mcp/`. Coding agents such as Claude Code and
+Codex can use it to load models, chat, generate images, audio and video,
+transcribe, train and export. Every tool goes through Unsloth Studio's own routes as
+your API key, so it sees what that key may see and nothing more.
-The server is disabled by default. Enable it for a local Unsloth process with:
+### Turn it on
+
+The server is off by default. While it is off, `/mcp/` answers 404. Start Unsloth
+Studio with `UNSLOTH_STUDIO_ENABLE_MCP=1` to turn it on.
+
+The endpoint is `http://127.0.0.1:8888/mcp/` on the default port. Always use
+the trailing slash. Use your own address and port when they differ, for example
+the LAN address or the Cloudflare tunnel URL.
+
+### Authentication
+
+Every request needs an Unsloth Studio API key: `Authorization: Bearer sk-unsloth-…`.
+Create one in **Settings → API**. Unsloth Studio refuses everything else with 401:
+
+- no key, an empty key, or a placeholder key such as `not-needed`, even when
+ keyless API access is on;
+- a signed-in session token;
+- a revoked or expired key;
+- the keys Unsloth Studio mints for its own recipe and Deep Research workflows.
+
+A managed account's key works too. Its tools act for that account only.
+
+Unsloth Studio does not offer OAuth. The OAuth discovery paths answer 404, so clients
+that probe them fall back to the key.
+
+A browser page from another site gets 403 `Origin not allowed for Unsloth Studio MCP`.
+This also blocks browser-based MCP inspectors. Command-line agents send no
+Origin and are not affected.
+
+### Breaking changes
+
+The static `UNSLOTH_STUDIO_MCP_TOKEN` is retired. A request that sends it gets
+401 with this detail:
+
+```
+The MCP static token is no longer supported; use an Unsloth Studio API key (sk-unsloth-…)
+```
+
+If the variable is still set, Unsloth Studio logs one warning at startup. Unsloth Studio no
+longer refuses to start when the token is missing.
+
+The tools changed:
+
+| Old tool | New tool |
+|---|---|
+| `list_local_models` | `list_models` |
+| `get_training_status` | `studio_status` |
+| `stop_training` | `cancel` with `kind="training"` |
+| `validate_recipe` | `run_recipe` with `mode="validate"` |
+| `get_recipe_job_status`, `get_recipe_job_dataset` | `get_job` with `kind="recipe"` |
+| `load_checkpoint` and `export_gguf` | `export_model` |
+
+`studio_status` and `start_training` keep their names, but now run as your key.
+
+### Set up an agent
+
+Each one reads the key from the `UNSLOTH_API_KEY` environment variable, so set
+it before you start the agent. Replace `http://127.0.0.1:8888` with your own
+address.
+
+**Claude Code** (macOS or Linux):
+
+```bash
+claude mcp add --transport http unsloth-studio http://127.0.0.1:8888/mcp/ --header "Authorization: Bearer $UNSLOTH_API_KEY"
+```
+
+**Claude Code** (Windows PowerShell):
+
+```powershell
+claude mcp add --transport http unsloth-studio http://127.0.0.1:8888/mcp/ --header "Authorization: Bearer $env:UNSLOTH_API_KEY"
+```
+
+**OpenAI Codex**:
+
+```bash
+codex mcp add unsloth-studio --url http://127.0.0.1:8888/mcp/ --bearer-token-env-var UNSLOTH_API_KEY
+# Optional, for long jobs, in ~/.codex/config.toml under [mcp_servers.unsloth-studio]:
+# tool_timeout_sec = 300
+```
+
+**OpenCode**, in `~/.config/opencode/opencode.json`:
+
+```json
+{
+ "mcp": {
+ "unsloth-studio": {
+ "type": "remote",
+ "url": "http://127.0.0.1:8888/mcp/",
+ "oauth": false,
+ "headers": {
+ "Authorization": "Bearer {env:UNSLOTH_API_KEY}"
+ }
+ }
+ }
+}
+```
+
+**Hermes Agent**, in `~/.hermes/config.yaml`, then run `/reload-mcp` in Hermes:
+
+```yaml
+mcp_servers:
+ unsloth_studio:
+ url: "http://127.0.0.1:8888/mcp/"
+ headers:
+ Authorization: "Bearer ${UNSLOTH_API_KEY}"
+```
+
+**OpenClaw**, in `~/.openclaw/openclaw.json`:
+
+```json
+{
+ "mcp": {
+ "servers": {
+ "unsloth-studio": {
+ "url": "http://127.0.0.1:8888/mcp/",
+ "transport": "streamable-http",
+ "headers": {
+ "Authorization": "Bearer ${UNSLOTH_API_KEY}"
+ }
+ }
+ }
+ }
+}
+```
+
+**Mistral Vibe**, in `~/.vibe/config.toml`:
+
+```toml
+[[mcp_servers]]
+name = "unsloth_studio"
+transport = "streamable-http"
+url = "http://127.0.0.1:8888/mcp/"
+
+[mcp_servers.auth]
+type = "static"
+api_key_env = "UNSLOTH_API_KEY"
+api_key_header = "Authorization"
+api_key_format = "Bearer {token}"
+```
+
+**DeepSeek Harness**, appended to `~/.dsh/cordis.patch.yml`:
+
+```yaml
+- insert:
+ - id: mcp-unsloth-studio
+ name: '@deepseek-ai/dsh-mcp-client'
+ config:
+ serverName: unsloth-studio
+ transport: streamable-http
+ url: "http://127.0.0.1:8888/mcp/"
+ headers:
+ Authorization: !!js '`Bearer ${process.env.UNSLOTH_API_KEY}`'
+```
+
+### Tools
+
+| Tool | What it does |
+|---|---|
+| `studio_status` | What is loaded, loading and running: chat, image, video, speech-to-text and embedding models, training, export and GPUs. |
+| `list_models` | Models Unsloth Studio can serve, by kind. With `model`, its training defaults. |
+| `load_model` | Load a chat, image, video or speech-to-text model, downloading it first if needed. Reports progress. |
+| `unload_model` | Unload a model. |
+| `chat` | Ask the loaded model, with optional images. Returns a `cancel_id`. |
+| `embed` | Embed up to 2048 texts. |
+| `system_one` | Ask the Decision API typed questions. The Decision API must be on. |
+| `generate_image` | Text to image, image to image, inpaint, edit, outpaint and upscale. |
+| `generate_audio` | Clone, speak, edit, convert, music and separate. |
+| `transcribe` | Speech to text, or translation to English. |
+| `generate_video` | Start a video. Poll it with `get_job`. |
+| `get_job` | The state of a video, recipe or export job. |
+| `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`. |
+| `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 training, a start request, image training, an export, a recipe, an image or video generation, a chat reply or a dataset download. |
+
+Long work returns at once. Start it, then poll `get_job` or `studio_status`,
+and stop it with `cancel`. Audio runs cannot be cancelled. Unsloth Studio runs one
+export at a time, so `export_model` is refused while another export runs, and
+cancelling an export job stops only that job's own step.
+
+### Media and files
+
+Generated images, audio and videos are saved to Unsloth Studio's galleries, the same as
+in the UI. Tools return each item's id and URL. Small items also come back
+inline. Large images come back as a preview plus a link. A video comes back as a
+thumbnail plus a link, and the MP4 is never sent inline. Links point at
+Unsloth Studio's API, so fetch them with the same `Authorization: Bearer` key.
+
+Media inputs can be an Unsloth Studio id, inline data, or a file path. **A file path
+works only when the agent runs on the Unsloth Studio computer** and connects over
+loopback. From any other computer, send the data or an Unsloth Studio id instead.
+An MCP request is limited to 4 MiB, so inline data has to fit in that. Send
+larger media as an Unsloth Studio id, or as a path from the Unsloth Studio computer. A remote
+agent can upload a large audio file, up to 200 MiB, to `POST /v1/audio/inputs` with its API key
+and pass the returned `id` as `input_id`. The route takes the file's raw bytes as
+the request body with a `Content-Length`, not a multipart form or JSON, and an
+optional `name` query parameter:
```bash
-UNSLOTH_STUDIO_ENABLE_MCP=1 \
-UNSLOTH_STUDIO_MCP_TOKEN='use-a-local-secret' \
-unsloth studio
+curl -X POST "http://127.0.0.1:8888/v1/audio/inputs?name=meeting.mp3" \
+ -H "Authorization: Bearer $UNSLOTH_API_KEY" \
+ --data-binary @meeting.mp3
```
-The endpoint is `http://127.0.0.1:8888/mcp/` when Unsloth uses its default port
-(a request to `/mcp` redirects to the canonical `/mcp/`). Use the actual Unsloth
-port when it is configured differently.
+`transcribe` sends files up to 25 MB directly. Larger files, and audio given by
+id, are uploaded to Unsloth Studio first, and their transcript is saved to Audio
+history. Translation needs a file under 25 MB. Transcribing from a URL or a
+YouTube link is not supported. `timestamps` needs a speech-to-text model that
+times segments, such as Qwen3-ASR (audio.cpp) or Parakeet-TDT; other models
+refuse it, and translation never has timestamps.
-The high-impact tools are:
+`studio_status` lists the loaded audio model's `audio_options`, such as its
+built-in voices. Pass them to `generate_audio` in `options`. A voice or other
+listed value is matched without regard to case, and a value the model does not
+list is refused.
-- `studio_status` and `list_local_models` for discovery
-- `get_training_status`, `start_training`, `stop_training`, and `list_training_runs`
-- `validate_recipe`, `get_recipe_job_status`, and `get_recipe_job_dataset`
-- `load_checkpoint` and `export_gguf`
+Tool results never contain paths on the Unsloth Studio computer. Checkpoints are named
+`<run folder>` or `<run folder>/checkpoint-N`. Exports are named relative to
+Unsloth Studio's exports folder, and `export_model` takes only a relative
+`save_directory`.
-`start_training` accepts the same fields as the Unsloth `TrainingStartRequest`.
-The request is validated by the existing Pydantic model before a subprocess is
-started. Export paths use the existing Unsloth validation as well.
+### Known limits
-The endpoint always requires `UNSLOTH_STUDIO_MCP_TOKEN` and checks an exact
-Bearer token for both HTTP and WebSocket connections. Keep it on localhost
-unless the deployment has an authenticated reverse proxy. The MCP endpoint is
-intentionally opt-in because tools can consume GPU memory, write model
-artifacts, and stop active work.
\ No newline at end of file
+- An API key cannot unload a chat model that was loaded from a local folder.
+ Unsloth Studio shows such a model to API keys under an opaque reference, and the
+ 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 to
+ an 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 then
+ say to load the model again.
diff --git a/studio/backend/core/export/orchestrator.py b/studio/backend/core/export/orchestrator.py
index 537287a6066..6836b828a06 100644
--- a/studio/backend/core/export/orchestrator.py
+++ b/studio/backend/core/export/orchestrator.py
@@ -15,6 +15,7 @@ from core.training.account_jobs import (
validate_job_paths,
)
import atexit
+import os
import structlog
from collections import deque
from loggers import get_logger
@@ -37,6 +38,10 @@ _LOG_BUFFER_MAXLEN = 4000
# How long an export op may go without a single log or status line before the worker is treated as
# dead. Not how long an export may run: a reporting worker resets it on every line.
_EXPORT_INACTIVITY_TIMEOUT = 3600.0
+CHECKPOINT_CHANGED = (
+ "The loaded checkpoint changed since this export was requested; nothing was exported."
+)
+OP_CANCELLED = "Export cancelled"
# Teardown is a bounded amount of work, so it is capped outright rather than by silence: the log
# gate an export opens is never closed, and teardown chatter would otherwise renew this forever.
@@ -78,6 +83,10 @@ class ExportOrchestrator:
self._op_lock = threading.Lock()
self._op_seq: int = 0
self._active_op_kind: Optional[str] = None
+ # A caller's id for the running op, so cancel(expected_op_id) stops only that op; ids cancelled
+ # before their op started are refused when it does.
+ self._active_op_id: Optional[str] = None
+ self._cancelled_op_ids: set = set()
self._last_op: Optional[Dict[str, Any]] = None
atexit.register(self._cleanup)
@@ -172,8 +181,22 @@ class ExportOrchestrator:
def get_active_op_kind(self) -> Optional[str]:
return self._active_op_kind
+ def _begin_op(self, op_id: Optional[str]) -> bool:
+ with self._op_lock:
+ if op_id is not None and op_id in self._cancelled_op_ids:
+ self._cancelled_op_ids.discard(op_id)
+ return False
+ # Reset here, before the id is cancellable, so a matching cancel that lands next is never erased.
+ self._cancel_requested = False
+ self._active_op_id = op_id
+ return True
+
+ def _end_op(self) -> None:
+ with self._op_lock:
+ self._active_op_id = None
+
@job_control
- def cancel_export(self) -> bool:
+ def cancel_export(self, expected_op_id: Optional[str] = None) -> bool:
"""Terminate the in-flight export subprocess immediately.
An export op holds ``self._lock`` for its whole duration (blocked in
@@ -184,8 +207,23 @@ class ExportOrchestrator:
Only the export subprocess is touched; training and inference run in
their own subprocesses and are left untouched.
+ With ``expected_op_id`` only that op is stopped; when another op (or none) is running, the id is
+ remembered so the op refuses to start, and False is returned.
+
Returns True if a live subprocess was terminated, False if none ran.
"""
+ if expected_op_id is None:
+ return self._terminate_worker()
+ # Held across the terminate so the op cannot end and another start in between.
+ with self._op_lock:
+ if self._active_op_id != expected_op_id:
+ if len(self._cancelled_op_ids) >= 256:
+ self._cancelled_op_ids.clear()
+ self._cancelled_op_ids.add(expected_op_id)
+ return False
+ return self._terminate_worker()
+
+ def _terminate_worker(self) -> bool:
self._cancel_requested = True
proc = self._proc
if proc is None or not proc.is_alive():
@@ -485,6 +523,7 @@ class ExportOrchestrator:
allow_ambient: bool = True,
subject: Optional[str] = None,
base_model: Optional[str] = None,
+ op_id: Optional[str] = None,
) -> Tuple[bool, str]:
"""Load a checkpoint for export.
@@ -521,9 +560,10 @@ class ExportOrchestrator:
sub_config["device_backend"] = get_device().value
with self._lock:
+ if not self._begin_op(op_id):
+ return False, OP_CANCELLED
# Fresh log buffer so the UI sees only this run's output.
self.clear_logs()
- self._cancel_requested = False
self._active_op_kind = "load_checkpoint"
self._export_active = True
op_success, op_message = False, ""
@@ -563,6 +603,15 @@ class ExportOrchestrator:
self.is_peft = False
self.decision = None
raise
+ # A cancel that landed while the old worker was torn down found nothing to kill: stop the new one.
+ if self._cancel_requested:
+ self._shutdown_subprocess(timeout = 5)
+ self.current_checkpoint = None
+ self.is_vision = False
+ self.is_peft = False
+ self.decision = None
+ op_message = OP_CANCELLED
+ return False, OP_CANCELLED
try:
resp = self._wait_response("loaded")
@@ -594,6 +643,7 @@ class ExportOrchestrator:
return False, error
finally:
self._record_op_finished(op_success, op_message, None)
+ self._end_op()
self._active_op_kind = None
self._export_active = False
@@ -607,6 +657,8 @@ class ExportOrchestrator:
private: bool = False,
compressed_method: Optional[str] = None,
install_missing_dependencies: bool = False,
+ expected_checkpoint: Optional[str] = None,
+ op_id: Optional[str] = None,
) -> Tuple[bool, str, Optional[str]]:
return self._run_export(
"merged",
@@ -619,6 +671,8 @@ class ExportOrchestrator:
"private": private,
"compressed_method": compressed_method,
"install_missing_dependencies": install_missing_dependencies,
+ "expected_checkpoint": expected_checkpoint,
+ "op_id": op_id,
},
)
@@ -630,6 +684,8 @@ class ExportOrchestrator:
hf_token: HfTokenArg = None,
private: bool = False,
base_model_id: Optional[str] = None,
+ expected_checkpoint: Optional[str] = None,
+ op_id: Optional[str] = None,
) -> Tuple[bool, str, Optional[str]]:
return self._run_export(
"base",
@@ -640,6 +696,8 @@ class ExportOrchestrator:
"hf_token": hf_token,
"private": private,
"base_model_id": base_model_id,
+ "expected_checkpoint": expected_checkpoint,
+ "op_id": op_id,
},
)
@@ -653,6 +711,8 @@ class ExportOrchestrator:
imatrix_file = None,
private: bool = False,
npu_q4nx: bool = False,
+ expected_checkpoint: Optional[str] = None,
+ op_id: Optional[str] = None,
) -> Tuple[bool, str, Optional[str]]:
"""Export model in GGUF format. `quantization_method` may be a single method or a list."""
return self._run_export(
@@ -666,6 +726,8 @@ class ExportOrchestrator:
"imatrix_file": imatrix_file,
"private": private,
"npu_q4nx": npu_q4nx,
+ "expected_checkpoint": expected_checkpoint,
+ "op_id": op_id,
},
)
@@ -679,6 +741,8 @@ class ExportOrchestrator:
gguf: bool = False,
gguf_outtype: str = "q8_0",
adapter_format: Optional[str] = None,
+ expected_checkpoint: Optional[str] = None,
+ op_id: Optional[str] = None,
) -> Tuple[bool, str, Optional[str]]:
"""Export LoRA adapter only (optionally also as a GGUF LoRA file)."""
return self._run_export(
@@ -692,6 +756,8 @@ class ExportOrchestrator:
"gguf": gguf,
"gguf_outtype": gguf_outtype,
"adapter_format": adapter_format,
+ "expected_checkpoint": expected_checkpoint,
+ "op_id": op_id,
},
)
@@ -702,6 +768,8 @@ class ExportOrchestrator:
Returns ``(success, message, output_path)``. ``output_path`` is the on-disk
dir the worker wrote to (None if it only pushed to Hub or failed pre-write).
"""
+ expected = params.pop("expected_checkpoint", None)
+ op_id = params.pop("op_id", None)
validate_job_paths(params)
with self._lock:
if not self._ensure_subprocess_alive():
@@ -710,9 +778,16 @@ class ExportOrchestrator:
"No export subprocess running. Load a checkpoint first.",
None,
)
+ # Checked under the lock the export holds, so no load can slip in before it starts.
+ loaded = self.current_checkpoint
+ if expected is not None and (
+ not loaded or os.path.realpath(loaded) != os.path.realpath(expected)
+ ):
+ return False, CHECKPOINT_CHANGED, None
+ if not self._begin_op(op_id):
+ return False, OP_CANCELLED, None
self.clear_logs()
- self._cancel_requested = False
self._active_op_kind = f"export_{export_type}"
self._export_active = True
op_success, op_message, op_output_path = False, "", None
@@ -749,6 +824,7 @@ class ExportOrchestrator:
return False, str(exc), None
finally:
self._record_op_finished(op_success, op_message, op_output_path)
+ self._end_op()
self._active_op_kind = None
self._export_active = False
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 6b4ff6ae6cd..7d7fe7b531e 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -1075,20 +1075,15 @@ _decisions_mcp_app = decisions_mcp.http_app(path = "/", stateless_http = True, j
app.router.lifespan_context = combine_lifespans(lifespan, _decisions_mcp_app.lifespan)
app.mount(DECISIONS_MCP_PATH, RequireStudioAuth(_decisions_mcp_app))
-# The MCP surface is opt-in: it can start GPU jobs and write model artifacts.
-if os.environ.get("UNSLOTH_STUDIO_ENABLE_MCP") == "1":
- from mcp_server import BearerTokenMiddleware, create_studio_mcp
-
- _studio_mcp_app = create_studio_mcp().http_app(path = "/")
- _studio_mcp_lifespan = _studio_mcp_app.lifespan
- _mcp_token = os.environ.get("UNSLOTH_STUDIO_MCP_TOKEN")
- if not _mcp_token:
- raise RuntimeError("UNSLOTH_STUDIO_MCP_TOKEN is required when MCP is enabled")
- _studio_mcp_app = BearerTokenMiddleware(_studio_mcp_app, _mcp_token)
- app.router.lifespan_context = combine_lifespans(
- app.router.lifespan_context, _studio_mcp_lifespan
- )
- app.mount("/mcp", _studio_mcp_app)
+# Always mounted; the gate answers 404 until the owner turns agent access on.
+from mcp_server import create_studio_mcp # noqa: E402
+from studio_mcp.gate import StudioMcpGate # noqa: E402
+
+_studio_mcp_app = create_studio_mcp().http_app(path = "/", stateless_http = True)
+app.router.lifespan_context = combine_lifespans(
+ app.router.lifespan_context, _studio_mcp_app.lifespan
+)
+app.mount("/mcp", StudioMcpGate(_studio_mcp_app))
from loggers.config import LogConfig
from loggers.handlers import LoggingMiddleware
@@ -1100,6 +1095,12 @@ logger = LogConfig.setup_logging(
app.add_middleware(LoggingMiddleware)
+if os.environ.get("UNSLOTH_STUDIO_MCP_TOKEN", "").strip():
+ logger.warning(
+ "UNSLOTH_STUDIO_MCP_TOKEN is no longer used and /mcp refuses it. "
+ "Agents connect with an Unsloth Studio API key (sk-unsloth-…) from Settings > API."
+ )
+
class ResearchPortMiddleware:
"""Capture the bound port without replacing the ASGI receive channel."""
@@ -3048,57 +3049,11 @@ def _inject_bootstrap(html_bytes: bytes, app: FastAPI):
return html.encode("utf-8"), nonce
-_DEFAULT_PORTS = {"http": 80, "https": 443, "ws": 80, "wss": 443}
-
-
-def _canonical_origin(scheme: str, netloc: str) -> Optional[tuple[str, str, int]]:
- """Canonicalise an Origin to ``(scheme, host, port)`` for equality. Browsers strip default ports (RFC 6454
- sec 6.1) and scheme/host are case-insensitive (RFC 3986), so a bare string compare misclassifies
- same-origin requests as cross-origin. Returns ``None`` on unparseable input so callers fall to the safer
- cross-origin default."""
- scheme = (scheme or "").strip().lower()
- if not scheme or not netloc:
- return None
- # Strip userinfo (RFC 3986); Origin never carries credentials.
- if "@" in netloc:
- netloc = netloc.rsplit("@", 1)[1]
- # IPv6 hosts use brackets (RFC 3986 3.2.2): bare partition(":") breaks `-H ::1`.
- if netloc.startswith("["):
- close = netloc.find("]")
- if close == -1:
- return None
- host = netloc[1:close]
- rest = netloc[close + 1 :]
- if rest.startswith(":"):
- port_str = rest[1:]
- elif rest == "":
- port_str = ""
- else:
- return None
- else:
- host, _, port_str = netloc.partition(":")
- host = host.strip().lower()
- if not host:
- return None
- if port_str:
- try:
- port = int(port_str)
- except ValueError:
- return None
- else:
- port = _DEFAULT_PORTS.get(scheme, 0)
- return (scheme, host, port)
-
-
-def _origin_of(url: Optional[str]) -> Optional[tuple[str, str, int]]:
- """Canonical origin of a URL or of an Origin header value, or ``None`` when it is neither."""
- if not url:
- return None
- try:
- parsed = urlparse(url)
- except ValueError:
- return None
- return _canonical_origin(parsed.scheme, parsed.netloc)
+# Also used by the /mcp gate, which cannot import main.
+from utils.origin_policy import ( # noqa: E402
+ canonical_origin as _canonical_origin,
+ origin_of as _origin_of,
+)
# Shared with the routes that must only answer the person at this computer (Settings > Sandbox).
@@ -3312,6 +3267,10 @@ def setup_frontend(
# for /v1/* ({"detail": ...} for /api/*). The request path is "/" + full_path.
if full_path in {"api", "v1"} or full_path.startswith(("api/", "v1/")):
raise HTTPException(status_code = 404, detail = "API endpoint not found")
+ # MCP clients probe these before connecting; the app shell with a 200 reads as an OAuth server, and
+ # they would start a login Unsloth Studio does not offer instead of sending the API key.
+ if full_path.startswith(".well-known/oauth-"):
+ raise HTTPException(status_code = 404, detail = "Not Found")
if not _frontend_request_allowed(request):
return Response(status_code = 404)
diff --git a/studio/backend/mcp_server.py b/studio/backend/mcp_server.py
index 3125c28719e..18e4070129e 100644
--- a/studio/backend/mcp_server.py
+++ b/studio/backend/mcp_server.py
@@ -1,268 +1,63 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Curated MCP tools for driving an Unsloth Studio instance. The MCP surface deliberately wraps the existing
-Unsloth services instead of duplicating training or export logic. It is opt-in because several tools can start
-GPU work or write model artifacts.
-"""
+"""Unsloth Studio's MCP server at /mcp: curated tools that reach Unsloth Studio through its own routes as the agent's API key. Off until the owner turns it on, because several tools start GPU work or write files."""
from __future__ import annotations
-import hmac
-import asyncio
-from typing import Any
-
from fastmcp import FastMCP
-
-class BearerTokenMiddleware:
- """Require an exact bearer token when Unsloth MCP is exposed remotely."""
-
- def __init__(self, app: Any, token: str) -> None:
- if not token or not token.strip():
- raise ValueError("Unsloth MCP bearer token must be a non-empty value")
- if not token.isascii():
- # A non-ASCII token cannot be sent in an HTTP header; reject it here.
- raise ValueError("Unsloth MCP bearer token must contain ASCII characters only")
- self.app = app
- # Compare on raw header bytes: str hmac.compare_digest raises on non-ASCII input, which would
- # surface as a 500 instead of a clean 401.
- self.expected = token.encode("utf-8")
-
- async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> None:
- scope_type = scope.get("type")
- if scope_type not in ("http", "websocket"):
- await self.app(scope, receive, send)
- return
-
- headers = dict(scope.get("headers", []))
- raw_auth = headers.get(b"authorization", b"")
- scheme, _, supplied = raw_auth.partition(b" ")
- if scheme.lower() != b"bearer" or not hmac.compare_digest(supplied, self.expected):
- await _send_unauthorized(send, scope_type)
- return
-
- await self.app(scope, receive, send)
-
-
-async def _send_unauthorized(send: Any, scope_type: str) -> None:
- if scope_type == "websocket":
- await send({"type": "websocket.close", "code": 4401})
- return
-
- await send(
- {
- "type": "http.response.start",
- "status": 401,
- "headers": [(b"content-type", b"application/json"), (b"www-authenticate", b"Bearer")],
- }
- )
- await send(
- {
- "type": "http.response.body",
- "body": b'{"detail":"MCP bearer token required"}',
- }
- )
-
-
-def _dump(value: Any) -> Any:
- """Convert Pydantic responses to plain JSON values for MCP clients."""
- if hasattr(value, "model_dump"):
- return value.model_dump(mode = "json")
- return value
-
-
-def _clamp(value: int, low: int, high: int) -> int:
- """Clamp an MCP-supplied integer into an inclusive range. MCP tools call the Unsloth route functions
- directly, which skips FastAPI's Query(ge=, le=) validation, so we re-apply the same bounds here.
- """
- return max(low, min(value, high))
+from studio_mcp.tools import (
+ audio,
+ cancel,
+ data,
+ export,
+ images,
+ jobs,
+ models,
+ status,
+ text,
+ training,
+ video,
+)
+
+INSTRUCTIONS = (
+ "Unsloth Studio runs models, generates media, trains and exports. "
+ "Call studio_status first to see what is loaded and running, and list_models to find models. "
+ "Load a model with load_model before chat, generate_image, generate_audio or generate_video; embed "
+ "and transcribe fall back to Unsloth Studio's own embedding and speech-to-text models. "
+ "Unsloth Studio may unload one model to fit another on the GPU (load_model lists what it unloaded), "
+ "so check studio_status before reusing a model you loaded earlier. "
+ "Long work returns at once: start it, then poll get_job (video, recipe, export) or studio_status "
+ "(training), and stop it with cancel. "
+ "File paths in inputs work only when you run on the Unsloth Studio computer; otherwise send data or an "
+ "Unsloth Studio id. "
+ "Generated images, audio and videos are saved to the Unsloth Studio galleries and returned with their id "
+ "and URL. "
+ "Training, generation and exports use the GPU and can take minutes."
+)
def create_studio_mcp() -> FastMCP:
"""Create the Unsloth MCP server and register the high-value tools."""
- mcp = FastMCP(
- "Unsloth Studio",
- instructions = (
- "Use read tools to inspect the local Unsloth state before starting GPU work. "
- "Training and export tools can consume substantial VRAM and write files. "
- "Never expose tokens or local paths from tool results unless the user asks."
- ),
- )
-
- @mcp.tool
- async def studio_status() -> dict[str, Any]:
- """Return the current training, export, inference, and GPU state."""
- from routes.export import get_export_status
- from routes.inference import get_status as get_inference_status
- from routes.training import get_training_status
-
- from utils.hardware import get_gpu_utilization
-
- training, export, inference = await _gather_status(
- get_training_status(current_subject = "mcp"),
- get_export_status(current_subject = "mcp"),
- get_inference_status(current_subject = "mcp"),
- )
- return {
- "training": _dump(training),
- "export": _dump(export),
- "inference": _dump(inference),
- # Off-loop: reaches hardware detection, which blocks on the warm's torch import.
- "hardware": await asyncio.to_thread(get_gpu_utilization),
- }
-
- @mcp.tool
- async def list_local_models(models_dir: str = "./models") -> dict[str, Any]:
- """List local and cached models available to Unsloth."""
- from routes.models import list_local_models as list_models
- return _dump(await list_models(models_dir = models_dir, current_subject = "mcp"))
-
- @mcp.tool
- async def get_training_status() -> dict[str, Any]:
- """Read the active training job, phase, progress, and recent metrics."""
- from routes.training import get_training_status as get_status
- return _dump(await get_status(current_subject = "mcp"))
-
- @mcp.tool
- async def start_training(config: dict[str, Any]) -> dict[str, Any]:
- """Start a validated Unsloth training job from a TrainingStartRequest-shaped object.
-
- The config is validated by the same Pydantic model used by the Unsloth UI.
- Call get_training_status first and do not start work while another job runs.
- """
- from models import TrainingStartRequest
- from routes.training import start_training as start
-
- request = TrainingStartRequest.model_validate(config)
- return _dump(await start(request, current_subject = "mcp", via_api_key = True))
-
- @mcp.tool
- async def stop_training(expected_job_id: str, save: bool = True) -> dict[str, Any]:
- """Stop the identified training job at its next safe checkpoint."""
- from routes.training import TrainingStopRequest, stop_training as stop
- return _dump(
- await stop(
- TrainingStopRequest(save = save, expected_job_id = expected_job_id),
- current_subject = "mcp",
+ mcp = FastMCP("Unsloth Studio", instructions = INSTRUCTIONS)
+
+ for module in (
+ status,
+ models,
+ text,
+ images,
+ audio,
+ video,
+ jobs,
+ data,
+ training,
+ export,
+ cancel,
+ ):
+ for tool, annotations, *schema in module.TOOLS:
+ mcp.tool(
+ tool, annotations = annotations, **({"output_schema": schema[0]} if schema else {})
)
- )
-
- @mcp.tool
- async def list_training_runs(limit: int = 50, offset: int = 0) -> dict[str, Any]:
- """List completed and stopped training runs, newest first."""
- from routes.training_history import list_training_runs as list_runs
-
- # Clamp here (direct call skips Query bounds); a negative LIMIT = no limit.
- limit = _clamp(limit, 1, 200)
- offset = max(0, offset)
- return _dump(await list_runs(limit = limit, offset = offset, current_subject = "mcp"))
-
- @mcp.tool
- def validate_recipe(recipe: dict[str, Any]) -> dict[str, Any]:
- """Validate a Data Recipe with the same validator used by Unsloth."""
- from models.data_recipe import RecipePayload
- from routes.data_recipe.validate import validate
-
- # Direct call, so the ViaApiKey dependency never runs and its `= False` default would read as a UI
- # session; this surface is a remote static bearer.
- return _dump(validate(RecipePayload(recipe = recipe), via_api_key = True))
-
- @mcp.tool
- def get_recipe_job_status(job_id: str) -> dict[str, Any]:
- """Read the status of a Data Recipe job."""
- from routes.data_recipe.jobs import job_status
- return _dump(job_status(job_id))
-
- @mcp.tool
- def get_recipe_job_dataset(
- job_id: str,
- limit: int = 20,
- offset: int = 0,
- ) -> dict[str, Any]:
- """Read a bounded page of generated Data Recipe rows."""
- from routes.data_recipe.jobs import job_dataset
-
- # Clamp here (direct call skips FastAPI's Query bounds).
- limit = _clamp(limit, 1, 500)
- offset = max(0, offset)
- return _dump(job_dataset(job_id, limit = limit, offset = offset))
-
- @mcp.tool
- async def load_checkpoint(
- checkpoint_path: str,
- max_seq_length: int = 2048,
- load_in_4bit: bool | None = None,
- trust_remote_code: bool = False,
- approved_remote_code_fingerprint: str | None = None,
- hf_token: str | None = None,
- ) -> dict[str, Any]:
- """Load a checkpoint into the export backend.
-
- Export runs in its own subprocess and coexists with training and
- inference; it does not unload them, so a load can fail with a clear
- out-of-memory error if the GPU is already full. Pass hf_token to load a
- gated checkpoint, and approved_remote_code_fingerprint to retry a
- trust_remote_code load that was blocked pending review. Leave
- load_in_4bit unset to load full fine-tunes in 16-bit and adapters in
- 4-bit.
- """
- from models import LoadCheckpointRequest
- from routes.export import load_checkpoint as load
-
- # Omit an unset load_in_4bit so the backend can pick 16-bit for a full fine-tune.
- optional = {} if load_in_4bit is None else {"load_in_4bit": load_in_4bit}
- request = LoadCheckpointRequest(
- checkpoint_path = checkpoint_path,
- max_seq_length = max_seq_length,
- trust_remote_code = trust_remote_code,
- approved_remote_code_fingerprint = approved_remote_code_fingerprint,
- hf_token = hf_token,
- **optional,
- )
- return _dump(await load(request, current_subject = "mcp", allow_ambient = False))
-
- @mcp.tool
- async def export_gguf(
- save_directory: str,
- quantization_method: str | list[str] = "Q4_K_M",
- push_to_hub: bool = False,
- repo_id: str | None = None,
- hf_token: str | None = None,
- imatrix: bool = False,
- imatrix_path: str | None = None,
- private: bool = False,
- ) -> dict[str, Any]:
- """Export the loaded model to GGUF using Unsloth's existing path validation.
-
- quantization_method may be a single method or a list to produce several
- GGUFs from one load. Pass hf_token when push_to_hub is set (the backend
- rejects a Hub upload without it). Set imatrix (or imatrix_path) for the
- IQ low-bit quants that require an importance matrix.
- """
- from models import ExportGGUFRequest
- from routes.export import export_gguf as export
-
- request = ExportGGUFRequest(
- save_directory = save_directory,
- quantization_method = quantization_method,
- push_to_hub = push_to_hub,
- repo_id = repo_id,
- hf_token = hf_token,
- imatrix = imatrix,
- imatrix_path = imatrix_path,
- private = private,
- )
- return _dump(await export(request, current_subject = "mcp", allow_ambient = False))
return mcp
-
-
-async def _gather_status(*coroutines: Any) -> tuple[Any, ...]:
- """Gather independent status calls without letting one optional backend fail all state."""
- import asyncio
-
- results = await asyncio.gather(*coroutines, return_exceptions = True)
- return tuple(
- {"error": str(result)} if isinstance(result, Exception) else result for result in results
- )
diff --git a/studio/backend/models/__init__.py b/studio/backend/models/__init__.py
index 370db920a21..4784b1a17c2 100644
--- a/studio/backend/models/__init__.py
+++ b/studio/backend/models/__init__.py
@@ -35,6 +35,7 @@ from .auth import (
)
from .export import (
LoadCheckpointRequest,
+ ExportCancelRequest,
ExportStatusResponse,
ExportOperationResponse,
ExportMergedModelRequest,
@@ -97,6 +98,7 @@ __all__ = [
"ModelCheckpoints",
"CheckpointListResponse",
"LoadCheckpointRequest",
+ "ExportCancelRequest",
"ExportStatusResponse",
"ExportOperationResponse",
"ExportMergedModelRequest",
diff --git a/studio/backend/models/export.py b/studio/backend/models/export.py
index 0c30acd8e2d..93473d839d8 100644
--- a/studio/backend/models/export.py
+++ b/studio/backend/models/export.py
@@ -59,6 +59,19 @@ class LoadCheckpointRequest(BaseModel):
None,
description = "Hugging Face token used to scan/load gated checkpoints and their base models.",
)
+ op_id: Optional[str] = Field(
+ None,
+ max_length = 128,
+ description = "Caller's id for this operation; POST /api/export/cancel with it as expected_op_id stops only it.",
+ )
+
+
+class ExportCancelRequest(BaseModel):
+ expected_op_id: Optional[str] = Field(
+ None,
+ max_length = 128,
+ description = "Stop only the operation started with this op_id; one not started yet is refused when it starts.",
+ )
class ExportStatusResponse(BaseModel):
@@ -186,6 +199,17 @@ class ExportCommonOptions(BaseModel):
None,
description = "HuggingFace model ID of the base model (for model card metadata)",
)
+ expected_checkpoint: Optional[str] = Field(
+ None,
+ max_length = 4096,
+ description = "Export only while this checkpoint is still the loaded one. A client that loads and then "
+ "exports in two calls sends it so another load in between is refused instead of exported.",
+ )
+ op_id: Optional[str] = Field(
+ None,
+ max_length = 128,
+ description = "Caller's id for this operation; POST /api/export/cancel with it as expected_op_id stops only it.",
+ )
class ExportMergedModelRequest(ExportCommonOptions):
@@ -224,6 +248,18 @@ class ExportBaseModelRequest(ExportCommonOptions):
class ExportGGUFRequest(BaseModel):
"""Request for exporting the current model to GGUF format."""
+ expected_checkpoint: Optional[str] = Field(
+ None,
+ max_length = 4096,
+ description = "Export only while this checkpoint is still the loaded one. A client that loads and then "
+ "exports in two calls sends it so another load in between is refused instead of exported.",
+ )
+ op_id: Optional[str] = Field(
+ None,
+ max_length = 128,
+ description = "Caller's id for this operation; POST /api/export/cancel with it as expected_op_id stops only it.",
+ )
+
save_directory: str = Field(
...,
description = "Directory where GGUF files will be saved",
diff --git a/studio/backend/routes/export.py b/studio/backend/routes/export.py
index 357c6231cda..a3d88288959 100644
--- a/studio/backend/routes/export.py
+++ b/studio/backend/routes/export.py
@@ -44,6 +44,7 @@ except ImportError:
from models import (
LoadCheckpointRequest,
+ ExportCancelRequest,
ExportStatusResponse,
ExportOperationResponse,
ExportMergedModelRequest,
@@ -151,6 +152,7 @@ async def load_checkpoint(
# A supplied token cannot say whether it came from a session or an API key.
allow_ambient = allow_ambient,
subject = current_subject,
+ op_id = request.op_id,
)
if not success:
@@ -200,7 +202,9 @@ async def cleanup_export_memory(current_subject: str = Depends(get_current_subje
@router.post("/cancel", response_model = ExportOperationResponse)
-async def cancel_export(current_subject: str = Depends(get_current_subject)):
+async def cancel_export(
+ body: Optional[ExportCancelRequest] = None, current_subject: str = Depends(get_current_subject)
+):
"""Cancel the in-flight export by terminating its worker subprocess.
Only the export subprocess is killed; training and inference run in their
@@ -209,7 +213,11 @@ async def cancel_export(current_subject: str = Depends(get_current_subject)):
require_job_owner(get_export_backend())
try:
backend = get_export_backend()
- cancelled = await asyncio.to_thread(backend.cancel_export)
+ expected = body.expected_op_id if body is not None else None
+ if expected is None:
+ cancelled = await asyncio.to_thread(backend.cancel_export)
+ else:
+ cancelled = await asyncio.to_thread(backend.cancel_export, expected_op_id = expected)
return ExportOperationResponse(
success = True,
message = "Export cancelled" if cancelled else "No active export to cancel",
@@ -424,6 +432,8 @@ async def export_merged_model(
private = request.private,
compressed_method = request.compressed_method,
install_missing_dependencies = request.install_missing_dependencies,
+ expected_checkpoint = request.expected_checkpoint,
+ op_id = request.op_id,
)
if not success:
@@ -483,6 +493,8 @@ async def export_base_model(
),
private = request.private,
base_model_id = request.base_model_id,
+ expected_checkpoint = request.expected_checkpoint,
+ op_id = request.op_id,
)
if not success:
@@ -537,6 +549,8 @@ async def export_gguf(
imatrix_file = imatrix_file,
private = request.private,
npu_q4nx = request.npu_q4nx,
+ expected_checkpoint = request.expected_checkpoint,
+ op_id = request.op_id,
)
if not success:
@@ -693,6 +707,8 @@ async def export_lora_adapter(
gguf = request.gguf,
gguf_outtype = request.gguf_outtype,
adapter_format = request.adapter_format,
+ expected_checkpoint = request.expected_checkpoint,
+ op_id = request.op_id,
)
if not success:
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index 352300c730b..4dd27b5a079 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -164,6 +164,7 @@ from utils.keyless_api_access import (
get_keyless_api_access_settings,
set_keyless_api_access,
)
+from utils.mcp_access import forced_by_env, is_mcp_enabled, set_mcp_enabled
from utils.preview_sharing_settings import (
DEFAULT_PREVIEW_SHARING_ENABLED,
get_preview_sharing_enabled,
@@ -3894,6 +3895,17 @@ class KeylessApiAccessResponse(BaseModel):
exposure: Optional[Literal["colab", "public_url", "private_lan", "network"]] = None
+class McpAccessPayload(BaseModel):
+ enabled: StrictBool
+
+
+class McpAccessResponse(BaseModel):
+ enabled: bool
+ forced_by_env: bool
+ # Display only: where an agent should point. Agents connect to whatever address reaches this server.
+ url: str
+
+
class PreviewSharingPayload(BaseModel):
enabled: bool
@@ -4310,6 +4322,46 @@ def update_keyless_api_access(
return _keyless_api_access_response(request)
+def _require_ui_session_for_mcp(via_api_key: bool = Depends(authenticated_via_api_key)) -> None:
+ """MCP admits API keys, so a key (or a keyless caller) must not be the thing that opens it."""
+ if via_api_key:
+ raise HTTPException(
+ status_code = 403, detail = "Agent access (MCP) can only be changed from the Unsloth UI."
+ )
+
+
+def _mcp_access_response(request: Request) -> McpAccessResponse:
+ return McpAccessResponse(
+ enabled = is_mcp_enabled(),
+ forced_by_env = forced_by_env(),
+ url = str(request.base_url).rstrip("/") + "/mcp/",
+ )
+
+
+@_owner_settings_router.get("/mcp-access", response_model = McpAccessResponse)
+def get_mcp_access(
+ request: Request,
+ current_subject: str = Depends(get_current_subject),
+ _ui_session: None = Depends(_require_ui_session_for_mcp),
+) -> McpAccessResponse:
+ return _mcp_access_response(request)
+
+
+@_owner_settings_router.put("/mcp-access", response_model = McpAccessResponse)
+def update_mcp_access(
+ request: Request,
+ payload: McpAccessPayload,
+ current_subject: str = Depends(get_current_subject),
+ _ui_session: None = Depends(_require_ui_session_for_mcp),
+) -> McpAccessResponse:
+ """Turn agent access over MCP on or off for the whole installation."""
+ if forced_by_env():
+ raise HTTPException(status_code = 409, detail = "Set by UNSLOTH_STUDIO_ENABLE_MCP.")
+ enabled = set_mcp_enabled(payload.enabled)
+ logger.info("settings.mcp_access_updated subject=%s enabled=%s", current_subject, enabled)
+ return _mcp_access_response(request)
+
+
def _is_bundled_avatar_url(value: str) -> bool:
parsed = urlsplit(value)
if parsed.scheme or parsed.netloc:
diff --git a/studio/backend/studio_mcp/__init__.py b/studio/backend/studio_mcp/__init__.py
new file mode 100644
index 00000000000..c7095c05fcc
--- /dev/null
+++ b/studio/backend/studio_mcp/__init__.py
@@ -0,0 +1,4 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Unsloth Studio's own MCP server at /mcp. Not named ``mcp``: the backend root is on sys.path, and a local ``mcp`` package would shadow the SDK that fastmcp imports."""
diff --git a/studio/backend/studio_mcp/caller.py b/studio/backend/studio_mcp/caller.py
new file mode 100644
index 00000000000..429255abed3
--- /dev/null
+++ b/studio/backend/studio_mcp/caller.py
@@ -0,0 +1,38 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Who is calling an MCP tool. The gate validates the key and records the caller in the request scope; tools read it back here, because fastmcp's own header accessor drops ``Authorization``."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, Optional
+
+STATE_KEY = "unsloth_mcp"
+
+
+@dataclass(frozen = True)
+class Caller:
+ token: str = field(repr = False)
+ account_id: str
+ # The outer /mcp request was a direct loopback connection, so host file paths are the caller's own.
+ direct_local: bool
+ # scheme://host[:port] of the outer request, for URLs handed back to the agent.
+ public_base: str
+ # The outer Studio app, so forwarded calls never need to import main.
+ studio_app: Any = field(repr = False)
+ hf_token: Optional[str] = field(default = None, repr = False)
+
+
+def caller_from_scope(scope: dict) -> Optional[Caller]:
+ caller = (scope.get("state") or {}).get(STATE_KEY)
+ return caller if isinstance(caller, Caller) else None
+
+
+def current_caller() -> Caller:
+ from fastmcp.server.dependencies import get_http_request
+
+ caller = caller_from_scope(get_http_request().scope)
+ if caller is None:
+ raise RuntimeError("Unsloth Studio MCP tools need a caller admitted by the /mcp gate.")
+ return caller
diff --git a/studio/backend/studio_mcp/checkpoints.py b/studio/backend/studio_mcp/checkpoints.py
new file mode 100644
index 00000000000..debba98b9ec
--- /dev/null
+++ b/studio/backend/studio_mcp/checkpoints.py
@@ -0,0 +1,84 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Checkpoints by name. The checkpoints route lists each training output with its host path, and the export routes want that path back; agents only ever see ``<run folder>`` (the final weights) or ``<run folder>/<checkpoint>``, and the path is looked up here and never leaves this module."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Optional
+
+from studio_mcp.caller import Caller
+from studio_mcp.errors import tool_error
+from studio_mcp.tools import as_dict, integer, leaf_name, number, opt_text, route_json
+
+
+@dataclass(frozen = True)
+class Checkpoint:
+ run: str
+ name: str
+ path: str = field(repr = False)
+ loss: Optional[float] = None
+ base_model: Optional[str] = None
+ peft_type: Optional[str] = None
+ lora_rank: Optional[int] = None
+ is_quantized: bool = False
+
+
+def run_folder_path(checkpoints: list[dict], folder: str) -> Optional[str]:
+ """The run folder's own path: its final checkpoint, else the parent of an intermediate one."""
+ paths = [
+ c.get("path") for c in checkpoints if isinstance(c, dict) and isinstance(c.get("path"), str)
+ ]
+ for path in paths:
+ if leaf_name(path) == folder:
+ return path
+ for path in paths:
+ trimmed, leaf = path.rstrip("\\/"), leaf_name(path)
+ if len(leaf) < len(trimmed):
+ return trimmed[: len(trimmed) - len(leaf)].rstrip("\\/")
+ return None
+
+
+async def list_checkpoints(caller: Caller) -> tuple[list[Checkpoint], dict[str, str]]:
+ """Every checkpoint by name, plus each run folder's path for matching training runs."""
+ listing = await route_json("GET", "/api/models/checkpoints", caller = caller)
+ models = as_dict(listing).get("models")
+ found: list[Checkpoint] = []
+ folders: dict[str, str] = {}
+ for model in models or []:
+ if not isinstance(model, dict) or not opt_text(model.get("name")):
+ continue
+ folder = model["name"]
+ entries = [c for c in model.get("checkpoints") or [] if isinstance(c, dict)]
+ folder_path = run_folder_path(entries, folder)
+ if folder_path:
+ folders[folder] = folder_path
+ for entry in entries:
+ path, label = opt_text(entry.get("path")), opt_text(entry.get("display_name"))
+ if path is None or label is None:
+ continue
+ found.append(
+ Checkpoint(
+ run = folder,
+ name = folder
+ if label == folder or leaf_name(path) == folder
+ else f"{folder}/{label}",
+ path = path,
+ loss = number(entry.get("loss")),
+ base_model = opt_text(model.get("base_model")),
+ peft_type = opt_text(model.get("peft_type")),
+ lora_rank = integer(model.get("lora_rank")),
+ is_quantized = model.get("is_quantized") is True,
+ )
+ )
+ return found, folders
+
+
+async def resolve(caller: Caller, name: str) -> Checkpoint:
+ checkpoints, _folders = await list_checkpoints(caller)
+ for checkpoint in checkpoints:
+ if checkpoint.name == name:
+ return checkpoint
+ available = ", ".join(sorted(c.name for c in checkpoints)[:20]) or "none"
+ raise tool_error(f"No checkpoint named {name}. Available: {available}")
diff --git a/studio/backend/studio_mcp/errors.py b/studio/backend/studio_mcp/errors.py
new file mode 100644
index 00000000000..541ca8700d7
--- /dev/null
+++ b/studio/backend/studio_mcp/errors.py
@@ -0,0 +1,171 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Turn a forwarded route's failure into an MCP ToolError the agent can act on. Unsloth Studio routes fail in several shapes (``{"detail"}`` on /api, the OpenAI envelope on /v1, gpu_busy three ways, a 200 that carries ``_deferred_error`` or ``status: "error"``, an NDJSON error line), and every message is scrubbed of host paths before it leaves."""
+
+from __future__ import annotations
+
+import json
+import re
+from typing import Any, Mapping, Optional
+
+import httpx
+from fastmcp.exceptions import ToolError
+
+from hub.utils.host_paths import redact_paths_in_text
+from studio_mcp.forward import parse_json
+
+# Route errors sometimes tell a browser client which route to call next ("Call POST /inference/load
+# first."). The path scrub turns that route into <path>, and an MCP agent cannot call routes anyway.
+_ROUTE_CLAUSE = re.compile(
+ r"\s*\b(?:Call|Use|See) (?:GET|POST|PUT|PATCH|DELETE) /[\w/{}.:-]*(?: first)?\.(?=\s|$)"
+)
+
+
+def _scrub(text: Any) -> str:
+ return redact_paths_in_text(_ROUTE_CLAUSE.sub("", text) if isinstance(text, str) else text)
+
+
+_MAX_MESSAGE_CHARS = 2000
+_DEFERRED_ERROR_KEY = "_deferred_error"
+REFUSAL_HEADER = "x-unsloth-refusal"
+MEMORY_REFUSAL = "memory-estimate"
+
+
+def tool_error(message: Any, hint: Optional[str] = None) -> ToolError:
+ """A scrubbed ToolError. ``hint`` is the tool's own guidance and goes on after the scrub, which would otherwise read a route like /v1/models as a path and drop it."""
+ text = _scrub(message).strip() or "Unsloth Studio returned an error"
+ if len(text) > _MAX_MESSAGE_CHARS:
+ text = text[:_MAX_MESSAGE_CHARS] + "…"
+ return ToolError(f"{text} {hint}" if hint else text)
+
+
+def _text(value: Any) -> str:
+ if isinstance(value, str):
+ return value
+ if value is None:
+ return ""
+ return json.dumps(value, ensure_ascii = False, default = str)
+
+
+def _validation_summary(errors: list) -> str:
+ parts = []
+ for error in errors[:10]:
+ if not isinstance(error, dict):
+ parts.append(_text(error))
+ continue
+ loc = [str(part) for part in error.get("loc") or () if part != "body"]
+ msg = _text(error.get("msg") or "invalid")
+ parts.append(f"{'.'.join(loc)}: {msg}" if loc else msg)
+ return "Invalid arguments: " + "; ".join(parts)
+
+
+def _gpu_busy(body: Any) -> Optional[tuple[str, Any]]:
+ """(message, retry_after) for any of the three gpu_busy shapes."""
+ if not isinstance(body, dict):
+ return None
+ candidates = [body, body.get("detail"), body.get("error")]
+ for candidate in candidates:
+ if not isinstance(candidate, dict):
+ continue
+ if candidate.get("error") == "gpu_busy" or candidate.get("code") == "gpu_busy":
+ return _text(candidate.get("message")), candidate.get("retry_after")
+ return None
+
+
+def _detail_message(detail: Any) -> str:
+ if isinstance(detail, list):
+ return _validation_summary(detail)
+ if isinstance(detail, dict):
+ for key in ("message", "detail", "error"):
+ if isinstance(detail.get(key), str) and detail[key]:
+ return detail[key]
+ return _text(detail)
+
+
+def _describe(status: int, body: Any, headers: Mapping[str, str]) -> str:
+ # Scrubbed before the hints go on: the redactor drops everything after a path it finds.
+ retry_after = headers.get("retry-after")
+ busy = _gpu_busy(body)
+ if busy is not None:
+ message, body_retry = busy
+ seconds = retry_after or body_retry
+ hint = f" Retry after {seconds} s." if seconds is not None else ""
+ return f"GPU busy: {_scrub(message).rstrip('.')}.{hint}"
+
+ if isinstance(body, dict) and "detail" in body:
+ if isinstance(body["detail"], list):
+ return _scrub(_validation_summary(body["detail"]))
+ message = _detail_message(body["detail"])
+ elif isinstance(body, dict) and isinstance(body.get("error"), dict):
+ envelope = body["error"]
+ message = _scrub(_text(envelope.get("message")))
+ # /v1 validation is a 400 whose envelope names the offending field.
+ if status == 400 and envelope.get("param"):
+ return f"Invalid arguments: {message}"
+ if envelope.get("code"):
+ message = f"{message} ({envelope['code']})"
+ elif isinstance(body, dict) and isinstance(body.get("message"), str):
+ message = body["message"]
+ else:
+ message = _text(body)
+
+ message = _scrub(message)
+ if status == 400 and headers.get(REFUSAL_HEADER) == MEMORY_REFUSAL:
+ return f"{message} Pass allow_oversized=true to try anyway."
+ message = f"{message} (HTTP {status})"
+ if status == 503 and retry_after:
+ message += f" Retry after {retry_after} s."
+ return message
+
+
+def _body(resp: httpx.Response) -> Any:
+ try:
+ return parse_json(resp.content)
+ except (ValueError, UnicodeDecodeError):
+ return resp.text.strip()
+
+
+def raise_for_payload(payload: Any) -> Any:
+ """Raise for an error carried inside a successful response; return the payload otherwise."""
+ if isinstance(payload, dict):
+ deferred = payload.get(_DEFERRED_ERROR_KEY)
+ if deferred is not None:
+ # /load and /unload commit a 200 to keep a tunnel open, then report a late failure here.
+ deferred = deferred if isinstance(deferred, dict) else {"detail": deferred}
+ status = deferred.get("status_code")
+ status = status if isinstance(status, int) else 500
+ raise tool_error(_describe(status, {"detail": deferred.get("detail")}, {}))
+ if payload.get("type") == "error":
+ nested = payload.get("error")
+ message = payload.get("message") or (
+ nested.get("message") if isinstance(nested, dict) else nested
+ )
+ raise tool_error(_text(message))
+ return payload
+
+
+def raise_for_status_field(payload: Any) -> Any:
+ """``/api/train/start`` refuses with a 200 and ``status: "error"``."""
+ if isinstance(payload, dict) and payload.get("status") == "error":
+ raise tool_error(_text(payload.get("message") or payload.get("error")))
+ return payload
+
+
+def raise_for_route(
+ resp: httpx.Response,
+ *,
+ payload: Any = None,
+ hints: Optional[Mapping[int, str]] = None,
+) -> Any:
+ """Raise a ToolError when the forwarded call failed; otherwise return its parsed JSON (or ``payload`` when the caller already parsed it, e.g. the last NDJSON line). ``hints`` maps a status to what the agent should do about it; a GPU-busy answer keeps its retry hint instead."""
+ if resp.status_code >= 400:
+ body = _body(resp)
+ hint = None if _gpu_busy(body) is not None else (hints or {}).get(resp.status_code)
+ raise tool_error(_describe(resp.status_code, body, resp.headers), hint)
+ if payload is None:
+ try:
+ payload = parse_json(resp.content) if resp.content.strip() else None
+ except (ValueError, UnicodeDecodeError):
+ return None
+ return raise_for_payload(payload)
diff --git a/studio/backend/studio_mcp/export_jobs.py b/studio/backend/studio_mcp/export_jobs.py
new file mode 100644
index 00000000000..b49a2a8a58b
--- /dev/null
+++ b/studio/backend/studio_mcp/export_jobs.py
@@ -0,0 +1,138 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Export jobs started over MCP. Loading a checkpoint and exporting it can take many minutes, longer than an agent waits on one tool call, so export_model runs them as a background task and get_job reports on it. Jobs are keyed by account, and an id from another account reads as unknown."""
+
+from __future__ import annotations
+
+import asyncio
+import re
+import secrets
+import time
+from collections import OrderedDict
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Awaitable, Callable, Optional
+
+from fastmcp.exceptions import ToolError
+
+from hub.utils.host_paths import redact_paths_in_text
+from studio_mcp.tools import leaf_name
+
+CAPACITY = 64
+
+
+@dataclass
+class ExportJob:
+ job_id: str
+ account_id: str
+ format: str
+ status: str = "running"
+ phase: str = "starting"
+ # The op id sent with the step in flight; cancel stops the worker only while that op runs.
+ op_id: Optional[str] = None
+ output: Optional[str] = None
+ error: Optional[str] = None
+ finished_at: Optional[float] = None
+ # Held here so the task outlives the tool call that started it.
+ task: Optional[asyncio.Task] = field(default = None, repr = False)
+
+ @property
+ def finished(self) -> bool:
+ return self.status != "running"
+
+
+_jobs: "OrderedDict[str, ExportJob]" = OrderedDict()
+
+
+def _key(account_id: str, job_id: str) -> str:
+ return f"{account_id}:{job_id}"
+
+
+def _evict() -> None:
+ while len(_jobs) > CAPACITY:
+ oldest = next((key for key, job in _jobs.items() if job.finished), None)
+ if oldest is None:
+ return
+ _jobs.pop(oldest)
+
+
+def output_name(path: Any) -> Optional[str]:
+ """An export's output as the agent may see it: relative to Unsloth Studio's exports folder, or just its name."""
+ if not isinstance(path, str) or not path:
+ return None
+ if not (path.startswith(("/", "\\")) or re.match(r"^[A-Za-z]:[\\/]", path)):
+ return path
+ try:
+ from utils.paths import exports_root
+ return Path(path).resolve().relative_to(Path(exports_root()).resolve()).as_posix()
+ except Exception:
+ return f"{leaf_name(path)} (outside exports folder)"
+
+
+def finish(
+ job: ExportJob,
+ status: str,
+ *,
+ error: Optional[str] = None,
+) -> None:
+ if job.finished:
+ return
+ job.status = status
+ job.phase = "done"
+ job.error = redact_paths_in_text(error) if error else job.error
+ job.finished_at = time.monotonic()
+
+
+async def settle(job: ExportJob, timeout: float) -> None:
+ """Wait up to ``timeout`` seconds for the job's task to finish on its own, without cancelling it."""
+ if job.task is not None and not job.task.done():
+ await asyncio.wait({job.task}, timeout = timeout)
+
+
+async def _drive(job: ExportJob, run: Callable[[ExportJob], Awaitable[None]]) -> None:
+ try:
+ await run(job)
+ except asyncio.CancelledError:
+ finish(job, "cancelled")
+ raise
+ except ToolError as exc:
+ finish(job, "failed", error = str(exc))
+ except Exception:
+ finish(job, "failed", error = "The export stopped unexpectedly.")
+ else:
+ finish(job, "completed")
+
+
+def start(account_id: str, format: str, run: Callable[[ExportJob], Awaitable[None]]) -> ExportJob:
+ job = ExportJob(job_id = secrets.token_urlsafe(12), account_id = account_id, format = format)
+ _jobs[_key(account_id, job.job_id)] = job
+ _evict()
+ job.task = asyncio.get_running_loop().create_task(_drive(job, run))
+ return job
+
+
+def lookup(account_id: str, job_id: str) -> ExportJob:
+ job = _jobs.get(_key(account_id, job_id))
+ if job is None:
+ raise ToolError("No such export job")
+ return job
+
+
+def any_running() -> bool:
+ return any(not job.finished for job in _jobs.values())
+
+
+def jobs_of(account_id: str) -> list[ExportJob]:
+ return [job for job in _jobs.values() if job.account_id == account_id]
+
+
+def mark_cancelled(job: ExportJob) -> None:
+ if job.task is not None and not job.task.done():
+ job.task.cancel()
+ finish(job, "cancelled")
+
+
+def _reset() -> None:
+ """Test hook."""
+ _jobs.clear()
diff --git a/studio/backend/studio_mcp/forward.py b/studio/backend/studio_mcp/forward.py
new file mode 100644
index 00000000000..cd8e654b1e5
--- /dev/null
+++ b/studio/backend/studio_mcp/forward.py
@@ -0,0 +1,104 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""MCP tools reach Unsloth Studio through its own HTTP routes, in-process, as the API-key caller. Calling the route functions directly would skip the auth dependency, so the call would run as the owner and see host paths; going through the app means each call is authenticated, account-scoped and redacted exactly as the same request from the agent would be.
+
+The in-process client is deliberately remote: a TEST-NET peer and an ``.invalid`` Host fail every loopback, LAN and keyless check, so a forwarded call can never use keyless access, whatever Unsloth Studio's keyless scope. Only the caller's key and, where a route reads it, the Hub token header are sent; nothing from the inbound request is copied."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from typing import Any, Optional
+
+import httpx
+
+from studio_mcp.caller import Caller
+
+# RFC 5737 TEST-NET-1 and an RFC 6761 .invalid name: neither can be loopback, private or resolvable.
+FORWARD_CLIENT = ("192.0.2.1", 0)
+FORWARD_BASE_URL = "http://unsloth-mcp.invalid"
+HF_TOKEN_HEADER = "X-Unsloth-HF-Token"
+
+# The route families MCP tools use. Anything else, notably auth, sandbox and the local-person settings, is a programming error.
+ALLOWED_PREFIXES = (
+ "/api/inference/",
+ "/v1/",
+ "/api/train/",
+ "/api/models/",
+ "/api/export/",
+ "/api/data-recipe/",
+ "/api/hub/datasets/",
+ "/api/hub/gguf-variants",
+ "/api/settings/embedding-model",
+)
+
+
+def checked_path(url: httpx.URL) -> str:
+ path = url.path
+ segments = path.split("/")
+ if not path.startswith(ALLOWED_PREFIXES) or any(s in (".", "..") for s in segments):
+ raise RuntimeError(f"Unsloth Studio MCP does not forward to {path!r}")
+ return path
+
+
+def _headers(caller: Caller, hub_header: bool, content_type: Optional[str]) -> dict[str, str]:
+ headers = {"Authorization": f"Bearer {caller.token}"}
+ if hub_header and caller.hf_token:
+ headers[HF_TOKEN_HEADER] = caller.hf_token
+ if content_type:
+ headers["Content-Type"] = content_type
+ return headers
+
+
+async def forward(
+ caller: Caller,
+ method: str,
+ path: str,
+ *,
+ params: Optional[dict[str, Any]] = None,
+ json_body: Any = None,
+ content: Optional[bytes] = None,
+ content_type: Optional[str] = None,
+ files: Any = None,
+ data: Optional[dict[str, Any]] = None,
+ hub_header: bool = False,
+) -> httpx.Response:
+ """Send one request to Unsloth Studio as ``caller`` and return the buffered response. ``content`` must be bytes, so httpx sets Content-Length: the upload routes answer a streamed body with 411."""
+ if content is not None and not isinstance(content, (bytes, bytearray)):
+ raise TypeError("forward() uploads need bytes")
+ # The route binds the account ContextVar in whatever task runs it; its own task keeps that out of the tool.
+ body = {"params": params, "json": json_body, "content": content, "files": files, "data": data}
+ task = asyncio.create_task(
+ _send(caller, method, path, body, _headers(caller, hub_header, content_type))
+ )
+ try:
+ return await task
+ except asyncio.CancelledError:
+ task.cancel()
+ raise
+
+
+async def _send(
+ caller: Caller, method: str, path: str, body: dict[str, Any], headers: dict[str, str]
+) -> httpx.Response:
+ transport = httpx.ASGITransport(app = caller.studio_app, client = FORWARD_CLIENT)
+ async with httpx.AsyncClient(
+ transport = transport, base_url = FORWARD_BASE_URL, timeout = None
+ ) as client:
+ request = client.build_request(method, path, headers = headers, **body)
+ checked_path(request.url)
+ return await client.send(request)
+
+
+def parse_json(body: bytes) -> Any:
+ """Route JSON. ``/load`` and ``/unload`` pad a slow answer with leading spaces to keep tunnels open."""
+ return json.loads(body.strip())
+
+
+def ndjson_last(body: bytes) -> Any:
+ """The last JSON line of an NDJSON stream, which carries the result or the error."""
+ lines = [line for line in body.splitlines() if line.strip()]
+ if not lines:
+ raise ValueError("empty NDJSON body")
+ return json.loads(lines[-1])
diff --git a/studio/backend/studio_mcp/gate.py b/studio/backend/studio_mcp/gate.py
new file mode 100644
index 00000000000..d88644fb359
--- /dev/null
+++ b/studio/backend/studio_mcp/gate.py
@@ -0,0 +1,214 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The ASGI gate in front of the Unsloth Studio MCP app. ``/mcp`` is always mounted, so the gate is what keeps it hidden: while the owner's switch is off every request gets the same 404 as an unknown path, before anything about the caller is read. Once on, a browser page from a foreign Origin is refused, and only a valid Unsloth Studio API key gets through; keyless access, UI sessions and workflow keys never do, whatever the keyless scope."""
+
+from __future__ import annotations
+
+import hmac
+import json
+import os
+from typing import Any, Optional
+
+from fastapi.security.utils import get_authorization_scheme_param
+from starlette.concurrency import run_in_threadpool
+from starlette.datastructures import URL
+from starlette.requests import Request
+
+from studio_mcp.caller import STATE_KEY, Caller
+from utils.account_context import ROLE_OWNER
+from utils.mcp_access import is_mcp_enabled
+
+LEGACY_TOKEN_ENV = "UNSLOTH_STUDIO_MCP_TOKEN"
+MOUNT = "/mcp"
+HF_TOKEN_HEADER = b"x-unsloth-hf-token"
+HF_TOKEN_MAX_LENGTH = 512
+
+NEED_KEY = "Unsloth Studio MCP needs an Unsloth Studio API key (sk-unsloth-…). Create one in Settings > API."
+ONE_HEADER = "Send one Authorization header"
+INVALID_KEY = "Invalid or expired API key"
+WORKFLOW_KEY = "Workflow keys cannot use Unsloth Studio MCP"
+RETIRED_TOKEN = (
+ "The MCP static token is no longer supported; use an Unsloth Studio API key (sk-unsloth-…)"
+)
+# The mcp SDK refuses bodies over 4 MiB from 1.29 on, as a bare 413 before any tool runs. Holding
+# every version to it here keeps the limit the same everywhere and says what to send instead.
+MAX_REQUEST_BYTES = 4 * 1024 * 1024
+TOO_LARGE = (
+ "Unsloth Studio MCP requests are limited to 4 MiB. Send larger media as an Unsloth Studio id "
+ "(gallery_id, input_id, clip_id or voice_id) or, from the Unsloth Studio computer, as a file path."
+)
+
+
+async def _respond(send: Any, status: int, body: bytes, headers: list) -> None:
+ await send({"type": "http.response.start", "status": status, "headers": headers})
+ await send({"type": "http.response.body", "body": body})
+
+
+async def send_json(
+ send: Any,
+ status: int,
+ body: dict,
+ headers: tuple = (),
+) -> None:
+ content_type = (b"content-type", b"application/json")
+ await _respond(send, status, json.dumps(body).encode(), [content_type, *headers])
+
+
+async def _unauthorized(send: Any, detail: str) -> None:
+ # No resource_metadata: advertising OAuth would send agents into a login flow Studio does not have.
+ await send_json(send, 401, {"detail": detail}, ((b"www-authenticate", b"Bearer"),))
+
+
+def _mount_relative_path(scope: dict) -> str:
+ path = scope.get("path", "")
+ root = scope.get("root_path", "")
+ return path[len(root) :] if root and path.startswith(root) else path
+
+
+def _validate_key(token: str) -> tuple[Optional[dict], str]:
+ """The key's account record, or None and why. Read-only: no account binding and no last-used write; the forwarded call does both."""
+ from auth import storage
+
+ try:
+ verified = storage.validate_api_key_account(token, touch = False)
+ if verified is None:
+ return None, INVALID_KEY
+ # Recipe and Deep Research keys carry narrower authority than every MCP tool.
+ if storage.is_internal_api_key(token):
+ return None, WORKFLOW_KEY
+ except Exception:
+ return None, INVALID_KEY
+ return verified[0], ""
+
+
+async def _bounded_receive(scope: dict, receive: Any) -> Optional[Any]:
+ """A receive that replays the request body, or None when the body is over MAX_REQUEST_BYTES."""
+ for name, value in scope.get("headers") or []:
+ if name.lower() == b"content-length":
+ try:
+ if int(value) > MAX_REQUEST_BYTES:
+ return None
+ except ValueError:
+ return None
+ chunks: list[bytes] = []
+ size = 0
+ while True:
+ message = await receive()
+ if message["type"] != "http.request":
+ # The client went away; let the app see the disconnect.
+ pending = [message]
+ break
+ body = message.get("body", b"")
+ size += len(body)
+ if size > MAX_REQUEST_BYTES:
+ return None
+ chunks.append(body)
+ if not message.get("more_body", False):
+ pending = [{"type": "http.request", "body": b"".join(chunks), "more_body": False}]
+ break
+
+ async def replay() -> dict:
+ return pending.pop(0) if pending else await receive()
+
+ return replay
+
+
+def _is_legacy_token(token: str) -> bool:
+ legacy = os.environ.get(LEGACY_TOKEN_ENV, "")
+ if not legacy.strip():
+ return False
+ return hmac.compare_digest(token.encode("utf-8"), legacy.encode("utf-8"))
+
+
+class StudioMcpGate:
+ def __init__(self, app: Any) -> None:
+ self.app = app
+
+ async def __call__(self, scope: dict, receive: Any, send: Any) -> None:
+ if scope["type"] == "lifespan":
+ await self.app(scope, receive, send)
+ return
+ if scope["type"] != "http":
+ await send({"type": "websocket.close", "code": 4404})
+ return
+
+ # The decisions mount only matches with the trailing slash, so /mcp/decisions lands here.
+ if _mount_relative_path(scope).rstrip("/") == "/decisions":
+ target = URL(scope = {**scope, "path": scope["path"].rstrip("/") + "/"})
+ await _respond(send, 307, b"", [(b"location", str(target).encode("latin-1"))])
+ return
+
+ if not await run_in_threadpool(is_mcp_enabled):
+ await send_json(send, 404, {"detail": "Not Found"})
+ return
+
+ headers = scope.get("headers") or []
+ origins = [value for name, value in headers if name.lower() == b"origin"]
+ if origins:
+ from utils.origin_policy import mcp_origin_allowed
+ outer = URL(scope = scope)
+ if len(origins) > 1 or not mcp_origin_allowed(
+ origins[0].decode("latin-1"),
+ request_scheme = outer.scheme,
+ request_netloc = outer.netloc,
+ app_state = getattr(scope.get("app"), "state", None),
+ ):
+ await send_json(send, 403, {"detail": "Origin not allowed for Unsloth Studio MCP"})
+ return
+
+ authorization = [value for name, value in headers if name.lower() == b"authorization"]
+ if len(authorization) > 1:
+ await _unauthorized(send, ONE_HEADER)
+ return
+ from utils.keyless_api_access import APPROVED_DUMMY_BEARERS
+
+ scheme, token = get_authorization_scheme_param(
+ authorization[0].decode("latin-1") if authorization else ""
+ )
+ if scheme.lower() != "bearer" or not token or token in APPROVED_DUMMY_BEARERS:
+ await _unauthorized(send, NEED_KEY)
+ return
+ if _is_legacy_token(token):
+ await _unauthorized(send, RETIRED_TOKEN)
+ return
+ from auth.storage import API_KEY_PREFIX
+
+ if not token.startswith(API_KEY_PREFIX):
+ await _unauthorized(send, NEED_KEY)
+ return
+ record, reason = await run_in_threadpool(_validate_key, token)
+ if record is None:
+ await _unauthorized(send, reason)
+ return
+
+ hf_values = [value for name, value in headers if name.lower() == HF_TOKEN_HEADER]
+ hf_token = hf_values[0].decode("latin-1").strip() if len(hf_values) == 1 else ""
+ if len(hf_values) > 1 or len(hf_token) > HF_TOKEN_MAX_LENGTH:
+ await send_json(
+ send, 400, {"detail": "Send one X-Unsloth-HF-Token of at most 512 characters"}
+ )
+ return
+
+ bounded = await _bounded_receive(scope, receive)
+ if bounded is None:
+ await send_json(send, 413, {"detail": TOO_LARGE})
+ return
+
+ from utils.client_ip import is_direct_local_request
+
+ outer = URL(scope = scope)
+ # Behind a root_path, Studio's own routes sit under the same prefix as /mcp.
+ mounted = scope.get("root_path", "")
+ prefix = mounted[: -len(MOUNT)] if mounted.endswith(MOUNT) else ""
+ scope.setdefault("state", {})[STATE_KEY] = Caller(
+ token = token,
+ account_id = record["account_id"],
+ # Host files are the owner's: a managed account stays inside its sandbox even on loopback.
+ direct_local = record.get("role") == ROLE_OWNER
+ and is_direct_local_request(Request(scope)),
+ public_base = f"{outer.scheme}://{outer.netloc}{prefix}",
+ studio_app = scope.get("app"),
+ hf_token = hf_token or None,
+ )
+ await self.app(scope, bounded, send)
diff --git a/studio/backend/studio_mcp/inputs.py b/studio/backend/studio_mcp/inputs.py
new file mode 100644
index 00000000000..b2e4086cb39
--- /dev/null
+++ b/studio/backend/studio_mcp/inputs.py
@@ -0,0 +1,196 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Media an agent hands to a tool: by Unsloth Studio id, as inline data, or as a file path. A path makes the server read a file on the Unsloth Studio computer, so it is honoured only when the agent itself runs there (a direct loopback /mcp request); anyone else gets told to send the bytes or an id, and the file is never touched."""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import re
+from pathlib import Path
+from typing import Any, Optional
+
+from fastmcp.exceptions import ToolError
+from pydantic import BaseModel, ConfigDict, model_validator
+
+from studio_mcp.caller import Caller
+from studio_mcp.errors import raise_for_route
+from studio_mcp.forward import forward
+from studio_mcp.media import image_gallery_path
+
+PATH_REMOTE = (
+ "File paths work only when the agent runs on the Unsloth Studio computer. "
+ "Send data_url/data_base64 or an Unsloth Studio id instead."
+)
+MAX_IMAGE_BYTES = 32 * 1024 * 1024 * 3 // 4
+IMAGE_MIMES = ("image/png", "image/jpeg", "image/webp")
+_DATA_URL = re.compile(r"^data:(image/(?:png|jpeg|webp));base64,(.*)$", re.DOTALL)
+
+
+class ImageInput(BaseModel):
+ """Exactly one of ``path`` (a file on the Unsloth Studio computer), ``data_url`` (data:image/png|jpeg|webp;base64,...) or ``gallery_id`` (an image in the Unsloth Studio Images gallery). Inline data rides in the MCP request, which is limited to 4 MiB."""
+
+ model_config = ConfigDict(extra = "forbid")
+
+ path: Optional[str] = None
+ data_url: Optional[str] = None
+ gallery_id: Optional[str] = None
+
+ @model_validator(mode = "after")
+ def _exactly_one(self) -> "ImageInput":
+ if sum(value is not None for value in (self.path, self.data_url, self.gallery_id)) != 1:
+ raise ValueError("Give exactly one of path, data_url or gallery_id.")
+ return self
+
+
+def sniff_image(data: bytes) -> Optional[str]:
+ if data.startswith(b"\x89PNG\r\n\x1a\n"):
+ return "image/png"
+ if data.startswith(b"\xff\xd8\xff"):
+ return "image/jpeg"
+ if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
+ return "image/webp"
+ return None
+
+
+def read_local(caller: Caller, path: str, max_bytes: int) -> bytes:
+ """A file named by the agent, read only for a caller on this computer and only when within ``max_bytes``."""
+ if not caller.direct_local:
+ raise ToolError(PATH_REMOTE)
+ file = Path(path).expanduser()
+ try:
+ size = file.stat().st_size
+ except OSError:
+ raise ToolError(f"Cannot read {path}") from None
+ if not file.is_file():
+ raise ToolError(f"{path} is not a file")
+ if size > max_bytes:
+ raise ToolError(f"{path} is larger than {max_bytes // (1024 * 1024)} MiB")
+ try:
+ return file.read_bytes()
+ except OSError:
+ raise ToolError(f"Cannot read {path}") from None
+
+
+def decode_base64(data: str, max_bytes: int, what: str) -> bytes:
+ # Checked on the encoded length, before anything is decoded.
+ if len(data) > 4 * ((max_bytes + 2) // 3):
+ raise ToolError(f"{what} is larger than {max_bytes // (1024 * 1024)} MiB")
+ try:
+ return base64.b64decode(data, validate = True)
+ except (binascii.Error, ValueError):
+ raise ToolError(f"{what} is not valid base64") from None
+
+
+async def resolve_image(
+ caller: Caller,
+ image: ImageInput,
+ *,
+ max_bytes: int = MAX_IMAGE_BYTES,
+ mimes: tuple[str, ...] = IMAGE_MIMES,
+) -> tuple[bytes, str]:
+ """The image's bytes and type."""
+ if image.path is not None:
+ data = read_local(caller, image.path, max_bytes)
+ elif image.data_url is not None:
+ match = _DATA_URL.match(image.data_url)
+ if match is None:
+ raise ToolError("data_url must be data:image/png, image/jpeg or image/webp;base64,...")
+ data = decode_base64(match.group(2), max_bytes, "data_url")
+ else:
+ response = await forward(caller, "GET", image_gallery_path(image.gallery_id))
+ raise_for_route(response)
+ data = response.content
+ if len(data) > max_bytes:
+ raise ToolError(f"Gallery image {image.gallery_id} is too large to send")
+ mime = sniff_image(data)
+ if mime not in mimes:
+ allowed = ", ".join(m.removeprefix("image/").upper() for m in mimes)
+ raise ToolError(f"Images must be {allowed}")
+ return data, mime
+
+
+async def resolve_images(
+ caller: Caller, images: list[ImageInput], *, total_cap: int, too_large: str, **limits: Any
+) -> list[str]:
+ """Each image as a data URL, refused with ``too_large`` as soon as their bytes together pass ``total_cap``."""
+ urls, total = [], 0
+ for image in images:
+ data, mime = await resolve_image(caller, image, **limits)
+ total += len(data)
+ if total > total_cap:
+ raise ToolError(too_large)
+ urls.append(data_url(data, mime))
+ return urls
+
+
+def data_url(data: bytes, mime: str) -> str:
+ return f"data:{mime};base64,{base64.b64encode(data).decode('ascii')}"
+
+
+MAX_AUDIO_BYTES = 200 * 1024 * 1024
+_AUDIO_ID = re.compile(r"^[A-Za-z0-9_-]{1,128}$")
+
+
+class AudioInput(BaseModel):
+ """Exactly one of ``path`` (a file on the Unsloth Studio computer), ``data_base64`` with a ``filename``, or an Unsloth Studio id: ``input_id`` (an uploaded clip), ``clip_id`` (an Audio history clip) or ``voice_id`` (a saved voice). Inline data rides in the MCP request, which is limited to 4 MiB."""
+
+ model_config = ConfigDict(extra = "forbid")
+
+ path: Optional[str] = None
+ data_base64: Optional[str] = None
+ filename: Optional[str] = None
+ input_id: Optional[str] = None
+ clip_id: Optional[str] = None
+ voice_id: Optional[str] = None
+
+ @model_validator(mode = "after")
+ def _exactly_one(self) -> "AudioInput":
+ sources = (self.path, self.data_base64, self.input_id, self.clip_id, self.voice_id)
+ if sum(value is not None for value in sources) != 1:
+ raise ValueError(
+ "Give exactly one of path, data_base64, input_id, clip_id or voice_id."
+ )
+ if (self.filename is not None) != (self.data_base64 is not None):
+ raise ValueError("filename goes with data_base64, and data_base64 needs one.")
+ for value in (self.input_id, self.clip_id, self.voice_id):
+ if value is not None and not _AUDIO_ID.match(value):
+ raise ValueError("Unsloth Studio audio ids are letters, digits, - and _.")
+ return self
+
+ @property
+ def is_upload(self) -> bool:
+ return self.path is not None or self.data_base64 is not None
+
+
+def audio_bytes(caller: Caller, audio: AudioInput) -> tuple[bytes, str]:
+ """The bytes and a display name of an audio input given as a path or inline data."""
+ if audio.path is not None:
+ return read_local(caller, audio.path, MAX_AUDIO_BYTES), Path(audio.path).name
+ return decode_base64(audio.data_base64, MAX_AUDIO_BYTES, "data_base64"), audio.filename
+
+
+async def upload_audio(caller: Caller, data: bytes, name: str) -> str:
+ """Store audio with Unsloth Studio and return its input id. Raw bytes, so the upload route sees a Content-Length; a re-upload of the same audio answers 200 with the existing id."""
+ if len(data) > MAX_AUDIO_BYTES:
+ raise ToolError("Audio is larger than 200 MiB")
+ response = await forward(
+ caller, "POST", "/v1/audio/inputs", params = {"name": name[:255] or "audio"}, content = data
+ )
+ record = raise_for_route(response)
+ if not isinstance(record, dict) or not isinstance(record.get("id"), str):
+ raise ToolError("Unsloth Studio did not store the audio")
+ return record["id"]
+
+
+async def audio_ref(caller: Caller, audio: AudioInput) -> dict[str, str]:
+ """The ``{input_id|clip_id|voice_id}`` reference an Unsloth Studio audio route takes, uploading first when needed."""
+ if audio.is_upload:
+ data, name = audio_bytes(caller, audio)
+ return {"input_id": await upload_audio(caller, data, name)}
+ for key in ("input_id", "clip_id", "voice_id"):
+ value = getattr(audio, key)
+ if value is not None:
+ return {key: value}
+ raise ToolError("No audio was given")
diff --git a/studio/backend/studio_mcp/loading.py b/studio/backend/studio_mcp/loading.py
new file mode 100644
index 00000000000..5992f12eb58
--- /dev/null
+++ b/studio/backend/studio_mcp/loading.py
@@ -0,0 +1,404 @@
+# 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 and unload models per kind. A load call blocks until the model is ready (a big download can take an hour), so progress comes from polling the progress routes in a sibling task and reporting it to the agent."""
+
+from __future__ import annotations
+
+import asyncio
+import dataclasses
+from typing import Any, Awaitable, Callable, Optional
+
+from fastmcp import Context
+from fastmcp.exceptions import ToolError
+
+from studio_mcp.caller import Caller
+from studio_mcp.errors import tool_error
+from studio_mcp.outputs import LoadResult, UnloadResult
+from studio_mcp.tools import as_dict, number, opt_text, route_json, strings
+
+POLL_INTERVAL_S = 2.0
+
+Progress = Optional[tuple[float, str]]
+
+
+async def with_progress(
+ ctx: Optional[Context], work: Awaitable[Any], poll: Callable[[], Awaitable[Progress]]
+) -> Any:
+ """Await ``work`` while reporting what ``poll`` sees. A failed poll is skipped, never fatal."""
+ task = asyncio.ensure_future(work)
+ try:
+ while True:
+ done, _pending = await asyncio.wait({task}, timeout = POLL_INTERVAL_S)
+ if done:
+ return task.result()
+ try:
+ progress = await poll()
+ except Exception:
+ progress = None
+ if progress is not None and ctx is not None:
+ await ctx.report_progress(progress[0], 1.0, progress[1])
+ finally:
+ if not task.done():
+ task.cancel()
+
+
+def _llm_poll(caller: Caller, model: str) -> Callable[[], Awaitable[Progress]]:
+ async def poll() -> Progress:
+ loading = await route_json("GET", "/api/inference/load-progress", caller = caller)
+ fraction = number(loading.get("fraction")) if isinstance(loading, dict) else None
+ if 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]:
+ return None
+ download = await route_json(
+ "GET",
+ "/api/models/download-progress",
+ caller = caller,
+ params = {"repo_id": model},
+ hub_header = True,
+ )
+ fraction = number(download.get("progress")) if isinstance(download, dict) else None
+ return (min(fraction, 1.0), "Downloading") if fraction else None
+
+ return poll
+
+
+async def load_llm(
+ caller: Caller,
+ ctx: Optional[Context],
+ *,
+ model: str,
+ variant: Optional[str],
+ max_seq_length: Optional[int],
+ load_in_4bit: bool,
+ hf_token: Optional[str],
+ kind: str = "llm",
+) -> LoadResult:
+ body: dict[str, Any] = {
+ "model_path": model,
+ "load_in_4bit": load_in_4bit,
+ "max_seq_length": max_seq_length or 0,
+ }
+ if variant:
+ body["gguf_variant"] = variant
+ # The load routes read the Hub token from the body, not the header.
+ token = hf_token or caller.hf_token
+ if token:
+ body["hf_token"] = token
+ before = await _serving_or_empty(caller)
+ payload = await with_progress(
+ ctx,
+ route_json("POST", "/api/inference/load", caller = caller, json_body = body),
+ _llm_poll(caller, model),
+ )
+ if not isinstance(payload, dict):
+ raise ToolError("Unsloth Studio did not confirm the load")
+ loaded = opt_text(payload.get("model")) or model
+ evicted = strings(payload.get("evicted"))
+ # Some loads (an audio engine switch) drop the chat model unlisted; only then, since the route lists its own drops by another id form.
+ if before and not evicted:
+ after = set(await _serving_or_empty(caller))
+ evicted += [
+ m for m in before if m not in after and m not in evicted and m not in (model, loaded)
+ ]
+ return LoadResult(
+ kind = kind, model = loaded, display_name = opt_text(payload.get("display_name")), evicted = evicted
+ )
+
+
+async def _serving_or_empty(caller: Caller) -> list[str]:
+ try:
+ serving, _checkpoints, _resident = await _llm_resident(caller)
+ except Exception:
+ # Only a report: a status read that fails must not turn a finished load into an error.
+ return []
+ return serving
+
+
+async def _llm_resident(caller: Caller) -> tuple[list[str], list[str], set[str]]:
+ status = as_dict(await route_json("GET", "/api/inference/status", caller = caller))
+ serving, checkpoints = (
+ strings(status.get("serving")),
+ strings(status.get("serving_checkpoints")),
+ )
+ return serving, checkpoints, {*serving, *checkpoints, *strings(status.get("loaded"))}
+
+
+async def unload_llm(caller: Caller, model: Optional[str]) -> UnloadResult:
+ serving, checkpoints, before = await _llm_resident(caller)
+ if model is None:
+ if not checkpoints:
+ return UnloadResult(kind = "llm", unloaded = False)
+ target, model = checkpoints[0], (serving[0] if serving else checkpoints[0])
+ else:
+ # The route unloads by checkpoint id, listed in the same order as serving.
+ target = dict(zip(serving, checkpoints)).get(model, model)
+ await route_json(
+ "POST", "/api/inference/unload", caller = caller, json_body = {"model_path": target}
+ )
+ # An id that matches nothing still answers success, so compare what is resident before and after.
+ _serving, _checkpoints, after = await _llm_resident(caller)
+ was_loaded = bool({model, target} & before)
+ return UnloadResult(
+ kind = "llm", model = model, unloaded = was_loaded and not ({model, target} & after)
+ )
+
+
+MEDIA_ROUTES = {
+ kind: {
+ "plan": f"/api/inference/{prefix}/download-plan",
+ "load": f"/api/inference/{prefix}/load",
+ "progress": f"/api/inference/{prefix}/load-progress",
+ "status": f"/api/inference/{prefix}/status",
+ "unload": f"/api/inference/{prefix}/unload",
+ }
+ for kind, prefix in (("image", "images"), ("video", "video"))
+}
+# Polls with no load in flight and the model still not resident before the load counts as lost.
+_IDLE_POLLS = 5
+
+
+def _media_fraction(progress: dict) -> Optional[float]:
+ # Images report bytes_downloaded/bytes_total, video downloaded_bytes/expected_bytes.
+ done = number(progress.get("bytes_downloaded", progress.get("downloaded_bytes")))
+ total = number(progress.get("bytes_total", progress.get("expected_bytes")))
+ if done is not None and total:
+ return min(done / total, 1.0)
+ return number(progress.get("fraction"))
+
+
+def _resident_matches(status: Any, model: str) -> bool:
+ if not isinstance(status, dict) or status.get("loaded") is not True:
+ return False
+ names = {opt_text(status.get("repo_id")), opt_text(status.get("display_repo_id"))}
+ return model.lower() in {name.lower() for name in names if name}
+
+
+async def _gguf_filename(caller: Caller, model: str, variant: Optional[str]) -> Optional[str]:
+ """The checkpoint file to load from a GGUF repo: the named variant, else the repo's default."""
+ listing = await route_json(
+ "GET", "/api/hub/gguf-variants", caller = caller, params = {"repo_id": model}, hub_header = True
+ )
+ listing = as_dict(listing)
+ variants = [v for v in listing.get("variants") or [] if isinstance(v, dict)]
+ wanted = (variant or opt_text(listing.get("default_variant")) or "").lower()
+ for entry in variants:
+ if str(entry.get("quant", "")).lower() == wanted and opt_text(entry.get("filename")):
+ return entry["filename"]
+ if variant:
+ raise ToolError(f"{model} has no GGUF variant {variant}")
+ return opt_text(variants[0].get("filename")) if variants else None
+
+
+async def load_media(
+ caller: Caller,
+ ctx: Optional[Context],
+ *,
+ kind: str,
+ model: str,
+ variant: Optional[str],
+ hf_token: Optional[str],
+) -> LoadResult:
+ routes = MEDIA_ROUTES[kind]
+ if hf_token:
+ # The GGUF lookup reads the Hub token from the header, so a gated repo needs it there too.
+ caller = dataclasses.replace(caller, hf_token = hf_token)
+ body: dict[str, Any] = {"model_path": model}
+ token = hf_token or caller.hf_token
+ if token:
+ body["hf_token"] = token
+ if variant or "gguf" in model.lower():
+ filename = await _gguf_filename(caller, model, variant)
+ if filename:
+ body["gguf_filename"] = filename
+ body["model_kind"] = "gguf"
+ # The plan validates the pick the way the load does, before any download.
+ plan = await route_json("POST", routes["plan"], caller = caller, json_body = body)
+ if isinstance(plan, dict):
+ if opt_text(plan.get("incompatible_reason")):
+ raise tool_error(plan["incompatible_reason"])
+ if "gguf_filename" not in body:
+ for entry in plan.get("entries") or []:
+ if (
+ isinstance(entry, dict)
+ and entry.get("checkpoint")
+ and opt_text(entry.get("gguf_filename"))
+ ):
+ body["gguf_filename"] = entry["gguf_filename"]
+ break
+ # The GPU arbiter may unload chat models to make room; diffed after the load like an LLM load.
+ before = await _serving_or_empty(caller)
+ # Starts the load in the background; its answer describes whatever was resident before.
+ await route_json("POST", routes["load"], caller = caller, json_body = body)
+ idle = 0
+ while True:
+ progress = as_dict(await route_json("GET", routes["progress"], caller = caller))
+ phase = progress.get("phase")
+ if phase == "error":
+ raise tool_error(opt_text(progress.get("error")) or f"The {kind} model failed to load")
+ if phase == "ready":
+ break
+ status = None
+ if phase is None:
+ status = await route_json("GET", routes["status"], caller = caller)
+ if _resident_matches(status, model):
+ break
+ idle += 1
+ if idle >= _IDLE_POLLS:
+ raise ToolError(
+ f"Unsloth Studio stopped reporting the {kind} load without loading {model}. "
+ "Another model load or a training run may be using the GPU; check studio_status and try again."
+ )
+ else:
+ idle = 0
+ fraction = _media_fraction(progress)
+ if ctx is not None and fraction is not None:
+ await ctx.report_progress(
+ fraction, 1.0, "Downloading" if phase == "downloading" else str(phase)
+ )
+ await asyncio.sleep(POLL_INTERVAL_S)
+ status = await route_json("GET", routes["status"], caller = caller)
+ if not _resident_matches(status, model):
+ raise ToolError(f"Unsloth Studio did not finish loading {model} as the {kind} model")
+ after = set(await _serving_or_empty(caller)) if before else set()
+ return LoadResult(
+ kind = kind,
+ model = opt_text(status.get("display_repo_id")) or opt_text(status.get("repo_id")) or model,
+ evicted = [name for name in before if name not in after],
+ )
+
+
+async def unload_media(caller: Caller, kind: str) -> UnloadResult:
+ routes = MEDIA_ROUTES[kind]
+ before = as_dict(await route_json("GET", routes["status"], caller = caller))
+ if before.get("loaded") is not True:
+ return UnloadResult(kind = kind, unloaded = False)
+ after = await route_json("POST", routes["unload"], caller = caller)
+ model = opt_text(before.get("display_repo_id")) or opt_text(before.get("repo_id"))
+ unloaded = isinstance(after, dict) and after.get("loaded") is not True
+ return UnloadResult(kind = kind, model = model, unloaded = unloaded)
+
+
+STT_STATUS = "/api/inference/audio/stt/status"
+# Transformers first: it is Studio's default and serves custom Whisper repos no list names.
+STT_ENGINES = ("transformers", "mtmd", "audiocpp", "gguf")
+
+
+async def stt_status(caller: Caller, model: Optional[str] = None) -> dict:
+ params = {"model": model} if model else None
+ return as_dict(await route_json("GET", STT_STATUS, caller = caller, params = params))
+
+
+def stt_engine(status: dict, model: str) -> str:
+ # Whisper ids are shared across engines: the one holding the model wins.
+ for engine in STT_ENGINES:
+ state = status.get(engine)
+ if isinstance(state, dict) and state.get("loaded_model") == model:
+ return engine
+ for engine in STT_ENGINES:
+ state = status.get(engine)
+ if isinstance(state, dict) and model in {
+ *strings(state.get("models")),
+ *strings(state.get("downloaded_models")),
+ }:
+ return engine
+ return "transformers"
+
+
+async def download_stt(
+ caller: Caller,
+ ctx: Optional[Context],
+ *,
+ model: str,
+ engine: str,
+ hf_token: Optional[str],
+ variant: Optional[str] = None,
+) -> None:
+ """Download an STT model and wait for it; the download route reads the Hub token from its header."""
+ if hf_token:
+ caller = dataclasses.replace(caller, hf_token = hf_token)
+ started = await route_json(
+ "POST",
+ "/api/inference/audio/stt/download",
+ caller = caller,
+ json_body = {
+ "model": model,
+ "engine": engine,
+ **({"gguf_variant": variant} if variant else {}),
+ },
+ hub_header = True,
+ )
+ download_id = started.get("download_id") if isinstance(started, dict) else None
+ while True:
+ await asyncio.sleep(POLL_INTERVAL_S)
+ state = (await stt_status(caller, model)).get(engine)
+ download = as_dict(as_dict(state).get("download"))
+ if download.get("downloading"):
+ done, total = number(download.get("bytes_done")), number(download.get("bytes_total"))
+ if ctx is not None and done is not None and total:
+ await ctx.report_progress(min(done / total, 1.0), 1.0, "Downloading")
+ continue
+ if opt_text(download.get("error")):
+ raise tool_error(f"Downloading {model} failed: {download['error']}")
+ if download.get("cancelled"):
+ raise ToolError(f"The download of {model} was cancelled")
+ if download_id is None or download_id in strings(download.get("completed_download_ids")):
+ return
+ if model in strings(as_dict(state).get("downloaded_models")):
+ return
+ raise ToolError(f"Unsloth Studio stopped downloading {model} before it finished")
+
+
+async def load_stt(
+ caller: Caller,
+ ctx: Optional[Context],
+ *,
+ model: str,
+ variant: Optional[str],
+ hf_token: Optional[str],
+) -> LoadResult:
+ status = await stt_status(caller, model)
+ engine = stt_engine(status, model)
+ state = as_dict(status.get(engine))
+ # Load refuses a model that is not on disk, so download first and load only once that finished.
+ # The route folds a variant into "model:variant"; another cached variant does not count.
+ wanted = f"{model}:{variant}" if variant and ":" not in model else model
+ if wanted not in strings(state.get("downloaded_models")):
+ await download_stt(
+ caller, ctx, model = model, engine = engine, hf_token = hf_token, variant = variant
+ )
+ body: dict[str, Any] = {"model": model, "engine": engine}
+ if variant:
+ body["gguf_variant"] = variant
+ loaded = await route_json(
+ "POST", "/api/inference/audio/stt/load", caller = caller, json_body = body
+ )
+ resident = opt_text(loaded.get("loaded_model")) if isinstance(loaded, dict) else None
+ if resident is None:
+ raise ToolError(
+ f"Unsloth Studio did not keep {model} loaded; another load may have replaced it"
+ )
+ return LoadResult(kind = "stt", model = resident)
+
+
+async def unload_stt(caller: Caller, model: Optional[str]) -> UnloadResult:
+ status = await stt_status(caller)
+ resident = {
+ engine: status[engine]["loaded_model"]
+ for engine in STT_ENGINES
+ if isinstance(status.get(engine), dict) and opt_text(status[engine].get("loaded_model"))
+ }
+ targets = [(e, m) for e, m in resident.items() if model is None or m == model]
+ if not targets:
+ return UnloadResult(kind = "stt", model = model, unloaded = False)
+ engine, name = targets[0]
+ await route_json(
+ "POST",
+ "/api/inference/audio/stt/unload",
+ caller = caller,
+ params = {"engine": engine, "model": name, "wait": "true"},
+ )
+ after = (await stt_status(caller)).get(engine)
+ still = isinstance(after, dict) and after.get("loaded_model") == name
+ return UnloadResult(kind = "stt", model = name, unloaded = not still)
diff --git a/studio/backend/studio_mcp/media.py b/studio/backend/studio_mcp/media.py
new file mode 100644
index 00000000000..bc7fe022f85
--- /dev/null
+++ b/studio/backend/studio_mcp/media.py
@@ -0,0 +1,80 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""How generated media reaches the agent: inline when small, otherwise a link to the Unsloth Studio gallery. Links are built from the address the agent used to reach /mcp, never from a forwarded answer, which only knows the in-process ``unsloth-mcp.invalid`` host."""
+
+from __future__ import annotations
+
+import base64
+import json
+from typing import Any, Optional
+from urllib.parse import quote, urlsplit
+
+from fastmcp.exceptions import ToolError
+from fastmcp.tools import ToolResult
+from mcp.types import AudioContent, ImageContent, ResourceLink, TextContent
+
+from studio_mcp.caller import Caller
+from studio_mcp.outputs import ToolOutput
+
+# Agents put inline media straight into the model's context; past this a link is kinder.
+INLINE_CAP = 1536 * 1024
+MEDIA_PREFIXES = ("/v1/", "/api/inference/")
+THUMB_SIDE = 1024
+
+
+def image_content(data: bytes, mime: str) -> ImageContent:
+ return ImageContent(type = "image", data = base64.b64encode(data).decode("ascii"), mimeType = mime)
+
+
+def audio_content(data: bytes, mime: str) -> AudioContent:
+ return AudioContent(type = "audio", data = base64.b64encode(data).decode("ascii"), mimeType = mime)
+
+
+def resource_link(
+ url: str,
+ name: str,
+ mime: Optional[str] = None,
+) -> ResourceLink:
+ return ResourceLink(type = "resource_link", uri = url, name = name, mimeType = mime)
+
+
+def _base(caller: Caller) -> str:
+ """The outer request's base, with the tunnel's scheme when it came through cloudflared, which reaches Unsloth Studio over plain http."""
+ base = urlsplit(caller.public_base)
+ tunnel = getattr(getattr(caller.studio_app, "state", None), "cloudflare_url", None)
+ if isinstance(tunnel, str) and tunnel:
+ published = urlsplit(tunnel)
+ if (
+ published.scheme in ("http", "https")
+ and published.netloc.lower() == base.netloc.lower()
+ ):
+ return f"{published.scheme}://{base.netloc}{base.path}"
+ return f"{base.scheme}://{base.netloc}{base.path}"
+
+
+def public_url(caller: Caller, path: str) -> str:
+ """An absolute Unsloth Studio URL for a media route, from a path or from a URL a route built for itself."""
+ parts = urlsplit(path)
+ if not parts.path.startswith(MEDIA_PREFIXES):
+ raise ToolError("Unsloth Studio returned a media link this tool cannot share")
+ query = f"?{parts.query}" if parts.query else ""
+ return f"{_base(caller)}{parts.path}{query}"
+
+
+def image_gallery_path(image_id: str, thumb: bool = False) -> str:
+ path = f"/api/inference/images/gallery/{quote(image_id, safe = '')}/file"
+ return f"{path}?thumb={THUMB_SIDE}" if thumb else path
+
+
+def audio_gallery_path(clip_id: str) -> str:
+ return f"/v1/audio/gallery/{quote(clip_id, safe = '')}/file"
+
+
+def media_result(contents: list[Any], output: ToolOutput) -> ToolResult:
+ """Media plus the typed output, which also goes first as JSON text for clients that ignore structuredContent."""
+ structured = output.model_dump(mode = "json")
+ text = TextContent(
+ type = "text", text = json.dumps(structured, ensure_ascii = False, separators = (",", ":"))
+ )
+ return ToolResult(content = [text, *contents], structured_content = structured)
diff --git a/studio/backend/studio_mcp/outputs.py b/studio/backend/studio_mcp/outputs.py
new file mode 100644
index 00000000000..c88aeb3806a
--- /dev/null
+++ b/studio/backend/studio_mcp/outputs.py
@@ -0,0 +1,450 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Typed tool outputs. Several Unsloth Studio routes still return host paths to API-key callers, so a tool never passes route JSON through: it copies named fields into a ToolOutput, which refuses anything undeclared. Free text that came from a route (a status message, an error) is declared ``RouteText`` and scrubbed of paths as a backstop; model-written text and Unsloth Studio URLs are plain ``str`` and left alone."""
+
+from __future__ import annotations
+
+from typing import Annotated, Any, Optional, TypeVar, Union, get_args, get_origin
+
+from pydantic import AfterValidator, BaseModel, ConfigDict, StrictBool, StrictFloat, StrictInt
+
+from hub.utils.host_paths import redact_paths_in_text
+
+RouteText = Annotated[str, AfterValidator(redact_paths_in_text)]
+
+
+class ToolOutput(BaseModel):
+ model_config = ConfigDict(extra = "forbid")
+
+ @classmethod
+ def from_route(cls: type[_Out], payload: Any, **overrides: Any) -> _Out:
+ """Copy each declared field from route JSON, coerced by its type: text must be non-empty, numbers must not be bools, a bool must be ``true``, a list of text keeps its strings. A field the route left out or sent malformed keeps its default; nested models, dicts and anything needing more care come in through ``overrides``."""
+ row = payload if isinstance(payload, dict) else {}
+ fields = {}
+ for name, info in cls.model_fields.items():
+ value = None if name in overrides else _route_value(info.annotation, row.get(name))
+ if value is not None:
+ fields[name] = value
+ return cls(**fields, **overrides)
+
+
+_Out = TypeVar("_Out", bound = ToolOutput)
+
+
+def _unwrap(annotation: Any) -> Any:
+ # The type under Annotated and Optional; None for a union of several types.
+ while get_origin(annotation) is Annotated:
+ annotation = get_args(annotation)[0]
+ if get_origin(annotation) is Union:
+ kinds = [kind for kind in get_args(annotation) if kind is not type(None)]
+ return _unwrap(kinds[0]) if len(kinds) == 1 else None
+ return annotation
+
+
+def _route_value(annotation: Any, value: Any) -> Any:
+ from studio_mcp.tools import integer, number, opt_text
+
+ kind = _unwrap(annotation)
+ if get_origin(kind) is list:
+ if _unwrap(get_args(kind)[0]) is not str or not isinstance(value, list):
+ return None
+ return [item for item in value if isinstance(item, str)]
+ if kind is bool:
+ return value is True
+ rule = {str: opt_text, int: integer, float: number}.get(kind)
+ return rule(value) if rule else None
+
+
+class AudioOption(ToolOutput):
+ name: RouteText
+ # bool, int, float, string or enum.
+ type: Optional[RouteText] = None
+ description: Optional[RouteText] = None
+ default: Optional[Union[StrictBool, StrictInt, StrictFloat, RouteText]] = None
+ min: Optional[float] = None
+ max: Optional[float] = None
+ # An enum's accepted values, such as the model's built-in voices.
+ values: list[RouteText] = []
+
+
+def audio_options(rows: Any) -> Optional[list[AudioOption]]:
+ """The options an audio model reports, or None when it reports none."""
+ options = []
+ for row in rows if isinstance(rows, list) else []:
+ if isinstance(row, dict) and isinstance(row.get("name"), str) and row["name"]:
+ default = row.get("default")
+ scalar = isinstance(default, (bool, int, float, str))
+ options.append(AudioOption.from_route(row, default = default if scalar else None))
+ return options or None
+
+
+class ChatModel(ToolOutput):
+ id: RouteText
+ display_name: Optional[RouteText] = None
+ is_gguf: Optional[bool] = None
+ # The active audio model's options for generate_audio, built-in voices included.
+ audio_options: Optional[list[AudioOption]] = None
+
+
+class ChatSlot(ToolOutput):
+ loaded: list[ChatModel] = []
+ loading: list[RouteText] = []
+
+
+class ImageSlot(ToolOutput):
+ loaded: bool = False
+ model: Optional[RouteText] = None
+ family: Optional[RouteText] = None
+ generating: bool = False
+
+
+class VideoSlot(ToolOutput):
+ loaded: bool = False
+ model: Optional[RouteText] = None
+ generating: bool = False
+
+
+class SttDownload(ToolOutput):
+ model: RouteText
+ fraction: Optional[float] = None
+
+
+class SttSlot(ToolOutput):
+ engine: Optional[RouteText] = None
+ model: Optional[RouteText] = None
+ loading: bool = False
+ downloading: list[SttDownload] = []
+
+
+class EmbedderSlot(ToolOutput):
+ # False when this key may not read the owner's embedder setting.
+ available: bool = False
+ loaded: bool = False
+ # A Hub repo id, or "custom" for a model the owner picked from disk.
+ model: Optional[RouteText] = None
+
+
+class TrainingSlot(ToolOutput):
+ job_id: Optional[RouteText] = None
+ phase: RouteText = "idle"
+ is_training_running: bool = False
+ message: RouteText = ""
+ error: Optional[RouteText] = None
+ step: Optional[int] = None
+ total_steps: Optional[int] = None
+ loss: Optional[float] = None
+ progress_percent: Optional[float] = None
+ eta_seconds: Optional[float] = None
+
+
+class ExportSlot(ToolOutput):
+ active: bool = False
+ op_kind: Optional[RouteText] = None
+ last_op_status: Optional[RouteText] = None
+ # The output folder's name, never its path.
+ last_output: Optional[RouteText] = None
+
+
+class GpuDevice(ToolOutput):
+ index: Optional[int] = None
+ gpu_utilization_pct: Optional[float] = None
+ vram_used_gb: Optional[float] = None
+ vram_total_gb: Optional[float] = None
+ temperature_c: Optional[float] = None
+
+
+class HardwareSlot(ToolOutput):
+ available: bool = False
+ backend: Optional[RouteText] = None
+ devices: list[GpuDevice] = []
+
+
+class StudioStatus(ToolOutput):
+ chat: ChatSlot = ChatSlot()
+ image: ImageSlot = ImageSlot()
+ video: VideoSlot = VideoSlot()
+ stt: SttSlot = SttSlot()
+ embedder: EmbedderSlot = EmbedderSlot()
+ training: TrainingSlot = TrainingSlot()
+ diffusion_training: TrainingSlot = TrainingSlot()
+ export: ExportSlot = ExportSlot()
+ hardware: HardwareSlot = HardwareSlot()
+ # Slots whose route failed, with the reason; the other slots are still reported.
+ unavailable: dict[str, RouteText] = {}
+
+
+class ModelEntry(ToolOutput):
+ id: RouteText
+ # From the route's task; "llm" when there is none.
+ kind: RouteText
+ loaded: bool = False
+ display_name: Optional[RouteText] = None
+ quant: Optional[RouteText] = None
+ context_length: Optional[int] = None
+ audio_workflows: Optional[list[RouteText]] = None
+
+
+class ModelList(ToolOutput):
+ models: list[ModelEntry] = []
+ # Studio's training defaults for the model named in the call.
+ training_defaults: Optional[dict[str, Union[StrictBool, StrictInt, StrictFloat, RouteText]]] = (
+ None
+ )
+
+
+class LoadResult(ToolOutput):
+ kind: RouteText
+ model: RouteText
+ loaded: bool = True
+ display_name: Optional[RouteText] = None
+ evicted: list[RouteText] = []
+
+
+class UnloadResult(ToolOutput):
+ kind: RouteText
+ model: Optional[RouteText] = None
+ unloaded: bool
+
+
+class Usage(ToolOutput):
+ prompt_tokens: Optional[int] = None
+ completion_tokens: Optional[int] = None
+ total_tokens: Optional[int] = None
+
+
+class ChatResult(ToolOutput):
+ # Model-written, so never rewritten.
+ text: str
+ model: Optional[RouteText] = None
+ finish_reason: Optional[RouteText] = None
+ usage: Optional[Usage] = None
+ note: Optional[RouteText] = None
+ # Pass to cancel(kind="chat", id=...) from another call to stop a long reply.
+ cancel_id: Optional[str] = None
+
+
+class EmbedResult(ToolOutput):
+ model: Optional[RouteText] = None
+ dimensions: int
+ embeddings: list[list[float]]
+
+
+class DecisionAnswer(ToolOutput):
+ type: RouteText
+ # noul: probability of yes. choice: the picked option. score: the level, 1 being lowest.
+ noul: Optional[float] = None
+ choice: Optional[RouteText] = None
+ score: Optional[float] = None
+ confidence: Optional[float] = None
+ probabilities: Optional[dict[str, float]] = None
+ legend: Optional[dict[str, RouteText]] = None
+
+
+class SystemOneResult(ToolOutput):
+ model: Optional[RouteText] = None
+ answers: dict[str, DecisionAnswer]
+ request_id: Optional[RouteText] = None
+
+
+class ImageItem(ToolOutput):
+ id: RouteText
+ url: str
+ width: Optional[int] = None
+ height: Optional[int] = None
+ seed: Optional[int] = None
+
+
+class ImageResult(ToolOutput):
+ images: list[ImageItem]
+
+
+class AudioClip(ToolOutput):
+ id: RouteText
+ role: RouteText = "output"
+ url: str
+ duration_s: Optional[float] = None
+ sample_rate: Optional[int] = None
+
+
+class AudioResult(ToolOutput):
+ model: Optional[RouteText] = None
+ group_id: Optional[RouteText] = None
+ clips: list[AudioClip] = []
+ # False when Studio could not save the clip to Audio history; the audio then comes back inline only.
+ saved: bool = True
+
+
+class TranscriptSegment(ToolOutput):
+ start: Optional[float] = None
+ end: Optional[float] = None
+ text: str = ""
+
+
+class TranscriptResult(ToolOutput):
+ text: str
+ language: Optional[RouteText] = None
+ model: Optional[RouteText] = None
+ segments: Optional[list[TranscriptSegment]] = None
+ saved_to_history: bool = False
+
+
+class VideoJobRef(ToolOutput):
+ id: RouteText
+ status: RouteText
+ progress: Optional[int] = None
+ model: Optional[RouteText] = None
+ seconds: Optional[RouteText] = None
+ size: Optional[RouteText] = None
+
+
+class VideoInfo(ToolOutput):
+ # The MP4, for the agent or its user to download; the tool never fetches it.
+ url: str
+ thumbnail_inline: bool = False
+
+
+class JobSummary(ToolOutput):
+ id: RouteText
+ status: RouteText
+ progress_percent: Optional[float] = None
+
+
+class RecipeError(ToolOutput):
+ message: RouteText
+ path: Optional[RouteText] = None
+
+
+class RecipeResult(ToolOutput):
+ mode: RouteText
+ valid: Optional[bool] = None
+ errors: Optional[list[RecipeError]] = None
+ job_id: Optional[RouteText] = None
+
+
+class RecipeInfo(ToolOutput):
+ stage: Optional[RouteText] = None
+ rows: Optional[int] = None
+ # The saved dataset's name under Studio's recipes folder, never its path.
+ dataset: Optional[RouteText] = None
+ total_rows: Optional[int] = None
+ data_rows: Optional[list[dict[str, Any]]] = None
+
+
+class ExportInfo(ToolOutput):
+ format: RouteText
+ # Relative to Studio's exports folder, or only a name; never a host path.
+ output: Optional[RouteText] = None
+ phase: RouteText
+
+
+class JobStatus(ToolOutput):
+ kind: RouteText
+ id: Optional[RouteText] = None
+ status: Optional[RouteText] = None
+ progress_percent: Optional[float] = None
+ error: Optional[RouteText] = None
+ video: Optional[VideoInfo] = None
+ recipe: Optional[RecipeInfo] = None
+ export: Optional[ExportInfo] = None
+ jobs: Optional[list[JobSummary]] = None
+
+
+class LocalDataset(ToolOutput):
+ id: RouteText
+ label: RouteText
+ source: RouteText = "local"
+ rows: Optional[int] = None
+
+
+class CachedDataset(ToolOutput):
+ repo_id: RouteText
+ size_bytes: Optional[int] = None
+
+
+class DatasetFormat(ToolOutput):
+ detected_format: Optional[RouteText] = None
+ requires_manual_mapping: Optional[bool] = None
+ columns: list[RouteText] = []
+ suggested_mapping: Optional[dict[str, RouteText]] = None
+ is_image: Optional[bool] = None
+ is_audio: Optional[bool] = None
+ total_rows: Optional[int] = None
+ warning: Optional[RouteText] = None
+
+
+class DatasetDownload(ToolOutput):
+ repo_id: RouteText
+ state: RouteText
+ error: Optional[RouteText] = None
+
+
+class DatasetsResult(ToolOutput):
+ local: Optional[list[LocalDataset]] = None
+ cached: Optional[list[CachedDataset]] = None
+ format: Optional[DatasetFormat] = None
+ download: Optional[DatasetDownload] = None
+
+
+class TrainingStarted(ToolOutput):
+ # None when validate_only checked the config without starting anything.
+ job_id: Optional[RouteText] = None
+ status: RouteText
+ message: Optional[RouteText] = None
+ # What cancel(kind="training_start") takes while the job has not begun.
+ start_request_id: Optional[RouteText] = None
+
+
+TrainingScalar = Union[StrictBool, StrictInt, StrictFloat, RouteText]
+
+
+class TrainingRun(ToolOutput):
+ id: RouteText
+ status: RouteText
+ model_name: Optional[RouteText] = None
+ dataset_name: Optional[RouteText] = None
+ display_name: Optional[RouteText] = None
+ started_at: Optional[RouteText] = None
+ ended_at: Optional[RouteText] = None
+ final_step: Optional[int] = None
+ final_loss: Optional[float] = None
+ can_resume: bool = False
+ error_message: Optional[RouteText] = None
+ # The run's folder name, which is also its checkpoint name for export_model.
+ run_folder: Optional[RouteText] = None
+
+
+class TrainingRunDetail(TrainingRun):
+ config: dict[str, TrainingScalar] = {}
+ step_history: Optional[list[int]] = None
+ loss_history: Optional[list[float]] = None
+
+
+class CheckpointName(ToolOutput):
+ run: RouteText
+ # "<run folder>" for the final weights, "<run folder>/<checkpoint>" for an intermediate one.
+ name: RouteText
+ loss: Optional[float] = None
+ base_model: Optional[RouteText] = None
+ peft_type: Optional[RouteText] = None
+ lora_rank: Optional[int] = None
+ is_quantized: bool = False
+
+
+class TrainingRuns(ToolOutput):
+ runs: list[TrainingRun] = []
+ total: Optional[int] = None
+ run: Optional[TrainingRunDetail] = None
+ checkpoints: Optional[list[CheckpointName]] = None
+
+
+class ExportJobRef(ToolOutput):
+ job_id: RouteText
+ status: RouteText = "running"
+
+
+class CancelResult(ToolOutput):
+ kind: RouteText
+ id: Optional[RouteText] = None
+ cancelled: bool
+ message: Optional[RouteText] = None
diff --git a/studio/backend/studio_mcp/tools/__init__.py b/studio/backend/studio_mcp/tools/__init__.py
new file mode 100644
index 00000000000..18ece31abfa
--- /dev/null
+++ b/studio/backend/studio_mcp/tools/__init__.py
@@ -0,0 +1,79 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The Unsloth Studio MCP tools, one module per area, each with a ``register_*(mcp)``."""
+
+from __future__ import annotations
+
+import re
+from typing import Any, Optional
+
+from mcp.types import ToolAnnotations
+
+from studio_mcp.caller import Caller, current_caller
+from studio_mcp.errors import raise_for_route
+from studio_mcp.forward import forward
+
+# Every tool acts on this Studio only. MCP assumes destructive unless told otherwise, so plain tools say so.
+READ_ONLY = ToolAnnotations(readOnlyHint = True, openWorldHint = False)
+DESTRUCTIVE = ToolAnnotations(readOnlyHint = False, destructiveHint = True, openWorldHint = False)
+WRITES = ToolAnnotations(readOnlyHint = False, destructiveHint = False, openWorldHint = False)
+EXPORT_STATUS = "/api/export/status"
+
+
+async def route_json(
+ method: str,
+ path: str,
+ *,
+ caller: Optional[Caller] = None,
+ hints: Optional[dict[int, str]] = None,
+ hint_if: Optional[tuple[str, dict[int, str]]] = None,
+ **kwargs: Any,
+) -> Any:
+ """Forward one call as the MCP caller and return its JSON, or raise a ToolError with ``hints`` guidance."""
+ response = await forward(caller or current_caller(), method, path, **kwargs)
+ # hint_if is (marker, hints): hints that apply only when the failed answer's text names the marker.
+ if hint_if is not None and response.status_code >= 400 and hint_if[0] in response.text:
+ hints = {**(hints or {}), **hint_if[1]}
+ return raise_for_route(response, hints = hints)
+
+
+async def try_json(caller: Caller, path: str, **kwargs: Any) -> Any:
+ # Best effort: the JSON of a 200 answer, else None; never raises.
+ try:
+ response = await forward(caller, "GET", path, **kwargs)
+ return response.json() if response.status_code == 200 else None
+ except Exception:
+ return None
+
+
+def number(value: Any) -> Optional[float]:
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ return None
+ return float(value)
+
+
+def integer(value: Any) -> Optional[int]:
+ if isinstance(value, bool) or not isinstance(value, int):
+ return None
+ return value
+
+
+def opt_text(value: Any) -> Optional[str]:
+ return value if isinstance(value, str) and value else None
+
+
+def strings(values: Any) -> list[str]:
+ return [v for v in values if isinstance(v, str)] if isinstance(values, list) else []
+
+
+def as_dict(value: Any) -> dict:
+ return value if isinstance(value, dict) else {}
+
+
+def leaf_name(path: str) -> str:
+ return re.split(r"[\\/]", path.rstrip("\\/"))[-1]
+
+
+def present(**values: Any) -> dict[str, Any]:
+ return {key: value for key, value in values.items() if value is not None}
diff --git a/studio/backend/studio_mcp/tools/audio.py b/studio/backend/studio_mcp/tools/audio.py
new file mode 100644
index 00000000000..bdfcce230f1
--- /dev/null
+++ b/studio/backend/studio_mcp/tools/audio.py
@@ -0,0 +1,387 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Audio tools: ``generate_audio`` runs any Audio page workflow and ``transcribe`` turns speech into text."""
+
+from __future__ import annotations
+
+import base64
+import binascii
+from typing import Any, Literal, Optional
+
+from fastmcp import Context
+from fastmcp.exceptions import ToolError
+from fastmcp.tools import ToolResult
+
+from studio_mcp import loading
+from studio_mcp.caller import Caller, current_caller
+from studio_mcp.errors import raise_for_route
+from studio_mcp.forward import forward, ndjson_last
+from studio_mcp.inputs import AudioInput, audio_bytes, audio_ref, upload_audio
+from studio_mcp.media import (
+ INLINE_CAP,
+ audio_content,
+ audio_gallery_path,
+ media_result,
+ public_url,
+ resource_link,
+)
+from studio_mcp.outputs import AudioClip, AudioResult, TranscriptResult, TranscriptSegment
+from studio_mcp.tools import WRITES, opt_text, present, route_json, strings, try_json
+
+LOAD_AUDIO_HINT = "Load a text-to-speech or music model with load_model(kind='tts') first."
+NOT_LOADED = "No model loaded"
+# 16-bit samples; channels are not reported, so mono is assumed and a stereo clip may still be fetched and then linked.
+_WAV_BYTES_PER_SAMPLE = 2
+
+
+async def _clip_contents(caller: Caller, clip: AudioClip) -> list[Any]:
+ """A clip inline when its WAV fits the cap, else a link; one that cannot fit is never fetched."""
+ estimate = (clip.duration_s or 0) * (clip.sample_rate or 0) * _WAV_BYTES_PER_SAMPLE
+ if clip.duration_s and clip.sample_rate and estimate <= INLINE_CAP:
+ response = await forward(caller, "GET", audio_gallery_path(clip.id))
+ if response.status_code == 200 and len(response.content) <= INLINE_CAP:
+ mime = response.headers.get("content-type", "audio/wav").split(";")[0]
+ return [audio_content(response.content, mime)]
+ return [resource_link(clip.url, f"{clip.id}.wav", "audio/wav")]
+
+
+async def _checked_options(
+ caller: Caller, workflow: str, options: dict[str, Any]
+) -> dict[str, Any]:
+ """``options`` with each enum value spelled as the loaded model lists it; the route drops a value it does not list, so that is refused here instead."""
+ status = await try_json(caller, "/api/inference/status")
+ if not isinstance(status, dict):
+ return options
+ by_workflow = status.get("audio_options_by_workflow")
+ schema = (by_workflow.get(workflow) if isinstance(by_workflow, dict) else None) or status.get(
+ "audio_options"
+ )
+ checked = dict(options)
+ for option in schema if isinstance(schema, list) else []:
+ if not isinstance(option, dict) or option.get("type") != "enum":
+ continue
+ name, values = option.get("name"), strings(option.get("values"))
+ if not isinstance(name, str) or checked.get(name) is None or not values:
+ continue
+ value = str(checked[name])
+ match = (
+ value
+ if value in values
+ else next((v for v in values if v.casefold() == value.casefold()), None)
+ )
+ if match is None:
+ raise ToolError(f"options.{name} '{value}' is not one of: {', '.join(values)}.")
+ checked[name] = match
+ return checked
+
+
+async def generate_audio(
+ workflow: Literal["clone", "speak", "edit", "convert", "music", "separate"],
+ text: Optional[str] = None,
+ language: Optional[str] = None,
+ instructions: Optional[str] = None,
+ reference: Optional[AudioInput] = None,
+ source: Optional[AudioInput] = None,
+ emotion: Optional[AudioInput] = None,
+ target: Optional[AudioInput] = None,
+ reference_text: Optional[str] = None,
+ source_text: Optional[str] = None,
+ mode: Optional[Literal["song", "sfx", "edit"]] = None,
+ lyrics: Optional[str] = None,
+ instrumental: bool = False,
+ duration_s: Optional[float] = None,
+ variations: int = 1,
+ edit: Optional[dict[str, Any]] = None,
+ convert: Optional[dict[str, Any]] = None,
+ speed: Optional[float] = None,
+ seed: Optional[int] = None,
+ max_tokens: Optional[int] = None,
+ options: Optional[dict[str, Any]] = None,
+) -> ToolResult:
+ """Run an Audio page workflow with the audio model loaded in Unsloth Studio; clips are saved to Audio history and returned inline when small, else as links. clone: speak ``text`` in the voice of ``reference`` (a clip, or a saved voice as voice_id; ``reference_text`` is its transcript). speak: ``text`` in the loaded model's default voice, or a saved voice via ``reference``. edit: change the words or delivery of ``source`` per ``edit``. convert: make ``source`` sound like ``target``. music: ``mode`` song or sfx from ``text`` (the style) and ``lyrics``; ``variations`` up to 4 share a group_id. separate: split ``source`` into stems. ``options`` are the loaded model's ``audio_options`` that studio_status lists, such as a built-in ``voice``. Audio inputs are an Unsloth Studio id, inline base64 with a filename, or a path on the Unsloth Studio computer."""
+ caller = current_caller()
+ inputs: dict[str, Any] = {}
+ for key, audio in (
+ ("reference", reference),
+ ("source", source),
+ ("emotion", emotion),
+ ("target", target),
+ ):
+ if audio is not None:
+ inputs[key] = await audio_ref(caller, audio)
+ inputs.update(present(reference_text = reference_text, source_text = source_text))
+ if options:
+ options = await _checked_options(caller, workflow, options)
+ body: dict[str, Any] = {"workflow": workflow, "inputs": inputs}
+ body.update(
+ present(
+ text = text,
+ language = language,
+ instructions = instructions,
+ mode = mode,
+ lyrics = lyrics,
+ duration_s = duration_s,
+ edit = edit,
+ convert = convert,
+ speed = speed,
+ seed = seed,
+ max_tokens = max_tokens,
+ options = options,
+ )
+ )
+ if instrumental:
+ body["instrumental"] = True
+ if variations != 1:
+ body["variations"] = variations
+ payload = await route_json(
+ "POST",
+ "/v1/audio/run",
+ caller = caller,
+ json_body = body,
+ hint_if = (NOT_LOADED, {400: LOAD_AUDIO_HINT}),
+ )
+ if not isinstance(payload, dict):
+ raise ToolError("Unsloth Studio returned no audio")
+ clips, contents = [], []
+ for row in payload.get("clips") or []:
+ if not isinstance(row, dict) or not opt_text(row.get("id")):
+ continue
+ clip = AudioClip.from_route(row, url = public_url(caller, audio_gallery_path(row["id"])))
+ clips.append(clip)
+ contents.extend(await _clip_contents(caller, clip))
+ saved = True
+ fallback = payload.get("audio")
+ if isinstance(fallback, dict) and isinstance(fallback.get("data"), str):
+ # History could not save the clip, so the route sent it inline instead.
+ saved = False
+ try:
+ data = base64.b64decode(fallback["data"], validate = True)
+ except (binascii.Error, ValueError):
+ raise ToolError("Unsloth Studio returned unreadable audio") from None
+ if len(data) > INLINE_CAP:
+ raise ToolError(
+ f"Unsloth Studio could not save the clip to Audio history, and at "
+ f"{len(data) / (1024 * 1024):.1f} MiB it is too large to return inline."
+ )
+ contents.append(audio_content(data, f"audio/{opt_text(fallback.get('format')) or 'wav'}"))
+ if not clips and saved:
+ raise ToolError("Unsloth Studio returned no audio")
+ return media_result(contents, AudioResult.from_route(payload, clips = clips, saved = saved))
+
+
+# OpenAI's own upload limit for /audio/transcriptions; past it the tool uploads first.
+MULTIPART_LIMIT = 25 * 1024 * 1024
+NOT_DOWNLOADED = "is not downloaded"
+TIMESTAMPS_HINT = (
+ "Timestamps need a speech-to-text model that times segments, such as Qwen3-ASR (audio.cpp) "
+ "or Parakeet-TDT; pass it as model."
+)
+
+
+def _segments(payload: dict) -> list[TranscriptSegment]:
+ # The routes leave segments out when there are none, which is not the same as not asking.
+ rows = payload.get("segments")
+ if not isinstance(rows, list):
+ return []
+ return [TranscriptSegment.from_route(row) for row in rows if isinstance(row, dict)]
+
+
+def _default_stt(status: dict) -> Optional[str]:
+ default = status.get("transformers") if isinstance(status.get("transformers"), dict) else {}
+ return opt_text(default.get("default_model")) or opt_text(status.get("default_model"))
+
+
+async def _download_then_retry(
+ caller: Caller, ctx: Optional[Context], model: Optional[str]
+) -> None:
+ """Fetch the STT model a transcription refused as missing, the way load_model does."""
+ status = await loading.stt_status(caller, model)
+ if model is None:
+ model = _default_stt(status)
+ if model is None:
+ raise ToolError("Unsloth Studio did not name a default speech-to-text model to download")
+ engine = loading.stt_engine(status, model)
+ await loading.download_stt(caller, ctx, model = model, engine = engine, hf_token = None)
+
+
+async def _multipart(
+ caller: Caller,
+ data: bytes,
+ name: str,
+ *,
+ language: Optional[str],
+ translate: bool,
+ timestamps: bool,
+ model: Optional[str],
+):
+ fields: dict[str, Any] = {"response_format": "verbose_json" if timestamps else "json"}
+ if timestamps and not translate:
+ # The route times segments only when asked, and refuses loudly on an engine that cannot.
+ fields["timestamp_granularities[]"] = "segment"
+ if model:
+ fields["model"] = model
+ if language and not translate:
+ fields["language"] = language
+ path = "/v1/audio/translations" if translate else "/v1/audio/transcriptions"
+ return await forward(
+ caller, "POST", path, files = {"file": (name, data, "application/octet-stream")}, data = fields
+ )
+
+
+async def _stt_model(caller: Caller, model: Optional[str]) -> tuple[str, str]:
+ """The model and engine to transcribe with: the one asked for, else the loaded one, else Unsloth Studio's default."""
+ status = await loading.stt_status(caller, model)
+ if model is None:
+ for engine in loading.STT_ENGINES:
+ state = status.get(engine)
+ if isinstance(state, dict) and opt_text(state.get("loaded_model")):
+ return state["loaded_model"], engine
+ model = _default_stt(status)
+ if model is None:
+ raise ToolError("Unsloth Studio did not name a speech-to-text model; pass model.")
+ return model, loading.stt_engine(status, model)
+
+
+async def _transcribe_source(
+ caller: Caller,
+ ctx: Optional[Context],
+ source: dict[str, str],
+ *,
+ language: Optional[str],
+ timestamps: bool,
+ model: Optional[str],
+) -> TranscriptResult:
+ """Audio Unsloth Studio already holds, transcribed by id; this route saves the transcript to history and streams NDJSON."""
+ model, engine = await _stt_model(caller, model)
+ body: dict[str, Any] = {
+ "source": source,
+ "model": model,
+ "engine": engine,
+ "timestamps": timestamps,
+ }
+ if language:
+ body["language"] = language
+
+ async def send():
+ response = await forward(
+ caller, "POST", "/api/inference/audio/transcribe/source", json_body = body
+ )
+ if response.status_code >= 400:
+ return response, None
+ try:
+ return response, ndjson_last(response.content)
+ except ValueError:
+ raise ToolError("Unsloth Studio returned no transcript") from None
+
+ response, payload = await send()
+ # A missing model is refused as a 409 before the stream starts, or as an error line within it.
+ if payload is None:
+ missing = response.status_code == 409 and NOT_DOWNLOADED in response.text
+ else:
+ # Only an error line: a transcript can say anything.
+ missing = (
+ isinstance(payload, dict)
+ and payload.get("type") == "error"
+ and NOT_DOWNLOADED in str(payload.get("message", ""))
+ )
+ if missing:
+ await _download_then_retry(caller, ctx, model)
+ response, payload = await send()
+ if payload is None:
+ raise_for_route(response)
+ raise_for_route(response, payload = payload)
+ if not isinstance(payload, dict) or payload.get("type") != "complete":
+ raise ToolError("The transcription did not finish")
+ return TranscriptResult(
+ text = payload.get("text") if isinstance(payload.get("text"), str) else "",
+ language = opt_text(payload.get("language")),
+ model = model,
+ segments = _segments(payload) if timestamps else None,
+ saved_to_history = True,
+ )
+
+
+async def transcribe(
+ audio: AudioInput,
+ language: Optional[str] = None,
+ translate: bool = False,
+ timestamps: bool = False,
+ model: Optional[str] = None,
+ ctx: Optional[Context] = None,
+) -> TranscriptResult:
+ """Transcribe speech with Unsloth Studio's speech-to-text, or translate it to English with ``translate``. ``audio`` is inline base64 with a filename, a path on the Unsloth Studio computer, or an Unsloth Studio id. Audio over 25 MB or given by id is stored with Unsloth Studio first and its transcript is saved to Audio history (``saved_to_history``); translation needs a smaller file. ``timestamps`` adds segments and needs a model that times them, such as Qwen3-ASR (audio.cpp) or Parakeet-TDT; others refuse it, and translation has none. A missing model is downloaded first. Without ``model`` the loaded speech-to-text model or Unsloth Studio's default is used."""
+ if translate and timestamps:
+ raise ToolError(
+ "Translation returns text only; leave out timestamps, or transcribe without translate."
+ )
+ caller = current_caller()
+ data, name = audio_bytes(caller, audio) if audio.is_upload else (None, None)
+ if data is None or len(data) > MULTIPART_LIMIT:
+ if translate:
+ raise ToolError("Translation needs a file under 25 MB sent as data or a path.")
+ source = (
+ {"input_id": await upload_audio(caller, data, name)}
+ if data is not None
+ else await audio_ref(caller, audio)
+ )
+ return await _transcribe_source(
+ caller, ctx, source, language = language, timestamps = timestamps, model = model
+ )
+ # Without a model the multipart route runs its Transformers default, not the loaded one.
+ model, engine = await _resident_stt(caller, model)
+ # A whisper.cpp id is shared with Transformers, so only the stored-audio route keeps that engine.
+ if engine == "gguf" and not translate:
+ source = {"input_id": await upload_audio(caller, data, name)}
+ return await _transcribe_source(
+ caller, ctx, source, language = language, timestamps = timestamps, model = model
+ )
+
+ async def send():
+ return await _multipart(
+ caller,
+ data,
+ name,
+ language = language,
+ translate = translate,
+ timestamps = timestamps,
+ model = model,
+ )
+
+ response = await send()
+ if response.status_code == 409 and NOT_DOWNLOADED in response.text:
+ await _download_then_retry(caller, ctx, model)
+ response = await send()
+ # Off audio.cpp the route refuses timestamps up front: 501 without language, 400 with it.
+ untimed = timestamps and engine != "audiocpp"
+ hints = {400: TIMESTAMPS_HINT, 501: TIMESTAMPS_HINT} if untimed else None
+ payload = raise_for_route(response, hints = hints)
+ if not isinstance(payload, dict):
+ raise ToolError("Unsloth Studio returned no transcript")
+ return TranscriptResult(
+ text = payload.get("text") if isinstance(payload.get("text"), str) else "",
+ # This route answers with the text alone, so report what was asked for and what ran.
+ # A translation is always English; its verbose form spells it "english".
+ language = "en" if translate else (opt_text(payload.get("language")) or language),
+ model = model or (await _resident_stt(caller))[0],
+ segments = _segments(payload) if timestamps else None,
+ saved_to_history = False,
+ )
+
+
+async def _resident_stt(
+ caller: Caller, model: Optional[str] = None
+) -> tuple[Optional[str], Optional[str]]:
+ """The model and the engine serving it: the named one where it is held, else the loaded one."""
+ payload = await try_json(caller, loading.STT_STATUS, params = {"model": model} if model else None)
+ status = payload if isinstance(payload, dict) else {}
+ if model:
+ return model, loading.stt_engine(status, model)
+ for engine in loading.STT_ENGINES:
+ state = status.get(engine)
+ if isinstance(state, dict) and opt_text(state.get("loaded_model")):
+ return state["loaded_model"], engine
+ return None, None
+
+
+TOOLS = ((generate_audio, WRITES, AudioResult.model_json_schema()), (transcribe, WRITES))
diff --git a/studio/backend/studio_mcp/tools/cancel.py b/studio/backend/studio_mcp/tools/cancel.py
new file mode 100644
index 00000000000..a5ce332cae9
--- /dev/null
+++ b/studio/backend/studio_mcp/tools/cancel.py
@@ -0,0 +1,152 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""``cancel``: stop Unsloth Studio work by kind."""
+
+from __future__ import annotations
+
+from typing import Any, Literal, Optional
+from urllib.parse import quote
+
+from fastmcp.exceptions import ToolError
+
+from studio_mcp import export_jobs
+from studio_mcp.caller import current_caller
+from studio_mcp.outputs import CancelResult
+from studio_mcp.tools import DESTRUCTIVE, EXPORT_STATUS, as_dict, opt_text, route_json
+
+CancelKind = Literal[
+ "training",
+ "training_start",
+ "diffusion_training",
+ "export",
+ "recipe",
+ "image",
+ "video",
+ "chat",
+ "dataset_download",
+]
+START_CANCELLED = "training_start_cancelled"
+NEEDS_ID = {
+ "training_start": "the start request id",
+ "recipe": "the recipe job id",
+ "chat": "the chat's cancel_id",
+ "dataset_download": "the dataset's repo_id",
+}
+# The route each other kind posts to, and the body field that carries its id (or ``save``), if any.
+ROUTES = {
+ "training_start": ("/api/train/start-requests/{id}/cancel", None),
+ "diffusion_training": ("/api/train/diffusion/stop", "save"),
+ "recipe": ("/api/data-recipe/jobs/{id}/cancel", None),
+ "image": ("/api/inference/images/generate/cancel", None),
+ "video": ("/api/inference/video/generate/cancel", None),
+ "chat": ("/api/inference/cancel", "cancel_id"),
+ "dataset_download": ("/api/hub/datasets/download/cancel", "repo_id"),
+}
+
+
+def _message(answer: Any) -> Optional[str]:
+ if isinstance(answer, dict):
+ return opt_text(answer.get("message")) or opt_text(answer.get("status"))
+ return None
+
+
+def _stopped(kind: str, answer: Any) -> bool:
+ """Whether the route says it stopped something. Each route answers an idle cancel normally, so success alone means nothing."""
+ if not isinstance(answer, dict):
+ return False
+ if kind in ("image", "video", "chat"):
+ return bool(answer.get("cancelled"))
+ if kind == "training":
+ return answer.get("status") == "stopped"
+ if kind == "training_start":
+ # Rejected for another reason (a bad model, say) is not a cancel.
+ return answer.get("state") == "rejected" and answer.get("error_code") == START_CANCELLED
+ if kind == "diffusion_training":
+ return answer.get("status") == "stopping"
+ if kind == "export":
+ return answer.get("message") == "Export cancelled"
+ # "cancelled" here is a job that had already ended; only "cancelling" means this call stopped it.
+ if kind == "recipe":
+ return answer.get("status") == "cancelling"
+ return answer.get("state") == "cancelling"
+
+
+# How long a cancel waits for a job whose export just finished to record its own result.
+SETTLE_S = 2.0
+
+
+async def _cancel_export_job(caller: Any, job: export_jobs.ExportJob) -> tuple[bool, str]:
+ """Stop only this job's own step: the route stops the worker when that op runs and otherwise refuses it when it starts."""
+ for _ in range(3):
+ op_id = job.op_id
+ if op_id is None:
+ break
+ answer = await route_json(
+ "POST", "/api/export/cancel", caller = caller, json_body = {"expected_op_id": op_id}
+ )
+ if _stopped("export", answer):
+ export_jobs.mark_cancelled(job)
+ return True, "The export was stopped and its checkpoint unloaded."
+ # Its step just ended, or is queued behind someone else's: let a finished job report itself.
+ await export_jobs.settle(job, SETTLE_S)
+ if job.finished:
+ return False, f"The export already {job.status}."
+ if job.op_id == op_id:
+ break
+ export_jobs.mark_cancelled(job)
+ return True, "The export job was stopped before its next step."
+
+
+async def cancel(
+ kind: CancelKind,
+ id: Optional[str] = None,
+ save: bool = True,
+) -> CancelResult:
+ """Stop Unsloth Studio work. "training" stops the LLM training run ``id`` (or the current one) at its next safe point, saving a checkpoint unless ``save`` is false. "training_start" withdraws a start request that has not begun. "diffusion_training" stops image LoRA training, saving the partial adapter unless ``save`` is false. "export" stops the running export and unloads its checkpoint; with ``id`` (an export_model job) only that job's own step, never someone else's export. "recipe" stops recipe job ``id``. "image" and "video" stop the generation in progress. "chat" stops the reply with cancel_id ``id``. "dataset_download" stops downloading the dataset ``id`` (its repo id). Audio runs cannot be cancelled. ``cancelled`` says whether this call stopped something."""
+ caller = current_caller()
+
+ def done(cancelled: bool, message: Optional[str]) -> CancelResult:
+ return CancelResult(kind = kind, id = id, cancelled = cancelled, message = message)
+
+ if kind in NEEDS_ID and not id:
+ raise ToolError(f"cancel(kind={kind!r}) needs id: {NEEDS_ID[kind]}.")
+ if kind == "training":
+ if not id:
+ status = await route_json("GET", "/api/train/status", caller = caller)
+ id = opt_text(status.get("job_id")) if isinstance(status, dict) else None
+ if not id or not (isinstance(status, dict) and status.get("is_training_running")):
+ return CancelResult(
+ kind = kind, cancelled = False, message = "No training job is running."
+ )
+ answer = await route_json(
+ "POST",
+ "/api/train/stop",
+ caller = caller,
+ json_body = {"save": save, "expected_job_id": id},
+ )
+ elif kind == "export":
+ if id:
+ job = export_jobs.lookup(caller.account_id, id)
+ if job.finished:
+ return done(False, f"The export already {job.status}.")
+ return done(*await _cancel_export_job(caller, job))
+ status = await route_json("GET", EXPORT_STATUS, caller = caller)
+ if not as_dict(status).get("is_export_active"):
+ return done(False, "No export is running.")
+ answer = await route_json("POST", "/api/export/cancel", caller = caller)
+ if not _stopped(kind, answer):
+ return done(False, _message(answer))
+ return done(True, "The export was stopped and its checkpoint unloaded.")
+ else:
+ path, id_field = ROUTES[kind]
+ answer = await route_json(
+ "POST",
+ path.format(id = quote(id or "", safe = "")),
+ caller = caller,
+ **({"json_body": {id_field: save if id_field == "save" else id}} if id_field else {}),
+ )
+ return done(_stopped(kind, answer), _message(answer))
+
+
+TOOLS = ((cancel, DESTRUCTIVE),)
diff --git a/studio/backend/studio_mcp/tools/data.py b/studio/backend/studio_mcp/tools/data.py
new file mode 100644
index 00000000000..fc93276290f
--- /dev/null
+++ b/studio/backend/studio_mcp/tools/data.py
@@ -0,0 +1,103 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""``datasets``: the training datasets Unsloth Studio has, and getting more."""
+
+from __future__ import annotations
+
+import dataclasses
+from typing import Literal, Optional
+
+from fastmcp.exceptions import ToolError
+
+from studio_mcp.caller import current_caller
+from studio_mcp.outputs import (
+ CachedDataset,
+ DatasetDownload,
+ DatasetFormat,
+ DatasetsResult,
+ LocalDataset,
+)
+from studio_mcp.tools import WRITES, as_dict, opt_text, route_json
+
+HUB_DATASETS = "/api/hub/datasets"
+
+
+async def datasets(
+ action: Literal["list", "check_format", "download", "status"],
+ 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,
+) -> 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."""
+ caller = current_caller()
+ if hf_token:
+ caller = dataclasses.replace(caller, hf_token = hf_token)
+ if action == "list":
+ local = await route_json("GET", f"{HUB_DATASETS}/local", caller = caller)
+ cached = await route_json("GET", f"{HUB_DATASETS}/cached", caller = caller)
+ return DatasetsResult(
+ local = [
+ LocalDataset.from_route(
+ row, label = opt_text(row.get("label")) or row["id"], source = "local"
+ )
+ for row in as_dict(local).get("datasets") or []
+ if isinstance(row, dict) and opt_text(row.get("id"))
+ ],
+ cached = [
+ CachedDataset.from_route(row)
+ for row in as_dict(cached).get("cached") or []
+ if isinstance(row, dict) and opt_text(row.get("repo_id"))
+ ],
+ )
+ if action == "check_format":
+ if not name:
+ raise ToolError(
+ "check_format needs name: a Hugging Face dataset id or a listed dataset."
+ )
+ body = {"dataset_name": name, "is_vlm": is_vlm, "train_split": train_split}
+ if subset:
+ body["subset"] = subset
+ found = await route_json(
+ "POST", f"{HUB_DATASETS}/check-format", caller = caller, json_body = body, hub_header = True
+ )
+ found = as_dict(found)
+ mapping = found.get("suggested_mapping")
+ return DatasetsResult(
+ format = DatasetFormat.from_route(
+ found,
+ suggested_mapping = {str(k): v for k, v in mapping.items() if isinstance(v, str)}
+ if isinstance(mapping, dict)
+ else None,
+ )
+ )
+ if not repo_id:
+ raise ToolError(f"{action} needs repo_id: a Hugging Face dataset id.")
+ if action == "download":
+ started = await route_json(
+ "POST",
+ f"{HUB_DATASETS}/download",
+ caller = caller,
+ json_body = {"repo_id": repo_id},
+ hub_header = True,
+ )
+ return DatasetsResult(
+ download = DatasetDownload(
+ repo_id = repo_id, state = opt_text(as_dict(started).get("state")) or "queued"
+ )
+ )
+ state = await route_json(
+ "GET", f"{HUB_DATASETS}/download-status", caller = caller, params = {"repo_id": repo_id}
+ )
+ state = as_dict(state)
+ return DatasetsResult(
+ download = DatasetDownload.from_route(
+ state, repo_id = repo_id, state = opt_text(state.get("state")) or "unknown"
+ )
+ )
+
+
+TOOLS = ((datasets, WRITES),)
diff --git a/studio/backend/studio_mcp/tools/export.py b/studio/backend/studio_mcp/tools/export.py
new file mode 100644
index 00000000000..7a66aedcd7a
--- /dev/null
+++ b/studio/backend/studio_mcp/tools/export.py
@@ -0,0 +1,118 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""``export_model``: a trained checkpoint, by name, to GGUF, merged weights, a LoRA adapter or the base model."""
+
+from __future__ import annotations
+
+import os
+import re
+from typing import Any, Literal, Optional, Union
+
+from fastmcp.exceptions import ToolError
+
+from studio_mcp import checkpoints, export_jobs
+from studio_mcp.caller import Caller, current_caller
+from studio_mcp.errors import tool_error
+from studio_mcp.outputs import ExportJobRef
+from studio_mcp.tools import EXPORT_STATUS, WRITES, present, route_json
+
+RUNNING = (
+ "Another export is running. Unsloth Studio exports one at a time, so try again when it ends."
+)
+
+
+def checked_save_directory(value: str) -> str:
+ """A folder under Unsloth Studio's exports folder; the route alone would also take any path on the host."""
+ text = value.strip()
+ if not text:
+ raise ToolError("save_directory must name a folder.")
+ if text.startswith(("/", "\\", "~")) or re.match(r"^[A-Za-z]:", text):
+ raise ToolError(
+ "save_directory must be relative to Unsloth Studio's exports folder, not an absolute path."
+ )
+ if ".." in re.split(r"[\\/]", text):
+ raise ToolError("save_directory must not contain '..'.")
+ return text
+
+
+async def _op(caller: Caller, path: str, body: dict[str, Any]) -> Any:
+ result = await route_json("POST", path, caller = caller, json_body = body)
+ if isinstance(result, dict) and result.get("success") is False:
+ raise tool_error(result.get("message") or "The export step failed")
+ return result
+
+
+def _same_checkpoint(status: Any, path: str) -> bool:
+ loaded = status.get("current_checkpoint") if isinstance(status, dict) else None
+ if not isinstance(loaded, str) or not loaded:
+ return False
+ return os.path.realpath(loaded) == os.path.realpath(path)
+
+
+async def export_model(
+ checkpoint: str,
+ format: Literal["gguf", "merged", "lora", "base"],
+ save_directory: str,
+ quantization_method: Union[str, list[str]] = "Q4_K_M",
+ push_to_hub: bool = False,
+ repo_id: Optional[str] = None,
+ hf_token: Optional[str] = None,
+ private: bool = False,
+ max_seq_length: int = 2048,
+ load_in_4bit: Optional[bool] = None,
+ imatrix: bool = False,
+) -> ExportJobRef:
+ """Export a trained checkpoint and return a job id at once; follow it with get_job(kind="export"). ``checkpoint`` is a name from list_training_runs(include_checkpoints=true): "<run folder>" or "<run folder>/checkpoint-N". ``format``: "gguf" (``quantization_method`` one or a list, e.g. Q4_K_M, Q8_0; ``imatrix`` true uses Unsloth's importance matrix, which the IQ quants such as IQ2_XXS need), "merged" (LoRA merged into 16-bit weights), "lora" (the adapter only) or "base". ``save_directory`` is a folder name under Unsloth Studio's exports folder. ``push_to_hub`` uploads to ``repo_id`` and needs ``hf_token``. Leave ``load_in_4bit`` unset to let Unsloth Studio choose. Unsloth Studio exports one at a time, so this is refused while another export runs."""
+ caller = current_caller()
+ save_directory = checked_save_directory(save_directory)
+ # One export worker, one job at a time.
+ running = await route_json("GET", EXPORT_STATUS, caller = caller)
+ if (isinstance(running, dict) and running.get("is_export_active")) or export_jobs.any_running():
+ raise ToolError(RUNNING)
+ found = await checkpoints.resolve(caller, checkpoint)
+ token = hf_token or caller.hf_token or None
+ load = {
+ "checkpoint_path": found.path,
+ "max_seq_length": max_seq_length,
+ **present(load_in_4bit = load_in_4bit, hf_token = token),
+ }
+ # In the body, as the export routes read it; an API key never falls back to the server's token.
+ body = {
+ "save_directory": save_directory,
+ "push_to_hub": push_to_hub,
+ "private": private,
+ **present(repo_id = repo_id or None, hf_token = token),
+ **({"quantization_method": quantization_method} if format == "gguf" else {}),
+ **({"imatrix": True} if format == "gguf" and imatrix else {}),
+ }
+
+ async def run(job: export_jobs.ExportJob) -> None:
+ job.phase, job.op_id = "loading", f"mcp-{job.job_id}-load"
+ await _op(caller, "/api/export/load-checkpoint", {**load, "op_id": job.op_id})
+ before = await route_json("GET", EXPORT_STATUS, caller = caller)
+ # Load and export are two calls; an Export page load between them would export under this job.
+ if not _same_checkpoint(before, found.path):
+ raise ToolError(
+ "Another checkpoint was loaded for export before this job's export began; nothing was exported."
+ )
+ job.phase, job.op_id = "exporting", f"mcp-{job.job_id}-export"
+ # The route checks this under the export lock, which closes the gap the status check leaves.
+ result = await _op(
+ caller,
+ f"/api/export/export/{format}",
+ {**body, "expected_checkpoint": found.path, "op_id": job.op_id},
+ )
+ # This call's own answer, not the export status: another export may have finished since.
+ details = result.get("details") if isinstance(result, dict) else None
+ if isinstance(details, dict):
+ job.output = export_jobs.output_name(details.get("output_path")) or job.output
+
+ # Checked again with no await before start, so two calls at once cannot both get past the guard.
+ if export_jobs.any_running():
+ raise ToolError(RUNNING)
+ job = export_jobs.start(caller.account_id, format, run)
+ return ExportJobRef(job_id = job.job_id)
+
+
+TOOLS = ((export_model, WRITES),)
diff --git a/studio/backend/studio_mcp/tools/images.py b/studio/backend/studio_mcp/tools/images.py
new file mode 100644
index 00000000000..c1279f65c63
--- /dev/null
+++ b/studio/backend/studio_mcp/tools/images.py
@@ -0,0 +1,162 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""``generate_image``: images saved to the Unsloth Studio gallery and returned inline when small."""
+
+from __future__ import annotations
+
+from typing import Annotated, Any, Literal, Optional
+
+from fastmcp import Context
+from fastmcp.exceptions import ToolError
+from fastmcp.tools import ToolResult
+from pydantic import Field
+
+from studio_mcp import loading
+from studio_mcp.caller import Caller, current_caller
+from studio_mcp.forward import forward
+from studio_mcp.inputs import ImageInput, data_url, resolve_image, sniff_image
+from studio_mcp.media import (
+ INLINE_CAP,
+ image_content,
+ image_gallery_path,
+ media_result,
+ public_url,
+ resource_link,
+)
+from studio_mcp.outputs import ImageItem, ImageResult
+from studio_mcp.tools import WRITES, integer, number, opt_text, present, route_json
+
+LOAD_IMAGE_HINT = "Load an image model with load_model(kind='image') first."
+NOT_LOADED = "No diffusion model is loaded"
+# The route takes 128 MiB of base64 across every image in one request.
+MAX_REQUEST_IMAGE_BYTES = 128 * 1024 * 1024 * 3 // 4
+
+
+def _progress_poll(caller: Caller):
+ async def poll():
+ progress = await route_json("GET", "/api/inference/images/generate-progress", caller = caller)
+ if not isinstance(progress, dict) or not progress.get("active"):
+ return None
+ fraction = number(progress.get("fraction")) or 0.0
+ step, total = integer(progress.get("step")), integer(progress.get("total_steps"))
+ return fraction, f"Step {step} of {total}" if step is not None and total else "Generating"
+
+ return poll
+
+
+async def _fetch(caller: Caller, path: str) -> Optional[bytes]:
+ response = await forward(caller, "GET", path)
+ return response.content if response.status_code == 200 else None
+
+
+async def _image_contents(caller: Caller, item: ImageItem) -> list[Any]:
+ """The PNG inline when it must fit the cap, else a WebP thumbnail plus a link; a large original is never fetched."""
+ if item.width and item.height and item.width * item.height * 3 <= INLINE_CAP:
+ data = await _fetch(caller, image_gallery_path(item.id))
+ if data is not None and len(data) <= INLINE_CAP:
+ return [image_content(data, "image/png")]
+ thumb = await _fetch(caller, image_gallery_path(item.id, thumb = True))
+ contents: list[Any] = []
+ if thumb is not None and len(thumb) <= INLINE_CAP:
+ # Studio sends the original PNG when it cannot make the thumbnail.
+ contents.append(image_content(thumb, sniff_image(thumb) or "image/webp"))
+ contents.append(resource_link(item.url, f"{item.id}.png", "image/png"))
+ return contents
+
+
+async def run_generation(
+ caller: Caller, ctx: Optional[Context], body: dict[str, Any]
+) -> ToolResult:
+ generate = route_json(
+ "POST",
+ "/api/inference/images/generate",
+ caller = caller,
+ json_body = body,
+ hint_if = (NOT_LOADED, {409: LOAD_IMAGE_HINT}),
+ )
+ payload = await loading.with_progress(ctx, generate, _progress_poll(caller))
+ rows = payload.get("images") if isinstance(payload, dict) else None
+ if not isinstance(rows, list) or not rows:
+ raise ToolError("Unsloth Studio returned no images")
+ items, contents = [], []
+ for row in rows:
+ if not isinstance(row, dict) or not opt_text(row.get("id")):
+ continue
+ item = ImageItem.from_route(row, url = public_url(caller, image_gallery_path(row["id"])))
+ items.append(item)
+ contents.extend(await _image_contents(caller, item))
+ return media_result(contents, ImageResult(images = items))
+
+
+async def _image_fields(
+ caller: Caller,
+ init_image: Optional[ImageInput],
+ mask_image: Optional[ImageInput],
+ reference_images: Optional[list[ImageInput]],
+) -> dict[str, Any]:
+ if mask_image is not None and init_image is None:
+ raise ToolError("mask_image needs init_image: the mask marks what to repaint in it.")
+ fields: dict[str, Any] = {}
+ total = 0
+ for key, image in (("init_image", init_image), ("mask_image", mask_image)):
+ if image is not None:
+ data, mime = await resolve_image(caller, image)
+ total += len(data)
+ fields[key] = data_url(data, mime)
+ references = []
+ for image in reference_images or []:
+ data, mime = await resolve_image(caller, image)
+ total += len(data)
+ references.append(data_url(data, mime))
+ if references:
+ fields["reference_images"] = references
+ if total > MAX_REQUEST_IMAGE_BYTES:
+ raise ToolError("The images together are larger than the 96 MiB one request takes")
+ return fields
+
+
+async def generate_image(
+ prompt: str,
+ negative_prompt: Optional[str] = None,
+ width: Optional[int] = None,
+ height: Optional[int] = None,
+ steps: Optional[int] = None,
+ guidance: Optional[float] = None,
+ seed: Optional[int] = None,
+ batch_size: Optional[int] = None,
+ init_image: Optional[ImageInput] = None,
+ mask_image: Optional[ImageInput] = None,
+ reference_images: Annotated[Optional[list[ImageInput]], Field(max_length = 9)] = None,
+ workflow: Optional[Literal["edit", "reference", "outpaint"]] = None,
+ strength: Optional[float] = None,
+ upscale: Optional[float] = None,
+ allow_oversized: bool = False,
+ ctx: Optional[Context] = None,
+) -> ToolResult:
+ """Generate or edit images with the image model loaded in Unsloth Studio (load_model(kind="image") first). Each image is saved to the Unsloth Studio Images gallery and returned with its id and URL; images up to 1.5 MiB come back inline, larger ones as a 1024 px preview plus a link. Width and height are pixels, multiples of 16; left out, the size is 1024x1024 with 9 steps and guidance 0, which suits turbo models (raise steps and guidance for others). With ``init_image`` it is img2img (``strength`` above 0 up to 1 sets how much is redrawn; left out, the model's default); add ``mask_image`` to inpaint (white is repainted); ``upscale`` 1 to 4 enlarges ``init_image`` and lightly redraws it, still guided by the prompt; ``workflow`` "edit" follows the prompt as an instruction over init_image and ``reference_images``, "reference" draws a new image guided by them, "outpaint" fills a padded init_image under its mask. A refusal on memory grounds can be overridden with ``allow_oversized``. Progress is reported while it runs."""
+ if upscale is not None and init_image is None:
+ raise ToolError("upscale needs init_image: it enlarges that image.")
+ caller = current_caller()
+ body: dict[str, Any] = {"prompt": prompt}
+ body.update(await _image_fields(caller, init_image, mask_image, reference_images))
+ body.update(
+ present(
+ negative_prompt = negative_prompt,
+ width = width,
+ height = height,
+ steps = steps,
+ guidance = guidance,
+ seed = seed,
+ batch_size = batch_size,
+ workflow = workflow,
+ strength = strength,
+ upscale = upscale,
+ )
+ )
+ if allow_oversized:
+ body["allow_oversized"] = True
+ return await run_generation(caller, ctx, body)
+
+
+TOOLS = ((generate_image, WRITES, ImageResult.model_json_schema()),)
diff --git a/studio/backend/studio_mcp/tools/jobs.py b/studio/backend/studio_mcp/tools/jobs.py
new file mode 100644
index 00000000000..3c45e6f615d
--- /dev/null
+++ b/studio/backend/studio_mcp/tools/jobs.py
@@ -0,0 +1,199 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Long-running Unsloth Studio jobs: ``run_recipe`` starts a data recipe and ``get_job`` reports on any job."""
+
+from __future__ import annotations
+
+from typing import Annotated, Any, Literal, Optional
+from urllib.parse import quote
+
+from fastmcp.exceptions import ToolError
+from fastmcp.tools import ToolResult
+from pydantic import Field
+
+from studio_mcp.caller import Caller, current_caller
+from studio_mcp.errors import raise_for_route
+from studio_mcp.forward import forward
+from studio_mcp.media import INLINE_CAP, image_content, media_result, public_url, resource_link
+from studio_mcp import export_jobs
+from studio_mcp.outputs import (
+ ExportInfo,
+ JobStatus,
+ JobSummary,
+ RecipeError,
+ RecipeInfo,
+ RecipeResult,
+ VideoInfo,
+)
+from studio_mcp.tools import READ_ONLY, WRITES, as_dict, integer, leaf_name, number, opt_text
+from studio_mcp.tools import route_json
+
+
+def _video_path(video_id: str, suffix: str = "") -> str:
+ return f"/v1/videos/{quote(video_id, safe = '')}{suffix}"
+
+
+async def _video_job(caller: Caller, video_id: str) -> ToolResult:
+ job = as_dict(await route_json("GET", _video_path(video_id), caller = caller))
+ error = as_dict(job.get("error"))
+ contents: list[Any] = []
+ video = None
+ if job.get("status") == "completed":
+ # The thumbnail only: the MP4 can be hundreds of MB and is shared as a link.
+ video_url = public_url(caller, _video_path(video_id, "/content"))
+ thumb = await forward(
+ caller, "GET", _video_path(video_id, "/content"), params = {"variant": "thumbnail"}
+ )
+ inline = thumb.status_code == 200 and len(thumb.content) <= INLINE_CAP
+ if inline:
+ contents.append(image_content(thumb.content, "image/webp"))
+ contents.append(resource_link(video_url, f"{video_id}.mp4", "video/mp4"))
+ video = VideoInfo(url = video_url, thumbnail_inline = inline)
+ status = JobStatus(
+ kind = "video",
+ id = opt_text(job.get("id")) or video_id,
+ status = opt_text(job.get("status")),
+ progress_percent = number(job.get("progress")),
+ error = opt_text(error.get("message")),
+ video = video,
+ )
+ return media_result(contents, status)
+
+
+async def _video_jobs(caller: Caller) -> ToolResult:
+ listing = await route_json("GET", "/v1/videos", caller = caller)
+ rows = as_dict(listing).get("data")
+ jobs = [
+ JobSummary.from_route(
+ row,
+ status = opt_text(row.get("status")) or "queued",
+ progress_percent = number(row.get("progress")),
+ )
+ for row in rows or []
+ if isinstance(row, dict) and opt_text(row.get("id"))
+ ]
+ return media_result([], JobStatus(kind = "video", jobs = jobs))
+
+
+RECIPE_ROUTES = "/api/data-recipe"
+
+
+def _recipe_dataset(artifact_path: Any) -> Optional[str]:
+ leaf = leaf_name(artifact_path) if opt_text(artifact_path) else None
+ return f"recipes/{leaf}" if leaf else None
+
+
+async def _recipe_job(
+ caller: Caller, job_id: Optional[str], rows: Optional[int], offset: int
+) -> ToolResult:
+ path = (
+ f"{RECIPE_ROUTES}/jobs/{quote(job_id, safe = '')}/status"
+ if job_id
+ else f"{RECIPE_ROUTES}/jobs/current"
+ )
+ if job_id:
+ job = await route_json("GET", path, caller = caller)
+ else:
+ response = await forward(caller, "GET", path)
+ # No recipe has run since Unsloth Studio started: nothing to report, not an error.
+ if response.status_code == 404:
+ return media_result([], JobStatus(kind = "recipe", jobs = []))
+ job = raise_for_route(response)
+ job = as_dict(job)
+ job_id = opt_text(job.get("job_id")) or job_id
+ progress = as_dict(job.get("progress"))
+ data_rows = total = None
+ if rows and job_id:
+ response = await forward(
+ caller,
+ "GET",
+ f"{RECIPE_ROUTES}/jobs/{quote(job_id, safe = '')}/dataset",
+ params = {"limit": rows, "offset": offset},
+ )
+ # 404 while no rows are written yet, 422 when the job ended without any (its detail names host
+ # paths): the status still answers, without rows.
+ page = None if response.status_code in (404, 422) else raise_for_route(response)
+ if isinstance(page, dict):
+ data_rows = [row for row in page.get("dataset") or [] if isinstance(row, dict)]
+ total = integer(page.get("total"))
+ status = JobStatus.from_route(
+ job,
+ kind = "recipe",
+ id = job_id,
+ progress_percent = number(progress.get("percent")),
+ recipe = RecipeInfo.from_route(
+ job,
+ dataset = _recipe_dataset(job.get("artifact_path")),
+ total_rows = total,
+ data_rows = data_rows,
+ ),
+ )
+ return media_result([], status)
+
+
+def _export_status(job: export_jobs.ExportJob) -> JobStatus:
+ return JobStatus(
+ kind = "export",
+ id = job.job_id,
+ status = job.status,
+ error = job.error,
+ export = ExportInfo(format = job.format, output = job.output, phase = job.phase),
+ )
+
+
+async def _export_job(caller: Caller, job_id: Optional[str]) -> ToolResult:
+ if job_id is None:
+ jobs = [
+ JobSummary(id = job.job_id, status = job.status)
+ for job in export_jobs.jobs_of(caller.account_id)
+ ]
+ return media_result([], JobStatus(kind = "export", jobs = jobs))
+ # Settles from its own export call, not the export status (that is whichever op ran last).
+ return media_result([], _export_status(export_jobs.lookup(caller.account_id, job_id)))
+
+
+async def get_job(
+ kind: Literal["video", "recipe", "export"],
+ id: Optional[str] = None,
+ rows: Annotated[Optional[int], Field(ge = 1, le = 500)] = None,
+ offset: Annotated[int, Field(ge = 0)] = 0,
+) -> ToolResult:
+ """The state of a long-running job. kind "video": with ``id``, its status and progress, and once completed a thumbnail plus the video's URL; without ``id``, recent video jobs. kind "recipe": a data recipe job's status and progress (without ``id``, the current one), and with ``rows`` that many generated rows from ``offset``. 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."""
+ caller = current_caller()
+ if kind == "recipe":
+ return await _recipe_job(caller, id, rows, offset)
+ if kind == "export":
+ return await _export_job(caller, id)
+ if id is None:
+ return await _video_jobs(caller)
+ return await _video_job(caller, id)
+
+
+async def run_recipe(
+ recipe: dict[str, Any], mode: Literal["validate", "preview", "full"] = "validate"
+) -> RecipeResult:
+ """Validate a Data Recipe, or run it. "validate" checks it and returns any errors; "preview" generates a few rows; "full" generates the whole dataset and saves it. A run returns a job id at once: follow it with get_job(kind="recipe"). Recipes that define a local (stdio) MCP server can only be run from the Unsloth Studio UI."""
+ if mode == "validate":
+ payload = await route_json(
+ "POST", f"{RECIPE_ROUTES}/validate", json_body = {"recipe": recipe}
+ )
+ payload = as_dict(payload)
+ errors = [
+ RecipeError.from_route(e, message = opt_text(e.get("message")) or "invalid")
+ for e in payload.get("errors") or []
+ if isinstance(e, dict)
+ ]
+ return RecipeResult(mode = mode, valid = payload.get("valid") is True, errors = errors)
+ created = await route_json(
+ "POST",
+ f"{RECIPE_ROUTES}/jobs",
+ json_body = {"recipe": recipe, "run": {"execution_type": mode}},
+ )
+ job_id = opt_text(created.get("job_id")) if isinstance(created, dict) else None
+ if job_id is None:
+ raise ToolError("Unsloth Studio did not start the recipe")
+ return RecipeResult(mode = mode, job_id = job_id)
+
+
+TOOLS = ((run_recipe, WRITES), (get_job, READ_ONLY, JobStatus.model_json_schema()))
diff --git a/studio/backend/studio_mcp/tools/models.py b/studio/backend/studio_mcp/tools/models.py
new file mode 100644
index 00000000000..b81aae36517
--- /dev/null
+++ b/studio/backend/studio_mcp/tools/models.py
@@ -0,0 +1,150 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Model discovery and residency for agents: ``list_models``, ``load_model``, ``unload_model``."""
+
+from __future__ import annotations
+
+from typing import Any, Literal, Optional
+from urllib.parse import quote
+
+from fastmcp import Context
+
+from studio_mcp import loading
+from studio_mcp.caller import current_caller
+from studio_mcp.outputs import LoadResult, ModelEntry, ModelList, UnloadResult
+from studio_mcp.tools import DESTRUCTIVE, READ_ONLY, WRITES, as_dict, opt_text, route_json
+
+# "tts" and "audio" are what list_models reports for audio models; they load in the llm slot.
+ModelKind = Literal["llm", "image", "video", "stt", "tts", "audio"]
+
+KIND_BY_TASK = {
+ "text-to-image": "image",
+ "text-to-video": "video",
+ "automatic-speech-recognition": "stt",
+ "text-to-speech": "tts",
+ "audio-to-audio": "audio",
+}
+
+# Scalars a training config may start from; nothing that names a file or a folder.
+TRAINING_DEFAULT_KEYS = {
+ "training": (
+ "max_seq_length",
+ "num_epochs",
+ "learning_rate",
+ "batch_size",
+ "gradient_accumulation_steps",
+ "warmup_ratio",
+ "max_steps",
+ "save_steps",
+ "weight_decay",
+ "random_seed",
+ "packing",
+ "train_on_completions",
+ "gradient_checkpointing",
+ "optim",
+ "lr_scheduler_type",
+ ),
+ "lora": ("lora_r", "lora_alpha", "lora_dropout", "use_rslora", "use_loftq", "use_dora"),
+}
+
+
+def kind_of(entry: dict) -> str:
+ task = entry.get("task")
+ if task is None:
+ return "llm"
+ return KIND_BY_TASK.get(task, str(task))
+
+
+def _entry(entry: dict) -> Optional[ModelEntry]:
+ if not opt_text(entry.get("id")):
+ return None
+ return ModelEntry.from_route(entry, kind = kind_of(entry))
+
+
+def _training_defaults(details: Any) -> Optional[dict[str, Any]]:
+ config = as_dict(details).get("config")
+ if not isinstance(config, dict):
+ return None
+ defaults = {}
+ for section, keys in TRAINING_DEFAULT_KEYS.items():
+ values = as_dict(config.get(section))
+ for key in keys:
+ if isinstance(values.get(key), (bool, int, float, str)):
+ defaults[key] = values[key]
+ return defaults
+
+
+def _same_model_id(listed: str, asked: str) -> bool:
+ # Hub ids are case-insensitive, and a GGUF may be asked for with its ":variant".
+ return listed.lower() == asked.split(":", 1)[0].lower() or listed.lower() == asked.lower()
+
+
+async def list_models(
+ kind: Optional[ModelKind] = None,
+ loaded_only: bool = False,
+ model: Optional[str] = None,
+) -> ModelList:
+ """Models this Unsloth Studio can serve: loaded ones and those already downloaded. Each entry has the id to pass to load_model, its kind and whether it is loaded. ``kind`` is read from the model's task; a model with no task is reported as "llm", which also covers embedding models and unloaded text-to-speech models Unsloth Studio cannot classify yet, so pass the kind explicitly to load_model. ``loaded_only`` returns just the resident models. ``model`` narrows the list to that model (empty when it is not downloaded yet) and adds Unsloth Studio's training defaults for it, which also works for a Hugging Face repo id that is not downloaded (send X-Unsloth-HF-Token for a gated repo)."""
+ if loaded_only and kind == "llm":
+ # Resident chat models without a scan of every model folder; it never lists image, video or STT.
+ listing = await route_json("GET", "/api/inference/loaded-models")
+ else:
+ listing = await route_json("GET", "/v1/models")
+ rows = as_dict(listing).get("data")
+ models = []
+ for row in rows if isinstance(rows, list) else []:
+ entry = _entry(row) if isinstance(row, dict) else None
+ if entry is None or (kind and entry.kind != kind) or (loaded_only and not entry.loaded):
+ continue
+ if model and not _same_model_id(entry.id, model):
+ continue
+ models.append(entry)
+ defaults = None
+ if model:
+ details = await route_json(
+ "GET", "/api/models/config/" + quote(model, safe = "/:"), hub_header = True
+ )
+ defaults = _training_defaults(details)
+ return ModelList(models = models, training_defaults = defaults)
+
+
+async def load_model(
+ model: str,
+ kind: ModelKind = "llm",
+ variant: Optional[str] = None,
+ max_seq_length: Optional[int] = None,
+ load_in_4bit: bool = True,
+ hf_token: Optional[str] = None,
+ ctx: Optional[Context] = None,
+) -> LoadResult:
+ """Load a model into Unsloth Studio, downloading it first if needed, and wait until it is ready; progress is reported while it loads. ``kind`` "llm" covers chat, vision, embedding and audio models, and the "tts" and "audio" kinds list_models reports load the same way; "image" and "video" load the generation models and "stt" a speech-to-text model (downloaded first when needed). ``model`` is an id from list_models or a Hugging Face repo id; ``variant`` picks a GGUF quantization such as Q4_K_M. ``max_seq_length`` 0 or unset lets Unsloth Studio choose the context, and ``load_in_4bit`` picks 4-bit weights (both llm only). ``hf_token`` is for gated repos. Loading may unload other models to make room, for example a chat model to fit an image model; they are listed in ``evicted``."""
+ caller = current_caller()
+ if kind == "stt":
+ return await loading.load_stt(caller, ctx, model = model, variant = variant, hf_token = hf_token)
+ if kind in loading.MEDIA_ROUTES:
+ return await loading.load_media(
+ caller, ctx, kind = kind, model = model, variant = variant, hf_token = hf_token
+ )
+ return await loading.load_llm(
+ caller,
+ ctx,
+ model = model,
+ variant = variant,
+ max_seq_length = max_seq_length,
+ load_in_4bit = load_in_4bit,
+ hf_token = hf_token,
+ kind = kind,
+ )
+
+
+async def unload_model(kind: ModelKind = "llm", model: Optional[str] = None) -> UnloadResult:
+ """Unload a model to free memory. Without ``model`` the active one of that kind is unloaded; image and video have one slot each, so ``model`` is ignored there. The embedding model is managed by Unsloth Studio and is not unloaded here. ``unloaded`` is false when nothing matching was loaded."""
+ if kind == "stt":
+ return await loading.unload_stt(current_caller(), model)
+ if kind in loading.MEDIA_ROUTES:
+ return await loading.unload_media(current_caller(), kind)
+ return await loading.unload_llm(current_caller(), model)
+
+
+TOOLS = ((list_models, READ_ONLY), (load_model, WRITES), (unload_model, DESTRUCTIVE))
diff --git a/studio/backend/studio_mcp/tools/status.py b/studio/backend/studio_mcp/tools/status.py
new file mode 100644
index 00000000000..0c05b512e13
--- /dev/null
+++ b/studio/backend/studio_mcp/tools/status.py
@@ -0,0 +1,204 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""``studio_status``: every model slot, training, export and the GPUs in one call."""
+
+from __future__ import annotations
+
+import asyncio
+from functools import partial
+from typing import Any, Callable
+
+from fastmcp.exceptions import ToolError
+
+from studio_mcp.caller import Caller, current_caller
+from studio_mcp.errors import raise_for_route
+from studio_mcp.forward import forward
+from studio_mcp.outputs import (
+ ChatModel,
+ ChatSlot,
+ EmbedderSlot,
+ ExportSlot,
+ GpuDevice,
+ HardwareSlot,
+ ImageSlot,
+ StudioStatus,
+ SttDownload,
+ SttSlot,
+ TrainingSlot,
+ VideoSlot,
+ audio_options,
+)
+from studio_mcp.tools import READ_ONLY, as_dict, integer, leaf_name, number, opt_text, try_json
+
+SLOT_ROUTES = {
+ "chat": "/api/inference/status",
+ "image": "/api/inference/images/status",
+ "video": "/api/inference/video/status",
+ "stt": "/api/inference/audio/stt/status",
+ "embedder": "/api/settings/embedding-model",
+ "training": "/api/train/status",
+ "diffusion_training": "/api/train/diffusion/status",
+ "export": "/api/export/status",
+ # The route reads the GPUs off the event loop; never call get_gpu_utilization from a tool.
+ "hardware": "/api/train/hardware",
+}
+STT_ENGINES = ("transformers", "mtmd", "gguf", "audiocpp")
+
+
+def _chat(payload: dict) -> ChatSlot:
+ active = payload.get("model_identifier")
+ options = audio_options(payload.get("audio_options"))
+ loaded = [
+ ChatModel(
+ id = model_id,
+ display_name = opt_text(payload.get("active_model")) if model_id == active else None,
+ is_gguf = bool(payload.get("is_gguf")) if model_id == active else None,
+ audio_options = options if model_id == active else None,
+ )
+ for model_id in payload.get("loaded") or []
+ if isinstance(model_id, str)
+ ]
+ loading = [model for model in payload.get("loading") or [] if isinstance(model, str)]
+ return ChatSlot(loaded = loaded, loading = loading)
+
+
+def _media(slot: type, payload: dict) -> Any:
+ if payload.get("loaded") is not True:
+ return slot()
+ model = opt_text(payload.get("display_repo_id")) or opt_text(payload.get("repo_id"))
+ family = {"family": opt_text(payload.get("family"))} if slot is ImageSlot else {}
+ return slot(loaded = True, model = model, **family)
+
+
+def _stt(payload: dict) -> SttSlot:
+ engine = model = None
+ loading = False
+ downloading = []
+ for name in STT_ENGINES:
+ state = payload.get(name)
+ if not isinstance(state, dict):
+ continue
+ if model is None and opt_text(state.get("loaded_model")):
+ engine, model = name, state["loaded_model"]
+ loading = loading or state.get("loading") is True
+ download = state.get("download")
+ if (
+ isinstance(download, dict)
+ and download.get("downloading")
+ and opt_text(download.get("model"))
+ ):
+ done, total = number(download.get("bytes_done")), number(download.get("bytes_total"))
+ fraction = min(1.0, done / total) if done is not None and total else None
+ downloading.append(SttDownload(model = download["model"], fraction = fraction))
+ return SttSlot(engine = engine, model = model, loading = loading, downloading = downloading)
+
+
+def _embedder(payload: dict) -> EmbedderSlot:
+ custom = payload.get("is_custom") is True
+ model = "custom" if custom else opt_text(payload.get("embedding_model"))
+ return EmbedderSlot.from_route(payload, available = True, model = model)
+
+
+def _training(payload: dict) -> TrainingSlot:
+ details = as_dict(payload.get("details"))
+ step, total = integer(details.get("step")), integer(details.get("total_steps"))
+ return TrainingSlot.from_route(
+ payload,
+ step = step,
+ total_steps = total,
+ loss = number(details.get("loss")),
+ progress_percent = round(100.0 * step / total, 1) if step is not None and total else None,
+ eta_seconds = number(details.get("eta_seconds")),
+ )
+
+
+def _diffusion_training(payload: dict) -> TrainingSlot:
+ step, total = integer(payload.get("step")), integer(payload.get("total_steps"))
+ return TrainingSlot.from_route(
+ payload,
+ phase = opt_text(payload.get("status")) or "idle",
+ is_training_running = payload.get("active") is True,
+ progress_percent = round(100.0 * step / total, 1) if step is not None and total else None,
+ )
+
+
+def _export(payload: dict) -> ExportSlot:
+ path = opt_text(payload.get("last_op_output_path"))
+ return ExportSlot.from_route(
+ payload,
+ active = payload.get("is_export_active") is True,
+ op_kind = opt_text(payload.get("active_op_kind")),
+ last_output = (path and leaf_name(path)) or None,
+ )
+
+
+def _hardware(payload: dict) -> HardwareSlot:
+ devices = [
+ GpuDevice.from_route(device)
+ for device in payload.get("devices") or []
+ if isinstance(device, dict)
+ ]
+ return HardwareSlot.from_route(payload, devices = devices)
+
+
+BUILDERS: dict[str, Callable[[dict], Any]] = {
+ "chat": _chat,
+ "image": partial(_media, ImageSlot),
+ "video": partial(_media, VideoSlot),
+ "stt": _stt,
+ "embedder": _embedder,
+ "training": _training,
+ "diffusion_training": _diffusion_training,
+ "export": _export,
+ "hardware": _hardware,
+}
+
+
+async def _read_slot(caller: Caller, slot: str) -> Any:
+ response = await forward(caller, "GET", SLOT_ROUTES[slot])
+ if slot == "embedder" and response.status_code == 403:
+ # The embedder setting is owner-only; a managed account's key simply cannot see it.
+ return EmbedderSlot(available = False)
+ payload = raise_for_route(response)
+ if not isinstance(payload, dict):
+ raise ToolError("unexpected response")
+ return BUILDERS[slot](payload)
+
+
+# Whether a generation is running; read best-effort, since a missing answer only means "not known".
+GENERATING_ROUTES = {
+ "image": "/api/inference/images/generate-progress",
+ "video": "/api/inference/video/generate-progress",
+}
+
+
+async def _generating(caller: Caller, slot: str) -> bool:
+ payload = await try_json(caller, GENERATING_ROUTES[slot])
+ return isinstance(payload, dict) and payload.get("active") is True
+
+
+async def studio_status() -> StudioStatus:
+ """What Unsloth Studio is doing right now: the loaded chat, image, video, speech-to-text and embedding models, any model still loading or downloading, whether an image or video is generating, the LLM and image (diffusion) training jobs, the export job and GPU use. A loaded audio model lists its ``audio_options`` for generate_audio, such as its built-in voices. Call this before loading a model or starting GPU work. The embedding model is managed by Unsloth Studio and unload_model does not unload it. A slot that could not be read is listed under ``unavailable`` with the reason."""
+ caller = current_caller()
+ slots = list(SLOT_ROUTES)
+ results, generating = await asyncio.gather(
+ asyncio.gather(*(_read_slot(caller, slot) for slot in slots), return_exceptions = True),
+ asyncio.gather(*(_generating(caller, slot) for slot in GENERATING_ROUTES)),
+ )
+ status: dict[str, Any] = {}
+ unavailable: dict[str, str] = {}
+ for slot, result in zip(slots, results):
+ if isinstance(result, ToolError):
+ unavailable[slot] = str(result)
+ elif isinstance(result, BaseException):
+ unavailable[slot] = "unexpected response"
+ else:
+ status[slot] = result
+ for slot, active in zip(GENERATING_ROUTES, generating):
+ if active and slot in status:
+ status[slot] = status[slot].model_copy(update = {"generating": True})
+ return StudioStatus(**status, unavailable = unavailable)
+
+
+TOOLS = ((studio_status, READ_ONLY),)
diff --git a/studio/backend/studio_mcp/tools/text.py b/studio/backend/studio_mcp/tools/text.py
new file mode 100644
index 00000000000..3f5c8c8de04
--- /dev/null
+++ b/studio/backend/studio_mcp/tools/text.py
@@ -0,0 +1,223 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Text tools: ``chat``, ``embed`` and ``system_one``."""
+
+from __future__ import annotations
+
+import json
+import uuid
+from typing import Annotated, Any, Literal, Optional, Union
+
+from fastmcp.exceptions import ToolError
+from pydantic import BaseModel, ConfigDict, Field
+
+from studio_mcp.caller import current_caller
+from studio_mcp.errors import raise_for_route
+from studio_mcp.forward import forward
+from studio_mcp.inputs import ImageInput, resolve_images
+from studio_mcp.outputs import ChatResult, DecisionAnswer, EmbedResult, SystemOneResult, Usage
+from studio_mcp.tools import READ_ONLY, WRITES, integer, number, opt_text, present, route_json
+
+MAX_EMBED_INPUTS = 2048
+LOAD_CHAT_HINT = "Load a chat model with load_model first; list_models shows the downloaded ones."
+NOT_LOADED = "No model loaded"
+# The chat route takes 128 MiB of base64 images per request.
+MAX_CHAT_IMAGE_BYTES = 128 * 1024 * 1024 * 3 // 4
+EMBED_DOWNLOAD_HINT = (
+ "Download the embedding model in Unsloth Studio first (Settings), or load an embedding GGUF with "
+ "load_model(kind='llm') and call embed again."
+)
+
+
+class ChatTurn(BaseModel):
+ model_config = ConfigDict(extra = "forbid")
+
+ role: Literal["system", "user", "assistant"]
+ content: str
+
+
+def _same_model(requested: str, answered: str) -> bool:
+ # A GGUF id may come back with its quant pinned (repo:Q4_K_M).
+ return answered.lower() == requested.lower() or answered.lower().startswith(
+ requested.lower() + ":"
+ )
+
+
+async def _attach_images(turns: list[dict], images: list[ImageInput]) -> None:
+ last_user = next((turn for turn in reversed(turns) if turn["role"] == "user"), None)
+ if last_user is None:
+ raise ToolError("images need a user turn to go with.")
+ urls = await resolve_images(
+ current_caller(),
+ images,
+ total_cap = MAX_CHAT_IMAGE_BYTES,
+ too_large = "The images together are larger than the 96 MiB a chat request takes",
+ )
+ parts = [{"type": "image_url", "image_url": {"url": url}} for url in urls]
+ last_user["content"] = [{"type": "text", "text": last_user["content"]}, *parts]
+
+
+async def chat(
+ messages: Optional[list[ChatTurn]] = None,
+ prompt: Optional[str] = None,
+ system: Optional[str] = None,
+ images: Optional[list[ImageInput]] = None,
+ max_tokens: Optional[int] = None,
+ temperature: Optional[float] = None,
+ model: Optional[str] = None,
+ cancel_id: Annotated[
+ Optional[str], Field(min_length = 8, max_length = 64, pattern = r"^[A-Za-z0-9_-]+$")
+ ] = None,
+) -> ChatResult:
+ """Chat with the model loaded in Unsloth Studio and return its reply. Send either ``prompt`` (one user turn) or ``messages`` (the whole conversation), plus an optional ``system`` prompt. ``images`` go with the last user turn and need a vision model. ``model`` names which loaded model should answer; without it the active one does. Load a model with load_model first. A thinking model spends tokens on reasoning before the reply, so leave ``max_tokens`` unset or give it a few hundred or more. Unsloth Studio's server-side tools are not used. To be able to stop a long reply from another call, pass your own ``cancel_id`` (8-64 letters, digits, - or _) and call cancel(kind="chat", id=cancel_id)."""
+ if (messages is None) == (prompt is None):
+ raise ToolError("Send either prompt or messages, not both and not neither.")
+ turns = (
+ [{"role": "user", "content": prompt}]
+ if prompt is not None
+ else [t.model_dump() for t in messages]
+ )
+ if not turns:
+ raise ToolError("messages is empty.")
+ if images:
+ await _attach_images(turns, images)
+ cancel_id = cancel_id or f"mcp-{uuid.uuid4().hex}"
+ if system:
+ turns.insert(0, {"role": "system", "content": system})
+ body = {
+ "model": model or "default",
+ "messages": turns,
+ "stream": False,
+ # Per-run id (the route scopes it to the caller's account), so only a cancel aimed at this chat stops it.
+ "cancel_id": cancel_id,
+ **present(max_tokens = max_tokens, temperature = temperature),
+ }
+ payload = await route_json(
+ "POST", "/v1/chat/completions", json_body = body, hint_if = (NOT_LOADED, {400: LOAD_CHAT_HINT})
+ )
+ choices = payload.get("choices") if isinstance(payload, dict) else None
+ if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
+ raise ToolError("Unsloth Studio returned no reply")
+ message = choices[0].get("message") if isinstance(choices[0].get("message"), dict) else {}
+ usage = payload.get("usage") if isinstance(payload.get("usage"), dict) else None
+ answered = opt_text(payload.get("model"))
+ text = message.get("content") if isinstance(message.get("content"), str) else ""
+ finish_reason = opt_text(choices[0].get("finish_reason"))
+ note = None
+ if model and answered and not _same_model(model, answered):
+ note = f"{answered} answered; {model} is not the model that served this request."
+ elif not text.strip() and finish_reason == "length":
+ # Thinking models can spend the whole budget before the visible reply starts.
+ note = "The reply ran out of tokens before any text, likely spent on the model's reasoning; raise max_tokens."
+ return ChatResult(
+ text = text,
+ model = answered,
+ finish_reason = finish_reason,
+ usage = Usage.from_route(usage) if usage else None,
+ note = note,
+ cancel_id = cancel_id,
+ )
+
+
+async def embed(
+ texts: Annotated[list[str], Field(min_length = 1, max_length = MAX_EMBED_INPUTS)],
+ model: Optional[str] = None,
+) -> EmbedResult:
+ """Embed up to 2048 texts and return one vector per text, in order. Uses the embedding GGUF loaded in Unsloth Studio when there is one, else Unsloth Studio's configured embedding model. ``model`` names a specific one; the result names the model that answered. Compare vectors with cosine similarity."""
+ body = {"input": texts}
+ if model:
+ body["model"] = model
+ payload = await route_json(
+ "POST", "/v1/embeddings", json_body = body, hints = {409: EMBED_DOWNLOAD_HINT}
+ )
+ rows = payload.get("data") if isinstance(payload, dict) else None
+ rows = sorted(
+ (
+ row
+ for row in rows or []
+ if isinstance(row, dict) and isinstance(row.get("embedding"), list)
+ ),
+ key = lambda row: integer(row.get("index")) or 0,
+ )
+ if len(rows) != len(texts):
+ raise ToolError(f"Unsloth Studio returned {len(rows)} embeddings for {len(texts)} texts")
+ embeddings = [[float(value) for value in row["embedding"]] for row in rows]
+ return EmbedResult(
+ model = opt_text(payload.get("model")), dimensions = len(embeddings[0]), embeddings = embeddings
+ )
+
+
+MAX_DECISION_QUESTIONS = 64
+# The Decision API's own image limits: PNG or JPEG, 4 MiB each, 8 MiB together.
+MAX_DECISION_IMAGES = 4
+MAX_DECISION_IMAGE_BYTES = 4 * 1024 * 1024
+MAX_DECISION_IMAGES_BYTES = 8 * 1024 * 1024
+DECISION_API_OFF_HINT = "Turn on the Decision API in Settings > API."
+
+
+class DecisionQuestion(BaseModel):
+ model_config = ConfigDict(extra = "forbid")
+
+ type: Literal["noul", "choice", "score"]
+ instructions: Optional[Union[str, dict[str, Any], list[Any]]] = None
+ criteria: Optional[Union[str, dict[str, Any], list[Any]]] = None
+
+
+def _floats(values: Any) -> Optional[dict[str, float]]:
+ if not isinstance(values, dict):
+ return None
+ return {str(k): float(v) for k, v in values.items() if number(v) is not None}
+
+
+def _answer(answer: dict) -> DecisionAnswer:
+ legend = answer.get("legend")
+ return DecisionAnswer.from_route(
+ answer,
+ type = str(answer.get("type")),
+ probabilities = _floats(answer.get("probabilities")),
+ legend = {
+ str(k): v if isinstance(v, str) else json.dumps(v, ensure_ascii = False)
+ for k, v in legend.items()
+ }
+ if isinstance(legend, dict)
+ else None,
+ )
+
+
+async def system_one(
+ state: Union[str, dict[str, Any], list[Any]],
+ questions: Annotated[
+ dict[str, DecisionQuestion], Field(min_length = 1, max_length = MAX_DECISION_QUESTIONS)
+ ],
+ images: Annotated[Optional[list[ImageInput]], Field(max_length = MAX_DECISION_IMAGES)] = None,
+ model: str = "default",
+) -> SystemOneResult:
+ """Ask Unsloth Studio's decision model (SystemOne) typed questions about a state, given as text or JSON. ``questions`` maps a name you pick to {"type", "instructions", "criteria"}, for example {"urgent": {"type": "noul", "instructions": "Does this need a reply within the hour?"}}. "noul" is yes or no and answers a probability; "choice" needs criteria mapping each option name to a description; "score" needs criteria listing 1 to 10 levels, lowest first. ``images`` (at most 4, PNG or JPEG) need a Clef model. ``model`` "default" uses the model picked in Settings. The Decision API must be on (Settings > API)."""
+ body: dict[str, Any] = {
+ "state": state,
+ "model": model,
+ "questions": {name: q.model_dump(exclude_none = True) for name, q in questions.items()},
+ }
+ if images:
+ body["images"] = await resolve_images(
+ current_caller(),
+ images,
+ total_cap = MAX_DECISION_IMAGES_BYTES,
+ too_large = "The images together are larger than 8 MiB",
+ max_bytes = MAX_DECISION_IMAGE_BYTES,
+ mimes = ("image/png", "image/jpeg"),
+ )
+ response = await forward(current_caller(), "POST", "/v1/systemone", json_body = body)
+ payload = raise_for_route(response, hints = {404: DECISION_API_OFF_HINT})
+ answers = payload.get("answers") if isinstance(payload, dict) else None
+ if not isinstance(answers, dict):
+ raise ToolError("Unsloth Studio returned no answers")
+ return SystemOneResult(
+ model = opt_text(payload.get("model")),
+ answers = {str(k): _answer(v) for k, v in answers.items() if isinstance(v, dict)},
+ request_id = opt_text(response.headers.get("x-typesafe-request-id")),
+ )
+
+
+TOOLS = ((chat, WRITES), (embed, READ_ONLY), (system_one, READ_ONLY))
diff --git a/studio/backend/studio_mcp/tools/training.py b/studio/backend/studio_mcp/tools/training.py
new file mode 100644
index 00000000000..b69bdcffd49
--- /dev/null
+++ b/studio/backend/studio_mcp/tools/training.py
@@ -0,0 +1,199 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Training tools: ``start_training`` for LLMs and image LoRAs, and ``list_training_runs``."""
+
+from __future__ import annotations
+
+import secrets
+from typing import Any, Literal, Optional
+from urllib.parse import quote
+
+from fastmcp.exceptions import ToolError
+
+from studio_mcp import checkpoints as named
+from studio_mcp.caller import Caller, current_caller
+from studio_mcp.errors import raise_for_status_field
+from studio_mcp.forward import forward
+from studio_mcp.outputs import (
+ CheckpointName,
+ TrainingRun,
+ TrainingRunDetail,
+ TrainingRuns,
+ TrainingStarted,
+)
+from studio_mcp.tools import READ_ONLY, WRITES, as_dict, integer, opt_text, route_json
+
+
+TRAINING_ROUTES = {"llm": "/api/train/start", "diffusion": "/api/train/diffusion/start"}
+# The dataset formats the trainer knows; the route itself accepts any string and fails later.
+FORMAT_TYPES = ("auto", "alpaca", "chatml", "sharegpt", "conversational", "raw")
+
+
+def _checked_config(config: dict[str, Any], kind: str) -> None:
+ """Validate the config the way the route will, so a mistake is reported before any GPU work."""
+ from pydantic import ValidationError
+
+ from models.training import DiffusionTrainingStartRequest, TrainingStartRequest
+
+ if kind == "llm" and "format_type" in config and config["format_type"] not in FORMAT_TYPES:
+ raise ToolError(f"format_type must be one of {', '.join(FORMAT_TYPES)}.")
+ model = TrainingStartRequest if kind == "llm" else DiffusionTrainingStartRequest
+ try:
+ model.model_validate(config)
+ except ValidationError as exc:
+ problems = "; ".join(
+ f"{'.'.join(str(part) for part in error['loc'])}: {error['msg']}"
+ for error in exc.errors()[:10]
+ )
+ raise ToolError(f"Invalid training config: {problems}") from 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}.
+
+ 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.
+
+ 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).
+
+ 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``)."""
+ config = dict(config)
+ if kind == "llm" and not config.get("start_request_id"):
+ config["start_request_id"] = f"mcp-{secrets.token_hex(8)}"
+ _checked_config(config, kind)
+ if validate_only:
+ return TrainingStarted(status = "valid", message = "The config is valid; nothing was started.")
+ start_request_id = opt_text(config.get("start_request_id"))
+ try:
+ payload = await route_json("POST", TRAINING_ROUTES[kind], json_body = config)
+ # The route refuses some starts with a 200 and status "error".
+ raise_for_status_field(payload)
+ except ToolError:
+ if start_request_id:
+ await _acknowledge_start(start_request_id)
+ raise
+ if not isinstance(payload, dict) or not opt_text(payload.get("job_id")):
+ raise ToolError("Unsloth Studio did not start the training job")
+ return TrainingStarted(
+ job_id = payload["job_id"],
+ status = opt_text(payload.get("status")) or "queued",
+ message = opt_text(payload.get("message")),
+ start_request_id = start_request_id,
+ )
+
+
+async def _acknowledge_start(start_request_id: str) -> None:
+ # A refused start stays the training status until acknowledged, hiding the run that is (or was) going; the
+ # training page acknowledges its own refusals the same way. Best effort: the refusal is what the agent needs.
+ try:
+ await forward(
+ current_caller(),
+ "POST",
+ f"/api/train/start-requests/{quote(start_request_id, safe = '')}/acknowledge",
+ )
+ except Exception:
+ pass
+
+
+# Scalars from a run's saved config worth showing; nothing that names a file or a folder.
+RUN_CONFIG_KEYS = (
+ "model_name",
+ "dataset",
+ "training_type",
+ "max_seq_length",
+ "num_epochs",
+ "max_steps",
+ "learning_rate",
+ "batch_size",
+ "gradient_accumulation_steps",
+ "warmup_steps",
+ "warmup_ratio",
+ "weight_decay",
+ "random_seed",
+ "load_in_4bit",
+ "packing",
+ "train_on_completions",
+ "optim",
+ "lr_scheduler_type",
+ "lora_r",
+ "lora_alpha",
+ "lora_dropout",
+ "use_rslora",
+)
+
+
+def _run_fields(row: dict, folders_by_ref: dict[str, str]) -> dict[str, Any]:
+ output_ref = opt_text(row.get("output_dir"))
+ return {
+ "id": row["id"],
+ "status": opt_text(row.get("status")) or "unknown",
+ "run_folder": folders_by_ref.get(output_ref) if output_ref else None,
+ }
+
+
+async def _folders_by_ref(caller: Caller) -> tuple[list[named.Checkpoint], dict[str, str]]:
+ """Run folders keyed by the opaque reference the runs route gives an API key for output_dir."""
+ from hub.utils.host_paths import cache_reference
+
+ checkpoints, folders = await named.list_checkpoints(caller)
+ return checkpoints, {cache_reference(path): folder for folder, path in folders.items()}
+
+
+def _numbers(values: Any, kind: type) -> Optional[list]:
+ if not isinstance(values, list):
+ return None
+ return [kind(v) for v in values if isinstance(v, (int, float)) and not isinstance(v, bool)]
+
+
+async def list_training_runs(
+ run_id: Optional[str] = None,
+ include_checkpoints: bool = False,
+ limit: int = 50,
+ offset: int = 0,
+) -> TrainingRuns:
+ """Training runs, newest first, with each run's folder; with ``run_id``, that run's saved settings and loss curve too. ``include_checkpoints`` lists every checkpoint by the name export_model takes: "<run folder>" for the final weights or "<run folder>/checkpoint-N". ``limit`` is 1 to 200."""
+ caller = current_caller()
+ checkpoints, folders_by_ref = await _folders_by_ref(caller)
+ limit, offset = max(1, min(limit, 200)), max(0, offset)
+ listing = await route_json(
+ "GET", "/api/train/runs", caller = caller, params = {"limit": limit, "offset": offset}
+ )
+ listing = as_dict(listing)
+ runs = [
+ TrainingRun.from_route(row, **_run_fields(row, folders_by_ref))
+ for row in listing.get("runs") or []
+ if isinstance(row, dict) and opt_text(row.get("id"))
+ ]
+ detail = None
+ if run_id:
+ found = as_dict(
+ await route_json("GET", f"/api/train/runs/{quote(run_id, safe = '')}", caller = caller)
+ )
+ row = {"id": run_id, **as_dict(found.get("run"))}
+ config, metrics = as_dict(found.get("config")), as_dict(found.get("metrics"))
+ detail = TrainingRunDetail.from_route(
+ row,
+ **_run_fields(row, folders_by_ref),
+ config = {
+ k: config[k]
+ for k in RUN_CONFIG_KEYS
+ if isinstance(config.get(k), (bool, int, float, str))
+ },
+ step_history = _numbers(metrics.get("step_history"), int),
+ loss_history = _numbers(metrics.get("loss_history"), float),
+ )
+ return TrainingRuns(
+ runs = runs,
+ total = integer(listing.get("total")),
+ run = detail,
+ checkpoints = [CheckpointName.model_validate(c, from_attributes = True) for c in checkpoints]
+ if include_checkpoints
+ else None,
+ )
+
+
+TOOLS = ((start_training, WRITES), (list_training_runs, READ_ONLY))
diff --git a/studio/backend/studio_mcp/tools/video.py b/studio/backend/studio_mcp/tools/video.py
new file mode 100644
index 00000000000..6a48515ebdd
--- /dev/null
+++ b/studio/backend/studio_mcp/tools/video.py
@@ -0,0 +1,50 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""``generate_video``: starts a video job; get_job follows it."""
+
+from __future__ import annotations
+
+from typing import Any, Optional
+
+from fastmcp.exceptions import ToolError
+
+from studio_mcp.caller import current_caller
+from studio_mcp.inputs import ImageInput, data_url, resolve_image
+from studio_mcp.outputs import VideoJobRef
+from studio_mcp.tools import WRITES, opt_text, present, route_json
+
+LOAD_VIDEO_HINT = "Load a video model with load_model(kind='video') first."
+
+
+def job_ref(job: Any) -> VideoJobRef:
+ if not isinstance(job, dict) or not opt_text(job.get("id")):
+ raise ToolError("Unsloth Studio returned no video job")
+ return VideoJobRef.from_route(job, status = opt_text(job.get("status")) or "queued")
+
+
+async def generate_video(
+ prompt: str,
+ seconds: Optional[str] = None,
+ size: Optional[str] = None,
+ first_frame: Optional[ImageInput] = None,
+ model: Optional[str] = None,
+) -> VideoJobRef:
+ """Start a video with the video model loaded in Unsloth Studio (load_model(kind="video") first) and return its job at once; poll get_job(kind="video", id=...) until it is completed, which returns a thumbnail and the video's URL. ``seconds`` and ``size`` ("WIDTHxHEIGHT") are strings, as in the OpenAI API; leave them out to use the model's defaults. Each video model takes only certain sizes, and an unsupported one is refused with the list it accepts. ``first_frame`` starts the video from an image."""
+ caller = current_caller()
+ body: dict[str, Any] = {"prompt": prompt, **present(seconds = seconds, size = size, model = model)}
+ if first_frame is not None:
+ data, mime = await resolve_image(caller, first_frame)
+ body["input_reference"] = data_url(data, mime)
+ job = await route_json(
+ "POST",
+ "/v1/videos",
+ caller = caller,
+ json_body = body,
+ hub_header = True,
+ hints = {503: LOAD_VIDEO_HINT},
+ )
+ return job_ref(job)
+
+
+TOOLS = ((generate_video, WRITES),)
diff --git a/studio/backend/tests/mcp_harness.py b/studio/backend/tests/mcp_harness.py
new file mode 100644
index 00000000000..05d06f430f4
--- /dev/null
+++ b/studio/backend/tests/mcp_harness.py
@@ -0,0 +1,441 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Serve a Studio MCP server behind the real gate in front of a fake Studio, so tool tests drive the whole path (gate, caller, forwarder) without a GPU or the real routes. Built fresh per test: at the fastmcp floor an http_app's session manager runs once per instance."""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import builtins
+import inspect
+import json
+import secrets
+import time
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any, Callable, Optional
+from urllib.parse import parse_qsl
+
+import pytest
+from fastapi import FastAPI, Request
+from fastapi.responses import JSONResponse, Response
+from fastapi.testclient import TestClient
+from starlette.applications import Starlette
+from starlette.routing import Mount
+
+from studio_mcp import gate
+from studio_mcp.caller import Caller
+from studio_mcp.gate import StudioMcpGate
+
+TEST_TOKEN = "sk-unsloth-test"
+MCP_HEADERS = {"Accept": "application/json, text/event-stream"}
+SENTINEL_ROOTS = ["/srv/mcp-sentinel-host", "C:\\mcp-sentinel"]
+# Client kwargs for TestClient: a loopback agent may name host paths, a remote one may not.
+LOCAL = {"base_url": "http://127.0.0.1:8888", "client": ("127.0.0.1", 50000)}
+REMOTE = {"base_url": "http://192.168.1.20:8888", "client": ("192.0.2.7", 50000)}
+PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 32
+JPEG = b"\xff\xd8\xff\xe0" + b"\x00" * 32
+WEBP = b"RIFF\x00\x00\x00\x00WEBPVP8 " + b"\x00" * 32
+WAV = b"RIFF\x24\x00\x00\x00WAVEfmt " + b"\x00" * 64
+WHISPER = "openai/whisper-small"
+# /load and /unload failures that arrive late, inside a padded 200.
+DEFERRED = [
+ {"status_code": 409, "detail": "Another model is loading"},
+ {"status_code": 500, "detail": "RuntimeError: CUDA out of memory"},
+]
+CONFIG = {
+ "model_name": "unsloth/Qwen3-0.6B",
+ "training_type": "LoRA/QLoRA",
+ "format_type": "auto",
+ "hf_dataset": "mlabonne/FineTome-100k",
+ "max_steps": 30,
+ "hf_token": "hf_cfg",
+}
+DIFFUSION = {
+ "base_model": "stabilityai/stable-diffusion-xl-base-1.0",
+ "data_dir": "my-photos",
+ "output_dir": "my-lora",
+ "train_steps": 500,
+}
+OUT = "/srv/unsloth/outputs"
+
+
+def _checkpoint(run: str, name: str, loss: float) -> dict:
+ path = f"{OUT}/{run}" if name == run else f"{OUT}/{run}/{name}"
+ return {"display_name": name, "path": path, "loss": loss}
+
+
+RUN_CHECKPOINTS = {
+ "outputs_dir": OUT,
+ "models": [
+ {
+ "name": "qwen-lora",
+ "checkpoints": [
+ _checkpoint("qwen-lora", "qwen-lora", 0.9),
+ _checkpoint("qwen-lora", "checkpoint-30", 1.1),
+ ],
+ "base_model": "unsloth/Qwen3-0.6B",
+ "peft_type": "LORA",
+ "lora_rank": 16,
+ "is_quantized": True,
+ },
+ {
+ "name": "qwen-lora-2",
+ "checkpoints": [_checkpoint("qwen-lora-2", "checkpoint-30", 1.0)],
+ "base_model": "unsloth/Qwen3-0.6B",
+ },
+ ],
+}
+
+
+def fake_studio(
+ routes: Optional[dict[tuple[str, str], Any]] = None, *, fallback: Any = None
+) -> FastAPI:
+ """A Studio stand-in. A callable handler gets ``(request, body)`` and returns a Response or JSON; any other value is the answer itself. Every call is recorded in ``app.state.calls`` as ``(method, path, headers, body)``, and its query string in ``app.state.queries`` as ``(method, path, query)``. With ``fallback``, every other route answers it, so nothing the tool calls goes unrecorded."""
+ app = FastAPI()
+ app.state.calls = []
+ app.state.queries = []
+
+ def bind(method: str, path: str, handler: Any) -> None:
+ async def endpoint(request: Request) -> Response:
+ body = await request.body()
+ app.state.calls.append((method, request.url.path, dict(request.headers), body))
+ app.state.queries.append((method, request.url.path, request.url.query))
+ result = handler
+ if callable(handler) and not isinstance(handler, Response):
+ result = handler(request, body)
+ if inspect.isawaitable(result):
+ result = await result
+ return result if isinstance(result, Response) else JSONResponse(result)
+
+ app.add_api_route(path, endpoint, methods = [method])
+
+ for (method, path), handler in (routes or {}).items():
+ bind(method, path, handler)
+ if fallback is not None:
+ for method in ("GET", "POST", "PUT", "PATCH", "DELETE"):
+ bind(method, "/{rest:path}", fallback)
+ return app
+
+
+def sequence(*answers: Any) -> Callable[..., Any]:
+ """A handler giving each answer in turn; the last one repeats."""
+ left = list(answers)
+ return lambda request, body: left.pop(0) if len(left) > 1 else left[0]
+
+
+def slow(answer: Any, seconds: float) -> Callable[..., Any]:
+ """A handler that gives ``answer`` after ``seconds``."""
+
+ async def handler(request: Request, body: bytes) -> Any:
+ await asyncio.sleep(seconds)
+ return answer
+
+ return handler
+
+
+def _accept_test_key(token: str) -> tuple[Optional[dict], str]:
+ if token == TEST_TOKEN:
+ return {"account_id": "owner", "username": "unsloth", "role": "owner"}, ""
+ return None, "Invalid or expired API key"
+
+
+def served(
+ mcp: Any,
+ studio_app: Any,
+ *,
+ monkeypatch: Any,
+ enabled: bool = True,
+ validate: Callable[[str], tuple[Optional[dict], str]] = _accept_test_key,
+) -> Starlette:
+ monkeypatch.setattr(gate, "is_mcp_enabled", lambda: enabled)
+ monkeypatch.setattr(gate, "_validate_key", validate)
+ mcp_app = mcp.http_app(path = "/", stateless_http = True)
+ app = Starlette(
+ routes = [Mount("/mcp", StudioMcpGate(mcp_app)), Mount("/", studio_app)],
+ lifespan = mcp_app.lifespan,
+ )
+ app.state.server_port = 8888
+ app.state.cloudflare_url = None
+ return app
+
+
+def _post_call(
+ client: Any,
+ name: str,
+ args: Optional[dict],
+ token: Optional[str],
+ headers: Optional[dict],
+ meta: Optional[dict] = None,
+) -> list[dict]:
+ """POST one ``tools/call``; returns every SSE ``data:`` message."""
+ params = {"name": name, "arguments": args or {}, **({"_meta": meta} if meta else {})}
+ sent = {**MCP_HEADERS, **(headers or {})}
+ if token is not None:
+ sent["Authorization"] = f"Bearer {token}"
+ body = {"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": params}
+ response = client.post("/mcp/", json = body, headers = sent)
+ assert response.status_code == 200, response.text
+ return [json.loads(line[5:]) for line in response.text.splitlines() if line.startswith("data:")]
+
+
+def _outcome(message: dict) -> dict:
+ return message.get("result", message.get("error"))
+
+
+def call_tool(
+ client: Any,
+ name: str,
+ args: Optional[dict] = None,
+ token: Optional[str] = TEST_TOKEN,
+ headers: Optional[dict] = None,
+) -> dict:
+ """``tools/call`` over the streamable HTTP transport; returns the JSON-RPC ``result`` (or ``error``)."""
+ return _outcome(_post_call(client, name, args, token, headers)[-1])
+
+
+def poison(payload: Any) -> Any:
+ """Suffix every string with both sentinel host paths, so a leak shows up wherever it comes from."""
+ if isinstance(payload, str):
+ return f"{payload} {SENTINEL_ROOTS[0]}/x {SENTINEL_ROOTS[1]}\\x"
+ if isinstance(payload, dict):
+ return {key: poison(value) for key, value in payload.items()}
+ if isinstance(payload, list):
+ return [poison(value) for value in payload]
+ return payload
+
+
+def run_tool(
+ monkeypatch: Any,
+ studio: Any,
+ name: str,
+ args: Optional[dict] = None,
+ *,
+ headers: Optional[dict] = None,
+ fallback: Any = None,
+ **client: Any,
+) -> tuple[dict, FastAPI]:
+ """Serve the Studio MCP server in front of ``studio`` (a fake_studio, or its routes and ``fallback``) and call one tool; returns ``(result, studio)``."""
+ from mcp_server import create_studio_mcp
+
+ studio = studio if isinstance(studio, FastAPI) else fake_studio(studio, fallback = fallback)
+ with TestClient(served(create_studio_mcp(), studio, monkeypatch = monkeypatch), **client) as http:
+ return call_tool(http, name, args, headers = headers), studio
+
+
+def call_with_progress(
+ monkeypatch: Any,
+ studio: FastAPI,
+ name: str,
+ args: dict,
+ token: str = "p",
+) -> tuple[list[dict], dict]:
+ """Call a tool with a progress token; returns the progress notifications' params and the final result."""
+ from mcp_server import create_studio_mcp
+
+ with TestClient(served(create_studio_mcp(), studio, monkeypatch = monkeypatch)) as http:
+ messages = _post_call(http, name, args, TEST_TOKEN, None, {"progressToken": token})
+ progress = [m["params"] for m in messages if m.get("method") == "notifications/progress"]
+ return progress, _outcome(messages[-1])
+
+
+def call_to(studio: FastAPI, path: str) -> tuple:
+ return next(c for c in studio.state.calls if c[1] == path)
+
+
+def bodies(studio: FastAPI, path: str) -> list[Any]:
+ return [json.loads(c[3]) for c in studio.state.calls if c[1] == path]
+
+
+def queries(studio: FastAPI, path: str) -> list[dict[str, str]]:
+ return [
+ dict(parse_qsl(q, keep_blank_values = True)) for _m, p, q in studio.state.queries if p == path
+ ]
+
+
+def form(studio: FastAPI, path: str) -> dict[str, tuple[Optional[str], bytes]]:
+ """The multipart fields of the first call to ``path``, as ``{name: (filename, data)}``."""
+ from email.parser import BytesParser
+ from email.policy import default
+
+ _m, _p, headers, body = call_to(studio, path)
+ 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 openai_error(
+ message: str,
+ status: int,
+ *,
+ type: str = "invalid_request_error",
+ param: Optional[str] = None,
+ code: Optional[str] = None,
+ headers: Optional[dict] = None,
+) -> JSONResponse:
+ error = {"message": message, "type": type, "param": param, "code": code}
+ return JSONResponse({"error": error}, status_code = status, headers = headers)
+
+
+def b64(data: bytes) -> str:
+ return base64.b64encode(data).decode()
+
+
+def data_url(data: bytes, mime: str) -> str:
+ return f"data:{mime};base64,{b64(data)}"
+
+
+PNG_URL = {"data_url": data_url(PNG, "image/png")}
+WAV_INPUT = {"data_base64": b64(WAV), "filename": "a.wav"}
+
+
+def make_caller(*, cloudflare_url: Optional[str] = None, **fields: Any) -> Caller:
+ # As the gate would admit a loopback agent; fields override any part.
+ defaults = {
+ "token": TEST_TOKEN,
+ "account_id": "owner",
+ "direct_local": True,
+ "public_base": "http://127.0.0.1:8888",
+ "studio_app": SimpleNamespace(state = SimpleNamespace(cloudflare_url = cloudflare_url)),
+ }
+ return Caller(**{**defaults, **fields})
+
+
+def stt_state(
+ *,
+ downloaded: Any = (),
+ loaded: Optional[str] = None,
+ download: Optional[dict] = None,
+ **fields: Any,
+) -> dict:
+ return {
+ "loaded_model": loaded,
+ "loading": False,
+ "models": [WHISPER, "openai/whisper-large-v3"],
+ "downloaded_models": list(downloaded),
+ "download": download or {"downloading": False, "completed_download_ids": []},
+ **fields,
+ }
+
+
+def register_export_job(
+ account_id: str = "owner",
+ job_id: str = "job-a",
+ **fields: Any,
+) -> Any:
+ from studio_mcp import export_jobs
+
+ job = export_jobs.ExportJob(job_id = job_id, account_id = account_id, format = "gguf", **fields)
+ export_jobs._jobs[f"{account_id}:{job_id}"] = job
+ return job
+
+
+def run_export_job(monkeypatch: Any, studio: FastAPI, args: dict) -> tuple[dict, Optional[dict]]:
+ """Serve ``studio``, start export_model, then poll get_job until the job settles; returns ``(started, job)``."""
+ from mcp_server import create_studio_mcp
+ with TestClient(served(create_studio_mcp(), studio, monkeypatch = monkeypatch)) as http:
+ started = call_tool(http, "export_model", args)
+ if started.get("isError"):
+ return started, None
+ job_id = started["structuredContent"]["job_id"]
+ # By time, not a fixed count: back-to-back polls can beat the background job on a slow host.
+ deadline = time.monotonic() + 30.0
+ while True:
+ job = call_tool(http, "get_job", {"kind": "export", "id": job_id})
+ if job["structuredContent"]["status"] != "running" or time.monotonic() > deadline:
+ return started, job
+ time.sleep(0.02)
+
+
+def route_studio(
+ router: Any = None,
+ prefix: str = "",
+ *,
+ subject: str = "unsloth",
+ overrides: Optional[dict] = None,
+) -> FastAPI:
+ from auth.authentication import get_current_subject
+
+ app = FastAPI()
+ app.state.bind_host = "127.0.0.1"
+ if router is not None:
+ app.include_router(router, prefix = prefix)
+ app.dependency_overrides[get_current_subject] = lambda: subject
+ app.dependency_overrides.update(overrides or {})
+ return app
+
+
+def _reset_auth_caches() -> None:
+ from auth import policy, storage
+ from utils import mcp_access
+ from utils.keyless_api_access import _reset_scope_cache
+
+ storage._reset_api_key_hash_cache()
+ policy.invalidate_account_cache()
+ _reset_scope_cache()
+ mcp_access._reset_cache()
+
+
+def isolated_auth(tmp_path, monkeypatch):
+ """An empty auth database of this test's own, with the MCP switch env unset and every cache reset."""
+ from auth import storage
+ from utils.mcp_access import ENV_FORCE
+
+ monkeypatch.setattr(storage, "DB_PATH", tmp_path / "auth.db")
+ monkeypatch.setattr(storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")
+ monkeypatch.setattr(storage, "_bootstrap_password", None)
+ monkeypatch.setattr(storage, "_api_key_pbkdf2_salt_cache", None)
+ monkeypatch.delenv(ENV_FORCE, raising = False)
+ monkeypatch.delenv("UNSLOTH_STUDIO_MCP_TOKEN", raising = False)
+ _reset_auth_caches()
+ yield
+ _reset_auth_caches()
+
+
+def seed_owner() -> None:
+ from auth import storage
+ storage.create_initial_user(
+ username = storage.DEFAULT_ADMIN_USERNAME,
+ password = "human-password-123",
+ jwt_secret = secrets.token_urlsafe(64),
+ must_change_password = False,
+ )
+
+
+def fast_polls(monkeypatch):
+ from studio_mcp import loading
+ monkeypatch.setattr(loading, "POLL_INTERVAL_S", 0.01)
+
+
+def owner_auth(isolated_auth):
+ seed_owner()
+
+
+def file_spy(monkeypatch):
+ """Records every way the tool could open or inspect a file."""
+ touched = []
+
+ def spy(kind: str, real: Callable) -> Callable:
+ def wrapper(target, *args, **kwargs):
+ if "mcp-input" in str(target):
+ touched.append((kind, str(target)))
+ return real(target, *args, **kwargs)
+
+ return wrapper
+
+ monkeypatch.setattr(builtins, "open", spy("open", builtins.open))
+ monkeypatch.setattr(Path, "stat", spy("stat", Path.stat))
+ monkeypatch.setattr(Path, "read_bytes", spy("read", Path.read_bytes))
+ return touched
diff --git a/studio/backend/tests/test_export_absolute_paths.py b/studio/backend/tests/test_export_absolute_paths.py
index 48f1d276051..34acbe04311 100644
--- a/studio/backend/tests/test_export_absolute_paths.py
+++ b/studio/backend/tests/test_export_absolute_paths.py
@@ -208,6 +208,7 @@ def _install_lightweight_backend_stubs(monkeypatch):
"LoRAInfo",
"ModelListResponse",
"LoadCheckpointRequest",
+ "ExportCancelRequest",
"ExportStatusResponse",
"ExportOperationResponse",
"ExportMergedModelRequest",
diff --git a/studio/backend/tests/test_export_expected_checkpoint.py b/studio/backend/tests/test_export_expected_checkpoint.py
new file mode 100644
index 00000000000..bb73a3d32db
--- /dev/null
+++ b/studio/backend/tests/test_export_expected_checkpoint.py
@@ -0,0 +1,180 @@
+# 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 and export are two calls, so another load can land between them; the orchestrator checks
+# expected_checkpoint under the lock the export holds.
+
+from __future__ import annotations
+
+import pytest
+
+import models
+
+
+def orchestrator(monkeypatch, tmp_path):
+ from core.export import orchestrator as orchestrator_module
+
+ orch = orchestrator_module.ExportOrchestrator()
+ sent = []
+ monkeypatch.setattr(orch, "_ensure_subprocess_alive", lambda: True)
+ monkeypatch.setattr(orch, "_send_cmd", lambda cmd: sent.append(cmd))
+ monkeypatch.setattr(
+ orch,
+ "_wait_response",
+ lambda kind, timeout = None: {"success": True, "message": "Exported", "output_path": None},
+ )
+ loaded = tmp_path / "run" / "checkpoint-30"
+ loaded.mkdir(parents = True)
+ orch.current_checkpoint = str(loaded)
+ yield orch, sent, loaded, orchestrator_module
+ # The orchestrator's atexit cleanup would otherwise try to shut down a fake worker.
+ orch._proc = None
+
+
+def test_an_export_of_a_replaced_checkpoint_sends_nothing(orchestrator, tmp_path):
+ orch, sent, _loaded, module = orchestrator
+ result = orch.export_gguf(save_directory = "out", expected_checkpoint = str(tmp_path / "other"))
+ assert result == (False, module.CHECKPOINT_CHANGED, None)
+ assert sent == []
+ assert orch.is_export_active() is False
+
+
[email protected]("unloaded", [False, True])
+def test_the_loaded_checkpoint_or_none_expected_exports(orchestrator, unloaded):
+ orch, sent, loaded, _module = orchestrator
+ if unloaded:
+ orch.current_checkpoint = None
+ assert orch.export_lora_adapter(save_directory = "out")[0] is True
+ else:
+ assert orch.export_merged_model(save_directory = "out", expected_checkpoint = f"{loaded}/")[0]
+ assert [cmd["export_type"] for cmd in sent] == ["lora" if unloaded else "merged"]
+ assert "expected_checkpoint" not in sent[0]
+
+
[email protected]("name", ["BaseModel", "GGUF", "LoRAAdapter", "MergedModel"])
+def test_every_export_request_takes_expected_checkpoint(name):
+ model = getattr(models, f"Export{name}Request")
+ assert model(save_directory = "out", expected_checkpoint = "/x").expected_checkpoint == "/x"
+ assert model(save_directory = "out").expected_checkpoint is None
+
+
+class _Worker:
+ pid = 0
+
+ def __init__(self):
+ self.terminated = False
+
+ def is_alive(self):
+ return not self.terminated
+
+ def terminate(self):
+ self.terminated = True
+
+ def join(self, timeout = None):
+ pass
+
+
+def test_cancel_with_an_op_id_stops_only_that_op(orchestrator):
+ orch, _sent, _loaded, _module = orchestrator
+ worker = orch._proc = _Worker()
+ assert orch._begin_op("theirs")
+ # Another caller's op is running: the worker is left alone.
+ assert orch.cancel_export(expected_op_id = "mine") is False
+ assert worker.terminated is False
+ assert orch.cancel_export(expected_op_id = "theirs") is True
+ assert worker.terminated is True
+
+
+def test_an_op_cancelled_before_it_started_is_refused_when_it_starts(orchestrator):
+ orch, sent, _loaded, module = orchestrator
+ orch._proc = _Worker()
+ assert orch.cancel_export(expected_op_id = "queued") is False
+ assert orch.export_gguf(save_directory = "out", op_id = "queued") == (
+ False,
+ module.OP_CANCELLED,
+ None,
+ )
+ assert sent == []
+ # Refused once: the id is spent, and an op without an id runs as before.
+ assert orch.export_gguf(save_directory = "out", op_id = "queued")[0] is True
+ assert orch.export_gguf(save_directory = "out")[0] is True
+ assert orch._active_op_id is None
+
+
+def test_cancel_without_an_op_id_stops_whatever_runs(orchestrator):
+ orch, _sent, _loaded, _module = orchestrator
+ worker = orch._proc = _Worker()
+ orch._begin_op("theirs")
+ assert orch.cancel_export() is True
+ assert worker.terminated is True
+
+
[email protected]("name", ["BaseModel", "GGUF", "LoRAAdapter", "MergedModel"])
+def test_every_load_and_export_request_takes_an_op_id(name):
+ model = getattr(models, f"Export{name}Request")
+ assert model(save_directory = "out", op_id = "op-1").op_id == "op-1"
+ assert models.LoadCheckpointRequest(checkpoint_path = "/x", op_id = "op-2").op_id == "op-2"
+ assert models.ExportCancelRequest().expected_op_id is None
+
+
+def test_a_cancel_landing_while_the_old_worker_is_torn_down_stops_the_new_one(
+ orchestrator, monkeypatch
+):
+ # The matched cancel finds no live worker to kill, so the load must not carry on in a fresh one.
+ orch, _sent, _loaded, module = orchestrator
+ import utils.transformers_version as tv
+
+ monkeypatch.setattr(tv, "sidecar_swap_in_progress", lambda: False)
+ spawned, shut = [], []
+
+ def shutdown(timeout = 10.0):
+ shut.append(orch._proc)
+ if len(shut) == 1:
+ orch._proc = None
+ assert orch.cancel_export(expected_op_id = "load-1") is False
+ return True
+
+ def spawn(config):
+ orch._proc = _Worker()
+ spawned.append(orch._proc)
+
+ monkeypatch.setattr(orch, "_shutdown_subprocess", shutdown)
+ monkeypatch.setattr(orch, "_spawn_subprocess", spawn)
+ monkeypatch.setattr(
+ orch,
+ "_wait_response",
+ lambda *a, **k: pytest.fail("a cancelled load must not wait for the worker"),
+ )
+ monkeypatch.setattr("utils.hardware.gpu_ids_with_torch_kernels", lambda: [])
+ orch._proc = _Worker()
+ assert orch.load_checkpoint("/ckpt", op_id = "load-1") == (False, module.OP_CANCELLED)
+ assert len(spawned) == 1 and shut[-1] is spawned[0]
+ assert orch.current_checkpoint is None
+ assert orch.get_last_op()["status"] == "cancelled"
+
+
[email protected]("op", ["load", "export"])
+def test_a_cancel_landing_right_after_the_op_starts_is_never_erased(orchestrator, monkeypatch, op):
+ orch, sent, _loaded, module = orchestrator
+ import utils.transformers_version as tv
+
+ monkeypatch.setattr(tv, "sidecar_swap_in_progress", lambda: False)
+ monkeypatch.setattr("utils.hardware.gpu_ids_with_torch_kernels", lambda: [])
+ orch._proc = _Worker()
+ cancelled = []
+ # The op id is published before clear_logs runs, so a matching cancel can land there.
+ monkeypatch.setattr(
+ orch, "clear_logs", lambda: cancelled.append(orch.cancel_export(expected_op_id = "op-1"))
+ )
+ monkeypatch.setattr(orch, "_shutdown_subprocess", lambda timeout = 10.0: True)
+ monkeypatch.setattr(orch, "_spawn_subprocess", lambda config: setattr(orch, "_proc", _Worker()))
+ if op == "load":
+ monkeypatch.setattr(
+ orch, "_wait_response", lambda *a, **k: pytest.fail("a cancelled load must not wait")
+ )
+ assert orch.load_checkpoint("/ckpt", op_id = "op-1") == (False, module.OP_CANCELLED)
+ else:
+ orch.export_gguf(save_directory = "out", op_id = "op-1")
+ assert cancelled == [True]
+ assert orch.get_last_op()["status"] == "cancelled"
diff --git a/studio/backend/tests/test_hub_write_ambient_token.py b/studio/backend/tests/test_hub_write_ambient_token.py
index 54d222a9871..074b7921b9c 100644
--- a/studio/backend/tests/test_hub_write_ambient_token.py
+++ b/studio/backend/tests/test_hub_write_ambient_token.py
@@ -659,19 +659,67 @@ def test_every_hub_write_route_names_the_ambient_policy():
assert not missing, "these reach a Hub write without the ambient policy: " + ", ".join(missing)
-def test_every_mcp_tool_that_calls_a_gated_route_names_the_policy():
- """A direct call never resolves a ``Depends`` default, so each tool passes it or goes
- ambient in silence."""
- import inspect
- import re
+def test_the_mcp_export_tool_never_goes_ambient(monkeypatch):
+ """The MCP export tool reaches the export routes as the agent's API key, so the routes'
+ own policy holds: allow_ambient is False for that caller. The tool sends the agent's token
+ in the body of both calls, and a push without one meets the route's refusal instead of
+ the server's own Hugging Face token."""
+ import json
+
+ from studio_mcp import export_jobs
- import mcp_server
+ from .mcp_harness import bodies, fake_studio, run_export_job
+
+ export_jobs._reset()
+ backend = _backend(monkeypatch, "export_gguf")
+
+ def status(request, body):
+ # Like the real route: it names the checkpoint the last load put in the worker.
+ loaded = bodies(studio, "/api/export/load-checkpoint")
+ return {
+ "last_op_seq": 0,
+ "current_checkpoint": loaded[-1]["checkpoint_path"] if loaded else None,
+ }
- src = inspect.getsource(mcp_server.create_studio_mcp)
- calls = re.findall(r"await (?:load|export)\(request[^)]*\)", src)
- assert calls, "the MCP tools no longer call the export routes the way this test reads"
- for call in calls:
- assert "allow_ambient = False" in call, f"MCP call goes ambient: {call}"
+ studio = fake_studio(
+ {
+ ("GET", "/api/models/checkpoints"): {
+ "outputs_dir": "/o",
+ "models": [
+ {"name": "run", "checkpoints": [{"display_name": "run", "path": "/o/run"}]}
+ ],
+ },
+ ("POST", "/api/export/load-checkpoint"): {"success": True, "message": "Loaded"},
+ ("GET", "/api/export/status"): status,
+ }
+ )
+ studio.state.bind_host = "127.0.0.1"
+ studio.include_router(export_routes.router, prefix = "/api/export")
+ studio.dependency_overrides[get_current_subject] = lambda: "unsloth"
+
+ def export(**args):
+ # The job runs in the background; a fixed number of back-to-back polls can beat it on a slow host.
+ sent = {"checkpoint": "run", "format": "gguf", "save_directory": "out", **args}
+ return run_export_job(monkeypatch, studio, sent)[1]["structuredContent"]
+
+ with_token = export(push_to_hub = True, repo_id = "me/m", hf_token = "hf_agent")
+ without = export(push_to_hub = True, repo_id = "me/m")
+ export_jobs._reset()
+
+ loads = [
+ {k: v for k, v in body.items() if k != "op_id"}
+ for body in bodies(studio, "/api/export/load-checkpoint")
+ ]
+ assert with_token["status"] == "completed"
+ assert loads[0] == {"checkpoint_path": "/o/run", "max_seq_length": 2048, "hf_token": "hf_agent"}
+ assert backend.export_gguf.call_args.kwargs["hf_token"] == "hf_agent"
+ assert without["status"] == "failed"
+ assert without["error"].startswith(
+ "Hugging Face token is required to push to Hub when authenticated via API key."
+ )
+ assert backend.export_gguf.call_count == 1
+ assert "hf_token" not in loads[1]
+ assert json.dumps(loads).count("hf_agent") == 1
def test_the_worker_can_still_disable_implicit_tokens_when_it_starts():
diff --git a/studio/backend/tests/test_mcp_access_route.py b/studio/backend/tests/test_mcp_access_route.py
new file mode 100644
index 00000000000..59a2328853c
--- /dev/null
+++ b/studio/backend/tests/test_mcp_access_route.py
@@ -0,0 +1,124 @@
+# 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 pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from auth import policy, storage
+from auth.authentication import create_access_token
+from routes import settings
+from utils.keyless_api_access import set_keyless_api_access
+from utils.mcp_access import ENV_FORCE, get_mcp_enabled
+
+from .mcp_harness import isolated_auth, owner_auth # noqa: F401 (fixtures)
+
+UI_ONLY = "Agent access (MCP) can only be changed from the Unsloth UI."
+URL = "/api/settings/mcp-access"
+pytestmark = pytest.mark.usefixtures("owner_auth")
+
+
+def client():
+ app = FastAPI()
+ app.include_router(settings.router, prefix = "/api/settings")
+ app.state.bind_host = "127.0.0.1"
+ app.state.secure = False
+ app.state.remote_access_is_colab = False
+ app.state.lan_access_is_colab = False
+ app.state.lan_access_secure_launch = False
+ app.state.cloudflare_url = None
+ with TestClient(app, base_url = "http://127.0.0.1:8888", client = ("127.0.0.1", 50000)) as http:
+ yield http
+
+
+def _owner_session():
+ return {
+ "Authorization": f"Bearer {create_access_token(subject = storage.DEFAULT_ADMIN_USERNAME)}"
+ }
+
+
+def _alice_session():
+ storage.issue_account_setup_code(username = "alice")
+ record = storage.get_user_record("alice")
+ secret = storage.update_account_password(
+ "alice",
+ "alice-password-123",
+ expect_password_hash = record["password_hash"],
+ expect_secret = record["jwt_secret"],
+ )
+ policy.invalidate_account_cache()
+ return {"Authorization": f"Bearer {create_access_token(subject = 'alice', secret = secret)}"}
+
+
+def test_the_owner_session_reads_and_turns_it_on(client):
+ got = client.get(URL, headers = _owner_session())
+ assert got.status_code == 200, got.text
+ assert got.json() == {
+ "enabled": False,
+ "forced_by_env": False,
+ "url": "http://127.0.0.1:8888/mcp/",
+ }
+
+ put = client.put(URL, json = {"enabled": True}, headers = _owner_session())
+ assert put.status_code == 200, put.text
+ assert put.json()["enabled"] is True
+ assert put.json()["url"].endswith("/mcp/")
+ assert get_mcp_enabled() is True
+
+ off = client.put(URL, json = {"enabled": False}, headers = _owner_session())
+ assert off.json()["enabled"] is False
+ assert get_mcp_enabled() is False
+
+
[email protected]("value", ["true", 1, None])
+def test_the_payload_must_be_a_strict_bool(client, value):
+ response = client.put(URL, json = {"enabled": value}, headers = _owner_session())
+ assert response.status_code == 422
+ assert get_mcp_enabled() is False
+
+
+def _owner_api_key():
+ raw_key, _row = storage.create_api_key(storage.DEFAULT_ADMIN_USERNAME, name = "agent")
+ return {"Authorization": f"Bearer {raw_key}"}
+
+
+def _keyless(headers):
+ def make():
+ set_keyless_api_access("full", tools = True)
+ return headers
+
+ return make
+
+
+OWNER_ONLY = "Only the installation owner can do this"
+
+
[email protected]("method", ["GET", "PUT"])
+ "make_headers,detail",
+ [
+ (_owner_api_key, UI_ONLY),
+ (_keyless({}), UI_ONLY),
+ (_keyless({"Authorization": "Bearer not-needed"}), UI_ONLY),
+ (_alice_session, OWNER_ONLY),
+ ],
+ ids = ["owner-api-key", "keyless", "keyless-dummy-bearer", "managed-account-session"],
+)
+def test_anything_but_the_owners_ui_session_is_refused(client, method, make_headers, detail):
+ response = client.request(method, URL, json = {"enabled": True}, headers = make_headers())
+ assert response.status_code == 403
+ assert response.json()["detail"] == detail
+ assert get_mcp_enabled() is False
+
+
+def test_a_put_while_forced_by_env_is_a_conflict(client, monkeypatch):
+ monkeypatch.setenv(ENV_FORCE, "1")
+ got = client.get(URL, headers = _owner_session())
+ assert got.json()["enabled"] is True
+ assert got.json()["forced_by_env"] is True
+
+ response = client.put(URL, json = {"enabled": False}, headers = _owner_session())
+ assert response.status_code == 409
+ assert response.json()["detail"] == "Set by UNSLOTH_STUDIO_ENABLE_MCP."
+ assert get_mcp_enabled() is False
diff --git a/studio/backend/tests/test_mcp_access_setting.py b/studio/backend/tests/test_mcp_access_setting.py
new file mode 100644
index 00000000000..3e2fb406a9d
--- /dev/null
+++ b/studio/backend/tests/test_mcp_access_setting.py
@@ -0,0 +1,104 @@
+# 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 pytest
+
+import storage.studio_db as studio_db
+from utils import mcp_access
+from utils.account_context import OWNER, AccountContext, run_as
+from utils.mcp_access import (
+ ENV_FORCE,
+ MCP_ENABLED_SETTING_KEY,
+ forced_by_env,
+ get_mcp_enabled,
+ is_mcp_enabled,
+ set_mcp_enabled,
+)
+
+ALICE = AccountContext("a" * 32, "alice")
+
+
[email protected](autouse = True)
+def fresh_cache(monkeypatch):
+ monkeypatch.delenv(ENV_FORCE, raising = False)
+ mcp_access._reset_cache()
+ yield
+ mcp_access._reset_cache()
+
+
[email protected]("value", [None, "1", "0", "true", "yes", "", " 1", "2"])
+def test_only_env_one_forces_it_on_and_never_writes_the_setting(monkeypatch, value):
+ if value is not None:
+ monkeypatch.setenv(ENV_FORCE, value)
+ assert forced_by_env() is (value == "1")
+ assert is_mcp_enabled() is (value == "1")
+ assert get_mcp_enabled() is False
+
+
+ "call",
+ [
+ lambda: run_as(ALICE, set_mcp_enabled, True),
+ *(lambda v = v: set_mcp_enabled(v) for v in ["true", 1, None]),
+ ],
+)
+def test_setter_refuses_a_managed_account_or_a_non_bool(call):
+ with pytest.raises(ValueError):
+ call()
+ assert get_mcp_enabled() is False
+
+
+def test_set_invalidates_the_cache():
+ assert get_mcp_enabled() is False
+ assert set_mcp_enabled(True) is True
+ assert get_mcp_enabled() is True
+ assert is_mcp_enabled() is True
+ set_mcp_enabled(False)
+ assert get_mcp_enabled() is False
+
+
+def test_a_cached_value_is_held_for_the_ttl():
+ assert get_mcp_enabled() is False
+ studio_db.upsert_app_settings({MCP_ENABLED_SETTING_KEY: True})
+ assert get_mcp_enabled() is False
+ mcp_access._reset_cache()
+ assert get_mcp_enabled() is True
+
+
+def test_a_db_error_reads_false(monkeypatch):
+ set_mcp_enabled(True)
+ mcp_access._reset_cache()
+
+ def broken(*args, **kwargs):
+ raise RuntimeError("database is locked")
+
+ monkeypatch.setattr(studio_db, "get_app_setting", broken)
+ assert get_mcp_enabled() is False
+ assert is_mcp_enabled() is False
+
+
+def test_a_non_bool_stored_value_reads_false():
+ studio_db.upsert_app_settings({MCP_ENABLED_SETTING_KEY: "true"})
+ assert get_mcp_enabled() is False
+
+
+def test_a_write_during_a_read_is_not_published(monkeypatch):
+ set_mcp_enabled(True)
+ real = mcp_access._read_from_db
+
+ def read_then_disable():
+ value = real()
+ set_mcp_enabled(False)
+ return value
+
+ monkeypatch.setattr(mcp_access, "_read_from_db", read_then_disable)
+ assert get_mcp_enabled() is False
+ monkeypatch.setattr(mcp_access, "_read_from_db", real)
+ assert get_mcp_enabled() is False
+
+
+def test_a_managed_account_reads_the_owners_value():
+ run_as(OWNER, set_mcp_enabled, True)
+ mcp_access._reset_cache()
+ assert run_as(ALICE, studio_db.get_app_setting, MCP_ENABLED_SETTING_KEY, None) is None
+ assert run_as(ALICE, get_mcp_enabled) is True
diff --git a/studio/backend/tests/test_mcp_errors.py b/studio/backend/tests/test_mcp_errors.py
new file mode 100644
index 00000000000..3b957b7ea54
--- /dev/null
+++ b/studio/backend/tests/test_mcp_errors.py
@@ -0,0 +1,212 @@
+# 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 httpx
+import pytest
+from fastmcp.exceptions import ToolError
+
+from studio_mcp.errors import raise_for_payload, raise_for_route, raise_for_status_field, tool_error
+from studio_mcp.forward import ndjson_last
+
+from .mcp_harness import DEFERRED, openai_error
+
+SENTINEL = "/srv/mcp-sentinel/models/secret.gguf"
+WIN_SENTINEL = "C:\\mcp-sentinel\\models\\secret.gguf"
+BUSY = f"Another account is generating on the resident model {SENTINEL}"
+BUSY_OUT = "GPU busy: Another account is generating"
+
+
+def _response(
+ status,
+ body = None,
+ *,
+ headers = None,
+ content = None,
+):
+ content = json.dumps(body).encode() if content is None else content
+ return httpx.Response(
+ status, content = content, headers = {"content-type": "application/json", **(headers or {})}
+ )
+
+
+def _v1(status, message, **fields):
+ sent = openai_error(message, status, **fields)
+ return httpx.Response(status, content = sent.body, headers = sent.raw_headers)
+
+
+def _route(resp, **kwargs):
+ # An NDJSON stream's caller passes its last line as the payload.
+ if resp.content.startswith(b'{"type"'):
+ kwargs["payload"] = ndjson_last(resp.content)
+ return raise_for_route(resp, **kwargs)
+
+
+def _message(resp, **kwargs):
+ with pytest.raises(ToolError) as caught:
+ _route(resp, **kwargs)
+ message = str(caught.value)
+ assert "mcp-sentinel" not in message
+ return message
+
+
+def _ndjson(*lines):
+ return _response(200, content = "\n".join(json.dumps(line) for line in lines).encode())
+
+
+# A plain {"detail": str} at each status the routes send.
+DETAIL_CASES = [
+ pytest.param(_response(status, {"detail": f"{text} {path}"}), [text, f"(HTTP {status})"], id = id)
+ for status, text, path, id in [
+ (404, "Model not found", SENTINEL, "api-detail"),
+ (499, "Client cancelled", "", "499"),
+ (501, "STT runtime missing", WIN_SENTINEL, "501-windows-path"),
+ (401, "Invalid or expired API key", "", "401"),
+ (403, "Only the installation owner can do this", "", "403"),
+ ]
+]
+VALIDATION_422 = {
+ "detail": [
+ {"loc": ["body", "max_tokens"], "msg": "Input should be a valid integer", "type": "x"},
+ {"loc": ["query", "name"], "msg": f"bad {SENTINEL}", "type": "value_error"},
+ ]
+}
+CASES = DETAIL_CASES + [
+ pytest.param(
+ _response(409, {"detail": {"message": f"Busy loading {SENTINEL}", "code": "x"}}),
+ ["Busy loading", "(HTTP 409)"],
+ id = "api-detail-dict",
+ ),
+ pytest.param(
+ _v1(404, f"No model {SENTINEL}", type = "not_found_error", code = "model_not_found"),
+ ["No model", "(model_not_found)", "(HTTP 404)"],
+ id = "v1-envelope",
+ ),
+ pytest.param(
+ _response(
+ 409,
+ {"error": "gpu_busy", "message": BUSY, "retry_after": 7},
+ headers = {"Retry-After": "7"},
+ ),
+ [BUSY_OUT, "Retry after 7 s."],
+ id = "gpu-busy-unwrapped",
+ ),
+ pytest.param(
+ _v1(409, BUSY, type = "conflict_error", code = "gpu_busy", headers = {"Retry-After": "4"}),
+ [BUSY_OUT, "Retry after 4 s."],
+ id = "gpu-busy-v1-envelope",
+ ),
+ pytest.param(
+ _response(409, {"detail": {"error": "gpu_busy", "message": BUSY, "retry_after": 9}}),
+ [BUSY_OUT, "Retry after 9 s."],
+ id = "gpu-busy-detail-wrapped",
+ ),
+ pytest.param(
+ _v1(400, "messages: Field required", param = "messages"),
+ ["Invalid arguments: messages: Field required"],
+ id = "v1-validation-400",
+ ),
+ pytest.param(
+ _response(422, VALIDATION_422),
+ ["Invalid arguments: max_tokens: Input should be a valid integer; query.name: bad"],
+ id = "api-validation-422",
+ ),
+ pytest.param(
+ _response(
+ 503,
+ {"detail": {"error_type": "model_loading", "message": f"Loading {SENTINEL}"}},
+ headers = {"Retry-After": "30"},
+ ),
+ ["Loading", "(HTTP 503)", "Retry after 30 s."],
+ id = "systemone-503-retry-after",
+ ),
+ pytest.param(
+ _response(
+ 400,
+ {"detail": f"Not enough memory for 4096x4096 {SENTINEL}"},
+ headers = {"X-Unsloth-Refusal": "memory-estimate"},
+ ),
+ ["Not enough memory for 4096x4096", "Pass allow_oversized=true to try anyway."],
+ id = "image-memory-refusal",
+ ),
+ pytest.param(
+ _response(502, content = f"Bad gateway {SENTINEL}".encode()),
+ ["Bad gateway", "(HTTP 502)"],
+ id = "plain-text",
+ ),
+ pytest.param(
+ _ndjson({"type": "progress"}, {"type": "error", "message": f"Decoding failed {SENTINEL}"}),
+ ["Decoding failed"],
+ id = "ndjson-error-line",
+ ),
+ *[
+ pytest.param(
+ _response(
+ 200,
+ content = b" " * 64
+ + json.dumps(
+ {"_deferred_error": {**d, "detail": f"{d['detail']} {SENTINEL}"}}
+ ).encode(),
+ ),
+ [d["detail"], f"(HTTP {d['status_code']})"],
+ id = f"padded-200-deferred-{d['status_code']}",
+ )
+ for d in DEFERRED
+ ],
+]
+
+
[email protected]("resp,expected", CASES)
+def test_route_errors_become_scrubbed_tool_errors(resp, expected):
+ message = _message(resp)
+ for text in expected:
+ assert text in message
+
+
+ "resp,expected",
+ [
+ (_response(200, content = b" \n " + b'{"status": "loaded"}'), {"status": "loaded"}),
+ (
+ _ndjson({"type": "progress"}, {"type": "result", "text": "hi"}),
+ {"type": "result", "text": "hi"},
+ ),
+ (httpx.Response(200, content = b"\x89PNG\r\n"), None),
+ ],
+ ids = ["padded-200", "ndjson-result", "non-json"],
+)
+def test_a_successful_body_parses(resp, expected):
+ assert _route(resp) == expected
+ assert raise_for_payload(None) is None
+
+
+def test_train_start_status_error_is_an_error():
+ payload = {"job_id": "", "status": "error", "message": f"Training is in progress {SENTINEL}"}
+ assert raise_for_route(_response(200, payload)) == payload
+ with pytest.raises(ToolError) as caught:
+ raise_for_status_field(payload)
+ assert str(caught.value).startswith("Training is in progress")
+ assert "mcp-sentinel" not in str(caught.value)
+ assert raise_for_status_field({"job_id": "j", "status": "queued"})["job_id"] == "j"
+
+
+def test_tool_guidance_survives_the_scrub():
+ hint = "Load one with load_model(kind='image') first, then retry POST /v1/images/generations."
+ message = _message(_response(409, {"detail": f"No model at {SENTINEL}"}), hints = {409: hint})
+ assert message == f"No model at <path> (HTTP 409) {hint}"
+ assert hint not in _message(_response(500, {"detail": "boom"}), hints = {409: hint})
+ # gpu_busy keeps its retry hint instead of the tool's guidance.
+ busy = _response(
+ 409,
+ {"error": "gpu_busy", "message": "Another account is generating.", "retry_after": 3},
+ headers = {"Retry-After": "3"},
+ )
+ assert _message(busy, hints = {409: "x"}) == f"{BUSY_OUT}. Retry after 3 s."
+
+
+def test_a_routes_own_call_this_route_hint_is_dropped():
+ error = tool_error("No model loaded. Call POST /inference/load first.", "Load a chat model.")
+ assert str(error) == "No model loaded. Load a chat model."
+ # A path outside a route hint is scrubbed, not dropped.
+ assert str(tool_error("Saved to /srv/mcp-sentinel/x.png")) == "Saved to <path>"
diff --git a/studio/backend/tests/test_mcp_forward.py b/studio/backend/tests/test_mcp_forward.py
new file mode 100644
index 00000000000..c1930e69bbc
--- /dev/null
+++ b/studio/backend/tests/test_mcp_forward.py
@@ -0,0 +1,271 @@
+# 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 asyncio
+
+import httpx
+import pytest
+from fastapi import Depends, Request
+from fastapi.testclient import TestClient
+from fastmcp import FastMCP
+
+from auth import storage
+from auth.authentication import get_current_subject
+from studio_mcp.caller import current_caller
+from studio_mcp.forward import FORWARD_BASE_URL, checked_path, forward, ndjson_last, parse_json
+from utils import keyless_api_access
+from utils.account_context import AccountContext, bind_account, current_account, reset_account
+from utils.client_ip import client_ip, is_direct_local_request
+
+from .mcp_harness import (
+ call_tool,
+ fake_studio,
+ isolated_auth, # noqa: F401 (fixture)
+ make_caller,
+ owner_auth, # noqa: F401 (fixture)
+ served,
+)
+
+PROBE_PATH = "/api/inference/__mcp_forward_probe"
+
+
+def studio_with_probe(monkeypatch, owner_auth):
+ import main
+
+ app = main.app
+
+ async def probe(request: Request, subject: str = Depends(get_current_subject)):
+ return {
+ "subject": subject,
+ "account": current_account().account_id,
+ "client_ip": client_ip(request),
+ "is_direct_local_request": is_direct_local_request(request),
+ "keyless_request_allowed": keyless_api_access.keyless_request_allowed(request),
+ "headers": {
+ name: value for name, value in request.headers.items() if name != "authorization"
+ },
+ }
+
+ app.add_api_route(PROBE_PATH, probe, methods = ["GET"])
+ routes = app.router.routes
+ routes.insert(0, routes.pop())
+ app.middleware_stack = None
+ for name, value in {
+ "bind_host": "127.0.0.1",
+ "secure": False,
+ "remote_access_is_colab": False,
+ "lan_access_is_colab": False,
+ "lan_access_secure_launch": False,
+ "cloudflare_url": None,
+ }.items():
+ monkeypatch.setattr(app.state, name, value, raising = False)
+ keyless_api_access.set_keyless_api_access("full", tools = True)
+ yield app
+ app.router.routes[:] = [r for r in app.router.routes if getattr(r, "path", None) != PROBE_PATH]
+ app.middleware_stack = None
+
+
+def test_keyless_full_on_loopback_still_works_for_a_direct_caller(studio_with_probe):
+ local = TestClient(
+ studio_with_probe, base_url = "http://127.0.0.1:8888", client = ("127.0.0.1", 50000)
+ )
+ response = local.get(PROBE_PATH)
+ assert response.status_code == 200, response.text
+ assert response.json()["keyless_request_allowed"] is True
+
+
[email protected]("token", ["", "not-needed", "lm-studio", "ollama", "no-key-required"])
+def test_a_forwarded_call_cannot_use_keyless(studio_with_probe, token):
+ response = asyncio.run(
+ forward(make_caller(studio_app = studio_with_probe, token = token), "GET", PROBE_PATH)
+ )
+ assert response.status_code == 401
+
+
+def test_a_forwarded_call_is_remote_keyed_and_leaves_the_tools_account_alone(studio_with_probe):
+ raw_key, _row = storage.create_api_key(storage.DEFAULT_ADMIN_USERNAME, name = "agent")
+ sentinel = AccountContext("sentinel-account", "sentinel")
+
+ async def run():
+ token = bind_account(sentinel)
+ try:
+ caller = make_caller(studio_app = studio_with_probe, token = raw_key)
+ return await forward(caller, "GET", PROBE_PATH), current_account()
+ finally:
+ reset_account(token)
+
+ response, after = asyncio.run(run())
+ assert response.status_code == 200, response.text
+ seen = response.json()
+ assert seen["subject"] == storage.DEFAULT_ADMIN_USERNAME
+ assert seen["account"] == "owner"
+ assert seen["client_ip"] == "192.0.2.1"
+ assert seen["is_direct_local_request"] is False
+ assert seen["keyless_request_allowed"] is False
+ assert seen["headers"]["host"] == "unsloth-mcp.invalid"
+ assert after == sentinel
+
+
+def _echo_server(monkeypatch, routes = None):
+ studio = fake_studio(
+ {
+ ("GET", "/api/inference/echo"): lambda request, body: {"ok": True},
+ ("POST", "/v1/audio/inputs"): lambda request, body: {"size": len(body)},
+ **(routes or {}),
+ }
+ )
+ mcp = FastMCP("probe")
+
+ @mcp.tool
+ async def echo(hub: bool = False) -> dict:
+ response = await forward(current_caller(), "GET", "/api/inference/echo", hub_header = hub)
+ return {"status": response.status_code}
+
+ @mcp.tool
+ async def upload(size: int) -> dict:
+ response = await forward(
+ current_caller(),
+ "POST",
+ "/v1/audio/inputs",
+ params = {"name": "a.wav"},
+ content = b"x" * size,
+ )
+ return response.json()
+
+ return studio, served(mcp, studio, monkeypatch = monkeypatch)
+
+
+def test_only_the_key_and_an_opted_in_hub_token_are_forwarded(monkeypatch):
+ studio, app = _echo_server(monkeypatch)
+ inbound = {
+ "CF-Connecting-IP": "127.0.0.1",
+ "Cookie": "session=abc",
+ "X-Forwarded-For": "127.0.0.1",
+ "X-Unsloth-HF-Token": "hf_secret",
+ "X-Custom": "1",
+ }
+ with TestClient(app, base_url = "http://127.0.0.1:8888", client = ("127.0.0.1", 50000)) as http:
+ assert call_tool(http, "echo", headers = inbound)["structuredContent"] == {"status": 200}
+ call_tool(http, "echo", {"hub": True}, headers = {"X-Unsloth-HF-Token": "hf_secret"})
+ call_tool(http, "echo", {"hub": True})
+ (_method, path, headers, _body), with_hub, without_hub = studio.state.calls
+ assert path == "/api/inference/echo"
+ assert headers["authorization"] == "Bearer sk-unsloth-test"
+ assert headers["host"] == "unsloth-mcp.invalid"
+ for name in ("cf-connecting-ip", "cookie", "x-forwarded-for", "x-custom", "x-unsloth-hf-token"):
+ assert name not in headers
+ assert with_hub[2]["x-unsloth-hf-token"] == "hf_secret"
+ assert "x-unsloth-hf-token" not in without_hub[2]
+
+
+def test_a_bytes_upload_carries_content_length(monkeypatch):
+ studio, app = _echo_server(monkeypatch)
+ with TestClient(app) as http:
+ result = call_tool(http, "upload", {"size": 4096})
+ assert result["structuredContent"] == {"size": 4096}
+ (_method, path, headers, body) = studio.state.calls[-1]
+ assert path == "/v1/audio/inputs"
+ assert headers["content-length"] == "4096"
+ assert "transfer-encoding" not in headers
+ assert len(body) == 4096
+
+
+def test_a_streamed_upload_is_refused():
+ caller = make_caller(studio_app = None)
+
+ async def chunks():
+ yield b"x"
+
+ with pytest.raises(TypeError):
+ asyncio.run(forward(caller, "POST", "/v1/audio/inputs", content = chunks()))
+
+
+ "path",
+ [
+ "/api/auth/api-keys",
+ "/api/settings/sandbox",
+ "/api/settings/mcp-access",
+ "/api/hub/token",
+ "/mcp/",
+ "/v1/../api/auth/api-keys",
+ "/api/inference/../../api/auth/api-keys",
+ "/v1/videos/%2e%2e/%2e%2e/api/auth/api-keys",
+ "/api/inference",
+ ],
+)
+def test_a_path_outside_the_allowlist_raises(path):
+ caller = make_caller(studio_app = None)
+ with pytest.raises(RuntimeError):
+ asyncio.run(forward(caller, "GET", path))
+
+
+ "path",
+ [
+ "/v1/models",
+ "/api/inference/status",
+ "/api/hub/gguf-variants",
+ "/api/settings/embedding-model",
+ ],
+)
+def test_allowlisted_paths_pass_the_check(path):
+ assert checked_path(httpx.URL(FORWARD_BASE_URL + path)) == path
+
+
+def test_padded_bodies_parse():
+ assert parse_json(b' \n {"loaded": true}') == {"loaded": True}
+ assert parse_json(b'{"a": 1} ') == {"a": 1}
+ assert ndjson_last(b'{"type":"progress"}\n{"type":"done","text":"hi"}\n\n') == {
+ "type": "done",
+ "text": "hi",
+ }
+ with pytest.raises(ValueError):
+ ndjson_last(b"\n \n")
+
+
+def test_cancelling_the_tool_cancels_the_forwarded_call():
+ state = {}
+
+ async def run():
+ started = asyncio.Event()
+
+ async def hang(request, body):
+ started.set()
+ try:
+ await asyncio.sleep(3600)
+ except asyncio.CancelledError:
+ state["route_cancelled"] = True
+ raise
+
+ studio = fake_studio({("GET", "/api/inference/hang"): hang})
+ tool = asyncio.create_task(
+ forward(make_caller(studio_app = studio), "GET", "/api/inference/hang")
+ )
+ await asyncio.wait_for(started.wait(), 10)
+ tool.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await tool
+ await asyncio.sleep(0)
+
+ asyncio.run(run())
+ assert state == {"route_cancelled": True}
+
+
+def test_concurrent_calls_under_different_keys_keep_their_own_account(studio_with_probe):
+ owner_key, _row = storage.create_api_key(storage.DEFAULT_ADMIN_USERNAME, name = "owner-agent")
+ alice = storage.issue_account_setup_code(username = "alice")["account"]["account_id"]
+ alice_key, _row = storage.create_api_key("alice", name = "alice-agent", account_id = alice)
+
+ async def run():
+ calls = [
+ forward(make_caller(studio_app = studio_with_probe, token = key), "GET", PROBE_PATH)
+ for key in (owner_key, alice_key) * 4
+ ]
+ responses = await asyncio.gather(*calls)
+ return [response.json()["account"] for response in responses], current_account()
+
+ accounts, after = asyncio.run(run())
+ assert accounts == ["owner", alice] * 4
+ assert after.account_id == "owner"
diff --git a/studio/backend/tests/test_mcp_gate.py b/studio/backend/tests/test_mcp_gate.py
new file mode 100644
index 00000000000..d69dc81c9a4
--- /dev/null
+++ b/studio/backend/tests/test_mcp_gate.py
@@ -0,0 +1,540 @@
+# 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 asyncio
+import json
+import os
+import sqlite3
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from starlette.applications import Starlette
+from starlette.routing import Mount
+
+from fastmcp import FastMCP
+
+from auth import storage
+from auth.authentication import create_access_token
+from mcp_server import create_studio_mcp
+from studio_mcp.caller import current_caller
+from studio_mcp.gate import MAX_REQUEST_BYTES, NEED_KEY, TOO_LARGE, StudioMcpGate
+from utils.account_context import AccountContext, bind_account, current_account, reset_account
+from utils.keyless_api_access import APPROVED_DUMMY_BEARERS, KEYLESS_SCOPES, set_keyless_api_access
+from utils.mcp_access import ENV_FORCE, set_mcp_enabled
+
+from .mcp_harness import LOCAL, MCP_HEADERS, REMOTE, isolated_auth, seed_owner # noqa: F401 (fixture)
+
+LISTING = {"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}
+# Every tool call here asks the probe's one tool, whoami, which takes no arguments.
+WHOAMI = {**LISTING, "id": 7, "method": "tools/call", "params": {"name": "whoami", "arguments": {}}}
+pytestmark = pytest.mark.usefixtures("isolated_auth")
+
+
+def owner_key(**kwargs):
+ return storage.create_api_key(storage.DEFAULT_ADMIN_USERNAME, name = "agent", **kwargs)
+
+
+def live_key():
+ """The owner's API key, with the switch on."""
+ seed_owner()
+ raw_key, _row = owner_key()
+ set_mcp_enabled(True)
+ return raw_key
+
+
+def probe_mcp():
+ mcp = FastMCP("probe")
+
+ @mcp.tool
+ async def whoami() -> dict:
+ caller = current_caller()
+ return {
+ "token": caller.token,
+ "account_id": caller.account_id,
+ "direct_local": caller.direct_local,
+ "public_base": caller.public_base,
+ "hf_token": caller.hf_token,
+ "has_studio_app": caller.studio_app is not None,
+ "bound_account": current_account().account_id,
+ }
+
+ return mcp
+
+
+def served(mcp, **state):
+ mcp_app = mcp.http_app(path = "/", stateless_http = True)
+ app = Starlette(routes = [Mount("/mcp", StudioMcpGate(mcp_app))], lifespan = mcp_app.lifespan)
+ for name, value in {"server_port": 8888, "cloudflare_url": None, **state}.items():
+ setattr(app.state, name, value)
+ return app
+
+
+def call_tool(http, headers):
+ response = http.post("/mcp/", json = WHOAMI, headers = {**MCP_HEADERS, **headers})
+ if response.status_code != 200:
+ return response, None
+ data = [line[5:].strip() for line in response.text.splitlines() if line.startswith("data:")]
+ return response, json.loads(data[-1])["result"]["structuredContent"]
+
+
+def bearer(token):
+ return {"Authorization": f"Bearer {token}"}
+
+
+def studio():
+ from main import app
+ return TestClient(app)
+
+
+def key_spy(monkeypatch):
+ calls = []
+ real = storage.validate_api_key_account
+
+ def spy(*args, **kwargs):
+ calls.append(kwargs)
+ return real(*args, **kwargs)
+
+ monkeypatch.setattr(storage, "validate_api_key_account", spy)
+ return calls
+
+
[email protected]("method", ["GET", "POST", "PUT", "DELETE", "PATCH"])
[email protected]("path", ["/mcp/", "/mcp/x"])
[email protected]("authorization", [None, "Bearer sk-unsloth-0123456789abcdef", "Bearer x"])
[email protected]("origin", [None, "https://evil.example"])
+def test_off_is_a_plain_404_before_any_auth(studio, key_spy, method, path, authorization, origin):
+ headers = {**MCP_HEADERS, **({"Authorization": authorization} if authorization else {})}
+ if origin:
+ headers["Origin"] = origin
+ response = studio.request(method, path, json = LISTING, headers = headers)
+ assert response.status_code == 404
+ assert response.json() == {"detail": "Not Found"}
+ assert "www-authenticate" not in response.headers
+ assert key_spy == []
+
+
[email protected]("enabled", [False, True])
+def test_decisions_keeps_its_redirect_and_its_own_auth(studio, enabled):
+ if enabled:
+ set_mcp_enabled(True)
+ for method in ("GET", "POST"):
+ response = studio.request(method, "/mcp/decisions?x=1", follow_redirects = False)
+ assert response.status_code == 307
+ assert response.headers["location"] == "http://testserver/mcp/decisions/?x=1"
+ response = studio.post("/mcp/decisions/", json = LISTING, headers = MCP_HEADERS)
+ assert response.status_code == 401
+
+
[email protected]("by_env", [False, True])
+def test_on_without_a_key_refuses_everyone(studio, monkeypatch, by_env):
+ if by_env:
+ monkeypatch.setenv(ENV_FORCE, "1")
+ else:
+ set_mcp_enabled(True)
+ response = studio.post("/mcp/", json = LISTING, headers = {**MCP_HEADERS, **bearer("anything")})
+ assert response.status_code == 401
+
+
+def test_the_switch_flips_live_without_a_restart(studio):
+ assert studio.post("/mcp/", json = LISTING, headers = MCP_HEADERS).status_code == 404
+ set_mcp_enabled(True)
+ assert studio.post("/mcp/", json = LISTING, headers = MCP_HEADERS).status_code == 401
+ set_mcp_enabled(False)
+ assert studio.post("/mcp/", json = LISTING, headers = MCP_HEADERS).status_code == 404
+
+
+def _run_gate(
+ scope,
+ inner = None,
+ receive = None,
+):
+ events = []
+
+ async def record(scope, receive, send):
+ events.append("app")
+
+ async def send(message):
+ events.append(message)
+
+ async def run():
+ await StudioMcpGate(inner or record)(scope, receive, send)
+ return current_account()
+
+ return events, asyncio.run(run())
+
+
+ "scope,events",
+ [
+ ({"type": "lifespan"}, ["app"]),
+ (
+ {"type": "websocket", "path": "/mcp/", "root_path": "/mcp", "headers": []},
+ [{"type": "websocket.close", "code": 4404}],
+ ),
+ ],
+)
+def test_lifespan_passes_through_and_a_websocket_is_closed(scope, events):
+ set_mcp_enabled(True)
+ assert _run_gate(scope)[0] == events
+
+
+def test_the_mcp_app_is_stateless_and_streams(live_key):
+ headers = {**MCP_HEADERS, **bearer(live_key)}
+ with TestClient(served(create_studio_mcp())) as http:
+ first = http.post("/mcp/", json = LISTING, headers = headers)
+ second = http.post("/mcp/", json = {**LISTING, "id": 2}, headers = headers)
+ for response in (first, second):
+ assert response.status_code == 200, response.text
+ assert "mcp-session-id" not in response.headers
+ assert response.headers["content-type"].startswith("text/event-stream")
+ assert '"tools"' in response.text
+
+
+KEYLESS_BEARERS = [
+ None,
+ "Bearer ",
+ "Bearer",
+ *(f"Bearer {dummy}" for dummy in sorted(APPROVED_DUMMY_BEARERS)),
+]
+
+
[email protected]("scope", KEYLESS_SCOPES)
[email protected]("authorization", KEYLESS_BEARERS)
+def test_keyless_is_never_admitted(scope, authorization):
+ seed_owner()
+ set_keyless_api_access(scope, tools = scope != "off")
+ set_mcp_enabled(True)
+ headers = {"Authorization": authorization} if authorization is not None else {}
+ with TestClient(served(probe_mcp()), **LOCAL) as http:
+ response, result = call_tool(http, headers)
+ assert response.status_code == 401
+ assert response.json() == {"detail": NEED_KEY}
+ assert response.headers["www-authenticate"] == "Bearer"
+ assert "resource_metadata" not in response.text
+ assert result is None
+
+
+ "authorization",
+ [
+ lambda: "Basic dXNlcjpwYXNz",
+ lambda: "Token sk-unsloth-x",
+ lambda: "Bearer not-a-key",
+ lambda: f"Bearer {create_access_token(subject = storage.DEFAULT_ADMIN_USERNAME)}",
+ ],
+ ids = ["basic", "token-scheme", "non-key", "ui-session-jwt"],
+)
+def test_other_schemes_and_non_keys_need_a_key(authorization):
+ seed_owner()
+ set_mcp_enabled(True)
+ with TestClient(served(probe_mcp())) as http:
+ response, _result = call_tool(http, {"Authorization": authorization()})
+ assert response.status_code == 401
+ assert response.json() == {"detail": NEED_KEY}
+
+
+def test_a_valid_key_passes_and_a_revoked_one_does_not():
+ seed_owner()
+ raw_key, row = owner_key()
+ set_mcp_enabled(True)
+ with TestClient(served(probe_mcp())) as http:
+ response, result = call_tool(http, bearer(raw_key))
+ assert response.status_code == 200, response.text
+ assert result["token"] == raw_key
+ assert result["account_id"] == storage.get_user_record("unsloth")["account_id"]
+ assert storage.revoke_api_key(storage.DEFAULT_ADMIN_USERNAME, row["id"])
+ storage._reset_api_key_hash_cache()
+ revoked, _result = call_tool(http, bearer(raw_key))
+ assert revoked.status_code == 401
+ assert revoked.json() == {"detail": "Invalid or expired API key"}
+
+
+ "workflow,detail",
+ [(False, "Invalid or expired API key"), (True, "Workflow keys cannot use Unsloth Studio MCP")],
+)
+def test_an_unknown_or_workflow_key_is_refused(workflow, detail):
+ seed_owner()
+ raw_key = owner_key(internal = True)[0] if workflow else "sk-unsloth-" + "0" * 32
+ set_mcp_enabled(True)
+ with TestClient(served(probe_mcp())) as http:
+ response, _result = call_tool(http, bearer(raw_key))
+ assert response.status_code == 401
+ assert response.json() == {"detail": detail}
+
+
+def test_a_managed_account_key_carries_its_account_but_never_reads_host_files():
+ seed_owner()
+ alice = storage.issue_account_setup_code(username = "alice")["account"]["account_id"]
+ raw_key, _row = storage.create_api_key("alice", name = "agent", account_id = alice)
+ set_mcp_enabled(True)
+ with TestClient(served(probe_mcp()), **LOCAL) as http:
+ response, result = call_tool(http, bearer(raw_key))
+ assert response.status_code == 200, response.text
+ assert result["account_id"] == alice
+ # Even from loopback; and the gate only validates, the forwarded route call binds the account.
+ assert result["direct_local"] is False
+ assert result["bound_account"] == "owner"
+
+
+ "authorization,detail",
+ [
+ (lambda key: [f"Bearer {key}".encode()] * 2, "Send one Authorization header"),
+ (lambda key: [b"Bearer \xff\xff"], NEED_KEY),
+ ],
+ ids = ["two-headers", "non-ascii"],
+)
+def test_a_malformed_authorization_header_is_a_clean_401(
+ live_key, monkeypatch, authorization, detail
+):
+ monkeypatch.setenv("UNSLOTH_STUDIO_MCP_TOKEN", "static-token")
+ headers = [("accept", MCP_HEADERS["Accept"])]
+ headers += [("authorization", value) for value in authorization(live_key)]
+ with TestClient(served(probe_mcp())) as http:
+ response = http.post("/mcp/", json = LISTING, headers = headers)
+ assert response.status_code == 401
+ assert response.json() == {"detail": detail}
+
+
+def test_the_gate_validates_without_touching_last_used(key_spy):
+ seed_owner()
+ raw_key, row = owner_key()
+ set_mcp_enabled(True)
+ with TestClient(served(probe_mcp())) as http:
+ response, _result = call_tool(http, bearer(raw_key))
+ assert response.status_code == 200, response.text
+ assert key_spy == [{"touch": False}]
+ conn = sqlite3.connect(storage.DB_PATH)
+ try:
+ last_used = conn.execute(
+ "SELECT last_used_at FROM api_keys WHERE id = ?", (row["id"],)
+ ).fetchone()[0]
+ finally:
+ conn.close()
+ assert last_used is None
+
+
+def test_the_gate_never_binds_an_account(live_key):
+ sentinel = AccountContext("sentinel-account", "sentinel")
+ seen = []
+
+ async def inner(scope, receive, send):
+ seen.append(current_account())
+ await send({"type": "http.response.start", "status": 204, "headers": []})
+ await send({"type": "http.response.body", "body": b""})
+
+ async def receive():
+ return {"type": "http.request", "body": b"", "more_body": False}
+
+ scope = {
+ "type": "http",
+ "method": "POST",
+ "path": "/mcp/",
+ "root_path": "/mcp",
+ "scheme": "http",
+ "query_string": b"",
+ "server": ("127.0.0.1", 8888),
+ "client": ("127.0.0.1", 50000),
+ "headers": [
+ (b"host", b"127.0.0.1:8888"),
+ (b"authorization", f"Bearer {live_key}".encode()),
+ ],
+ }
+ token = bind_account(sentinel)
+ try:
+ sent, after = _run_gate(scope, inner, receive)
+ finally:
+ reset_account(token)
+ assert sent[0]["status"] == 204
+ assert seen == [sentinel]
+ assert after == sentinel
+
+
+def test_tools_see_the_outer_request(live_key):
+ with TestClient(served(probe_mcp()), **LOCAL) as http:
+ _response, local = call_tool(http, {**bearer(live_key), "X-Unsloth-HF-Token": " hf_abc "})
+ with TestClient(served(probe_mcp()), **REMOTE) as http:
+ _response, remote = call_tool(http, bearer(live_key))
+ assert local["direct_local"] is True
+ assert local["public_base"] == "http://127.0.0.1:8888"
+ assert local["hf_token"] == "hf_abc"
+ assert local["has_studio_app"] is True
+ assert remote["direct_local"] is False
+ assert remote["public_base"] == "http://192.168.1.20:8888"
+ assert remote["hf_token"] is None
+
+
+def test_a_root_path_carries_into_the_public_base(live_key):
+ # The client's base URL carries the prefix, so call_tool's /mcp/ goes to /studio/mcp/.
+ client = {**LOCAL, "base_url": "http://127.0.0.1:8888/studio"}
+ with TestClient(served(probe_mcp()), root_path = "/studio", **client) as http:
+ response, result = call_tool(http, bearer(live_key))
+ assert response.status_code == 200
+ assert result["public_base"] == "http://127.0.0.1:8888/studio"
+
+
+def test_an_oversized_hf_token_is_refused(live_key):
+ with TestClient(served(probe_mcp())) as http:
+ response, _result = call_tool(http, {**bearer(live_key), "X-Unsloth-HF-Token": "h" * 513})
+ assert response.status_code == 400
+
+
+def _padded_call(pad):
+ body = {**WHOAMI, "params": {**WHOAMI["params"], "_meta": {"pad": "x" * pad}}}
+ return json.dumps(body).encode()
+
+
[email protected]("chunked", [False, True])
[email protected]("over", [True, False])
+def test_a_request_over_4_mib_is_refused_and_one_under_reaches_the_tool(live_key, chunked, over):
+ payload = _padded_call(MAX_REQUEST_BYTES if over else MAX_REQUEST_BYTES - 4096)
+ assert (len(payload) > MAX_REQUEST_BYTES) is over
+ content = (
+ (payload[i : i + 65536] for i in range(0, len(payload), 65536)) if chunked else payload
+ )
+ with TestClient(served(probe_mcp())) as http:
+ response = http.post(
+ "/mcp/",
+ content = content,
+ headers = {**MCP_HEADERS, **bearer(live_key), "Content-Type": "application/json"},
+ )
+ if over:
+ assert response.status_code == 413
+ assert response.json() == {"detail": TOO_LARGE}
+ else:
+ assert response.status_code == 200
+ assert '"isError":false' in response.text.replace(" ", "")
+
+
+def test_current_caller_outside_the_gate_is_an_error():
+ with pytest.raises(RuntimeError):
+ current_caller()
+
+
+def test_the_static_token_is_retired(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_MCP_TOKEN", "static-token")
+ set_mcp_enabled(True)
+ with TestClient(served(create_studio_mcp())) as http:
+ response = http.post(
+ "/mcp/", json = LISTING, headers = {**MCP_HEADERS, **bearer("static-token")}
+ )
+ assert response.status_code == 401
+ assert response.json() == {
+ "detail": "The MCP static token is no longer supported; use an Unsloth Studio API key (sk-unsloth-…)"
+ }
+ assert response.headers["www-authenticate"] == "Bearer"
+
+
+def _import_main(extra_env):
+ env = {
+ name: value
+ for name, value in os.environ.items()
+ if name not in ("UNSLOTH_STUDIO_ENABLE_MCP", "UNSLOTH_STUDIO_MCP_TOKEN")
+ }
+ env.update(extra_env)
+ return subprocess.run(
+ [sys.executable, "-c", "import main"],
+ cwd = Path(__file__).resolve().parent.parent,
+ env = env,
+ capture_output = True,
+ text = True,
+ timeout = 600,
+ )
+
+
[email protected]("token,warnings", [(None, 0), ("legacy", 1)])
+def test_enabling_by_env_starts_and_a_leftover_static_token_logs_one_warning(token, warnings):
+ env = {"UNSLOTH_STUDIO_ENABLE_MCP": "1"}
+ if token:
+ env["UNSLOTH_STUDIO_MCP_TOKEN"] = token
+ result = _import_main(env)
+ assert result.returncode == 0, result.stderr[-2000:]
+ output = (result.stdout + result.stderr).splitlines()
+ lines = [line for line in output if "UNSLOTH_STUDIO_MCP_TOKEN" in line]
+ assert len(lines) == warnings, lines
+ assert all(json.loads(line)["level"] == "warning" for line in lines)
+
+
+TUNNEL = "https://abc-def.trycloudflare.com"
+
+
+ "base_url,origin,allowed",
+ [
+ ("http://127.0.0.1:8888", None, True),
+ ("http://127.0.0.1:8888", "http://localhost:8888", True),
+ ("http://127.0.0.1:8888", "http://127.0.0.1:8888", True),
+ ("http://127.0.0.1:8888", "http://[::1]:8888", True),
+ ("http://192.168.1.20:8888", "http://192.168.1.20:8888", True),
+ (TUNNEL, TUNNEL, True),
+ ("http://127.0.0.1:8888", "tauri://localhost", True),
+ ("http://127.0.0.1:8888", "http://tauri.localhost", True),
+ ("http://127.0.0.1:8888", "https://evil.example", False),
+ ("http://evil.example:8888", "http://evil.example:8888", False),
+ ("http://127.0.0.1:8888", "null", False),
+ ("http://127.0.0.1:8888", "http://localhost:3000", False),
+ ],
+)
+def test_origin_allowlist(key_spy, base_url, origin, allowed, live_key):
+ headers = {**bearer(live_key), **({"Origin": origin} if origin else {})}
+ with TestClient(served(probe_mcp(), cloudflare_url = TUNNEL), base_url = base_url) as http:
+ response, _result = call_tool(http, headers)
+ if allowed:
+ assert response.status_code == 200, response.text
+ else:
+ assert response.status_code == 403
+ assert response.json() == {"detail": "Origin not allowed for Unsloth Studio MCP"}
+ assert key_spy == []
+
+
+ "headers",
+ [
+ # No key at all: the origin refusal comes before the missing-key 401.
+ [("origin", "https://evil.example")],
+ [
+ ("authorization", "Bearer {key}"),
+ ("origin", "http://127.0.0.1:8888"),
+ ("origin", "https://evil.example"),
+ ],
+ ],
+ ids = ["foreign-before-auth", "two-origins"],
+)
+def test_a_foreign_or_doubled_origin_is_a_403(live_key, headers):
+ sent = [("accept", MCP_HEADERS["Accept"])]
+ sent += [(name, value.format(key = live_key)) for name, value in headers]
+ with TestClient(served(probe_mcp()), base_url = "http://127.0.0.1:8888") as http:
+ response = http.post("/mcp/", json = LISTING, headers = sent)
+ assert response.status_code == 403
+
+
+ "path",
+ [
+ "/.well-known/oauth-protected-resource",
+ "/.well-known/oauth-protected-resource/mcp/",
+ "/.well-known/oauth-authorization-server",
+ "/.well-known/oauth-authorization-server/mcp",
+ ],
+)
+def test_oauth_discovery_is_a_404_not_the_app_shell(tmp_path, path):
+ import main
+
+ (tmp_path / "index.html").write_text("<!doctype html><title>studio</title>")
+ app = FastAPI()
+ assert main.setup_frontend(app, tmp_path)
+ client = TestClient(app, base_url = "http://127.0.0.1:8888", client = ("127.0.0.1", 40000))
+ response = client.get(path)
+ assert response.status_code == 404
+ assert response.json() == {"detail": "Not Found"}
+ root = client.get("/")
+ assert root.status_code == 200
+ assert "<title>studio</title>" in root.text
diff --git a/studio/backend/tests/test_mcp_no_host_paths.py b/studio/backend/tests/test_mcp_no_host_paths.py
new file mode 100644
index 00000000000..18df04bace3
--- /dev/null
+++ b/studio/backend/tests/test_mcp_no_host_paths.py
@@ -0,0 +1,214 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""No MCP tool may hand a host path to the agent. Every tool gets a case here: the fake Studio answers each route with its payload poisoned by sentinel paths, and nothing the tool returns may contain one."""
+
+import asyncio
+import json
+from typing import Any, Optional
+
+import pytest
+from fastapi.responses import JSONResponse
+from fastapi.testclient import TestClient
+from fastmcp import FastMCP
+from pydantic import ValidationError
+
+from hub.utils.host_paths import response_leaks_host_path
+from mcp_server import create_studio_mcp
+from studio_mcp.caller import current_caller
+from studio_mcp.errors import raise_for_route
+from studio_mcp.forward import forward
+from studio_mcp.outputs import RouteText, ToolOutput
+
+from .mcp_harness import (
+ OUT,
+ RUN_CHECKPOINTS,
+ SENTINEL_ROOTS,
+ WAV_INPUT,
+ call_tool,
+ fake_studio,
+ poison,
+ served,
+)
+from .test_mcp_tools_audio import PAYLOADS as AUDIO_PAYLOADS
+from .test_mcp_tools_audio import TRANSCRIPT, VERBOSE
+from .test_mcp_tools_cancel import PAYLOADS as CANCEL_PAYLOADS
+from .test_mcp_tools_datasets import PAYLOADS as DATASETS_PAYLOADS
+from .test_mcp_tools_images import PAYLOADS as IMAGES_PAYLOADS
+from .test_mcp_tools_loading import PAYLOADS as LOADING_PAYLOADS
+from .test_mcp_tools_models import PAYLOADS as MODELS_PAYLOADS
+from .test_mcp_tools_recipe import PAYLOADS as RECIPE_PAYLOADS
+from .test_mcp_tools_status import PAYLOADS as STATUS_PAYLOADS
+from .test_mcp_tools_text import PAYLOADS as TEXT_PAYLOADS
+from .test_mcp_tools_training import PAYLOADS as TRAINING_PAYLOADS
+from .test_mcp_tools_training import RUN_PAYLOADS
+from .test_mcp_tools_video import PAYLOADS as VIDEO_PAYLOADS
+
+TRANSCRIBE_PAYLOADS = {
+ ("POST", "/v1/audio/transcriptions"): VERBOSE,
+ ("POST", "/v1/audio/translations"): TRANSCRIPT,
+}
+EXPORT_PAYLOADS = {
+ ("GET", "/api/models/checkpoints"): {
+ **RUN_CHECKPOINTS,
+ "models": RUN_CHECKPOINTS["models"][:1],
+ },
+ ("GET", "/api/export/status"): {
+ "last_op_seq": 1,
+ "current_checkpoint": f"{OUT}/qwen-lora",
+ "last_op_output_path": f"{OUT}/x",
+ },
+ ("POST", "/api/export/load-checkpoint"): {
+ "success": True,
+ "message": f"Loaded {OUT}/qwen-lora",
+ },
+ ("POST", "/api/export/export/gguf"): {"success": True, "message": f"Saved to {OUT}/x"},
+}
+
+# tool name -> (fake Studio routes, tool arguments), or a list of them
+CASES: dict[str, Any] = {
+ "studio_status": (STATUS_PAYLOADS, {}),
+ "list_models": (MODELS_PAYLOADS, {"model": "unsloth/Qwen3-0.6B"}),
+ "load_model": (LOADING_PAYLOADS, {"model": "unsloth/Llama-3.2-1B-Instruct-GGUF"}),
+ "unload_model": (LOADING_PAYLOADS, {}),
+ "chat": (TEXT_PAYLOADS, {"prompt": "hi"}),
+ "embed": (TEXT_PAYLOADS, {"texts": ["a", "b"]}),
+ "system_one": (TEXT_PAYLOADS, {"state": "x", "questions": {"urgent": {"type": "noul"}}}),
+ "generate_image": (IMAGES_PAYLOADS, {"prompt": "a red fox"}),
+ "generate_video": (VIDEO_PAYLOADS, {"prompt": "waves"}),
+ "get_job": [
+ (VIDEO_PAYLOADS, {"kind": "video"}),
+ (VIDEO_PAYLOADS, {"kind": "video", "id": "video-1"}),
+ (RECIPE_PAYLOADS, {"kind": "recipe", "id": "job-1", "rows": 2}),
+ ],
+ "start_training": [
+ (TRAINING_PAYLOADS, {"config": {"model_name": "m"}}),
+ (TRAINING_PAYLOADS, {"config": {"base_model": "m", "data_dir": "d"}, "kind": "diffusion"}),
+ ],
+ "list_training_runs": (RUN_PAYLOADS, {"run_id": "run-1", "include_checkpoints": True}),
+ "export_model": [
+ (EXPORT_PAYLOADS, {"checkpoint": "qwen-lora", "format": "gguf", "save_directory": "out"}),
+ (EXPORT_PAYLOADS, {"checkpoint": "missing", "format": "gguf", "save_directory": "out"}),
+ ],
+ "cancel": [
+ (CANCEL_PAYLOADS, {"kind": "training"}),
+ (CANCEL_PAYLOADS, {"kind": "recipe", "id": "rec-1"}),
+ ],
+ "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"}),
+ ],
+ "transcribe": (TRANSCRIBE_PAYLOADS, {"audio": WAV_INPUT, "timestamps": True, "language": "en"}),
+ "generate_audio": (AUDIO_PAYLOADS, {"workflow": "clone", "text": "hi", "reference": WAV_INPUT}),
+}
+
+# Output keys that carry model-written text, which is the model's to say and is never rewritten.
+MODEL_TEXT = {"chat": {"text"}, "transcribe": {"text"}, "get_job": {"data_rows"}}
+
+
+def leaks(result: dict, ignore: frozenset = frozenset()) -> Optional[str]:
+ payloads = [result.get("structuredContent")]
+ for item in result.get("content") or []:
+ if item.get("type") == "text":
+ try:
+ payloads.append(json.loads(item["text"]))
+ except ValueError:
+ payloads.append(item["text"])
+ for payload in payloads:
+ found = response_leaks_host_path(payload, roots = SENTINEL_ROOTS, ignore = ignore)
+ if found is not None:
+ return found
+ return None
+
+
+def run_case(monkeypatch, mcp, name: str, routes: dict, args: dict) -> dict:
+ with TestClient(served(mcp, fake_studio(poison(routes)), monkeypatch = monkeypatch)) as http:
+ return call_tool(http, name, args)
+
+
+def test_every_registered_tool_has_a_host_path_case():
+ names = {tool.name for tool in asyncio.run(create_studio_mcp().list_tools())}
+ assert set(MODEL_TEXT) <= set(CASES) == names
+ assert len(names) == 18
+
+
[email protected]("name", sorted(CASES))
+def test_no_host_path_in_tool_output(monkeypatch, name):
+ cases = CASES[name] if isinstance(CASES[name], list) else [CASES[name]]
+ for routes, args in cases:
+ result = run_case(monkeypatch, create_studio_mcp(), name, routes, args)
+ assert leaks(result, frozenset(MODEL_TEXT.get(name, ()))) is None, args
+
+
+class _Status(ToolOutput):
+ message: RouteText
+ error: Optional[RouteText] = None
+ notes: list[RouteText] = []
+ url: str
+ text: str
+
+
+def test_tool_outputs_refuse_undeclared_fields():
+ assert _Status.model_json_schema()["additionalProperties"] is False
+ with pytest.raises(ValidationError):
+ _Status(message = "ok", url = "http://127.0.0.1:8888/x", text = "hi", output_dir = "/srv/x")
+
+
+def test_route_text_is_scrubbed_but_urls_and_model_text_are_not():
+ status = _Status(
+ message = f"Saved to {SENTINEL_ROOTS[0]}/run",
+ error = f"Failed at {SENTINEL_ROOTS[1]}\\run",
+ notes = [f"cache {SENTINEL_ROOTS[0]}/cache"],
+ url = "http://127.0.0.1:8888/v1/audio/gallery/abc/file",
+ text = "The file lives at /etc/hosts on most systems.",
+ )
+ assert status.model_dump() == {
+ "message": "Saved to <path>",
+ "error": "Failed at <path>",
+ "notes": ["cache <path>"],
+ "url": "http://127.0.0.1:8888/v1/audio/gallery/abc/file",
+ "text": "The file lives at /etc/hosts on most systems.",
+ }
+
+
+def _probe_mcp():
+ mcp = FastMCP("probe")
+
+ class Echo(ToolOutput):
+ message: RouteText
+
+ @mcp.tool
+ async def passthrough() -> dict:
+ return raise_for_route(await forward(current_caller(), "GET", "/api/train/status"))
+
+ @mcp.tool
+ async def typed() -> Echo:
+ payload = raise_for_route(await forward(current_caller(), "GET", "/api/train/status"))
+ return Echo(message = payload["message"])
+
+ @mcp.tool
+ async def failing() -> Echo:
+ raise_for_route(await forward(current_caller(), "GET", "/api/train/missing"))
+
+ return mcp
+
+
+ROUTES = {("GET", "/api/train/status"): {"message": "Training", "output_dir": "/srv/out"}}
+
+
+def test_the_checker_sees_a_leak_but_typed_outputs_and_route_errors_do_not_leak(monkeypatch):
+ # Positive control: a passed-through route payload is caught.
+ assert leaks(run_case(monkeypatch, _probe_mcp(), "passthrough", ROUTES, {})) is not None
+ typed = run_case(monkeypatch, _probe_mcp(), "typed", ROUTES, {})
+ assert typed["structuredContent"]["message"].startswith("Training")
+ assert leaks(typed) is None
+
+ missing = JSONResponse({"detail": poison("Run not found")}, status_code = 404)
+ failed = run_case(
+ monkeypatch, _probe_mcp(), "failing", {("GET", "/api/train/missing"): missing}, {}
+ )
+ assert failed["isError"] is True
+ assert "Run not found" in failed["content"][0]["text"]
+ assert leaks(failed) is None
diff --git a/studio/backend/tests/test_mcp_server.py b/studio/backend/tests/test_mcp_server.py
index 8fd63768a2e..7d00c9b3b03 100644
--- a/studio/backend/tests/test_mcp_server.py
+++ b/studio/backend/tests/test_mcp_server.py
@@ -2,379 +2,86 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import asyncio
-import sys
-import types
import pytest
-from mcp_server import BearerTokenMiddleware, _clamp, _dump, create_studio_mcp
+from mcp_server import INSTRUCTIONS, create_studio_mcp
+READ_ONLY = {"studio_status", "list_models", "embed", "system_one", "get_job", "list_training_runs"}
+DESTRUCTIVE = {"unload_model", "cancel"}
+OTHERS = set(
+ "load_model chat generate_image generate_audio transcribe generate_video run_recipe datasets"
+ " start_training export_model".split()
+)
-def _get_tool(name):
- tools = asyncio.run(create_studio_mcp().list_tools())
- return {tool.name: tool for tool in tools}[name]
-
-def test_studio_mcp_registers_control_plane_tools():
- tools = asyncio.run(create_studio_mcp().list_tools())
-
- assert {tool.name for tool in tools} == {
- "studio_status",
- "list_local_models",
- "get_training_status",
- "start_training",
- "stop_training",
- "list_training_runs",
- "validate_recipe",
- "get_recipe_job_status",
- "get_recipe_job_dataset",
- "load_checkpoint",
- "export_gguf",
- }
-
-
-def test_dump_serializes_pydantic_values():
- class Response:
- def model_dump(self, *, mode):
- assert mode == "json"
- return {"ok": True}
-
- assert _dump(Response()) == {"ok": True}
- assert _dump({"already": "json"}) == {"already": "json"}
-
-
-def test_bearer_token_middleware_rejects_wrong_token():
- events = []
-
- async def app(scope, receive, send):
- events.append("app")
-
- async def send(message):
- events.append(message)
-
- middleware = BearerTokenMiddleware(app, "secret")
- asyncio.run(
- middleware(
- {"type": "http", "headers": [(b"authorization", b"Bearer wrong")]},
- None,
- send,
- )
- )
-
- assert events[0]["status"] == 401
- assert "app" not in events
-
-
-def test_bearer_token_middleware_closes_unauthorized_websocket():
- events = []
-
- async def app(scope, receive, send):
- events.append("app")
-
- async def send(message):
- events.append(message)
-
- middleware = BearerTokenMiddleware(app, "secret")
- asyncio.run(
- middleware(
- {"type": "websocket", "headers": []},
- None,
- send,
- )
- )
-
- assert events == [{"type": "websocket.close", "code": 4401}]
-
-
-def test_bearer_token_middleware_rejects_non_ascii_authorization():
- # A non-ASCII bearer value must produce a clean 401, not a 500. Comparing on
- # bytes avoids the str hmac.compare_digest TypeError on non-ASCII input.
- events = []
-
- async def app(scope, receive, send):
- events.append("app")
-
- async def send(message):
- events.append(message)
-
- middleware = BearerTokenMiddleware(app, "secret")
- asyncio.run(
- middleware(
- {"type": "http", "headers": [(b"authorization", b"Bearer \xff\xff")]},
- None,
- send,
- )
- )
-
- assert events[0]["status"] == 401
- assert "app" not in events
-
-
-def test_bearer_token_middleware_accepts_correct_token():
- events = []
-
- async def app(scope, receive, send):
- events.append("app")
-
- async def send(message):
- events.append(message)
-
- middleware = BearerTokenMiddleware(app, "secret")
- asyncio.run(
- middleware(
- {"type": "http", "headers": [(b"authorization", b"Bearer secret")]},
- None,
- send,
- )
- )
-
- assert events == ["app"]
-
-
-def test_bearer_token_middleware_requires_non_empty_token():
- async def app(scope, receive, send):
- pass
-
- for bad in ("", " "):
- with pytest.raises(ValueError):
- BearerTokenMiddleware(app, bad)
-
-
-def test_bearer_token_middleware_rejects_non_ascii_token():
- async def app(scope, receive, send):
- pass
-
- # non-ASCII tokens cannot be transmitted in an HTTP header by a standard
- # client, so they are rejected at construction instead of locking out.
- for bad in ("töken", "\U0001f600"):
- with pytest.raises(ValueError):
- BearerTokenMiddleware(app, bad)
-
-
-def test_bearer_token_middleware_passes_through_non_http_scopes():
- events = []
-
- async def app(scope, receive, send):
- events.append("app")
-
- async def send(message):
- events.append(message)
-
- middleware = BearerTokenMiddleware(app, "secret")
- asyncio.run(middleware({"type": "lifespan"}, None, send))
-
- assert events == ["app"]
-
-
-def test_clamp_restricts_to_inclusive_bounds():
- assert _clamp(5, 1, 200) == 5
- assert _clamp(-10, 1, 200) == 1
- assert _clamp(10_000, 1, 200) == 200
- assert _clamp(0, 1, 500) == 1
- assert _clamp(1_000, 1, 500) == 500
-
-
-def test_export_and_checkpoint_tools_expose_forwarded_fields():
- export_props = set(_get_tool("export_gguf").parameters["properties"])
- assert {"hf_token", "imatrix", "imatrix_path", "private"} <= export_props
-
- checkpoint_props = set(_get_tool("load_checkpoint").parameters["properties"])
- assert {"hf_token", "approved_remote_code_fingerprint"} <= checkpoint_props
-
- stop_schema = _get_tool("stop_training").parameters
- assert "expected_job_id" in stop_schema["required"]
+def _tools():
+ return {tool.name: tool for tool in asyncio.run(create_studio_mcp().list_tools())}
-def _stub_module(monkeypatch, name, **attrs):
- module = types.ModuleType(name)
- for key, value in attrs.items():
- setattr(module, key, value)
- if "." in name:
- module.__path__ = [] # mark package-like so submodule imports resolve
- monkeypatch.setitem(sys.modules, name, module)
- return module
-
-
-def test_export_gguf_forwards_hf_token_and_imatrix(monkeypatch):
- captured = {}
-
- class FakeExportGGUFRequest:
- def __init__(self, **kwargs):
- captured.update(kwargs)
-
- async def fake_export(request, current_subject, allow_ambient):
- return {"current_subject": current_subject, "allow_ambient": allow_ambient}
-
- _stub_module(monkeypatch, "models", ExportGGUFRequest = FakeExportGGUFRequest)
- _stub_module(monkeypatch, "routes")
- _stub_module(monkeypatch, "routes.export", export_gguf = fake_export)
-
- tool = _get_tool("export_gguf")
- result = asyncio.run(
- tool.fn(
- save_directory = "/tmp/out",
- quantization_method = ["Q4_K_M", "Q8_0"],
- push_to_hub = True,
- repo_id = "me/model",
- hf_token = "hf_secret",
- imatrix = True,
- imatrix_path = "/tmp/imatrix.dat",
- private = True,
- )
- )
-
- assert captured["hf_token"] == "hf_secret"
- assert captured["imatrix"] is True
- assert captured["imatrix_path"] == "/tmp/imatrix.dat"
- assert captured["quantization_method"] == ["Q4_K_M", "Q8_0"]
- assert captured["private"] is True
- assert result["current_subject"] == "mcp"
- # A direct call skips FastAPI, so the route's Depends default never resolves; MCP has to
- # name the policy itself or allow_ambient arrives as a truthy Depends object.
- assert result["allow_ambient"] is False
-
-
-def test_load_checkpoint_forwards_token_and_fingerprint(monkeypatch):
- captured = {}
-
- class FakeLoadCheckpointRequest:
- def __init__(self, **kwargs):
- captured.update(kwargs)
-
- async def fake_load(request, current_subject, allow_ambient):
- return {"current_subject": current_subject, "allow_ambient": allow_ambient}
-
- _stub_module(monkeypatch, "models", LoadCheckpointRequest = FakeLoadCheckpointRequest)
- _stub_module(monkeypatch, "routes")
- _stub_module(monkeypatch, "routes.export", load_checkpoint = fake_load)
-
- tool = _get_tool("load_checkpoint")
- result = asyncio.run(
- tool.fn(
- checkpoint_path = "/tmp/ckpt",
- approved_remote_code_fingerprint = "sha256:abc",
- hf_token = "hf_secret",
- )
- )
-
- assert captured["hf_token"] == "hf_secret"
- assert captured["approved_remote_code_fingerprint"] == "sha256:abc"
- assert result["allow_ambient"] is False
-
-
[email protected]("load_in_4bit", [None, True, False])
-def test_load_checkpoint_leaves_unset_load_in_4bit_to_the_route(monkeypatch, load_in_4bit):
- from models.export import LoadCheckpointRequest
-
- captured = {}
-
- async def fake_load(request, current_subject, allow_ambient):
- captured["fields_set"] = request.model_fields_set
- captured["load_in_4bit"] = request.load_in_4bit
- return {}
-
- _stub_module(monkeypatch, "models", LoadCheckpointRequest = LoadCheckpointRequest)
- _stub_module(monkeypatch, "routes")
- _stub_module(monkeypatch, "routes.export", load_checkpoint = fake_load)
-
- extra = {} if load_in_4bit is None else {"load_in_4bit": load_in_4bit}
- asyncio.run(_get_tool("load_checkpoint").fn(checkpoint_path = "/tmp/ckpt", **extra))
-
- # The route only picks 16-bit for a full fine-tune when load_in_4bit was not sent.
- assert ("load_in_4bit" in captured["fields_set"]) is (load_in_4bit is not None)
- if load_in_4bit is not None:
- assert captured["load_in_4bit"] is load_in_4bit
-
-
-def test_stop_training_forwards_job_scope(monkeypatch):
- captured = {}
-
- class FakeTrainingStopRequest:
- def __init__(self, **kwargs):
- captured.update(kwargs)
-
- async def fake_stop(request, current_subject):
- assert isinstance(request, FakeTrainingStopRequest)
- captured["current_subject"] = current_subject
- return {"status": "stopped"}
-
- _stub_module(monkeypatch, "routes")
- _stub_module(
- monkeypatch,
- "routes.training",
- TrainingStopRequest = FakeTrainingStopRequest,
- stop_training = fake_stop,
- )
-
- tool = _get_tool("stop_training")
- result = asyncio.run(tool.fn(expected_job_id = "job-A", save = False))
-
- assert captured["expected_job_id"] == "job-A"
- assert captured["save"] is False
- assert captured["current_subject"] == "mcp"
- assert result == {"status": "stopped"}
-
-
-def test_start_training_forwards_as_api_key_caller(monkeypatch):
- captured = {}
-
- class FakeTrainingStartRequest:
- @classmethod
- def model_validate(cls, config):
- captured["config"] = config
- return cls()
-
- async def fake_start(request, current_subject, via_api_key):
- assert isinstance(request, FakeTrainingStartRequest)
- captured["current_subject"] = current_subject
- captured["via_api_key"] = via_api_key
- return {"status": "queued"}
-
- _stub_module(monkeypatch, "models", TrainingStartRequest = FakeTrainingStartRequest)
- _stub_module(monkeypatch, "routes")
- _stub_module(monkeypatch, "routes.training", start_training = fake_start)
-
- tool = _get_tool("start_training")
- result = asyncio.run(tool.fn(config = {"model_name": "unsloth/test"}))
-
- assert captured["config"] == {"model_name": "unsloth/test"}
- assert captured["current_subject"] == "mcp"
- assert captured["via_api_key"] is True
- assert result == {"status": "queued"}
-
-
-def test_list_training_runs_clamps_pagination(monkeypatch):
- captured = {}
-
- async def fake_list_runs(limit, offset, current_subject):
- captured["limit"] = limit
- captured["offset"] = offset
- return {"ok": True}
-
- _stub_module(monkeypatch, "routes")
- _stub_module(monkeypatch, "routes.training_history", list_training_runs = fake_list_runs)
-
- tool = _get_tool("list_training_runs")
- asyncio.run(tool.fn(limit = 10_000, offset = -5))
-
- assert captured["limit"] == 200
- assert captured["offset"] == 0
-
-
-def test_get_recipe_job_dataset_clamps_pagination(monkeypatch):
- captured = {}
-
- def fake_job_dataset(job_id, limit, offset):
- captured["limit"] = limit
- captured["offset"] = offset
- return {"ok": True}
-
- _stub_module(monkeypatch, "routes")
- _stub_module(monkeypatch, "routes.data_recipe")
- _stub_module(monkeypatch, "routes.data_recipe.jobs", job_dataset = fake_job_dataset)
-
- tool = _get_tool("get_recipe_job_dataset") # this tool is synchronous
- tool.fn(job_id = "job-1", limit = -1, offset = -9)
-
- assert captured["limit"] == 1
- assert captured["offset"] == 0
+def test_studio_mcp_registers_control_plane_tools():
+ tools = _tools()
+ assert READ_ONLY | DESTRUCTIVE | OTHERS == set(tools)
+ assert len(tools) == 18
+ for name, tool in tools.items():
+ hints = tool.annotations
+ assert hints is not None, name
+ assert hints.openWorldHint is False, name
+ assert hints.readOnlyHint is (name in READ_ONLY), name
+ # MCP reads an unset hint as destructive, so tools that only add work say so.
+ if name not in READ_ONLY:
+ assert hints.destructiveHint is (name in DESTRUCTIVE), name
+ assert tool.output_schema["type"] == "object", name
+ assert tool.description, name
+
+
+# (tool, path into the listed tool, the value or a check on it).
+SCHEMA_FACTS = [
+ ("embed", "parameters/properties/texts/minItems", 1),
+ ("embed", "parameters/properties/texts/maxItems", 2048),
+ ("system_one", "parameters/properties/model/default", "default"),
+ ("system_one", "parameters/properties/images/anyOf/0/maxItems", 4),
+ ("generate_image", "output_schema/properties/images/type", "array"),
+ ("generate_image", "output_schema/additionalProperties", False),
+ ("generate_audio", "output_schema/additionalProperties", False),
+ ("generate_audio", "parameters/properties", lambda props: "text" in props),
+ ("studio_status", "output_schema/additionalProperties", False),
+ ("studio_status", "parameters", lambda params: params.get("properties", {}) == {}),
+ (
+ "list_models",
+ "parameters/properties",
+ lambda props: set(props) == {"kind", "loaded_only", "model"},
+ ),
+ (
+ "load_model",
+ "parameters/properties",
+ lambda props: set(props)
+ == {"model", "kind", "variant", "max_seq_length", "load_in_4bit", "hf_token"},
+ ),
+ ("load_model", "parameters/properties/kind/default", "llm"),
+ (
+ "cancel",
+ "parameters/properties/kind/enum",
+ lambda kinds: "audio" not in kinds and len(kinds) == 9,
+ ),
+ ("get_job", "parameters/properties/kind/enum", lambda kinds: {"video", "recipe"} <= set(kinds)),
+]
+
+
[email protected]("name,path,expected", SCHEMA_FACTS)
+def test_tool_schemas_keep_their_limits_and_defaults(name, path, expected):
+ attribute, *keys = path.split("/")
+ value = getattr(_tools()[name], attribute)
+ for key in keys:
+ value = value[int(key)] if isinstance(value, list) else value[key]
+ if callable(expected):
+ assert expected(value), (name, path, value)
+ else:
+ assert value == expected and type(value) is type(expected), (name, path, value)
+
+
+def test_instructions_point_agents_at_the_workflow():
+ assert create_studio_mcp().instructions == INSTRUCTIONS
+ for phrase in ("studio_status", "list_models", "load_model", "get_job", "cancel"):
+ assert phrase in INSTRUCTIONS
+ assert "Studio computer" in INSTRUCTIONS and "galleries" in INSTRUCTIONS
diff --git a/studio/backend/tests/test_mcp_stdio_api_key_gate.py b/studio/backend/tests/test_mcp_stdio_api_key_gate.py
index a08952fba5d..1c5601ed91c 100644
--- a/studio/backend/tests/test_mcp_stdio_api_key_gate.py
+++ b/studio/backend/tests/test_mcp_stdio_api_key_gate.py
@@ -519,14 +519,25 @@ def test_list_shows_stdio_rows_to_a_ui_session(tmp_path, monkeypatch, stdio_on):
assert rows[0].headers == {"API_KEY": "sk-env-secret"}
-def test_studio_mcp_surface_refuses_stdio_recipes():
- """mcp_server.py calls the validate route function directly, so the ViaApiKey
- dependency never runs and its `= False` default would read as a UI session.
- That remote static bearer surface must pass True itself or the gate is dead."""
- import inspect
-
- import mcp_server
-
- assert "validate(RecipePayload(recipe = recipe), via_api_key = True)" in inspect.getsource(
- mcp_server
[email protected]("mode", ["validate", "preview", "full"])
+def test_studio_mcp_surface_refuses_stdio_recipes(monkeypatch, mode):
+ """Studio MCP reaches the recipe routes as the agent's API key, so the routes' own
+ UI-session gate holds: a recipe that defines a local (stdio) MCP command is refused
+ with the route's 403 text, whichever mode runs it."""
+ from auth.authentication import get_current_credential
+ from routes.data_recipe import router as data_recipe_router
+
+ from .mcp_harness import route_studio, run_tool
+
+ studio = route_studio(
+ data_recipe_router,
+ "/api/data-recipe",
+ overrides = {get_current_credential: lambda: ("unsloth", None)},
+ )
+ result, _studio = run_tool(
+ monkeypatch, studio, "run_recipe", {"recipe": _STDIO_RECIPE, "mode": mode}
+ )
+ assert result["isError"] is True
+ assert result["content"][0]["text"].startswith(
+ "Local (stdio) MCP servers can only be configured from the Unsloth UI, not with an API key."
)
diff --git a/studio/backend/tests/test_mcp_tool_contract.py b/studio/backend/tests/test_mcp_tool_contract.py
new file mode 100644
index 00000000000..0c262600c14
--- /dev/null
+++ b/studio/backend/tests/test_mcp_tool_contract.py
@@ -0,0 +1,456 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Contracts every Unsloth Studio MCP tool keeps, one row per case: a refused input never reaches a route, a route's failure becomes the message the agent acts on, and only a local agent may name a host file."""
+
+from typing import Optional
+
+import pytest
+from fastapi.responses import JSONResponse
+
+from studio_mcp.inputs import PATH_REMOTE
+from studio_mcp.outputs import RouteText, ToolOutput, Usage
+
+from .mcp_harness import (
+ CONFIG,
+ DIFFUSION,
+ LOCAL,
+ PNG,
+ PNG_URL,
+ REMOTE,
+ WAV,
+ WAV_INPUT,
+ WEBP,
+ WHISPER,
+ call_to,
+ data_url,
+ file_spy, # noqa: F401 (fixture)
+ form,
+ openai_error,
+ run_tool,
+ stt_state,
+)
+from .test_mcp_tools_audio import TRANSCRIPT
+from .test_mcp_tools_text import CHAT, URGENT
+
+EXPORT = {"checkpoint": "qwen-lora", "format": "gguf"}
+ONE = {"state": "x", "questions": URGENT}
+
+
+# Over the 4 MiB inline limit, so only a (local) file path can carry these.
+def _big_png(tmp_path):
+ big = tmp_path / "big.png"
+ big.write_bytes(PNG + b"\x00" * (4 * 1024 * 1024))
+ return {"state": "x", "questions": URGENT, "images": [{"path": str(big)}]}
+
+
+def _huge_wav(tmp_path):
+ huge = tmp_path / "huge.wav"
+ with huge.open("wb") as handle:
+ handle.truncate(200 * 1024 * 1024 + 1)
+ return {"workflow": "clone", "text": "Hi", "reference": {"path": str(huge)}}
+
+
+# (tool, args or a tmp_path -> args builder (called as a local agent), refusal substring or None).
+REFUSED = [
+ ("chat", {}, None),
+ ("chat", {"prompt": "a", "messages": [{"role": "user", "content": "b"}]}, None),
+ ("chat", {"messages": []}, None),
+ ("chat", {"messages": [{"role": "tool", "content": "x"}]}, None),
+ ("chat", {"messages": [{"role": "assistant", "content": "x"}], "images": [PNG_URL]}, None),
+ ("chat", {"prompt": "x", "images": [{"data_url": "data:image/gif;base64,R0lG"}]}, None),
+ ("chat", {"prompt": "x", "images": [{"data_url": "data:image/png;base64,@@@"}]}, None),
+ ("chat", {"prompt": "x", "images": [{"data_url": data_url(b"text", "image/png")}]}, None),
+ ("embed", {"texts": []}, None),
+ ("embed", {"texts": ["x"] * 2049}, None),
+ ("system_one", {"state": "x", "questions": {}}, None),
+ ("system_one", {"state": "x", "questions": {f"q{i}": {} for i in range(65)}}, None),
+ ("system_one", {"state": "x", "questions": {"q": {"type": "maybe"}}}, None),
+ ("system_one", {"state": "x", "questions": {"q": {"type": "noul", "extra": 1}}}, None),
+ ("system_one", {**ONE, "images": [{"data_url": data_url(WEBP, "image/webp")}]}, None),
+ ("system_one", {**ONE, "images": [PNG_URL] * 5}, None),
+ ("system_one", _big_png, None),
+ *[
+ ("generate_audio", {"workflow": "clone", "text": "Hi", "reference": reference}, None)
+ for reference in (
+ {},
+ {"clip_id": "a", "voice_id": "b"},
+ {"data_base64": "AAAA"},
+ {"clip_id": "../etc"},
+ )
+ ],
+ ("generate_audio", _huge_wav, "larger than 200 MiB"),
+ ("transcribe", {"audio": {"clip_id": "clip-7"}, "translate": True}, "under 25 MB"),
+ ("transcribe", {"audio": WAV_INPUT, "translate": True, "timestamps": True}, "text only"),
+ ("generate_image", {"prompt": "x", "mask_image": PNG_URL}, "mask_image needs init_image"),
+ ("generate_image", {"prompt": "x", "upscale": 2}, None),
+ (
+ "generate_image",
+ {"prompt": "x", "init_image": PNG_URL, "reference_images": [PNG_URL] * 10},
+ None,
+ ),
+ *[
+ ("start_training", {"config": config, "validate_only": validate_only}, message)
+ for config, message in (
+ ({**CONFIG, "format_type": "bogus"}, "format_type must be one of"),
+ ({"model_name": "m"}, "Invalid training config: training_type: Field required"),
+ ({**CONFIG, "training_type": "Everything"}, "Invalid training config: training_type"),
+ )
+ for validate_only in (False, True)
+ ],
+ ("get_job", {"kind": "recipe", "id": "job-1", "rows": 0}, None),
+ ("get_job", {"kind": "recipe", "id": "job-1", "rows": 501}, None),
+ ("datasets", {"action": "check_format"}, "check_format needs name"),
+ ("datasets", {"action": "download"}, None),
+ ("datasets", {"action": "status"}, None),
+ *[
+ ("cancel", {"kind": kind}, "needs id")
+ for kind in ("training_start", "recipe", "chat", "dataset_download")
+ ],
+ *[
+ ("export_model", {**EXPORT, "save_directory": directory}, None)
+ for directory in ("/srv/out", "C:\\out", "~/out", "a/../../etc", "..", " ")
+ ],
+]
+
+
[email protected]("tool,args,message", REFUSED)
+def test_a_refused_input_never_reaches_a_route(monkeypatch, tmp_path, tool, args, message):
+ client = LOCAL if callable(args) else {}
+ args = args(tmp_path) if callable(args) else args
+ # Every route answers, so any call the tool made would be recorded.
+ result, studio = run_tool(monkeypatch, {}, tool, args, fallback = {}, **client)
+ assert result["isError"] is True
+ assert message is None or message in result["content"][0]["text"]
+ assert studio.state.calls == []
+
+
+def _detail(detail, status, **headers):
+ return JSONResponse({"detail": detail}, status_code = status, headers = headers)
+
+
+SYSTEM_ONE = ("POST", "/v1/systemone")
+IMAGES = ("POST", "/api/inference/images/generate")
+STT_LOAD = ("POST", "/api/inference/audio/stt/load")
+
+# (tool, args, the studio's routes, then the whole message or (check, text) pairs).
+ROUTE_ERRORS = [
+ (
+ "chat",
+ {"prompt": "hi"},
+ {CHAT: openai_error("No model loaded. Call POST /inference/load first.", 400)},
+ ("ends", "Load a chat model with load_model first; list_models shows the downloaded ones."),
+ ),
+ (
+ "chat",
+ {"prompt": "hi"},
+ {CHAT: openai_error("Busy.", 409, code = "gpu_busy", headers = {"Retry-After": "5"})},
+ "GPU busy: Busy. Retry after 5 s.",
+ ),
+ (
+ "embed",
+ {"texts": ["x"]},
+ {("POST", "/v1/embeddings"): openai_error("Model /srv/models/nomic is missing.", 409)},
+ ("starts", "Model <path>"),
+ ("lacks", "/srv/models"),
+ ("ends", "load_model(kind='llm') and call embed again."),
+ ),
+ (
+ "system_one",
+ {"state": "x", "questions": URGENT},
+ {SYSTEM_ONE: _detail({"error_type": "api_usage_error", "message": "API off."}, 404)},
+ ("starts", "API off."),
+ ("ends", "Turn on the Decision API in Settings > API."),
+ ),
+ (
+ "system_one",
+ {"state": "x", "questions": URGENT},
+ {
+ SYSTEM_ONE: _detail(
+ {"error_type": "model_loading", "message": "Loading."}, 503, **{"Retry-After": "12"}
+ )
+ },
+ "Loading. (HTTP 503) Retry after 12 s.",
+ ),
+ (
+ "generate_audio",
+ {"workflow": "speak", "text": "Hi"},
+ {("POST", "/v1/audio/run"): openai_error("No model loaded.", 400)},
+ "No model loaded. (HTTP 400) Load a text-to-speech or music model with load_model(kind='tts') first.",
+ ),
+ (
+ "generate_audio",
+ {"workflow": "speak", "text": "Hi", "options": {"speaker_wav": "/srv/x.wav"}},
+ {("POST", "/v1/audio/run"): openai_error("speaker_wav refused.", 400, param = "options")},
+ "Invalid arguments: speaker_wav refused.",
+ ),
+ # Off audio.cpp, timestamps are refused as a 501 without language and a 400 with it.
+ *[
+ (
+ "transcribe",
+ {"audio": WAV_INPUT, "timestamps": True, **args},
+ {("POST", "/v1/audio/transcriptions"): openai_error("No timings.", status)},
+ f"No timings. (HTTP {status}) Timestamps need a speech-to-text model that times"
+ " segments, such as Qwen3-ASR (audio.cpp) or Parakeet-TDT; pass it as model.",
+ )
+ for status, args in ((501, {}), (400, {"language": "en"}))
+ ],
+ # An audio.cpp model's own refusal already says what to do.
+ (
+ "transcribe",
+ {"audio": WAV_INPUT, "timestamps": True},
+ {
+ ("GET", "/api/inference/audio/stt/status"): {
+ "audiocpp": stt_state(loaded = "Parakeet-TDT-0.6B-v3-GGUF")
+ },
+ ("POST", "/v1/audio/transcriptions"): openai_error("Send the 'language'.", 501),
+ },
+ "Send the 'language'. (HTTP 501)",
+ ),
+ (
+ "generate_video",
+ {"prompt": "waves"},
+ {("POST", "/v1/videos"): openai_error("No video model is loaded.", 503)},
+ "No video model is loaded. (HTTP 503) Load a video model with load_model(kind='video') first.",
+ ),
+ (
+ "generate_image",
+ {"prompt": "x"},
+ {IMAGES: _detail("No diffusion model is loaded.", 409)},
+ "No diffusion model is loaded. (HTTP 409) Load an image model with load_model(kind='image') first.",
+ ),
+ (
+ "generate_image",
+ {"prompt": "x"},
+ {IMAGES: _detail("Diffusion generation was cancelled.", 409)},
+ "Diffusion generation was cancelled. (HTTP 409)",
+ ),
+ (
+ "generate_image",
+ {"prompt": "x", "width": 2048, "height": 2048},
+ {IMAGES: _detail("Needs 30 GB.", 400, **{"X-Unsloth-Refusal": "memory-estimate"})},
+ "Needs 30 GB. Pass allow_oversized=true to try anyway.",
+ ),
+ (
+ "run_recipe",
+ {"recipe": {"columns": [{"name": "q", "column_type": "sampler"}]}, "mode": "full"},
+ {("POST", "/api/data-recipe/jobs"): _detail("A recipe job is already running.", 409)},
+ "A recipe job is already running. (HTTP 409)",
+ ),
+ (
+ "start_training",
+ {"config": DIFFUSION, "kind": "diffusion"},
+ {("POST", "/api/train/diffusion/start"): _detail("An LLM run is active.", 409)},
+ "An LLM run is active. (HTTP 409)",
+ ),
+ (
+ "start_training",
+ {"config": CONFIG},
+ {("POST", "/api/train/start"): {"job_id": "", "status": "error", "message": "Busy."}},
+ "Busy.",
+ ),
+ (
+ "cancel",
+ {"kind": "training", "id": "someone-elses"},
+ {
+ ("GET", "/api/train/status"): {"job_id": "job-7", "is_training_running": True},
+ ("POST", "/api/train/stop"): _detail("No longer active.", 404),
+ },
+ "No longer active. (HTTP 404)",
+ ),
+ (
+ "load_model",
+ {"model": WHISPER, "kind": "stt"},
+ {
+ ("GET", "/api/inference/audio/stt/status"): {
+ "transformers": stt_state(downloaded = [WHISPER])
+ },
+ STT_LOAD: _detail("whisper-server is missing.", 501),
+ },
+ ("starts", "whisper-server is missing. (HTTP 501)"),
+ ),
+]
+CHECKS = {
+ "starts": str.startswith,
+ "ends": str.endswith,
+ "lacks": lambda message, text: text not in message,
+}
+
+
[email protected]("tool,args,routes,expected", [(*row[:3], row[3:]) for row in ROUTE_ERRORS])
+def test_a_route_failure_is_a_tool_error_the_agent_can_act_on(
+ monkeypatch, tool, args, routes, expected
+):
+ result, _studio = run_tool(monkeypatch, routes, tool, args)
+ assert result["isError"] is True
+ message = result["content"][0]["text"]
+ for check in expected:
+ if isinstance(check, str):
+ assert message == check
+ else:
+ assert CHECKS[check[0]](message, check[1]), (check, message)
+
+
+COMPLETION = {"model": "m", "choices": [{"message": {"content": "ok"}, "finish_reason": "stop"}]}
+DECISION = {"model": "m", "answers": {"q": {"type": "noul", "noul": 0.5}}}
+CLIP = {"id": "clip-1", "role": "output", "sample_rate": 24000, "duration_s": 1.0}
+
+# (tool, args for a file path, routes, the routes a local call reaches in order, extra check).
+PATH_CALLS = [
+ (
+ "chat",
+ lambda path: {"prompt": "What is this?", "images": [{"path": path}]},
+ {CHAT: COMPLETION},
+ ["/v1/chat/completions"],
+ None,
+ ),
+ (
+ "system_one",
+ lambda path: {
+ "state": "x",
+ "questions": {"q": {"type": "noul"}},
+ "images": [{"path": path}],
+ },
+ {SYSTEM_ONE: DECISION},
+ ["/v1/systemone"],
+ None,
+ ),
+ (
+ "generate_audio",
+ lambda path: {"workflow": "separate", "source": {"path": path}},
+ {
+ ("POST", "/v1/audio/inputs"): JSONResponse({"id": "in-1"}, status_code = 201),
+ ("POST", "/v1/audio/run"): {"clips": [CLIP]},
+ },
+ ["/v1/audio/inputs", "/v1/audio/run", "/v1/audio/gallery/clip-1/file"],
+ lambda result, studio: call_to(studio, "/v1/audio/inputs")[3] == WAV,
+ ),
+ (
+ "transcribe",
+ lambda path: {"audio": {"path": path}},
+ {("POST", "/v1/audio/transcriptions"): TRANSCRIPT},
+ [
+ "/api/inference/audio/stt/status",
+ "/v1/audio/transcriptions",
+ "/api/inference/audio/stt/status",
+ ],
+ lambda result, studio: (
+ result["structuredContent"]["text"] == "Hello from Studio."
+ and form(studio, "/v1/audio/transcriptions")["file"] == ("mcp-input.wav", WAV)
+ ),
+ ),
+ (
+ "generate_image",
+ lambda path: {"prompt": "x", "init_image": {"path": path}},
+ {IMAGES: {"images": [{"id": "img-1", "width": 8, "height": 8}]}},
+ ["/api/inference/images/generate", "/api/inference/images/gallery/img-1/file"],
+ None,
+ ),
+ (
+ "generate_video",
+ lambda path: {"prompt": "waves", "first_frame": {"path": path}},
+ {("POST", "/v1/videos"): {"id": "video-1", "status": "queued"}},
+ ["/v1/videos"],
+ None,
+ ),
+]
+
+
+def _input_file(tmp_path, tool):
+ audio = tool in ("generate_audio", "transcribe")
+ path = tmp_path / ("mcp-input.wav" if audio else "mcp-input.png")
+ path.write_bytes(WAV if audio else PNG)
+ return str(path)
+
+
[email protected]("tool,args,routes,reached,check", PATH_CALLS)
+def test_a_local_agent_may_send_a_path(
+ monkeypatch, file_spy, tmp_path, tool, args, routes, reached, check
+):
+ path = _input_file(tmp_path, tool)
+ # Every route answers, so the list of calls is the whole story.
+ result, studio = run_tool(monkeypatch, routes, tool, args(path), fallback = {}, **LOCAL)
+ assert result["isError"] is False, result
+ assert [kind for kind, touched in file_spy if kind == "read" and touched == path] == ["read"]
+ assert [c[1] for c in studio.state.calls] == reached
+ assert check is None or check(result, studio)
+
+
+ "client",
+ [REMOTE, {**LOCAL, "headers": {"X-Forwarded-For": "203.0.113.9"}}],
+ ids = ["remote", "proxied-loopback"],
+)
[email protected]("tool,args,routes,reached,check", PATH_CALLS)
+def test_a_remote_agent_may_not_and_the_file_is_never_opened(
+ monkeypatch, file_spy, tmp_path, client, tool, args, routes, reached, check
+):
+ path = _input_file(tmp_path, tool)
+ result, studio = run_tool(monkeypatch, routes, tool, args(path), fallback = {}, **client)
+ assert result["isError"] is True
+ assert result["content"][0]["text"] == PATH_REMOTE
+ assert file_spy == []
+ assert studio.state.calls == []
+
+
+class _Row(ToolOutput):
+ text: RouteText = "fallback"
+ note: Optional[RouteText] = None
+ count: Optional[int] = None
+ ratio: Optional[float] = None
+ flag: bool = False
+ maybe: Optional[bool] = None
+ names: list[RouteText] = []
+ tags: Optional[list[RouteText]] = None
+ usage: Optional[Usage] = None
+
+
+DEFAULTS = {
+ "text": "fallback",
+ "note": None,
+ "count": None,
+ "ratio": None,
+ "flag": False,
+ "maybe": False,
+ "names": [],
+ "tags": None,
+ "usage": None,
+}
+
+
+ "payload,expected",
+ [
+ ({}, DEFAULTS),
+ ("not a dict", DEFAULTS),
+ (
+ {"text": "a", "note": "see /srv/x/y", "count": 3, "ratio": 2, "flag": True},
+ {**DEFAULTS, "text": "a", "note": "see <path>", "count": 3, "ratio": 2.0, "flag": True},
+ ),
+ (
+ {
+ "text": "",
+ "count": True,
+ "ratio": False,
+ "flag": 1,
+ "maybe": True,
+ "names": ["a", 1],
+ },
+ {**DEFAULTS, "maybe": True, "names": ["a"]},
+ ),
+ (
+ {"note": 5, "count": 2.5, "ratio": "1", "names": "a", "tags": ["b", None]},
+ {**DEFAULTS, "tags": ["b"]},
+ ),
+ ({"usage": {"total_tokens": 1}, "unknown": "x"}, DEFAULTS),
+ ],
+)
+def test_from_route_copies_each_field_by_its_type(payload, expected):
+ row = _Row.from_route(payload)
+ assert row.model_dump(mode = "json") == expected
+ assert list(row.model_dump(mode = "json")) == list(_Row.model_fields)
+
+
+def test_from_route_takes_overrides_as_given():
+ row = _Row.from_route({"text": "a", "flag": True}, flag = False, usage = Usage(total_tokens = 3))
+ assert (row.text, row.flag, row.usage) == ("a", False, Usage(total_tokens = 3))
diff --git a/studio/backend/tests/test_mcp_tools_audio.py b/studio/backend/tests/test_mcp_tools_audio.py
new file mode 100644
index 00000000000..d4df9a8b1ac
--- /dev/null
+++ b/studio/backend/tests/test_mcp_tools_audio.py
@@ -0,0 +1,533 @@
+# 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 base64
+import json
+
+import pytest
+from fastapi.responses import JSONResponse, Response
+
+from models.inference import AudioRunRequest
+
+from .mcp_harness import (
+ REMOTE,
+ WAV,
+ WHISPER,
+ b64,
+ bodies,
+ call_to,
+ fast_polls, # noqa: F401 (fixture)
+ form,
+ openai_error,
+ run_tool,
+ sequence,
+ stt_state,
+)
+
+
+def _clip(clip_id, **fields):
+ return {
+ "id": clip_id,
+ "role": "output",
+ "url": f"/v1/audio/gallery/{clip_id}/file",
+ "sample_rate": 24000,
+ "duration_s": 1.0,
+ "workflow": "speak",
+ **fields,
+ }
+
+
+RUN = {"clips": [_clip("clip-1")], "group_id": None, "model": "unsloth/orpheus-3b", "audio": None}
+UPLOADED = {
+ "id": "in-1",
+ "name": "ref.wav",
+ "duration_s": 3.0,
+ "sample_rate": 24000,
+ "channels": 1,
+ "url": "/v1/audio/inputs/in-1/file",
+ "expires_at": "2026-10-10T00:00:00Z",
+}
+
+PAYLOADS = {("POST", "/v1/audio/run"): RUN, ("POST", "/v1/audio/inputs"): UPLOADED}
+
+
+def _wav(request, body):
+ return Response(WAV, media_type = "audio/wav")
+
+
+GALLERY = {
+ ("GET", f"/v1/audio/gallery/{clip_id}/file"): _wav
+ for clip_id in ("clip-1", "vocals", "drums", "bass", "other", "var-1", "var-2")
+}
+
+
+def _generate(
+ monkeypatch,
+ args,
+ run = RUN,
+ routes = None,
+ upload_status = 201,
+ **client,
+):
+ studio = {
+ ("POST", "/v1/audio/run"): run,
+ ("POST", "/v1/audio/inputs"): JSONResponse(UPLOADED, status_code = upload_status),
+ **GALLERY,
+ **(routes or {}),
+ }
+ return run_tool(monkeypatch, studio, "generate_audio", args, **client)
+
+
+MUSIC = {"clips": [_clip("var-1"), _clip("var-2")], "group_id": "grp-9", "model": "ace-step"}
+STEMS = ("vocals", "drums", "bass", "other")
+SEPARATED = {"clips": [_clip(s, role = s) for s in STEMS], "group_id": "grp-1", "model": "htdemucs"}
+# (workflow, args, answer, what else the sent body and the result must show).
+WORKFLOWS = [
+ ("clone", {"text": "Hi", "reference": {"clip_id": "ref-1"}, "reference_text": "Hi"}, RUN, None),
+ (
+ "speak",
+ {"text": "Hi", "reference": {"voice_id": "voice-1"}, "language": "en"},
+ RUN,
+ lambda body, result: body["inputs"] == {"reference": {"voice_id": "voice-1"}},
+ ),
+ (
+ "edit",
+ {"text": "Hi", "source": {"clip_id": "clip-0"}, "edit": {"mode": "words", "markup": "Hi"}},
+ RUN,
+ None,
+ ),
+ (
+ "convert",
+ {
+ "source": {"clip_id": "clip-0"},
+ "target": {"voice_id": "voice-1"},
+ "convert": {"mode": "singing"},
+ },
+ RUN,
+ None,
+ ),
+ (
+ "music",
+ {"text": "lo-fi", "mode": "song", "lyrics": "la", "duration_s": 30, "variations": 2},
+ MUSIC,
+ lambda body, result: (
+ body["variations"] == 2
+ and result["structuredContent"]["group_id"] == "grp-9"
+ and len(result["structuredContent"]["clips"]) == 2
+ ),
+ ),
+ ("separate", {"source": {"input_id": "in-9"}}, RUN, None),
+ (
+ "separate",
+ {"source": {"clip_id": "song-1"}},
+ SEPARATED,
+ lambda body, result: (
+ [c["role"] for c in result["structuredContent"]["clips"]] == list(STEMS)
+ and result["structuredContent"]["group_id"] == "grp-1"
+ and [c["type"] for c in result["content"][1:]] == ["audio"] * 4
+ ),
+ ),
+]
+
+
[email protected]("workflow,args,run,expect", WORKFLOWS)
+def test_each_workflow_sends_a_body_the_route_accepts(monkeypatch, workflow, args, run, expect):
+ result, studio = _generate(monkeypatch, {"workflow": workflow, **args}, run)
+ assert result["isError"] is False, result
+ (body,) = bodies(studio, "/v1/audio/run")
+ AudioRunRequest.model_validate(body)
+ assert body["workflow"] == workflow
+ assert "voice_id" not in body
+ assert expect is None or expect(body, result)
+
+
+VOICE = {"name": "voice", "type": "enum", "values": ["vivian", "ryan"], "default": "vivian"}
+CUSTOM_VOICE = {"audio_options": [VOICE, {"name": "temperature", "type": "float"}]}
+
+
+# The route drops an enum value it does not list, so "Ryan" would speak in the default voice.
+ "voice,sent,refusal",
+ [
+ ("Ryan", "ryan", None),
+ ("ryan", "ryan", None),
+ ("Bob", None, "'Bob' is not one of: vivian, ryan"),
+ ],
+)
+def test_an_enum_option_is_sent_as_the_model_lists_it(monkeypatch, voice, sent, refusal):
+ args = {"workflow": "speak", "text": "Hi", "options": {"voice": voice, "temperature": 0.7}}
+ routes = {("GET", "/api/inference/status"): CUSTOM_VOICE}
+ result, studio = _generate(monkeypatch, args, routes = routes)
+ if refusal:
+ assert result["isError"] is True and refusal in result["content"][0]["text"]
+ assert bodies(studio, "/v1/audio/run") == []
+ else:
+ (body,) = bodies(studio, "/v1/audio/run")
+ assert body["options"] == {"voice": sent, "temperature": 0.7}
+
+
+def test_short_clips_are_inline_and_long_ones_are_links_never_fetched(monkeypatch):
+ long_clip = _clip("long-1", duration_s = 600.0, sample_rate = 44100)
+ fetched = []
+ run = {"clips": [_clip("clip-1"), long_clip], "model": "m"}
+ long_file = {
+ ("GET", "/v1/audio/gallery/long-1/file"): lambda request, body: fetched.append(1)
+ or Response(WAV)
+ }
+ result, _studio = _generate(
+ monkeypatch, {"workflow": "speak", "text": "Hi"}, run, long_file, **REMOTE
+ )
+ content = result["content"]
+ assert [c["type"] for c in content[1:]] == ["audio", "resource_link"]
+ assert base64.b64decode(content[1]["data"]) == WAV
+ assert content[2]["uri"] == "http://192.168.1.20:8888/v1/audio/gallery/long-1/file"
+ assert fetched == []
+ assert (
+ result["structuredContent"]["clips"][0]["url"]
+ == "http://192.168.1.20:8888/v1/audio/gallery/clip-1/file"
+ )
+
+
+def test_an_unsaved_clip_over_the_inline_cap_is_not_inlined(monkeypatch):
+ from studio_mcp.media import INLINE_CAP
+
+ big = WAV + b"\x00" * INLINE_CAP
+ fallback = {"model": "kokoro", "clips": [], "audio": {"data": b64(big), "format": "wav"}}
+ result, _studio = _generate(monkeypatch, {"workflow": "speak", "text": "Hi"}, fallback)
+ assert result["isError"] is True
+ assert "too large to return inline" in result["content"][0]["text"]
+ assert all(c["type"] != "audio" for c in result["content"])
+
+
+def test_the_history_fallback_comes_back_inline_and_unsaved(monkeypatch):
+ fallback = {
+ "clips": [],
+ "model": "m",
+ "audio": {"data": b64(WAV), "format": "wav", "sample_rate": 24000},
+ }
+ result, _studio = _generate(monkeypatch, {"workflow": "speak", "text": "Hi"}, fallback)
+ assert result["structuredContent"]["saved"] is False
+ assert result["structuredContent"]["clips"] == []
+ assert base64.b64decode(result["content"][1]["data"]) == WAV
+
+
[email protected]("status", [201, 200])
+def test_inline_audio_is_uploaded_with_a_content_length(monkeypatch, status):
+ args = {
+ "workflow": "clone",
+ "text": "Hi",
+ "reference": {"data_base64": b64(WAV), "filename": "ref.wav"},
+ }
+ result, studio = _generate(monkeypatch, args, upload_status = status)
+ assert result["isError"] is False
+ (_m, path, headers, body) = call_to(studio, "/v1/audio/inputs")
+ assert headers["content-length"] == str(len(WAV))
+ assert body == WAV
+ (run,) = bodies(studio, "/v1/audio/run")
+ assert run["inputs"]["reference"] == {"input_id": "in-1"}
+
+
+TRANSCRIPT = {"text": "Hello from Studio."}
+VERBOSE = {
+ "task": "transcribe",
+ "language": "en",
+ "duration": 2.0,
+ "text": "Hello from Studio.",
+ "segments": [
+ {"id": 0, "start": 0.0, "end": 1.2, "text": "Hello"},
+ {"id": 1, "start": 1.2, "end": 2.0, "text": "from Studio."},
+ ],
+}
+TRANSCRIPTIONS = ("POST", "/v1/audio/transcriptions")
+TRANSLATIONS = ("POST", "/v1/audio/translations")
+STT_STATUS_ROUTE = ("GET", "/api/inference/audio/stt/status")
+STT_DOWNLOAD = ("POST", "/api/inference/audio/stt/download")
+# Before and after the missing default model is downloaded.
+MISSING_STATE = {"transformers": stt_state(default_model = WHISPER)}
+DONE_STATE = {
+ "transformers": stt_state(
+ downloaded = [WHISPER],
+ download = {"downloading": False, "completed_download_ids": ["d1"]},
+ default_model = WHISPER,
+ )
+}
+
+
+MISSING = "STT model 'openai/whisper-small' is not downloaded. Download it in Settings, then Voice, before loading it."
+
+
+def _memo(filename = "a.wav", **args):
+ return {"audio": {"data_base64": b64(WAV), "filename": filename}, **args}
+
+
+def test_without_a_model_the_resident_one_is_named(monkeypatch):
+ routes = {
+ TRANSCRIPTIONS: TRANSCRIPT,
+ STT_STATUS_ROUTE: {"transformers": {"loaded_model": "small", "loading": False}},
+ }
+ result, studio = run_tool(monkeypatch, routes, "transcribe", _memo("memo.wav"))
+ assert result["structuredContent"]["model"] == "small"
+ assert result["structuredContent"]["language"] is None
+ assert form(studio, "/v1/audio/transcriptions")["model"][1] == b"small"
+
+
+def test_small_audio_runs_on_the_loaded_non_transformers_model(monkeypatch):
+ # Without the id the route would run its Transformers default and the result would name Qwen3-ASR.
+ asr = "unsloth/Qwen3-ASR-0.6B-GGUF"
+ routes = {
+ TRANSCRIPTIONS: TRANSCRIPT,
+ STT_STATUS_ROUTE: {"mtmd": {"loaded_model": asr, "loading": False}},
+ }
+ result, studio = run_tool(monkeypatch, routes, "transcribe", _memo())
+ assert result["structuredContent"]["model"] == asr
+ assert form(studio, "/v1/audio/transcriptions")["model"][1] == asr.encode()
+
+
+SEGMENTS = [
+ {"start": 0.0, "end": 1.2, "text": "Hello"},
+ {"start": 1.2, "end": 2.0, "text": "from Studio."},
+]
+
+
+UNTIMED = {key: value for key, value in VERBOSE.items() if key != "segments"}
+
+
+# A text-only answer reports the language asked for; timestamps ask for verbose_json and always
+# come back as a list, empty when the route timed no speech.
+ "answer,model,timestamps,segments",
+ [
+ (TRANSCRIPT, "openai/whisper-small", False, None),
+ (VERBOSE, None, True, SEGMENTS),
+ (UNTIMED, None, True, []),
+ ],
+)
+def test_small_audio_goes_as_multipart_with_openai_field_names(
+ monkeypatch, answer, model, timestamps, segments
+):
+ args = _memo("memo.wav", language = "en", model = model, timestamps = timestamps)
+ result, studio = run_tool(monkeypatch, {TRANSCRIPTIONS: answer}, "transcribe", args)
+ out = result["structuredContent"]
+ assert (out["text"], out["language"]) == ("Hello from Studio.", "en")
+ assert out["segments"] == segments
+ assert out["saved_to_history"] is False
+ fields = form(studio, "/v1/audio/transcriptions")
+ assert fields["file"] == ("memo.wav", WAV)
+ assert {k: v[1] for k, v in fields.items() if k != "file"} == {
+ "response_format": b"verbose_json" if timestamps else b"json",
+ # Without it the route returns verbose_json with no segments at all.
+ **({"timestamp_granularities[]": b"segment"} if timestamps else {}),
+ **({"model": model.encode()} if model else {}),
+ "language": b"en",
+ }
+ if model:
+ assert out["model"] == model
+
+
+def test_translate_drops_language_and_reports_english_however_spelled(monkeypatch):
+ verbose = {**VERBOSE, "task": "translate", "language": "english"}
+ args = _memo(translate = True, language = "de")
+ result, studio = run_tool(monkeypatch, {TRANSLATIONS: verbose}, "transcribe", args)
+ assert result["structuredContent"]["language"] == "en"
+ assert "language" not in form(studio, "/v1/audio/translations")
+ assert [c[1] for c in studio.state.calls] == ["/v1/audio/translations"]
+
+
+def test_a_missing_model_is_downloaded_then_the_transcription_retried_once(monkeypatch, fast_polls):
+ refusal = openai_error(MISSING, 409, type = "conflict_error")
+ routes = {
+ TRANSCRIPTIONS: sequence(refusal, JSONResponse(TRANSCRIPT)),
+ STT_STATUS_ROUTE: sequence(MISSING_STATE, DONE_STATE),
+ STT_DOWNLOAD: {"downloading": True, "download_id": "d1"},
+ }
+ result, studio = run_tool(monkeypatch, routes, "transcribe", _memo())
+ assert result["structuredContent"]["text"] == "Hello from Studio."
+ assert [c[1] for c in studio.state.calls] == [
+ # Nothing loaded, so the route's default is asked for.
+ "/api/inference/audio/stt/status",
+ "/v1/audio/transcriptions",
+ "/api/inference/audio/stt/status",
+ "/api/inference/audio/stt/download",
+ "/api/inference/audio/stt/status",
+ "/v1/audio/transcriptions",
+ # Names the model that ran, since no model was asked for.
+ "/api/inference/audio/stt/status",
+ ]
+ assert bodies(studio, "/api/inference/audio/stt/download") == [
+ {"model": "openai/whisper-small", "engine": "transformers"}
+ ]
+
+
+def test_a_second_refusal_is_not_retried_again(monkeypatch, fast_polls):
+ routes = {
+ TRANSCRIPTIONS: lambda request, body: openai_error(
+ "STT model 'x' is not downloaded.", 409, type = "conflict_error"
+ ),
+ STT_STATUS_ROUTE: {"transformers": stt_state(downloaded = ["x"], models = ["x"])},
+ STT_DOWNLOAD: {"downloading": True},
+ }
+ result, studio = run_tool(monkeypatch, routes, "transcribe", _memo(model = "x"))
+ assert result["isError"] is True
+ assert [c[1] for c in studio.state.calls].count("/v1/audio/transcriptions") == 2
+
+
+TURBO = "whisper-large-v3-turbo-q5"
+STT_STATUS = {
+ "transformers": stt_state(downloaded = [WHISPER], default_model = WHISPER),
+ "gguf": stt_state(loaded = TURBO, downloaded = [TURBO], models = [TURBO]),
+}
+COMPLETE = {
+ "type": "complete",
+ "text": "A long meeting.",
+ "language": "en",
+ "segments": [{"start": 0.0, "end": 5.0, "text": "A long meeting."}],
+ "record": {"id": "tr-1"},
+}
+SOURCE = ("POST", "/api/inference/audio/transcribe/source")
+
+
+def _ndjson(*events):
+ return Response(
+ b"".join(json.dumps(e).encode() + b"\n" for e in events), media_type = "application/x-ndjson"
+ )
+
+
+def _from_source(
+ monkeypatch,
+ args,
+ events = None,
+ status = None,
+):
+ events = events or [{"type": "progress", "fraction": 0.5}, {"type": "heartbeat"}, COMPLETE]
+ routes = {
+ STT_STATUS_ROUTE: status or STT_STATUS,
+ SOURCE: _ndjson(*events),
+ ("POST", "/v1/audio/inputs"): JSONResponse(UPLOADED, status_code = 201),
+ }
+ return run_tool(monkeypatch, routes, "transcribe", args)
+
+
+IDLE = {**STT_STATUS, "gguf": {**STT_STATUS["gguf"], "loaded_model": None}}
+
+
+# Without a loaded model the curated default is used.
+ "status,args,model,engine",
+ [
+ (STT_STATUS, {"audio": {"clip_id": "clip-7"}, "timestamps": True}, TURBO, "gguf"),
+ (IDLE, {"audio": {"input_id": "in-3"}, "language": "en"}, WHISPER, "transformers"),
+ ],
+)
+def test_a_stored_clip_is_transcribed_by_id_with_the_loaded_model(
+ monkeypatch, status, args, model, engine
+):
+ result, studio = _from_source(monkeypatch, args, status = status)
+ timestamps = args.get("timestamps", False)
+ assert result["structuredContent"] == {
+ "text": "A long meeting.",
+ "language": "en",
+ "model": model,
+ "segments": [{"start": 0.0, "end": 5.0, "text": "A long meeting."}] if timestamps else None,
+ "saved_to_history": True,
+ }
+ extra = {"language": "en"} if "language" in args else {}
+ assert bodies(studio, "/api/inference/audio/transcribe/source") == [
+ {
+ "source": args["audio"],
+ "model": model,
+ "engine": engine,
+ "timestamps": timestamps,
+ **extra,
+ }
+ ]
+
+
+def test_small_audio_keeps_a_loaded_whisper_cpp_model_on_its_engine(monkeypatch):
+ # The id is shared with Transformers, so multipart would quietly run another engine.
+ result, studio = _from_source(monkeypatch, _memo())
+ assert result["structuredContent"]["model"] == TURBO
+ assert "/v1/audio/transcriptions" not in [c[1] for c in studio.state.calls]
+ assert bodies(studio, "/api/inference/audio/transcribe/source")[0]["engine"] == "gguf"
+
+
+SHARED = {
+ "transformers": stt_state(downloaded = [WHISPER], models = [WHISPER]),
+ "gguf": stt_state(loaded = WHISPER, downloaded = [WHISPER], models = [WHISPER]),
+}
+
+
+# Stored audio, and a small file naming the model: both stay on whisper.cpp.
[email protected]("audio", [{"clip_id": "clip-7"}, _memo()["audio"]])
+def test_a_shared_whisper_id_runs_on_the_engine_holding_it(monkeypatch, audio):
+ args = {"audio": audio, "model": WHISPER}
+ result, studio = _from_source(monkeypatch, args, status = SHARED)
+ assert result["structuredContent"]["model"] == WHISPER
+ assert "/v1/audio/transcriptions" not in [c[1] for c in studio.state.calls]
+ assert bodies(studio, "/api/inference/audio/transcribe/source")[0]["engine"] == "gguf"
+
+
+def test_audio_over_25_mib_is_uploaded_then_transcribed(monkeypatch):
+ from studio_mcp.tools import audio
+
+ monkeypatch.setattr(audio, "MULTIPART_LIMIT", len(WAV) - 1)
+ result, studio = _from_source(monkeypatch, _memo("meeting.wav"))
+ assert result["structuredContent"]["saved_to_history"] is True
+ assert [c[1] for c in studio.state.calls] == [
+ "/v1/audio/inputs",
+ "/api/inference/audio/stt/status",
+ "/api/inference/audio/transcribe/source",
+ ]
+ upload = studio.state.calls[0]
+ assert upload[2]["content-length"] == str(len(WAV))
+ assert bodies(studio, "/api/inference/audio/transcribe/source")[0]["source"] == {
+ "input_id": "in-1"
+ }
+
+
[email protected]("as_stream", [True, False])
+def test_a_missing_model_is_downloaded_before_a_stored_clip_is_retried(
+ monkeypatch, fast_polls, as_stream
+):
+ refusal = (
+ _ndjson({"type": "error", "message": MISSING})
+ if as_stream
+ else JSONResponse({"detail": MISSING}, status_code = 409)
+ )
+ routes = {
+ SOURCE: sequence(refusal, _ndjson(COMPLETE)),
+ STT_STATUS_ROUTE: sequence(MISSING_STATE, MISSING_STATE, DONE_STATE),
+ STT_DOWNLOAD: {"downloading": True, "download_id": "d1"},
+ }
+ result, studio = run_tool(monkeypatch, routes, "transcribe", {"audio": {"clip_id": "clip-7"}})
+ assert result["structuredContent"]["text"] == "A long meeting."
+ paths = [c[1] for c in studio.state.calls]
+ assert paths.count("/api/inference/audio/transcribe/source") == 2
+ assert "/api/inference/audio/stt/download" in paths
+
+
+def test_a_transcript_that_mentions_the_phrase_is_not_retried(monkeypatch):
+ said = {**COMPLETE, "text": "The file is not downloaded yet, he said."}
+ result, studio = _from_source(monkeypatch, {"audio": {"clip_id": "clip-7"}}, [said])
+ assert result["structuredContent"]["text"] == "The file is not downloaded yet, he said."
+ paths = [c[1] for c in studio.state.calls]
+ assert paths.count("/api/inference/audio/transcribe/source") == 1
+ assert "/api/inference/audio/stt/download" not in paths
+
+
+ "events,message",
+ [
+ (
+ [
+ {"type": "progress"},
+ {"type": "error", "message": "Audio is longer than 30 minutes."},
+ ],
+ "Audio is longer than 30 minutes.",
+ ),
+ ([{"type": "progress"}, {"type": "heartbeat"}], None),
+ ],
+)
+def test_an_ndjson_error_line_or_early_stop_is_a_tool_error(monkeypatch, events, message):
+ result, _studio = _from_source(monkeypatch, {"audio": {"clip_id": "clip-7"}}, events)
+ assert result["isError"] is True
+ assert message is None or result["content"][0]["text"] == message
diff --git a/studio/backend/tests/test_mcp_tools_cancel.py b/studio/backend/tests/test_mcp_tools_cancel.py
new file mode 100644
index 00000000000..9efd52a2a06
--- /dev/null
+++ b/studio/backend/tests/test_mcp_tools_cancel.py
@@ -0,0 +1,264 @@
+# 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 asyncio
+import types
+
+import pytest
+
+from studio_mcp import export_jobs
+
+from .mcp_harness import bodies, register_export_job, run_tool, sequence
+
+START = "/api/train/start-requests/req-1/cancel"
+RECIPE = "/api/data-recipe/jobs/rec-1/cancel"
+DOWNLOAD = "/api/hub/datasets/download/cancel"
+STOPPING = "Stop requested. Training will stop at the next safe step."
+PAYLOADS = {
+ ("GET", "/api/train/status"): {"job_id": "job-7", "is_training_running": True},
+ ("POST", "/api/train/stop"): {"status": "stopped", "message": STOPPING},
+ ("POST", START): {
+ "state": "rejected",
+ "message": "Training start was cancelled",
+ "error_code": "training_start_cancelled",
+ },
+ ("POST", "/api/train/diffusion/stop"): {"status": "stopping"},
+ ("GET", "/api/export/status"): {"is_export_active": True, "active_op_kind": "export_gguf"},
+ ("POST", "/api/export/cancel"): {"success": True, "message": "Export cancelled"},
+ ("POST", RECIPE): {"job_id": "rec-1", "status": "cancelling"},
+ ("POST", "/api/inference/images/generate/cancel"): {"cancelled": True},
+ ("POST", "/api/inference/video/generate/cancel"): {"cancelled": True},
+ ("POST", "/api/inference/cancel"): {"cancelled": 1},
+ ("POST", DOWNLOAD): {"repo_id": "a/b", "state": "cancelling"},
+}
+
+
[email protected](autouse = True)
+def fresh_registry():
+ export_jobs._reset()
+ yield
+ export_jobs._reset()
+
+
+def _call(
+ monkeypatch,
+ args,
+ overrides = None,
+):
+ return run_tool(monkeypatch, {**PAYLOADS, **(overrides or {})}, "cancel", args)
+
+
+ "args,route,body",
+ [
+ (
+ {"kind": "training", "id": "job-7", "save": False},
+ "/api/train/stop",
+ {"save": False, "expected_job_id": "job-7"},
+ ),
+ ({"kind": "training_start", "id": "req-1"}, START, None),
+ ({"kind": "diffusion_training"}, "/api/train/diffusion/stop", {"save": True}),
+ (
+ {"kind": "diffusion_training", "save": False},
+ "/api/train/diffusion/stop",
+ {"save": False},
+ ),
+ ({"kind": "recipe", "id": "rec-1"}, RECIPE, None),
+ ({"kind": "image"}, "/api/inference/images/generate/cancel", None),
+ ({"kind": "video"}, "/api/inference/video/generate/cancel", None),
+ ({"kind": "chat", "id": "mcp-abc"}, "/api/inference/cancel", {"cancel_id": "mcp-abc"}),
+ ({"kind": "dataset_download", "id": "a/b"}, DOWNLOAD, {"repo_id": "a/b"}),
+ ],
+)
+def test_each_kind_reaches_its_route(monkeypatch, args, route, body):
+ result, studio = _call(monkeypatch, args)
+ assert result["structuredContent"]["cancelled"] is True
+ assert result["structuredContent"]["kind"] == args["kind"]
+ (call,) = [c for c in studio.state.calls if c[0] == "POST"]
+ assert call[1] == route
+ assert (bodies(studio, route)[0] if call[3] else None) == body
+
+
+def test_training_without_an_id_stops_the_running_job(monkeypatch):
+ result, studio = _call(monkeypatch, {"kind": "training"})
+ assert result["structuredContent"] == {
+ "kind": "training",
+ "id": "job-7",
+ "cancelled": True,
+ "message": STOPPING,
+ }
+ assert [c[1] for c in studio.state.calls] == ["/api/train/status", "/api/train/stop"]
+ assert bodies(studio, "/api/train/stop") == [{"save": True, "expected_job_id": "job-7"}]
+
+
+def test_training_with_nothing_running_stops_nothing(monkeypatch):
+ result, studio = _call(
+ monkeypatch,
+ {"kind": "training"},
+ {("GET", "/api/train/status"): {"job_id": "", "is_training_running": False}},
+ )
+ assert result["structuredContent"]["cancelled"] is False
+ assert [c[1] for c in studio.state.calls] == ["/api/train/status"]
+
+
+def test_an_export_job_cancel_stops_only_its_own_op(monkeypatch):
+ job = register_export_job(job_id = "exp-1", phase = "exporting", op_id = "op-x")
+ result, studio = _call(monkeypatch, {"kind": "export", "id": "exp-1"})
+ assert result["structuredContent"]["cancelled"] is True
+ assert (
+ result["structuredContent"]["message"]
+ == "The export was stopped and its checkpoint unloaded."
+ )
+ assert job.status == "cancelled"
+ assert [c[1] for c in studio.state.calls] == ["/api/export/cancel"]
+ assert bodies(studio, "/api/export/cancel") == [{"expected_op_id": "op-x"}]
+
+
+def test_a_job_before_its_first_step_never_touches_the_worker(monkeypatch):
+ job = register_export_job(job_id = "exp-1", phase = "starting")
+ result, studio = _call(monkeypatch, {"kind": "export", "id": "exp-1"})
+ assert (result["structuredContent"]["cancelled"], result["structuredContent"]["message"]) == (
+ True,
+ "The export job was stopped before its next step.",
+ )
+ assert job.status == "cancelled"
+ assert studio.state.calls == []
+
+
+def test_without_an_id_an_idle_worker_is_never_touched(monkeypatch):
+ idle = {"is_export_active": False, "current_checkpoint": "ref:abc", "last_op_seq": 5}
+ result, studio = _call(monkeypatch, {"kind": "export"}, {("GET", "/api/export/status"): idle})
+ assert result["structuredContent"]["message"] == "No export is running."
+ assert [c[1] for c in studio.state.calls] == ["/api/export/status"]
+
+
+NOT_RUNNING = {"success": True, "message": "No active export to cancel"}
+
+
+def _cancel_directly(monkeypatch, job_run, answers):
+ """Run cancel on the loop the job's task lives on, which a served tool call cannot share."""
+ from studio_mcp.tools import cancel as cancel_module
+
+ answer = sequence(*answers)
+ calls = []
+
+ async def route_json(
+ method,
+ path,
+ json_body = None,
+ **_kwargs,
+ ):
+ calls.append((method, path, json_body))
+ return answer(None, None)
+
+ monkeypatch.setattr(cancel_module, "route_json", route_json)
+ monkeypatch.setattr(
+ cancel_module, "current_caller", lambda: types.SimpleNamespace(account_id = "owner")
+ )
+ monkeypatch.setattr(cancel_module, "SETTLE_S", 0.2)
+
+ async def run():
+ job = export_jobs.start("owner", "gguf", job_run)
+ await asyncio.sleep(0)
+ result = await cancel_module.cancel("export", job.job_id)
+ status = job.status
+ export_jobs.mark_cancelled(job)
+ await asyncio.gather(job.task, return_exceptions = True)
+ job.status = status
+ return job, result, calls
+
+ return asyncio.run(run())
+
+
+def test_an_export_whose_answer_is_on_its_way_is_reported_done(monkeypatch):
+ # The worker already finished the export; the route is still writing its answer.
+ async def answered_soon(job):
+ job.phase, job.op_id = "exporting", "op-e"
+ await asyncio.sleep(0.05)
+
+ job, result, _calls = _cancel_directly(monkeypatch, answered_soon, [NOT_RUNNING])
+ assert (result.cancelled, result.message) == (False, "The export already completed.")
+ assert job.status == "completed"
+
+
+def test_a_job_queued_behind_someone_elses_export_is_withdrawn_and_theirs_left_alone(monkeypatch):
+ # Its op has not started: the route remembers the id and refuses the op when it would start.
+ async def queued(job):
+ job.phase, job.op_id = "exporting", "op-e"
+ await asyncio.Event().wait()
+
+ job, result, calls = _cancel_directly(monkeypatch, queued, [NOT_RUNNING])
+ assert (result.cancelled, result.message) == (
+ True,
+ "The export job was stopped before its next step.",
+ )
+ assert job.status == "cancelled"
+ assert calls == [("POST", "/api/export/cancel", {"expected_op_id": "op-e"})]
+
+
+def test_a_job_that_moved_to_its_next_step_is_stopped_there(monkeypatch):
+ async def next_step(job):
+ job.phase, job.op_id = "loading", "op-l"
+ await asyncio.sleep(0.05)
+ job.phase, job.op_id = "exporting", "op-e"
+ await asyncio.Event().wait()
+
+ answers = [NOT_RUNNING, {"success": True, "message": "Export cancelled"}]
+ job, result, calls = _cancel_directly(monkeypatch, next_step, answers)
+ assert result.cancelled is True
+ assert result.message == "The export was stopped and its checkpoint unloaded."
+ assert [c[2] for c in calls] == [{"expected_op_id": "op-l"}, {"expected_op_id": "op-e"}]
+ assert job.status == "cancelled"
+
+
+IDLE_EXPORT = (
+ "export",
+ "/api/export/cancel",
+ {"success": True, "message": "No active export to cancel"},
+)
+# What each route answers when there was nothing of the caller's to stop.
+IDLE_ANSWERS = [
+ ("training", "/api/train/stop", {"status": "idle", "message": "No training job is running"}),
+ ("training_start", START, {"state": "accepted", "message": "Started"}),
+ # A start request rejected for another reason was not cancelled.
+ ("training_start", START, {"state": "rejected", "error_code": "model_not_found"}),
+ ("diffusion_training", "/api/train/diffusion/stop", {"status": "idle"}),
+ IDLE_EXPORT,
+ ("recipe", RECIPE, {"job_id": "rec-1", "status": "completed"}),
+ ("recipe", RECIPE, {"job_id": "rec-1", "status": "cancelled"}),
+ ("image", "/api/inference/images/generate/cancel", {"cancelled": False}),
+ ("video", "/api/inference/video/generate/cancel", {"cancelled": False}),
+ ("chat", "/api/inference/cancel", {"cancelled": 0}),
+ ("dataset_download", DOWNLOAD, {"repo_id": "a/b", "state": "completed"}),
+ ("dataset_download", DOWNLOAD, {"repo_id": "a/b", "state": "cancelled"}),
+]
+IDS = {
+ "training": "job-7",
+ "training_start": "req-1",
+ "recipe": "rec-1",
+ "chat": "mcp-abc",
+ "dataset_download": "a/b",
+}
+
+
[email protected]("kind,route,answer", IDLE_ANSWERS)
+def test_a_cancel_that_stopped_nothing_says_so(monkeypatch, kind, route, answer):
+ args = {"kind": kind, **({"id": IDS[kind]} if kind in IDS else {})}
+ result, _studio = _call(monkeypatch, args, {("POST", route): answer})
+ assert result["structuredContent"]["cancelled"] is False
+
+
[email protected]("status", ["completed", "failed", "cancelled"])
+def test_a_finished_export_job_never_stops_the_export_running_now(monkeypatch, status):
+ register_export_job(job_id = "exp-1", status = status)
+ result, studio = _call(monkeypatch, {"kind": "export", "id": "exp-1"})
+ assert result["structuredContent"]["cancelled"] is False
+ assert result["structuredContent"]["message"] == f"The export already {status}."
+ assert studio.state.calls == []
+
+
+def test_another_accounts_export_is_not_cancelled(monkeypatch):
+ register_export_job(account_id = "alice", job_id = "exp-1")
+ result, studio = _call(monkeypatch, {"kind": "export", "id": "exp-1"})
+ assert result["content"][0]["text"] == "No such export job"
+ assert studio.state.calls == []
diff --git a/studio/backend/tests/test_mcp_tools_datasets.py b/studio/backend/tests/test_mcp_tools_datasets.py
new file mode 100644
index 00000000000..6afc58babd4
--- /dev/null
+++ b/studio/backend/tests/test_mcp_tools_datasets.py
@@ -0,0 +1,123 @@
+# 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
+
+from fastapi.responses import JSONResponse
+
+from .mcp_harness import call_to, queries, run_tool
+
+PAYLOADS = {
+ ("GET", "/api/hub/datasets/local"): {
+ "datasets": [
+ {
+ "id": "my-chats",
+ "label": "My chats",
+ "path": "/srv/unsloth/datasets/my-chats",
+ "rows": 120,
+ }
+ ]
+ },
+ ("GET", "/api/hub/datasets/cached"): {
+ "cached": [
+ {
+ "repo_id": "mlabonne/FineTome-100k",
+ "size_bytes": 1024,
+ "cache_path": "/srv/hf/datasets--mlabonne--FineTome-100k",
+ "load_cache_path": "/srv/hf/datasets/mlabonne___fine_tome-100k",
+ }
+ ]
+ },
+ ("POST", "/api/hub/datasets/check-format"): {
+ "requires_manual_mapping": False,
+ "detected_format": "sharegpt",
+ "columns": ["conversations", "source"],
+ "suggested_mapping": {"conversations": "messages"},
+ "preview_samples": [{"conversations": "hi"}],
+ "total_rows": 100000,
+ "warning": None,
+ },
+ ("POST", "/api/hub/datasets/download"): {
+ "repo_id": "mlabonne/FineTome-100k",
+ "state": "running",
+ "accepted": True,
+ "generation": 1,
+ },
+ ("GET", "/api/hub/datasets/download-status"): {
+ "state": "error",
+ "error": "401 gated dataset",
+ "generation": 1,
+ "attempt": 1,
+ },
+}
+
+
+def _call(
+ monkeypatch,
+ args,
+ headers = None,
+):
+ download = JSONResponse(PAYLOADS[("POST", "/api/hub/datasets/download")], status_code = 202)
+ routes = {**PAYLOADS, ("POST", "/api/hub/datasets/download"): download}
+ return run_tool(monkeypatch, routes, "datasets", args, headers = headers)
+
+
+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}],
+ "cached": [{"repo_id": "mlabonne/FineTome-100k", "size_bytes": 1024}],
+ "format": None,
+ "download": None,
+ }
+ assert "/srv" not in json.dumps(result)
+
+
+def test_check_format_sends_the_hub_token_header(monkeypatch):
+ result, studio = _call(
+ monkeypatch,
+ {"action": "check_format", "name": "mlabonne/FineTome-100k", "hf_token": "hf_arg"},
+ )
+ assert result["structuredContent"]["format"] == {
+ "detected_format": "sharegpt",
+ "requires_manual_mapping": False,
+ "columns": ["conversations", "source"],
+ "suggested_mapping": {"conversations": "messages"},
+ "is_image": False,
+ "is_audio": False,
+ "total_rows": 100000,
+ "warning": None,
+ }
+ (_m, _p, headers, body) = call_to(studio, "/api/hub/datasets/check-format")
+ assert headers["x-unsloth-hf-token"] == "hf_arg"
+ assert json.loads(body) == {
+ "dataset_name": "mlabonne/FineTome-100k",
+ "is_vlm": False,
+ "train_split": "train",
+ }
+
+
+def test_download_starts_and_returns_the_202_state(monkeypatch):
+ result, studio = _call(
+ monkeypatch,
+ {"action": "download", "repo_id": "mlabonne/FineTome-100k"},
+ headers = {"X-Unsloth-HF-Token": "hf_h"},
+ )
+ assert result["structuredContent"]["download"] == {
+ "repo_id": "mlabonne/FineTome-100k",
+ "state": "running",
+ "error": None,
+ }
+ (_m, _p, headers, body) = call_to(studio, "/api/hub/datasets/download")
+ assert headers["x-unsloth-hf-token"] == "hf_h"
+ assert json.loads(body) == {"repo_id": "mlabonne/FineTome-100k"}
+
+
+def test_status_reads_the_download_state(monkeypatch):
+ result, studio = _call(monkeypatch, {"action": "status", "repo_id": "a/b"})
+ assert result["structuredContent"]["download"] == {
+ "repo_id": "a/b",
+ "state": "error",
+ "error": "401 gated dataset",
+ }
+ assert queries(studio, "/api/hub/datasets/download-status") == [{"repo_id": "a/b"}]
diff --git a/studio/backend/tests/test_mcp_tools_export.py b/studio/backend/tests/test_mcp_tools_export.py
new file mode 100644
index 00000000000..b72c21beaae
--- /dev/null
+++ b/studio/backend/tests/test_mcp_tools_export.py
@@ -0,0 +1,335 @@
+# 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 asyncio
+import json
+from pathlib import Path
+
+import pytest
+from fastmcp.exceptions import ToolError
+
+from studio_mcp import export_jobs
+
+from .mcp_harness import (
+ OUT,
+ RUN_CHECKPOINTS,
+ fake_studio,
+ register_export_job,
+ run_export_job,
+ run_tool,
+ sequence,
+)
+
+
[email protected](autouse = True)
+def fresh_registry():
+ export_jobs._reset()
+ yield
+ export_jobs._reset()
+
+
+def _get(
+ monkeypatch,
+ args,
+ status = None,
+):
+ return run_tool(monkeypatch, {("GET", "/api/export/status"): status or {}}, "get_job", args)
+
+
[email protected]("job_id", ["job-a", "nope"])
+def test_another_accounts_or_an_unknown_job_is_unknown(monkeypatch, job_id):
+ register_export_job(account_id = "alice-id", job_id = "job-a")
+ result, _studio = _get(monkeypatch, {"kind": "export", "id": job_id})
+ assert result["isError"] is True
+ assert result["content"][0]["text"] == "No such export job"
+ with pytest.raises(ToolError):
+ export_jobs.lookup("owner", "job-a")
+
+
+def test_a_running_job_is_not_settled_from_the_export_status(monkeypatch):
+ # The status names whatever op ran last (here the Export page's); only the job's own call settles it.
+ register_export_job(phase = "exporting")
+ status = {
+ "last_op_seq": 4,
+ "last_op_kind": "export_gguf",
+ "last_op_status": "success",
+ "last_op_output_path": "theirs",
+ "is_export_active": False,
+ }
+ result, studio = _get(monkeypatch, {"kind": "export", "id": "job-a"}, status)
+ assert result["structuredContent"]["status"] == "running"
+ assert result["structuredContent"]["export"]["output"] is None
+ assert studio.state.calls == []
+
+
+def test_a_failed_job_reports_its_error_scrubbed(monkeypatch):
+ export_jobs.finish(
+ register_export_job(), "failed", error = "Disk full writing /srv/exports/x.gguf"
+ )
+ result, _studio = _get(monkeypatch, {"kind": "export", "id": "job-a"})
+ assert result["structuredContent"]["status"] == "failed"
+ assert result["structuredContent"]["error"].startswith("Disk full writing")
+ assert "/srv" not in json.dumps(result)
+
+
+def test_an_absolute_output_outside_exports_is_reduced_to_its_name():
+ from utils.paths import exports_root
+
+ name = export_jobs.output_name
+ assert name(str(Path(exports_root()) / "my-model" / "gguf")) == "my-model/gguf"
+ assert name("/srv/elsewhere/my-gguf") == "my-gguf (outside exports folder)"
+ assert name("C:\\Users\\me\\out\\model") == "model (outside exports folder)"
+ assert name("my-model/gguf") == "my-model/gguf"
+
+
+def test_the_registry_runs_settles_fails_and_cancels_tasks():
+ async def run():
+ async def quick(job):
+ job.phase = "exporting"
+ await asyncio.sleep(0.01)
+
+ async def fails(job):
+ raise ToolError("Checkpoint not found")
+
+ async def hangs(job):
+ await asyncio.Event().wait()
+
+ done = export_jobs.start("owner", "gguf", quick)
+ assert done.task is not None and done.status == "running"
+ failed = export_jobs.start("owner", "gguf", fails)
+ await export_jobs.settle(done, 1.0)
+ stuck = export_jobs.start("owner", "lora", hangs)
+ await export_jobs.settle(stuck, 0.01)
+ # settle never cancels: a job still busy after the wait is left running.
+ assert stuck.status == "running"
+ export_jobs.mark_cancelled(stuck)
+ await asyncio.gather(failed.task, stuck.task, return_exceptions = True)
+ return done, failed, stuck
+
+ done, failed, stuck = asyncio.run(run())
+ assert (done.status, done.phase) == ("completed", "done")
+ assert len(done.job_id) >= 16
+ assert (failed.status, failed.error) == ("failed", "Checkpoint not found")
+ assert stuck.status == "cancelled"
+
+
+def test_without_an_id_only_this_accounts_jobs_are_listed(monkeypatch):
+ register_export_job(job_id = "mine", status = "completed")
+ register_export_job(account_id = "alice-id", job_id = "theirs")
+ result, _studio = _get(monkeypatch, {"kind": "export"})
+ assert result["structuredContent"]["jobs"] == [
+ {"id": "mine", "status": "completed", "progress_percent": None}
+ ]
+
+
+def test_capacity_drops_the_oldest_finished_jobs_first():
+ for index in range(export_jobs.CAPACITY):
+ register_export_job(job_id = f"done-{index}", status = "completed")
+ running = register_export_job(job_id = "running")
+ export_jobs._evict()
+ assert len(export_jobs._jobs) == export_jobs.CAPACITY
+ assert "owner:done-0" not in export_jobs._jobs
+ assert export_jobs.lookup("owner", "running") is running
+
+
+CHECKPOINTS = {**RUN_CHECKPOINTS, "models": RUN_CHECKPOINTS["models"][:1]}
+ARGS = {"checkpoint": "qwen-lora", "format": "gguf", "save_directory": "out"}
+DONE = {
+ "last_op_seq": 6,
+ "last_op_status": "success",
+ "last_op_output_path": "my-gguf",
+ "current_checkpoint": f"{OUT}/qwen-lora",
+}
+EXPORTED = {"success": True, "message": "Exported", "details": {"output_path": "my-gguf"}}
+
+
+def _export_studio(
+ *,
+ export_answer = EXPORTED,
+ statuses = ({"last_op_seq": 5}, DONE),
+ calls = None,
+ op_ids = None,
+):
+ # export_model first checks that no export is running.
+ next_status = sequence({"is_export_active": False, "last_op_seq": 5}, *statuses)
+ calls = [] if calls is None else calls
+ op_ids = [] if op_ids is None else op_ids
+
+ def record(name, answer):
+ def handler(request, body):
+ sent = json.loads(body) if body else None
+ if isinstance(sent, dict) and "op_id" in sent:
+ op_ids.append((name, sent.pop("op_id")))
+ calls.append((name, sent))
+ return answer
+
+ return handler
+
+ def status(request, body):
+ answer = next_status(request, body)
+ # The worker holds whatever the last load put there, unless a test says otherwise.
+ loads = [body["checkpoint_path"] for name, body in calls if name == "load"]
+ if loads and "current_checkpoint" not in answer:
+ answer = {**answer, "current_checkpoint": loads[-1]}
+ return answer
+
+ routes = {
+ ("GET", "/api/models/checkpoints"): CHECKPOINTS,
+ ("GET", "/api/export/status"): status,
+ ("POST", "/api/export/load-checkpoint"): record("load", {"success": True, "message": "Ok"}),
+ }
+ for fmt in ("gguf", "merged", "lora", "base"):
+ routes[("POST", f"/api/export/export/{fmt}")] = record(fmt, export_answer)
+ return fake_studio(routes)
+
+
+def test_an_export_finishing_after_this_one_does_not_become_its_result(monkeypatch):
+ # The Export page's own export ended before the status was read again; the job keeps its answer.
+ theirs = {
+ "last_op_seq": 7,
+ "last_op_kind": "export_gguf",
+ "last_op_status": "error",
+ "last_op_error": "theirs failed",
+ "current_checkpoint": f"{OUT}/qwen-lora",
+ }
+ studio = _export_studio(statuses = [{"last_op_seq": 5}, theirs])
+ _started, job = run_export_job(monkeypatch, studio, {**ARGS, "save_directory": "my-gguf"})
+ out = job["structuredContent"]
+ assert (out["status"], out["error"], out["export"]["output"]) == ("completed", None, "my-gguf")
+
+
+def test_export_returns_a_job_at_once_and_the_job_completes(monkeypatch):
+ calls = []
+ path = f"{OUT}/qwen-lora/checkpoint-30"
+ args = {**ARGS, "checkpoint": "qwen-lora/checkpoint-30", "save_directory": "my-gguf"}
+ args["quantization_method"] = ["Q4_K_M", "Q8_0"]
+ started, job = run_export_job(monkeypatch, _export_studio(calls = calls), args)
+ assert started["structuredContent"]["status"] == "running"
+ assert job["structuredContent"]["status"] == "completed"
+ assert job["structuredContent"]["export"] == {
+ "format": "gguf",
+ "output": "my-gguf",
+ "phase": "done",
+ }
+ assert calls == [
+ ("load", {"checkpoint_path": path, "max_seq_length": 2048}),
+ (
+ "gguf",
+ {
+ "save_directory": "my-gguf",
+ "push_to_hub": False,
+ "private": False,
+ "quantization_method": ["Q4_K_M", "Q8_0"],
+ "expected_checkpoint": path,
+ },
+ ),
+ ]
+ assert OUT not in json.dumps([started, job])
+
+
+def test_an_export_is_refused_while_another_one_runs(monkeypatch):
+ routes = {
+ ("GET", "/api/export/status"): {"is_export_active": True, "active_op_kind": "export_gguf"},
+ ("GET", "/api/models/checkpoints"): CHECKPOINTS,
+ }
+ result, studio = run_tool(monkeypatch, routes, "export_model", ARGS)
+ assert result["isError"] is True
+ assert result["content"][0]["text"].startswith("Another export is running.")
+ assert [c[0] for c in studio.state.calls] == ["GET"]
+
+
[email protected]("race", [False, True])
+def test_an_export_is_refused_while_an_mcp_export_job_runs(monkeypatch, race):
+ from studio_mcp.tools import export as export_tool
+
+ real = export_tool.checkpoints.resolve
+
+ async def racing(caller, name):
+ # Another call registers its job while this one awaits the checkpoint lookup.
+ found = await real(caller, name)
+ register_export_job(account_id = "owner", job_id = "first")
+ return found
+
+ if race:
+ monkeypatch.setattr(export_tool.checkpoints, "resolve", racing)
+ else:
+ register_export_job(account_id = "alice-id", job_id = "first")
+ calls = []
+ result, _job = run_export_job(monkeypatch, _export_studio(calls = calls), ARGS)
+ assert result["content"][0]["text"].startswith("Another export is running.")
+ assert calls == []
+ assert [job.job_id for job in export_jobs._jobs.values()] == ["first"]
+
+
+ "studio_kw,error,names",
+ [
+ # A checkpoint loaded by someone else in between is never exported.
+ (
+ {"statuses": [{"last_op_seq": 5, "current_checkpoint": f"{OUT}/someone-else"}]},
+ "nothing was exported",
+ ["load"],
+ ),
+ (
+ {
+ "export_answer": {
+ "success": False,
+ "message": "llama.cpp converter missing at /srv/x",
+ }
+ },
+ "llama.cpp converter missing at",
+ ["load", "gguf"],
+ ),
+ ],
+)
+def test_a_failed_step_fails_the_job_without_leaking_paths(monkeypatch, studio_kw, error, names):
+ calls = []
+ started, job = run_export_job(monkeypatch, _export_studio(calls = calls, **studio_kw), ARGS)
+ assert started["isError"] is False
+ assert job["structuredContent"]["status"] == "failed"
+ assert error in job["structuredContent"]["error"]
+ assert [name for name, _ in calls] == names
+ assert "/srv" not in json.dumps([started, job])
+
+
+ "extra,expected",
+ [
+ ({"format": "merged"}, {}),
+ ({"format": "lora"}, {}),
+ ({"format": "base"}, {}),
+ ({"imatrix": True}, {"imatrix": True}),
+ (
+ {"format": "merged", "push_to_hub": True, "repo_id": "me/m", "hf_token": "hf_x"},
+ {"hf_token": "hf_x", "repo_id": "me/m"},
+ ),
+ ],
+)
+def test_each_format_reaches_its_route_with_its_body(monkeypatch, extra, expected):
+ calls = []
+ run_export_job(
+ monkeypatch, _export_studio(calls = calls), {**ARGS, **extra, "load_in_4bit": False}
+ )
+ fmt = extra.get("format", "gguf")
+ assert [name for name, _ in calls] == ["load", fmt]
+ load = {"checkpoint_path": f"{OUT}/qwen-lora", "max_seq_length": 2048, "load_in_4bit": False}
+ assert calls[0][1] == {**load, **({"hf_token": "hf_x"} if "hf_token" in extra else {})}
+ assert calls[1][1].items() >= expected.items()
+ assert ("quantization_method" in calls[1][1]) == (fmt == "gguf")
+
+
+def test_an_unknown_checkpoint_lists_the_names(monkeypatch):
+ started, _job = run_export_job(monkeypatch, _export_studio(), {**ARGS, "checkpoint": "nope"})
+ assert started["isError"] is True
+ assert (
+ started["content"][0]["text"]
+ == "No checkpoint named nope. Available: qwen-lora, qwen-lora/checkpoint-30"
+ )
+
+
+def test_each_step_carries_its_own_op_id(monkeypatch):
+ # cancel(kind="export", id=...) sends the step's op id, so only this job's own op is ever stopped.
+ op_ids = []
+ started, _job = run_export_job(monkeypatch, _export_studio(op_ids = op_ids), ARGS)
+ job_id = started["structuredContent"]["job_id"]
+ assert op_ids == [("load", f"mcp-{job_id}-load"), ("gguf", f"mcp-{job_id}-export")]
diff --git a/studio/backend/tests/test_mcp_tools_images.py b/studio/backend/tests/test_mcp_tools_images.py
new file mode 100644
index 00000000000..29f07229b0d
--- /dev/null
+++ b/studio/backend/tests/test_mcp_tools_images.py
@@ -0,0 +1,183 @@
+# 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 base64
+import json
+
+import pytest
+
+from fastapi.responses import Response
+
+from studio_mcp.media import INLINE_CAP
+
+from .mcp_harness import (
+ JPEG,
+ PNG,
+ PNG_URL,
+ REMOTE,
+ WEBP,
+ bodies,
+ call_with_progress,
+ data_url,
+ fake_studio,
+ fast_polls, # noqa: F401 (fixture)
+ queries,
+ run_tool,
+ slow,
+)
+
+
+def _image(image_id, side, seed):
+ return {
+ "id": image_id,
+ "url": f"/api/inference/images/gallery/{image_id}/file",
+ "prompt": "a red fox",
+ "width": side,
+ "height": side,
+ "steps": 4,
+ "guidance": 0.0,
+ "seed": seed,
+ "model": "black-forest-labs/FLUX.1-schnell",
+ }
+
+
+GENERATED = {"images": [_image("img-small", 512, 1), _image("img-large", 1024, 2)]}
+
+
+def _png(request, body):
+ return Response(PNG, media_type = "image/png")
+
+
+def _webp(request, body):
+ assert request.query_params.get("thumb") == "1024"
+ return Response(WEBP, media_type = "image/webp")
+
+
+PAYLOADS = {
+ ("POST", "/api/inference/images/generate"): GENERATED,
+ ("GET", "/api/inference/images/generate-progress"): {
+ "active": True,
+ "step": 2,
+ "total_steps": 4,
+ "fraction": 0.5,
+ },
+}
+
+
+GALLERY = "/api/inference/images/gallery"
+GENERATE = ("POST", "/api/inference/images/generate")
+
+
+def _studio(overrides = None):
+ return fake_studio(
+ {
+ **PAYLOADS,
+ ("GET", f"{GALLERY}/img-small/file"): _png,
+ ("GET", f"{GALLERY}/img-large/file"): _webp,
+ **(overrides or {}),
+ }
+ )
+
+
+def _generate(
+ monkeypatch,
+ args,
+ overrides = None,
+ **client,
+):
+ return run_tool(monkeypatch, _studio(overrides), "generate_image", args, **client)
+
+
+def test_txt2img_returns_ids_urls_and_inline_images(monkeypatch):
+ result, studio = _generate(
+ monkeypatch, {"prompt": "a red fox", "width": 512, "steps": 4}, **REMOTE
+ )
+ remote = "http://192.168.1.20:8888" + GALLERY
+ assert result["structuredContent"] == {
+ "images": [
+ {"id": i, "url": f"{remote}/{i}/file", "width": side, "height": side, "seed": seed}
+ for i, side, seed in (("img-small", 512, 1), ("img-large", 1024, 2))
+ ]
+ }
+ content = result["content"]
+ assert json.loads(content[0]["text"]) == result["structuredContent"]
+ assert [c["type"] for c in content[1:]] == ["image", "image", "resource_link"]
+ assert base64.b64decode(content[1]["data"]) == PNG
+ assert content[1]["mimeType"] == "image/png"
+ assert base64.b64decode(content[2]["data"]) == WEBP
+ assert content[2]["mimeType"] == "image/webp"
+ assert content[3]["uri"] == f"{remote}/img-large/file"
+ assert bodies(studio, "/api/inference/images/generate") == [
+ {"prompt": "a red fox", "width": 512, "steps": 4}
+ ]
+ # A large image is never fetched in full; gallery files are fetched as the caller.
+ assert queries(studio, f"{GALLERY}/img-large/file") == [{"thumb": "1024"}]
+ fetches = [c[2] for c in studio.state.calls if "/gallery/" in c[1]]
+ assert len(fetches) == 2
+ for headers in fetches:
+ assert headers["authorization"] == "Bearer sk-unsloth-test"
+ assert headers["host"] == "unsloth-mcp.invalid"
+
+
+def test_a_thumbnail_studio_could_not_make_keeps_its_png_type(monkeypatch):
+ # The gallery route answers a failed thumbnail with the original PNG.
+ result, _studio = _generate(
+ monkeypatch, {"prompt": "x"}, {("GET", f"{GALLERY}/img-large/file"): _png}
+ )
+ previews = [c for c in result["content"] if c["type"] == "image"]
+ assert previews[-1]["mimeType"] == "image/png"
+
+
+def test_a_full_image_over_the_cap_falls_back_to_the_thumbnail(monkeypatch):
+ def huge(request, body):
+ if request.query_params.get("thumb"):
+ return Response(WEBP, media_type = "image/webp")
+ return Response(PNG + b"\x00" * INLINE_CAP, media_type = "image/png")
+
+ overrides = {
+ GENERATE: {"images": [_image("img-small", 512, 7)]},
+ ("GET", f"{GALLERY}/img-small/file"): huge,
+ }
+ result, _studio = _generate(monkeypatch, {"prompt": "x"}, overrides)
+ assert [c["type"] for c in result["content"][1:]] == ["image", "resource_link"]
+ assert result["content"][1]["mimeType"] == "image/webp"
+
+
+def test_progress_is_reported_while_generating(monkeypatch, fast_polls):
+ studio = _studio({GENERATE: slow(GENERATED, 0.2)})
+ progress, _result = call_with_progress(
+ monkeypatch, studio, "generate_image", {"prompt": "x"}, "g"
+ )
+ assert progress and progress[0]["progress"] == 0.5
+ assert progress[0]["message"] == "Step 2 of 4"
+
+
+PNG_DATA = data_url(PNG, "image/png")
+
+
+ "args,expected",
+ [
+ (
+ {
+ "prompt": "make it night",
+ "init_image": {"gallery_id": "src-1"},
+ "mask_image": PNG_URL,
+ "reference_images": [{"data_url": data_url(JPEG, "image/jpeg")}],
+ "workflow": "edit",
+ "strength": 0.6,
+ "allow_oversized": True,
+ },
+ {
+ "init_image": PNG_DATA,
+ "mask_image": PNG_DATA,
+ "reference_images": [data_url(JPEG, "image/jpeg")],
+ },
+ ),
+ ({"prompt": "sharper", "init_image": PNG_URL, "upscale": 2}, {"init_image": PNG_DATA}),
+ ],
+)
+def test_edit_and_upscale_inputs_land_in_their_body_fields(monkeypatch, args, expected):
+ result, studio = _generate(monkeypatch, args, {("GET", f"{GALLERY}/src-1/file"): _png})
+ assert result["isError"] is False
+ assert bodies(studio, "/api/inference/images/generate") == [{**args, **expected}]
diff --git a/studio/backend/tests/test_mcp_tools_loading.py b/studio/backend/tests/test_mcp_tools_loading.py
new file mode 100644
index 00000000000..56b1dde712e
--- /dev/null
+++ b/studio/backend/tests/test_mcp_tools_loading.py
@@ -0,0 +1,454 @@
+# 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 fastapi.responses import Response
+
+from .mcp_harness import (
+ DEFERRED,
+ WHISPER,
+ bodies,
+ call_to,
+ call_with_progress,
+ fake_studio,
+ fast_polls, # noqa: F401 (fixture)
+ queries,
+ run_tool,
+ sequence,
+ slow,
+ stt_state,
+)
+
+LLM = "unsloth/Llama-3.2-1B-Instruct-GGUF"
+LOADED = {
+ "status": "loaded",
+ "model": LLM,
+ "display_name": "Llama 3.2 1B",
+ "is_gguf": True,
+ "inference": {"temperature": 0.7},
+ "evicted": ["unsloth/Qwen3-0.6B"],
+}
+STATUS = {"loaded": [LLM], "serving": [LLM], "serving_checkpoints": ["/srv/models/llama.gguf"]}
+EMPTY_STATUS = {"loaded": [], "serving": [], "serving_checkpoints": []}
+LOAD = ("POST", "/api/inference/load")
+STT = "/api/inference/audio/stt"
+STATUS_ROUTE = ("GET", "/api/inference/status")
+
+PAYLOADS = {
+ LOAD: LOADED,
+ ("GET", "/api/inference/load-progress"): {"phase": "mmap", "fraction": 0.5},
+ ("GET", "/api/models/download-progress"): {
+ "progress": 0.25,
+ "downloaded_bytes": 1,
+ "expected_bytes": 4,
+ },
+ ("POST", "/api/inference/unload"): {"status": "unloaded", "model": LLM},
+ STATUS_ROUTE: STATUS,
+}
+
+
+# tts / audio load through the LLM route but report the kind asked for. STATUS serves LLM
+# before and after, so only the route's own evicted list counts.
[email protected]("kind", [None, "tts", "audio"])
+def test_load_sends_the_body_and_reports_the_result(monkeypatch, kind):
+ args = {"model": LLM, "variant": "Q4_K_M", **({"kind": kind} if kind else {})}
+ result, studio = run_tool(monkeypatch, PAYLOADS, "load_model", args)
+ assert result["structuredContent"] == {
+ "kind": kind or "llm",
+ "model": LLM,
+ "loaded": True,
+ "display_name": "Llama 3.2 1B",
+ "evicted": ["unsloth/Qwen3-0.6B"],
+ }
+ assert bodies(studio, "/api/inference/load") == [
+ {"model_path": LLM, "load_in_4bit": True, "max_seq_length": 0, "gguf_variant": "Q4_K_M"}
+ ]
+
+
+ "kind,route_evicted,before,after,expected",
+ [
+ # An audio engine switch unloads the chat model without the route saying so.
+ (
+ "tts",
+ [],
+ {**STATUS, "serving": ["unsloth/Qwen3-0.6B-GGUF"]},
+ EMPTY_STATUS,
+ ["unsloth/Qwen3-0.6B-GGUF"],
+ ),
+ # The route keys a dropped GGUF as repo:variant while status serves the bare repo id.
+ (
+ "llm",
+ ["unsloth/Qwen3-8B-GGUF:Q4_K_M"],
+ {**STATUS, "serving": [LLM, "unsloth/Qwen3-8B-GGUF"]},
+ STATUS,
+ ["unsloth/Qwen3-8B-GGUF:Q4_K_M"],
+ ),
+ ],
+)
+def test_evicted_merges_the_route_list_and_status(
+ monkeypatch, kind, route_evicted, before, after, expected
+):
+ routes = {
+ **PAYLOADS,
+ LOAD: {**LOADED, "evicted": route_evicted},
+ STATUS_ROUTE: sequence(before, after),
+ }
+ result, _studio = run_tool(monkeypatch, routes, "load_model", {"model": LLM, "kind": kind})
+ assert result["structuredContent"]["evicted"] == expected
+
+
+ "args,headers,token",
+ [
+ ({"hf_token": "hf_param", "load_in_4bit": False}, None, "hf_param"),
+ ({}, {"X-Unsloth-HF-Token": "hf_header"}, "hf_header"),
+ ],
+)
+def test_the_hub_token_goes_in_the_body_not_the_header(monkeypatch, args, headers, token):
+ _result, studio = run_tool(
+ monkeypatch, PAYLOADS, "load_model", {"model": LLM, **args}, headers = headers
+ )
+ (_m, _p, sent_headers, body) = call_to(studio, "/api/inference/load")
+ assert json.loads(body)["hf_token"] == token
+ assert json.loads(body)["load_in_4bit"] is ("load_in_4bit" not in args)
+ assert "x-unsloth-hf-token" not in sent_headers
+
+
[email protected]("deferred", DEFERRED)
+def test_a_padded_deferred_error_is_a_tool_error(monkeypatch, deferred):
+ padded = b" " * 40 + json.dumps({"_deferred_error": deferred}).encode()
+ routes = {**PAYLOADS, LOAD: Response(padded, media_type = "application/json")}
+ result, _studio = run_tool(monkeypatch, routes, "load_model", {"model": LLM})
+ assert result["isError"] is True
+ assert deferred["detail"] in result["content"][0]["text"]
+ assert f"(HTTP {deferred['status_code']})" in result["content"][0]["text"]
+
+
+def test_progress_is_reported_while_the_load_runs(monkeypatch, fast_polls):
+ studio = fake_studio({**PAYLOADS, LOAD: slow(LOADED, 0.3)})
+ progress, result = call_with_progress(monkeypatch, studio, "load_model", {"model": LLM}, "p1")
+ assert progress, result
+ assert progress[0]["progressToken"] == "p1"
+ assert progress[0]["progress"] == 0.5
+ assert "mmap" in progress[0]["message"]
+ assert result["structuredContent"]["loaded"] is True
+
+
+def test_download_progress_is_used_before_the_load_starts(monkeypatch, fast_polls):
+ routes = {
+ **PAYLOADS,
+ LOAD: slow(LOADED, 0.2),
+ ("GET", "/api/inference/load-progress"): {"phase": None, "fraction": 0.0},
+ }
+ _result, studio = run_tool(monkeypatch, routes, "load_model", {"model": LLM})
+ downloads = [c for c in studio.state.calls if c[1] == "/api/models/download-progress"]
+ assert downloads
+ assert all(c[2].get("x-unsloth-hf-token") is None for c in downloads)
+
+
+# Without a model the serving one is unloaded; a public id maps to its checkpoint. An unload
+# that matched nothing, or left the model resident (STATUS still serves LLM), is not success.
+ "args,statuses,model,sent",
+ [
+ ({}, (STATUS, EMPTY_STATUS), LLM, [{"model_path": "/srv/models/llama.gguf"}]),
+ ({"model": LLM}, (STATUS, EMPTY_STATUS), LLM, [{"model_path": "/srv/models/llama.gguf"}]),
+ ({"model": "unsloth/not-loaded"}, (STATUS,), "unsloth/not-loaded", None),
+ ({"model": LLM}, (STATUS,), LLM, None),
+ ({}, (EMPTY_STATUS,), None, []),
+ ],
+)
+def test_unload_picks_the_serving_checkpoint_and_checks_the_result(
+ monkeypatch, args, statuses, model, sent
+):
+ routes = {**PAYLOADS, STATUS_ROUTE: sequence(*statuses)}
+ result, studio = run_tool(monkeypatch, routes, "unload_model", args)
+ assert result["structuredContent"] == {"kind": "llm", "model": model, "unloaded": bool(sent)}
+ if sent is not None:
+ assert bodies(studio, "/api/inference/unload") == sent
+
+
+FLUX_GGUF = "city96/FLUX.1-schnell-gguf"
+LTX = "Lightricks/LTX-Video"
+QUANTS = ("Q4_K_S", "Q8_0")
+READY = {"phase": "ready"}
+
+
+def _media_studio(
+ kind,
+ *,
+ progress = ({"phase": "ready"},),
+ statuses = ({"loaded": False},),
+ load_answer = None,
+ plan = None,
+ chat_statuses = None,
+):
+ """``progress`` and ``statuses`` are consumed in order; the last one repeats."""
+ prefix = "/api/inference/images" if kind == "image" else "/api/inference/video"
+ return fake_studio(
+ {
+ **({STATUS_ROUTE: sequence(*chat_statuses)} if chat_statuses else {}),
+ ("GET", "/api/hub/gguf-variants"): {
+ "repo_id": FLUX_GGUF,
+ "default_variant": "Q4_K_S",
+ "variants": [{"filename": f"flux1-schnell-{q}.gguf", "quant": q} for q in QUANTS],
+ },
+ ("POST", f"{prefix}/download-plan"): plan or {"entries": [], "plan_failed": False},
+ ("POST", f"{prefix}/load"): load_answer or {"loaded": False},
+ ("GET", f"{prefix}/load-progress"): sequence(*progress),
+ ("GET", f"{prefix}/status"): sequence(*statuses),
+ ("POST", f"{prefix}/unload"): {"loaded": False},
+ }
+ )
+
+
+# No variant named: the default is used, and the hf_token argument reaches the (gated) lookup.
+ "extra,filename",
+ [
+ ({"variant": "Q8_0"}, "flux1-schnell-Q8_0.gguf"),
+ ({"hf_token": "hf_arg"}, "flux1-schnell-Q4_K_S.gguf"),
+ ],
+)
+def test_a_gguf_image_repo_sends_its_gguf_filename(monkeypatch, fast_polls, extra, filename):
+ studio = _media_studio(
+ "image",
+ progress = [{"phase": "downloading", "bytes_downloaded": 1, "bytes_total": 2}, READY],
+ statuses = [{"loaded": True, "repo_id": FLUX_GGUF, "family": "flux"}],
+ )
+ result, _studio = run_tool(
+ monkeypatch, studio, "load_model", {"model": FLUX_GGUF, "kind": "image", **extra}
+ )
+ loaded = {"kind": "image", "model": FLUX_GGUF, "loaded": True, "display_name": None}
+ assert result["structuredContent"] == {**loaded, "evicted": []}
+ expected = {"model_path": FLUX_GGUF, "gguf_filename": filename, "model_kind": "gguf"}
+ expected.update({"hf_token": extra["hf_token"]} if "hf_token" in extra else {})
+ assert bodies(studio, "/api/inference/images/download-plan") == [expected]
+ assert bodies(studio, "/api/inference/images/load") == [expected]
+ lookup_token = call_to(studio, "/api/hub/gguf-variants")[2].get("x-unsloth-hf-token")
+ assert lookup_token == extra.get("hf_token")
+
+
+def test_a_plan_entry_supplies_the_checkpoint_file(monkeypatch, fast_polls):
+ entry = {"repo_id": "a/b", "files": [], "bytes": 1, "checkpoint": True}
+ plan = {"entries": [{**entry, "gguf_filename": "model.safetensors"}]}
+ studio = _media_studio("image", statuses = [{"loaded": True, "repo_id": "a/b"}], plan = plan)
+ run_tool(monkeypatch, studio, "load_model", {"model": "a/b", "kind": "image"})
+ assert bodies(studio, "/api/inference/images/load") == [
+ {"model_path": "a/b", "gguf_filename": "model.safetensors"}
+ ]
+ assert [c for c in studio.state.calls if c[1] == "/api/hub/gguf-variants"] == []
+
+
+PREVIOUS = {"loaded": True, "repo_id": "old/model"}
+AB = {"model": "a/b", "kind": "image"}
+DISK_FULL = [{"phase": "downloading"}, {"phase": "error", "error": "Out of disk space"}]
+
+
+ "args,studio_kwargs,message",
+ [
+ ({**AB, "model": FLUX_GGUF, "variant": "Q2_K"}, {}, "Q2_K"),
+ (
+ AB,
+ {"plan": {"entries": [], "incompatible_reason": "Needs a CUDA GPU"}},
+ "Needs a CUDA GPU",
+ ),
+ (AB, {"progress": DISK_FULL}, "Out of disk space"),
+ # The previous model in the load answer is not success.
+ (
+ {**AB, "model": "new/m"},
+ {"statuses": [PREVIOUS], "load_answer": PREVIOUS},
+ "loading new/m",
+ ),
+ ({"model": LTX, "kind": "video"}, {"progress": [{}], "statuses": [PREVIOUS]}, "stopped"),
+ ],
+)
+def test_a_media_load_failure_is_a_tool_error(
+ monkeypatch, fast_polls, args, studio_kwargs, message
+):
+ studio = _media_studio(args["kind"], **studio_kwargs)
+ result, _studio = run_tool(monkeypatch, studio, "load_model", args)
+ assert result["isError"] is True
+ assert message in result["content"][0]["text"]
+ if "variant" in args:
+ assert bodies(studio, "/api/inference/images/load") == []
+
+
+def test_a_previous_model_answer_then_the_new_one_loads(monkeypatch, fast_polls):
+ studio = _media_studio(
+ "image",
+ progress = [{"phase": None}, {"phase": "downloading"}, READY],
+ statuses = [PREVIOUS, {"loaded": True, "repo_id": "new/model"}],
+ load_answer = PREVIOUS,
+ )
+ result, _studio = run_tool(
+ monkeypatch, studio, "load_model", {"model": "new/model", "kind": "image"}
+ )
+ assert result["structuredContent"]["model"] == "new/model"
+
+
[email protected]("kind,model", [("image", FLUX_GGUF), ("video", LTX)])
+def test_a_media_load_reports_the_chat_model_the_gpu_arbiter_unloaded(
+ monkeypatch, fast_polls, kind, model
+):
+ studio = _media_studio(
+ kind,
+ statuses = [{"loaded": True, "repo_id": model}],
+ chat_statuses = [STATUS, EMPTY_STATUS],
+ )
+ result, _studio = run_tool(monkeypatch, studio, "load_model", {"model": model, "kind": kind})
+ assert result["structuredContent"]["evicted"] == [LLM]
+
+
+def test_video_progress_uses_its_own_field_names(monkeypatch, fast_polls):
+ studio = _media_studio(
+ "video",
+ progress = [
+ {"phase": "downloading", "downloaded_bytes": 1, "expected_bytes": 4},
+ {"phase": "finalizing", "downloaded_bytes": 4, "expected_bytes": 4},
+ {"phase": "ready"},
+ ],
+ statuses = [{"loaded": True, "repo_id": LTX}],
+ )
+ progress, result = call_with_progress(
+ monkeypatch, studio, "load_model", {"model": LTX, "kind": "video"}
+ )
+ assert [p["progress"] for p in progress] == [0.25, 1.0]
+ assert progress[0]["message"] == "Downloading"
+ assert result["structuredContent"]["model"] == LTX
+ assert bodies(studio, "/api/inference/video/load") == [{"model_path": LTX}]
+
+
+ "kind,statuses,model",
+ [
+ ("image", [{"loaded": True, "repo_id": LTX}], LTX),
+ ("video", [{"loaded": True, "repo_id": LTX}], LTX),
+ ("image", [{"loaded": False}], None),
+ ],
+)
+def test_media_unload_takes_no_body(monkeypatch, kind, statuses, model):
+ studio = _media_studio(kind, statuses = statuses)
+ result, _studio = run_tool(monkeypatch, studio, "unload_model", {"kind": kind})
+ assert result["structuredContent"] == {
+ "kind": kind,
+ "model": model,
+ "unloaded": model is not None,
+ }
+ unloads = [c[3] for c in studio.state.calls if c[1].endswith("/unload")]
+ assert unloads == ([b""] if model else [])
+
+
+def _stt_studio(statuses, *, download = None):
+ return fake_studio(
+ {
+ ("GET", f"{STT}/status"): sequence(*statuses),
+ ("POST", f"{STT}/download"): download
+ or {"downloading": True, "model": WHISPER, "download_id": "d1"},
+ ("POST", f"{STT}/load"): {"loaded_model": WHISPER, "device": "cuda"},
+ ("POST", f"{STT}/unload"): {"loaded_model": None, "device": None},
+ }
+ )
+
+
+# The token rides the download header (never the body), from the header or the argument.
+ "headers,extra", [({"X-Unsloth-HF-Token": "hf_h"}, {}), (None, {"hf_token": "hf_h"})]
+)
+def test_stt_downloads_then_loads_in_order(monkeypatch, fast_polls, headers, extra):
+ progress = {"downloading": True, "model": WHISPER, "bytes_done": 1, "bytes_total": 2}
+ done = {"downloading": False, "completed_download_ids": ["d1"]}
+ studio = _stt_studio(
+ [
+ {"transformers": stt_state()},
+ {"transformers": stt_state(download = progress)},
+ {"transformers": stt_state(downloaded = [WHISPER], download = done)},
+ ]
+ )
+ result, _studio = run_tool(
+ monkeypatch,
+ studio,
+ "load_model",
+ {"model": WHISPER, "kind": "stt", **extra},
+ headers = headers,
+ )
+ assert result["structuredContent"]["model"] == WHISPER
+ assert [(m, p) for m, p, _h, _b in studio.state.calls] == [
+ ("GET", f"{STT}/status"),
+ ("POST", f"{STT}/download"),
+ ("GET", f"{STT}/status"),
+ ("GET", f"{STT}/status"),
+ ("POST", f"{STT}/load"),
+ ]
+ expected = [{"model": WHISPER, "engine": "transformers"}]
+ assert bodies(studio, f"{STT}/download") == expected
+ assert call_to(studio, f"{STT}/download")[2]["x-unsloth-hf-token"] == "hf_h"
+ assert bodies(studio, f"{STT}/load") == expected
+
+
+def test_a_downloaded_stt_model_loads_straight_away(monkeypatch):
+ q5 = "whisper-small-q5"
+ studio = _stt_studio([{"gguf": {**stt_state(downloaded = [q5]), "models": [q5]}}])
+ result, _studio = run_tool(monkeypatch, studio, "load_model", {"model": q5, "kind": "stt"})
+ assert result["isError"] is False
+ assert [c[1] for c in studio.state.calls if c[0] == "POST"] == [f"{STT}/load"]
+ assert bodies(studio, f"{STT}/load") == [{"model": q5, "engine": "gguf"}]
+
+
+def test_a_requested_variant_is_downloaded_even_when_another_is_cached(monkeypatch, fast_polls):
+ moon = "audio-cpp/audio.cpp-gguf/Moonshine-Streaming-GGUF"
+ done = {"downloading": False, "completed_download_ids": ["d1"]}
+ studio = _stt_studio(
+ [
+ {"audiocpp": {**stt_state(downloaded = [moon]), "models": [moon]}},
+ {"audiocpp": {**stt_state(downloaded = [moon, f"{moon}:small/Q8_0"]), "download": done}},
+ ]
+ )
+ args = {"model": moon, "kind": "stt", "variant": "small/Q8_0"}
+ result, _studio = run_tool(monkeypatch, studio, "load_model", args)
+ assert result["isError"] is False
+ expected = [{"model": moon, "engine": "audiocpp", "gguf_variant": "small/Q8_0"}]
+ assert bodies(studio, f"{STT}/download") == expected
+ assert bodies(studio, f"{STT}/load") == expected
+
+
+def test_a_failed_download_never_loads(monkeypatch, fast_polls):
+ failed = {"downloading": False, "error": "401 gated repo"}
+ studio = _stt_studio(
+ [{"transformers": stt_state()}, {"transformers": stt_state(download = failed)}]
+ )
+ result, _studio = run_tool(monkeypatch, studio, "load_model", {"model": WHISPER, "kind": "stt"})
+ assert result["isError"] is True
+ assert "401 gated repo" in result["content"][0]["text"]
+ assert [c for c in studio.state.calls if c[1].endswith("/load")] == []
+
+
+ "statuses,args,model,query",
+ [
+ (
+ [
+ {"transformers": stt_state(), "mtmd": stt_state(loaded = "qwen3-asr")},
+ {"transformers": stt_state(), "mtmd": stt_state()},
+ ],
+ {},
+ "qwen3-asr",
+ {"engine": "mtmd", "model": "qwen3-asr", "wait": "true"},
+ ),
+ ([{"transformers": stt_state(loaded = WHISPER)}], {"model": "other"}, "other", None),
+ ],
+)
+def test_stt_unload_names_the_engine_and_model_in_the_query(
+ monkeypatch, statuses, args, model, query
+):
+ studio = _stt_studio(statuses)
+ result, _studio = run_tool(monkeypatch, studio, "unload_model", {"kind": "stt", **args})
+ unloaded = query is not None
+ assert result["structuredContent"] == {"kind": "stt", "model": model, "unloaded": unloaded}
+ assert queries(studio, f"{STT}/unload") == ([query] if query else [])
+ unloads = [c[3] for c in studio.state.calls if c[1].endswith("/unload")]
+ assert unloads == ([b""] if unloaded else [])
diff --git a/studio/backend/tests/test_mcp_tools_media.py b/studio/backend/tests/test_mcp_tools_media.py
new file mode 100644
index 00000000000..b9a5a252e5c
--- /dev/null
+++ b/studio/backend/tests/test_mcp_tools_media.py
@@ -0,0 +1,100 @@
+# 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 fastmcp.exceptions import ToolError
+from pydantic import ValidationError
+
+from studio_mcp import inputs, media
+from studio_mcp.inputs import ImageInput
+from studio_mcp.outputs import ToolOutput
+
+from .mcp_harness import PNG, file_spy, make_caller # noqa: F401 (file_spy is a fixture)
+
+LAN = {"public_base": "http://192.168.1.20:8888"}
+TUNNEL = "https://abc-def.trycloudflare.com"
+CLIP = "/v1/audio/gallery/clip-1/file"
+
+
+ "caller,route_url,expected",
+ [
+ # Built from the outer request, never the host the forwarder used.
+ (LAN, CLIP, f"http://192.168.1.20:8888{CLIP}"),
+ (LAN, f"http://unsloth-mcp.invalid{CLIP}", f"http://192.168.1.20:8888{CLIP}"),
+ (LAN, f"http://unsloth-mcp.invalid:80{CLIP}", f"http://192.168.1.20:8888{CLIP}"),
+ (
+ {},
+ "/api/inference/images/gallery/i/file?thumb=1024",
+ "http://127.0.0.1:8888/api/inference/images/gallery/i/file?thumb=1024",
+ ),
+ (
+ {"public_base": "http://abc-def.trycloudflare.com", "cloudflare_url": TUNNEL},
+ "/v1/videos/v1",
+ f"{TUNNEL}/v1/videos/v1",
+ ),
+ # Another host keeps its own scheme while a tunnel is up.
+ ({"cloudflare_url": TUNNEL}, "/v1/videos/v1", "http://127.0.0.1:8888/v1/videos/v1"),
+ (
+ {"public_base": "http://127.0.0.1:8888/studio"},
+ CLIP,
+ f"http://127.0.0.1:8888/studio{CLIP}",
+ ),
+ ],
+)
+def test_public_url(caller, route_url, expected):
+ assert media.public_url(make_caller(**caller), route_url) == expected
+
+
+ "route_url", ["/api/auth/api-keys", "/srv/gallery/x.png", "file:///srv/x.png"]
+)
+def test_non_media_links_are_refused(route_url):
+ with pytest.raises(ToolError):
+ media.public_url(make_caller(), route_url)
+
+
+def test_gallery_paths_quote_the_id():
+ assert media.image_gallery_path("a/b") == "/api/inference/images/gallery/a%2Fb/file"
+ assert media.image_gallery_path("a", thumb = True).endswith("/a/file?thumb=1024")
+ assert media.audio_gallery_path("c 1") == "/v1/audio/gallery/c%201/file"
+
+
+def test_a_media_result_carries_the_output_as_json_text_first():
+ class Out(ToolOutput):
+ id: str
+
+ result = media.media_result([media.image_content(b"png", "image/png")], Out(id = "a"))
+ assert [c.type for c in result.content] == ["text", "image"]
+ assert json.loads(result.content[0].text) == result.structured_content == {"id": "a"}
+
+
+ "fields",
+ [
+ {},
+ {"path": "/a", "data_url": "data:image/png;base64,AA=="},
+ {"gallery_id": "a", "path": "/a"},
+ ],
+)
+def test_an_image_input_takes_exactly_one_source(fields):
+ with pytest.raises(ValidationError):
+ ImageInput(**fields)
+
+
+def test_an_oversized_file_is_refused_before_it_is_read(file_spy, tmp_path):
+ path = tmp_path / "mcp-input-big.png"
+ path.write_bytes(PNG + b"\x00" * 2048)
+ with pytest.raises(ToolError, match = "larger than"):
+ inputs.read_local(make_caller(), str(path), max_bytes = 1024)
+ assert {kind for kind, _ in file_spy} == {"stat"}
+
+
+def test_oversized_inline_data_is_refused_before_decoding(monkeypatch):
+ decoded = []
+ monkeypatch.setattr(inputs.base64, "b64decode", lambda *a, **k: decoded.append(a) or b"")
+ with pytest.raises(ToolError, match = "larger than"):
+ inputs.decode_base64("A" * 2000, 1024, "data_url")
+ assert decoded == []
diff --git a/studio/backend/tests/test_mcp_tools_models.py b/studio/backend/tests/test_mcp_tools_models.py
new file mode 100644
index 00000000000..111f034a48c
--- /dev/null
+++ b/studio/backend/tests/test_mcp_tools_models.py
@@ -0,0 +1,154 @@
+# 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 pytest
+
+from .mcp_harness import run_tool
+
+CATALOG = {
+ "object": "list",
+ "data": [
+ {
+ "id": "unsloth/Llama-3.2-1B-Instruct-GGUF",
+ "loaded": True,
+ "quant": "Q4_K_M",
+ "context_length": 8192,
+ "display_name": "Llama 3.2 1B",
+ },
+ {"id": "unsloth/Qwen3-0.6B", "object": "model", "loaded": False},
+ {
+ "id": "black-forest-labs/FLUX.1-schnell",
+ "task": "text-to-image",
+ "loaded": False,
+ "quant": "Q8_0",
+ },
+ {"id": "Lightricks/LTX-Video", "task": "text-to-video", "loaded": True},
+ {"id": "openai/whisper-small", "task": "automatic-speech-recognition", "loaded": False},
+ {
+ "id": "unsloth/orpheus-3b",
+ "task": "text-to-speech",
+ "loaded": False,
+ "audio_workflows": ["speak", "clone"],
+ },
+ {
+ "id": "audio-separator/htdemucs",
+ "task": "audio-to-audio",
+ "loaded": False,
+ "audio_workflows": ["separate"],
+ },
+ ],
+}
+LOADED = {
+ "object": "list",
+ "data": [{"id": "unsloth/Llama-3.2-1B-Instruct-GGUF", "context_length": 8192, "loaded": True}],
+}
+CONFIG = {
+ "id": "unsloth/Qwen3-0.6B",
+ "display_name": "Qwen3 0.6B",
+ "config": {
+ "training": {
+ "max_seq_length": 2048,
+ "learning_rate": "2e-4",
+ "packing": False,
+ "output_dir": "/srv/out",
+ },
+ "lora": {"lora_r": 16, "target_modules": ["q_proj"]},
+ "inference": {"temperature": 0.7},
+ },
+}
+
+PAYLOADS = {
+ ("GET", "/v1/models"): CATALOG,
+ ("GET", "/api/inference/loaded-models"): LOADED,
+ ("GET", "/api/models/config/unsloth/Qwen3-0.6B"): CONFIG,
+}
+
+
+def _list(
+ monkeypatch,
+ args = None,
+ headers = None,
+ routes = PAYLOADS,
+):
+ return run_tool(monkeypatch, routes, "list_models", args or {}, headers = headers)
+
+
+ "kind,expected",
+ [
+ ("llm", {"unsloth/Llama-3.2-1B-Instruct-GGUF", "unsloth/Qwen3-0.6B"}),
+ ("image", {"black-forest-labs/FLUX.1-schnell"}),
+ ("video", {"Lightricks/LTX-Video"}),
+ ("stt", {"openai/whisper-small"}),
+ ("tts", {"unsloth/orpheus-3b"}),
+ ("audio", {"audio-separator/htdemucs"}),
+ ],
+)
+def test_kind_comes_from_the_task(monkeypatch, kind, expected):
+ result, studio = _list(monkeypatch, {"kind": kind})
+ models = result["structuredContent"]["models"]
+ assert {model["id"] for model in models} == expected
+ assert {model["kind"] for model in models} == {kind}
+ assert [query for _m, _p, query in studio.state.queries] == [""]
+
+
+def test_entries_carry_only_the_allowlisted_fields(monkeypatch):
+ result, studio = _list(monkeypatch)
+ models = {model["id"]: model for model in result["structuredContent"]["models"]}
+ assert models["unsloth/Llama-3.2-1B-Instruct-GGUF"] == {
+ "id": "unsloth/Llama-3.2-1B-Instruct-GGUF",
+ "kind": "llm",
+ "loaded": True,
+ "display_name": "Llama 3.2 1B",
+ "quant": "Q4_K_M",
+ "context_length": 8192,
+ "audio_workflows": None,
+ }
+ assert models["unsloth/orpheus-3b"]["audio_workflows"] == ["speak", "clone"]
+ assert result["structuredContent"]["training_defaults"] is None
+ (_method, path, _headers, _body) = studio.state.calls[-1]
+ assert path == "/v1/models"
+
+
+LLAMA = "unsloth/Llama-3.2-1B-Instruct-GGUF"
+
+
+# The fast path knows only chat models; without a kind, resident media models are listed too.
+ "kind,expected,route",
+ [
+ ("llm", [LLAMA], "/api/inference/loaded-models"),
+ (None, [LLAMA, "Lightricks/LTX-Video"], "/v1/models"),
+ ("video", ["Lightricks/LTX-Video"], "/v1/models"),
+ ],
+)
+def test_loaded_only_takes_the_fast_path_for_chat(monkeypatch, kind, expected, route):
+ args = {"loaded_only": True, **({"kind": kind} if kind else {})}
+ result, studio = _list(monkeypatch, args)
+ assert [model["id"] for model in result["structuredContent"]["models"]] == expected
+ assert [(path, query) for _m, path, query in studio.state.queries] == [(route, "")]
+
+
+# ``model`` narrows the list to that model and adds its scalar training defaults.
+ "asked", ["unsloth/Qwen3-0.6B", "unsloth/qwen3-0.6b", "unsloth/Qwen3-0.6B:Q4_K_M"]
+)
+def test_model_matches_whatever_case_or_variant_is_asked_for(monkeypatch, asked):
+ routes = {**PAYLOADS, ("GET", f"/api/models/config/{asked}"): CONFIG}
+ result, _studio = _list(monkeypatch, {"model": asked}, routes = routes)
+ assert [m["id"] for m in result["structuredContent"]["models"]] == ["unsloth/Qwen3-0.6B"]
+ assert result["structuredContent"]["training_defaults"] == {
+ "max_seq_length": 2048,
+ "learning_rate": "2e-4",
+ "packing": False,
+ "lora_r": 16,
+ }
+
+
[email protected]("token", [None, "hf_secret"])
+def test_the_config_request_carries_the_hub_token_only_when_given(monkeypatch, token):
+ headers = {"X-Unsloth-HF-Token": token} if token else None
+ _result, studio = _list(monkeypatch, {"model": "unsloth/Qwen3-0.6B"}, headers = headers)
+ calls = {path: h for _m, path, h, _b in studio.state.calls}
+ assert calls["/api/models/config/unsloth/Qwen3-0.6B"].get("x-unsloth-hf-token") == token
+ assert "x-unsloth-hf-token" not in calls["/v1/models"]
diff --git a/studio/backend/tests/test_mcp_tools_recipe.py b/studio/backend/tests/test_mcp_tools_recipe.py
new file mode 100644
index 00000000000..b72806958a1
--- /dev/null
+++ b/studio/backend/tests/test_mcp_tools_recipe.py
@@ -0,0 +1,118 @@
+# 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 fastapi.responses import JSONResponse
+
+from .mcp_harness import bodies, queries, run_tool
+
+ERRORS = [{"message": "column q needs params", "path": "columns.0"}]
+RECIPE = {"columns": [{"name": "q", "column_type": "sampler"}]}
+STATUS = {
+ "job_id": "job-1",
+ "status": "completed",
+ "stage": "done",
+ "progress": {"done": 10, "total": 10, "percent": 100.0},
+ "rows": 10,
+ "error": None,
+ "artifact_path": "/srv/unsloth/recipes/my-dataset",
+ "execution_type": "full",
+}
+PAYLOADS = {
+ ("POST", "/api/data-recipe/validate"): {"valid": False, "errors": ERRORS},
+ ("POST", "/api/data-recipe/jobs"): {"job_id": "job-1"},
+ ("GET", "/api/data-recipe/jobs/job-1/status"): STATUS,
+ ("GET", "/api/data-recipe/jobs/current"): STATUS,
+ ("GET", "/api/data-recipe/jobs/job-1/dataset"): {
+ "dataset": [{"q": "a"}, {"q": "b"}],
+ "total": 10,
+ "limit": 2,
+ "offset": 4,
+ },
+}
+
+
[email protected]("mode", [None, "preview", "full"])
+def test_validate_checks_and_preview_or_full_starts_a_job(monkeypatch, mode):
+ args = {"recipe": RECIPE, **({"mode": mode} if mode else {})}
+ result, studio = run_tool(monkeypatch, PAYLOADS, "run_recipe", args)
+ started = [{"recipe": RECIPE, "run": {"execution_type": mode}}] if mode else []
+ assert result["structuredContent"] == {
+ "mode": mode or "validate",
+ "valid": None if mode else False,
+ "errors": None if mode else ERRORS,
+ "job_id": "job-1" if mode else None,
+ }
+ assert bodies(studio, "/api/data-recipe/jobs") == started
+ assert bodies(studio, "/api/data-recipe/validate") == ([] if mode else [{"recipe": RECIPE}])
+
+
+def test_a_job_reports_its_dataset_by_name_never_its_path(monkeypatch):
+ result, studio = run_tool(monkeypatch, PAYLOADS, "get_job", {"kind": "recipe", "id": "job-1"})
+ out = result["structuredContent"]
+ assert out["status"] == "completed"
+ assert out["progress_percent"] == 100.0
+ assert out["recipe"] == {
+ "stage": "done",
+ "rows": 10,
+ "dataset": "recipes/my-dataset",
+ "total_rows": None,
+ "data_rows": None,
+ }
+ assert "/srv" not in json.dumps(out)
+ assert [c[1] for c in studio.state.calls] == ["/api/data-recipe/jobs/job-1/status"]
+
+
+def test_without_an_id_the_current_job_is_read(monkeypatch):
+ result, studio = run_tool(monkeypatch, PAYLOADS, "get_job", {"kind": "recipe"})
+ assert result["structuredContent"]["id"] == "job-1"
+ assert [c[1] for c in studio.state.calls] == ["/api/data-recipe/jobs/current"]
+
+
+def test_rows_page_through_the_dataset(monkeypatch):
+ args = {"kind": "recipe", "id": "job-1", "rows": 2, "offset": 4}
+ result, studio = run_tool(monkeypatch, PAYLOADS, "get_job", args)
+ assert result["structuredContent"]["recipe"]["data_rows"] == [{"q": "a"}, {"q": "b"}]
+ assert result["structuredContent"]["recipe"]["total_rows"] == 10
+ assert queries(studio, "/api/data-recipe/jobs/job-1/dataset") == [{"limit": "2", "offset": "4"}]
+
+
+def _missing(detail):
+ return JSONResponse({"detail": detail}, status_code = 404)
+
+
+def test_no_current_job_is_an_empty_result(monkeypatch):
+ routes = {**PAYLOADS, ("GET", "/api/data-recipe/jobs/current"): _missing("no job")}
+ result, _studio = run_tool(monkeypatch, routes, "get_job", {"kind": "recipe"})
+ assert result["isError"] is False
+ assert result["structuredContent"]["jobs"] == []
+
+
+def test_an_unknown_recipe_id_is_still_an_error(monkeypatch):
+ routes = {**PAYLOADS, ("GET", "/api/data-recipe/jobs/nope/status"): _missing("job not found")}
+ result, _studio = run_tool(monkeypatch, routes, "get_job", {"kind": "recipe", "id": "nope"})
+ assert result["isError"] is True
+ assert "job not found" in result["content"][0]["text"]
+
+
+# The dataset route answers 404 while a job runs and 422 (naming host paths) when it ended without rows.
+ "code,detail", [(404, "dataset not ready"), (422, "dataset path missing: /srv/x")]
+)
+def test_rows_not_written_yet_still_report_the_status(monkeypatch, code, detail):
+ routes = {
+ **PAYLOADS,
+ ("GET", "/api/data-recipe/jobs/job-1/status"): {**STATUS, "status": "running"},
+ ("GET", "/api/data-recipe/jobs/job-1/dataset"): JSONResponse(
+ {"detail": detail}, status_code = code
+ ),
+ }
+ result, _studio = run_tool(
+ monkeypatch, routes, "get_job", {"kind": "recipe", "id": "job-1", "rows": 5}
+ )
+ assert result["isError"] is False, result
+ assert result["structuredContent"]["status"] == "running"
+ assert result["structuredContent"]["recipe"]["data_rows"] is None
+ assert "/srv/x" not in json.dumps(result)
diff --git a/studio/backend/tests/test_mcp_tools_status.py b/studio/backend/tests/test_mcp_tools_status.py
new file mode 100644
index 00000000000..1d3ef4f9b07
--- /dev/null
+++ b/studio/backend/tests/test_mcp_tools_status.py
@@ -0,0 +1,260 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from fastapi.responses import JSONResponse
+
+from .mcp_harness import run_tool
+
+CHAT = {
+ "active_model": "Llama 3.2 1B",
+ "model_identifier": "unsloth/Llama-3.2-1B-Instruct-GGUF",
+ "is_gguf": True,
+ "loaded": ["unsloth/Llama-3.2-1B-Instruct-GGUF", "unsloth/Qwen3-0.6B"],
+ "loading": ["unsloth/gemma-3-1b-it"],
+ "serving_checkpoints": ["/srv/models/llama"],
+}
+STT = {
+ "available": True,
+ "transformers": {
+ "loaded_model": None,
+ "loading": False,
+ "download": {
+ "downloading": True,
+ "model": "openai/whisper-small",
+ "bytes_done": 25,
+ "bytes_total": 100,
+ },
+ },
+ "gguf": {
+ "loaded_model": "whisper-large-v3-turbo-q5",
+ "loading": False,
+ "download": {"downloading": False},
+ },
+ "mtmd": {"loaded_model": None, "loading": True},
+}
+TRAINING = {
+ "job_id": "job-1",
+ "phase": "training",
+ "is_training_running": True,
+ "message": "Training step 25",
+ "error": None,
+ "details": {"step": 25, "total_steps": 100, "loss": 1.25, "output_dir": "/srv/outputs/run"},
+}
+DIFFUSION_TRAINING = {
+ "active": True,
+ "job_id": "diff-1",
+ "status": "training",
+ "message": "Step 12/500",
+ "step": 12,
+ "total_steps": 500,
+ "loss": 0.5,
+ "output_dir": "/srv/outputs/diff",
+ "lora_path": "/srv/outputs/diff/lora.safetensors",
+}
+HARDWARE = {
+ "available": True,
+ "backend": "cuda",
+ "devices": [
+ {
+ "index": 0,
+ "gpu_utilization_pct": 40,
+ "vram_used_gb": 3.5,
+ "vram_total_gb": 24.0,
+ "temperature_c": 51,
+ "name": "RTX",
+ }
+ ],
+}
+
+PAYLOADS = {
+ ("GET", "/api/inference/status"): CHAT,
+ ("GET", "/api/inference/images/status"): {
+ "loaded": True,
+ "repo_id": "/srv/hf/flux",
+ "display_repo_id": "black-forest-labs/FLUX.1-schnell",
+ "family": "flux",
+ },
+ ("GET", "/api/inference/video/status"): {
+ "loaded": True,
+ "repo_id": "Lightricks/LTX-Video",
+ "display_repo_id": None,
+ },
+ ("GET", "/api/inference/audio/stt/status"): STT,
+ ("GET", "/api/settings/embedding-model"): {
+ "embedding_model": "/srv/custom-embedder",
+ "is_custom": True,
+ "loaded": True,
+ },
+ ("GET", "/api/train/status"): TRAINING,
+ ("GET", "/api/train/diffusion/status"): DIFFUSION_TRAINING,
+ ("GET", "/api/export/status"): {
+ "is_export_active": False,
+ "active_op_kind": None,
+ "last_op_status": "succeeded",
+ "last_op_output_path": "/srv/exports/my-model-gguf",
+ },
+ ("GET", "/api/train/hardware"): HARDWARE,
+}
+
+
+def _status(monkeypatch, overrides = None):
+ return run_tool(monkeypatch, {**PAYLOADS, **(overrides or {})}, "studio_status")
+
+
+def test_every_slot_is_reported(monkeypatch):
+ # No generate-progress route answers here: an unreadable generation check reads as not generating.
+ result, studio = _status(monkeypatch)
+ status = result["structuredContent"]
+ assert status["chat"] == {
+ "loaded": [
+ {
+ "id": "unsloth/Llama-3.2-1B-Instruct-GGUF",
+ "display_name": "Llama 3.2 1B",
+ "is_gguf": True,
+ "audio_options": None,
+ },
+ {
+ "id": "unsloth/Qwen3-0.6B",
+ "display_name": None,
+ "is_gguf": None,
+ "audio_options": None,
+ },
+ ],
+ "loading": ["unsloth/gemma-3-1b-it"],
+ }
+ assert status["image"] == {
+ "loaded": True,
+ "model": "black-forest-labs/FLUX.1-schnell",
+ "family": "flux",
+ "generating": False,
+ }
+ assert status["video"] == {"loaded": True, "model": "Lightricks/LTX-Video", "generating": False}
+ assert status["stt"] == {
+ "engine": "gguf",
+ "model": "whisper-large-v3-turbo-q5",
+ "loading": True,
+ "downloading": [{"model": "openai/whisper-small", "fraction": 0.25}],
+ }
+ assert status["embedder"] == {"available": True, "loaded": True, "model": "custom"}
+ assert status["training"] == {
+ "job_id": "job-1",
+ "phase": "training",
+ "is_training_running": True,
+ "message": "Training step 25",
+ "error": None,
+ "step": 25,
+ "total_steps": 100,
+ "loss": 1.25,
+ "progress_percent": 25.0,
+ "eta_seconds": None,
+ }
+ # Image LoRA training runs on its own trainer: start_training(kind="diffusion") is followed here.
+ assert status["diffusion_training"] == {
+ "job_id": "diff-1",
+ "phase": "training",
+ "is_training_running": True,
+ "message": "Step 12/500",
+ "error": None,
+ "step": 12,
+ "total_steps": 500,
+ "loss": 0.5,
+ "progress_percent": 2.4,
+ "eta_seconds": None,
+ }
+ assert status["export"] == {
+ "active": False,
+ "op_kind": None,
+ "last_op_status": "succeeded",
+ "last_output": "my-model-gguf",
+ }
+ assert status["hardware"] == {
+ "available": True,
+ "backend": "cuda",
+ "devices": [
+ {
+ "index": 0,
+ "gpu_utilization_pct": 40.0,
+ "vram_used_gb": 3.5,
+ "vram_total_gb": 24.0,
+ "temperature_c": 51.0,
+ }
+ ],
+ }
+ assert status["unavailable"] == {}
+ called = {(method, path) for method, path, _headers, _body in studio.state.calls}
+ assert called == set(PAYLOADS)
+
+
+def test_failing_and_owner_only_slots_do_not_fail_the_tool(monkeypatch):
+ broken = JSONResponse({"detail": "Video backend crashed at /srv/hf/ltx"}, status_code = 500)
+ owner_only = JSONResponse(
+ {"detail": "Only the installation owner can do this"}, status_code = 403
+ )
+ overrides = {
+ ("GET", "/api/inference/video/status"): broken,
+ # A managed key sees the embedder as unavailable, not as a failure.
+ ("GET", "/api/settings/embedding-model"): owner_only,
+ ("GET", "/api/inference/images/generate-progress"): {"active": True, "step": 3},
+ ("GET", "/api/inference/video/generate-progress"): {"active": False},
+ }
+ result, _studio = _status(monkeypatch, overrides)
+ assert result["isError"] is False
+ status = result["structuredContent"]
+ assert set(status["unavailable"]) == {"video"}
+ assert "Video backend crashed" in status["unavailable"]["video"]
+ assert "/srv/hf" not in status["unavailable"]["video"]
+ assert status["video"] == {"loaded": False, "model": None, "generating": False}
+ assert status["embedder"] == {"available": False, "loaded": False, "model": None}
+ assert status["image"]["generating"] is True
+ assert status["chat"]["loaded"]
+
+
+def test_the_active_audio_model_lists_its_options(monkeypatch):
+ tts = "unsloth/Qwen3-TTS-12Hz-1.7B-CustomVoice-GGUF"
+ voice = {
+ "name": "voice",
+ "type": "enum",
+ "description": "Built-in speaker.",
+ "required": False,
+ "default": "vivian",
+ "min": None,
+ "max": None,
+ "values": ["vivian", "ryan"],
+ }
+ chat = {
+ "model_identifier": tts,
+ "loaded": [tts],
+ "audio_options": [voice, {"name": "temperature", "type": "float", "default": 0.9}, "x"],
+ }
+ overrides = {("GET", "/api/inference/status"): chat}
+ (model,) = _status(monkeypatch, overrides)[0]["structuredContent"]["chat"]["loaded"]
+ assert model["audio_options"] == [
+ {
+ "name": "voice",
+ "type": "enum",
+ "description": "Built-in speaker.",
+ "default": "vivian",
+ "min": None,
+ "max": None,
+ "values": ["vivian", "ryan"],
+ },
+ {
+ "name": "temperature",
+ "type": "float",
+ "description": None,
+ "default": 0.9,
+ "min": None,
+ "max": None,
+ "values": [],
+ },
+ ]
+
+
+def test_unloaded_slots_name_no_model(monkeypatch):
+ overrides = {
+ ("GET", "/api/inference/images/status"): {"loaded": False, "repo_id": "stale/repo"},
+ ("GET", "/api/inference/video/status"): {"loaded": False},
+ }
+ status = _status(monkeypatch, overrides)[0]["structuredContent"]
+ assert status["image"] == {"loaded": False, "model": None, "family": None, "generating": False}
+ assert status["video"] == {"loaded": False, "model": None, "generating": False}
diff --git a/studio/backend/tests/test_mcp_tools_text.py b/studio/backend/tests/test_mcp_tools_text.py
new file mode 100644
index 00000000000..b6d9af9da21
--- /dev/null
+++ b/studio/backend/tests/test_mcp_tools_text.py
@@ -0,0 +1,255 @@
+# 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 pytest
+from fastapi.responses import JSONResponse, Response
+
+from .mcp_harness import JPEG, PNG, PNG_URL, bodies, call_to, data_url, run_tool
+
+LLM = "unsloth/Llama-3.2-1B-Instruct-GGUF"
+COMPLETION = {
+ "id": "chatcmpl-1",
+ "object": "chat.completion",
+ "model": LLM,
+ "choices": [
+ {"index": 0, "message": {"role": "assistant", "content": "Paris."}, "finish_reason": "stop"}
+ ],
+ "usage": {"prompt_tokens": 12, "completion_tokens": 2, "total_tokens": 14},
+}
+
+EMBEDDINGS = {
+ "object": "list",
+ "model": "nomic-embed-text-v1.5",
+ "data": [
+ {"object": "embedding", "index": 1, "embedding": [0.0, 1.0, 0.5]},
+ {"object": "embedding", "index": 0, "embedding": [1.0, 0.0, 0.25]},
+ ],
+}
+
+DECISION = {
+ "model": "laya-multilingual",
+ "answers": {
+ "urgent": {"type": "noul", "noul": 0.9},
+ "topic": {
+ "type": "choice",
+ "choice": "billing",
+ "confidence": 0.8,
+ "probabilities": {"billing": 0.8, "bug": 0.2},
+ },
+ "tone": {
+ "type": "score",
+ "score": 2.0,
+ "confidence": 0.7,
+ "legend": {"0": "calm", "1": {"text": "angry"}},
+ "probabilities": {"1": 0.3, "2": 0.7},
+ },
+ },
+ "usage": {"input_tokens": 40, "output_tokens": 0},
+}
+
+PAYLOADS = {
+ ("POST", "/v1/chat/completions"): COMPLETION,
+ ("POST", "/v1/embeddings"): EMBEDDINGS,
+ ("POST", "/v1/systemone"): DECISION,
+}
+QUESTIONS = {
+ "urgent": {"type": "noul", "instructions": "Does this need a reply within the hour?"},
+ "topic": {"type": "choice", "criteria": {"billing": "Money", "bug": "Defect"}},
+ "tone": {"type": "score", "criteria": ["calm", "angry"]},
+}
+CHAT = ("POST", "/v1/chat/completions")
+URGENT = {"urgent": QUESTIONS["urgent"]}
+
+
+def _chat(
+ monkeypatch,
+ args,
+ reply = None,
+):
+ routes = PAYLOADS if reply is None else {**PAYLOADS, CHAT: reply}
+ return run_tool(monkeypatch, routes, "chat", args)
+
+
+def test_a_prompt_becomes_one_user_turn(monkeypatch):
+ result, studio = _chat(
+ monkeypatch, {"prompt": "Capital of France?", "system": "Be brief.", "max_tokens": 16}
+ )
+ out = result["structuredContent"]
+ assert out == {
+ "text": "Paris.",
+ "model": LLM,
+ "finish_reason": "stop",
+ "usage": {"prompt_tokens": 12, "completion_tokens": 2, "total_tokens": 14},
+ "note": None,
+ "cancel_id": out["cancel_id"],
+ }
+ run_tool(monkeypatch, studio, "chat", {"prompt": "b"})
+ body, second = bodies(studio, "/v1/chat/completions")
+ assert out["cancel_id"] == body["cancel_id"] != second["cancel_id"]
+ assert body["messages"] == [
+ {"role": "system", "content": "Be brief."},
+ {"role": "user", "content": "Capital of France?"},
+ ]
+ assert body["stream"] is False
+ assert body["model"] == "default"
+ assert body["max_tokens"] == 16
+ assert "temperature" not in body
+ assert body["cancel_id"].startswith("mcp-") and len(body["cancel_id"]) > 20
+
+
+def test_a_caller_chosen_cancel_id_is_sent_so_another_call_can_stop_the_reply(monkeypatch):
+ result, studio = _chat(monkeypatch, {"prompt": "a", "cancel_id": "agent-run-0001"})
+ assert bodies(studio, "/v1/chat/completions")[0]["cancel_id"] == "agent-run-0001"
+ assert result["structuredContent"]["cancel_id"] == "agent-run-0001"
+ for bad in ("short", "has space in it", "x" * 65):
+ refused, studio = _chat(monkeypatch, {"prompt": "a", "cancel_id": bad})
+ assert refused["isError"] is True
+ assert bodies(studio, "/v1/chat/completions") == []
+
+
+def test_messages_are_sent_as_given(monkeypatch):
+ messages = [
+ {"role": "user", "content": "Hi"},
+ {"role": "assistant", "content": "Hello"},
+ {"role": "user", "content": "Capital of France?"},
+ ]
+ _result, studio = _chat(monkeypatch, {"messages": messages, "temperature": 0.2, "model": LLM})
+ (body,) = bodies(studio, "/v1/chat/completions")
+ assert body["messages"] == messages
+ assert body["temperature"] == 0.2
+ assert body["model"] == LLM
+
+
+def test_chat_images_ride_the_last_user_turn(monkeypatch):
+ gallery = {
+ ("GET", "/api/inference/images/gallery/img-1/file"): Response(PNG, media_type = "image/png")
+ }
+ messages = [
+ {"role": "user", "content": "Hi"},
+ {"role": "assistant", "content": "Hello"},
+ {"role": "user", "content": "What is in these?"},
+ ]
+ images = [{"data_url": data_url(JPEG, "image/jpeg")}, {"gallery_id": "img-1"}]
+ result, studio = run_tool(
+ monkeypatch, {**PAYLOADS, **gallery}, "chat", {"messages": messages, "images": images}
+ )
+ assert result["isError"] is False
+ (body,) = bodies(studio, "/v1/chat/completions")
+ assert body["messages"][0] == {"role": "user", "content": "Hi"}
+ assert body["messages"][2]["content"] == [
+ {"type": "text", "text": "What is in these?"},
+ {"type": "image_url", "image_url": {"url": data_url(JPEG, "image/jpeg")}},
+ {"type": "image_url", "image_url": {"url": data_url(PNG, "image/png")}},
+ ]
+ assert call_to(studio, "/api/inference/images/gallery/img-1/file")[2]["authorization"] == (
+ "Bearer sk-unsloth-test"
+ )
+
+
+def test_a_different_answering_model_is_noted(monkeypatch):
+ result, _studio = _chat(monkeypatch, {"prompt": "hi", "model": "unsloth/Qwen3-0.6B"})
+ note = result["structuredContent"]["note"]
+ assert LLM in note and "unsloth/Qwen3-0.6B" in note
+
+ pinned = {**COMPLETION, "model": f"{LLM}:Q4_K_M"}
+ result, _studio = _chat(monkeypatch, {"prompt": "hi", "model": LLM}, pinned)
+ assert result["structuredContent"]["note"] is None
+
+
+ "content,finish_reason,noted",
+ [("", "length", True), ("", "stop", False), ("Edit /etc/hosts as root.", "stop", False)],
+)
+def test_an_empty_reply_cut_off_by_the_budget_says_so(monkeypatch, content, finish_reason, noted):
+ reply = {
+ **COMPLETION,
+ "choices": [{"message": {"content": content}, "finish_reason": finish_reason}],
+ }
+ result, _studio = _chat(monkeypatch, {"prompt": "hi", "max_tokens": 300}, reply)
+ out = result["structuredContent"]
+ assert out["text"] == content
+ assert ("raise max_tokens" in out["note"]) if noted else out["note"] is None
+
+
[email protected]("model", [None, "bge-m3"])
+def test_embed_returns_vectors_in_input_order(monkeypatch, model):
+ args = {"texts": ["first", "second"], **({"model": model} if model else {})}
+ result, studio = run_tool(monkeypatch, PAYLOADS, "embed", args)
+ assert result["structuredContent"] == {
+ "model": "nomic-embed-text-v1.5",
+ "dimensions": 3,
+ "embeddings": [[1.0, 0.0, 0.25], [0.0, 1.0, 0.5]],
+ }
+ assert bodies(studio, "/v1/embeddings") == [
+ {"input": args["texts"], **({"model": model} if model else {})}
+ ]
+
+
+# The 2048-text limit is accepted; fewer vectors than texts is an error.
[email protected]("rows,texts", [(2048, 2048), (1, 2)])
+def test_embed_accepts_the_limit_and_refuses_a_short_answer(monkeypatch, rows, texts):
+ answer = {"model": "m", "data": [{"index": i, "embedding": [0.5]} for i in range(rows)]}
+ result, _studio = run_tool(
+ monkeypatch, {("POST", "/v1/embeddings"): answer}, "embed", {"texts": ["x"] * texts}
+ )
+ if rows < texts:
+ assert result["isError"] is True
+ else:
+ assert result["structuredContent"]["dimensions"] == 1
+ assert len(result["structuredContent"]["embeddings"]) == texts
+
+
+def _decide(
+ monkeypatch,
+ args,
+ answer = None,
+):
+ routes = PAYLOADS if answer is None else {**PAYLOADS, ("POST", "/v1/systemone"): answer}
+ return run_tool(monkeypatch, routes, "system_one", args)
+
+
+def test_system_one_sends_the_default_model_and_maps_every_answer_type(monkeypatch):
+ answer = JSONResponse(DECISION, headers = {"x-typesafe-request-id": "req-1"})
+ args = {"state": "Customer: I was charged twice!", "questions": QUESTIONS}
+ result, studio = _decide(monkeypatch, args, answer)
+ blank = dict.fromkeys(["noul", "choice", "score", "confidence", "probabilities", "legend"])
+ assert result["structuredContent"] == {
+ "model": "laya-multilingual",
+ "request_id": "req-1",
+ "answers": {
+ "urgent": {**blank, "type": "noul", "noul": 0.9},
+ "topic": {**blank, **DECISION["answers"]["topic"]},
+ "tone": {
+ **blank,
+ **DECISION["answers"]["tone"],
+ "legend": {"0": "calm", "1": '{"text": "angry"}'},
+ },
+ },
+ }
+ (body,) = bodies(studio, "/v1/systemone")
+ assert body == {
+ "state": "Customer: I was charged twice!",
+ "model": "default",
+ "questions": QUESTIONS,
+ }
+
+
+def test_a_detail_error_type_message_is_used(monkeypatch):
+ unknown = JSONResponse(
+ {"detail": {"error_type": "api_usage_error", "message": "Unknown model: nope"}},
+ status_code = 400,
+ )
+ args = {"state": "x", "questions": URGENT, "model": "nope"}
+ result, studio = _decide(monkeypatch, args, unknown)
+ assert result["content"][0]["text"] == "Unknown model: nope (HTTP 400)"
+ assert bodies(studio, "/v1/systemone")[0]["model"] == "nope"
+
+
+def test_system_one_sends_json_state_and_png_or_jpeg_images(monkeypatch):
+ images = [PNG_URL, {"data_url": data_url(JPEG, "image/jpeg")}]
+ args = {"state": {"ticket": 7}, "questions": URGENT, "images": images}
+ result, studio = _decide(monkeypatch, args)
+ assert result["isError"] is False
+ (body,) = bodies(studio, "/v1/systemone")
+ assert body["state"] == {"ticket": 7}
+ assert body["images"] == [data_url(PNG, "image/png"), data_url(JPEG, "image/jpeg")]
diff --git a/studio/backend/tests/test_mcp_tools_training.py b/studio/backend/tests/test_mcp_tools_training.py
new file mode 100644
index 00000000000..3de42c36fb9
--- /dev/null
+++ b/studio/backend/tests/test_mcp_tools_training.py
@@ -0,0 +1,192 @@
+# 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 asyncio
+import json
+
+import pytest
+from fastapi.responses import JSONResponse
+from fastmcp.exceptions import ToolError
+
+from hub.utils.host_paths import cache_reference
+
+from studio_mcp import checkpoints
+
+from .mcp_harness import (
+ CONFIG,
+ DIFFUSION,
+ OUT,
+ RUN_CHECKPOINTS,
+ bodies,
+ fake_studio,
+ make_caller,
+ queries,
+ run_tool,
+)
+
+PAYLOADS = {
+ ("POST", "/api/train/start"): {"job_id": "job-7", "status": "queued", "message": "Queued"},
+ ("POST", "/api/train/diffusion/start"): {
+ "job_id": "diff-1",
+ "status": "queued",
+ "output_dir": "/srv/unsloth/outputs/my-lora",
+ },
+}
+ACKNOWLEDGE = ("POST", "/api/train/start-requests/{start_request_id}/acknowledge")
+
+
+def _start(
+ monkeypatch,
+ args,
+ overrides = None,
+):
+ routes = {**PAYLOADS, ACKNOWLEDGE: {"status": "ok"}, **(overrides or {})}
+ return run_tool(monkeypatch, routes, "start_training", args)
+
+
[email protected]("request_id", [None, "mine-1"])
+def test_start_forwards_the_config_as_sent_and_acknowledges_nothing(monkeypatch, request_id):
+ config = {**CONFIG, **({"start_request_id": request_id} if request_id else {})}
+ result, studio = _start(monkeypatch, {"config": config})
+ (sent,) = bodies(studio, "/api/train/start")
+ sent_id = sent.pop("start_request_id")
+ assert sent_id == request_id if request_id else sent_id.startswith("mcp-")
+ assert sent == CONFIG
+ assert result["structuredContent"] == {
+ "job_id": "job-7",
+ "status": "queued",
+ "message": "Queued",
+ "start_request_id": sent_id,
+ }
+ assert "x-unsloth-hf-token" not in studio.state.calls[0][2]
+ assert [c[1] for c in studio.state.calls] == ["/api/train/start"]
+
+
+ "answer",
+ [
+ {"job_id": "", "status": "error", "error": "Training already active"},
+ JSONResponse({"detail": "A transformers installation is in progress."}, status_code = 409),
+ ],
+)
+def test_a_refused_start_is_acknowledged(monkeypatch, answer):
+ result, studio = _start(monkeypatch, {"config": CONFIG}, {("POST", "/api/train/start"): answer})
+ assert result["isError"] is True
+ (sent,) = bodies(studio, "/api/train/start")
+ acknowledged = [p for _m, p, _h, _b in studio.state.calls if p.endswith("/acknowledge")]
+ # Without this the refusal would stay the training status and hide the run that is going.
+ assert acknowledged == [f"/api/train/start-requests/{sent['start_request_id']}/acknowledge"]
+
+
+def test_validate_only_starts_nothing(monkeypatch):
+ result, studio = _start(monkeypatch, {"config": CONFIG, "validate_only": True})
+ assert result["structuredContent"]["status"] == "valid"
+ assert result["structuredContent"]["job_id"] is None
+ assert studio.state.calls == []
+
+
+def test_kind_routes_to_the_matching_start_route(monkeypatch):
+ result, studio = _start(monkeypatch, {"config": DIFFUSION, "kind": "diffusion"})
+ assert result["structuredContent"] == {
+ "job_id": "diff-1",
+ "status": "queued",
+ "message": None,
+ "start_request_id": None,
+ }
+ assert "/srv" not in json.dumps(result)
+ assert bodies(studio, "/api/train/diffusion/start") == [DIFFUSION]
+ assert bodies(studio, "/api/train/start") == []
+
+
+def _run(run_id, folder):
+ return {
+ "id": run_id,
+ "status": "completed",
+ "model_name": "unsloth/Qwen3-0.6B",
+ "dataset_name": "mlabonne/FineTome-100k",
+ "started_at": "2026-10-08T10:00:00Z",
+ "final_step": 30,
+ "final_loss": 0.9,
+ "output_dir": cache_reference(f"{OUT}/{folder}"),
+ "can_resume": False,
+ }
+
+
+RUNS = {"runs": [_run("run-1", "qwen-lora"), _run("run-2", "qwen-lora-2")], "total": 2}
+DETAIL = {
+ "run": _run("run-1", "qwen-lora"),
+ "config": {
+ "model_name": "unsloth/Qwen3-0.6B",
+ "learning_rate": 0.0002,
+ "max_steps": 30,
+ "output_dir": "/srv/out",
+ "hf_token": "hf_secret",
+ },
+ "metrics": {"step_history": [1, 2], "loss_history": [1.5, 1.2]},
+}
+RUN_PAYLOADS = {
+ ("GET", "/api/models/checkpoints"): RUN_CHECKPOINTS,
+ ("GET", "/api/train/runs"): RUNS,
+ ("GET", "/api/train/runs/run-1"): DETAIL,
+}
+
+
+NAMES = ["qwen-lora", "qwen-lora/checkpoint-30", "qwen-lora-2/checkpoint-30"]
+
+
+def _runs(monkeypatch, args):
+ return run_tool(monkeypatch, RUN_PAYLOADS, "list_training_runs", args)[0]
+
+
+def test_runs_name_their_folder_and_checkpoints_by_name(monkeypatch):
+ result = _runs(monkeypatch, {"include_checkpoints": True})
+ out = result["structuredContent"]
+ assert [r["run_folder"] for r in out["runs"]] == ["qwen-lora", "qwen-lora-2"]
+ assert [c["name"] for c in out["checkpoints"]] == NAMES
+ assert out["checkpoints"][0] == {
+ "run": "qwen-lora",
+ "name": "qwen-lora",
+ "loss": 0.9,
+ "base_model": "unsloth/Qwen3-0.6B",
+ "peft_type": "LORA",
+ "lora_rank": 16,
+ "is_quantized": True,
+ }
+ assert OUT not in json.dumps(result)
+
+
+def test_names_resolve_back_to_paths_in_process():
+ caller = make_caller(
+ direct_local = False, public_base = "http://h", studio_app = fake_studio(RUN_PAYLOADS)
+ )
+ found = {c.name: c.path for c in asyncio.run(checkpoints.list_checkpoints(caller))[0]}
+ assert found == {name: f"{OUT}/{name}" for name in NAMES}
+ for name, path in found.items():
+ assert asyncio.run(checkpoints.resolve(caller, name)).path == path
+ with pytest.raises(
+ ToolError, match = "Available: qwen-lora, qwen-lora-2/checkpoint-30, qwen-lora/checkpoint-30"
+ ):
+ asyncio.run(checkpoints.resolve(caller, "missing"))
+
+
+def test_a_run_detail_keeps_only_scalar_settings(monkeypatch):
+ result = _runs(monkeypatch, {"run_id": "run-1"})
+ run = result["structuredContent"]["run"]
+ assert run["config"] == {
+ "model_name": "unsloth/Qwen3-0.6B",
+ "learning_rate": 0.0002,
+ "max_steps": 30,
+ }
+ assert run["loss_history"] == [1.5, 1.2]
+ assert run["run_folder"] == "qwen-lora"
+ assert result["structuredContent"]["checkpoints"] is None
+
+
+def test_limit_is_clamped(monkeypatch):
+ studio = fake_studio(RUN_PAYLOADS)
+ run_tool(monkeypatch, studio, "list_training_runs", {"limit": 10_000, "offset": -5})
+ run_tool(monkeypatch, studio, "list_training_runs", {"limit": 0})
+ assert queries(studio, "/api/train/runs") == [
+ {"limit": "200", "offset": "0"},
+ {"limit": "1", "offset": "0"},
+ ]
diff --git a/studio/backend/tests/test_mcp_tools_video.py b/studio/backend/tests/test_mcp_tools_video.py
new file mode 100644
index 00000000000..d3d6566d019
--- /dev/null
+++ b/studio/backend/tests/test_mcp_tools_video.py
@@ -0,0 +1,161 @@
+# 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 base64
+
+import pytest
+
+from fastapi.responses import Response
+
+from .mcp_harness import (
+ PNG,
+ PNG_URL,
+ WEBP,
+ bodies,
+ call_to,
+ fake_studio,
+ openai_error,
+ queries,
+ run_tool,
+)
+
+
+def _job(video_id, status, progress, **fields):
+ return {
+ "id": video_id,
+ "object": "video",
+ "model": "Lightricks/LTX-Video",
+ "status": status,
+ "progress": progress,
+ "created_at": 1,
+ "prompt": "waves",
+ "size": "704x480",
+ "seconds": "4",
+ "error": None,
+ **fields,
+ }
+
+
+PAYLOADS = {
+ ("POST", "/v1/videos"): _job("video-1", "queued", 0),
+ ("GET", "/v1/videos"): {
+ "object": "list",
+ "data": [_job("video-2", "in_progress", 40), _job("video-1", "completed", 100)],
+ },
+ ("GET", "/v1/videos/video-1"): _job("video-1", "completed", 100),
+}
+
+
+def _thumbnail(request, body):
+ variant = request.query_params.get("variant")
+ assert variant == "thumbnail", f"the tool asked for variant={variant!r}"
+ return Response(WEBP, media_type = "image/webp")
+
+
+def _studio(overrides = None):
+ return fake_studio(
+ {**PAYLOADS, ("GET", "/v1/videos/video-1/content"): _thumbnail, **(overrides or {})}
+ )
+
+
+def _get_job(
+ monkeypatch,
+ args,
+ overrides = None,
+ **client,
+):
+ return run_tool(monkeypatch, _studio(overrides), "get_job", {"kind": "video", **args}, **client)
+
+
+def test_generate_video_starts_a_job_with_string_fields(monkeypatch):
+ args = {"prompt": "waves", "seconds": "4", "size": "704x480", "first_frame": PNG_URL}
+ result, studio = run_tool(
+ monkeypatch, _studio(), "generate_video", args, headers = {"X-Unsloth-HF-Token": "hf_h"}
+ )
+ assert result["structuredContent"] == {
+ "id": "video-1",
+ "status": "queued",
+ "progress": 0,
+ "model": "Lightricks/LTX-Video",
+ "seconds": "4",
+ "size": "704x480",
+ }
+ assert bodies(studio, "/v1/videos") == [
+ {
+ "prompt": "waves",
+ "seconds": "4",
+ "size": "704x480",
+ "input_reference": "data:image/png;base64," + base64.b64encode(PNG).decode(),
+ }
+ ]
+ assert call_to(studio, "/v1/videos")[2]["x-unsloth-hf-token"] == "hf_h"
+
+
+def test_a_completed_job_returns_its_thumbnail_and_a_link_never_the_mp4(monkeypatch):
+ result, studio = _get_job(monkeypatch, {"id": "video-1"}, base_url = "http://192.168.1.20:8888")
+ out = result["structuredContent"]
+ assert out == {
+ "kind": "video",
+ "id": "video-1",
+ "status": "completed",
+ "progress_percent": 100.0,
+ "error": None,
+ "video": {
+ "url": "http://192.168.1.20:8888/v1/videos/video-1/content",
+ "thumbnail_inline": True,
+ },
+ "recipe": None,
+ "export": None,
+ "jobs": None,
+ }
+ content = result["content"]
+ assert [c["type"] for c in content[1:]] == ["image", "resource_link"]
+ assert base64.b64decode(content[1]["data"]) == WEBP
+ assert content[2]["uri"] == "http://192.168.1.20:8888/v1/videos/video-1/content"
+ assert content[2]["mimeType"] == "video/mp4"
+ assert queries(studio, "/v1/videos/video-1/content") == [{"variant": "thumbnail"}]
+ assert not [c for c in studio.state.calls if "/gallery/" in c[1]]
+
+
+def test_an_unavailable_thumbnail_leaves_only_the_link(monkeypatch):
+ unavailable = openai_error(
+ "ffmpeg is not installed", 501, type = "api_error", code = "video_thumbnail_unavailable"
+ )
+ content = {("GET", "/v1/videos/video-1/content"): unavailable}
+ result, _studio = _get_job(monkeypatch, {"id": "video-1"}, content)
+ assert result["isError"] is False
+ assert [c["type"] for c in result["content"][1:]] == ["resource_link"]
+ assert result["structuredContent"]["video"]["thumbnail_inline"] is False
+
+
+ "job",
+ [
+ _job("video-2", "in_progress", 40),
+ _job(
+ "video-3",
+ "failed",
+ 10,
+ error = {"code": "video_generation_failed", "message": "Out of memory"},
+ ),
+ ],
+)
+def test_an_unfinished_job_reports_progress_and_error_without_media(monkeypatch, job):
+ path = f"/v1/videos/{job['id']}"
+ result, studio = _get_job(monkeypatch, {"id": job["id"]}, {("GET", path): job})
+ out = result["structuredContent"]
+ assert out["status"] == job["status"]
+ assert out["progress_percent"] == float(job["progress"])
+ assert out["error"] == (job["error"] or {}).get("message")
+ assert out["video"] is None
+ assert [c["type"] for c in result["content"]] == ["text"]
+ assert [c[1] for c in studio.state.calls] == [path]
+
+
+def test_without_an_id_recent_jobs_are_listed(monkeypatch):
+ result, studio = _get_job(monkeypatch, {})
+ assert result["structuredContent"]["jobs"] == [
+ {"id": "video-2", "status": "in_progress", "progress_percent": 40.0},
+ {"id": "video-1", "status": "completed", "progress_percent": 100.0},
+ ]
+ assert [c[1] for c in studio.state.calls] == ["/v1/videos"]
diff --git a/studio/backend/tests/test_mcp_training_start_guard.py b/studio/backend/tests/test_mcp_training_start_guard.py
index bd17777a3c6..d02c4683dd7 100644
--- a/studio/backend/tests/test_mcp_training_start_guard.py
+++ b/studio/backend/tests/test_mcp_training_start_guard.py
@@ -331,10 +331,12 @@ def test_an_unknown_start_request_id_is_still_refused_without_a_record(monkeypat
def test_the_mcp_tool_surfaces_the_409_as_a_tool_error_not_a_dict(monkeypatch):
- """stop_training/get_training_status return dicts; a refused start raises."""
- import mcp_server
+ """The MCP tool forwards to the real training route under the agent's API key, so the
+ route's own guard refuses it, and the agent sees the 409 detail as a tool error."""
import routes.training as training_routes
+ from .mcp_harness import route_studio, run_tool
+
monkeypatch.setattr(
training_routes,
"get_training_backend",
@@ -347,38 +349,13 @@ def test_the_mcp_tool_surfaces_the_409_as_a_tool_error_not_a_dict(monkeypatch):
)
monkeypatch.setattr(training_routes, "_background_video_generation_active", lambda: False)
- server = mcp_server.create_studio_mcp()
-
- # The tool body raises rather than returning the {"status": ...} dict that
- # stop_training / get_training_status return.
- # Public fastmcp API only. The private equivalents (_get_tool/_call_tool_mcp)
- # work too, but _call_tool_mcp was dropped in fastmcp 4.0.0 while the pin is an
- # open ">=3.0.2", so a private call here breaks the suite on an upstream major
- # that the product itself is unaffected by. get_tool/call_tool are present with
- # these same signatures on both 3.0.2 (the floor) and 4.x.
- async def run_tool_body():
- tool = await server.get_tool("start_training")
- assert tool is not None, "start_training must be registered on the studio MCP server"
- return await tool.fn(config = _config())
-
- with pytest.raises(HTTPException) as excinfo:
- asyncio.run(run_tool_body())
- assert excinfo.value.status_code == 409
-
- from fastmcp.exceptions import ToolError
-
- # call_tool, not the private _call_tool_mcp fastmcp 4 dropped: requirements
- # floor it at 3.0.2 and never cap it, so a test may only use the public API.
- with pytest.raises(ToolError) as tool_error:
- asyncio.run(server.call_tool("start_training", {"config": _config()}))
+ studio = route_studio(training_routes.router, "/api/train")
+ result, _studio = run_tool(monkeypatch, studio, "start_training", {"config": _config()})
- # mask_error_details defaults False, so the 409 detail survives to the client
- # (as the text of an isError CallToolResult, not a JSON-RPC protocol error).
- # Asserted through the surfaced message rather than the server's private
- # _mask_error_details flag: the detail reaching the caller is the property that
- # matters, and it stays true however that flag is spelled upstream.
- assert "inference request is in progress" in str(tool_error.value)
- assert "Error calling tool 'start_training'" in str(tool_error.value)
+ # An isError result with the route's detail, not a raised HTTPException or a status dict.
+ assert result["isError"] is True
+ assert "inference request is in progress" in result["content"][0]["text"]
+ assert "(HTTP 409)" in result["content"][0]["text"]
# --------------------------------------------------------------------------------------
diff --git a/studio/backend/tests/test_origin_policy.py b/studio/backend/tests/test_origin_policy.py
new file mode 100644
index 00000000000..6a423cc14c4
--- /dev/null
+++ b/studio/backend/tests/test_origin_policy.py
@@ -0,0 +1,100 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from types import SimpleNamespace
+
+import pytest
+
+from utils.origin_policy import canonical_origin, mcp_origin_allowed, origin_of
+
+TUNNEL = "https://abc-def.trycloudflare.com"
+
+
+def test_main_reexports_the_moved_helpers():
+ import main
+ assert main._canonical_origin is canonical_origin
+ assert main._origin_of is origin_of
+
+
+ "value,expected",
+ [
+ ("http://localhost", ("http", "localhost", 80)),
+ ("https://Example.COM:443", ("https", "example.com", 443)),
+ ("http://[::1]:8888", ("http", "::1", 8888)),
+ ("http://[::1]", ("http", "::1", 80)),
+ ("http://user:[email protected]:8888", ("http", "127.0.0.1", 8888)),
+ ("tauri://localhost", ("tauri", "localhost", 0)),
+ ("null", None),
+ ("", None),
+ ("http://[::1", None),
+ ("http://host:port", None),
+ ],
+)
+def test_origin_canonicalisation(value, expected):
+ assert origin_of(value) == expected
+
+
+def _allowed(
+ origin,
+ *,
+ host = "127.0.0.1:8888",
+ scheme = "http",
+ **state,
+):
+ app_state = SimpleNamespace(**{"server_port": 8888, "cloudflare_url": None, **state})
+ return mcp_origin_allowed(
+ origin, request_scheme = scheme, request_netloc = host, app_state = app_state
+ )
+
+
+ "origin,allowed",
+ [
+ *(
+ (o, True)
+ for o in ["http://localhost:8888", "http://127.0.0.1:8888", "http://[::1]:8888"]
+ ),
+ *(
+ (o, True)
+ for o in ["HTTP://LOCALHOST:8888", "tauri://localhost", "http://tauri.localhost"]
+ ),
+ *(
+ (o, False)
+ for o in ["https://evil.example", "http://localhost:3000", "http://localhost:5173"]
+ ),
+ *((o, False) for o in ["http://localhost", "null", "", "not a url", "http://[::1", TUNNEL]),
+ ],
+)
+def test_origins_against_the_default_loopback_host(origin, allowed):
+ assert _allowed(origin) is allowed
+
+
+ "origin,kwargs,allowed",
+ [
+ # Loopback at the request's own port passes without a published port.
+ ("http://localhost:9000", {"host": "127.0.0.1:9000", "server_port": None}, True),
+ ("http://localhost:9001", {"host": "127.0.0.1:9000", "server_port": None}, False),
+ ("http://[::1]:8888", {"host": "[::1]:8888"}, True),
+ ("http://localhost:8888", {"host": "[::1]:8888"}, True),
+ ("http://[::1]:8889", {"host": "[::1]:8888"}, False),
+ # A rebound name matching the Host header is still refused.
+ ("http://evil.example:8888", {"host": "evil.example:8888"}, False),
+ ("http://192.168.1.20:8888", {"host": "192.168.1.20:8888"}, True),
+ ("http://[fe80::1]:8888", {"host": "[fe80::1]:8888"}, True),
+ ("http://192.168.1.21:8888", {"host": "192.168.1.20:8888"}, False),
+ ("http://192.168.1.20", {"host": "192.168.1.20:80"}, True),
+ ("https://192.168.1.20:443", {"host": "192.168.1.20", "scheme": "https"}, True),
+ (TUNNEL, {"cloudflare_url": TUNNEL + "/"}, True),
+ (TUNNEL, {"host": "abc-def.trycloudflare.com", "cloudflare_url": TUNNEL}, True),
+ ],
+)
+def test_origins_against_other_hosts(origin, kwargs, allowed):
+ assert _allowed(origin, **kwargs) is allowed
+
+
+def test_cors_origins_env_is_honoured_but_never_a_wildcard(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_CORS_ORIGINS", "*, https://studio.example.org")
+ assert _allowed("https://studio.example.org")
+ assert not _allowed("https://evil.example")
diff --git a/studio/backend/tests/test_shutdown_preserves_live_worker.py b/studio/backend/tests/test_shutdown_preserves_live_worker.py
index 29acb1072e4..5c0847643c5 100644
--- a/studio/backend/tests/test_shutdown_preserves_live_worker.py
+++ b/studio/backend/tests/test_shutdown_preserves_live_worker.py
@@ -195,6 +195,9 @@ class TestSpawnPathsHonorFailedShutdown:
o = ExportOrchestrator.__new__(ExportOrchestrator)
o._lock = threading.RLock()
+ o._op_lock = threading.Lock()
+ o._active_op_id = None
+ o._cancelled_op_ids = set()
o._proc = _FakeProc(dies_on = None) # survivor
o.clear_logs = lambda: None
o._cancel_requested = False
diff --git a/studio/backend/tests/test_warm_window_review_fixes.py b/studio/backend/tests/test_warm_window_review_fixes.py
index b2246772caf..a0b4f5ded50 100644
--- a/studio/backend/tests/test_warm_window_review_fixes.py
+++ b/studio/backend/tests/test_warm_window_review_fixes.py
@@ -1231,29 +1231,31 @@ def test_shutdown_retires_the_detection_epoch():
# ------------------------------------------- the MCP status tool stays off-loop
def test_the_mcp_status_tool_reads_hardware_off_the_event_loop():
- """get_gpu_utilization() reaches detection, which blocks on the warm import."""
- path = _BACKEND / "mcp_server.py"
- tree = ast.parse(path.read_text(encoding = "utf-8"))
- called_directly = [
- node
- for node in ast.walk(tree)
- if isinstance(node, ast.Call)
- and isinstance(node.func, ast.Name)
- and node.func.id == "get_gpu_utilization"
- ]
- assert not called_directly, (
- "the MCP status tool calls get_gpu_utilization() inline again; it blocks "
- "the event loop on the warm's torch import"
- )
- offloaded = [
- node
- for node in ast.walk(tree)
- if isinstance(node, ast.Call)
- and isinstance(node.func, ast.Attribute)
- and node.func.attr == "to_thread"
- and any(isinstance(a, ast.Name) and a.id == "get_gpu_utilization" for a in node.args)
- ]
- assert offloaded, "the hardware read is no longer handed to a worker thread"
+ """get_gpu_utilization() reaches detection, which blocks on the warm import. The MCP tools
+ must not call it at all: studio_status reads /api/train/hardware, whose route runs it in a
+ worker thread."""
+ sources = [_BACKEND / "mcp_server.py", *sorted((_BACKEND / "studio_mcp").rglob("*.py"))]
+ for path in sources:
+ tree = ast.parse(path.read_text(encoding = "utf-8"))
+ named = [
+ node
+ for node in ast.walk(tree)
+ # A name, an attribute, or a name imported from a module.
+ if "get_gpu_utilization" in (getattr(node, "id", None), getattr(node, "attr", None))
+ or isinstance(node, ast.ImportFrom)
+ and "get_gpu_utilization" in [alias.name for alias in node.names]
+ ]
+ assert not named, (
+ f"{path.name} reaches get_gpu_utilization() again; it blocks the event loop on the "
+ "warm's torch import"
+ )
+ status = (_BACKEND / "studio_mcp" / "tools" / "status.py").read_text(encoding = "utf-8")
+ routes = {node.value for node in ast.walk(ast.parse(status)) if isinstance(node, ast.Constant)}
+ assert "/api/train/hardware" in routes, "studio_status no longer reads the hardware route"
+ training = (_BACKEND / "routes" / "training.py").read_text(encoding = "utf-8")
+ assert (
+ "await asyncio.to_thread(get_gpu_utilization)" in training
+ ), "the hardware route no longer hands the read to a worker thread"
# -------------------------------- an authed reply is not both settled and not
diff --git a/studio/backend/utils/mcp_access.py b/studio/backend/utils/mcp_access.py
new file mode 100644
index 00000000000..30df095f2cd
--- /dev/null
+++ b/studio/backend/utils/mcp_access.py
@@ -0,0 +1,81 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Installation-wide switch for agent access to Unsloth Studio over MCP (``/mcp``). Off by default; the owner turns it on from Settings, and ``UNSLOTH_STUDIO_ENABLE_MCP=1`` forces it on. The value is read as the owner, so a managed account's API key sees the owner's switch and not its own settings database, and an unreadable setting counts as off."""
+
+from __future__ import annotations
+
+import os
+import threading
+import time
+from typing import Any, Optional
+
+from utils.account_context import OWNER, is_owner_context, run_as
+
+MCP_ENABLED_SETTING_KEY = "studio_mcp_enabled"
+ENV_FORCE = "UNSLOTH_STUDIO_ENABLE_MCP"
+
+# The gate asks on every /mcp request; each read opens its own sqlite connection.
+_CACHE_TTL_S = 1.0
+_cached: Optional[tuple[float, bool]] = None
+# Bumped by every write, so a read that started before it is never published.
+_generation = 0
+_cache_lock = threading.Lock()
+
+
+def _reset_cache() -> None:
+ """Test hook: forget a value cached before the DB was written directly."""
+ global _cached
+ with _cache_lock:
+ _cached = None
+
+
+def forced_by_env() -> bool:
+ return os.environ.get(ENV_FORCE) == "1"
+
+
+def _read_from_db() -> bool:
+ from storage.studio_db import get_app_setting
+ return run_as(OWNER, get_app_setting, MCP_ENABLED_SETTING_KEY, None) is True
+
+
+def get_mcp_enabled() -> bool:
+ """The owner's stored switch, ignoring the environment. Fails closed."""
+ global _cached
+ with _cache_lock:
+ cached = _cached
+ if cached is not None and time.monotonic() - cached[0] < _CACHE_TTL_S:
+ return cached[1]
+ generation = _generation
+ try:
+ enabled = _read_from_db()
+ except Exception:
+ return False
+ with _cache_lock:
+ if generation == _generation:
+ _cached = (time.monotonic(), enabled)
+ else:
+ enabled = False
+ return enabled
+
+
+def is_mcp_enabled() -> bool:
+ return forced_by_env() or get_mcp_enabled()
+
+
+def set_mcp_enabled(enabled: Any) -> bool:
+ global _cached, _generation
+ if not is_owner_context():
+ raise ValueError("Only the installation owner can change agent access over MCP.")
+ if not isinstance(enabled, bool):
+ raise ValueError("Agent access over MCP must be true or false.")
+ from storage.studio_db import upsert_app_settings
+
+ try:
+ upsert_app_settings({MCP_ENABLED_SETTING_KEY: enabled}, read_back = False)
+ finally:
+ # Invalidate even on failure: the write may have committed.
+ with _cache_lock:
+ _generation += 1
+ _cached = None
+ return enabled
diff --git a/studio/backend/utils/origin_policy.py b/studio/backend/utils/origin_policy.py
new file mode 100644
index 00000000000..f1b9743afbb
--- /dev/null
+++ b/studio/backend/utils/origin_policy.py
@@ -0,0 +1,106 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Origin comparison shared by main.py and the /mcp gate."""
+
+from __future__ import annotations
+
+import ipaddress
+import os
+from typing import Any, Optional
+from urllib.parse import urlparse
+
+DEFAULT_PORTS = {"http": 80, "https": 443, "ws": 80, "wss": 443}
+
+
+def canonical_origin(scheme: str, netloc: str) -> Optional[tuple[str, str, int]]:
+ """Canonicalise an Origin to ``(scheme, host, port)`` for equality. Browsers strip default ports (RFC 6454
+ sec 6.1) and scheme/host are case-insensitive (RFC 3986), so a bare string compare misclassifies
+ same-origin requests as cross-origin. Returns ``None`` on unparseable input so callers fall to the safer
+ cross-origin default."""
+ scheme = (scheme or "").strip().lower()
+ if not scheme or not netloc:
+ return None
+ # Strip userinfo (RFC 3986); Origin never carries credentials.
+ if "@" in netloc:
+ netloc = netloc.rsplit("@", 1)[1]
+ # IPv6 hosts use brackets (RFC 3986 3.2.2): bare partition(":") breaks `-H ::1`.
+ if netloc.startswith("["):
+ close = netloc.find("]")
+ if close == -1:
+ return None
+ host = netloc[1:close]
+ rest = netloc[close + 1 :]
+ if rest.startswith(":"):
+ port_str = rest[1:]
+ elif rest == "":
+ port_str = ""
+ else:
+ return None
+ else:
+ host, _, port_str = netloc.partition(":")
+ host = host.strip().lower()
+ if not host:
+ return None
+ if port_str:
+ try:
+ port = int(port_str)
+ except ValueError:
+ return None
+ else:
+ port = DEFAULT_PORTS.get(scheme, 0)
+ return (scheme, host, port)
+
+
+def origin_of(url: Optional[str]) -> Optional[tuple[str, str, int]]:
+ """Canonical origin of a URL or of an Origin header value, or ``None`` when it is neither."""
+ if not url:
+ return None
+ try:
+ parsed = urlparse(url)
+ except ValueError:
+ return None
+ return canonical_origin(parsed.scheme, parsed.netloc)
+
+
+# Never the localhost dev-server origins from host_policy: any local page could claim those.
+TAURI_ORIGINS = ("tauri://localhost", "http://tauri.localhost")
+_LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
+
+
+def _is_literal_ip(host: str) -> bool:
+ try:
+ ipaddress.ip_address(host)
+ except ValueError:
+ return False
+ return True
+
+
+def mcp_origin_allowed(
+ origin: str, *, request_scheme: str, request_netloc: str, app_state: Any
+) -> bool:
+ """Whether a browser page at ``origin`` may call /mcp. "Origin equals Host" is not enough: a DNS-rebound page has both set to its own name, so a named host is trusted only when Unsloth Studio itself published it (the tunnel, Tauri, UNSLOTH_CORS_ORIGINS)."""
+ if not origin or origin == "null":
+ return False
+ canon = origin_of(origin)
+ if canon is None:
+ return False
+ named = [*TAURI_ORIGINS, getattr(app_state, "cloudflare_url", None)]
+ named += [
+ entry.strip()
+ for entry in os.environ.get("UNSLOTH_CORS_ORIGINS", "").split(",")
+ if entry.strip() and entry.strip() != "*"
+ ]
+ if canon in {origin_of(value) for value in named if value}:
+ return True
+ try:
+ own = canonical_origin(request_scheme, request_netloc)
+ except ValueError:
+ own = None
+ scheme, host, port = canon
+ if host in _LOOPBACK_HOSTS and scheme in ("http", "https"):
+ ports = {getattr(app_state, "server_port", None), own[2] if own else None}
+ if port in ports:
+ return True
+ # A rebound name cannot pose as a literal IP, so the page's own LAN address is safe to trust.
+ return own is not None and canon == own and _is_literal_ip(own[1])