Repository navigation
fix: reject unsupported background and prompt parameters in typed Responses execution - #456
Conversation
Signed-off-by: Zheng Lu <[email protected]>
Signed-off-by: Zheng Lu <[email protected]>
Signed-off-by: Zheng Lu <[email protected]>
…d parameters Signed-off-by: Zheng Lu <[email protected]>
…execution Signed-off-by: Zheng Lu <[email protected]>
Signed-off-by: Zheng Lu <[email protected]>
| pub context_management: Option<Vec<ContextManagement>>, | ||
| /// Detection only, never serialized: typed execution rejects `true` (background mode is #357). | ||
| #[serde(default, skip_serializing)] | ||
| pub background: Option<bool>, |
There was a problem hiding this comment.
RequestPayload<RawValue> is deserialized before HTTP route selection. Adding background: Option<bool> means an otherwise direct request with store: false and "background": 0, "false", or {} now fails locally instead of reaching the upstream unchanged.
I reproduced this using the actual routing type. This contradicts the PR’s documented policy that direct-route validation remains upstream-owned. The new routing test only covers boolean/null background values, so it misses this regression.
Please use a typed wire representation that preserves invalid value kinds through routing, then validate during executor admission. Add direct JSON/SSE regression tests covering non-boolean values.
There was a problem hiding this comment.
Fixed in a852678:
backgroundis now aBackgroundwire value that accepts any JSON kind, following themax_tool_callsprecedent. Routing never fails on it, and the direct route forwards the original body.- Executor admission validates it.
trueis stillunsupported_value. Any other non-boolean is nowinvalid_type, with themax_tool_callswording: "Invalid type for 'background': expected a boolean, but got a string instead."JsonKindgainsIntegerfor that message.
New regression test: test_non_boolean_background_is_forwarded_directly_and_rejected_by_typed_execution.
- It covers
0,"false",{},[]and0.5, for JSON and SSE. - On the direct route, each body is forwarded unchanged. On the typed route, each gets the exact
invalid_typeenvelope with no upstream call. - It failed before the fix: the direct request got a local
400.
I also added non-boolean values to the routing-parse unit test, the core admission tests (which also cover WebSocket and split execution) and the error-envelope test. The docs matrix now lists invalid_type.
Resolve the conflicts with vllm-project#436 by keeping both sides. Its prompt-cache options validation runs first in rehydrate_request, then the unsupported-parameter check. Signed-off-by: Zheng Lu <[email protected]>
The HTTP router parses each request before choosing a route. Typing
`background` as `Option<bool>` made a direct `store: false` request with
`"background": 0`, `"false"` or `{}` fail locally instead of reaching
the upstream unchanged, contrary to the documented policy that the
upstream decides on the direct route.
`background` is now a `Background` wire value that accepts any JSON
kind, following `max_tool_calls`. Executor admission rejects `true` as
`unsupported_value`, as before, and any other non-boolean as
`invalid_type` ("Invalid type for 'background': expected a boolean, but
got a string instead."). `JsonKind` gains `Integer` for that message.
Signed-off-by: Zheng Lu <[email protected]>
… 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]>
Summary
Part of #314. Typed Responses execution now rejects two request members it recognizes but can't honour. Before, it silently answered a different request than the client sent.
Before:
RequestPayloadhad nobackgroundorpromptfield, so serde dropped both. A request that selected typed execution (storage, a continuation, built-in tools, and so on) ran as a foreground, prompt-less response, with no error.After:
backgroundpromptnull, orfalseaccepted;true→400 unsupported_value,param: backgroundnullaccepted; any other value →400 unsupported_parameter,param: promptThe rejection happens before history lookup, tool discovery, storage, or inference. Background mode itself is #357.
Why the direct route is left alone. It follows the policy #436 documents for
prompt_cache_options, and the handler's existing rule that direct requests keep their raw body: on the direct route, the upstream decides. For vLLM (the contract at840c7c2f, the commit #436 cites), that means:background: trueis already rejected unlessstoreis true. The direct route only carriesstore: falserequests, so vLLM rejects every one of them.promptis accepted and echoed, but the serving path never reads it.The gap #314 targets, "required request semantics do not silently disappear when enabling storage or built-in tools", is the typed route. That is where this PR acts.
How it's built:
RequestPayloadgainsbackground: Option<bool>andprompt: Option<RejectedValue>. Both areskip_serializing, so they never reach storage, the split-execution context, or the upstream request the executor builds.RejectedValueaccepts any JSON value and keeps none of it, so the boundary stays typed, and the HTTP routing parse never fails on a value it must forward.UnsupportedParameterErrorprovidescode()andparam(). It converts intoExecutorError::UnsupportedParameterthrough#[from], mirroringMaxToolCallsErrorandInvalidMaxToolCalls. The existingUnsupportedValue { param, message }variant can't carryunsupported_parameter.ensure_supported_parameters()runs first inrehydrate_request. Every typed entry point reaches it: executor-routed HTTP, WebSocketresponse.create,rehydrate_conversation(llm-d and embedders), and sessions. The HTTP handler is unchanged.docs/api/index.mdgains the per-path matrix above. It also lists the unmodelled members typed execution still ignores (top_logprobs,user,safety_identifier,stream_options, and vLLM sampling extensions), which Report effective Responses parameters from upstream execution #434 tracks.Out of scope:
file_search. Its "accepted but not offered to the model" behaviour is documented inROADMAP.mdanddocs/design/codex-integration.md, andmax_tool_calls_testrelies on a request-declaredfile_search. Whether to reject it until a handler exists is a separate decision.Overlap with #436
I checked against #436 at
3e601ca:executor/error.rs,executor/rehydrate.rs,executor/telemetry.rs,types/request_response.rs). Each is two adjacent additions: a newExecutorErrorvariant, a new first line inrehydrate_request, or a new child module and its re-export. Keep both.ensure_supported_parametersis implemented on the typedRequestPayload, which keeps feat: preserve prompt_cache_options across Responses execution #436's new default type parameter.request_responseunit tests, the core admission tests,responses_test,responses_websocket_test,compaction_test,openapi_test, and llm-dhttp_contract.types/request_response.rsat 474 lines after feat: preserve prompt_cache_options across Responses execution #436's text-config split.Test Plan
New tests:
types/request_response/unsupported.rs(unit):null, andfalseare accepted;background: trueis rejected;background: "yes"is a parse error;promptshapes are rejected;backgroundis checked beforeprompt;executor/error.rs:unsupported_parameters_match_openai_error_envelopeschecks both exact envelopes.agentic-server-core/tests/unsupported_parameters_test.rs:rehydrate_conversationrejects them.responses_test::test_unsupported_parameters_are_rejected_by_typed_execution_and_passed_through_directly:store: truewith JSON,store: truewith SSE, andstore: falsewith a missingprevious_response_id), return exact envelopes with zero upstream calls. The last case returns400 unsupported_*, not404, so the check runs before history lookup.responses_websocket_test::websocket_rejects_unsupported_parameters_and_keeps_the_connection: checks the exact error frames, then a validresponse.createon the same socket completes.agentic-llm-dhttp_contract::hydrate_rejects_unsupported_parameters_with_a_standard_envelope.Evidence:
400instead of forwarding).rehydrate_requestfails all five rejection tests (core execution, core rehydration, HTTP, WebSocket, llm-d). The explicit-defaults test still passes.response.createframes. None sendsbackgroundorprompt, so recorded Codex, Claude Code, and SDK flows are unaffected.Gate:
cargo fmt -- --checkcargo clippy --workspace --all-targets -- -D warnings--features embedded-code-interpreter) foragentic-server-coreandagentic-serverpre-commit run --all-filesmkdocs build --strictcargo test --workspace --no-fail-fast: 2521 passed, 1 failed. The failure istool::web_fetch::http::tests::the_deadline_bounds_a_slow_origin, a wall-clock bound that also fails on unmodifiedmainwhen the whole lib suite runs in parallel. It passes in isolation.