Skip to content

Studio: let chat call Unsloth's own MCP tools - #15631

Merged
danielhanchen merged 78 commits into
unslothai:mainfrom
Etherll:studio/chat-unsloth-tools
Nov 8, 2026
Merged

danielhanchen merged 78 commits into
unslothai:mainfrom
Etherll:studio/chat-unsloth-tools

Conversation

@Etherll

@Etherll Etherll commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator

Replaces #14349, with the same final code as one commit. It is stacked on #15629, so merge that first. Until then this diff also shows #15629's changes, and only the last commit is new. It includes the fixes Daniel and Nilay made on #14349, and both are credited as co-authors.

Summary

This PR adds an Unsloth preset at the top of the chat MCP dropdown. Ticking it lets the chat model call Unsloth Studio's own MCP tools in process, with no API key to paste and no network listener.

Chat MCP dropdown

  • Which tools the chat gets: only the tools the owner left on in Settings > Agents > Choose tools, minus the ones that would evict or re-enter the chat that calls them: chat, load_model, unload_model, cancel, start_training, export_model and run_recipe (CHAT_DENYLIST in mcp_server.py). The tools dialog names those once, in a note under the groups.
  • Toggles apply right away: the row's tools are re-listed on every send, so a change in Settings applies to the next message.
  • External agent access is unaffected: it works whether or not "Agent access (MCP)" is on, and /mcp still returns 404 while that is off.

Tools dialog note

Safety

  • Per-call key: each tool call runs as the chat's own account, with an internal API key minted for that call. The key is deleted when the call ends, including on Stop, timeout and error.
  • No host files: host file paths are refused for these calls, even for the owner.
  • Who can turn it on: only a signed-in UI session can add the row or point another row at it. API keys and keyless callers get 403, and keyless callers never see the row.
  • Stop: a chat Stop also stops the image, audio or video job a tool call started.
  • Model switches: a chat tool call never switches the loaded model.
  • Media links: links open through the user's session, so they work in the desktop app and behind a proxy path prefix.

Testing

cd studio/backend
python -m pytest tests/test_studio_tools_chat.py tests/test_mcp_*.py tests/test_settings*.py tests/test_systemone_connections.py tests/test_research_internal_key_monitor.py tests/test_fine_tuned_model_serving.py tests/test_openai_tool_passthrough.py
cd ../frontend
npm run typecheck && npm run i18n:check:strict && npm test && npm run build && npm run bundle:check
  • Backend: 2,237 passed, plus 499 in the model-switch and tool-passthrough files. The same 3 test_mcp_images.py tests fail here and on main.
  • Frontend: typecheck clean, i18n:check:strict passes, and the settings, MCP and chat-composer tests pass (871).
  • Bundle: within budget. The budget grows by +1,363 B raw / +366 B transfer over Studio: per-tool MCP switches at the end of Settings > Agents #15629, from the chat preset and the note.

I also ran Unsloth Studio from this branch to check the dropdown and the dialog note.

Studio UI regression check

Base 81dc73ac4 vs head fe799ee49. Functional: NO_REGRESSION, UI coverage 83%, 1 visual change(s), 5 text-only change(s). Only steps whose screenshots differ are shown.

Note: in this run diffusion_video failed once on head inside the regression harness's own fixture copy (a temp-dir race between the two arms, fixed in the harness), before any request reached Unsloth. A rerun of that journey on both arms at the same head gave 6/6 identical steps; its results are used here.

settings/s06_tab_api: | reproduced on confirm (VISUAL_DIFF)
settings/s06_tab_api

Step Text / structure change
settings/s10_tab_agents {'removed': [], 'added': ['Unsloth MCP', 'Agent access (MCP)', 'Let coding agents […] use Unsloth over MCP.', '23 of 23 on', 'Choose t
parallel/stop_training {'removed': ['65/4.1k', 'Three fruits are named:', '#ctrl button:Name three fruits.', '#ctrl button:Context usage: 65 of 4.1k tokens'], 'added': ['Name three an
crawl/r_projects
crawl/r_export
crawl/r_data_recipes

Chat MCP preset: before and after this layer

BEFORE is #15629's head (069a35528), AFTER is this PR's head (fe799ee49), so only this layer's change shows; this is not the PR's own merge base.

The chat's MCP menu now offers Unsloth first, which answers with Unsloth's own tools in process:

Chat MCP menu, before and after

The tools dialog in Settings > Agents ends with the tools a chat never gets ("The chat never gets Load model, Unload model, Plan a load, Chat, Run Data Recipe, Start training, Export model, and Cancel work."):

Unsloth MCP tools dialog, before and after

@chatgpt-codex-connector

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 🔄 Running since 2026-10-28T00:59:09.805863Z 15155c5 PR opened
ℹ️ 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.

@chatgpt-codex-connector

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

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

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

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-07T18:29:50.652740Z
We couldn’t complete this review. Comment @codex review to try again.
9a563d5 Manual request
ℹ️ 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.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator

Tested this on a branch build with a real GGUF (Qwen3-1.7B, CPU llama.cpp, Windows 11) after merging current main. The chat path works end to end. With Unsloth ticked, the model calls studio_status in process, and the per-call key is gone after every call. A tool switched off in Settings > Agents drops out on the next send, and the MCP App tool-call route fails closed.

Re-checked at 0f05c307e6: the PR's backend suites pass (294), the 9 frontend test files pass (88) with i18n parity, typecheck is clean, and the bundle is within budget. Three things to look at:

  1. An API key can turn the Unsloth row back on. After the owner unticks it, PUT /api/mcp/servers/{id} with is_enabled: true returns 200, and the key can then drive the tools through /v1/chat/completions with Agent access off. Suggestion: make turning the row on UI-only, like adding it (mcp_servers.py:487), and leave turning it off open. A test for the "on" direction in test_mcp_servers.py fails against the current route.
  2. download_model is on for chats by default. It keeps downloading after the call returns, and the chat can't cancel it: a 105 MB GGUF landed 6 s after the tool returned. That's the same shape as export_model, which CHAT_DENYLIST already excludes for that reason, so adding it there seems right.
  3. Signed media links break in Desktop behind a proxy prefix. With a root_path like /studio, the media tools return /studio/api/.../file-signed?token=.... desktopSignedMediaPath only matches a leading /api or /v1, so it returns null, and protectedBackendPath skips file-signed? links. The image falls through to a raw <img src> the Desktop webview can't load. Accepting leading root-path segments, the way protectedBackendPath does, would cover it.

Smaller:

Etherll and others added 8 commits October 29, 2026 22:05
Lets the owner choose which of Unsloth Studio's MCP tools agents can see.
The Agent access (MCP) switch and setup snippet move to the end of
Settings > Agents, under an "Unsloth MCP" heading, with a Tools row
("20 of 23 on") that opens a dialog. The dialog groups the tools (Models,
Generate, Training and export, Data and library, Jobs) with one switch per
tool, one per group, and Turn all on. Settings > API keeps a one-line link
to it.

A tool that is off is left out of tools/list and calls to it are refused.
Saves send only the changed tools (tool_states) and the server merges them,
so two windows toggling different tools both keep their change.

Co-authored-by: Daniel Han <[email protected]>
Adds an "Unsloth" preset to the chat MCP dropdown. Ticking it lets the chat
model call Unsloth Studio's own MCP tools in process, with no API key to
paste. The chat gets only the tools the owner left on in Settings > Agents,
minus the ones that would evict or re-enter the chat that calls them
(chat, load_model, unload_model, cancel, start_training, export_model,
run_recipe); the tools dialog names those once in a note.

Each call runs as the chat's own account with a short-lived internal key
that is deleted when the call ends. Host file paths are refused, keyless
API callers can't use the row, a chat Stop also stops the image, audio or
video job the tool started, and media links open through the session on
Desktop and behind a proxy prefix.

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: Nilay Yadav <[email protected]>
Chat tool calls get a clear surface and clear failures:

- EnsureModel decides whether a request may load the model it names, from a
  load policy carried by the authenticating key. The chat's per-call key may
  load beside the chat model, never in its place; otherwise it gets
  needs_user_load with the Studio page to load it from. Routes no longer
  import studio_mcp.
- Routes name agent-actionable failures in an X-Unsloth-Problem header;
  studio_mcp/problems.py turns codes into tags and hints for the caller's
  tools, replacing the English matching in errors.py.
- One model identity module for name matching (fixes plan_load and
  load_model disagreeing on case).
- CallerProfile replaces CHAT_DENYLIST: tools declare facts, the profile
  withholds by them and renders tool text for its own surface.
- Read-only MCP tools no longer count as new work in the chat loop, the
  duplicate-call nudge asks for the answer, chat results drop nulls.
…hen it can't

From a live Colab run of the song chat on this branch:

- The owner's chat may load a model beside the chat model without
  "Switch model by request" (off by default). That switch guards API
  clients; the chat's key can never unload the chat model. A managed
  account still needs the switch.
- needs_user_load names the real reason: Keep multiple models loaded is Off,
  or the model does not fit under When they fit (set it to Always), or the
  switch is off for a managed account. It no longer always claims the load
  "would unload the model serving this chat".
- A model that is not on disk gets needs_download, with a download_model
  hint, instead of needs_user_load.
- The hint no longer repeats the instruction the message already gives.
- After a needs_user_load result, the chat loop does not re-prompt the model
  to call tools: telling the user what to do is the answer.
- list_models' default source lists downloaded audio.cpp models, which the
  /v1/models scan skips, so a model download_model just fetched shows up.
…d list_models

- A beside-only (chat tools) primary load frees image and video models only,
  never a kept chat model; a vLLM/SGLang load that would retire kept models
  refuses with needs_user_load first.
- A measured Always refusal no longer tags kind=chat: the kind names the model
  to unload, so agents were told to unload the chat model even when an image
  or video model held the GPU.
- Revert the audio catalog merge in list_models: /v1/models already lists
  runnable downloaded audio.cpp models, and the merge listed ones without a
  runtime and reached the network-backed catalog on every default call.
- test_multi_model_always: a padded refusal keeps the X-Unsloth-Problem header.
…d stop re-prompting a chat blocked on the user

From a live Colab run: a chat tool loaded the music model beside the chat
model (log: "loaded successfully in subprocess"), then the same run failed
"No model loaded.".

- _run_music_workflow routes to the kept slot, then calls _generate_tts_wav
  with no model; its _maybe_auto_switch_model(reload-only) re-routed with
  None and model_slots.route reset routed_slot to the empty primary. A
  reload-only request now keeps the slot this task already routed to. This
  also affected the Audio page's music runs with a model kept beside chat.
- A music run that names no model uses the one music model kept beside the
  chat model (several: the caller names one).
- tests/test_music_beside_chat.py runs the real route chain up to the
  orchestrator's generate for a kept model, one loaded on this call, and an
  omitted model; all three returned "No model loaded." before the fix.
- The chat loop's post-tool re-prompt also skips a not_loaded result whose
  hint asks the user to act.
…odel, and check MCP options against the model that runs

- A speak/clone/edit/convert, /v1/audio/speech or separation run that names
  no model now uses the one model for that workflow kept beside the chat
  model, as music already did (_route_to_kept_audio_model). Before, it read
  the primary and answered "No model loaded.".
- generate_audio's option check and variations plan read the status of the
  model that will run: the named one (status?model=), else the one the route
  picks, including a model kept beside the chat model. Before, they read the
  chat model's status, so options went unchecked and a sequential music
  model got one batch request.
- test_openai_catalog: reset the media pick cache and resident media status
  an earlier test can leave, which added a FLUX row in full runs (also on the
  PR head).
get_job and cancel each carried their own per-kind branches (export,
training, load, download, video, recipe, generate_audio). The kinds now
live in studio_mcp/job_kinds.py and register with studio_mcp/jobs.py, which
gives both tools one lookup, one status shape and one cancel path. The tool
modules keep only their MCP signatures and docs.

No behavior change: the existing get_job and cancel tests pass unchanged
apart from where they patch the moved helpers, and test_mcp_jobs_module.py
covers the registry.
@Etherll
Etherll force-pushed the studio/chat-unsloth-tools branch from 0f05c30 to 4a38430 Compare October 29, 2026 20:00
@Etherll
Etherll marked this pull request as ready for review October 29, 2026 20:01
Merges near-duplicate cases into tables and shared helpers, and drops
asserts on incidental wording. Every fix in this PR keeps a regression
test; the music scenario now keeps two music models, so it also catches
a reload-only TTS step losing its held slot.
@LeoBorcherding

LeoBorcherding commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Re-checked at b3e674053a, after the Jobs module, beside-the-chat loading and audio routing commits. The two merges since (cc07b5479b) only move the bundle budget numbers, so this holds for the current head too. The core still holds: the per-call key is gone after every call (also with 12 calls at once), withheld tools are unknown to the chat, and get_job/cancel can't reach another account's export, load or download.

Before is main c97cd18cea, after is this PR, same model (Qwen3-1.7B-GGUF UD-Q4_K_XL), Unsloth Studio on a Mac M5.

Turning it on: the chat's MCP menu

Before After
Before: Unsloth is an ordinary row added by hand, at the bottom After: Unsloth is a built-in entry at the top

It works: "Call the studio_status tool"

Before: the model can't see the tool.

Before: the model says studio_status isn't available

After: the chat calls Unsloth · studio_status in process and answers with the real loaded model.

After: Used tool Unsloth studio_status, answers with the loaded model

The three points from my last comment are all still open at this head:

  1. An API key can still turn the Unsloth row back on (mcp_servers.py:487). I see the comment there says is_enabled stays open to API keys on purpose, but for this row it undoes the owner unticking it, so I'd still make turning it on UI-only.
  2. Small one: a chat can start a download_model it can't cancel (you can still cancel it from Unsloth Studio). export_model is already kept from chats for the same reason, so download_model probably belongs there too. If chats should be able to download or export, that could be an opt-in permission instead: off by default, the owner can turn it on, and other accounts only get it if the owner grants it to them. If that lands, the open question is what the chat does while it waits, for example a load right after a download sits until the file arrives: show progress, and let the user cancel from the chat. generate_video and the dataset download in datasets work the same way (they start a job and return while it runs, with no cancel in a chat), so they'd fit under the same permission.
  3. desktopSignedMediaPath still only matches a leading /api or /v1.

New since then:

  • With "Switch model by request" off, the owner's chat can now load another model beside the chat model (inference.py:11006). That seems fine since it can't unload the chat model, but the body still says a chat tool call never switches the loaded model and still names CHAT_DENYLIST. Worth updating, along with the switch's description in Settings.
  • A beside-only load under When they fit can still free the user's image or video model (inference.py:12072). Refusing with needs_user_load there, like the Always path, would match the rest of the policy.
  • The test trim dropped the only check that a full job store never evicts a running job. If JobStore.evict drops the oldest job regardless of state, everything still passes. Bringing back that one case would cover it.

Smaller: the body's tests/test_settings*.py still matches no file, tools/audio.py re-exports private names just for the tests, and the bundle budget comment still cites #14349.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator

Five small commits for #15631, all on LeoBorcherding#655 and each cherry-picks onto your branch as is:

  1. a9e70d00da: add "[multi_model_always" to AWAITS_USER_WHEN_ASKED in tool_facts.py. When a chat turn hits an Always refusal it gets told to ask the user to unload a model, but awaits_user() was False, so the reprompt guard could push the model into a retry that can't work. Agents that have unload_model aren't affected.
  2. 2d2fb8fa4f: Source lint's import-hoist check blocks the unused stop_run re-export in tools/audio.py and the test that re-points jobs at studio_mcp.jobs. The tests now import audio_runs directly and alias the module.
  3. 44e8fe8474: encoding = "utf-8" on the read_text() in test_load_policy.py (Repo tests rest-2).
  4. f991ce7e29: drop DUPLICATE_CALL_NUDGE from the refactor guard baselines, since the PR deletes it and nothing else uses it.
  5. 410c5d75bd: the Always-refusal test in test_mlx_diffusion_routing.py now expects the X-Unsloth-Problem header you added.

The two frontend reds are main's (same failures on 7af6ba3dde), and I ran typecheck, the build and bundle:check locally since CI stops before them: all pass. The Chat UI bookmarks failure looks like a flake, worth a rerun. Codex is clean on the fixes.

@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 Nov 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 7, 2026
@unslothai unslothai deleted a comment from Etherll Nov 7, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 7, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 7, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 7, 2026
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.

4 participants