Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Preserve prompt cache during deferred MCP tool search (#16546)

Wasim Yousef Said4710162e8c9a
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 23e7174ad9c..74a6651c222 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -38060,12 +38060,25 @@ class LlamaCppBackend:
if logit_bias:
payload["logit_bias"] = logit_bias
# An empty list would still advertise tool use.
+ if _reasoning_kw is not None:
+ payload["chat_template_kwargs"] = _reasoning_kw
if safe_tools:
- payload["tools"] = llama_grammar_tools(safe_tools)
+ grammar_tools = safe_tools
+ if not forced_name and requested_choice != "none":
+ grammar_tools = neutralize_tool_descriptions(
+ tool_controller.active_tools(include_deferred = True),
+ _markup_cache,
+ self.markup_profile,
+ )
+ payload["tools"] = llama_grammar_tools(grammar_tools)
payload["tool_choice"] = requested_choice
+ if grammar_tools != safe_tools:
+ # The parser needs discovered names; the template keeps its cached declaration.
+ payload["chat_template_kwargs"] = {
+ **(_reasoning_kw or {}),
+ "tools": llama_grammar_tools(safe_tools),
+ }
_last_sent_tools = safe_tools
- if _reasoning_kw is not None:
- payload["chat_template_kwargs"] = _reasoning_kw
if thinking_budget_tokens is not None:
payload["thinking_budget_tokens"] = thinking_budget_tokens
# Re-checked per iteration: once a tool result is appended the partial is
diff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.py
index 607de727215..7ecc09e2df0 100644
--- a/studio/backend/core/inference/studio_tool_loop.py
+++ b/studio/backend/core/inference/studio_tool_loop.py
@@ -1589,7 +1589,8 @@ async def _stream_with_studio_tools(
# Hold the turn-ending chunk until finalize() says whether a call was promoted, then arm the headerless stripper; arming at promotion is too late.
held_final: str | None = None
- active_tools = controller.active_tools()
+ # External APIs cannot separate decoding schemas from the prompt's tools.
+ active_tools = controller.active_tools(include_deferred = True)
tools_available = (
tool_choice != "none" and bool(active_tools) and (unlimited or remaining > 0)
)
diff --git a/studio/backend/core/inference/tool_loop_controller.py b/studio/backend/core/inference/tool_loop_controller.py
index 2e21b914c49..97a04455595 100644
--- a/studio/backend/core/inference/tool_loop_controller.py
+++ b/studio/backend/core/inference/tool_loop_controller.py
@@ -627,25 +627,29 @@ def _declared_properties(tool_name: str, tool_schemas) -> Any:
def _mcp_tool_spec(tool_name: str) -> Any:
try:
from core.inference.tools import mcp_tool_spec # noqa: PLC0415 -- cycle at import time
- return mcp_tool_spec(tool_name)
+ from core.inference.chat_template_helpers import neutralize_tool_descriptions # noqa: PLC0415
+
+ specs = neutralize_tool_descriptions([mcp_tool_spec(tool_name)])
+ return specs[0] if specs else None
except Exception: # noqa: BLE001 -- an unknown tool stays disabled
return None
-def _mcp_fit_loaded(specs: list) -> list:
- try:
- from core.inference.tools import mcp_fit_loaded # noqa: PLC0415 -- cycle at import time
- return mcp_fit_loaded(specs)
- except Exception: # noqa: BLE001 -- unsized, the newest load still goes through
- return specs[:1]
-
-
-def _mcp_tool_search_specs(arguments: Any) -> list:
- try:
- from core.inference.tools import mcp_tool_search_specs # noqa: PLC0415 -- cycle at import time
- return mcp_tool_search_specs(arguments)
- except Exception: # noqa: BLE001 -- a failed load leaves the listing as it was
- return []
+def _mcp_tool_search_specs(result: str) -> list:
+ specs = []
+ # The worker's result budget is absent here; its returned schemas are authoritative.
+ for line in result.splitlines():
+ if not line.startswith(" schema: "):
+ continue
+ try:
+ schema = json.loads(line.removeprefix(" schema: "))
+ except (ValueError, TypeError):
+ continue
+ name = _tool_name_from_schema(schema) if isinstance(schema, Mapping) else None
+ spec = _mcp_tool_spec(name) if name else None
+ if spec is not None:
+ specs.append(spec)
+ return specs
def _tool_name_key(name: str) -> str:
@@ -1235,8 +1239,6 @@ class ToolLoopController:
name for name in (_tool_name_from_schema(tool) for tool in self._tools) if name
}
self._mcp_search = MCP_TOOL_SEARCH_NAME in self._allowed_tool_names
- self._listed_count = len(self._tools)
- self._mcp_loaded: list[dict[str, Any]] = []
self._auto_heal_tool_calls = auto_heal_tool_calls
self._deduplicate_tool_calls = deduplicate_tool_calls
self._one_shot_tools = one_shot_tools
@@ -1267,12 +1269,20 @@ class ToolLoopController:
for tool in self._tools
)
- def active_tools(self) -> list[dict[str, Any]]:
- """Return tools still worth advertising to the next model call."""
+ def active_tools(self, *, include_deferred: bool = False) -> list[dict[str, Any]]:
+ """Return prompt tools, optionally including deferred schemas for decoding."""
if self._force_final_answer:
return []
active: list[dict[str, Any]] = []
- for tool in self._tools:
+ tools = self._tools
+ if include_deferred and self._mcp_search:
+ declared = {_tool_name_from_schema(tool) for tool in tools}
+ tools = tools + [
+ spec
+ for name in sorted(self._allowed_tool_names - declared)
+ if (spec := _mcp_tool_spec(name)) is not None
+ ]
+ for tool in tools:
name = _tool_name_from_schema(tool)
if name in self._completed_one_shot_tools:
continue
@@ -1296,17 +1306,21 @@ class ToolLoopController:
canonical = _canonical_tool_name(tool_name, self._allowed_tool_names)
if canonical is not None:
tool_name, name_healed = canonical, True
+ # Deferred schemas must not shift the cached prompt prefix.
+ extra_schema = None
if (
self._mcp_search
and tool_name.startswith(MCP_TOOL_PREFIX)
- and tool_name not in self._allowed_tool_names
+ and tool_name not in {_tool_name_from_schema(tool) for tool in self._tools}
):
- self._load_mcp_tools([_mcp_tool_spec(tool_name)])
+ extra_schema = _mcp_tool_spec(tool_name)
+ if extra_schema is not None:
+ self._allowed_tool_names.add(tool_name)
coerced = coerce_tool_arguments(
function.get("arguments", {}),
heal = self._auto_heal_tool_calls,
tool_name = tool_name,
- tool_schemas = self._tools,
+ tool_schemas = self._tools + ([extra_schema] if extra_schema is not None else []),
)
arguments = coerced.arguments
if tool_name == "web_search" and UNPARSED_ARGUMENTS_KEY not in arguments:
@@ -1341,7 +1355,6 @@ class ToolLoopController:
# Not the browser tools: each acts on or reads the page as it is now, so a second
# scroll down or a snapshot after a click is new work, and two such no-ops ended the turn.
# Nor the media tools: the same prompt again is another image with a fresh seed.
- # Nor mcp_tool_search: a repeat restores tools a later load evicted.
action = "duplicate"
noop = _noop_result("duplicate", tool_name)
@@ -1416,7 +1429,10 @@ class ToolLoopController:
if not failed:
self._successful_keys.add(decision.key)
if self._mcp_search and decision.tool_name == MCP_TOOL_SEARCH_NAME:
- self._load_mcp_tools(_mcp_tool_search_specs(decision.arguments))
+ for spec in _mcp_tool_search_specs(result_text):
+ name = _tool_name_from_schema(spec) if isinstance(spec, Mapping) else None
+ if name:
+ self._allowed_tool_names.add(name)
elif decision.tool_name.startswith(MCP_TOOL_PREFIX):
# Also while the catalog is listed in full, for a later turn that defers it.
self._remember_mcp_tools([decision.tool_name])
@@ -1429,33 +1445,6 @@ class ToolLoopController:
executed = True,
)
- def _load_mcp_tools(self, specs) -> None:
- from core.inference.chat_template_helpers import neutralize_tool_descriptions # noqa: PLC0415
-
- # Remote text, swept as the loops sweep the catalog this controller was built from (#7066); with no model's
- # profile at hand, against every family's markup.
- specs = (
- neutralize_tool_descriptions([dict(s) for s in specs if isinstance(s, Mapping)]) or []
- )
- listed = self._tools[: self._listed_count]
- listed_names = {_tool_name_from_schema(tool) for tool in listed}
- fresh = [s for s in specs if _tool_name_from_schema(s) not in listed_names]
- fresh_names = {_tool_name_from_schema(s) for s in fresh}
- # Newest first into the turn's load share, so a later search can retire an older load but never overflow.
- kept = _mcp_fit_loaded(
- fresh
- + [
- s
- for s in reversed(self._mcp_loaded)
- if _tool_name_from_schema(s) not in fresh_names
- ]
- )
- self._mcp_loaded = [_copy_schema(s) for s in reversed(kept)]
- self._tools = listed + self._mcp_loaded
- self._allowed_tool_names = {
- name for name in (_tool_name_from_schema(tool) for tool in self._tools) if name
- }
-
def _remember_mcp_tools(self, names) -> None:
if not names:
return
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 544522e1ceb..f4338c1f8d6 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -12358,7 +12358,6 @@ _MCP_TOOL_SEARCH_LIMIT = 5
# window: small models often answer that a tool is unavailable rather than search for it (#10997).
_MCP_TOOL_PRELOAD = 5
_MCP_TOOL_PRELOAD_SHARE = 0.33
-# Tools a turn loads by search or by name, newest first; older ones leave the listing to stay within it.
_MCP_TOOL_LOAD_SHARE = 0.5
_MCP_TOOL_SEARCH_SUMMARY_CHARS = 80
_MCP_TOOL_SEARCH_MAX_LIMIT = 10
@@ -12845,13 +12844,33 @@ def mcp_fit_loaded(specs: list[dict]) -> list[dict]:
return fitted
+def _mcp_search_result(found: list[dict]) -> str:
+ lines = [
+ f"- {spec['function']['name']}: {_mcp_summary(spec['function'].get('description') or '')}\n"
+ f" schema: {json.dumps(spec, separators=(',', ':'))}"
+ for spec in found
+ ]
+ return (
+ f"Loaded {len(found)} MCP tool{'s' if len(found) != 1 else ''}. Call the one that fits directly, "
+ "with the parameters in its schema:\n" + "\n".join(lines)
+ )
+
+
def _mcp_search_matches(arguments) -> tuple[list[dict], list[dict]]:
"""(the cached MCP tools a mcp_tool_search call loads, the matches too large to)."""
arguments = arguments if isinstance(arguments, dict) else {}
specs = _cached_mcp_catalog()
order, exact = _mcp_ranked(specs, arguments.get("query"))
picked = [specs[i] for i in order[: max(_mcp_search_limit(arguments.get("limit")), exact)]]
- fitted = mcp_fit_loaded(picked)
+ fitted = []
+ for spec in picked:
+ retained = [*fitted, spec]
+ if len(mcp_fit_loaded(retained)) != len(retained):
+ continue
+ candidate = _mcp_search_result(retained)
+ # Include the envelope so the result cap cannot split a schema.
+ if _fit_result_to_room(candidate, MCP_TOOL_SEARCH_NAME) == candidate:
+ fitted.append(spec)
return fitted, [spec for spec in picked if spec not in fitted]
@@ -12874,14 +12893,7 @@ def _mcp_tool_search(arguments) -> str:
f"No MCP tool matched '{query.strip()}'. Try other keywords, or one of the tool names "
f"listed in the {MCP_TOOL_SEARCH_NAME} description."
)
- lines = [
- f"- {spec['function']['name']}: {_mcp_summary(spec['function'].get('description') or '')}"
- for spec in found
- ]
- return (
- f"Loaded {len(found)} MCP tool{'s' if len(found) != 1 else ''}. Call the one that fits directly, "
- "with the parameters in its schema:\n" + "\n".join(lines)
- )
+ return _mcp_search_result(found)
def _mcp_tool_prefix(server: dict) -> str:
diff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.py
index 63d9b8395b9..b0f7c636cc3 100644
--- a/studio/backend/tests/test_llama_cpp_tool_loop.py
+++ b/studio/backend/tests/test_llama_cpp_tool_loop.py
@@ -7093,7 +7093,7 @@ def test_nested_object_schema_is_relaxed_on_the_wire_but_not_in_the_loop(monkeyp
def test_an_mcp_tool_search_leaves_a_budget_of_one_for_the_tool_it_found(monkeypatch):
- """Loading deferred MCP tools is not a tool round (#10997)."""
+ """Search preserves the execution budget and rendered prefix while expanding the decoding grammar."""
from core.inference import tools as tools_mod
ping = {
@@ -7104,7 +7104,7 @@ def test_an_mcp_tool_search_leaves_a_budget_of_one_for_the_tool_it_found(monkeyp
"parameters": {"type": "object"},
},
}
- monkeypatch.setattr(tools_mod, "mcp_tool_search_specs", lambda arguments: [ping])
+ monkeypatch.setattr(tools_mod, "mcp_tool_spec", lambda name: ping)
monkeypatch.setattr(tools_mod, "mcp_loadable_specs", lambda tools: [ping])
monkeypatch.setattr(tools_mod, "mcp_record_loaded_tools", lambda *a: None)
streams = [
@@ -7113,7 +7113,12 @@ def test_an_mcp_tool_search_leaves_a_budget_of_one_for_the_tool_it_found(monkeyp
[_sse({"content": "Pinged."}), _done()],
]
backend, payloads = _backend_and_payloads(monkeypatch, streams)
- calls = _record_tool_calls(monkeypatch, "ok")
+ calls = _record_tool_calls(
+ monkeypatch,
+ lambda name: "Loaded 1 MCP tool.\n schema: " + json.dumps(ping)
+ if name == "mcp_tool_search"
+ else "ok",
+ )
_run_tool_loop(
backend,
@@ -7123,7 +7128,9 @@ def test_an_mcp_tool_search_leaves_a_budget_of_one_for_the_tool_it_found(monkeyp
)
assert [name for name, _ in calls] == ["mcp_tool_search", "mcp__srv1__ping"]
- assert "mcp__srv1__ping" in [t["function"]["name"] for t in payloads[1].get("tools", [])]
+ assert payloads[1]["tools"] == payloads[0]["tools"] + [ping]
+ assert payloads[1]["chat_template_kwargs"]["tools"] == payloads[0]["tools"]
+ assert payloads[2]["tools"] == payloads[0]["tools"]
def test_budget_exhausted_final_pass_keeps_the_cached_tool_catalogue(monkeypatch):
diff --git a/studio/backend/tests/test_mcp_servers.py b/studio/backend/tests/test_mcp_servers.py
index 1c0f9783ad5..dd1e7344839 100644
--- a/studio/backend/tests/test_mcp_servers.py
+++ b/studio/backend/tests/test_mcp_servers.py
@@ -2344,6 +2344,10 @@ def test_mcp_tool_search_loads_exact_names_then_ranked_matches(tmp_path, monkeyp
out = tools_mod.execute_tool("mcp_tool_search", {"query": "query rows with sql"})
assert out.startswith("Loaded 1 MCP tool. Call the one that fits directly")
assert "- mcp__srv1__query: [A] Query rows." in out
+ assert (
+ "schema: " + json.dumps(tools_mod.mcp_tool_spec("mcp__srv1__query"), separators = (",", ":"))
+ in out
+ )
assert tools_mod.execute_tool("mcp_tool_search", {"query": "zzzz"}).startswith(
"No MCP tool matched 'zzzz'."
)
@@ -2473,19 +2477,25 @@ def test_controller_loads_searched_and_named_mcp_tools(tmp_path, monkeypatch, se
"function": {"name": "mcp_tool_search", "arguments": '{"query": "move pages", "limit": 1}'}
}
decision = controller.prepare_call(call)
- controller.record_result(
- decision, tools_mod.execute_tool("mcp_tool_search", decision.arguments)
+ result = tools_mod.execute_tool("mcp_tool_search", decision.arguments)
+ controller.record_result(decision, result)
+ assert _names(controller.active_tools()) == ["mcp_tool_search"]
+ assert "schema: " in result
+ assert (
+ json.dumps(tools_mod.mcp_tool_spec("mcp__srv1__move-pages"), separators = (",", ":"))
+ in result
+ )
+ moved_call = controller.prepare_call(
+ {"function": {"name": "mcp__srv1__move-pages", "arguments": "{}"}}
)
- active = controller.active_tools()
- assert _names(active) == ["mcp_tool_search", "mcp__srv1__move-pages"]
- assert active[1] == tools_mod.mcp_tool_spec("mcp__srv1__move-pages")
+ assert moved_call.action == "execute"
+ assert _names(controller.active_tools()) == ["mcp_tool_search"]
- # A deferred tool named without a search loads too, typed by its full schema.
named = controller.prepare_call(
{"function": {"name": "mcp__srv1__ping", "arguments": '{"n": "3"}'}}
)
assert named.action == "execute" and named.arguments == {"n": 3}
- assert "mcp__srv1__ping" in _names(controller.active_tools())
+ assert "mcp__srv1__ping" not in _names(controller.active_tools())
# Later turns of the thread list the tools it ran, newest first; a tool only loaded is not relisted.
assert _names(listing_for("thread-1")) == ["mcp_tool_search"]
@@ -2522,7 +2532,7 @@ def test_a_search_loads_only_what_fits_the_window(tmp_path, monkeypatch):
assert out.endswith("are too large for this model's context window.")
-def test_controller_retires_older_loads_to_stay_within_the_window(tmp_path, monkeypatch):
+def test_controller_keeps_the_declared_tools_stable_across_searches(tmp_path, monkeypatch):
from core.inference import tools as tools_mod
from core.inference.tool_loop_controller import ToolLoopController
@@ -2535,23 +2545,21 @@ def test_controller_retires_older_loads_to_stay_within_the_window(tmp_path, monk
lambda: int(2.5 * cost / tools_mod._MCP_TOOL_LOAD_SHARE),
)
controller = ToolLoopController(tools = [tools_mod._mcp_tool_search_spec([])])
+ before = controller.active_tools()
for name in ("query-0", "query-1", "query-2"):
decision = controller.prepare_call(
{"function": {"name": "mcp_tool_search", "arguments": json.dumps({"query": name})}}
)
controller.record_result(decision, "Loaded")
- assert _names(controller.active_tools()) == [
- "mcp_tool_search",
- "mcp__srv1__query-1",
- "mcp__srv1__query-2",
- ]
- assert (
- controller.prepare_call(
- {"function": {"name": "mcp__srv1__query-0", "arguments": "{}"}}
- ).action
- == "execute"
- )
- assert _names(controller.active_tools())[1:] == ["mcp__srv1__query-2", "mcp__srv1__query-0"]
+ assert controller.active_tools() == before
+ for name in ("query-0", "query-2"):
+ assert (
+ controller.prepare_call(
+ {"function": {"name": f"mcp__srv1__{name}", "arguments": "{}"}}
+ ).action
+ == "execute"
+ )
+ assert controller.active_tools() == before
def test_forced_and_image_mapped_tools_stay_listed(tmp_path, monkeypatch, searching):
@@ -2665,3 +2673,179 @@ def test_controller_without_the_search_tool_never_loads_mcp_tools(tmp_path, monk
decision = controller.prepare_call({"function": {"name": "mcp__srv1__ping", "arguments": "{}"}})
assert decision.action == "disabled"
assert controller.active_tools() == []
+
+
[email protected]("searched", [False, True])
+def test_deferred_mcp_calls_keep_catalog_coercion_on_every_call(monkeypatch, searched):
+ from core.inference import tool_loop_controller as controller_mod
+
+ ping = {
+ "type": "function",
+ "function": {
+ "name": "mcp__srv1__ping",
+ "parameters": {"type": "object", "properties": {"n": {"type": "integer"}}},
+ },
+ }
+ monkeypatch.setattr(
+ controller_mod,
+ "_mcp_tool_spec",
+ lambda name: ping if name == "mcp__srv1__ping" else None,
+ )
+ monkeypatch.setattr(controller_mod, "_mcp_tool_search_specs", lambda arguments: [ping])
+ search_spec = {
+ "type": "function",
+ "function": {
+ "name": "mcp_tool_search",
+ "parameters": {"type": "object", "properties": {}},
+ },
+ }
+ controller = controller_mod.ToolLoopController(tools = [search_spec])
+ before = controller.active_tools()
+ if searched:
+ search = controller.prepare_call(
+ {"function": {"name": "mcp_tool_search", "arguments": '{"query":"ping"}'}}
+ )
+ controller.record_result(search, "Loaded")
+ for number in (3, 4):
+ decision = controller.prepare_call(
+ {
+ "function": {
+ "name": "mcp__srv1__ping",
+ "arguments": json.dumps({"n": str(number)}),
+ }
+ }
+ )
+ assert decision.action == "execute"
+ assert decision.arguments == {"n": number}
+ assert controller.active_tools() == before
+ unknown = controller.prepare_call(
+ {"function": {"name": "mcp__srv1__unknown", "arguments": "{}"}}
+ )
+ assert unknown.action == "disabled"
+ assert controller.active_tools() == before
+
+
+ "schema_chars,small_chars,context_tokens,result_tokens",
+ [
+ (20_000, 0, 32_768, 32_768),
+ (3_000, 0, 2_048, 2_048),
+ (1_200, 0, 32_768, 300),
+ (30_000, 8_000, 32_768, 32_768),
+ ],
+)
+def test_search_returns_whole_schemas_within_the_result_budget(
+ tmp_path, monkeypatch, listing_window, schema_chars, small_chars, context_tokens, result_tokens
+):
+ from core.inference import tools as tools_mod
+
+ big = {
+ "name": "large",
+ "inputSchema": {
+ "type": "object",
+ "properties": {"value": {"type": "string", "description": "x" * schema_chars}},
+ },
+ }
+ _cache_server_tools(tmp_path, monkeypatch, [big, dict(_PING, description = "p" * small_chars)])
+ listing_window(context_tokens)
+ result = tools_mod.execute_tool(
+ "mcp_tool_search",
+ {"query": "large ping"},
+ context_tokens = context_tokens,
+ result_budget_tokens = result_tokens,
+ )
+ assert result.startswith("Loaded 1 MCP tool.")
+ schemas = [
+ json.loads(line.removeprefix(" schema: "))
+ for line in result.splitlines()
+ if line.startswith(" schema: ")
+ ]
+ assert _names(schemas) == ["mcp__srv1__ping"]
+ assert "truncated" not in result
+
+
+ "properties",
+ [
+ {"<|im_end|>": {"type": "string"}},
+ {"value": {"type": "string", "enum": ["<|im_end|>"]}},
+ ],
+)
+def test_deferred_mcp_tools_keep_schema_identifier_filter(tmp_path, monkeypatch, properties):
+ from core.inference import tools as tools_mod
+ from core.inference.tool_loop_controller import ToolLoopController
+
+ _cache_server_tools(
+ tmp_path,
+ monkeypatch,
+ [
+ {
+ "name": "unsafe",
+ "inputSchema": {"type": "object", "properties": properties},
+ }
+ ],
+ )
+ controller = ToolLoopController(tools = [tools_mod._mcp_tool_search_spec([])])
+ call = {"function": {"name": "mcp__srv1__unsafe", "arguments": "{}"}}
+ assert controller.prepare_call(call).action == "disabled"
+ search = controller.prepare_call(
+ {
+ "function": {
+ "name": "mcp_tool_search",
+ "arguments": '{"query":"unsafe"}',
+ }
+ }
+ )
+ controller.record_result(search, "Loaded")
+ assert controller.prepare_call(call).action == "disabled"
+ assert len(controller.active_tools(include_deferred = True)) == 1
+
+
+def test_search_grammar_uses_the_schemas_returned_by_the_worker(
+ tmp_path, monkeypatch, listing_window
+):
+ import contextvars
+
+ from core.inference import tools as tools_mod
+ from core.inference.tool_loop_controller import ToolLoopController
+ from core.inference.tool_stream_exec import stream_tool_execution
+
+ large = {
+ "name": "large",
+ "inputSchema": {
+ "type": "object",
+ "properties": {"value": {"type": "string", "description": "x" * 30_000}},
+ },
+ }
+ _cache_server_tools(tmp_path, monkeypatch, [large, dict(_PING, description = "p" * 4_000)])
+ listing_window(32_768)
+ monkeypatch.setattr(
+ tools_mod,
+ "_REQUEST_RESULT_BUDGET",
+ contextvars.ContextVar("test_result_budget", default = None),
+ )
+ controller = ToolLoopController(tools = [tools_mod._mcp_tool_search_spec([])])
+ arguments = {"query": "large ping"}
+ decision = controller.prepare_call(
+ {"function": {"name": "mcp_tool_search", "arguments": json.dumps(arguments)}}
+ )
+ stream = stream_tool_execution(
+ lambda callback: tools_mod.execute_tool(
+ "mcp_tool_search", arguments, context_tokens = 32_768, result_budget_tokens = 3_000
+ ),
+ tool_name = "mcp_tool_search",
+ )
+ while True:
+ try:
+ next(stream)
+ except StopIteration as stop:
+ result = stop.value
+ break
+ assert "- mcp__srv1__ping:" in result
+ assert "- mcp__srv1__large:" not in result
+ assert tools_mod._REQUEST_RESULT_BUDGET.get() is None
+ controller.record_result(decision, result)
+ assert _names(controller.active_tools(include_deferred = True)) == [
+ "mcp_tool_search",
+ "mcp__srv1__ping",
+ ]
diff --git a/studio/backend/tests/test_studio_tool_loop.py b/studio/backend/tests/test_studio_tool_loop.py
index 63175713caa..12490e908a7 100644
--- a/studio/backend/tests/test_studio_tool_loop.py
+++ b/studio/backend/tests/test_studio_tool_loop.py
@@ -2163,3 +2163,37 @@ def test_a_trailing_image_turn_takes_the_notice_as_a_text_part():
],
}
]
+
+
+def test_deferred_mcp_schema_reaches_external_transports(monkeypatch, executed):
+ from core.inference import tool_loop_controller as controller_mod
+
+ search = _tool("mcp_tool_search")
+ ping = _tool("mcp__srv1__ping")
+ monkeypatch.setattr(controller_mod, "_mcp_tool_search_specs", lambda args: [ping])
+ monkeypatch.setattr(controller_mod, "_mcp_tool_spec", lambda name: ping)
+ transport = FakeTransport(
+ [
+ [
+ _sse(
+ {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "search",
+ "function": {
+ "name": "mcp_tool_search",
+ "arguments": '{"query":"ping"}',
+ },
+ }
+ ]
+ }
+ ),
+ _sse(finish = "tool_calls"),
+ _DONE,
+ ],
+ [_sse({"content": "ready"}), _sse(finish = "stop"), _DONE],
+ ]
+ )
+ _run(transport, tools = [search])
+ assert transport.requests[1]["tools"] == [search, ping]