Skip to main content

strands_harness/tools/
web_search.rs

1//! `web_search`: search the web and return the top results as numbered sources.
2//!
3//! Three modes serve the `web_search` built-in ([`WebSearchSetting`]):
4//!
5//! - native: a provider server tool on the model itself (Anthropic `web_search`, the OpenAI
6//!   Responses `web_search` tool, Bedrock Mantle's GPT models), with no harness tool. The tool
7//!   records for those are [`anthropic_web_search_tool`], [`openai_web_search_tool`] and
8//!   [`bedrock_mantle_web_search_tool`];
9//! - AgentCore (features `bedrock` or `mantle`): on Bedrock models without native search, the
10//!   `make_agent_core_web_search` tool built here, backed by Amazon Bedrock AgentCore's
11//!   `InvokeWebSearch` API and authorized by IAM;
12//! - Exa (opt-in, feature `mcp`): the `web_search_tool` built here, backed by Exa's hosted MCP
13//!   server, a third party that receives the queries. The keyless tier works out of the box and
14//!   `EXA_API_KEY` lifts its rate limit.
15//!
16//! The tool/backend split ([`search_tool`] over a [`SearchBackend`]) keeps the model-facing
17//! contract fixed while the provider behind it can change.
18
19use std::fmt;
20use std::sync::Arc;
21
22use async_trait::async_trait;
23use serde::de::{self, Visitor};
24use serde::{Deserialize, Deserializer, Serialize, Serializer};
25use serde_json::json;
26use strands::tools::{FunctionTool, ToolError};
27use strands::types::{JsonSchema, JsonValue};
28
29/// Exa's hosted MCP endpoint.
30#[cfg(feature = "mcp")]
31pub(crate) const EXA_MCP_URL: &str = "https://mcp.exa.ai/mcp";
32/// The Exa MCP tool `web_search` calls.
33#[cfg(feature = "mcp")]
34pub(crate) const EXA_TOOL: &str = "web_search_exa";
35const MAX_RESULTS: i64 = 10;
36const DEFAULT_RESULTS: i64 = 5;
37#[cfg_attr(
38    not(any(feature = "mcp", feature = "bedrock", feature = "mantle")),
39    allow(dead_code, reason = "used by the Exa and AgentCore backends")
40)]
41const SNIPPET_CHARS: usize = 500;
42
43/// The `web_search` tool description.
44pub const WEB_SEARCH_DESCRIPTION: &str =
45    "Search the web and return the top results as numbered sources with a short excerpt each.";
46
47/// The `web_search` built-in setting (`WebSearchSetting`): on (native search where the model has
48/// it), off, or Exa on any model. JSON form: `true`, `false` or `"exa"`.
49#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
50#[non_exhaustive]
51pub enum WebSearchSetting {
52    /// Off (`false`).
53    Off,
54    /// The model's native search where it has one (`true`, the default).
55    #[default]
56    On,
57    /// Exa's hosted search on any model, replacing native search (`'exa'`).
58    Exa,
59}
60
61impl From<bool> for WebSearchSetting {
62    fn from(enabled: bool) -> Self {
63        if enabled { Self::On } else { Self::Off }
64    }
65}
66
67impl Serialize for WebSearchSetting {
68    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
69        match self {
70            Self::Off => serializer.serialize_bool(false),
71            Self::On => serializer.serialize_bool(true),
72            Self::Exa => serializer.serialize_str("exa"),
73        }
74    }
75}
76
77struct SettingVisitor;
78
79impl Visitor<'_> for SettingVisitor {
80    type Value = WebSearchSetting;
81
82    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        f.write_str("a boolean or 'exa'")
84    }
85
86    fn visit_bool<E: de::Error>(self, value: bool) -> Result<Self::Value, E> {
87        Ok(value.into())
88    }
89
90    fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
91        if value == "exa" {
92            return Ok(WebSearchSetting::Exa);
93        }
94        Err(E::custom("must be a boolean or 'exa'."))
95    }
96}
97
98impl<'de> Deserialize<'de> for WebSearchSetting {
99    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
100        deserializer.deserialize_any(SettingVisitor)
101    }
102}
103
104/// The Anthropic server tool record for native search (`ANTHROPIC_WEB_SEARCH`), for
105/// `AnthropicModelConfig` `anthropic_tools`.
106#[must_use]
107pub fn anthropic_web_search_tool() -> JsonValue {
108    json!({"type": "web_search_20260318", "name": "web_search", "allowed_callers": ["direct"]})
109}
110
111/// The OpenAI Responses built-in tool for native search, for the model's `params.tools`.
112#[must_use]
113pub fn openai_web_search_tool() -> JsonValue {
114    json!({"type": "web_search"})
115}
116
117/// The Bedrock Mantle (GPT models) built-in tool for native search, for the model's
118/// `params.tools`.
119#[must_use]
120pub fn bedrock_mantle_web_search_tool() -> JsonValue {
121    json!({"type": "web_search", "external_web_access": true})
122}
123
124/// One search result (`SearchResult`).
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126#[non_exhaustive]
127pub struct SearchResult {
128    /// The page title.
129    pub title: String,
130    /// The page URL.
131    pub url: String,
132    /// A short excerpt; may be empty.
133    pub snippet: String,
134}
135
136impl SearchResult {
137    /// A result.
138    pub fn new(title: impl Into<String>, url: impl Into<String>, snippet: impl Into<String>) -> Self {
139        Self {
140            title: title.into(),
141            url: url.into(),
142            snippet: snippet.into(),
143        }
144    }
145}
146
147/// A backend failure with a message the model can act on (`WebSearchError`).
148#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
149#[error("{message}")]
150#[non_exhaustive]
151pub struct WebSearchError {
152    message: String,
153}
154
155impl WebSearchError {
156    /// An error with `message`.
157    pub fn new(message: impl Into<String>) -> Self {
158        Self {
159            message: message.into(),
160        }
161    }
162
163    /// What failed.
164    #[must_use]
165    pub fn message(&self) -> &str {
166        &self.message
167    }
168}
169
170/// Runs a search (`SearchBackend`): the top `max_results` results for `query`.
171#[async_trait]
172pub trait SearchBackend: Send + Sync + 'static {
173    /// Searches.
174    ///
175    /// # Errors
176    ///
177    /// When the search fails; the model sees `web_search failed: <message>`.
178    async fn search(&self, query: &str, max_results: usize) -> Result<Vec<SearchResult>, WebSearchError>;
179}
180
181fn input_schema() -> JsonSchema {
182    json!({
183        "type": "object",
184        "properties": {
185            "query": {
186                "type": "string",
187                "description": "What to search for. A descriptive sentence works better than bare keywords."
188            },
189            "max_results": {
190                "description": "How many results to return, 1-10.",
191                "type": "integer",
192                "minimum": -9_007_199_254_740_991_i64,
193                "maximum": 9_007_199_254_740_991_i64
194            }
195        },
196        "required": ["query"],
197        "additionalProperties": false
198    })
199}
200
201fn one_line(text: &str) -> String {
202    text.split_whitespace().collect::<Vec<_>>().join(" ")
203}
204
205#[allow(
206    clippy::cast_possible_truncation,
207    clippy::cast_sign_loss,
208    reason = "clamped to 1..=10"
209)]
210fn max_results(input: &JsonValue) -> usize {
211    let requested = input
212        .get("max_results")
213        .and_then(JsonValue::as_i64)
214        .unwrap_or(DEFAULT_RESULTS);
215    requested.clamp(1, MAX_RESULTS) as usize
216}
217
218fn format_results(results: &[SearchResult]) -> String {
219    if results.is_empty() {
220        return "No results.".to_owned();
221    }
222    let mut lines = vec!["Sources:".to_owned()];
223    for (index, result) in results.iter().enumerate() {
224        lines.push(format!(
225            "{}. {} \u{2014} {}",
226            index + 1,
227            one_line(&result.title),
228            result.url
229        ));
230        if !result.snippet.is_empty() {
231            lines.push(format!("   {}", one_line(&result.snippet)));
232        }
233    }
234    lines.join("\n")
235}
236
237/// Builds a `web_search` tool that formats `backend`'s results as a numbered `Sources:` list.
238/// `max_results` is clamped to 1-10 (5 when omitted); failures and empty results come back as text.
239#[must_use]
240pub fn search_tool(backend: Arc<dyn SearchBackend>) -> FunctionTool {
241    FunctionTool::builder("web_search", WEB_SEARCH_DESCRIPTION)
242        .input_schema(input_schema())
243        .callback(move |input, _context| {
244            let backend = backend.clone();
245            async move {
246                let query = input
247                    .get("query")
248                    .and_then(JsonValue::as_str)
249                    .ok_or_else(|| ToolError::msg("Invalid input: expected string at \"query\"."))?;
250                let text = match backend.search(query, max_results(&input)).await {
251                    Ok(results) => format_results(&results),
252                    Err(error) => {
253                        let reason = if error.message().is_empty() {
254                            "Error"
255                        } else {
256                            error.message()
257                        };
258                        format!("web_search failed: {reason}")
259                    }
260                };
261                Ok::<JsonValue, ToolError>(text.into())
262            }
263        })
264}
265
266/// Splits Exa's `---`-separated `Title:/URL:/.../Highlights:` blocks into results. Only a block
267/// that opens with a `Title:` line directly followed by a `URL:` line counts, so those words
268/// inside a page's highlighted text do not start a source.
269#[cfg_attr(not(feature = "mcp"), allow(dead_code, reason = "used by the Exa backend"))]
270fn parse_exa(text: &str) -> Vec<SearchResult> {
271    let mut blocks = Vec::new();
272    let mut current = String::new();
273    for line in text.split_inclusive('\n') {
274        let bare = line.trim_end_matches(['\n', '\r']);
275        if bare.starts_with("---") && bare[3..].chars().all(char::is_whitespace) {
276            blocks.push(std::mem::take(&mut current));
277            continue;
278        }
279        current.push_str(line);
280    }
281    blocks.push(current);
282    blocks.iter().filter_map(|block| parse_block(block)).collect()
283}
284
285#[cfg_attr(not(feature = "mcp"), allow(dead_code, reason = "used by the Exa backend"))]
286fn parse_block(block: &str) -> Option<SearchResult> {
287    let rest = block.trim_start();
288    let rest = rest.strip_prefix("Title: ")?;
289    let (title, rest) = rest.split_once('\n')?;
290    let title = title.strip_suffix('\r').unwrap_or(title);
291    let rest = rest.strip_prefix("URL: ")?;
292    let url: String = rest.chars().take_while(|c| !c.is_whitespace()).collect();
293    if url.is_empty() {
294        return None;
295    }
296    let highlights = block
297        .find("Highlights:")
298        .map_or("", |index| &block[index + "Highlights:".len()..]);
299    let snippet: String = one_line(highlights).chars().take(SNIPPET_CHARS).collect();
300    Some(SearchResult::new(title.trim(), url, snippet))
301}
302
303#[cfg(any(feature = "bedrock", feature = "mantle"))]
304pub(crate) use agentcore::agent_core_web_search;
305#[cfg(any(feature = "bedrock", feature = "mantle"))]
306pub use agentcore::{AgentCoreBackend, MakeAgentCoreWebSearchOptions, make_agent_core_web_search};
307#[cfg(feature = "mcp")]
308pub use exa::{ExaBackend, web_search_tool};
309
310#[cfg(any(feature = "bedrock", feature = "mantle"))]
311mod agentcore;
312
313#[cfg(feature = "mcp")]
314mod exa {
315    use std::collections::BTreeMap;
316    use std::fmt;
317    use std::sync::Arc;
318    use std::time::Duration;
319
320    use async_trait::async_trait;
321    use serde_json::json;
322    use strands::Tool;
323    use strands::mcp::{McpCallToolOptions, McpClient, McpClientConfig, McpClientOptions, McpToolFilters};
324    use strands::tools::FunctionTool;
325    use strands::types::JsonValue;
326
327    use super::{EXA_MCP_URL, EXA_TOOL, SearchBackend, SearchResult, WebSearchError, parse_exa, search_tool};
328
329    const TIMEOUT: Duration = Duration::from_secs(30);
330
331    type EnvLookup = Arc<dyn Fn() -> Option<String> + Send + Sync>;
332
333    /// The search backend over Exa's hosted MCP server. Each search opens its own
334    /// MCP session and closes it.
335    #[derive(Clone)]
336    pub struct ExaBackend {
337        api_key: Option<String>,
338        url: String,
339        env: EnvLookup,
340    }
341
342    impl fmt::Debug for ExaBackend {
343        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
344            f.debug_struct("ExaBackend")
345                .field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
346                .field("url", &self.url)
347                .finish_non_exhaustive()
348        }
349    }
350
351    impl Default for ExaBackend {
352        fn default() -> Self {
353            Self::new(None)
354        }
355    }
356
357    impl ExaBackend {
358        /// A backend sending `api_key` as `x-api-key`. `None` reads `EXA_API_KEY` on every
359        /// search; an empty key (or variable) searches keyless.
360        #[must_use]
361        pub fn new(api_key: Option<String>) -> Self {
362            Self {
363                api_key,
364                url: EXA_MCP_URL.to_owned(),
365                env: Arc::new(|| std::env::var("EXA_API_KEY").ok()),
366            }
367        }
368
369        /// Uses another MCP endpoint, such as a proxy in front of Exa.
370        #[must_use]
371        pub fn with_url(mut self, url: impl Into<String>) -> Self {
372            self.url = url.into();
373            self
374        }
375
376        #[cfg(test)]
377        pub(super) fn with_env(mut self, env: impl Fn() -> Option<String> + Send + Sync + 'static) -> Self {
378            self.env = Arc::new(env);
379            self
380        }
381
382        async fn call(&self, query: &str, max_results: usize, key: &str) -> Result<Vec<SearchResult>, WebSearchError> {
383            let headers = (!key.is_empty()).then(|| BTreeMap::from([("x-api-key".to_owned(), key.to_owned())]));
384            let config = McpClientConfig {
385                url: Some(self.url.clone()),
386                headers,
387                options: McpClientOptions {
388                    tool_filters: Some(McpToolFilters {
389                        allowed: Some(vec![EXA_TOOL.into()]),
390                        rejected: None,
391                    }),
392                    ..McpClientOptions::default()
393                },
394                ..McpClientConfig::default()
395            };
396            let client = McpClient::new(config).map_err(|error| WebSearchError::new(error.to_string()))?;
397            let result = self.call_with(&client, query, max_results).await;
398            if let Err(error) = client.disconnect().await {
399                tracing::debug!("error=<{error}> | exa mcp session teardown failed");
400            }
401            let result = result?;
402            let text = result
403                .get("content")
404                .and_then(JsonValue::as_array)
405                .map(|blocks| {
406                    blocks
407                        .iter()
408                        .filter_map(|block| block.get("text").and_then(JsonValue::as_str))
409                        .collect::<Vec<_>>()
410                        .join("\n")
411                })
412                .unwrap_or_default();
413            if result.get("isError").and_then(JsonValue::as_bool) == Some(true) {
414                let message = if text.is_empty() {
415                    "Exa reported an error".to_owned()
416                } else {
417                    text
418                };
419                return Err(WebSearchError::new(message));
420            }
421            Ok(parse_exa(&text))
422        }
423
424        async fn call_with(
425            &self,
426            client: &McpClient,
427            query: &str,
428            max_results: usize,
429        ) -> Result<JsonValue, WebSearchError> {
430            let tools = client.list_tools().await.map_err(|error| {
431                WebSearchError::new(format!("could not reach Exa's MCP server at {} ({error})", self.url))
432            })?;
433            let Some(exa) = tools.iter().find(|tool| tool.name() == EXA_TOOL) else {
434                return Err(WebSearchError::new(format!(
435                    "Exa's MCP server does not offer {EXA_TOOL}"
436                )));
437            };
438            let options = McpCallToolOptions {
439                timeout: Some(TIMEOUT),
440                ..McpCallToolOptions::default()
441            };
442            client
443                .call_tool(exa, json!({"query": query, "numResults": max_results}), options)
444                .await
445                .map_err(|error| WebSearchError::new(error.to_string()))
446        }
447    }
448
449    #[async_trait]
450    impl SearchBackend for ExaBackend {
451        async fn search(&self, query: &str, max_results: usize) -> Result<Vec<SearchResult>, WebSearchError> {
452            let key = self.api_key.clone().or_else(|| (self.env)()).unwrap_or_default();
453            match self.call(query, max_results, &key).await {
454                Ok(results) => Ok(results),
455                Err(error) if !key.is_empty() => Err(error),
456                Err(error) => Err(WebSearchError::new(format!(
457                    "{} (Exa's keyless tier is rate limited; set EXA_API_KEY to lift it.)",
458                    error.message()
459                ))),
460            }
461        }
462    }
463
464    /// The `web_search` tool served by Exa; `EXA_API_KEY` is read on every
465    /// call. The harness builds it when `web_search` is set to [`WebSearchSetting::Exa`](super::WebSearchSetting::Exa).
466    ///
467    /// ```
468    /// use strands::Tool;
469    ///
470    /// let tool = strands_harness::tools::web_search::web_search_tool();
471    /// assert_eq!(tool.name(), "web_search");
472    /// ```
473    #[must_use]
474    pub fn web_search_tool() -> FunctionTool {
475        search_tool(Arc::new(ExaBackend::default()))
476    }
477}
478
479#[cfg(test)]
480mod tests;