Skip to content

feat: execute Claude's native web_fetch tool on /v1/messages - #414

Merged
maralbahari merged 2 commits into
vllm-project:mainfrom
StevenWang-CY:feat-messages-web-fetch
Oct 2, 2026
Merged

maralbahari merged 2 commits into
vllm-project:mainfrom
StevenWang-CY:feat-messages-web-fetch

Conversation

@StevenWang-CY

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

Copy link
Copy Markdown
Contributor

Summary

Closes #408.

A request that declares Claude's native web_fetch_20250910 server tool on /v1/messages is forwarded unchanged today; vLLM's Anthropic tool model requires input_schema, so the whole request fails before inference, and /v1/messages/count_tokens fails 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 ordinary web_fetch function 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 hidden tool_result, and the call never reaches the client. The client keeps sending the standard declaration, and count_tokens accepts it too.

What the gateway honours, and where each rule lives:

  • Ownership is request-scoped and derived from the registry. request_gateway_map marks the web_fetch name 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 named web_fetch stays client-owned and is returned to the client as before. Claude Code is unaffected: its WebFetch is a client tool with its own schema.
  • max_uses counts 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 as invalid_tool_input without 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.
  • Only a URL the conversation has shown can be fetched. It must appear, whole, in a user message or a 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 with url_not_in_prior_context. This rule and the budget live in the loop because only the loop holds the conversation.
  • Internal addresses are never contacted. Only absolute http/https URLs 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's allowed_domains / blocked_domains. Under this policy the fetcher connects directly and ignores the HTTP_PROXY / HTTPS_PROXY environment, 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 = true is the operator opt-in for intranet deployments, and restores proxy use.
  • Every fetch is bounded. One absolute deadline of 20 s covers name resolution, every request, redirects, and the body read; 10 MiB (a longer body is cut and reported as truncated); 5 redirect hops; and at most max_concurrent_gateway_calls fetches 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 answer unsupported_content_type. max_content_tokens is applied as an approximate four bytes per token, and the output stays under the gateway's 1 MiB tool output cap after JSON escaping.
  • Failures reach the model, not the client. 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, and unavailable come back in the documented web_fetch_tool_result_error shape as an error tool_result, so the turn continues. Backend failures are thiserror enums with their sources; they become documented codes at one boundary, and the message keeps the cause.
  • Nothing is silently ignored. citations enabled, the use_cache and response_inclusion settings of later tool versions, any other web_fetch_* version, a malformed domain list, a domain entry that is not a host name (a scheme, a path, a wildcard, .), and a non-positive max_uses or max_content_tokens are rejected with HTTP 400; allowed_callers: ["direct"] and citations: {"enabled": false} are accepted. A gateway whose operator disabled the fetcher ([web_fetch] enabled = false or AGENTIC_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 into WebFetchToolParam, and routes them through the tool handler's validate and normalize; the registry seam reads a declaration with the same parser, and web_search declarations take the same path. GatewayExecutors::require_web_fetch owns the operator switch for registry construction and count_tokens alike. A call produces one WebFetchOutcome — a rendered page or a refusal — serialized once at the model-facing boundary (tool/web_fetch/output.rs); the loop reads the result's type to mark a refusal is_error.

Retrieval sits behind a WebFetchBackend trait, crate-private like WebSearchProvider, 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. Returning server_tool_use blocks to the client (#409), PDF text, citations, and use_cache are 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/deploying the environment variables, ARCHITECTURE.md the adapter/handler/loop split, and the CHANGELOG has an entry under Unreleased.

Test Plan

Red on unmodified main (42780da) and green with this change.

  • Against the real agentic-server binary, with a stdlib inference backend that behaves like vLLM (a tool without input_schema is rejected with 400) and a page origin on the same loopback listener, so the enabled run sets AGENTIC_WEB_FETCH_ALLOW_PRIVATE_NETWORKS=true: the binary built from main fails every request that declares the native tool over JSON, SSE, and count_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 with url required, feeds back a web_fetch_result with the page title and text, rewrites the declaration for count_tokens, and with AGENTIC_WEB_FETCH_ENABLED=false answers 400 on both endpoints without contacting the upstream or the origin.
  • Recorded cassettes: tests/cassettes/messages/messages-web-fetch-Qwen-Qwen3-8B-{nonstreaming,streaming}.yaml were 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.rs replays 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 and retrieved_at normalized), 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.rs drives 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_uses counting 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 named web_fetch returned to the client; a disabled executor failing registry construction.
  • crates/agentic-server/tests/messages_web_fetch_test.rs runs the same contract through the HTTP gateway: JSON, SSE, count_tokens rewriting the declaration and forwarding other tools unchanged, 400 on both endpoints when disabled, 400 for an unsupported version, citations enabled, and max_uses: 0, and 400 on both endpoints for an allowlist that names no host.
  • Internal addresses through a redirect are tested against the real HTTP backend in web_fetch/http.rs: with 127.0.0.2 standing 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 follows allow_private_networks. The address policy is unit-tested on every refused and allowed range, IPv4 and IPv6, and resolve_addrs on literals and on localhost by name.
  • Unit tests cover the declaration validation and rewrite with its budgets, including that the upstream declaration equals the handler's own normalization for web_search and web_fetch, host-name entries accepted after normalization and ., example.com/blog, and *.example.com rejected; the typed declaration parser; the handler's validate and 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 by type; 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 in GatewayExecutors; and the file and environment configuration with its precedence and rejection of invalid values.
  • pre-commit run --all-files (including rust-file-sizes with RUST_FILE_SIZE_BASE=origin/main), cargo fmt -- --check, cargo clippy --all-targets -- -D warnings, and cargo test --no-fail-fast across the workspace pass on the exact commit from a clean worktree.

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 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 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]>

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

@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_search and web_fetch.
  • Carrying explicit success/failure status through ToolOutput and dispatch, so the Messages loop no longer needs to infer it from serialized JSON.

@maralbahari
maralbahari merged commit 8880987 into vllm-project:main Oct 2, 2026
22 checks passed
@StevenWang-CY

Copy link
Copy Markdown
Contributor Author

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 web_search and web_fetch, and explicit success/failure status carried through ToolOutput and dispatch. The follow-up PR is in preparation.

haoshan98 added a commit that referenced this pull request Oct 6, 2026
…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]>
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.

Support the web_fetch tool on /v1/messages

2 participants