Skip to main content

adk_tool/builtin/
web_search.rs

1use adk_core::{Result, Tool, ToolContext, ToolEffect};
2use async_trait::async_trait;
3use serde_json::{Value, json};
4use std::sync::Arc;
5
6/// Approximate user location for Anthropic's web search tool.
7#[derive(Debug, Clone, Default)]
8pub struct WebSearchUserLocation {
9    city: Option<String>,
10    country: Option<String>,
11    region: Option<String>,
12    timezone: Option<String>,
13}
14
15impl WebSearchUserLocation {
16    /// Create a new empty user location.
17    pub fn new() -> Self {
18        Self::default()
19    }
20
21    /// Set the city name.
22    pub fn with_city(mut self, city: impl Into<String>) -> Self {
23        self.city = Some(city.into());
24        self
25    }
26
27    /// Set the country name.
28    pub fn with_country(mut self, country: impl Into<String>) -> Self {
29        self.country = Some(country.into());
30        self
31    }
32
33    /// Set the region name.
34    pub fn with_region(mut self, region: impl Into<String>) -> Self {
35        self.region = Some(region.into());
36        self
37    }
38
39    /// Set the timezone identifier.
40    pub fn with_timezone(mut self, timezone: impl Into<String>) -> Self {
41        self.timezone = Some(timezone.into());
42        self
43    }
44
45    fn to_json(&self) -> Value {
46        json!({
47            "type": "approximate",
48            "city": self.city,
49            "country": self.country,
50            "region": self.region,
51            "timezone": self.timezone,
52        })
53    }
54}
55
56/// WebSearch is a built-in tool for Anthropic Claude models that enables
57/// server-side web search. The model searches the web internally and returns
58/// results as ServerToolUse / WebSearchToolResult content blocks.
59///
60/// The tool declares `web_search_20250305` unless
61/// [`with_dynamic_filtering`](Self::with_dynamic_filtering) selects
62/// `web_search_20260209`.
63#[derive(Debug, Clone, Default)]
64pub struct WebSearchTool {
65    allowed_domains: Option<Vec<String>>,
66    blocked_domains: Option<Vec<String>>,
67    max_uses: Option<i32>,
68    user_location: Option<WebSearchUserLocation>,
69    dynamic_filtering: bool,
70    allowed_callers: Option<Vec<String>>,
71}
72
73impl WebSearchTool {
74    /// Create a new `WebSearchTool` with default settings.
75    pub fn new() -> Self {
76        Self::default()
77    }
78
79    /// Restrict search results to the specified domains.
80    pub fn with_allowed_domains(
81        mut self,
82        domains: impl IntoIterator<Item = impl Into<String>>,
83    ) -> Self {
84        self.allowed_domains = Some(domains.into_iter().map(Into::into).collect());
85        self.blocked_domains = None;
86        self
87    }
88
89    /// Block search results from the specified domains.
90    pub fn with_blocked_domains(
91        mut self,
92        domains: impl IntoIterator<Item = impl Into<String>>,
93    ) -> Self {
94        self.blocked_domains = Some(domains.into_iter().map(Into::into).collect());
95        self.allowed_domains = None;
96        self
97    }
98
99    /// Set the maximum number of search invocations per turn.
100    pub fn with_max_uses(mut self, max_uses: i32) -> Self {
101        self.max_uses = Some(max_uses);
102        self
103    }
104
105    /// Set the approximate user location for localized results.
106    pub fn with_user_location(mut self, user_location: WebSearchUserLocation) -> Self {
107        self.user_location = Some(user_location);
108        self
109    }
110
111    /// Declare the `web_search_20260209` version, which filters results with code
112    /// before they reach the context window.
113    ///
114    /// Supported on Claude Opus 5.5, Opus 5, Opus 4.8, Opus 4.7, Opus 4.6,
115    /// Sonnet 5.5, Sonnet 5, and Sonnet 4.6. Do not combine it with a code
116    /// execution tool in the same request.
117    ///
118    /// # Example
119    ///
120    /// ```
121    /// use adk_core::Tool;
122    /// use adk_tool::WebSearchTool;
123    ///
124    /// let tool = WebSearchTool::new().with_dynamic_filtering().with_max_uses(3);
125    /// let declaration = tool.declaration();
126    /// assert_eq!(declaration["x-adk-anthropic-tool"]["type"], "web_search_20260209");
127    /// ```
128    pub fn with_dynamic_filtering(mut self) -> Self {
129        self.dynamic_filtering = true;
130        self
131    }
132
133    /// Set who may call the `web_search_20260209` tool selected by
134    /// [`with_dynamic_filtering`](Self::with_dynamic_filtering).
135    ///
136    /// The API defaults that version to `["code_execution_20260120"]`, which filters
137    /// results with code. `["direct"]` keeps the newer tool version but turns dynamic
138    /// filtering off, which Zero Data Retention and models without programmatic tool
139    /// calling require. `web_search_20250305` already defaults to direct calls, so the
140    /// setting is sent only with dynamic filtering.
141    ///
142    /// # Example
143    ///
144    /// ```
145    /// use adk_core::Tool;
146    /// use adk_tool::WebSearchTool;
147    ///
148    /// let tool = WebSearchTool::new().with_dynamic_filtering().with_allowed_callers(["direct"]);
149    /// let declaration = tool.declaration();
150    /// assert_eq!(
151    ///     declaration["x-adk-anthropic-tool"]["allowed_callers"],
152    ///     serde_json::json!(["direct"])
153    /// );
154    /// ```
155    pub fn with_allowed_callers(
156        mut self,
157        callers: impl IntoIterator<Item = impl Into<String>>,
158    ) -> Self {
159        self.allowed_callers = Some(callers.into_iter().map(Into::into).collect());
160        self
161    }
162}
163
164#[async_trait]
165impl Tool for WebSearchTool {
166    fn name(&self) -> &str {
167        "web_search"
168    }
169
170    fn description(&self) -> &str {
171        "Searches the web for current information (server-side)."
172    }
173
174    fn is_builtin(&self) -> bool {
175        true
176    }
177
178    // Runs on the provider; a policy sees this effect before the tool is attached.
179    fn effect(&self) -> ToolEffect {
180        ToolEffect::ReadOnly
181    }
182
183    fn declaration(&self) -> Value {
184        let allowed_callers = self.allowed_callers.as_ref().filter(|_| self.dynamic_filtering);
185        json!({
186            "name": self.name(),
187            "description": self.description(),
188            "x-adk-anthropic-tool": {
189                "type": if self.dynamic_filtering { "web_search_20260209" } else { "web_search_20250305" },
190                "name": "web_search",
191                "allowed_domains": self.allowed_domains,
192                "blocked_domains": self.blocked_domains,
193                "max_uses": self.max_uses,
194                "user_location": self.user_location.as_ref().map(WebSearchUserLocation::to_json),
195                "allowed_callers": allowed_callers,
196            }
197        })
198    }
199
200    async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
201        Err(adk_core::AdkError::tool("WebSearch is handled internally by Anthropic"))
202    }
203}