Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: name the MCP server while the tool call is still streaming (#9212)
Daniel Han329a7dee0d4d
diff --git a/studio/backend/core/inference/sse_control_frames.py b/studio/backend/core/inference/sse_control_frames.pyindex b783db1ba0b..699050dd253 100644--- a/studio/backend/core/inference/sse_control_frames.py+++ b/studio/backend/core/inference/sse_control_frames.py@@ -44,7 +44,13 @@ _CONTROL_TYPES = frozenset()# Unsloth extensions carried inside a chunk: in no provider's wire format, read with the same trust as the frames above.-_CONTROL_KEYS = ("_toolEvent", "_toolStatus", "_diffusionFrame", "_reasoningDurationMs")+_CONTROL_KEYS = (+ "_toolEvent",+ "_toolStatus",+ "_diffusionFrame",+ "_reasoningDurationMs",+ "_mcp_provenance",+)# A stripped frame is only worth relaying if it still says something in the provider's own vocabulary._SUBSTANTIVE_KEYS = ("choices", "usage", "error")@@ -182,6 +188,7 @@ def strip_server_executed_tool_call(line: str, pending_call: bool = False) -> stnot_really_final = ("tool_calls", "stop", "function_call") if pending_call else ("tool_calls",)changed = False+ calls_withheld = Falsekept_choices = []for choice in choices:if not isinstance(choice, dict):@@ -195,7 +202,7 @@ def strip_server_executed_tool_call(line: str, pending_call: bool = False) -> stif isinstance(src, dict) and "tool_calls" in src:src = {k: v for k, v in src.items() if k != "tool_calls"}choice[src_key] = src- withheld = True+ withheld = calls_withheld = Trueif choice.get("finish_reason") in not_really_final:# Blanked, not renamed: the turn has not finished, the loop answers in the next# one. Cannot be keyed on a call withheld on this line, since the arguments@@ -213,6 +220,9 @@ def strip_server_executed_tool_call(line: str, pending_call: bool = False) -> stif not changed:return linepayload = {**payload, "choices": kept_choices}+ if calls_withheld:+ # Names the withheld calls by id; the caller never saw them.+ payload.pop("_mcp_provenance", None)if not _choices_say_anything(kept_choices) and "usage" not in payload:return Nonereturn "data: " + json.dumps(payload, separators = (",", ":"))diff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.pyindex 07e5e4be23f..4dac8793105 100644--- a/studio/backend/core/inference/studio_tool_loop.py+++ b/studio/backend/core/inference/studio_tool_loop.py@@ -86,6 +86,7 @@ from core.inference.tool_loop_controller import (awaiting_approval_status,canonical_arguments_text,mcp_display_parts,+ provisional_tool_provenance,strip_result_for_model,)from core.inference.tool_stream_exec import (@@ -1091,6 +1092,36 @@ def _unrun_call_card(]+def _is_strict_prefix_of_declared(name: str, declared_names: set[str]) -> bool:+ return any(other != name and other.startswith(name) for other in declared_names)+++def _mcp_provenance_by_id(+ turn: "_Turn", declared_names: set[str], stamped: set[str]+) -> dict[str, Any]:+ """MCP provenance per call id once its whole name has streamed, once per id.++ Declared catalog decides completeness (``mcp__srv__cre`` is well formed too); strict-prefix names wait for tool_start.+ """+ stamps: dict[str, Any] = {}+ for call in turn.by_index.values():+ call_id = call.get("id")+ if not isinstance(call_id, str) or not call_id or call_id in stamped:+ continue+ function = call.get("function")+ name = function.get("name") if isinstance(function, dict) else None+ if not isinstance(name, str) or name not in declared_names:+ continue+ if _is_strict_prefix_of_declared(name, declared_names):+ continue+ # Mark before the lookup: mcp_display_parts hits SQLite and is falsy without a display_name.+ stamped.add(call_id)+ if not mcp_display_parts(name):+ continue+ stamps[call_id] = provisional_tool_provenance(name)+ return stamps++def _status_sse(text: str) -> str:"""Tool badge text, in the shape the chat client already parses."""return _sse({"type": "tool_status", "content": text})@@ -1298,6 +1329,8 @@ async def stream_with_studio_tools(breakprovider_turns += 1turn = _Turn(round = provider_turns)+ # Per turn: ids restart each turn, so a later call_0 is a new card.+ mcp_stamped_ids: set[str] = set()healer = StreamToolCallHealer(heal_names, tools) if heal_names else None# A healed text-form call never reaches the wire as a tool_calls key, so a headerless caller's stripper cannot# tell this turn ends in a call the loop is about to run rather than in an answer. Hold the turn-ending chunk@@ -1397,6 +1430,10 @@ async def stream_with_studio_tools(turn.text.append(value)yield _sse({"choices": [{"index": 0, "delta": {"content": value}}]})turn.merge_structured(raw_calls)+ stamps = _mcp_provenance_by_id(turn, allowed_tool_names, mcp_stamped_ids)+ if stamps:+ payload["_mcp_provenance"] = stamps+ line = "data: " + json.dumps(payload, separators = (",", ":"))if healer is None or healer.dormant or not isinstance(content, str) or not content:plain = _delta_text(content)diff --git a/studio/backend/tests/test_external_mcp_delta_provenance.py b/studio/backend/tests/test_external_mcp_delta_provenance.pynew file mode 100644index 00000000000..87f7d7e8f8c--- /dev/null+++ b/studio/backend/tests/test_external_mcp_delta_provenance.py@@ -0,0 +1,360 @@+# 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 display name rides the provider's own tool_calls chunk, not a second card event (that would reset arguments)."""++from __future__ import annotations++import json+import threading++import pytest++from core.inference import studio_tool_loop as loop_mod+from core.inference import tool_loop_controller as controller_mod+from core.inference.studio_tool_loop import (+ ToolLoopPolicy,+ ToolLoopRun,+ stream_with_studio_tools,+)++_DONE = "data: [DONE]"++MCP_NAME = "mcp__a3f9c1d2e4b6f807__create_issue"+DISPLAY = "GitHub"+++def _tool(name: str) -> dict:+ return {+ "type": "function",+ "function": {+ "name": name,+ "description": "",+ "parameters": {"type": "object", "properties": {}},+ },+ }+++def _delta(+ fragment: str = "",+ arguments: str = "",+ call_id: str = "c1",+) -> str:+ function: dict = {}+ if fragment:+ function["name"] = fragment+ if arguments:+ function["arguments"] = arguments+ return "data: " + json.dumps(+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "tool_calls": [+ {"index": 0, "id": call_id, "type": "function", "function": function}+ ]+ },+ }+ ]+ }+ )+++def _finish(reason: str = "tool_calls") -> str:+ return "data: " + json.dumps({"choices": [{"index": 0, "delta": {}, "finish_reason": reason}]})+++class FakeTransport:+ heals_text_tool_calls = False++ def __init__(self, turns):+ self.turns = [list(turn) for turn in turns]+ self.requests: list[dict] = []++ def stream(self, *, messages, tools, tool_choice, cancel_event):+ self.requests.append({"messages": [dict(m) for m in messages]})+ assert len(self.requests) <= 10, "loop never terminated"+ lines = self.turns.pop(0) if self.turns else [_DONE]++ async def _gen():+ for line in lines:+ yield line++ return _gen()+++def named(monkeypatch):+ """Resolve only the one MCP name, so an incomplete one cannot look valid."""++ def _parts(tool_name: str):+ return (DISPLAY, "create_issue") if tool_name == MCP_NAME else None++ # Two references: this module's import and the controller global provisional_tool_provenance reads.+ monkeypatch.setattr(loop_mod, "mcp_display_parts", _parts)+ monkeypatch.setattr(controller_mod, "mcp_display_parts", _parts)+ monkeypatch.setattr(loop_mod, "execute_tool", lambda name, arguments, **kw: "ok")+ monkeypatch.setattr(loop_mod, "build_rag_autoinject", lambda *a, **k: None)+ monkeypatch.setattr(loop_mod, "is_high_risk_tool_call", lambda name, args: False)+++def _run(transport, tools):+ import asyncio+ async def _collect():+ out: list[str] = []+ agen = stream_with_studio_tools(+ transport,+ run = ToolLoopRun(+ messages = [{"role": "user", "content": "hi"}],+ session_id = "s1",+ thread_id = "t1",+ model = "m",+ ),+ policy = ToolLoopPolicy(+ tools = tools,+ max_calls = 25,+ timeout = 300,+ permission_mode = "off",+ confirm_calls = False,+ bypass_permissions = False,+ rag_scope = None,+ ),+ cancel_event = threading.Event(),+ )+ async for line in agen:+ out.append(line)+ return out++ return asyncio.run(_collect())+++def _stamps(lines: list[str]) -> list[dict]:+ out = []+ for line in lines:+ if not line.startswith("data: ") or line == _DONE:+ continue+ try:+ payload = json.loads(line[6:])+ except json.JSONDecodeError:+ continue+ if isinstance(payload, dict) and payload.get("_mcp_provenance"):+ out.append(payload["_mcp_provenance"])+ return out+++def _index_of_first_tool_start(lines: list[str]) -> int:+ for i, line in enumerate(lines):+ if '"type": "tool_start"' in line or '"type":"tool_start"' in line:+ return i+ return -1+++def test_the_display_name_rides_on_the_delta_that_completes_the_name(named):+ lines = _run(+ FakeTransport([[_delta(MCP_NAME), _delta(arguments = '{"a":1}'), _finish()], [_DONE]]),+ [_tool(MCP_NAME)],+ )+ stamps = _stamps(lines)+ assert stamps, "the streamed delta carried no display name"+ assert stamps[0] == {"c1": stamps[0]["c1"]}+ assert stamps[0]["c1"]["mcp_server"] == DISPLAY+++def test_the_stamp_beats_the_real_tool_start(named):+ lines = _run(+ FakeTransport([[_delta(MCP_NAME), _delta(arguments = "{}"), _finish()], [_DONE]]),+ [_tool(MCP_NAME)],+ )+ first_stamp = next(i for i, line in enumerate(lines) if '"_mcp_provenance"' in line)+ start = _index_of_first_tool_start(lines)+ assert start != -1, "the turn never ran the tool"+ assert first_stamp < start+++def test_it_is_keyed_by_the_streamed_call_id_and_sent_once(named):+ lines = _run(+ FakeTransport(+ [+ [+ _delta(MCP_NAME),+ _delta(arguments = '{"a":'),+ _delta(arguments = "1}"),+ _finish(),+ ],+ [_DONE],+ ]+ ),+ [_tool(MCP_NAME)],+ )+ stamps = _stamps(lines)+ assert len(stamps) == 1, "the stamp repeated on later argument fragments"+ assert list(stamps[0]) == ["c1"]+++def test_a_name_split_across_fragments_waits_until_it_is_whole(named):+ """``mcp__srv__cre`` is well formed too, so only the declared name may stamp."""+ lines = _run(+ FakeTransport(+ [+ [+ _delta("mcp__a3f9c1d2e4b6f807__cre"),+ _delta("ate_issue"),+ _delta(arguments = "{}"),+ _finish(),+ ],+ [_DONE],+ ]+ ),+ [_tool(MCP_NAME)],+ )+ stamped_at = [i for i, line in enumerate(lines) if '"_mcp_provenance"' in line]+ assert len(stamped_at) == 1+ assert '"cre"' not in lines[stamped_at[0]]+ assert _stamps(lines)[0]["c1"]["mcp_server"] == DISPLAY+++def test_a_plain_tool_is_left_alone(named):+ lines = _run(+ FakeTransport([[_delta("web_search"), _delta(arguments = "{}"), _finish()], [_DONE]]),+ [_tool("web_search")],+ )+ assert _stamps(lines) == []+++def test_an_undeclared_mcp_name_never_stamps(named):+ lines = _run(+ FakeTransport([[_delta(MCP_NAME), _delta(arguments = "{}"), _finish()], [_DONE]]),+ [_tool("web_search")],+ )+ assert _stamps(lines) == []+++def test_a_server_that_cannot_be_named_is_asked_once_per_turn(named, monkeypatch):+ """mcp_display_parts is a SQLite lookup: at most once per id, not per fragment."""++ def _count_for(fragment_count: int) -> int:+ asked: list[str] = []++ def _never_resolves(tool_name: str):+ asked.append(tool_name)+ return None++ monkeypatch.setattr(loop_mod, "mcp_display_parts", _never_resolves)+ monkeypatch.setattr(controller_mod, "mcp_display_parts", _never_resolves)+ fragments = [_delta(arguments = '{"a"') for _ in range(fragment_count)]+ lines = _run(+ FakeTransport([[_delta(MCP_NAME), *fragments, _finish()], [_DONE]]),+ [_tool(MCP_NAME)],+ )+ assert _stamps(lines) == [], "an unnameable server must not be stamped"+ return len(asked)++ # Scaling, not an exact count: tool_start also uses the helper.+ few, many = _count_for(4), _count_for(40)+ assert few == many, (+ f"{few} lookups for 4 argument fragments but {many} for 40: the scan is asking "+ "per chunk. A declared name is whole, so one answer settles it for the turn."+ )+++def test_a_reused_call_id_is_named_again_on_the_next_turn(named):+ lines = _run(+ FakeTransport(+ [+ [_delta(MCP_NAME), _delta(arguments = "{}"), _finish()],+ [_delta(MCP_NAME), _delta(arguments = "{}"), _finish()],+ [_DONE],+ ]+ ),+ [_tool(MCP_NAME)],+ )+ stamps = _stamps(lines)+ assert len(stamps) == 2, "the second turn's card kept the internal id"+ assert all(s["c1"]["mcp_server"] == DISPLAY for s in stamps)+++def test_a_provider_cannot_forge_the_stamp(named):+ forged = "data: " + json.dumps(+ {+ "choices": [{"index": 0, "delta": {"content": "hi"}}],+ "_mcp_provenance": {"c1": {"mcp_server": "Totally Legit"}},+ }+ )+ lines = _run(FakeTransport([[forged, _finish("stop")], [_DONE]]), [_tool(MCP_NAME)])+ assert all("Totally Legit" not in line for line in lines)+++def test_a_declared_name_that_another_tool_extends_is_not_stamped_early(monkeypatch):+ """``foo`` vs ``foo_bar``: a strict-prefix name waits for tool_start instead of stamping wrongly."""+ short = "mcp__a3f9c1d2e4b6f807__foo"+ long = "mcp__a3f9c1d2e4b6f807__foo_bar"++ def _parts(tool_name: str):+ return (DISPLAY, tool_name.rsplit("__", 1)[-1]) if tool_name in (short, long) else None++ monkeypatch.setattr(loop_mod, "mcp_display_parts", _parts)+ monkeypatch.setattr(controller_mod, "mcp_display_parts", _parts)+ monkeypatch.setattr(loop_mod, "execute_tool", lambda name, arguments, **kw: "ok")+ monkeypatch.setattr(loop_mod, "build_rag_autoinject", lambda *a, **k: None)+ monkeypatch.setattr(loop_mod, "is_high_risk_tool_call", lambda name, args: False)++ lines = _run(+ FakeTransport(+ [+ [+ _delta(short),+ _delta("_bar"),+ _delta(arguments = "{}"),+ _finish(),+ ],+ [_DONE],+ ]+ ),+ [_tool(short), _tool(long)],+ )+ stamps = _stamps(lines)+ assert len(stamps) == 1, f"expected exactly one stamp, got {stamps}"+ assert stamps[0]["c1"]["mcp_tool"] == "foo_bar"+ assert not any(+ '"mcp_tool": "foo"' in line for line in lines+ ), "stamped the shorter declared name, so the card read as the wrong tool"++ lines = _run(+ FakeTransport([[_delta(short), _delta(arguments = "{}"), _finish()], [_DONE]]),+ [_tool(short), _tool(long)],+ )+ assert _stamps(lines) == []++ lines = _run(+ FakeTransport([[_delta(long), _delta(arguments = "{}"), _finish()], [_DONE]]),+ [_tool(long)],+ )+ assert _stamps(lines)[0]["c1"]["mcp_server"] == DISPLAY+++def test_the_prefix_test_only_looks_at_other_declared_names():+ from core.inference.studio_tool_loop import _is_strict_prefix_of_declared++ assert _is_strict_prefix_of_declared("a", {"a", "ab"}) is True+ assert _is_strict_prefix_of_declared("ab", {"a", "ab"}) is False+ assert _is_strict_prefix_of_declared("a", {"a"}) is False+ assert _is_strict_prefix_of_declared("a", set()) is False+++def test_a_caller_without_ui_events_never_sees_the_stamp():+ from core.inference.sse_control_frames import strip_server_executed_tool_call++ chunk = {+ "choices": [+ {+ "index": 0,+ "delta": {"content": "hi", "tool_calls": [{"index": 0, "id": "call_0"}]},+ "finish_reason": None,+ }+ ],+ "_mcp_provenance": {"call_0": {"mcp_server": DISPLAY}},+ }+ out = json.loads(strip_server_executed_tool_call("data: " + json.dumps(chunk))[len("data: ") :])+ assert out["choices"][0]["delta"] == {"content": "hi"}+ assert "_mcp_provenance" not in outdiff --git a/studio/backend/tests/test_provider_control_frame_spoofing.py b/studio/backend/tests/test_provider_control_frame_spoofing.pyindex 81891bed0e3..8e601b9432f 100644--- a/studio/backend/tests/test_provider_control_frame_spoofing.py+++ b/studio/backend/tests/test_provider_control_frame_spoofing.py@@ -48,7 +48,14 @@ def test_every_control_type_is_dropped(frame_type):@pytest.mark.parametrize(- "key", ["_toolEvent", "_toolStatus", "_diffusionFrame", "_reasoningDurationMs"]+ "key",+ [+ "_toolEvent",+ "_toolStatus",+ "_diffusionFrame",+ "_reasoningDurationMs",+ "_mcp_provenance",+ ],)def test_every_studio_private_key_is_stripped(key):line = "data: " + json.dumps(diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 6a0d5dba518..23019c1db17 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -7765,17 +7765,38 @@ export function createOpenAIStreamAdapter(addedToolCall = true;}}+ const mcpStamps = (+ chunk as { _mcp_provenance?: Record<string, unknown> }+ )._mcp_provenance;+ let stampedProvenance = false;+ if (mcpStamps && typeof mcpStamps === "object") {+ for (const [backendId, raw] of Object.entries(mcpStamps)) {+ const partId = resolveToolPartId(backendId);+ const at = toolCallParts.findIndex(+ (p) => p.toolCallId === partId,+ );+ if (at === -1) continue;+ const existing = toolCallParts[at] as PositionedToolCallPart;+ toolCallParts[at] = {+ ...existing,+ provenance: mergeToolProvenance(+ existing.provenance,+ parseToolProvenance(raw),+ ),+ };+ stampedProvenance = true;+ }+ }// After this chunk's deltas: a provider can put finish_reason on the same chunk as the turn's// last name-only delta.if (chunk.choices?.[0]?.finish_reason) {// Ending the turn drops cards, so the publish below must see it rather than wait for the pacing gate.replayStateChanged ||= endProviderTurn();}- if (- addedToolCall ||- replayStateChanged ||- canPublish(streamedChars)- ) {+ // A relabel adds no characters, so the pacing gate alone would hold it back.+ const forcePublish =+ addedToolCall || replayStateChanged || stampedProvenance;+ if (forcePublish || canPublish(streamedChars)) {yield {content: liveAssistantContent(),metadata: {diff --git a/studio/frontend/tests/parallel-tool-call-arguments.test.ts b/studio/frontend/tests/parallel-tool-call-arguments.test.tsindex 32e50f86735..d68706c819d 100644--- a/studio/frontend/tests/parallel-tool-call-arguments.test.ts+++ b/studio/frontend/tests/parallel-tool-call-arguments.test.ts@@ -173,9 +173,10 @@ function liftDeltaLoop(): string {loopStart >= 0,"the delta.tool_calls loop moved in chat-adapter.ts",);- const gate = adapterSource.lastIndexOf(- "if (",- adapterSource.indexOf("addedToolCall ||", loopStart),+ // Searching back for `if (` truncated the slice once the condition moved into a variable.+ const gate = adapterSource.indexOf(+ "if (forcePublish || canPublish(",+ loopStart,);assert.ok(gate > loopStart, "the publish gate moved in chat-adapter.ts");const lifted = adapterSource.slice(loopStart, gate);@@ -183,6 +184,14 @@ function liftDeltaLoop(): string {lifted.includes("splitTopLevelJsonObjects"),"the loop no longer splits on JSON object boundaries",);+ assert.ok(+ lifted.includes("endProviderTurn()"),+ "the lifted loop stops before the turn ends, so it is not the loop production runs",+ );+ assert.ok(+ lifted.includes("const forcePublish ="),+ "the lifted loop stops before the publish decision it is supposed to reach",+ );return lifted;}