Skip to content

Studio: search and load large MCP tool catalogs on demand - #13601

Merged
danielhanchen merged 11 commits into
mainfrom
studio-mcp-tool-search
Oct 14, 2026
Merged

danielhanchen merged 11 commits into
mainfrom
studio-mcp-tool-search

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

Fixes #10997

Large MCP catalogs eat the context window: Notion's 44 tools are about 65,000 tokens, so on a 100K window more than half the context goes to tool schemas on every request. #11046 only compacted the listing once it would not fit at all, so a window that could hold it still paid for all of it.

This adds tool search for local models, the way Claude Code and Codex defer MCP tools.

What changes

  • While the MCP listing takes at most 10% of the loaded local model's window, nothing changes: every tool is listed in full. External providers always get the full listing.
  • Past that, the model gets mcp_tool_search instead of the schemas. Its description names every tool with a one-line summary, so the model knows what exists.
  • A search ranks the catalog with SQLite FTS5 BM25 and reciprocal rank fusion, the same tokenizer, query shaping and fusion the knowledge-base search uses. Tool names and descriptions are indexed separately, because a word every Notion description shares ("page") otherwise has no weight at all. Exact tool names always load, including a name two servers share.
  • The matches are loaded into the running tool loop, so the next model call lists them with their full schemas and the model calls them directly. A deferred tool the model calls by name loads the same way.
  • Up front, the listing also carries the tools ranked best against the user's message (up to 5, within a third of the window), the tools the chat ran on earlier turns (so the prompt prefix the model server caches holds), a tool a forced tool_choice names, and the tools mapped to take an attached image.
  • Tools a turn loads stay within half of the window, oldest leaving first; a single tool too large for the window is refused with a message naming it.
  • The compaction path from Studio: list large MCP tool schemas compactly and load the full schema on demand #11046 (mcp_tool_schema, compact parameter listings, schema-on-error) is removed: every loaded tool has its full schema.

Accuracy

PR #11046's harness: a stdio stand-in serving Notion's real 44-tool catalog that validates every call against the tool's real inputSchema, 29 single-action tasks, Q4_K_M, temperature 0. Both sides ran on the same machine in the same Studio install, only the backend tree differs.

model window listing first call correct correct call anywhere in the turn prompt tokens (median) seconds per task (median)
Qwen3-30B-A3B-Instruct-2507 100K main, full 52% 83% 65,184 36.0
Qwen3-30B-A3B-Instruct-2507 100K this PR, tool search 76% 90% 11,366 7.2
Qwen3-30B-A3B-Instruct-2507 64K main, compacted 48% 86% 44,240 22.2
Qwen3-30B-A3B-Instruct-2507 64K this PR, tool search 72% 83% 10,817 7.4
Qwen3-4B-Instruct-2507 100K main, full 69% 72% 65,147 84.2
Qwen3-4B-Instruct-2507 100K this PR, tool search 69% 79% 11,394 8.3
Qwen3-4B-Instruct-2507 64K main, compacted 72% 79% 44,187 42.1
Qwen3-4B-Instruct-2507 64K this PR, tool search 69% 72% 11,392 8.3

30B on an A100, 4B on an L4. One greedy sample per task, so a 3 to 7 point move is one or two tasks: read it as 30B clearly better on the first call and level on the turn, 4B level.

An earlier version that listed only the search tool scored 59% on the 4B at 64K: small models often answered that a tool was unavailable rather than search for it. Listing the tools ranked against the user's message, and naming every tool with a summary, is what closed that gap.

Tests

studio/backend/tests/test_mcp_servers.py covers the full listing while it fits, deferral past the share, the search tool's description and its size budget, ranking (exact names, shared names, aliases, app-only tools, malformed schemas), loading through the tool loop controller with the load budget and eviction, the per-chat memory, and the forced and image-mapped tools. test_permission_mode.py covers the approval stream a deferred catalog needs. The tool loop, MCP and permission suites pass (6603 passed; the two test_checkpoint_compaction.py probe tests fail the same way on main).

Before / after in the chat UI

Notion's catalog connected through the local stdio stand-in, Qwen3-4B-Instruct-2507 Q4_K_M loaded at a 65,536-token window, same prompt on both sides. Before (merge base 280c456): the request carries all 44 Notion schemas in compacted form and the context meter reads 44.2k of 65.5k. After (572f09f): the request carries mcp_tool_search plus the five tools ranked against the message, the model calls the same notion-search, and the meter reads 6.4k of 65.5k.

Before: 44.2k of 65.5k context used for a one-line prompt. After: 6.4k of 65.5k, same notion-search call.

@danielhanchen danielhanchen self-assigned this Oct 13, 2026
@chatgpt-codex-connector

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

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 ✅ Completed 2026-10-14T10:18:57.069227Z 435ff56 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.

@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 ⚠️ Failed 2026-10-13T12:31:00.082435Z cddbb86 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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…aration by tokens, admit loadable names in the bare-JSON gate
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…eated search run, remember MCP calls before deferral
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@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: ae1e82f1da

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

Comment on lines +1390 to +1392
specs = (
neutralize_tool_descriptions([dict(s) for s in specs if isinstance(s, Mapping)]) or []
)

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 Pass the active markup profile when loading deferred tools

On a profiled model whose control vocabulary differs from the universal fallback, this unprofiled sweep can discard a schema that the initial model-specific sweep accepted. For example, the existing profile tests show that a Llama profile safely retains a property named </think>, whereas neutralize_tool_descriptions(..., markup=None) drops it; once that tool is deferred, mcp_tool_search reports it as loaded but the controller silently adds nothing, and a direct named call is classified as disabled. Thread the active render profile into the controller and use it here, as is already done when constructing the controller.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not changing this: it needs an MCP schema whose property names are another model family's control tokens, which no real server ships. The fallback sweep is stricter than any profile, so it can only drop such a tool, never let unsafe markup through.

Comment on lines +13874 to +13877
listing = [search]
listing += [by_name[name] for name in dict.fromkeys(pinned) if name in by_name]
room = ctx * _MCP_TOOL_PRELOAD_SHARE - _text_token_cost(
json.dumps(listing, separators = (",", ":")), ctx

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 Bound pinned schemas before adding them to the listing

When a request has an image attachment or a forced MCP tool, the full pinned schemas are appended without any admission check; room is computed only afterward and can already be negative. An MCP configuration with several image-mapped tools carrying large schemas, or a single oversized forced tool, therefore recreates the context overflow that catalog deferral is intended to prevent. Fit pinned schemas against a measured budget, retaining at least one suitable image recipient, and reject an oversized forced tool explicitly rather than sending an over-window prompt.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not changing this: these are pinned only when the request needs them (a forced tool_choice, or an attached image), and main lists them in full too. An over-window request is refused with the usual context error rather than silently truncated, so there is no regression to bound.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@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: ae1e82f1da

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

Comment on lines +1249 to +1254
if (
self._mcp_search
and tool_name.startswith(MCP_TOOL_PREFIX)
and tool_name not in self._allowed_tool_names
):
self._load_mcp_tools([_mcp_tool_spec(tool_name)])

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 Report oversized direct MCP loads instead of disabling them

When a deferred MCP tool's schema exceeds the 50% load share and the model invokes that tool directly by name, _mcp_fit_loaded drops the only requested spec, but preparation then continues and classifies the call as an ordinary disabled tool. The model receives the generic instruction to provide a final answer without more tools, rather than learning that the schema is too large and that reducing context or using another model could make the call possible. Detect this failed direct load and return the same context-size-specific error used by mcp_tool_search.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not changing this: it needs a single tool larger than half the window called by name without a search, and the only difference is the wording of the no-op reply. The search path already names such a tool as too large.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@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: e7f81a631d

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

Comment on lines +13871 to +13873
while max_chars and _text_token_cost(json.dumps(search, separators = (",", ":")), ctx) > budget:
max_chars //= 2
search = _mcp_tool_search_spec(catalog, max_chars)

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 Keep the minimal search declaration within budget

For small supported context windows, this loop stops as soon as max_chars reaches zero without checking whether the fixed search schema now fits. The zero-line fallback serializes to 682 ASCII characters, which _text_token_cost charges as 341 tokens when the model counter is unavailable, so a 1,000-token window still receives a declaration over three times its 10% budget (the existing 1,000-token test only checks its suffix). Even after the server-heading fallback, this fresh case can still crowd out or overflow an otherwise short request; validate the zero-line declaration too and shrink it further or reject deferral explicitly when it cannot fit.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not changing this: deferral only happens when the full listing is already over the share, and the zero-line declaration (about 170 real tokens) is always far smaller than the listing it replaces, so it never costs more than main. A 1,000-token window with an MCP catalog is not a configuration Studio serves.

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

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@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: e7f81a631d

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

descriptions ranked by BM25 and fused as the knowledge-base search fuses its legs."""
if not isinstance(query, str) or not query.strip() or not specs:
return [], 0
words = [w.casefold() for w in re.split(r"[\s,]+", query) if w]

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 Match aliased raw names before splitting search terms

When an MCP server advertises a raw tool name containing whitespace or a comma, _mcp_tool_names supports it by generating an alias, but an exact search for that raw name is split into separate words here before by_name is consulted. The tool is therefore treated only as a lexical match and, in a catalog with enough competing matches to exceed the search limit, may not be loaded at all despite the exact-name guarantee. Check the complete normalized query against by_name before splitting it into search terms.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not changing this: MCP tool names are not expected to contain spaces or commas, and the search tool's description lists the composed alias, not the raw name, so the name a model searches with is the alias, which matches exactly.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: e7f81a631d

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

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 13, 2026
# Conflicts:
#	studio/backend/tests/test_llama_cpp_tool_loop.py
@NilayYadav

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 9c761a00ba

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

@NilayYadav NilayYadav left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review + reproduction evidence

Pinned review: 9c761a00baee3749dd693cc6ee9cb532e47634a6. No blocking findings; one P2 suggestion below.

I reproduced the large-catalog cost on fresh upstream main (NVIDIA L4, Chromium 1440x900, unsloth/Qwen3-4B-Instruct-2507-GGUF Q4_K_M at Auto context). The setup was a remote MCP server serving a 40-tool Notion-style catalog (about 90K characters of schemas, nested filter/sort parameters) and the prompt "Search my Notion pages for Roadmap Q3":

  • main 7d132bb: context meter 29.6k / 134.9k, notion-search-pages called, 39.1 s for the turn, 29.9 tok/s. Three follow-up turns: 29.9k, 30.2k and 30.6k, at 17 s, 15 s and 19 s. With two chats generating at once, one failed with "The model ran out of context space while generating".
  • PR head (same change as 9c761a0): context meter 5.7k / 134.7k, the same notion-search-pages call, 15.0 s, 61.2 tok/s. Follow-ups: 6.1k, 7.1k and 8.8k, at 11 s, 11 s and 13 s. Asking for a tool that is not preloaded showed an mcp_tool_search card, then notion-create-comments ran with the right parent page id.

PR 13601 before/after

  • Small catalog under 10% of the window (Unsloth Docs only): both sides list it in full and call askQuestion, with the meter at 2.6k vs 2.7k; the difference is answer length. External providers, managed engines and the Responses passthrough never set the listing window, so they keep the full listing.
  • Tests: the 18 new tests in test_mcp_servers.py fail on main and pass on the head, and 2540 others are unchanged. The tool loop, MCP, permission and tools suites (82 files) show the same 7 environment failures on main and on the merged head (root uid AMD node tests, IPv6 loopback, one spill test), with 7437 vs 7440 passed.
  • The red pre-commit.ci check on 572f09f was its mergeable check stopping on a merge conflict: both sides appended tests at the end of test_llama_cpp_tool_loop.py. 9c761a0 resolves it, and the PR is mergeable again.

P2 suggestion: a ranked preload can list near-miss siblings and hide the tool that fits.

For "Add a comment to the Roadmap Q3 page saying the launch moved to September.", the five tools ranked against the message are notion-search-pages, notion-fetch-page, notion-fetch-comment, notion-search-comments and notion-update-comment. notion-create-comments is not among them, because "add" matches nothing in its text.

Qwen3-4B then called notion-update-comment, passing the page id as the comment id, in 4 of 4 runs (one follow-up turn and three fresh chats). On main the same prompt called notion-create-comments. This is the failure the deferral comment in _mcp_listing describes: a listed tool is called in place of the right, deferred one. How often it happens depends on the catalog, since a description that says "Add a comment" would rank it. Possible directions:

  • preload the siblings that share a ranked tool's object noun;
  • preload only when the top match clearly leads;
  • expand common verbs (add / create / new, remove / delete) on the name leg of the query.

PR 13601 add comment tool choice

Conclusion: the problem is real, and the PR fixes it. For the same request it uses about a fifth of the context and turns are 1.4x to 2.6x faster, with no change for small catalogs or external providers. Ready once CI on 9c761a0 is green; the near-miss preload above is worth a look first.

…load

"Add a comment" ranked update-comment and fetch-comment above create-comments
when no tool text said "add", so the model called the listed sibling. The name
leg now also matches the other verbs of the same write (create/add/new/reply,
delete/remove, update/edit/change).
@danielhanchen

Copy link
Copy Markdown
Member Author

Thanks for the independent repro and the near-miss case, that is a real wrong-tool failure.

Fixed in 435ff56: the name leg of the preload ranking now also matches the other verbs of the same write, so "add a comment" reaches create-comments instead of only the update-comment / fetch-comment siblings that share the noun. The groups are create (add, new, make, insert, append, post, reply), delete (remove, erase, trash, drop) and update (edit, change, modify, rename, patch). Read verbs are left alone on purpose: expanding "find" to "search" pulled every search-* tool above get-teams for "Find the teamspace called Design".

On the real 44-tool Notion catalog, the expected tool is in the preload for 26 of 29 eval tasks (was 25 of 29) at both 64K and 100K, with no task losing its tool; the one gained is "Reply ... to the existing discussion", which now lists notion-create-comment. test_mcp_listing_matches_a_write_verb_to_the_tool_named_with_another uses your catalog shape (a create tool whose text never says "add") and fails without the change.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 435ff5631b

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

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.

[Feature] MCP tools lazy loading

2 participants