Repository navigation
feat: execute Claude's native web_fetch tool on /v1/messages - #414
Conversation
A native web_fetch_20250910 declaration was forwarded unchanged and rejected by vLLM, whose tool model requires an input_schema, so the request failed before inference. The gateway now rewrites the declaration into an ordinary web_fetch function tool in the upstream copy only, fetches the page the model names, feeds the text back as a hidden tool_result, and keeps the call out of the client-visible response, as it does for native web search. count_tokens accepts the declaration too. Ownership is request-scoped: the web_fetch name is gateway-owned only when the request declares the native type, so a client function of that name stays client-owned. max_uses is a request-wide budget of fetches charged for every admitted call, and only a URL that already appeared whole in a user message or a tool result can be fetched. Non-public addresses are refused directly, through DNS, and through redirects, with the connection pinned to the checked addresses; every fetch is bounded in time, size, redirects, and concurrency. Documented failures reach the model as web_fetch_tool_result_error results, and unsupported parameters or versions are rejected with 400. Operators tune or disable the fetcher with [web_fetch] in config.toml or the AGENTIC_WEB_FETCH_* variables. Closes vllm-project#408. Signed-off-by: Chuyue Wang <[email protected]>
maralbahari
left a comment
There was a problem hiding this comment.
Thanks for adding native web fetch support! The shared JSON/SSE dispatch path and backend abstraction are good foundations. I’ve left inline comments on correctness, test coverage, and responsibility boundaries.
I’d like the correctness and security issues addressed in this PR. Separating internal registry declarations from Responses wire types and extracting shared domain policy could be follow-up work to keep this change focused.
Addresses the review of vllm-project#414. Correctness and security: - Decode HTML character references in linear time: the search for a reference's `;` is bounded by the reference length, so a flood of ampersands no longer costs quadratic work (regression test at 300 KiB). - Hold the fetch permit through extraction, which runs off the async workers, so the concurrency ceiling bounds the whole call. - Fail closed when an allowlist names no usable host: `DomainFilter` denies every host instead of widening to all of them, and `WebFetchHandler::validate` rejects entries that are not host names (schemes, paths, wildcards, `.`) with HTTP 400 on both endpoints. - Count name resolution against the fetch deadline and bound the send with the same absolute deadline. - Connect directly under the public-only policy: environment proxies are ignored unless `allow_private_networks` is set, so the address check and the pin apply to the real destination. Structure: - `FetchFailure` and `UrlRejection` are `thiserror` enums with sources, mapped to the documented codes in one place; failure detection reads the result's `type`, not a byte prefix. A call produces one `WebFetchOutcome`, serialized at the model-facing boundary (`tool/web_fetch/output.rs`). - The Messages adapter judges the Anthropic-specific settings, reads the shared parameters once into `WebFetchToolParam`, and routes them through the tool handler's `validate` and `normalize`; the registry seam reads a declaration with the same parser. `web_search` declarations take the same path. - `GatewayExecutors::require_web_fetch` is the one owner of the operator switch, used by registry construction and `count_tokens`. - Request-scoped `web_fetch` ownership is derived from the registry (`request_gateway_map`) instead of re-reading the declarations. Tests: - Messages cassettes (JSON and SSE) recorded against vLLM serving Qwen3-8B replay through both loops, asserting the complete upstream requests, the call/result pairing, and that the client sees the answer and never the call. Signed-off-by: Chuyue Wang <[email protected]>
There was a problem hiding this comment.
@StevenWang-CY Thanks for addressing the review comments! Could you please open an issue and link it here to track the refactoring deferred to a follow-up PR?
The issue should cover:
- Introducing a protocol-neutral internal tool declaration, with both APIs using a shared registry-building path.
- Extracting shared domain validation and filtering into a common module used by
web_searchandweb_fetch. - Carrying explicit success/failure status through
ToolOutputand dispatch, so the Messages loop no longer needs to infer it from serialized JSON.
|
Opened #416 to track the three refactors deferred from this PR: a protocol-neutral internal tool declaration with a shared registry-building path, a shared domain validation and filtering module for |
…ool output status (#417) ## 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. --------- Signed-off-by: Chuyue Wang <[email protected]> Co-authored-by: Hao Shan <[email protected]>
Summary
Closes #408.
A request that declares Claude's native
web_fetch_20250910server tool on/v1/messagesis forwarded unchanged today; vLLM's Anthropic tool model requiresinput_schema, so the whole request fails before inference, and/v1/messages/count_tokensfails the same way. This PR makes the gateway execute the tool the way it already executes native web search: the declaration is rewritten into an ordinaryweb_fetchfunction tool with a{"url": string}schema in the upstream copy only, the gateway fetches the page the model names, the page text goes back to the model as a hiddentool_result, and the call never reaches the client. The client keeps sending the standard declaration, andcount_tokensaccepts it too.What the gateway honours, and where each rule lives:
request_gateway_mapmarks theweb_fetchname gateway-owned only when the request-scoped registry bound it to the gateway executor, which only a native declaration does, so the loop's classification cannot drift from the registry. A client function that happens to be namedweb_fetchstays client-owned and is returned to the client as before. Claude Code is unaffected: itsWebFetchis a client tool with its own schema.max_usescounts fetches. The budget is request-wide and separate from the web search budget. Every admitted call is charged whatever its outcome — Anthropic documents that failed fetches count — and a call whose arguments carry no URL is answered asinvalid_tool_inputwithout being charged. Admission runs in model order before any call starts, in the dispatcher both loops share; the arguments are parsed once for the budget and the URL.tool_result: the client's, or a hidden web search or fetch round. A URL the model produced itself, or one that appears only in the system prompt, is refused withurl_not_in_prior_context. This rule and the budget live in the loop because only the loop holds the conversation.http/httpsURLs of at most 250 characters without credentials are accepted. A host that is, or resolves to, a loopback, private, link-local (which covers cloud metadata), carrier-grade NAT, multicast, documentation, benchmarking, or other non-public address is refused before any connection, including the IPv6 mapped, NAT64, and 6to4 forms that embed one. The connection is pinned to the addresses that passed the check (resolve_to_addrs), redirects are followed by the gateway rather than the HTTP client, and every hop is checked again with the same rules and the declaration'sallowed_domains/blocked_domains. Under this policy the fetcher connects directly and ignores theHTTP_PROXY/HTTPS_PROXYenvironment, so the check and the pin apply to the real destination. A declared allowlist admits only the hosts it names; one whose entries normalize to nothing admits no host.[web_fetch] allow_private_networks = trueis the operator opt-in for intranet deployments, and restores proxy use.max_concurrent_gateway_callsfetches in flight at once, each holding its slot until extraction has finished. HTML is reduced to plain text in-tree (scripts, styles, and markup dropped, character references decoded in a bounded search,<pre>kept verbatim, the declared or sniffed charset honoured);text/*, XHTML, XML, and JSON bodies are returned as text; PDF and other binary types answerunsupported_content_type.max_content_tokensis applied as an approximate four bytes per token, and the output stays under the gateway's 1 MiB tool output cap after JSON escaping.url_not_accessible,url_not_allowed,too_many_requests,unsupported_content_type,url_too_long,invalid_tool_input,max_uses_exceeded,url_not_in_prior_context, andunavailablecome back in the documentedweb_fetch_tool_result_errorshape as an errortool_result, so the turn continues. Backend failures arethiserrorenums with their sources; they become documented codes at one boundary, and the message keeps the cause.citationsenabled, theuse_cacheandresponse_inclusionsettings of later tool versions, any otherweb_fetch_*version, a malformed domain list, a domain entry that is not a host name (a scheme, a path, a wildcard,.), and a non-positivemax_usesormax_content_tokensare rejected with HTTP 400;allowed_callers: ["direct"]andcitations: {"enabled": false}are accepted. A gateway whose operator disabled the fetcher ([web_fetch] enabled = falseorAGENTIC_WEB_FETCH_ENABLED=false) rejects the declaration with 400 on both endpoints instead of forwarding it in a shape the upstream cannot execute.The Messages adapter judges what is Anthropic-specific about a declaration (tool version,
citations, cache settings,allowed_callers,max_uses), reads the shared parameters once intoWebFetchToolParam, and routes them through the tool handler'svalidateandnormalize; the registry seam reads a declaration with the same parser, andweb_searchdeclarations take the same path.GatewayExecutors::require_web_fetchowns the operator switch for registry construction andcount_tokensalike. A call produces oneWebFetchOutcome— a rendered page or a refusal — serialized once at the model-facing boundary (tool/web_fetch/output.rs); the loop reads the result'stypeto mark a refusalis_error.Retrieval sits behind a
WebFetchBackendtrait, crate-private likeWebSearchProvider, with the HTTP fetcher as the built-in backend; an extraction service replaces it without touching the Messages loop.encoding_rs, already in the dependency tree through reqwest, becomes a direct dependency for bodies declared in a non-UTF-8 charset. Returningserver_tool_useblocks to the client (#409), PDF text, citations, anduse_cacheare the follow-ups the issue names; a protocol-neutral internal declaration type and a shared domain-policy module are the follow-ups the review named.The README documents the request contract and the
[web_fetch]settings,docs/deployingthe environment variables,ARCHITECTURE.mdthe adapter/handler/loop split, and the CHANGELOG has an entry under Unreleased.Test Plan
Red on unmodified
main(42780da) and green with this change.agentic-serverbinary, with a stdlib inference backend that behaves like vLLM (a tool withoutinput_schemais rejected with 400) and a page origin on the same loopback listener, so the enabled run setsAGENTIC_WEB_FETCH_ALLOW_PRIVATE_NETWORKS=true: the binary built frommainfails every request that declares the native tool over JSON, SSE, andcount_tokens. The binary built from this branch returns 200 with the final answer and no gateway call over JSON and SSE, fetches the page exactly once, offers the upstream a function tool withurlrequired, feeds back aweb_fetch_resultwith the page title and text, rewrites the declaration forcount_tokens, and withAGENTIC_WEB_FETCH_ENABLED=falseanswers 400 on both endpoints without contacting the upstream or the origin.tests/cassettes/messages/messages-web-fetch-Qwen-Qwen3-8B-{nonstreaming,streaming}.yamlwere recorded with the existing Messages recorder against vLLM serving Qwen3-8B with tool calling on, for a request that declares the native tool as the gateway rewrites it (the recorder's tool and tool-output fixtures are checked in beside them).crates/agentic-server-core/tests/messages_web_fetch_cassette_test.rsreplays them through the JSON and SSE loops: the mock upstream serves the recorded turns, the real fetch hits a loopback page carrying a verification token, and the assertions compare the loop's complete upstream requests with the recording (the origin andretrieved_atnormalized), check the call/result pairing and that the page was fetched exactly once, and check that the client receives the token and never the call.crates/agentic-server-core/tests/messages_web_fetch_test.rsdrives the JSON and SSE loops against a mock upstream and a page origin on one listener: the hidden fetch and the fed-back result over both transports; a URL from an earlier fetch result fetched in the next round; a URL the conversation never showed refused and still charged;max_usescounting a failed fetch and not an unparseable call; loopback by address and by name refused before any connection under the default policy; domain filters applied to a redirect hop; a redirect to a URL carrying credentials refused and a redirect loop stopped after five hops, with the origin's request log proving the refused targets were never requested; PDF and HTTP 429 answering their codes; a client function namedweb_fetchreturned to the client; a disabled executor failing registry construction.crates/agentic-server/tests/messages_web_fetch_test.rsruns the same contract through the HTTP gateway: JSON, SSE,count_tokensrewriting the declaration and forwarding other tools unchanged, 400 on both endpoints when disabled, 400 for an unsupported version,citationsenabled, andmax_uses: 0, and 400 on both endpoints for an allowlist that names no host.web_fetch/http.rs: with127.0.0.2standing in for an internal address under a test-only address predicate, a direct fetch and a redirect from the test origin to it are both refused before any connection, and the origin's request count shows that only the first hop was requested. A 50 ms deadline against an origin that answers after 2 s times out at the deadline. The proxy switch followsallow_private_networks. The address policy is unit-tested on every refused and allowed range, IPv4 and IPv6, andresolve_addrson literals and onlocalhostby name.web_searchandweb_fetch, host-name entries accepted after normalization and.,example.com/blog, and*.example.comrejected; the typed declaration parser; the handler'svalidateand a specification-only handler; the ownership map; whole-URL prior-context matching (a prefix of a seen URL does not count); the argument parser; the documented output and error shapes and their detection bytype; refusal codes and source chains; the content limit and the output cap after JSON escaping; backend failure mapping; the concurrency ceiling with every permit returned after extraction; a domain filter whose allowlist names no domain admitting nothing; HTML extraction (titles, blocks,<pre>, entities, a 300 KiB run of ampersands decoding in linear time, skipped elements, charset sniffing); content-type parsing; body decoding; the operator switch inGatewayExecutors; and the file and environment configuration with its precedence and rejection of invalid values.pre-commit run --all-files(includingrust-file-sizeswithRUST_FILE_SIZE_BASE=origin/main),cargo fmt -- --check,cargo clippy --all-targets -- -D warnings, andcargo test --no-fail-fastacross the workspace pass on the exact commit from a clean worktree.