Skip to content

refactor: neutral tool declarations, shared domain policy, explicit tool output status - #417

Merged
haoshan98 merged 10 commits into
vllm-project:mainfrom
StevenWang-CY:refactor-shared-tool-declaration
Oct 6, 2026
Merged

haoshan98 merged 10 commits into
vllm-project:mainfrom
StevenWang-CY:refactor-shared-tool-declaration

Conversation

@StevenWang-CY

@StevenWang-CY StevenWang-CY commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #416, the three refactors deferred from #414. The PR is behaviour-preserving: no request or response wire shape changes for either API, and every recorded cassette replays unchanged.

Explicit tool output status. ToolOutput gains a status (ToolOutputStatus::Success or Failure), set by the handler that produced the output and carried unchanged through ToolRegistry::dispatch. A web_fetch refusal is a failure output, a rendered page a success, and the gateway's execution-error output a failure. The Messages loop sets tool_result.is_error from the status instead of parsing the output's type field, so the decision no longer depends on one tool's output layout; web_fetch::is_failure_output is gone. Constructors (ToolOutput::success / failure) replace the struct literals.

One domain policy for both web tools. tool/domain_policy.rs owns what web_search and web_fetch do with a declaration's domain lists: the host-name rule for a declared entry (validate_domain_entry, validate_domain_filters) and the DomainFilter that admits a URL by host, including the fail-closed behaviour for an allowlist whose entries normalize to nothing. Web search keeps result retention as a thin call on top (retain_allowed_results); web fetch imports nothing from web search. The parameter contract is one neutral type, DomainFilters in types/tools/domain.rs (formerly WebSearchFilters, the same two fields), shared by WebSearchToolParam and WebFetchToolParam; the Responses web_search filters wire shape is unchanged, and the OpenAPI component carries the new name. web_search declarations keep their current validation (non-empty entries): Anthropic's web search contract accepts subpath entries, which the host-only rule would refuse, so aligning the two tools' entry rules is a matcher decision for its own change.

One concrete tool declaration, converted at each API's boundary. tool/declaration.rs introduces ToolDeclaration, the one internal declaration type the tool layer works on. Each API converts its wire tools into it at its adapter boundary: responses_declarations (and From<ResponsesTool>) for the Responses wire enum, exposed as RequestPayload::tool_declarations, and tool::registry_tools for the Messages ToolParam blocks. ToolRegistry::build_with_handlers and the registry's helpers (namespace resolution, MCP server labels and counts, code-interpreter and custom-tool declaration checks, executor availability) take ToolDeclaration directly, and validate, tool_type, and to_function_tools are implemented once on it in tool/normalize.rs, still through ToolHandler for validation and normalization, GatewayExecutor for execution, and GatewayBinding for pairing executors with their typed parameters. What MCP discovery records on a declaration is propagated back into the Responses request's wire tools explicitly, by record_discovered_mcp_tools after the registry is built, so the discovered tools go upstream and are stored with the request without a mutation capability on every declared tool. ResponsesTool is a wire type again: the #[serde(skip)] WebFetch variant, its arms in every exhaustive match over the wire enum, and the declaration methods on the enum are gone, and the Messages declaration mapping moved from types/messages/tool_seam.rs into the tool layer (tool::registry_tools), keeping types::messages to protocol shapes and the gateway-ownership map.

ARCHITECTURE.md describes the new boundary (declaration.rs and the two adapter conversions, the build_with_handlers signature, and the shared domain policy), and the CHANGELOG notes the crate-level changes under Unreleased.

Test Plan

  • Status: unit tests for the ToolOutput constructors, for the outcome-to-output mapping in web_fetch/output.rs (a page is a success, a refusal a failure), for the gateway's execution-error output carrying the failure status, and for status propagation through ToolRegistry::dispatch with a handler that answers a failure. The existing Messages tests still see is_error: true for a refused fetch over JSON and SSE, and the recorded web_fetch cassettes replay unchanged.
  • Domain policy: the matcher's tests move with it (label-boundary matching, exclusion after inclusion, fail-closed on unparsable URLs, IDNA normalization, an allowlist that names no domain), plus new tests for validate_domain_filters (mutual exclusion, host-name entries, the error wording per tool and field) and DomainFilter::from_filters; result retention keeps its test in web search; the Brave and Tavily provider tests and the HTTP-level web_fetch tests (allowed_domains: ["."] rejected with 400 on both endpoints) are unchanged.
  • Declarations: tests for the Messages mapping (gateway and client kinds, operator aliases, a native web_search with its settings, a native web_fetch with its settings, a plain function named web_fetch, an unreadable web_fetch declaration dropped rather than weakened), for the wire-to-declaration conversion agreeing by reference and by value on every declaration kind with Unknown becoming Unsupported, for discovered MCP tools recorded back into the Responses request's declarations, and for a web_fetch declaration validating and normalizing through its handler. The registry, Codex namespace, custom-tool, MCP, tool-search, and cassette suites run unchanged on the concrete type.
  • cargo fmt -- --check, cargo clippy --all-targets -- -D warnings, cargo test --no-fail-fast across the workspace, and pre-commit run --all-files (including rust-file-sizes with RUST_FILE_SIZE_BASE=origin/main) pass on the exact commit from a clean worktree.

`ToolOutput` gains an explicit `status` (`ToolOutputStatus::Success` or
`Failure`), set by the handler that produced the output and carried
unchanged through `ToolRegistry::dispatch`. A `web_fetch` refusal is a
failure output; a rendered page, and every other handler's answer, a
success. The gateway's execution-error output is a failure as well.

The Messages loop sets `tool_result.is_error` from the status instead of
parsing the output's `type` field, so the decision no longer depends on
one tool's output layout; `web_fetch::is_failure_output` is removed.
Constructors (`ToolOutput::success` / `failure`) replace the struct
literals.

Tests: the output constructors, the outcome-to-output mapping in
`web_fetch/output.rs`, and status propagation through `dispatch`.
Existing Messages tests still see `is_error: true` for a refused fetch over
JSON and SSE.

Part of vllm-project#416.

Signed-off-by: Chuyue Wang <[email protected]>
`tool/domain_policy.rs` now owns what `web_search` and `web_fetch` both do
with a declaration's domain lists: the host-name rule for a declared entry
(`validate_domain_entry`, `validate_domain_filters`) and the `DomainFilter`
that admits a URL by host, including the fail-closed behaviour for an
allowlist whose entries normalize to nothing. Web search keeps result
retention as a thin call on top (`retain_allowed_results`); web fetch no
longer imports anything from `web_search`.

The parameter contract uses one neutral type, `DomainFilters`, in
`types/tools/domain.rs` (formerly `WebSearchFilters`, the same two fields):
`WebSearchToolParam.filters` and `WebFetchToolParam.filters` share it, the
request wire shape is unchanged, and the OpenAPI component carries the
new name.

`web_search` declarations keep their current validation (non-empty
entries): Anthropic's web search contract accepts subpath entries, which
the host-only rule would refuse.

Tests move with the code; `validate_domain_filters` and
`DomainFilter::from_filters` gain their own.

Part of vllm-project#416.

Signed-off-by: Chuyue Wang <[email protected]>
`tool/declaration.rs` introduces `ToolDeclaration` (owned; what the
Messages mapping produces), the borrowed `ToolDeclarationRef` view, and
the `DeclaredTool` trait that both it and the wire `ResponsesTool`
implement. `ToolRegistry::build_with_handlers` and the registry's helpers
(namespace resolution, MCP server labels and counts, code-interpreter and
custom-tool declaration checks, executor availability) are generic over
that view: the Responses path passes its `ResponsesTool`s unchanged, with
discovered MCP tools recorded into them as before, and the Messages path
passes the declarations `tool::registry_tools` builds. One registry-
building path serves both APIs with no copy and no write-back.

`validate`, `tool_type`, and `to_function_tools` are implemented once on
the view (`tool/normalize.rs`) and reached from both types;
`RequestPayload::to_upstream_request` validates and normalizes the
resolved declarations.

`ResponsesTool` is a wire type again: the `#[serde(skip)] WebFetch`
variant and its arms in every exhaustive match over the wire enum are
gone, and the Messages declaration mapping moved from
`types/messages/tool_seam.rs` into the tool layer (`tool::registry_tools`),
so `types::messages` keeps protocol shapes and the gateway-ownership map.
The file-size exception for `types/tools/params.rs` returns to its
pre-vllm-project#414 entry.

Tests: the Messages mapping (gateway and client kinds, aliases, native
web_search and web_fetch settings, a plain function named web_fetch, an
unreadable declaration dropped), the wire-to-declaration conversion
yielding the same view, discovered MCP tools recorded on both kinds, and
a web_fetch declaration validating and normalizing through its handler;
the registry, namespace, custom, MCP, tool-search, and cassette suites run
unchanged on the generic path.

Closes vllm-project#416.

Signed-off-by: Chuyue Wang <[email protected]>
The Responses gateway answers a failed call with its own error output; a
unit test now asserts that output carries the failure status, so the
status is the signal rather than the text's shape.

Part of vllm-project#416.

Signed-off-by: Chuyue Wang <[email protected]>
`ToolOutputStatus` is re-exported beside `ToolOutput`, loses the `Default`
nothing read, and the constructors are `#[must_use]`. The Messages
adapter's domain-list check is named for the shape it validates, and both
it and the domain policy report the exclusive-lists rule from one
constant. The module and CHANGELOG wording says which tool validates its
entries as host names, the `ToolDeclaration` docs describe the path each
API takes, the wire-conversion test covers every declaration kind, and the
`params.rs` size exception is the file's count.

Part of vllm-project#416.

Signed-off-by: Chuyue Wang <[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.

Thanks for working through the follow-up points. We do want Messages and Responses to have separate API boundaries while sharing the internal tool implementation, so each API can evolve independently.

My concern is the additional abstraction around that separation: ToolDeclarationRef, the DeclaredTool trait, and generic bounds across several tool APIs.

Could we simplify this around one concrete internal ToolDeclaration and reuse the existing behavior interfaces?

  • Keep ResponsesTool and the Messages tool types as their respective wire models.
  • Convert each API’s declarations into ToolDeclaration at its adapter boundary, reusing the existing typed parameter structs.
  • Have the registry and declaration helpers accept that concrete internal type directly.
  • Continue using ToolHandler for validation and normalization, GatewayExecutor for execution, and GatewayBinding for pairing executors with their typed parameters.
  • Preserve MCP discovery updates through explicit propagation back to the Responses request where needed for persistence, rather than putting that mutation capability on every declared tool.

Some declaration-consuming signatures will necessarily change, but this would preserve the separation we requested while keeping one internal representation and reusing the current interfaces. I’d prefer starting with this simpler approach and introducing borrowed views only where a demonstrated need justifies the additional complexity.

The registry and the declaration helpers accept `ToolDeclaration`
directly. Each API converts its wire tools at its adapter boundary:
`responses_declarations` (and `From<&ResponsesTool>`) for the Responses
enum, exposed as `RequestPayload::tool_declarations`, and
`registry_tools` for the Messages blocks. What MCP discovery records on
a declaration is written back into the Responses request's wire tools
by `record_discovered_mcp_tools` after the registry is built, so the
discovered tools go upstream and are stored without a mutation
capability on every declared tool. `ToolDeclarationRef`, `DeclaredTool`,
the generic bounds, and the declaration methods on `ResponsesTool` are
gone; the tool-search checks that are Responses-only read the wire enum
again.

Part of vllm-project#416.

Signed-off-by: Chuyue Wang <[email protected]>
The Responses executor builds the registry from converted declarations
and writes what discovery found back into the request's own `mcp`
declaration; a test now asserts that the discovered tool reaches the
wire declaration the upstream request and storage read.

Part of vllm-project#416.

Signed-off-by: Chuyue Wang <[email protected]>
@StevenWang-CY

Copy link
Copy Markdown
Contributor Author

Thanks for the review. The branch now follows the simpler shape you described, in one commit on top of the earlier ones:

  • ToolDeclaration is the single internal declaration type. ToolDeclarationRef, the DeclaredTool trait, and the generic bounds are gone; ToolRegistry::build_with_handlers and every declaration helper (namespace resolution, MCP server labels and counts, code-interpreter and custom-tool checks, executor availability, tool-search validation) take ToolDeclaration directly.
  • Each API converts at its adapter boundary, reusing the existing typed parameter structs: responses_declarations (and From<&ResponsesTool> / From<ResponsesTool>) for the Responses wire enum, exposed as RequestPayload::tool_declarations, and registry_tools for the Messages blocks. ResponsesTool and the Messages tool types stay pure wire models; the declaration methods on ResponsesTool are removed.
  • validate, tool_type, and to_function_tools live once on ToolDeclaration and still go through ToolHandler; execution stays on GatewayExecutor and GatewayBinding.
  • MCP discovery is propagated explicitly: the Responses executor converts the request's tools, builds the registry from the declarations, then record_discovered_mcp_tools writes the discovered tools back into the request's mcp wire declarations for upstream use and persistence. No declared tool carries a mutation capability.
  • The Responses-only tool-search checks (tool_has_deferred_definition, has_reserved_tool_search_name) read the wire enum again.

The rework commit touches 25 files (+481/−518), and a follow-up test commit pins at the executor level that the registry build records the discovered MCP tools into the request's mcp declaration; ARCHITECTURE.md, the CHANGELOG entry, and the PR description are updated to match. Clean-worktree pre-commit, cargo fmt --check, cargo clippy --all-targets -- -D warnings, and the full test suite pass on the exact head.

@haoshan98
haoshan98 merged commit 5b3e556 into vllm-project:main Oct 6, 2026
20 checks passed
maralbahari added a commit that referenced this pull request Oct 20, 2026
## Summary

Adds Serply as a fourth selectable `web_search` provider beside You.com,
Brave Search and Tavily, following the shape of the Tavily provider
(#329). Closes #381.

- `WebSearchProviderKind::Serply` (`serply`), key from `SERPLY_API_KEY`,
base URL `https://api.serply.io`, no provider-imposed concurrency
ceiling (per-request metering, like Tavily).
- `tool/web_search/serply.rs` calls `GET /v1/search` with the
`X-Api-Key` header and maps the model's arguments onto Google
parameters: `count` to `num` (clamped to 10), `country` to `gl`,
`language` to `hl`, `safesearch: strict` to `safe=active`, and
`freshness` day/week/month/year to `tbs=qdr:*`.
- Domain allowlists and blocklists (tool filters first, then arguments,
same precedence as the other providers) are sent as `site:a OR site:b` /
`-site:x` query operators, and explicit date ranges as `after:` /
`before:`, so the 10-result page is spent on matching hosts. The shared
`DomainFilter` still re-checks every result on the way back.
- Google redirect links (`https://www.google.com/url?q=<real>`) that
appear with time filters are unwrapped before filtering, so sources
point at the real page.
- 401/403 names `SERPLY_API_KEY` without echoing the key; 429 is
surfaced with `Retry-After` and never retried; other statuses include
the upstream body.
- Docs: README provider section and tables, CHANGELOG, ARCHITECTURE,
deploying guide and Kubernetes notes.
- `.rust-file-sizes.json`: `config.rs` goes from 637 to 642. The five
lines are the exhaustive `match` arms for the new variant, so I raised
the reviewed exception rather than splitting the enum out; happy to
split instead if you prefer.

## Test Plan

- `cargo fmt -- --check`, `cargo clippy --all-targets -- -D warnings`,
`cargo test` (93 suites, 0 failed), and `pre-commit run --from-ref
upstream/main --to-ref HEAD` all pass.
- 12 unit tests in `serply.rs` cover parameter mapping, filter
precedence, operator building, date-range handling, redirect unwrapping
and null/missing response fields.
- `tests/web_search_serply_test.rs` runs the handler against a local
Axum mock: exact query parameters and output JSON, public `sources`,
`site:` / `-site:` plus `after:` / `before:` with client-side filtering,
rejected credentials without leaking the key, 429 without retry, and 422
with its body.
- `web_search_config_selects_serply_from_environment` plus the
provider-switch loop in `agentic-server`.
- Live run against `api.serply.io` through `WebSearchHandler` (temporary
test, not committed): a plain query, a two-query batch restricted to
`docs.rs` / `github.com`, `freshness: week` + `language: en` (redirects
unwrapped, `page_age` filled), a `2026-01-01to2026-03-01` range
(`latency: 1.25`), and a bad key returning the `SERPLY_API_KEY` message.

Note: #417 also touches `tool/web_search/`. I'm glad to rebase onto it
if it lands first.

Disclosure: I work with Serply. Happy to adjust scope, naming, or drop
this entirely if it isn't a direction you want for the project.

---------

Signed-off-by: serply <[email protected]>
Co-authored-by: Hao Shan <[email protected]>
Co-authored-by: Maral <[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.

Follow-ups from #414: protocol-neutral tool declarations, a shared domain-policy module, explicit tool-output status

3 participants