Repository navigation
feat: execute hosted tool_search over deferred functions, namespaces, and MCP servers - #472
Conversation
… and MCP servers Closes vllm-project#448. Signed-off-by: haoshan98 <[email protected]>
…e-size limits Signed-off-by: haoshan98 <[email protected]>
…nish A hosted search's output no longer waits for slower calls in its round. Calls run to completion independently of client delivery, so a slow client cannot stall them, and a failing call still drains its peers. Also makes two matches exhaustive and borrows the tool list when loading searched tools. Signed-off-by: haoshan98 <[email protected]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Signed-off-by: haoshan98 <[email protected]>
… no lint suppression, docs Signed-off-by: haoshan98 <[email protected]>
|
@codex review |
|
Codex Review: Something went wrong. Try again later by commenting “@codex review”. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Signed-off-by: haoshan98 <[email protected]> # Conflicts: # crates/agentic-server-core/src/types/io/input.rs
|
@codex review again |
|
Codex Review: Something went wrong. Try again later by commenting “@codex review”. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
tjtanaa
left a comment
There was a problem hiding this comment.
Two source-traced tool-identity issues in replay and same-response continuation. I have not executed the branch; the suggested regression cases below are not runtime reproductions.
| call_pair( | ||
| call, | ||
| &call.id, | ||
| model_tool_name(&call.server_label, &call.name), |
There was a problem hiding this comment.
[P2] Preserve collision-resolved MCP names when replaying calls
This reconstructs the model-facing name with an empty collision map rather than the alias assigned during discovery. For example, if server docs lists read.file followed by read_file, discovery assigns the second tool a suffixed internal name. Its public mcp_call still contains name: "read_file", so replaying it with store:false produces mcp__docs__read_file, the alias belonging to the first tool. The model then sees the second tool's arguments/result attributed to the wrong function. Please resolve replay names against the discovered identities, or share collision-safe naming between discovery and replay, and add a round-trip test with two names that sanitize identically.
There was a problem hiding this comment.
Thanks, confirmed and fixed in 379c9aa.
A replayed mcp_call now takes the name discovery assigned its tool in this request (McpToolNames, built from the declaration's discovered tools), and only derives a name when the server is not discovered in the request. With tool search active, the private input now keeps replayed gateway calls typed (model_input_keeping_gateway_calls), so the upstream request names them after discovery instead of before.
Tests: replayed_mcp_call_keeps_the_name_discovery_assigned (unit, read.file then read_file on docs) and replayed_mcp_call_keeps_its_discovered_name_when_tool_search_is_active (integration). Both failed before the fix.
There was a problem hiding this comment.
The ordinary replay path now preserves the discovered aliases, including the hosted-search case. There is still a compaction variant at 379c9aa: summarize_items retains the public MCP call records but constructs a fresh summarization request with tools: None (executor/compaction.rs, request_payload and the call around lines 173–196). Its McpToolNames is therefore empty, so the fallback still lowers docs/read.file and docs/read_file to the same function name in the summarizer input. This loses the distinction between their arguments/results in the summary; it does not dispatch a tool. Could we preserve the identity mapping for compaction without enabling tool execution, and add a collision replay test with a forced compaction threshold? This remaining path is source-traced; I have not executed the test.
There was a problem hiding this comment.
Thanks, confirmed and fixed in 442e335 for both compaction paths. Single-agent compaction now names replayed MCP calls with the compacted request's discovered tools before building the summary request, and multi-agent CompactionPlan keeps the request's MCP declarations for its summary (only the declarations; neither summary request offers tools, so nothing can execute).
Tests: compaction_summary_keeps_discovered_mcp_names_for_replayed_calls (forced threshold, end to end) and multi_agent_compaction_summary_keeps_discovered_mcp_names; both failed before the fix.
One remaining limit: the explicit /v1/responses/compact endpoint runs no MCP discovery, so it has no discovered names and still derives them.
| if let OutputItem::FunctionCall(call) = item | ||
| && call.namespace.is_none() | ||
| && self.self_namespaced_functions.contains(&call.name) | ||
| { | ||
| call.namespace = Some(call.name.clone()); |
There was a problem hiding this comment.
[P2] Strip the public self-namespace before an async continuation round
When hosted search loads a top-level function declared with async:true, its call can continue into another inference round in the same AgentTurn. This adds namespace=get_weather to that call, and append_round_input copies the decorated output into the next model input. The self-namespace stripping in prepare_history runs at request preparation, while the subsequent input normalization/async lowering does not remove this decoration. Consequently vLLM flattens the history call to get_weather__get_weather although the declared tool remains get_weather. Could we keep the public decoration separate from model-facing history, or strip it on every upstream request? A hosted-search → deferred async function → next inference round test should assert that the next upstream call remains unqualified.
There was a problem hiding this comment.
Thanks, confirmed and fixed in 379c9aa.
CodexNamespaceHandler::resolve_input now drops namespace from a call whose namespace equals its own name when that name is a declared top-level function, on every upstream request, so async continuation rounds see the plain call too. The public item keeps the self-namespace. A call to an undeclared namespace x with member x is forwarded as before.
Test: async_continuation_after_a_search_keeps_the_call_unqualified_for_the_model (hosted search loads a deferred async function, the response continues, and the next upstream call stays get_weather). It failed before the fix.
… in every round A replayed mcp_call takes the name discovery assigned its tool in this request, so two tools whose names sanitize alike keep distinct names; tool search keeps replayed gateway calls typed until the upstream request names them. A searched top-level function's self-namespace is dropped on every upstream request, including async continuation rounds. Signed-off-by: haoshan98 <[email protected]>
…ries Single-agent compaction names replayed MCP calls with the compacted request's discovered tools before building its summary request, and the multi-agent compaction plan keeps the request's MCP declarations for its summary. Neither summary request offers tools. Signed-off-by: haoshan98 <[email protected]>
…log and docs - One `is_searched_function_call` predicate in tool/codex.rs decides when a searched top-level function's self-namespace is dropped; the upstream request and replayed tool-search history both use it. - Replace inline `std::` paths added by this branch with top-level imports. - Move the search-output doc comment onto `canonical_search_output`. - CHANGELOG: add hosted tool_search (vllm-project#448), and the MCP listing failure (424 / response.failed), empty `allowed_tools`, and MCP `tool_choice` 400 changes. - ARCHITECTURE: name `normalized_model_input_with` / `model_input_with` as the upstream projection that names replayed MCP calls with discovered tools. Signed-off-by: haoshan98 <[email protected]>
Brings in vllm-project#437 (shared tool scheduling limits for Messages). The conflict in GatewayScheduler::execute_all keeps this branch's ordered results and uses vllm-project#437's GatewaySchedulerPolicy::new_round_execution_slots for the round's execution slots, here and in gateway/lifecycle.rs, replacing the branch's own execution_slots helper. Signed-off-by: haoshan98 <[email protected]>
| item: ToolSearchCall::try_from(payload).ok()?, | ||
| }, | ||
| // Only the gateway produces search outputs; an upstream never streams one. | ||
| SSEItemType::ToolSearchOutput => return None, |
There was a problem hiding this comment.
still need to add try_from pattern for this. upstream is not limited to vLLM only. other upstream might still emit ToolSearchOuput
There was a problem hiding this comment.
Thanks, agreed that silently dropping it isn't right in general. Looking into it, parsing the output alone wouldn't change anything:
- The gateway never declares
tool_searchto the upstream: every declaration, includingtool_search, is lowered to a function (ToolDeclaration::to_function_toolsinto_upstream_request), so no upstream is asked to run a search. - An upstream that searched anyway would emit a
tool_search_callwithcall_id: null. Today streaming ignores that call leniently (and marks completion uncertain), and the blocking path rejects it (native_call_idrequires client execution), so its output would have no call to pair with.
I also checked this end to end with OpenAI (gpt-5.6) as the upstream, recording the contract scenarios through the gateway with a logging proxy in front of OpenAI: all 42 declarations went upstream as functions, and OpenAI returned only function_call, reasoning and message items, never tool_search_call or tool_search_output. That run also showed the lowered search call kept the public tsc_ item id, which OpenAI rejects for a function_call; 4608829 sends it without an item id, and all 24 upstream requests then succeed.
Supporting it means a third kind of search next to client and gateway-hosted: an origin marker (like CodeInterpreterCallOrigin) so an upstream-executed pair isn't mistaken for a gateway-hosted one, the streaming and blocking paths, history, and lifecycle tests.
Since that's a new capability rather than part of hosted search, I'd like to track it as a follow-up issue and keep this PR to the projection/ownership changes from your other comments. Does that work for you, or would you prefer it here?
Brings in vllm-project#458 (opt-in per-caller request rate limiting). Merged without conflicts. Signed-off-by: haoshan98 <[email protected]>
| description: Option<&'a str>, | ||
| } | ||
|
|
||
| pub(super) fn prepare_history( |
There was a problem hiding this comment.
Why does tool search need its own history-to-model-input preparation path? This combines definition availability, call/output validation, and construction of model-facing items. Definition loading belongs in tool-search state, but model-input projection already belongs to types/io/input.rs, and client call/output linkage is also validated by executor/pending_calls.rs. Please consolidate these responsibilities with their existing owners. Extracting this code from tool_search.rs preserves the overlapping responsibilities rather than resolving them.
There was a problem hiding this comment.
Thanks, agreed. Reworked in 6332a9f (with d0359aa pinning the behavior first):
- Model-input projection now lives in
types/io/input:SearchHistory(types/io/input/search_history.rs) pairs search items and lowers them, andproject_for_modelcalls it.tool_search/history.rsno longer builds model items; it only loads the definitions search outputs carry (load_history_definitions) and checks the rules the ledger can't see (item ids, hosted pairs, output status). - Client call/output linkage is owned by
executor/pending_calls.rs. It now also runs on the direct (store: false) path when the input replays search items, so a malformed history gets the same answer as on aprevious_response_idcontinuation. The oldSearchPairingvalidator intool_search/history.rsis gone; pairing is now a per-item result of the walker intypes/io/input/search_history.rs. tests/tool_search_pairing_characterization_test.rspins each malformed case on both paths (written before the change, updated where the owner changed; CHANGELOG lists the error changes).
| .filter(|item| !item.is_compaction_trigger()) | ||
| .collect(); | ||
| // The summary request carries no tools, so replayed MCP calls take this request's discovered names here. | ||
| let mcp_names = McpToolNames::from_tools(request.tools.as_deref().unwrap_or_default()); |
There was a problem hiding this comment.
Compaction should not need to construct MCP name mappings or explicitly lower replayed gateway calls. This makes it responsible for tool-specific conversion details and creates another place that must change when tool representations evolve. Please preserve historical naming context independently of the tools callable in the summary request, and use the shared input projection. Compaction should select the history window and request a summary with tools disabled; the input conversion layer should resolve historical tool names.
There was a problem hiding this comment.
Agreed. In 53ad953, compaction no longer builds names or lowers calls: name_replayed_gateway_calls and CompactionPlan::mcp_declarations are removed, and both summary requests carry no tools. Historical naming now comes from the input itself: McpToolNames::with_listings (types/io/input/mcp_names.rs, the discovery naming algorithm moved out of tool::mcp) names a replayed call from the server's latest successful mcp_list_tools record in the input, with this request's discovery taking precedence when it has one. A single-agent response records its current listing in the enriched input (multi-agent histories already do), so a mid-response summary names calls the same way. The multi-agent test is now multi_agent_compaction_summary_names_replayed_mcp_calls_from_the_listing, with a history that carries its listing, as real ones do.
| status: GatewayCallStatus, | ||
| ) -> Option<OutputItem>; | ||
|
|
||
| fn model_input( |
There was a problem hiding this comment.
Why is model-input conversion being added to the execution ownership interface? These methods are forwarded through ErasedGatewayExecutor, TypedGatewayExecutor, and GatewayBinding, spreading the responsibility across the binding layers. types/io/input.rs should remain the authoritative model-input projection path. Please remove these conversion hooks from the executor trait and ownership wrappers, let the executor record canonical items, and use the existing input projection for subsequent inference. This also keeps live execution and replay from requiring separate conversion paths.
There was a problem hiding this comment.
Removed in c1c165e. model_input/history_input are gone from GatewayExecutor, ErasedGatewayExecutor, TypedGatewayExecutor and GatewayBinding (ownership.rs is identical to upstream main again). A gateway result carries one set of input items, recorded as history and appended for the next round; the upstream projection in types/io/input lowers them, so live execution and replay share one conversion path.
| self.executor.public_output(call, output, status, &self.params) | ||
| } | ||
|
|
||
| fn model_input( |
There was a problem hiding this comment.
why this function model_input and history_inputs keep on repeating everywhere. seems complicated and not maintainable.
There was a problem hiding this comment.
Agreed — they're gone (c1c165e); see the reply above.
|
|
||
| /// The model sees the same call and output a continuation rebuilds from | ||
| /// the public pair, so later prompts share this response's prefix. | ||
| fn model_input( |
There was a problem hiding this comment.
This crosses the execution, history, and input-conversion boundaries. The OpenAI recordings show that a client-submitted tool_search_output.tools loads definitions for subsequent calls, and that replaying a hosted tool_search_call / tool_search_output pair restores the loaded definitions without another search. Hosted execution has a different lifecycle—both items are emitted in the same response with execution: "server" and call_id: null—but this does not require the hosted executor to own another model-input/history preparation path.
The PR already reuses load_definition(), so please extend that reuse through result application and projection: have hosted search produce a typed result, let the executor gateway apply it and record/emit the canonical public items, and keep their model-facing conversion in types/io/input.rs. The new model_input() / history_input() hooks make the hosted handler construct both representations and spread that responsibility through the ownership wrappers. Preserve the hosted-specific pairing and event lifecycle, while giving live execution and replay one authoritative projection path.
Recording evidence (checked against the committed OpenAI reference captures, not a new live API run):
- Client output loads definitions: turn 2 submits
tool_search_output.tools; the response callsget_weather, and the next turn calls the loadedtravel.get_timezone. - Hosted transcript replay restores availability: the second
store: falserequest replays the public search pair; its response calls the MCP tool without another search. - Hosted SSE uses ordinary item lifecycle events:
output_item.added/output_item.donefor the call, followed by the same events for its output.
These recordings establish observable loading, replay, and lifecycle behavior. They do not establish OpenAI's internal module boundaries; consolidating ownership is the architectural recommendation for this repository.
There was a problem hiding this comment.
Done in c1c165e on top of 6332a9f:
- The hosted search runs once, when the call is planned, and returns a typed
PlannedResult::SearchPair(completed publictool_search_call+tool_search_output). The gateway records it without a permit, timeout or execution, emits the follow-uptool_search_outputfrom it, and keeps its output bounded and budgeted. - The canonical public pair is what's recorded;
SearchHistoryintypes/io/inputlowers it for the model, the same for the live round, aprevious_response_idcontinuation and astore: falsereplay (tests/hosted_tool_search_projection_test.rschecks the prefixes match, and that a multi-agent history stored with the old private pair still restores). One gap remains outside this change: when the model emits reasoning before a gateway call, stored history puts the call ahead of that reasoning, for every gateway tool and already on main, so a continuation reorders it; tracked in Continuations reorder a round's reasoning around gateway-executed calls #482. - The hosted-specific pairing (
call_id: null, output answers the oldest open hosted call) and event lifecycle are unchanged; the recorded cassettes pass at 4608829. - 4608829 sends the lowered
tool_searchcall, and the function calls replayed formcp_call/web_search_call, without an item id: recording through the gateway against OpenAI showed it rejects afunction_callid that doesn't start withfc_and ties anfc_id to thecall_idit issued, so the call is identified by itscall_idalone.
Characterization before moving tool-search pairing and model-input lowering to single owners: - each malformed search history's answer on the direct and previous_response_id paths; - the live round, continuation and store: false replay show the model the same search call and output; - multi-agent history stores the model's private pair (fixture captured from this code), and the tool-less compaction summary shows the pair and the searched call unqualified; - the token estimate of that history, and that a hosted pair is never a pending call. Signed-off-by: haoshan98 <[email protected]>
- SearchHistory (types/io/input/search_history.rs) pairs search items without rejecting anything: a client item keeps its call_id, a hosted output answers the oldest open hosted call. The upstream projection and the compaction estimate lower search items through it, so live, continuation and replay show the model the same pair. - prepare_history becomes load_history_definitions: it loads definitions and keeps the rules the ledger cannot see (item ids, hosted pairs, output status). The prepared input keeps the public search items. - The pending-call ledger owns client search pairing on every path, now also on the direct path for input with search items, so a malformed history gets the same answer as on a continuation. - A call whose namespace is its own name is unqualified without needing declarations; ensure_request_prepared is keyed on declarations, so a tool-less compaction summary may carry public search items. Signed-off-by: haoshan98 <[email protected]>
…put hooks - The hosted search runs once, when the call is planned, and attaches a typed PlannedResult::SearchPair to its GatewayToolEventPlan. The gateway records it without a permit, timeout or execution; the follow-up tool_search_output and the completed call item come from it, and its model-facing output stays bounded and budgeted. - model_input/history_input leave GatewayExecutor, the ownership wrappers and the hosted executor; GatewayCallResult carries one input that is both history and the next round's input, lowered by the upstream projection. - Multi-agent history now stores the public pair; a history stored with the model's private pair (captured fixture) still restores and continues. Signed-off-by: haoshan98 <[email protected]>
…tion - types/io/input/mcp_names.rs holds the discovery naming algorithm (moved from tool::mcp::handler) and McpToolNames: this request's discovered names win, since the model can call those tools now; each server's latest successful listing in the input names the rest; the derived name is the last resort. - The upstream projection reads the listings in its own input, so a compaction summary that offers no tools still names calls as the model knew them. Compaction no longer builds an MCP name mapping: name_replayed_gateway_calls and CompactionPlan::mcp_declarations go, and the multi-agent summary carries no tools again. - A single-agent response records each server's current successful listing in the enriched input (as multi-agent histories do), even when the registry does not emit it again, for a mid-response summary; it is never stored from there. Signed-off-by: haoshan98 <[email protected]>
…d MCP names ARCHITECTURE.md, the tool-framework and MCP design docs, and the API doc describe the reworked design: types/io/input lowers search items and replayed calls for every upstream request, a hosted search's PlannedResult is recorded without execution, gateway results carry one input, the pending-call ledger also checks replayed search history on the direct path, and MCP names come from this request's discovery, else the listings in the input. Signed-off-by: haoshan98 <[email protected]>
The upstream projection lowered a hosted or client tool_search_call, and a replayed mcp_call or web_search_call, to a function_call that kept the public item id (tsc_, mcp_, ws_). vLLM accepts any id, but OpenAI requires a function_call id to begin with fc_, and it ties a known fc_ id to the call_id it issued. The public items keep no such call_id (a hosted search has call_id null), so with OpenAI as the upstream every round after a hosted search failed with 400. The lowered call now carries no item id; its call_id still pairs it with its output, the same live, on continuation and on replay. Checked through the gateway against OpenAI (gpt-5.6: all 24 upstream requests succeed, JSON and streaming) and live against vLLM (Qwen3.6). Tests assert that a lowered search call has no id; the estimate test now counts the call the model reads without it. Signed-off-by: haoshan98 <[email protected]>
tjtanaa
left a comment
There was a problem hiding this comment.
Re-reviewed the updated source and regression tests. One additional namespace-identity issue remains below; this is source-traced, not an executed reproduction.
| } else if names_itself(call) { | ||
| call.namespace = None; |
There was a problem hiding this comment.
[P2] Preserve real same-name namespaces when declarations are absent
namespace == name does not establish that this was a searched top-level function: a valid namespace weather can also contain a member named weather. summarize_items passes canonical history into a compaction request with tools: None, so there is no namespace map here and this branch rewrites that real weather.weather call to top-level weather. The previous implementation preserved unmapped namespaces; now the summarizer loses which tool produced the arguments/result, and no-tools replay has the same ambiguity. Please require searched-top-level provenance before stripping the namespace (or preserve unknown namespaces), and add a no-declarations projection/compaction test that distinguishes a genuine same-name namespace member from a searched top-level function.
There was a problem hiding this comment.
Good catch, agreed. Fixed in 266c3c3: a call that names itself is unqualified only when its name is a top-level function the request declares or a completed tool_search_output in the input loaded (ResponsesInput::searched_function_names), the same predicate load_history_definitions uses. Any other unmapped call keeps its namespace, as on main, so a genuine weather.weather member stays namespaced in the compaction summary while a searched function's call is still unqualified.
The upstream projection dropped the namespace from any function_call whose namespace equals its name when no declared namespace mapped it, assuming it was a searched top-level function. A namespace may hold a member of its own name, so a genuine weather.weather call reached the model as top-level weather, notably in the compaction summary, which declares no tools. The namespace is now dropped only when the name is a top-level function the request declares or a completed tool_search_output in the input loaded (ResponsesInput::searched_function_names), the predicate load_history_definitions already applies. Any other unmapped call keeps its namespace, as before hosted search. CodexNamespaceHandler::resolve_input takes the request's function names. Tests cover no declarations with a search that loaded a function, a namespace, or nothing; a declared function whose search output is gone; and a forced compaction summary. Signed-off-by: haoshan98 <[email protected]>
tjtanaa
left a comment
There was a problem hiding this comment.
The original real-namespace case is corrected and now has targeted coverage. Source review found a distinct regression in searched-function history after a prior compaction; no tests were executed in this review.
| functions.extend(declarations.iter().flatten().filter_map(ToolDeclaration::function_name)); | ||
| let input = lower_async_calls(CodexNamespaceHandler.resolve_input( |
There was a problem hiding this comment.
[P2] Retain searched-function provenance across successive compactions
The real-namespace case is fixed, but this now misses a previously searched top-level function once its search output has been compacted away. A reachable sequence is: load deferred get_weather, compact that history, then continue and call the still-loaded function before another compaction. prepare::restored_loaded_tools restores its definition from metadata and ToolSearchState puts it in the request's declarations, not back into search-output history; its public call still has namespace: "get_weather". The next summarize_items creates a fresh tools: None request, so neither source used here contains the function. That summary receives the artificial namespace instead of the original unqualified get_weather, changing the tool identity associated with its arguments/result.
Please preserve non-callable historical naming provenance into the summary without enabling tools, and cover a second compaction after metadata-restored loading. a_declared_top_level_function_call_is_unqualified_without_its_search_output does not cover this path because it supplies declarations, whereas the summary deliberately has none. This is source-traced, not an executed reproduction.
Brings in vllm-project#466 (DELETE /v1/responses/{id} and GET .../input_items; tool outputs carry ids and statuses) and vllm-project#475 (HTTP store:false runs through the executor). Lowered search outputs and replayed gateway calls carry no id or status; replayed search history is checked on vllm-project#466's resolved items; a replayed gateway record resolved to its stored output stays an input record, so store:false replays of stored MCP, web search and multi-agent hosted items still reach the model. Tests updated for vllm-project#466's duplicate-item check and Signed-off-by: haoshan98 <[email protected]> vllm-project#475's unstored conversation turns.
|
@haoshan98 I re-reviewed this PR, but the Files changed view is very large and some files would not load for me to leave inline comments. I have put those comments together in this message instead. 1. Make the registry the single runtime inventoryInline location: tool/tool_search.rs:677 Could we simplify this around one request-scoped I suggest building the registry once from the full rehydrated public declarations, then adding discovered MCP members and applying completed This removes 2. Use one tool-search type and handlerInline location: tool/registry.rs:40 Please remove the internal 3. Centralize tool validation and definition indexingInline location: tool/tool_search/definitions.rs:42 Tool identity and collision checks are now split across Tool search would then add only the timing rules: a completed 4. Give pairing and replay one validation pathInline location: tool/tool_search/history.rs:31 The latest revision correctly moved model-facing search conversion into 5. Keep MCP naming context out of request inputInline location: executor/engine.rs:144
|
A compaction summary declares no tools, so its projection unqualified a self-named call only when a search output in its input loaded the function. Once an earlier compaction removed that search, a function restored from response metadata and called again reached the next summary as get_weather.get_weather. Compaction now hands the summary its source request's top-level functions (RequestPayload::top_level_function_names: declared, including restored loads, plus those a search in its input loaded) as naming context only, on the single-agent, multi-agent and standalone compact paths. The summary still sends no tools and compaction rewrites no call; the shared projection adds the names to the set it already uses. A name the source's namespace map resolves as a member of its own namespace is left out, so the summary reads that call as the member, as the live request does. Signed-off-by: haoshan98 <[email protected]>
A response appended each MCP server's current listing to its enriched input so a tool-less compaction summary could name replayed mcp_call items, though the model never reads a listing. The summary now receives its source request's naming as context instead: HistoryNaming holds the searched top-level functions (as since 82acce2) and the MCP names discovery recorded on the declared servers, and the upstream projection uses them after the request's own discovery and before listings in the input, the order the appended listing gave. Real listings stay public output and history records. Signed-off-by: haoshan98 <[email protected]>
Hosted search had its own ToolType::HostedToolSearch and a HostedToolSearchExecutor that repeated ToolSearchHandler's validation and lowering. Both modes now register ToolType::ToolSearch; the declaration's execution chooses the entry's ownership (ToolDeclaration::is_gateway_owned), and the gateway runs a hosted search with ToolSearchHandler as its GatewayExecutor. Routing reads (kind, ownership): the dispatcher sends a gateway-owned search down the gateway path as it does for a gateway shell, and admission, planning and the translation context check ownership. The documented agentic.tool.type value for an executed search stays hosted_tool_search. The tool-search registry entries move to the registry's tool-search module, lowering tool_search.rs's size baseline. Signed-off-by: haoshan98 <[email protected]>
Tool search kept its own definition index (records, namespace member state, withheld names, MCP loads) in ToolSearchState and checked flattened names in a separate namespace-only pass (validate_namespace_collisions). That inventory is now a general tool::catalog::ToolCatalog. Declarations enter through ToolCatalog::build, which checks identities, namespace members and deferred MCP namespaces; every later definition, from a client search output, a hosted search or response metadata restored after compaction, enters through ToolCatalog::load, which compares it with the held one or inserts it; and validate_model_visible_names checks the whole inventory's names together, at the same point and with the same messages as before. Tool search adds only its timing rules (PriorCalls: a load must not resolve a call the history made before it). tool_search/definitions.rs and the codex validator are removed; tool_search.rs drops to 1244 lines. Signed-off-by: haoshan98 <[email protected]>
tool_search/history.rs scanned replayed history again for item ids, hosted pairs and output status beside SearchHistory, which already pairs the items for the upstream projection. SearchHistory now also owns those rules: scan records each position's first defect as a typed SearchHistoryDefect (same messages) and whether a hosted call is left open. The pending-call ledger keeps the client call/output rules. ToolCatalog::load_history walks the history once, applies each position's verdict in order, loads each completed output and checks each call against what is loaded, so a history with several defects still gets the answer of the earliest one (two new pairing cases pin that). tool_search/history.rs is removed. Signed-off-by: haoshan98 <[email protected]>
Hosted search built a third searchable index (HostedCatalog of HostedCatalogEntry values) from ToolSearchState beside the registry. The catalog now holds what that index held: each deferred MCP server's discovered members (ToolCatalog::discover_mcp) and the tools loaded before this response (begin_response, set at preparation, so a repeated search in a response still returns the same tools and a later response is not offered earlier loads). ToolCatalog::search is the lookup, with the recorded query cases moved over; the hosted search entry is bound to the catalog, and ToolSearchHandler's gateway execution moves to the registry's tool-search module. The public tool_search_call/tool_search_output constructors and the public item id move to types/io/output/tool_search_call.rs. tool/tool_search/hosted.rs is removed. Signed-off-by: haoshan98 <[email protected]>
ToolSearchState kept the live catalog through the response, beside the registry. Preparation still builds the catalog (so an invalid history is a 400 before streaming), but the response's registry now takes it (build_tool_registry; a rebuild takes the freshly prepared one, or else the previous registry's) and owns it as Arc<ToolCatalog>, which the hosted search entry shares. Withheld names, deferred MCP tools, hosted deferred functions and the availability and MCP tool_choice checks read the registry; ToolRegistry::load_searched_tools loads a search's tools into the catalog, regenerates the offered tools with the fixed synthetic declaration, refreshes client entries and rebinds the search. ToolSearchState keeps only the public snapshot persistence needs (effective declarations and loaded definitions, which the registry updates after each load) and preparation's private views. Signed-off-by: haoshan98 <[email protected]>
Ingestion already rejects a call to a withheld definition, but a deferred MCP tool is a registered gateway entry from discovery, so the registry would run it if a call reached it. The registry now keeps the deferred MCP names with its catalog (updated after each load), answers is_deferred for them and for withheld functions and members, and refuses such a call before a round's tools run (ensure_loaded_calls) and in dispatch, with ingestion's error. withheld_names reads the same state. Tests pin that a deferred function becomes callable only after a load, and that a call to an unloaded deferred MCP tool fails the response with zero tools/call, blocking and streaming. ARCHITECTURE.md describes the catalog the registry owns. Signed-off-by: haoshan98 <[email protected]>
- Streaming kept applying the client search's strict call checks to hosted
searches once both shared ToolType::ToolSearch, so a hosted call with
malformed arguments failed the stream where it had loaded nothing; the
checks now apply to client searches only, as before (blocking still
refuses, as before). A test pins both answers.
- The catalog's name check calls the namespace map builder instead of a
second copy of the flattened-name rule.
- ensure_loaded_calls also refuses a call to a deferred namespace member,
which reaches the registry restored to its public {namespace, name}, and
still refuses a searched function's call restored with its own name as
namespace.
- A registry built without its prepared catalog is a configuration error,
not an empty catalog; the unused fallback to the previous registry's
catalog is removed, and ToolCatalog::load_history keeps its prior-call
map to itself.
- validate_tool_search_availability checks the search entry's ownership
against the declared mode; the tool-search item id reuses
stable_name_hash; ARCHITECTURE.md names the round's call check as the
guard behind ingestion.
Signed-off-by: haoshan98 <[email protected]>
|
|
||
| exec_ctx | ||
| .gateway_executors | ||
| .apply_configured_mcp_defaults(ctx.enriched_request.tools.as_deref_mut()); |
There was a problem hiding this comment.
why is this configuration before the exec_ctx.gateway_executors.validate_declaration()?
There was a problem hiding this comment.
apply_configured_mcp_defaults fills the two fields an [mcp_servers] entry can default, defer_loading and the
server description, on request declarations of configured servers. It runs after rehydration and before the
second validate_declarations so that this check and everything after it, tool-search preparation in particular
(which reads defer_loading to decide whether a server is searched or eager), see the declaration the request will
actually run with, including one inherited from an earlier turn. validate_declarations itself does not read either
field today, so the order does not change its answer; it keeps the checked declaration and the executed one the same.
The first validate_declarations (before storage work) checks the request as sent.
| params.server_label | ||
| ))); | ||
| } | ||
| fn validate(&self, _params: &McpToolParam) -> Result<(), ToolError> { |
There was a problem hiding this comment.
this function now is stale no implementation! I think the validation of params has to be added back we need validation of tools params belongs to ToolHandlers. while resolving name collision among tools to be refactored with use of tool catalog in registry as commented earlier to use these two patterns.
There was a problem hiding this comment.
Done in 4bd143dc:
McpHandler::validatenow holds the checks one declaration can answer alone:connector_idis unsupported, andrequire_approvalmust be"never". They run with request validation, so a streaming request now gets HTTP 400 before its stream starts instead of an error event in a 200 stream (pinned byunsupported_mcp_options_reject_before_the_stream). Discovery calls the samevalidatefor callers that build a registry directly. Only the rule that needs the gateway's configuration (a server the gateway does not configure must setrequire_approval) stays inGatewayExecutors. Messages are unchanged.- The tool catalog owns the name rule:
ToolCatalog::validate_declared_names. The registry applies it first in every build, before it registers or discovers anything, so requests with and without tool search reach the same check; tool-search preparation applies it to the whole catalog (deferred definitions included) so an invalid catalog is still a 400 before streaming. Messages and the order of errors are unchanged.
Brings in vllm-project#480 (ARCHITECTURE.md request admission and rate limiting), vllm-project#481 (PostgreSQL conversation upsert), vllm-project#467 (prompt cache breakpoints on inlined text files), vllm-project#478 (benchmark session sweep) and vllm-project#487 (test alignment with typed Responses validation). Merged without conflicts. Signed-off-by: haoshan98 <[email protected]>
| @@ -0,0 +1,229 @@ | |||
| //! Public records of gateway-executed calls that a client replays as input. | |||
| //! | |||
| //! A `store: false` client sends back the `mcp_call` and `web_search_call` items a response returned. The model | |||
There was a problem hiding this comment.
this is out of the scope of this PR and does not limit to only mcp_call or web_search_call it extends to all the input item types cause vLLM upstream does not understand these types that is the reason why we have normalization of tools as well as extend of lifecycle of these call handled only on gateway. this case has to be handled properly in another PR. The standard is the request coming in and they pass through the normalization paths and not replayed back by directly receiving these input item types. the standard request-in and response-out is how we record cassettes.
this is a separate problem. please open issue for this separately one criteria is that to verify parity with openai replay these calls back if client suppose to send these calls then match gateway behavior accordingly.
There was a problem hiding this comment.
Agreed, and removed in 5276ac54. The removal takes out replayed_calls.rs together with the MCP naming that only served it (mcp_names.rs and the MCP half of HistoryNaming) and their tests, so #464's gateway_call_input_preserves_typed_payloads_in_canonical_history is back to main's assertions and replayed mcp_call/web_search_call items behave exactly as they do on main. Because the hosted tool-search replay cassette group replays mcp_call items, its gateway leg is dropped, while the OpenAI reference recording stays as parity evidence for the follow-up. That follow-up is #492, which covers every gateway item type, both inline and by-id replays, and makes recording OpenAI's replay behavior per type its first acceptance criterion, so the gateway matches it.
Addresses review comment 4385725195 on mcp/handler.rs. - McpHandler::validate now refuses connector_id and any require_approval other than "never", with the same messages. It runs with request validation, so a streaming request gets HTTP 400 before its stream starts instead of an error event in a 200 stream. Discovery calls the same check for callers that build a registry directly. - GatewayExecutors keeps only the rule that needs the gateway's configuration (validate_mcp_approval_source): a server the gateway does not configure must set require_approval. - ToolCatalog::validate_declared_names owns the model-visible name rule. Every registry build applies it first (resolve_declarations), and tool-search preparation still applies it to the whole catalog, so an invalid catalog stays a 400 before streaming. Messages and error order are unchanged. Signed-off-by: haoshan98 <[email protected]>
Addresses review comment 4385842254: converting replayed gateway-executed call items is out of scope for hosted tool search and moves to a follow-up issue covering every gateway item type. - Remove replayed_calls.rs, the MCP naming that served it (mcp_names.rs, the mcp half of HistoryNaming) and their tests. internal_mcp_tool_name is private to mcp/handler.rs again, as on main; stable_name_hash moves to utils::common for its two users. - The model-input projection lowers only tool_search items and compaction checkpoints. A replayed mcp_call or web_search_call reaches vLLM unchanged, as on main; one referenced by id is left out of model input, as on main. vllm-project#464's canonical-history test is back to main's assertions. - The gateway leg of the hosted tool-search replay cassette is dropped (it replays mcp_call items); the OpenAI reference recording stays as parity evidence. - Docs and CHANGELOG state the known gap. Signed-off-by: haoshan98 <[email protected]>
Brings in vllm-project#468 (shared Messages tool-round decisions) and vllm-project#473 (trace context and baggage propagation to operator-configured MCP servers). No textual conflicts. vllm-project#473's mcp_trace_context_test builds an McpServerEntry::Http literal, which now also sets the description and defer_loading fields this branch adds. Signed-off-by: haoshan98 <[email protected]>
maralbahari
left a comment
There was a problem hiding this comment.
@haoshan98 Thanks for the work!
Summary
Adds hosted (gateway-executed)
tool_searchfor deferred functions, namespace members, and MCP servers. Closes #448.A request that declares
{"type": "tool_search"}(noexecution, orexecution: "server") now has the gateway run the search itself, as the Responses API does. Deferred tools stay hidden from the model until a search loads them. The search happens inside the same response, and the round continues with the loaded tools.execution: "client"(Codex) is unchanged.The behavior follows new OpenAI reference cassettes (gpt-5.6), recorded before any code change, and matching gateway cassettes (Qwen/Qwen3.6-35B-A3B-FP8 on vLLM). Both are pinned by
tests/hosted_tool_search_characterization_test.rs. For the 20 of 21querylegs where Qwen sent exactly the reference's arguments, the gateway loaded exactly the reference's tools.After review, each rule has one owner. One tool catalog (
tool::catalog::ToolCatalog) holds every definition a search can load and owns the model-visible name rule; the response'sToolRegistryowns that catalog; both search modes are one tool kind, owned where the declaration runs it; and one projection intypes/io/inputlowers the public search items for every upstream request: live, on continuation, onstore: falsereplay, and in compaction. See Design after review. The commits are staged so they can be read one at a time.Behavior
type: "mcp"servers withdefer_loading: true.mcp_<server_label>. Its description isserver_description, or""when absent.tool_searchwith{"paths": [...], "query"?: "..."}.querykeeps only tools whose name or description contains the whole query, ignoring case. This matches 22 recorded cases.tools/callis sent.tool_search_callandtool_search_output, both withexecution: "server"andcall_id: null. Streaming emits onlyoutput_item.added/donefor them, in the recorded order. Later items in the round shift by one output index, andoutput_item.addedevents stay in output-index order even when one round holds several searches.max_tool_calls.parallel_tool_calls: trueis allowed.toolsecho shows{"type": "tool_search", "description": null, "parameters": null}.namespaceset to its own name, as the reference does. A replayedfunction_callwhosenamespaceequals itsnamereaches the model unqualified only when that name is a top-level function the request declares or a completed search in the input loaded; any other unmapped call keeps its namespace, as before.previous_response_id, conversations, WebSocket sessions, compaction (restored metadata), astore: falsereplay that sends back the search items, and multi-agent.tool_searchwith no deferred tool: 400.execution: "client": 400.tool_choicenaming an unloaded deferred function or MCP tool: 400.tool_choice: {"type": "mcp", "server_label": ..., "name"?: ...}: now parsed and rejected with a typed 400 through fix: reject unsupported background and prompt parameters in typed Responses execution #456'sUnsupportedParameterError(code: "unsupported_value",param: "tool_choice", "MCP tool_choice is not supported; useauto,required, or a functiontool_choiceinstead"). Unlikebackgroundandprompt, it is also rejected on the direct route: a direct request declares no MCP server, so the selector names nothing. Before, it failed JSON parsing with a generic message. The reference returns 500 for a deferred server. Supporting it is tracked separately.[mcp_servers]entries acceptdefer_loadinganddescriptionas defaults. They are applied after rehydration and before the second declaration check, so that check and tool-search preparation see the declaration the request runs with.Behavior change: a failed MCP listing fails the request (all Responses MCP servers)
Until now, a Responses request whose MCP server could not list its tools carried on: the response held a failed
mcp_list_toolsitem and the server offered no tools. That behavior came from #178 (with #172 and #180), before any OpenAI recording of this case. New OpenAI recordings (mcp-failures: an unreachable host and an HTTP 500, each deferred and eager, plus a non-MCP endpoint and a 401) show the Responses API fails the whole request instead. The gateway now matches it for every MCP server, deferred or not:{"type": "external_connector_error", "code": "http_error", "param": "tools", "message": "Error retrieving tool list from MCP server: '<label>'. Http status code: 424 (Failed Dependency)"}.response.created,response.in_progress,output_item.added(anmcp_list_toolsitem withtools: []),response.mcp_list_tools.in_progress,response.mcp_list_tools.failed,error, andresponse.failedwhose output holds that listing. Nooutput_item.doneis sent for the listing, as recorded. Every frame echoes the declared tools, without MCP credentials, as the reference does./v1/messageshas no MCP support and is unchanged.errorframe (status 424) rather than the SSE sequence; with several servers, the stream'sresponse.failedoutput holds only the first failed listing.Clients that relied on a failed server being skipped now get the error and must remove or fix that server.
Behavior change: an
allowed_toolsfilter that matches nothing is no longer an errorThe gateway rejected an MCP server whose
allowed_toolsmatched none of its tools with a 400 ("empty final allowed tool set", a rule from #138). Themcp-failuresrecording shows the Responses API accepts it: the listing is empty (tools: []) and the response completes. The gateway now does the same for request-declared and operator-configured servers.Behavior change: unsupported MCP options are rejected before the stream
An MCP declaration with
connector_id, or with arequire_approvalother than"never", is now refused by the declaration's own check (McpHandler::validate) during request validation instead of during MCP discovery, with the same messages. A streaming HTTP or WebSocket request therefore gets the error before its stream starts (HTTP 400invalid_request_error) instead of an error event inside a 200 stream, and a request with several invalid declarations or inputs may now see this error first. The rule that needs the gateway's configuration (a server the gateway does not configure must setrequire_approval) stays with the gateway executors.Behavior change: replayed search history is checked the same way on every path
store: falserequest that carriestool_search_call/tool_search_outputitems now runs the pending-call check aprevious_response_idor conversation continuation runs. A duplicate clientcall_idor output, an output with no call, or a client search or other synchronous call without its output gets that check's 400 (for example "No tool call found for function call output with call_id …",param: "input") instead oftool error: invalid tool config: …. A request without search items is unchanged.tests/tool_search_pairing_characterization_test.rspins every case on both paths.tool_search_callwhose item id equals another call'scall_idis rejected (duplicate tool_search_call call_id), since the model would otherwise see two calls with one id.Known gap, unchanged from
main: replayedmcp_callandweb_search_callitems (#492)A client that replays a hosted MCP or web-search response gets the same result as on
main: sent inline withstore: false, themcp_call/web_search_callrecord reaches vLLM unchanged and vLLM rejects the request (500); sent byid, the stored record is left out of the model's input. Continuing withprevious_response_idworks. An earlier revision of this PR lowered these records; review moved that out of scope so every gateway item type is converted together, with OpenAI parity per type, in #492. The gateway leg of the hosted tool-searchreplaycassette is dropped for this reason, and the OpenAI reference recording stays as parity evidence.OpenAI as the upstream
The contract scenarios were also recorded through the gateway with OpenAI (gpt-5.6) as its upstream, with a logging proxy in front of OpenAI (evidence only; nothing added to the repo). Every declaration reached OpenAI as a function, and OpenAI never returned
tool_search_callortool_search_output. The run also found that the lowered search call kept the publictsc_item id, which OpenAI rejects for afunction_call(and anfc_id is tied to thecall_idOpenAI issued, which the public pair does not keep), so every round after a hosted search failed with 400. The lowered search call now carries no item id: all 24 upstream requests succeed, JSON and streaming, and a live vLLM run still works.Intentional differences from the reference
"strict": null, which cannot survive storage through the typed field. They keep"output_schema": null.output_schema: null.toolsecho keeps declaration order.param. The MCP listing failure matches the reference exactly,paramincluded.Implementation
ToolSearchExecution::Server.call_id: Option<String>on search items, validated at deserialization by execution.OutputItem::ToolSearchOutput.McpToolParam.server_description.tool/catalog.rs): declarations enter throughToolCatalog::build; every later definition (a client search output, a hosted search, response metadata restored after compaction) enters throughToolCatalog::load, which compares it with the one it holds or inserts it. It also holds each deferred MCP server's discovered members (discover_mcp) and the tools loaded before this response (begin_response), andToolCatalog::searchis the hosted lookup. Tool search adds only its timing rule (PriorCalls: a load must not resolve a call the history made before it).ToolType::ToolSearch; the declaration'sexecutiondecides the entry's ownership, and the gateway runs a hosted search withToolSearchHandleras itsGatewayExecutor. The telemetry valueagentic.tool.typefor an executed hosted search stayshosted_tool_search.ToolRegistrytakes it (Arc<ToolCatalog>). The registry offers the loaded definitions, withholds the deferred ones, refuses a call to a deferred tool before a round's tools run (ensure_loaded_calls) and in dispatch, andload_searched_toolsloads a search's results and regenerates the offered tools.GatewayToolEventPlancarries a typedPlannedResult::SearchPair, which the gateway records without a permit, timeout or execution. Its follow-uptool_search_outputtakes the next public output index.loaded_tool_names). NewExecutorError::McpListToolsFailed:AgentTurn::newraises it when a response's first registry build recorded a failed listing with no successful one in history; the streaming path renders it as the recorded event sequence.Design after review
SearchHistory(types/io/input/search_history.rs) pairs search items (a client item by itscall_id, a hosted output with the oldest open hosted call) and lowers them; the upstream projection and the compaction estimate use it. It also owns the search-only history rules (item ids, hosted pairs, output status) as typedSearchHistoryDefectverdicts, andToolCatalog::load_historywalks the history once, so a history with several defects gets the answer of the earliest one.ToolCatalog::validate_declared_names): every registry build applies it to the request's declarations before it registers or discovers anything, and tool-search preparation applies it to the whole catalog, deferred definitions included.CodexNamespaceHandler::validate_namespace_collisionsis removed.McpHandler::validateowns the checks one MCP declaration can answer alone; the gateway executors own the one that needs their configuration.GatewayExecutor, the ownership wrappers andGatewayBindingbuild no model input;tool/ownership.rsis identical tomain.HistoryNamingcarries the source request's searched top-level functions into a compaction summary, which declares no tools. Nothing in it is callable.ensure_request_preparedis keyed on declarations, so a tool-less summary may carry public search items.tool/catalog.rsandtool/catalog/{history,load,search}.rs,tool/tool_search/validation.rs,tool/registry/{mcp_listing,hosted_search}.rs,executor/gateway/public_output.rs,executor/engine/agent_turn/hosted_search.rs,types/io/input/{tool_search,search_history,history_naming}.rs,types/io/output/tool_search_call.rs, andtypes/tools/tool_search.rs.tool_search.rsshrinks below its recorded baseline, so.rust-file-sizes.jsonlowers it from 1660 to 1078.Model-facing search tool
The Responses API does not expose its search tool's description, so the gateway writes its own:
pathsis required andqueryis optional. Early gateway recordings showed Qwen putting the user's question inquery, which matches no tool. The description now says thatqueryonly narrows by tool name or description and should usually be omitted. Qwen still sometimes guesses aquery; the recordings keep that behavior. A search that loads nothing tells the model why (queryfilters by name or description, and earlier loads are not returned again), so a model does not keep repeating a filter that matches nothing. Codex's client-executed search output is unchanged.Not in this PR
mcp_call,web_search_call, and others) to model input: Convert replayed gateway-executed call items to model input, with OpenAI parity per item type #492.customtools are still rejected.tool_searchupstream, and an upstream-run call (call_id: null) is ignored when streaming and rejected (502) otherwise. Proposed as a follow-up.main; follow-up issue.main.Test Plan
cargo test --workspaceat 29a7f0a (this branch merged withmainthrough fix: propagate trace context and baggage to MCP servers #473): 2891 passed, 0 failed.cargo clippy --all-targets -- -D warnings,cargo fmt -- --checkand the Rust file-size check are clean; pre-commit passes on the changed files.tool_search_pairing_characterization_test(every malformed search history on the direct andprevious_response_idpaths) andhosted_tool_search_projection_test(live, continuation andstore: falsereplay show the model the same prefix; a multi-agent history stored with the old private pair restores; a tool-less compaction summary).hosted_tool_search_characterization_test(16): pins the OpenAI reference cassettes and checks the Qwen gateway cassettes against them: item shape and pairing,added/done-only streaming in order, identical tools for identical search arguments, validation statuses, and themcp-failures424 bodies and SSE sequence.hosted_tool_search_test(34, mock upstream and stub MCP server): blocking and SSE, query filtering, namespaces, deferred MCP, a call to an unloaded deferred tool refused with zerotools/call, MCP listing failures, emptyallowed_tools,max_tool_calls,parallel_tool_calls, validation, streaming order, continuations,store: falsereplay, operator defaults, multi-agent, and compaction.unsupported_mcp_options_reject_before_the_stream(HTTP):connector_idandrequire_approval: "always"get 400invalid_request_errorfor JSON and SSE, and the upstream receives no request.the_registry_applies_the_catalog_name_rule_before_discoverypins that a registry built directly reports the name collision before any MCP check.main.