Skip to content

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

Merged
danielhanchen merged 104 commits into
unslothai:mainfrom
Etherll:fix/inline-studio-mcp-agents-905d73a2ece1
Oct 13, 2026
Merged

danielhanchen merged 104 commits into
unslothai:mainfrom
Etherll:fix/inline-studio-mcp-agents-905d73a2ece1

Conversation

@Etherll

@Etherll Etherll commented Oct 9, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Coding agents such as Claude Code and Codex can now drive Unsloth Studio through /mcp/ with a normal Unsloth Studio API key (sk-unsloth-...). The owner turns it on with UNSLOTH_STUDIO_ENABLE_MCP=1, or through the owner-only /api/settings/mcp-access route from a signed-in session. studio/MCP.md documents setup for each agent. #13167 adds the Settings > API section that switches it on and builds the setup command, and it builds on this pull request.

The old tools called route functions directly. That had three bugs, all fixed here:

  • They ran as the installation owner, so managed-account checks were skipped.
  • Unresolved FastAPI Depends defaults put host paths in the output of get_training_status, list_local_models and list_training_runs.
  • studio_status returned the unredacted inner status.

Every tool now calls Unsloth Studio's own HTTP routes in-process as the API-key caller, and tool outputs are typed models that have no host-path fields.

BREAKING CHANGE

  • UNSLOTH_STUDIO_MCP_TOKEN is retired. /mcp answers 401 The MCP static token is no longer supported; use an Unsloth Studio API key (sk-unsloth-…), and startup logs one warning while the variable is set.
  • UNSLOTH_STUDIO_ENABLE_MCP=1 still forces /mcp on, but callers now need an sk key. Startup no longer raises when the token is missing.
  • Renamed or merged tools:
    • list_local_models -> list_models
    • get_training_status -> studio_status
    • stop_training -> cancel
    • validate_recipe, get_recipe_job_status, get_recipe_job_dataset -> run_recipe and get_job
    • load_checkpoint + export_gguf -> export_model

Migration: create a key in Settings > API, start Unsloth Studio with UNSLOTH_STUDIO_ENABLE_MCP=1, and point the agent at http://<studio>/mcp/ with Authorization: Bearer <key>.

What agents can do

18 tools, each with an outputSchema:

  • Models: list_models, load_model (llm, image, video, stt, plus the tts and audio kinds list_models reports; downloads STT models first), unload_model, studio_status (every model slot, and whether an image or video is generating).
  • Text: chat (with images), embed, system_one.
  • Media: generate_image (txt2img, img2img, inpaint, upscale, edit/reference/outpaint), generate_audio (clone, speak, edit, convert, music, separate), transcribe (transcribe or translate; large files go through the upload route), generate_video.
  • Training and data: start_training (LLM or diffusion LoRA; the config is checked before any GPU work, validate_only checks it without starting, and the result carries the id that cancels a pending start), list_training_runs (runs and their checkpoints by name), export_model (gguf, merged, lora, base), datasets (list, check_format, download, status), run_recipe (validate, preview, full).
  • Jobs: get_job (video, recipe, export), cancel (training, export, recipe, image, video, chat, dataset download).

Media inputs are accepted as an Unsloth Studio id, inline data, or a local file path. Small media results come back inline and larger ones as a preview plus a link.

How it is gated

  • The switch is off by default. While it is off, /mcp/ answers the same 404 as an unknown path. Only the owner can change it, and only from a signed-in UI session; an API key gets 403.
  • A request with a foreign Origin gets 403.
  • Only a valid, non-workflow Unsloth Studio API key is admitted. No auth, Bearer not-needed and other keyless bearers, UI sessions, and recipe or Deep Research workflow keys get 401, whatever the keyless scope is.
  • /.well-known/oauth-* returns 404 so MCP clients send the key instead of starting an OAuth login. POST /mcp/decisions redirects (307) to /mcp/decisions/.
  • Forwarded calls come from a TEST-NET client address (192.0.2.1) with an .invalid Host, so loopback, LAN and keyless checks never pass. Only the caller's own key (plus an optional X-Unsloth-HF-Token) is replayed, and only to the same Unsloth Studio, so this is not token passthrough to another service.
  • File-path inputs are refused unless the request comes from the Unsloth Studio computer itself.

Known limits:

  • URL and YouTube transcription is not supported. There is no backing route.
  • Remote agents must send media as data or an Unsloth Studio id, because file paths only work on the Unsloth Studio computer.
  • An API key cannot unload a model loaded from a local folder, because /unload does not resolve ref handles. This is pre-existing.
  • Recipe job ids are not bound to an account (pre-existing single-slot route).
  • Some routes still return host paths to direct API-key callers: /api/models/checkpoints, export status and logs, recipe artifact_path, diffusion status, and local/cached datasets. The MCP tools never pass these through. Fixing the routes is out of scope here.

Testing

From studio/backend:

pytest tests/test_mcp_*.py tests/test_hub_write_ambient_token.py tests/test_export_expected_checkpoint.py \
  tests/test_keyless_api_access.py tests/test_origin_policy.py tests/test_middleware.py \
  tests/test_warm_window_review_fixes.py

1729 passed and 4 failed on fastmcp 3.2.4. The same 4 fail on main in this environment: 3 test_mcp_images tests and one test_hub_write_ambient_token test, which need a GPU or a matching transformers and huggingface-hub pair. The MCP tests also pass on fastmcp 3.4.8 and 4.0.11, apart from the same 3 image tests.

Live end to end on one GPU, with an Unsloth Studio built from this branch and a real sk-unsloth key:

  • Switch off gives 404 on /mcp/. An API key cannot turn the switch on (403). A foreign Origin gets 403.
  • Bearer not-needed and no auth get 401 with keyless scope off and with it set to full. The old UNSLOTH_STUDIO_MCP_TOKEN gets 401 with the retirement message.
  • POST /mcp/decisions gives 307 to /mcp/decisions/, and /.well-known/oauth-* gives 404.
  • tools/list returns 18 tools, each with an outputSchema.
  • Qwen3-0.6B GGUF: load, chat, embed, unload.
  • sdxl-turbo: txt2img, then img2img from a local path and from a gallery id.
  • Kokoro speak, HTDemucs separation into 4 stems, and transcription with an automatic STT download, including a 27 MiB WAV through the upload path.
  • Wan2.2-TI2V-5B: a 1 s video job completed with an inline thumbnail and an MP4 link.
  • run_recipe validate, datasets list, list_training_runs.
  • A file-path input from a non-loopback address is refused.
  • claude mcp add --transport http ... --header "Authorization: Bearer $KEY", then claude mcp list shows Connected.
  • No host path appeared in any of the 46 saved tool results.

First-time agents with no prior context ran tasks through the tools, using models from capable ones down to a small one at low, medium and high effort. The tasks were chat, images, image edits, speech, transcription, embeddings, video, fine-tune setup, and checking and stopping GPU work. Their friction notes led to the config check above, clearer tool descriptions and errors, and a note when a thinking model's reply runs out of tokens before any text.

Etherll added 30 commits October 8, 2026 20:09
Agents should reach Studio over MCP only when the owner opts in. The switch is read as the owner and fails closed, so a managed account's key or a damaged settings DB never opens /mcp, and UNSLOTH_STUDIO_ENABLE_MCP=1 still forces it on.
The owner needs a way to open /mcp without restarting Studio with an env var. Only a UI session may flip it, because MCP admits API keys and a key must not be what opens it; a PUT while the env var forces it on is refused.
The owner switch has to take effect without a restart, so /mcp is always mounted and a gate answers a plain 404 while it is off, before reading anything about the caller. The gate also sends /mcp/decisions back to its own mount, which the always-on /mcp would otherwise swallow.
MCP tools act for whoever holds the key, so /mcp takes a valid sk-unsloth key and nothing else: keyless access, dummy bearers, UI sessions and workflow keys are refused at every keyless scope. The gate validates read-only and records the caller in the request scope, leaving account binding to the forwarded route call.
A shared static token cannot say which account an agent acts for, while API keys can and can be revoked one at a time. A bearer equal to the old token now gets a 401 that points at API keys, Studio logs one warning when the variable is still set, and it no longer refuses to start without it.
A web page must not be able to drive Studio's MCP tools from the browser, and comparing Origin with Host does not stop DNS rebinding. The gate accepts only the origins Studio already trusts (loopback at its port, its own literal-IP address, the tunnel, Tauri and UNSLOTH_CORS_ORIGINS), and the origin helpers move out of main.py so the gate can share them.
Codex and OpenCode probe the OAuth discovery paths before connecting, and the SPA catch-all answered them with the app shell and a 200, which reads as an OAuth server. A 404 there, and a 401 from /mcp with no resource_metadata, lets them fall back to the bearer key.
Calling route functions directly skips auth, so tools ran as the owner and saw host paths. Tools now go through Studio's own routes with the caller's key from a TEST-NET peer and an .invalid Host, which no keyless, loopback or LAN check accepts, and only the key and an opted-in Hub token header are sent.
The route a tool forwards to binds the caller's account in whatever task runs it, and in the tool's own task that binding leaked into the tool and into later calls. Each forward now runs in its own task, which is cancelled when the tool is.
An agent needs a failed tool call to say what went wrong and whether to retry, but Studio routes fail in several shapes, some of them inside a 200. Each shape becomes a ToolError with the route's message, a retry or load hint where one applies, and any host path scrubbed.
Several Studio routes still return host paths to API-key callers, so tools must never pass route JSON through. Outputs are closed pydantic models whose route-originated text is scrubbed, and a coverage test makes every registered tool carry a sentinel host-path case.
The old studio_status called the unredacted inference status as the owner and covered only the chat slot. It now reads all eight status routes through the forwarder as the caller, reports each slot in a typed model, and lists a slot whose route failed instead of failing the whole call.
list_local_models scanned folders as the owner and returned host paths. list_models reads the same catalog Studio serves on /v1/models as the caller, so ids are public and account-scoped, says which kind each model is, and can add the training defaults for one model.
…tatus

An agent cannot chat with a model it cannot load. load_model waits for the padded /load answer, treats a deferred error as a failure and reports progress from the load and download routes; unload_model unloads by the serving checkpoint and checks the status afterwards, since an unmatched id still answers success. get_training_status goes because studio_status now covers training.
Image and video loads start in the background and answer with whatever was resident before, and a GGUF repo needs its checkpoint file named. The tool resolves the file from the repo's variants, validates the pick with the download plan, then follows load progress until it is ready or failed and confirms the new model in the status.
The STT load route refuses a model that is not on disk, and its download route runs in the background and reads the Hub token from a header. The tool picks the engine that lists the model, downloads and waits when needed, then loads; unload names the engine and model so it frees only what the agent asked for.
Agents need to ask the loaded model a question without speaking the OpenAI API themselves. chat takes a prompt or a message list, calls /v1/chat/completions without streaming under its own cancel id, and says so when a different model answered than the one asked for.
Agents building retrieval need vectors from the same embedder Studio uses. embed sends up to 2048 texts to /v1/embeddings and returns the vectors in input order; a model that still needs downloading gets guidance appended after the message is scrubbed, so a route name in the hint is never mistaken for a path. Route text in the load errors is scrubbed the same way.
Agents connected to Studio's MCP should reach the decision model there too, without a second server entry. system_one forwards typed questions to /v1/systemone as the caller, maps each answer type, and tells the agent to turn the Decision API on when it is off.
Generated images and audio should reach the agent in its own context when they are small, and as a gallery link when they are not. Links are built from the address the agent used for /mcp, with the tunnel's scheme when the request came through cloudflared, because forwarded answers only know the in-process .invalid host.
Vision chat and SystemOne need images, and an agent may hold them as a gallery id, inline data or a file. A path makes the server read a file on the Studio computer, so it is honoured only for a direct loopback caller and is never opened for anyone else; sizes are checked against the route limits before anything is read or decoded.
Agents should be able to make an image with the model Studio has loaded and see it. generate_image runs the Images route as the caller, saves to the gallery as the UI does, reports step progress, and returns each image inline when it fits; a larger one comes back as a thumbnail and a link and is never fetched in full.
Image edits need source, mask and reference images, which an agent holds as gallery ids, inline data or local files. generate_image now resolves them through the same input rules as chat, places them in the route's fields, refuses a mask or upscale without a source, and passes allow_oversized through for a memory refusal.
The Audio page's six workflows take clips by id, so audio an agent holds as data or a local file has to be stored with Studio first. generate_audio uploads such inputs as raw bytes, nests the ids under inputs the way the route requires, and returns every clip and group id, inline when the clip is short and as a link when it is not.
Agents need speech turned into text with the model Studio serves. transcribe sends small audio to the OpenAI-compatible transcription or translation route, asks for segments when timestamps are wanted, and when the model is not on disk downloads it the way load_model does and retries once.
The OpenAI transcription route takes 25 MB, and Studio has no route that fetches audio from a URL. Larger audio, and audio already in Studio, is uploaded or named by id and transcribed through the Audio page's source route with the loaded or default STT model; that route saves the transcript to history, which the result reports.
A video takes minutes, so generate_video starts the job and returns at once and get_job reports its progress; a finished job comes back as a thumbnail and a link, and the MP4 is never fetched. The shared text helper is renamed to opt_text because the tools.text module shadowed it for any tool module imported after it.
The old recipe tools called the routes directly and had to pass via_api_key themselves to keep stdio recipes behind a UI session. run_recipe forwards to the validate and jobs routes as the caller, so that gate holds on its own, and get_job reports a recipe job's progress and rows with the dataset named, never its path.
Before training, an agent has to find a dataset, check that Studio reads its format, and download it. datasets lists uploaded and downloaded datasets by name and size only, never their cache paths; the format check and the download send the caller's Hub token as the routes expect.
The old start_training called the route function as the owner and leaked an HTTPException out of the tool body. The tool now forwards to /api/train/start as the caller, so the route's API-key guards and account scoping apply, and a 200 that carries status error becomes a tool error.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

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

Copy link
Copy Markdown
Member

@codex review

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

Copy link
Copy Markdown
Member

@codex review

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

Copy link
Copy Markdown
Member

@codex review

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

Copy link
Copy Markdown
Member

@codex review

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

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a6b5b14575

ℹ️ 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".

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Mark unscoped cancellations on the matching export job

When cancel(kind="export") is used without the optional job id while an export_model job is the active export, this call kills the worker but leaves the corresponding ExportJob running. The background _op then receives the cancellation as a route error, and export_jobs._drive catches that ToolError and finishes the job as failed, so a subsequent get_job contradicts the successful cancel response. Locate the active tracked job and mark it cancelled in this no-id path as well.

Useful? React with 👍 / 👎.

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 13, 2026
Etherll and others added 4 commits October 13, 2026 03:40
transcribe(timestamps=true) could come back with segments: null and no
error. The translation route never times segments, so translate with
timestamps is now refused up front. A route answer with no segments is an
empty list, so null only means timestamps were not asked for. The hint on
the route's 400/501 refusal now names a model that can time segments; the
old "pass language" advice led to a second refusal.
The upload route reads the whole request body as the audio, so a multipart
form or a JSON body is not read as the file. Say so, with the size limit,
the name query parameter and a curl example.
generate_audio sent options as given, and the route silently drops an enum
value it does not list, so a voice of "Ryan" for the model's "ryan" spoke
in the default voice. An enum value is now sent as the loaded model spells
it, and a value it does not list is refused with the ones it does.
studio_status lists the active audio model's options, built-in voices
included, so an agent can find them before it calls generate_audio.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

new-feature# regresses# security# Moves a security boundary: sandbox, allowlist, permission or network guard >3000#

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants