Skip to content

fix: revisit MCP support, remove MCP resources, support only discover and execute native tools [1/2] - #138

Merged
franciscojavierarceo merged 12 commits into
vllm-project:mainfrom
EmbeddedLLM:fix-mcp-tool-call-1
Jul 29, 2026
Merged

franciscojavierarceo merged 12 commits into
vllm-project:mainfrom
EmbeddedLLM:fix-mcp-tool-call-1

Conversation

@maralbahari

@maralbahari maralbahari commented Jul 21, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

This PR revisits the gateway's MCP support following a comparison with the OpenAI Responses MCP contract.

The previous implementation was largely based on Codex behavior. Codex maintains its own MCP client lifecycle and supports application-controlled MCP resources through client-side operations such as read_mcp_resource. That behavior does not map directly to the gateway's OpenAI-compatible type: "mcp" contract.

For simplicity and a clearer responsibility boundary, the gateway will not support MCP resources for now. Resource discovery, selection, and reading should remain client-controlled behavior in applications such as Codex and Claude Code. Resource support can be revisited later as a separate host-facing context design.

The updated architecture is documented in docs/design/mcp-gateway-integration.md.

This PR:

  • Removes the synthetic read_mcp_resource function bridge and resources/read execution.
  • Removes the Codex-specific MCP resource metadata conversion.
  • Removes the obsolete MCP resource tests, cassettes, fixture, and recorder script.
  • Treats a client-declared function named read_mcp_resource as an ordinary client-executed function.
  • Accepts OpenAI-style type: "mcp" declarations using server_label and connection information without a client-supplied tool name.
  • Connects to request-declared MCP servers and discovers their tools through tools/list.
  • Applies allowed_tools filtering to discovered tools.
  • Normalizes discovered MCP tools into model-visible function tools.
  • Stores discovered tools and their handlers in the request-scoped ToolRegistry.
  • Caches discovered handlers by server_label.
  • Executes model-selected MCP tools through tools/call.
  • Preserves the original MCP server and tool identity during internal execution.
  • Rejects duplicate MCP server labels and empty discovered tool sets.
  • Supports request headers and bearer authorization for remote MCP servers.

This PR intentionally retains the existing mcp_tool_call public output item and streaming lifecycle. A follow-up PR will align public output items and SSE events with OpenAI's mcp_call contract.

Important Note:

MCP name collision handling: MCP declarations no longer expose the non-standard mcp.name field. MCP internal names are derived only after tool discovery, so Codex namespace resolution does not inspect MCP names. During registry construction, discovered MCP entries are checked against all registered tools, rejecting collisions across MCP servers and with existing tool entries regardless of declaration order.

Test Plan

  • cargo check --workspace
  • cargo test --workspace
  • cargo clippy --all-targets -- -D warnings
  • cargo fmt -- --check

@maralbahari maralbahari changed the title fix: revisit MCP support, remove MCP resources, support only discover and execute native tools fix: revisit MCP support, remove MCP resources, support only discover and execute native tools [1/2] Jul 21, 2026

@ashwing ashwing left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Went through this end-to-end against the OpenAI type:mcp contract and our Messages side. Direction is right — rebasing on server_label + tools/list + allowed_tools + tools/call and dropping the synthetic read_mcp_resource bridge is the correct contract, and the executor came out protocol-neutral (our Messages stream loop already consumes ToolRegistry::dispatch). A few things worth resolving before merge; details inline plus one below.

Output item type vs the design doc (output.rs is outside this diff so noting here): the code emits type: "mcp_tool_call" (fields server/tool/result), but the design doc specifies OpenAI's mcp_call (server_label/name/output) and states "The current gateway work implements the mcp_call lifecycle" (mcp-gateway-integration.md:59) — which doesn't match what ships. Either reconcile the doc to call mcp_tool_call the interim shape pending #139, or land the mcp_call rename here. With no external consumers yet, renaming now avoids shipping a non-conformant item type that clients parse and then breaks under them in #139.

@maralbahari

maralbahari commented Jul 22, 2026 •

Copy link
Copy Markdown
Collaborator Author

Output item type vs the design doc (output.rs is outside this diff so noting here): the code emits type: "mcp_tool_call" (fields server/tool/result), but the design doc specifies OpenAI's mcp_call (server_label/name/output) and states "The current gateway work implements the mcp_call lifecycle" (mcp-gateway-integration.md:59) — which doesn't match what ships. Either reconcile the doc to call mcp_tool_call the interim shape pending #139, or land the mcp_call rename here. With no external consumers yet, renaming now avoids shipping a non-conformant item type that clients parse and then breaks under them in #139.

@ashwing I would still prefer to keep the mcp_call emitting into #139 even renaming would be adding more file changes to this PR and makes it larger. the reason doc is changed to the whole overall picture of redesign that would be in #139 is to state the whole design for review to know what to expect while #138 is to just ease the shipment and PR review.

I will address your following comments in a bit and push commit. Thanks ashwin

@franciscojavierarceo franciscojavierarceo 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.

I found a few issues that look worth addressing before this lands, mostly around approval defaults, credential handling, request-scoped filtering, and preserving MCP discovery errors.

@ashwing ashwing left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

A few things from a fresh pass, beyond the inline notes:

SSRF via allowlisted hostnames (tool/mcp/pool.rs validate_request_server_url + tool/mcp/client.rs:283 pinned_http_client): the allowlist matches on the host string, but pinned_http_client then resolves the domain and pins whatever DNS returns without checking the resolved addresses aren't loopback-adjacent / RFC1918 / 169.254.169.254. The pinning stops rebinding between validate and connect, but an allowlisted name that resolves to an internal address still connects — the existing test only rejects the literal metadata IP, not a domain resolving to it. Since this is the trust boundary, worth rejecting resolved addresses in private/link-local ranges unless explicitly opted in.

#139 rename scope (types/io/output.rs McpToolCall): the item ships server/tool/result; OpenAI's mcp_call uses server_label/name/output. Flagging so #139 covers the field names too, not just the mcp_tool_call->mcp_call type tag — otherwise clients coding to the OpenAI schema still break after the rename.

Minor: the streaming-accumulator test fixture (executor/accumulator.rs:611-614) still emits tool:"read_mcp_resource" items — harmless test data, but it's the exact shape this PR removes, so worth updating so it doesn't imply the path survives.

Comment thread docs/design/mcp-gateway-integration.md Resolved
Comment thread docs/design/mcp-gateway-integration.md Resolved
@maralbahari

Copy link
Copy Markdown
Collaborator Author

A few things from a fresh pass, beyond the inline notes:

SSRF via allowlisted hostnames (tool/mcp/pool.rs validate_request_server_url + tool/mcp/client.rs:283 pinned_http_client): the allowlist matches on the host string, but pinned_http_client then resolves the domain and pins whatever DNS returns without checking the resolved addresses aren't loopback-adjacent / RFC1918 / 169.254.169.254. The pinning stops rebinding between validate and connect, but an allowlisted name that resolves to an internal address still connects — the existing test only rejects the literal metadata IP, not a domain resolving to it. Since this is the trust boundary, worth rejecting resolved addresses in private/link-local ranges unless explicitly opted in.

This was addressed during the initial MCP support work, with subsequent SSRF hardening adding an explicit hostname allowlist as the operator trust boundary by fransico; restricting resolved address ranges would be a separate policy change because private MCP servers may be intentional. This PR does not change that behavior from main

#139 rename scope (types/io/output.rs McpToolCall): the item ships server/tool/result; OpenAI's mcp_call uses server_label/name/output. Flagging so #139 covers the field names too, not just the mcp_tool_call->mcp_call type tag — otherwise clients coding to the OpenAI schema still break after the rename.

If is start touching renaming McptToolCall in this PR there will be many more files being touched. please let's go by the logical split this PR mainly removes mcp resources and fixes some of the design to add in the tool discovery in tool/executors.rs and tool/registy. the design doc is changed to tell the reader what Is the final overall mcp design contract not tide to #138 PR. I will add a note to the bottom the new design planned to ship in sequential with explanation of how the logics are separated.

Minor: the streaming-accumulator test fixture (executor/accumulator.rs:611-614) still emits tool:"read_mcp_resource" items — harmless test data, but it's the exact shape this PR removes, so worth updating so it doesn't imply the path survives.

removed this and some other tests that were referring to read_mcp_resources.

@ashwing ashwing left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks — this all looks reasonable, approving.

  • SSRF: fair — it predates this PR and restricting resolved address ranges is a separate policy call (private MCP servers are a legitimate use). Agreed it's out of scope here.
  • Field rename / doc: makes sense to keep the mcp_call field+type rename in #139 and have the design doc describe the end-state contract with the sequential-PR note — reads clearly now.
  • require_approval: the scalar "never" path is the right v1, and #145 covers the object/approval-filtering form. One breadcrumb for #145: the object form currently fails McpToolParam deserialization and falls through the other -> Unknown arm, so the server is dropped silently rather than erroring — worth making that a clear "approval not yet supported" error there rather than a silent drop.
  • Fixture cleanup + tools/list error propagation look good.

LGTM.

@maralbahari

Copy link
Copy Markdown
Collaborator Author

@franciscojavierarceo addressed the comments. Could you please check again. thanks

@franciscojavierarceo franciscojavierarceo 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.

Thanks for the updates — the earlier points look addressed. I noticed a few follow-ups while checking the new version; leaving them inline.

// persistence mode builds and serializes effective tool metadata.
if let Some(tools) = ctx.enriched_request.tools.as_mut() {
for tool in tools {
tool.redact_runtime_credentials();

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.

I think this redaction can still be bypassed by the WebSocket generate: false path. That route forces store = true, then calls resp_handler.execute_turn() directly instead of going through persist_response(), so the MCP authorization and headers can still end up in effective_tools. Could we move the scrub down to where the response metadata is actually written and add a small WebSocket prewarm regression 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.

Fixed by moving credential redaction into TryFrom<&ResponseMetadata> for String, the shared storage serialization boundary used by all persistence paths. Added a WebSocket generate: false regression test confirming MCP headers and authorization are not stored.

@franciscojavierarceo franciscojavierarceo 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.

One more thing I noticed in the MCP call path:

));
};
let param = mcp_tool_param(&config)?;
let output = execute_tool_call(client, &param.server_label, &param.tool_name, &arguments).await?;

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.

Could we make the argument handling fail closed before calling the MCP server here? execute_tool_call() currently turns malformed JSON into None, which call_tool treats as a valid no-argument request. That means a tool with optional/default arguments could still run even though the model gave us invalid input. I think we should parse strictly, require an object, and return a ToolError without making the call if parsing fails.

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.

Added parse_tool_arguments(), which is called first in execute_tool_call() to strictly parse and validate an argument object before any MCP server call is made.

@franciscojavierarceo franciscojavierarceo 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.

And one small persistence cleanup:

// persistence mode builds and serializes effective tool metadata.
if let Some(tools) = ctx.enriched_request.tools.as_mut() {
for tool in tools {
tool.redact_runtime_credentials();

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.

Small follow-up: should we clear discovered_tools here too? Those server-provided schemas get persisted in effective_tools, but the field is skip_deserializing, so we throw them away when reading the record back. Stripping them here would avoid storing potentially large request-scoped data that we can't reuse.

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.

Renamed redact_runtime_credentials() to sanitize_for_persistence(), which clears both MCP credentials and discovered_tools; it is called when ResponseMetadata is serialized for storage.

@franciscojavierarceo
franciscojavierarceo merged commit fa1c901 into vllm-project:main Jul 29, 2026
4 checks passed
haoshan98 added a commit that referenced this pull request Oct 30, 2026
… and MCP servers (#472)

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

- [x] `cargo test --workspace` at 29a7f0a (this branch merged with
`main` through #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.
- [x] Each review commit was also checked on its own: 4bd143d alone
(2895 passed, before the removal's tests left) and 5276ac5 (2882
passed).
- [x] 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).
- [x] `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.
- [x] `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.
- [x] `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.
- [x] 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.
- [x] Mutation checks (earlier rounds): each new rule was broken on
purpose, and a test failed every time.
- [x] 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.
- [x] 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.
- [x] 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).
- [x] 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).

---------

Signed-off-by: haoshan98 <[email protected]>
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.

3 participants