Repository navigation
feat: support mcp_list_tools - #172
Merged
franciscojavierarceo merged 31 commits intoAug 14, 2026
Merged
Conversation
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
…-header Signed-off-by: maral <[email protected]>
…to mcp-tool-list Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
Signed-off-by: maral <[email protected]>
maralbahari
marked this pull request as ready for review
August 13, 2026 08:30
maralbahari
requested review from
bbrowning,
franciscojavierarceo,
jiahuei,
leseb,
noobHappylife,
qandrew and
tjtanaa
as code owners
August 13, 2026 08:30
Signed-off-by: maral <[email protected]>
franciscojavierarceo
approved these changes
Aug 14, 2026
12 of 13 tasks
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Expose MCP tool discovery through the Responses API using OpenAI-compatible
mcp_list_toolsoutput items and streaming lifecycle events.The gateway previously discovered remote MCP tools internally but did not include the discovery lifecycle in the public response.
Changes
mcp_list_toolsas a first-class response output item.McpClient::list_tools()during MCP handler initialization to discover tools from the remote server.read_onlyannotationallowed_toolsfiltering to the discovered tool set.mcp_list_toolsitem in streaming and non-streaming response output.response.output_item.addedresponse.mcp_list_tools.in_progressresponse.mcp_list_tools.completedresponse.output_item.donemcpl_item ID and output index throughout the lifecycle.response.mcp_list_tools.failed.ResponseAccumulatorto reconstructmcp_list_toolsitems from upstream streaming events.mcp_list_toolsas public response metadata rather than an executable tool call or client-action item.Testing
mcp_list_toolsoutput items.output_item.addedandoutput_item.done.