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.

Studio: keep the MCP tool list steady between messages (#16488)

Nilayc8ad341008ad
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 7373879c677..735ac264b5a 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -12362,7 +12362,8 @@ _MCP_TOOL_LOAD_SHARE = 0.5
_MCP_TOOL_SEARCH_SUMMARY_CHARS = 80
_MCP_TOOL_SEARCH_MAX_LIMIT = 10
_MCP_TOOL_SEARCH_MAX_NAMES = 200
-# Tools a thread ran stay listed on its later turns, so the prompt prefix (and llama-server's cache) holds.
+# Tools a thread ran stay listed on its later turns, so the prompt prefix (and llama-server's cache) holds; its
+# ranked tools hold until a message's best match is listable and not among them.
_MCP_LOADED_PER_THREAD = 8
_MCP_LOADED_THREADS_MAX = 512
MCP_TOOL_SEARCH_NAME = "mcp_tool_search"
@@ -12373,6 +12374,7 @@ _MCP_LISTING_FORCED: ContextVar = ContextVar("mcp_listing_forced", default = Non
_MCP_LISTING_IMAGE: ContextVar = ContextVar("mcp_listing_image", default = False)
# (account, thread) -> MCP tools the thread ran while they were deferred, oldest first.
_MCP_LOADED_THREADS: "OrderedDict[tuple, list[str]]" = OrderedDict()
+_MCP_RANKED_THREADS: "OrderedDict[tuple, list[str]]" = OrderedDict()
_MCP_LOADED_LOCK = threading.Lock()
# Digest of the catalog's searchable text -> its in-memory FTS5 index, rebuilt only when that text changes.
_MCP_SEARCH_INDEXES: "OrderedDict[str, sqlite3.Connection]" = OrderedDict()
@@ -12599,6 +12601,25 @@ def mcp_record_loaded_tools(thread_id, names) -> None:
_MCP_LOADED_THREADS.popitem(last = False)
+def _mcp_held_ranking(by_name: dict) -> list[str]:
+ key = _mcp_thread_key()
+ if key is None:
+ return []
+ with _MCP_LOADED_LOCK:
+ return [n for n in _MCP_RANKED_THREADS.get(key, ()) if n in by_name]
+
+
+def _mcp_hold_ranking(names: list[str]) -> None:
+ key = _mcp_thread_key()
+ if key is None:
+ return
+ with _MCP_LOADED_LOCK:
+ _MCP_RANKED_THREADS.pop(key, None)
+ _MCP_RANKED_THREADS[key] = names
+ while len(_MCP_RANKED_THREADS) > _MCP_LOADED_THREADS_MAX:
+ _MCP_RANKED_THREADS.popitem(last = False)
+
+
def _mcp_listing(listed: list[tuple[dict, list[dict], list[dict]]]) -> list[dict]:
specs = [spec for _, _, server_specs in listed for spec in server_specs]
ctx = _MCP_LISTING_CONTEXT_TOKENS.get()
@@ -12652,14 +12673,30 @@ def _mcp_listing(listed: list[tuple[dict, list[dict], list[dict]]]) -> list[dict
)
ran = [name for name in reversed(_mcp_loaded_names()) if name in by_name]
ranked = [specs[i]["function"]["name"] for i in _mcp_ranked(specs, _MCP_LISTING_QUERY.get())[0]]
- for name in dict.fromkeys(ran + ranked[:_MCP_TOOL_PRELOAD]):
- if by_name[name] in listing:
- continue
- cost = _text_token_cost(json.dumps(by_name[name], separators = (",", ":")), ctx)
- if cost <= room:
- listing.append(by_name[name])
- room -= cost
- return listing
+ ranked = ranked[:_MCP_TOOL_PRELOAD]
+
+ def filled(names: list[str]) -> list[dict]:
+ chosen = list(listing)
+ left = room
+ for name in dict.fromkeys(ran + names):
+ if by_name[name] in chosen:
+ continue
+ cost = _text_token_cost(json.dumps(by_name[name], separators = (",", ":")), ctx)
+ if cost <= left:
+ chosen.append(by_name[name])
+ left -= cost
+ return chosen
+
+ held = _mcp_held_ranking(by_name)
+ chosen = filled(held)
+ held = [name for name in held if by_name[name] in chosen]
+ if ranked and (not held or by_name[ranked[0]] not in chosen):
+ fresh = filled(ranked)
+ # A best match too big to list is not worth dropping the held tools for.
+ if not held or by_name[ranked[0]] in fresh:
+ chosen, held = fresh, [name for name in ranked if by_name[name] in fresh]
+ _mcp_hold_ranking(held)
+ return chosen
def _cached_mcp_catalog() -> list[dict]:
diff --git a/studio/backend/tests/test_mcp_servers.py b/studio/backend/tests/test_mcp_servers.py
index dd1e7344839..48b2c5c4be1 100644
--- a/studio/backend/tests/test_mcp_servers.py
+++ b/studio/backend/tests/test_mcp_servers.py
@@ -2189,6 +2189,7 @@ def _cache_server_tools(tmp_path, monkeypatch, tools):
_reset_db(tmp_path, monkeypatch)
monkeypatch.setattr(mcp_client, "_tool_cache", {})
monkeypatch.setattr(tools_mod, "_MCP_LOADED_THREADS", OrderedDict())
+ monkeypatch.setattr(tools_mod, "_MCP_RANKED_THREADS", OrderedDict())
mcp_servers_db.create_server(id = "srv1", display_name = "A", url = "https://a.example/mcp")
mcp_client.cache_tools("srv1", tools)
@@ -2380,6 +2381,185 @@ def test_mcp_listing_lists_the_tools_the_user_message_asks_for(tmp_path, monkeyp
assert listing_for(ask) == ["mcp_tool_search"]
+def _thread_listing(tools_mod, searching, messages):
+ import contextvars
+
+ ctx = contextvars.copy_context()
+ ctx.run(tools_mod.set_mcp_listing_context_tokens, searching, "thread-1", messages)
+ return ctx.run(lambda: tools_mod.cached_mcp_tools()[0])
+
+
+def test_mcp_listing_holds_while_the_best_match_stays_listed(tmp_path, monkeypatch, searching):
+ from core.inference import tools as tools_mod
+
+ _cache_server_tools(tmp_path, monkeypatch, _NOTES)
+ rankings = {"first": [0, 1], "second": [0, 2]}
+ monkeypatch.setattr(tools_mod, "_mcp_ranked", lambda specs, query: (rankings[query], 0))
+
+ first = _thread_listing(tools_mod, searching, [{"role": "user", "content": "first"}])
+ second = _thread_listing(tools_mod, searching, [{"role": "user", "content": "second"}])
+
+ assert len(_names(first)) > 1 and second == first
+
+
+def test_mcp_listing_lists_a_best_match_that_did_not_fit_before(tmp_path, monkeypatch, searching):
+ from core.inference import tools as tools_mod
+
+ _cache_server_tools(tmp_path, monkeypatch, _NOTES)
+ real_cost = tools_mod._text_token_cost
+
+ def cost(text, ctx):
+ if '"name":"mcp_tool_search"' in text:
+ return 0
+ return 100 if text.startswith("{") else real_cost(text, ctx)
+
+ monkeypatch.setattr(tools_mod, "_text_token_cost", cost)
+ monkeypatch.setattr(tools_mod, "_MCP_TOOL_PRELOAD_SHARE", 150 / searching)
+ rankings = {"first": [0, 1], "second": [1, 0]}
+ seen = []
+
+ def ranked(specs, query):
+ seen[:] = [spec["function"]["name"] for spec in specs]
+ return rankings[query], 0
+
+ monkeypatch.setattr(tools_mod, "_mcp_ranked", ranked)
+
+ first = _thread_listing(tools_mod, searching, [{"role": "user", "content": "first"}])
+ assert seen[0] in _names(first) and seen[1] not in _names(first)
+ second = _thread_listing(tools_mod, searching, [{"role": "user", "content": "second"}])
+ assert seen[1] in _names(second)
+
+
[email protected]("how", ["forced", "ran"])
+def test_mcp_listing_ranks_the_first_message_when_its_best_match_is_listed(
+ tmp_path, monkeypatch, searching, how
+):
+ import contextvars
+
+ from core.inference import tools as tools_mod
+
+ _cache_server_tools(tmp_path, monkeypatch, _NOTES)
+ best = "mcp__srv1__move-pages"
+ other = []
+
+ def ranked(specs, query):
+ names = [spec["function"]["name"] for spec in specs]
+ first = names.index(best)
+ second = 0 if first else 1
+ other[:] = [names[second]]
+ return [first, second], 0
+
+ monkeypatch.setattr(tools_mod, "_mcp_ranked", ranked)
+ choice = None
+ if how == "forced":
+ choice = {"type": "function", "function": {"name": best}}
+ else:
+ tools_mod.mcp_record_loaded_tools("thread-1", [best])
+ ctx = contextvars.copy_context()
+ ctx.run(
+ tools_mod.set_mcp_listing_context_tokens,
+ searching,
+ "thread-1",
+ [{"role": "user", "content": "move it"}],
+ choice,
+ )
+ names = _names(ctx.run(lambda: tools_mod.cached_mcp_tools()[0]))
+
+ assert best in names and other[0] in names
+
+
+def test_mcp_listing_lists_a_tool_a_later_message_needs(tmp_path, monkeypatch, searching):
+ from core.inference import tools as tools_mod
+
+ _cache_server_tools(tmp_path, monkeypatch, _NOTES)
+ chat = [{"role": "user", "content": "hello"}]
+ assert "mcp__srv1__move-pages" not in _names(_thread_listing(tools_mod, searching, chat))
+ chat += [
+ {"role": "assistant", "content": "Hi."},
+ {"role": "user", "content": "Move my roadmap page under the Archive page."},
+ ]
+ assert "mcp__srv1__move-pages" in _names(_thread_listing(tools_mod, searching, chat))
+
+
+def test_mcp_listing_reranks_when_no_held_tool_still_fits(tmp_path, monkeypatch, searching):
+ from core.inference import tools as tools_mod
+
+ _cache_server_tools(tmp_path, monkeypatch, _NOTES)
+ sizes = {"ping": 100, "create-pages": 60, "move-pages": 40}
+ real_cost = tools_mod._text_token_cost
+
+ def cost(text, ctx):
+ if '"name":"mcp_tool_search"' in text:
+ return 0
+ for name, size in sizes.items():
+ if text.startswith("{") and f'"name":"mcp__srv1__{name}"' in text:
+ return size
+ return 1000 if text.startswith("{") else real_cost(text, ctx)
+
+ monkeypatch.setattr(tools_mod, "_text_token_cost", cost)
+ monkeypatch.setattr(tools_mod, "_MCP_TOOL_PRELOAD_SHARE", 110 / searching)
+ held, ran, best = (f"mcp__srv1__{name}" for name in sizes)
+ rankings = {"first": [held], "second": [ran, best]}
+
+ def ranked(specs, query):
+ names = [spec["function"]["name"] for spec in specs]
+ return [names.index(name) for name in rankings[query]], 0
+
+ monkeypatch.setattr(tools_mod, "_mcp_ranked", ranked)
+
+ assert held in _names(
+ _thread_listing(tools_mod, searching, [{"role": "user", "content": "first"}])
+ )
+ tools_mod.mcp_record_loaded_tools("thread-1", [ran])
+ chat = [{"role": "user", "content": "second"}]
+ second = _thread_listing(tools_mod, searching, chat)
+ assert _names(second) == ["mcp_tool_search", ran, best]
+ assert _thread_listing(tools_mod, searching, chat) == second
+
+
+def test_mcp_listing_holds_when_the_best_match_cannot_fit(tmp_path, monkeypatch, searching):
+ from core.inference import tools as tools_mod
+
+ _cache_server_tools(tmp_path, monkeypatch, _NOTES)
+ sizes = {"ping": 40, "create-pages": 40, "query": 1000}
+ real_cost = tools_mod._text_token_cost
+
+ def cost(text, ctx):
+ if '"name":"mcp_tool_search"' in text:
+ return 0
+ for name, size in sizes.items():
+ if text.startswith("{") and f'"name":"mcp__srv1__{name}"' in text:
+ return size
+ return 40 if text.startswith("{") else real_cost(text, ctx)
+
+ monkeypatch.setattr(tools_mod, "_text_token_cost", cost)
+ monkeypatch.setattr(tools_mod, "_MCP_TOOL_PRELOAD_SHARE", 100 / searching)
+ rankings = {"first": ["ping", "create-pages"], "second": ["query", "move-pages"]}
+
+ def ranked(specs, query):
+ names = [spec["function"]["name"] for spec in specs]
+ return [names.index(f"mcp__srv1__{name}") for name in rankings[query]], 0
+
+ monkeypatch.setattr(tools_mod, "_mcp_ranked", ranked)
+
+ first = _thread_listing(tools_mod, searching, [{"role": "user", "content": "first"}])
+ assert _names(first) == ["mcp_tool_search", "mcp__srv1__ping", "mcp__srv1__create-pages"]
+ assert _thread_listing(tools_mod, searching, [{"role": "user", "content": "second"}]) == first
+
+
+def test_mcp_listing_follows_a_change_of_subject(tmp_path, monkeypatch, searching):
+ from core.inference import tools as tools_mod
+
+ _cache_server_tools(tmp_path, monkeypatch, _NOTES)
+ chat = [{"role": "user", "content": "Who are the users in the workspace?"}]
+ _thread_listing(tools_mod, searching, chat)
+ chat += [
+ {"role": "assistant", "content": "Two people."},
+ {"role": "user", "content": "Move my roadmap page under the Archive page."},
+ ]
+ assert "mcp__srv1__move-pages" in _names(_thread_listing(tools_mod, searching, chat))
+
+
def test_mcp_listing_matches_a_write_verb_to_the_tool_named_with_another(
tmp_path, monkeypatch, searching
):