Skip to content

Studio: MCP errors, cancels and chat controls agents can act on - #14081

Merged
danielhanchen merged 16 commits into
unslothai:mainfrom
Etherll:fix/inline-mcp-actionable-errors-16d10d2b
Oct 19, 2026
Merged

danielhanchen merged 16 commits into
unslothai:mainfrom
Etherll:fix/inline-mcp-actionable-errors-16d10d2b

Conversation

@Etherll

@Etherll Etherll commented Oct 17, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Agents that drive Unsloth Studio over MCP couldn't tell one failure from another, saw cancelled work reported as failed, got hints naming parameters the MCP tools don't have, and sat through long calls with no progress. MCP errors now start with a machine-readable tag, cancelled jobs read as cancelled, long calls report a heartbeat, and chat, embed and cancel take the options agents were missing.

Changes

Error tags (studio_mcp/errors.py)

A failure an agent can branch on now starts with [<code> k=v]. Plain refusals stay untagged.

  • [gpu_busy retry_after=12] GPU busy: ... Retry after 12 s. for all three gpu_busy shapes.
  • [multi_model_always kind=chat] ... Call unload_model(kind='llm') to free the GPU; retrying won't help. Detected from the X-Unsloth-Refusal: multi-model-always header, the multi_model_always code, or the 409 copy. No Retry-After.
  • [active_generations running=N] ... with a hint to wait or cancel your own chat by cancel_id. The route's force_cancel_active advice is stripped, since the MCP tools don't expose it.
  • [memory_estimate] ... Pass allow_oversized=true to try anyway. for the 400 memory refusal.
  • [not_loaded kind=image] (or chat, video, audio, stt) for "No model loaded" answers, with the kind taken from the message or the route path.
  • A route's detail.code or /v1 error.code becomes the tag verbatim. The /v1 code used to be appended as a (code) suffix.
  • Deferred (padded 200) errors now read headers the route copied into _deferred_error, so the multi-model refusal is tagged there too.
  • llama-server startup failures keep the error lines (up to 8) instead of the full startup log, so the cause fits under the 2000-character cap.

Jobs and status

  • get_job on a cancelled video returns status: "cancelled" and error_code: "cancelled" instead of failed.
  • The export job listing returns format, phase, output and error for each job, newest first (ExportJobSummary).
  • VideoJobRef adds progress_percent, the same number JobStatus uses.
  • studio_status training: loss is None at step 0 instead of the 0.0 placeholder, and elapsed_seconds is reported. /api/train/status details now carry eta_seconds and elapsed_seconds.
  • A stop that lands during the final save no longer reads "Training completed!". It reads "Training cancelled." or "Training stopped." (core/training/training.py).

Tools

  • chat takes enable_thinking, reasoning_effort and response_format. Any finish_reason: "length" now adds a note: "The reply was cut off at max_tokens" when there is text, the existing reasoning note when there isn't.
  • chat, generate_audio and transcribe report a progress heartbeat every 2 s (studio_mcp/progress.py). The tool's own progress, such as transcribe's download fraction, goes into the heartbeat message so MCP progress only increases.
  • embed(query, top_k) ranks texts by cosine similarity to query and returns the top_k best (default 10) as matches with index, score and text, without vectors. top_k without query is refused, and query allows at most 2047 texts.
  • cancel(kind="video", id=...) stops only that video. POST /api/inference/video/generate/cancel accepts an optional {"video_id": "..."} body and answers 409 "That video is not rendering." when the id is not the running render, and 422 for an empty video_id. With no body it behaves as before.
  • cancel(kind="image" | "diffusion_training") now refuses an id instead of ignoring it.

Docs and copy

  • MCP INSTRUCTIONS are rewritten one sentence per line: the one-GPU rule, the heartbeat, polling intervals, the training flow, cancel by id and the error tags.
  • studio/MCP.md documents the Settings > API "Allow agent connections" switch, sets tool_timeout_sec = 300 for Codex, and adds a "Long calls" paragraph (MCP_TOOL_TIMEOUT=300000 for Claude Code). The chat, embed and cancel rows are updated.
  • The agent access copy in Settings > API (settings.apiKeys.mcp.description, enableDescription, exportKeyHint) says "Unsloth Studio" and "Unsloth Studio API key" in all 14 locales. "API key" matches UNSLOTH_API_KEY and the page's existing coding-agents hint; the token list above it still says "Access tokens", which this PR leaves alone. Values only, no key changes.

MCP clients that parse error text will see the tag prefix and the /v1 code moved from the end to the tag. EmbedResult.embeddings is now optional, but it is still returned whenever query is not set.

Testing

Run on this head (studio/backend, Unsloth Studio venv, CPU):

  • pytest tests/test_mcp_*.py tests/test_video_cancel_by_id.py tests/test_video_routes.py tests/test_training_status_eta_and_stop.py tests/test_training_status_terminal.py tests/test_training_stop_watchdog.py tests/test_job_accounts.py tests/test_openai_videos_route.py: 1823 passed, 4 failed. The same 4 fail on main e795149 in this environment: 3 in test_mcp_images.py (transformers vs huggingface-hub 1.33 import) and test_video_download_plan_judges_a_quantized_reference_pick_per_partition (PyAV not installed).
  • tests/test_training_*.py: the only failures are the same huggingface-hub import errors, also on main.
  • The new tests fail against main's sources: 38 tag/hint cases in test_mcp_errors.py, test_mcp_tool_contract.py and test_mcp_tools_loading.py, plus the training eta/elapsed and stop-during-save cases. The negative controls pass on both.
  • ruff check (0.6.9) is clean, scripts/run_ruff_format.py was applied, and npm run i18n:check:strict passes.

New test files:

  • tests/test_mcp_progress.py: heartbeat, the progress relay, strictly increasing progress, ctx-free schemas.
  • tests/test_training_status_eta_and_stop.py: eta/elapsed in /api/train/status, the stop-during-save and drafter-phase messages, and a no-stop run that still reads completed.
  • tests/test_video_cancel_by_id.py: a wrong id gets 409 and the render keeps going, the matching id cancels, no body behaves as before, bad bodies and an empty id get 422.

UI: before/after screenshots of Settings > API > Agent access (English and German) are in the evidence comment below.

Notes for related work

  • studio_mcp/errors.py keeps the multi_model_always hint on one constant (MULTI_MODEL_HINT) and has an empty CODE_HINTS map, so later work can add unload_model(kind="all") or audio-code hints without touching the detection.
  • The INSTRUCTIONS text marks the load, one-GPU, audio, polling, training and galleries lines with comments, so a later PR can add its sentence after the matching line.

UI before / after

Settings > API > Agent access (MCP) with agent connections on: the section description, the switch description and the UNSLOTH_API_KEY setup hint now say "Unsloth API key" instead of "access token". BEFORE is the merge base, AFTER is this PR, two separate installs.

Agent access (MCP) wording before and after

- Tag every MCP ToolError with the route's code: [gpu_busy retry_after=N],
  [multi_model_always kind=...] (unload_model hint, no retry), [active_generations]
  (wait or cancel your own chat), [memory_estimate], [not_loaded kind=...], and
  detail.code / /v1 error.code verbatim. Keep llama-server's error lines, not its log.
- get_job: a cancelled video reads cancelled with error_code; the export listing
  carries format, phase, output and error, newest first; VideoJobRef.progress_percent.
- Training status: loss is None at step 0; /api/train/status details carry
  eta_seconds and elapsed_seconds; a stop during the final save no longer reads
  Training completed.
- chat: enable_thinking, reasoning_effort, response_format, a cut-off note on any
  length stop, and a progress heartbeat (also on generate_audio and transcribe).
- embed(query, top_k) ranks texts and returns matches without vectors.
- cancel: video by id (route refuses an id that is not rendering); image and
  diffusion_training refuse an id.
- Rewrite the MCP INSTRUCTIONS, MCP.md setup/timeout docs, and the agent access
  copy in all 14 locales (Unsloth Studio, Unsloth Studio API key).
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-19T01:20:02.271470Z 762d030 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Etherll

Etherll commented Oct 18, 2026 •

Copy link
Copy Markdown
Collaborator Author

Review and evidence (head 7584704b7c)

UI: Settings > API > Agent access, before (main e795149d99) and after, English and German. Only the three settings.apiKeys.mcp strings change; layout and components are untouched.

Agent access before and after

Review. A two-lane review of 475e4330d3 closed all 231 obligations with no findings. Codex raised one P2 on that head: an explicit empty video_id was turned into an unscoped cancel, so cancel(kind="video", id="") would stop whatever the caller was rendering. 7584704b7c now answers that with a 422 ("video_id is empty; leave it out to stop the running render."), and the render keeps going. The new test fails on 475e4330d3 and passes here.

Tests on this head (studio/backend, Unsloth Studio venv, CPU):

  • tests/test_mcp_*.py, test_video_cancel_by_id.py, test_training_status_eta_and_stop.py, test_job_accounts.py: 1602 passed, 3 skipped, 3 failed. The 3 failures are in test_mcp_images.py (transformers vs huggingface-hub import) and fail the same way on main.
  • test_video_cancel_by_id.py, test_mcp_tools_cancel.py, test_video_routes.py: 120 passed, 1 failed (test_video_download_plan_judges_a_quantized_reference_pick_per_partition, PyAV not installed, also fails on main).
  • With main's sources and this PR's tests, 69 of the new cases fail, so they cover the change.
  • ruff check 0.6.9 is clean and scripts/run_ruff_format.py was applied.

Codex: two "Didn't find any major issues" in a row on 7584704b7c (Etherll/unsloth-staging-review#82, mirror head c3aaa9934b), after the P2 above was fixed.

@danielhanchen

Copy link
Copy Markdown
Member

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

Failed to sample tokens
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…ed completion as stopped, and say chat cancel ids are chosen up front

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

… drop a progress note its phase stopped sending
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

Failed to sample tokens
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: ad4b7a8dfc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: c99643359c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 18, 2026
danielhanchen added a commit that referenced this pull request Oct 19, 2026
…cks takes and cancels by id (#14080)

Includes #14075 (Studio: clearer audio.cpp errors, cleaner Speak/Clone,
reproducible takes); review the non-merge commits from 14e6b65 to
HEAD (skipping #14075's own fix commits that came in by merge), or `git
diff dfa58e0..HEAD` against #14075's head.

## Summary

An agent using Unsloth Studio over MCP could not tell when a music
duration was clamped or an option was dropped, got bare error text from
audio.cpp failures, had no way to check a finished take, and could not
stop an audio run (`cancel` said "Audio runs cannot be cancelled"). This
adds those four things to the audio routes and the MCP tools.

## Changes

Audio routes:

- `/audio/run` answers with `applied` (the music `duration_s` actually
used) and `warnings` (`"duration_s 600 clamped to 240"`, plus one
`Ignored option <name>` line per entry in `ignored_options`). Clip rows
carry `voice_id` and `source_clip_id`, and Separate stem rows carry
`source_clip_id`.
- `/audio/run` takes an optional `cancel_id`. `POST /audio/cancel
{"cancel_id": ...}` stops that run the way a client disconnect does: it
answers 499 and saves nothing. The key is namespaced as `("audio", id)`,
so a chat `cancel_id` cannot stop an audio run. The run registers its id
before any model switch, so a cancel sent while a cold model is still
loading stops the run once the load ends, before anything is generated.
A cancel that arrives while the clips are being saved removes the clips
the run made, including an Edit source recording it saved (one an
earlier run kept, or one another Edit now plays, stays; an Edit's source
handoff and this cleanup share a lock), and still answers 499. A second
run under a `cancel_id` that a running audio run holds gets 409, so one
cancel never stops two runs. A cancel that arrives before the run starts
is kept for 30 s.
- New `POST /audio/analyze` measures an upload, history clip or saved
voice: duration, integrated loudness (BS.1770-4, gated), true peak (4x
oversampled), clipped samples (runs of 3+ identical samples at full
scale that the waveform lands on or leaves more steeply than a smooth
peak could: PCM rounds a clean peak to a flat top of L samples that it
leaves by at most about ((L + 1) / (L - 1))² quantization steps, so the
limit is twice that, using the WAV's own sample width (for 32-bit PCM
the float32 spacing near full scale, 2^-24). Clean 16-bit tones from 1
Hz to 2 kHz at 0.99-1.0 of full scale count 0 (400 random tones), and a
2% overdrive counts from 10 Hz to 1 kHz, in 8-bit too, where a clean
tone within 1% of full scale also reads as clipped because 8-bit is too
coarse to tell the two apart) and the span that holds sound (a final
partial 20 ms frame counts, so a 6 ms beep has a span). With
`expected_text` it transcribes with the resident speech-to-text model
(or the default) and returns `match_score`, 1 minus the word error rate,
or null when the two texts are too long to align (over 50 million word
pairs, about a quarter second of numpy work). Nothing is saved. Clips
over 10 minutes get 413. The measurements are in
`core/inference/audio_metrics.py`, which uses numpy only and walks the
audio in chunks: a 10-minute 48 kHz stereo clip needs about 21 MiB of
working memory on top of the decoded audio, and clipping runs are judged
per chunk, so even audio at full scale every other sample stays at a few
MiB. Transcript scoring runs off the event loop.
- An audio.cpp runtime that dies or goes silent mid-request on generate,
separate or music now raises a 500 with code `runtime_stopped` and the
message "The audio runtime stopped: <reason>. Try again; if it fails
again, load the model again." Paths and tokens are removed from the
reason. A failure that #14075 already classified (out of memory and so
on) is re-raised unchanged.

MCP tools:

- `generate_audio` returns `applied`, `warnings`, `ignored_options` and
`cancel_id`. It accepts a `cancel_id` and makes one (`mcp-<hex>`) when
omitted. A reused id that is still running or was cancelled in the last
30 s is refused.
- When the loaded music model makes variations one at a time
(`variations.how == "sequential"` in status), `generate_audio` sends
them take by take under one `group_id`, reusing take 1's seed, as the
Audio page does. A cancel between takes stops before the next POST and
keeps the finished takes. A take that fails after earlier takes
succeeded becomes a warning instead of losing the finished clips.
- `cancel(kind="audio", id=<cancel_id>)` stops a run: between takes it
stops locally, otherwise it posts to `/api/inference/audio/cancel`.
- Audio route failures with a known code now start with a `[code]` tag
and end with what to do next, from `AUDIO_HINTS` in
`studio_mcp/errors.py`. For example `[out_of_memory]` suggests
`device='cpu'` and lists the smaller variants when the error body
carries them (the `/v1` error envelope that `generate_audio` reads keeps
only the code, so there the hint stays generic), and `[runtime_stopped]`
says to retry once and then reload the model.
- `transcribe` gains `speakers` (labels each segment's speaker; it needs
a diarizing model and always uses the stored-audio route) and
`expected_text` (adds `match_score`).
- New `analyze_audio` tool wraps `/audio/analyze`. It is not marked
read-only, because inline audio or a path is uploaded to Unsloth Studio
first. If the speech-to-text model is not downloaded, the 409 hint says
to run `transcribe` once or leave out `expected_text`.
- `studio_status` lists the active music model's `duration_s` min, max
and default per mode as `audio_music`, so an agent can see the clamp
range before it asks for a duration.
- `studio/MCP.md` documents `analyze_audio` and the new `transcribe`
arguments. Its `cancel` row and the "Audio runs cannot be cancelled"
sentence are left alone here: #14081 rewrites that row into a
kind-agnostic form and #14089 removes the sentence, and those PRs own
those lines. The audio kind is documented in the `cancel` tool's own
docstring.

One small edit lands on #14075's code (the only edit outside this PR's
own files, in its own commit):

- d46103b: `_CODES` in `audio_cpp_failures.py` gains
`runtime_stopped`, so the worker and orchestrator keep that code when
they rebuild a failure.

## Testing

New tests:

- `tests/test_audio_metrics.py`: a -20 dBFS 1 kHz sine measures -23.0
LUFS and -20.0 dBTP within 0.05; hard clipping is detected and clean
full-scale 10 Hz, 100 Hz and 1 kHz sines are not, also as 16-bit WAVs at
10 Hz and 40 Hz and at 50 Hz and 0.999 of full scale, while a 10%
overdriven 10 Hz WAV is, and so is an overdriven 100 Hz 8-bit WAV; 8-bit
clipping counts on both rails; small chunk sizes give exactly the
one-pass numbers; padded silence gives the expected span; silence gives
`None`; cross-checks against pyloudnorm and jiwer when installed.
- `tests/test_audio_analyze_route.py`: metrics, `match_score` with a
stubbed transcriber, the speech-to-text 409, non-WAV input through
transcode, on both mounts.
- `tests/test_audio_edit_route.py`: a cancel during the save removes the
source recording the run saved (with or without a kept output) and keeps
one an earlier run saved or another Edit now plays.
- `tests/test_audio_run_cancel.py`: two concurrent runs with ids A and
B; cancelling A gives A 499 and B 200; a chat `/cancel` with id A stops
nothing; a cancel sent during a slow model load gives 499 and never
starts generation; a cancel sent while the clip saves gives 499 and
removes the saved clip; a second run under a live `cancel_id` gets 409.
- `tests/test_audio_run_extras.py`: `applied`, clamp and ignored-option
warnings, `voice_id` and `source_clip_id` on clip rows.
- `tests/test_audio_runtime_stopped.py`: generate, separate and music
map a mid-request stop to `runtime_stopped` with no path or token in the
message; an attached `out_of_memory` passes through unchanged; the code
survives the worker, orchestrator, route and `/v1` envelope.
- `tests/test_mcp_audio_takes.py`, `tests/test_mcp_audio_reports.py`,
`tests/test_mcp_audio_hints.py`: take-by-take runs and cancel during and
between takes, reused id refusal, batch mode as one request, reported
fields, and `[code]` hints.

Existing MCP contract tests (`test_mcp_server.py`,
`test_mcp_tool_contract.py`, `test_mcp_no_host_paths.py`,
`test_mcp_tools_audio.py`, `test_mcp_tools_status.py`) are updated for
the new tool, the `audio` cancel kind and the new output fields.

Results on c7d6ade (Linux, CPU):

- Every test file this PR touches (25 files, including
`test_audio_run_route.py` and `test_audio_edit_route.py`) plus
`test_audio_edit_requests.py` and `test_audio_gallery.py`: 1035 passed.
- On 2e46efe, all `tests/test_mcp_*.py`: 1475 passed, 3 skipped, 3
failed. The 3 failures are in `test_mcp_images.py` and fail the same way
on #14075's head (a transformers / huggingface-hub version mismatch in
the test venv).
- A live check on an earlier head: with a dead audio runtime injected on
the first request, a fresh agent driving the MCP tools got
`[runtime_stopped]`, retried once as the hint says, and got its clip.
- Negative controls: without the new except branches the three
runtime_stopped cases raise the bare runtime error; with
`runtime_stopped` removed from `_CODES` the orchestrator drops the code;
without the namespaced cancel key `/audio/cancel` stops nothing and a
chat `/cancel` would stop the audio run; without the run-length rule a
2-sample burst counts as clipping; with the cancel registered only after
the model switch (the previous code), the slow-load cancel test times
out because the run goes on to generate; without the after-save check
the save-time cancel answers 200 and keeps the clip.

The first commit (14e6b65) is the shared one-name-per-line reshape of
`test_mcp_server.py`, byte-identical to the same commit in the sibling
MCP PRs, so their tool-name additions merge cleanly.

```bash
cd studio/backend
python -m pytest tests/test_audio_metrics.py tests/test_audio_analyze_route.py tests/test_audio_run_cancel.py tests/test_audio_run_extras.py tests/test_audio_runtime_stopped.py tests/test_mcp_audio_takes.py tests/test_mcp_audio_reports.py tests/test_mcp_audio_hints.py tests/test_mcp_server.py tests/test_mcp_tool_contract.py tests/test_mcp_no_host_paths.py tests/test_mcp_tools_audio.py tests/test_mcp_tools_status.py -q
```

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
# Conflicts:
#	studio/backend/studio_mcp/errors.py
#	studio/backend/studio_mcp/tools/audio.py
#	studio/backend/studio_mcp/tools/cancel.py
#	studio/backend/tests/test_mcp_tools_status.py
@danielhanchen
danielhanchen merged commit 43ceef8 into unslothai:main Oct 19, 2026
danielhanchen added a commit that referenced this pull request Oct 19, 2026
… load unloads (#14089)

Includes #14088 (Studio: add an Always choice to Keep multiple models
loaded, track every model on the GPU, and report every model a load
unloads); review the last 16 commits (7c4c66d..HEAD, leaving out the
merges of #14088's branch and pre-commit.ci's autofix).

## Summary

Agents followed long Unsloth Studio work by polling in shell loops: in
one promo run, 598 of 854 MCP calls were polls. `load_model` blocked for
the whole download and load, so a client timeout (Codex defaults to 60
s, and 8 of 14 promo loads took longer) lost the result. Loads also
missed media evictions (`load-ltx` over Qwen-Image reported `evicted:
[]`), `unload_model(kind="tts")` echoed `"llm"`, and MCP.md said long
work "returns at once". With this change, one `get_job` call waits for a
job to move, a load outlives the call that started it, and every load
names what it unloaded.

## What changes

- `get_job` takes `wait_s` (0 to 240). It re-reads the job every 2 s,
reports progress, and returns when the job finishes, its status or phase
changes, or the wait runs out. A job that is still running includes
`poll_after_s`.
- `get_job` gains the kinds `training` and `diffusion_training` (run
folder and checkpoint names once completed) and `load`.
- `load_model` takes `wait_s` (240 s when unset). The load runs as a job
in the new `studio_mcp/job_store.py`, so a client that stops waiting
does not stop it. An early return gives `status: "loading"` and a
`job_id` for `get_job(kind="load")`, and calling `load_model` again
joins the load already in flight. The job is registered before any route
read (resident-model snapshot, image and video Hub and download-plan
reads), so `wait_s=0` always returns a `job_id` at once.
- Loads return `evicted_slots` (`{kind, model}`). The list comes from
the load response's `evicted_slots` (added by the included PR), else its
`evicted` ids placed by a snapshot of resident models, plus a
before/after diff of the slots that list does not cover (all of them for
routes that report nothing).
- A repeat `load_model` with the same model, variant, settings and Hub
token joins the load already running; so does a chat load (without
`variant`) that Unsloth Studio is already running for another caller. A
failed status read while following a load is skipped.
- An image or video `load_model` of another variant of the resident repo
waits for that variant: the resident check compares the requested GGUF
file (image status) or its quant and MiniMax-H3 partition (video
status), not only the repo id. Video status drops a `-<n>bpw` suffix, so
a bpw build is confirmed only once the load reports ready.
- `unload_model` echoes the kind that was requested, and speech-to-text
loads run as jobs too. `cancel` has no load kind, so
`unload_model(kind="image"|"video"|"stt")` also stops a `load_model` of
that kind still running. Image and video post their unload route, which
cancels a pending load. A speech-to-text load still downloading has its
download cancelled; one past its download is unloaded once it finishes,
even if that takes longer than the call. Chat loads in flight keep their
earlier unload behavior: stopping a GGUF download needs the load to
carry a `load_request_id`, which is left for a follow-up.
- `export_jobs.py` is now a thin wrapper over the job store.
- The server INSTRUCTIONS still say "poll get_job"; #14081 rewrites
INSTRUCTIONS, and the `wait_s` sentence goes in after it lands. Until
then the `load_model` and `get_job` descriptions carry the `wait_s`
guidance.
- MCP.md describes `wait_s`, the 240 s cap, and `wait_s=50` for Codex's
60 s default timeout, and drops "Audio runs cannot be cancelled" (the
cancel tool's own description keeps that fact until audio cancel lands).

## Tests

- `tests/test_mcp_tools_loading.py` and the new
`tests/test_mcp_tools_jobs.py`. Every new test fails on main
`e795149d99` and passes on this head.
- Full `tests/test_mcp_*.py` suite: 1506 passed, 3 skipped on the
current head (merged with #14088).

```bash
cd studio/backend
python -m pytest tests/test_mcp_tools_loading.py tests/test_mcp_tools_jobs.py -q
python -m pytest tests/test_mcp_*.py -q
```

## Live check

Unsloth Studio from this branch on one B200, MCP clients with a 60 s
timeout, fresh no-context agents given only the task:

- "Render 3 short clips and train 30 steps on a tiny model": 24 tool
calls, 1 `get_job(wait_s=50)` per clip (Wan2.2-TI2V-5B), 5 for the
30-step run (each returned on a phase change), no shell loop, no client
timeouts.
- "Load a 7B+ model, then chat for a 2k-token reply":
`unsloth/Qwen3-8B-GGUF` loaded inside `wait_s=50`, chat returned 2,383
tokens.
- Image then video load: the video `load_model` answered
`"evicted_slots":[{"kind":"image","model":"unsloth/Z-Image-Turbo-GGUF"}]`;
on main this was `evicted: []`.
- A 9 GB `unsloth/Qwen3-14B-GGUF` load whose client gave up after 5 s
kept running; the next `load_model` returned `status: "loading"` with a
job id, a third call got the same job id, and `get_job(kind="load",
wait_s=50)` returned the loaded result. The server log shows one
download and one llama-server start.


















## Follow-ups

- A video download plan that picks a plain `.safetensors` checkpoint
while a GGUF build of the same repo is resident can still read as loaded
early, because video status names no checkpoint file. The fix (reject a
GGUF resident for a non-GGUF request) is a narrow build-matrix case,
kept for a follow-up.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Etherl <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
danielhanchen added a commit that referenced this pull request Oct 19, 2026
…oad models ahead of time (#14107)

Includes #14088, #14089 and #14090; review the last 24 commits
(7cbecec..HEAD: `git log --no-merges 06a089d..HEAD`), leaving out
the merges of #14090's branch.

## Summary

Over MCP, an agent could start training in Unsloth Studio, but it could
not upload its own data, load the model it had trained, or download the
next model ahead of time. This PR adds dataset uploads, loading a
checkpoint or export by name, a resolved `validate_only` echo, TTS
fine-tuning guidance, and a `download_model` tool backed by Unsloth
Studio's download manager.

## Changes

### Datasets

- `datasets(action="upload", filename, data_base64 | rows)` sends a file
to `/api/hub/datasets/upload`. It returns a `ref:` handle for
`config.local_datasets`, never the stored path the route returns.
- `datasets(action="upload_images", name, images, captions)` sends
captioned images to the diffusion dataset route. Every image gets a
fresh file stem, so a later upload never replaces an earlier one. Images
past Unsloth Studio's upload limit are refused before anything is sent,
with a note to split them across calls. It returns the dataset name that
`start_training(kind="diffusion")` takes as `data_dir`.

### Loading what you trained

- `load_model(checkpoint="<run>" | "<run>/checkpoint-N")` resolves the
name through `checkpoints.resolve`. `load_model(export="<name>")`
resolves it under the exports folder, and `variant` picks a GGUF
export's quantization.
- Both load through a minted `ref:` handle and report the name back,
never a path or the handle. `evicted_slots` entries get their names back
the same way, and so does the `get_job(kind="load")` result of a load
that outlasted `wait_s`. `unload_model(model=<that name>)` finds it.
- `is_lora` follows the run's PEFT type, passed through #14090's
`is_lora` kwarg. The load route detects LoRA itself, so a full fine-tune
is not forced to load as LoRA.
- A GGUF export loads as its folder plus the quantization in its file
name, or the `variant` passed, so `device="cpu"` places it as GGUF. An
export whose file name has no quantization needs `variant` before it can
be placed. A checkpoint is refused for `device="cpu"`.
- `checkpoint` and `export` are refused for `kind` image, video and stt.
- Unsloth Studio serves a trained load under its `ref:` handle, so the
field text says to chat with it by leaving `chat`'s `model` unset.

### `start_training`

- `validate_only` now returns the resolved config, with every path and
secret dropped.
- Refusals name the model as the caller sent it, never the host path a
`ref:` handle resolves to.
- It runs the trainer's audio-type detection. GGUF, audio.cpp and native
TTS ids are refused, with the list of trainable bases. It sets
`is_dataset_audio` for codec TTS: Orpheus/SNAC, CSM, Spark/BiCodec and
OuteTTS/DAC. A real start runs the same check, so it refuses the same
models and sends `is_dataset_audio` for codec TTS.
- The docstring names the trainable TTS bases:
`unsloth/orpheus-3b-0.1-ft`, `sesame/csm-1b`, `unsloth/Spark-TTS-0.5B`
and `unsloth/Llama-OuteTTS-1.0-1B`. It covers:
- the columns (audio + text, optional speaker_id) and the
`custom_format_mapping` roles;
  - CUDA only;
  - that GGUF/audio.cpp TTS (Qwen3-TTS, Breeze) can't be trained;
- the one-GPU order main uses: training unloads image and video models,
and unloads chat or TTS only when they don't fit next to it. A 409 comes
back while inference is running. Then export →
`load_model(checkpoint/export)` → `generate_audio`.
- Agents follow training with `get_job(kind="training", wait_s=50)`
instead of `studio_status`.

### Prefetch

- `ALLOWED_PREFIXES` gains exactly `/api/hub/download`. That covers
`/download`, `/download-status`, `/download-progress` and
`/download/cancel`, and nothing else under `/api/hub`.
- `download_model(model, kind, variant?)` starts a download without
loading anything. GGUF repos send `gguf_variant`, image and video send
their download-plan entries with `scope_id="diffusion"`, a native TTS or
audio model sends its audio download-plan entries (companion codec repos
included) with `scope_id="audio"`, and STT reuses `download_stt`. Image
and video downloads take the same options `load_model` takes
(`memory_mode`, `speed_mode`, `transformer_quant`, `text_encoder_quant`,
`h3_task`), so the plan stages the files the load will read.
- The id carries each start's `generation`, so
`cancel(kind="model_download", id)` (through `/download/cancel`) stops
only the run `download_model` started. `get_job(kind="download", id)`
reads `/download-status` and works with `wait_s`.
- An image or video download that fails part-way stops the parts it
already started. A cancel stops every part before it reports a refusal.
- `repo:variant` shorthand downloads and waits on that variant. A native
speech prefetch under `kind="tts"` or `"audio"` serves a load of either
kind.
- K16 guard 2: `load_model` waits for a running Unsloth Studio download
of the same model or variant before #14090's partial-variant refusal.
The wait runs inside the load job (#14090 now runs every pre-load read
there), so it outlives `wait_s`: the call returns `loading` with a job
id, `get_job(kind="load")` names the download id while it waits, and the
load starts once the download ends. The wait is capped at an hour, after
which the load fails and names the download id. A managed download is
waited on, never refused. An attach to an in-flight load (guard 1) still
comes first, and an unmanaged partial variant is still refused.
- New outputs: `JobStatus.download` and `DownloadRef`.

`studio/MCP.md` gets the `download_model` row and updated `datasets` and
`start_training` rows.

## Testing

New tests: `test_mcp_tools_datasets_upload.py`,
`test_mcp_tools_datasets_images.py`,
`test_mcp_tools_training_validate.py`, `test_mcp_tools_download.py`,
`test_mcp_train_to_use.py` and `test_mcp_k16_guard_order.py`.
`test_mcp_server.py`, `test_mcp_forward.py`,
`test_mcp_no_host_paths.py`, `test_mcp_tool_contract.py` and the cancel,
jobs, placement, training and video tests were updated. #14090's
allowlist test now expects the whole download manager to be forwarded.
In #14090's `test_mcp_tools_plan_load.py`, the fake `download-status`
now reports only the partial Q8_0 as running: with guard 2, a
`load_model` waits on any running managed download, so a world where
every download is running made those loads wait out `wait_s`.

```bash
cd studio/backend
python -m pytest tests/test_mcp_*.py tests/test_gpu_arbiter.py tests/test_multi_model_always.py tests/test_multi_model_settings.py -q
```

Result on this head: 1,840 passed, 3 skipped.

GPU run on the head before the last two own commits (one device, real
Unsloth Studio on its own port, 91 MCP calls):

- **Train to use:**
- `datasets(upload)` with 40 rows returned a `ref:`, and `validate_only`
echoed the config with no paths.
- `unsloth/Qwen3-0.6B` trained for 10 steps (~57 s), followed with
`get_job(kind="training", wait_s)`.
- `load_model(checkpoint=<run>)` loaded it in 26 s, reported the name
only, and `chat` answered. `checkpoint-5` also loaded.
- `export_model(format="lora")`, then `get_job(kind="export")`, then
`load_model(export="<run>/lora")` and `chat` worked.
  - `unload_model(kind="all")` returned GPU memory to baseline.
- **TTS:** MOSS-TTS-Nano and Qwen3-TTS GGUF were refused with the
trainable list. Orpheus `validate_only` set `is_dataset_audio`.
- **Prefetch ("plan a film for a 24 GB card and prefetch everything",
GPU size stubbed):** zero calls went around MCP.
- `download_model` worked for Qwen3-4B-GGUF UD-Q4_K_XL, Z-Image-Turbo
and Wan2.2-TI2V-5B GGUF (already on disk, so they came back completed),
and audio.cpp TTS.
- FLUX.2-klein and LTX-2.3 (69 GB) were cancelled while running with
`cancel(kind="model_download")`.
- A `load_model` during a running download returned `loading` with a job
id and later finished.

No UI change.

## Not in this PR

- The INSTRUCTIONS prefetch sentence waits for the MCP errors PR
(#14081), which owns INSTRUCTIONS.
- After a checkpoint or export load, `studio_status` and
`unload_model(kind="all")` show its `ref:` handle (opaque, not a path)
instead of its name. That code is owned elsewhere; follow-up.
- GGUF and diffusion downloads report no percent, because
`gguf-download-progress` is left off the allowlist on purpose.
- A merged or LoRA export whose `save_directory` has only one level is
not found by name. Use `"<run>/<name>"`.
- Backend TTS refusals and an audio dataset builder are deferred.

## Follow-ups

- A safetensors repo whose id contains "gguf" is treated as GGUF by
`download_model` (no variant listed, so it is refused). This is the same
name-based rule #14090's `is_gguf` uses for loads, so prefetch and load
agree. Moving both to the listing signal is a follow-up.
- A `get_job(kind="load")` read in the same event-loop turn a trained
load finishes can still show its `ref:` handle, and a cancelled trained
load names the handle. The fix belongs in the shared load job runner.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Etherl <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
danielhanchen added a commit that referenced this pull request Oct 19, 2026
#14080 and #14081 landed together and their error tagging now overlaps:
`tool_error` (from #14081) leads every route error with its `[code]`
tag, while an audio.cpp failure whose message already starts with
`[out_of_memory]` got the tag a second time (`[out_of_memory]
[out_of_memory] Out of memory.`). Five tests in
`tests/test_mcp_audio_hints.py` fail on main because of it.

- `studio_mcp/errors.py`: `tool_error` leaves a message that already
starts with its own `[code]` tag as it is.
- `tests/test_mcp_audio_hints.py`: the gpu_busy case expects the
`[gpu_busy retry_after=5]` tag #14081 adds (still no audio tag), and the
"other errors" cases check that the audio path returns exactly what the
generic route error returns instead of asserting no tag at all.

`python -m pytest tests/test_mcp_*.py`: 2038 passed, 5 skipped (main: 5
failed in test_mcp_audio_hints.py).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants