Skip to content

feat: execute hosted tool_search over deferred functions, namespaces, and MCP servers - #472

Merged
haoshan98 merged 32 commits into
vllm-project:mainfrom
EmbeddedLLM:hosted-tool-search
Oct 30, 2026
Merged

haoshan98 merged 32 commits into
vllm-project:mainfrom
EmbeddedLLM:hosted-tool-search

Conversation

@haoshan98

@haoshan98 haoshan98 commented Oct 20, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds hosted (gateway-executed) tool_search for deferred functions, namespace members, and MCP servers. Closes #448.

A request that declares {"type": "tool_search"} (no execution, or execution: "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 21 query legs 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's ToolRegistry owns that catalog; both search modes are one tool kind, owned where the declaration runs it; and one projection in types/io/input lowers the public search items for every upstream request: live, on continuation, on store: false replay, and in compaction. See Design after review. The commits are staged so they can be read one at a time.

Behavior

  • Catalog:
    • Deferred functions, namespaces with deferred members, and type: "mcp" servers with defer_loading: true.
    • An MCP server is searched as the namespace mcp_<server_label>. Its description is server_description, or "" when absent.
    • Tools loaded by an earlier response are not offered again; a repeat search within one response returns them again.
  • Search: the model calls tool_search with {"paths": [...], "query"?: "..."}.
    • Each path loads a deferred function, a namespace's deferred members, or an MCP server's tools.
    • query keeps only tools whose name or description contains the whole query, ignoring case. This matches 22 recorded cases.
    • Unknown paths load nothing.
  • Deferred tools stay uncallable until loaded: a call to a deferred function, namespace member or MCP tool that no search has loaded is refused before any of the round's tools run, with ingestion's error, and no MCP tools/call is sent.
  • Public items: each search returns tool_search_call and tool_search_output, both with execution: "server" and call_id: null. Streaming emits only output_item.added/done for them, in the recorded order. Later items in the round shift by one output index, and output_item.added events stay in output-index order even when one round holds several searches.
  • Limits and echo:
    • Searches do not count toward max_tool_calls.
    • parallel_tool_calls: true is allowed.
    • The response tools echo shows {"type": "tool_search", "description": null, "parameters": null}.
  • Namespace field: a call to a searched top-level function reports namespace set to its own name, as the reference does. A replayed function_call whose namespace equals its name reaches 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.
  • Continuation and transports:
    • Loads persist across previous_response_id, conversations, WebSocket sessions, compaction (restored metadata), a store: false replay that sends back the search items, and multi-agent.
    • The public pair is the stored history, also for multi-agent. The projection lowers it to the model's call and output the same way live and on every replay: a hosted output answers the oldest open hosted call, whose item id is the model's call id. The lowered call carries no item id (see OpenAI as the upstream).
    • A compaction summary declares no tools, so it receives its source request's searched top-level functions as naming context only.
  • Validation:
    • tool_search with no deferred tool: 400.
    • Deferred MCP with execution: "client": 400.
    • tool_choice naming 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's UnsupportedParameterError (code: "unsupported_value", param: "tool_choice", "MCP tool_choice is not supported; use auto, required, or a function tool_choice instead"). Unlike background and prompt, 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.
  • Operator config: [mcp_servers] entries accept defer_loading and description as 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_tools item 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:

  • JSON: HTTP 424 with {"type": "external_connector_error", "code": "http_error", "param": "tools", "message": "Error retrieving tool list from MCP server: '<label>'. Http status code: 424 (Failed Dependency)"}.
  • Streaming: HTTP 200 with response.created, response.in_progress, output_item.added (an mcp_list_tools item with tools: []), response.mcp_list_tools.in_progress, response.mcp_list_tools.failed, error, and response.failed whose output holds that listing. No output_item.done is sent for the listing, as recorded. Every frame echoes the declared tools, without MCP credentials, as the reference does.
  • A continuation whose history already holds a successful listing for that server keeps going when the fresh listing fails, since the Responses API does not list such a server again. A mid-response rebuild (multi-agent refresh after client discovery) also keeps the failed item, as before, because output may already be streaming.
  • /v1/messages has no MCP support and is unchanged.
  • Not recorded from OpenAI, so not pinned: WebSocket sends a single error frame (status 424) rather than the SSE sequence; with several servers, the stream's response.failed output 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_tools filter that matches nothing is no longer an error

The gateway rejected an MCP server whose allowed_tools matched none of its tools with a 400 ("empty final allowed tool set", a rule from #138). The mcp-failures recording 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 a require_approval other 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 400 invalid_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 set require_approval) stays with the gateway executors.

Behavior change: replayed search history is checked the same way on every path

  • A store: false request that carries tool_search_call / tool_search_output items now runs the pending-call check a previous_response_id or conversation continuation runs. A duplicate client call_id or 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 of tool error: invalid tool config: …. A request without search items is unchanged. tests/tool_search_pairing_characterization_test.rs pins every case on both paths.
  • A hosted tool_search_call whose item id equals another call's call_id is rejected (duplicate tool_search_call call_id), since the model would otherwise see two calls with one id.
  • Compaction's token estimate counts a search output as the text the model reads.

Known gap, unchanged from main: replayed mcp_call and web_search_call items (#492)

A client that replays a hosted MCP or web-search response gets the same result as on main: sent inline with store: false, the mcp_call/web_search_call record reaches vLLM unchanged and vLLM rejects the request (500); sent by id, the stored record is left out of the model's input. Continuing with previous_response_id works. 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-search replay cassette 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_call or tool_search_output. The run also found that the lowered search call kept the public tsc_ item id, which OpenAI rejects for a function_call (and an fc_ id is tied to the call_id OpenAI 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

  • Wire details:
    • MCP members omit "strict": null, which cannot survive storage through the typed field. They keep "output_schema": null.
    • Function entries do not gain output_schema: null.
    • The tools echo keeps declaration order.
  • Errors: messages for some validation errors differ in wording, and those errors carry no param. The MCP listing failure matches the reference exactly, param included.

Implementation

  • Wire types:
    • ToolSearchExecution::Server.
    • call_id: Option<String> on search items, validated at deserialization by execution.
    • New OutputItem::ToolSearchOutput.
    • McpToolParam.server_description.
  • Tool catalog (tool/catalog.rs): declarations enter through ToolCatalog::build; every later definition (a client search output, a hosted search, response metadata restored after compaction) enters through ToolCatalog::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), and ToolCatalog::search is the hosted lookup. Tool search adds only its timing rule (PriorCalls: a load must not resolve a call the history made before it).
  • One tool-search kind: both modes register ToolType::ToolSearch; the declaration's execution decides the entry's ownership, and the gateway runs a hosted search with ToolSearchHandler as its GatewayExecutor. The telemetry value agentic.tool.type for an executed hosted search stays hosted_tool_search.
  • The registry owns the catalog for the response: preparation builds the catalog, so an invalid history is a 400 before streaming, and the response's ToolRegistry takes 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, and load_searched_tools loads a search's results and regenerates the offered tools.
  • A planned search: the hosted search runs once, when the call is planned: GatewayToolEventPlan carries a typed PlannedResult::SearchPair, which the gateway records without a permit, timeout or execution. Its follow-up tool_search_output takes the next public output index.
  • MCP: deferred MCP servers expose only loaded tools upstream (loaded_tool_names). New ExecutorError::McpListToolsFailed: AgentTurn::new raises 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.
  • Persistence: the storage writers skip an output whose id is already in the turn's history, so hosted items are stored once.

Design after review

  • One projection: SearchHistory (types/io/input/search_history.rs) pairs search items (a client item by its call_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 typed SearchHistoryDefect verdicts, and ToolCatalog::load_history walks the history once, so a history with several defects gets the answer of the earliest one.
  • One owner per rule:
    • The pending-call ledger owns client call/output pairing on every path.
    • The catalog owns the model-visible name rule (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_collisions is removed.
    • McpHandler::validate owns the checks one MCP declaration can answer alone; the gateway executors own the one that needs their configuration.
  • No model-input hooks: GatewayExecutor, the ownership wrappers and GatewayBinding build no model input; tool/ownership.rs is identical to main.
  • Naming context for summaries: HistoryNaming carries the source request's searched top-level functions into a compaction summary, which declares no tools. Nothing in it is callable.
  • ensure_request_prepared is keyed on declarations, so a tool-less summary may carry public search items.
  • Module layout: the hosted-search code sits in its own modules so every production file stays within the file-size limits: tool/catalog.rs and tool/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, and types/tools/tool_search.rs. tool_search.rs shrinks below its recorded baseline, so .rust-file-sizes.json lowers 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: paths is required and query is optional. Early gateway recordings showed Qwen putting the user's question in query, which matches no tool. The description now says that query only narrows by tool name or description and should usually be omitted. Qwen still sometimes guesses a query; the recordings keep that behavior. A search that loads nothing tells the model why (query filters 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

  • Converting replayed gateway-executed call items (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.
  • Deferred custom tools are still rejected.
  • Searches run by an upstream itself (review comment 1): the gateway never declares tool_search upstream, and an upstream-run call (call_id: null) is ignored when streaming and rejected (502) otherwise. Proposed as a follow-up.
  • Reasoning order on resume: when the model reasons before a gateway-run call, a continuation of a first-turn or conversation response puts the call ahead of that reasoning. This affects every gateway tool and already happens on main; follow-up issue.
  • Continuing after an OpenAI upstream answer: the gateway's check against replaying encrypted reasoning (written for vLLM) refuses it. Already on main.

Test Plan

  • cargo test --workspace at 29a7f0a (this branch merged with main through fix: propagate trace context and baggage to MCP servers #473): 2891 passed, 0 failed. cargo clippy --all-targets -- -D warnings, cargo fmt -- --check and the Rust file-size check are clean; pre-commit passes on the changed files.
  • Each review commit was also checked on its own: 4bd143d alone (2895 passed, before the removal's tests left) and 5276ac5 (2882 passed).
  • Characterization first (d0359aa), before any production change: tool_search_pairing_characterization_test (every malformed search history on the direct and previous_response_id paths) and hosted_tool_search_projection_test (live, continuation and store: false replay 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 the mcp-failures 424 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 zero tools/call, MCP listing failures, empty allowed_tools, max_tool_calls, parallel_tool_calls, validation, streaming order, continuations, store: false replay, operator defaults, multi-agent, and compaction.
  • unsupported_mcp_options_reject_before_the_stream (HTTP): connector_id and require_approval: "always" get 400 invalid_request_error for JSON and SSE, and the upstream receives no request. the_registry_applies_the_catalog_name_rule_before_discovery pins that a registry built directly reports the name collision before any MCP check.
  • Unit tests: the catalog (build, load, search, names), the walker's pairing and lowering, a planned call taking no permit, and the token estimate. The hosted-id collision is a case in the pairing characterization test.
  • Mutation checks (earlier rounds): each new rule was broken on purpose, and a test failed every time.
  • Independent end-to-end run against Qwen/Qwen3.6-35B-A3B-FP8 on vLLM and a mock suite at 4608829, base build vs this branch: no regressions; the intended changes show.
  • End-to-end against the built gateway for the latest review changes: MCP option errors are 400 for JSON and streaming; a namespace collision is a JSON 400 and an in-stream error when streaming, as on main.
  • End-to-end hosted search and replay against live vLLM for the latest review changes: pending, the vLLM upstream was unreachable.
  • Gateway → OpenAI (gpt-5.6) recording of the contract scenarios through a logging proxy: all 24 upstream requests succeed after 4608829 (8 of 17 failed before).
  • Existing client tool-search suites pass; their assertions follow the new ownership (client linkage errors come from the pending-call check; the prepared request keeps public search items).

…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]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 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 ⚠️ Failed 2026-10-22T03:12:59.673526Z
We couldn’t complete this review. Comment @codex review to try again.
34bcb7f 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.

@haoshan98

haoshan98 commented Oct 22, 2026 •

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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".

Signed-off-by: haoshan98 <[email protected]>

# Conflicts:
#	crates/agentic-server-core/src/types/io/input.rs
@haoshan98

Copy link
Copy Markdown
Collaborator Author

@codex review again

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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".

@tjtanaa tjtanaa left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Comment on lines +218 to +222
if let OutputItem::FunctionCall(call) = item
&& call.namespace.is_none()
&& self.self_namespaced_functions.contains(&call.name)
{
call.namespace = Some(call.name.clone());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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]>
@haoshan98
haoshan98 requested a review from tjtanaa October 22, 2026 08:12
item: ToolSearchCall::try_from(payload).ok()?,
},
// Only the gateway produces search outputs; an upstream never streams one.
SSEItemType::ToolSearchOutput => return None,

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.

still need to add try_from pattern for this. upstream is not limited to vLLM only. other upstream might still emit ToolSearchOuput

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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_search to the upstream: every declaration, including tool_search, is lowered to a function (ToolDeclaration::to_function_tools in to_upstream_request), so no upstream is asked to run a search.
  • An upstream that searched anyway would emit a tool_search_call with call_id: null. Today streaming ignores that call leniently (and marks completion uncertain), and the blocking path rejects it (native_call_id requires 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(

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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, and project_for_model calls it. tool_search/history.rs no 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 a previous_response_id continuation. The old SearchPairing validator in tool_search/history.rs is gone; pairing is now a per-item result of the walker in types/io/input/search_history.rs.
  • tests/tool_search_pairing_characterization_test.rs pins 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());

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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(

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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(

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.

why this function model_input and history_inputs keep on repeating everywhere. seems complicated and not maintainable.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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(

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.

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):

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in c1c165e on top of 6332a9f:

  • The hosted search runs once, when the call is planned, and returns a typed PlannedResult::SearchPair (completed public tool_search_call + tool_search_output). The gateway records it without a permit, timeout or execution, emits the follow-up tool_search_output from it, and keeps its output bounded and budgeted.
  • The canonical public pair is what's recorded; SearchHistory in types/io/input lowers it for the model, the same for the live round, a previous_response_id continuation and a store: false replay (tests/hosted_tool_search_projection_test.rs checks 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_search call, and the function calls replayed for mcp_call/web_search_call, without an item id: recording through the gateway against OpenAI showed it rejects a function_call id that doesn't start with fc_ and ties an fc_ id to the call_id it issued, so the call is identified by its call_id alone.

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 tjtanaa left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Re-reviewed the updated source and regression tests. One additional namespace-identity issue remains below; this is source-traced, not an executed reproduction.

Comment on lines +375 to +376
} else if names_itself(call) {
call.namespace = None;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[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.

@haoshan98 haoshan98 Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 tjtanaa left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Comment on lines +375 to +376
functions.extend(declarations.iter().flatten().filter_map(ToolDeclaration::function_name));
let input = lower_async_calls(CodexNamespaceHandler.resolve_input(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[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.
@maralbahari

Copy link
Copy Markdown
Collaborator

@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 inventory

Inline location: tool/tool_search.rs:677

Could we simplify this around one request-scoped ToolRegistry? ToolSearchState currently retains public and private tool lists, definition records and indexes, withheld names, MCP loads, and loaded keys; after that, registry construction creates another set of entries and hosted_catalog() builds a third searchable index. The resulting flow is hard to follow when a search loads a tool mid-response.

I suggest building the registry once from the full rehydrated public declarations, then adding discovered MCP members and applying completed tool_search_output.tools in history order. Each entry should retain its typed definition and per-entry deferred/loaded state, including individual namespace members. From that inventory, derive (a) the tools offered to the model, (b) the tools callable by the gateway or client, and (c) hosted paths/query results; dispatch must reject unloaded entries. Client outputs may introduce previously undeclared tools, so applying an output must also support validated insertion. Keep only the public effective declarations and loaded-definition snapshot needed for persistence; avoid a second live catalog in ToolSearchState.

This removes HostedCatalog and HostedCatalogEntry rather than recreating them beside the registry. The search lookup and typed call/output construction can use existing registry, tool-handler, and I/O modules, allowing tool/tool_search/hosted.rs to be removed. Please preserve the current client versus hosted event timing and replay behavior while consolidating the ownership.

2. Use one tool-search type and handler

Inline location: tool/registry.rs:40

Please remove the internal ToolType::HostedToolSearch and use ToolType::ToolSearch for both execution: "client" and execution: "server". The declaration's execution mode should select the registry entry's client or gateway ownership; tool kind and execution location are separate facts. HostedToolSearchExecutor currently repeats ToolSearchHandler validation and normalization, while ToolType::is_gateway_owned() requires a second kind to express different ownership. Please use the existing ToolSearchHandler for both modes and route from ToolEntry.ownership after the declaration is known. The gateway can still emit the hosted tool_search_call and tool_search_output pair through its existing typed lifecycle path.

3. Centralize tool validation and definition indexing

Inline location: tool/tool_search/definitions.rs:42

Tool identity and collision checks are now split across ToolDeclaration::validate() for one declaration, CodexNamespaceHandler::validate_namespace_collisions() for flattened namespace names, registry insertion for routing-key collisions, and this separate definition index for names and schemas. I do not think the namespace-specific validator should become the design to reuse. Could the tool layer offer one collection-level validation/index-building operation over ToolDeclarations (for example ToolDeclaration::validate_catalog(&[ToolDeclaration]) or the registry builder) that validates all model-visible names, namespace members, and typed definitions together? If DefinitionRecord and DefinitionAccumulator are useful, make them general tool/ inventory-building types rather than tool_search-specific parallel state, and remove the superseded namespace-only validation pass. Initial declarations, discovered MCP tools, dynamically returned client definitions, hosted results, and restored definitions should all enter through that operation.

Tool search would then add only the timing rules: a completed tool_search_output activates its definitions, a call cannot use a deferred definition before loading, and reusing an identity with a different schema must fail. Two individually valid weather definitions can still conflict across outputs, so that comparison must remain; it should use the shared definition index. With that ownership, tool_search/definitions.rs no longer needs to be a separate catalog implementation.

4. Give pairing and replay one validation path

Inline location: tool/tool_search/history.rs:31

The latest revision correctly moved model-facing search conversion into types/io/input/search_history.rs. Could replay now consume one validated sequence of search pairs instead of scanning the same input again for item IDs, hosted IDs, completed outputs, and availability? executor/pending_calls.rs already checks client call/output IDs, and SearchHistory already pairs hosted items for projection. Make pairing/ID validation authoritative in those existing paths, then have the registry apply each completed output in order. This keeps the history rule needed for calls before load without another tool-search-specific pairing ledger or tool_search/history.rs module.

5. Keep MCP naming context out of request input

Inline location: executor/engine.rs:144

mcp_list_tools records gateway-side MCP discovery in the public response; it is not a call made by the model and has no corresponding model-facing call/output pair. The OpenAI first-turn capture emits the listing before the hosted tool_search_call, while this gateway's InputItem::is_model_visible() correctly removes McpListTools from upstream input. The model receives callable tool definitions through the upstream tools list when they become available, not the discovery listing as a conversation item. I understand why the current listing is useful for naming replayed mcp_call items during a summary request that offers no tools. Could the registry pass that discovery-assigned name mapping to the shared types/io projection instead of appending a fresh McpListTools item to enriched_request.input solely for conversion? Keep actual listings as public output/history records when emitted; do not synthesize an input item to carry gateway naming state into compaction.

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());

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.

why is this configuration before the exec_ctx.gateway_executors.validate_declaration()?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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> {

@maralbahari maralbahari Oct 27, 2026 •

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.

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.

@haoshan98 haoshan98 Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 4bd143dc:

  • McpHandler::validate now holds the checks one declaration can answer alone: connector_id is unsupported, and require_approval must 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 by unsupported_mcp_options_reject_before_the_stream). Discovery calls the same validate for callers that build a registry directly. Only the rule that needs the gateway's configuration (a server the gateway does not configure must set require_approval) stays in GatewayExecutors. 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

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 maralbahari 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.

@haoshan98 Thanks for the work!

@haoshan98
haoshan98 merged commit 63a5210 into vllm-project:main Oct 30, 2026
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support gateway-executed (hosted) tool_search over deferred functions, namespaces, and MCP servers

3 participants