1mod extract;
5
6use std::sync::{Arc, LazyLock};
7
8use regex::Regex;
9use serde_json::json;
10
11use super::http_request::LazyClient;
12use super::input::InputReader;
13use crate::agent::{Agent, InvocationContext, InvokeOptions};
14use crate::cancel::CancelSignal;
15use crate::error::{Error, Result};
16use crate::models::Model;
17use crate::tools::{FunctionTool, ToolContext, ToolError};
18use crate::types::{ContentBlock, JsonSchema, JsonValue};
19
20static CHARSET: LazyLock<Option<Regex>> =
22 LazyLock::new(|| Regex::new(r#"(?i-u:charset=)(?:"([^"]+)"|'([^']+)'|([^;\s]+))"#).ok());
23
24pub(crate) const DEFAULT_MAX_BYTES: usize = 5 * 1024 * 1024;
26
27pub(crate) const DEFAULT_MAX_CONTENT_CHARS: usize = 50_000;
29
30pub(crate) const WEB_FETCH_DESCRIPTION_MARKDOWN: &str = concat!(
32 "Fetches an HTTP(S) URL and returns its content as clean markdown. ",
33 "HTML pages are converted to markdown with scripts, styles, and noise stripped; ",
34 "other content types are returned as-is."
35);
36
37pub(crate) const WEB_FETCH_DESCRIPTION_AGENTIC: &str = concat!(
39 "Fetches an HTTP(S) URL and answers a prompt about its content. ",
40 "The analyst processes the page directly so the full content never enters ",
41 "the main agent's context. ",
42 "The prompt parameter is required."
43);
44
45const USER_AGENT: &str = "strands-agents-web-fetch/1.0";
46const ACCEPT: &str = "text/html,application/xhtml+xml;q=0.9,*/*;q=0.8";
47const TRUNCATED: &str = "\n\n[content truncated]";
48
49const ANALYST_PROMPT: &str = concat!(
50 "You answer a request about a single fetched web page. Use only the provided ",
51 "content; if it does not contain the answer, say so plainly. Be concise and ",
52 "factual, and preserve concrete details (names, numbers, quotes, links) ",
53 "relevant to the request."
54);
55
56#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
58#[non_exhaustive]
59pub enum WebFetchMode {
60 Markdown,
62 #[default]
64 Agentic,
65}
66
67#[derive(Clone, Default, bon::Builder)]
69#[builder(on(String, into))]
70pub struct MakeWebFetchOptions {
71 pub name: Option<String>,
73 pub description: Option<String>,
75 pub max_bytes: Option<usize>,
77 pub max_content_chars: Option<usize>,
80 pub model: Option<Arc<dyn Model>>,
83 pub mode: Option<WebFetchMode>,
85}
86
87impl std::fmt::Debug for MakeWebFetchOptions {
88 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89 f.debug_struct("MakeWebFetchOptions")
90 .field("name", &self.name)
91 .field("max_bytes", &self.max_bytes)
92 .field("max_content_chars", &self.max_content_chars)
93 .field("model", &self.model.as_ref().map(|model| model.model_id()))
94 .field("mode", &self.mode)
95 .finish_non_exhaustive()
96 }
97}
98
99fn input_schema(mode: WebFetchMode) -> JsonSchema {
100 let url = json!({"type": "string", "description": "URL to fetch. Must be http:// or https://."});
101 match mode {
102 WebFetchMode::Markdown => json!({
103 "type": "object",
104 "properties": {"url": url},
105 "required": ["url"],
106 "additionalProperties": false
107 }),
108 WebFetchMode::Agentic => json!({
109 "type": "object",
110 "properties": {
111 "url": url,
112 "prompt": {"type": "string", "description": "Question or instruction about the page content."}
113 },
114 "required": ["url", "prompt"],
115 "additionalProperties": false
116 }),
117 }
118}
119
120struct Settings {
121 mode: WebFetchMode,
122 max_bytes: usize,
123 max_content_chars: usize,
124 model: Option<Arc<dyn Model>>,
125 client: LazyClient,
126}
127
128#[must_use]
130pub fn web_fetch() -> FunctionTool {
131 build(
132 "web_fetch".to_owned(),
133 WEB_FETCH_DESCRIPTION_AGENTIC.to_owned(),
134 Settings {
135 mode: WebFetchMode::Agentic,
136 max_bytes: DEFAULT_MAX_BYTES,
137 max_content_chars: DEFAULT_MAX_CONTENT_CHARS,
138 model: None,
139 client: LazyClient::default(),
140 },
141 )
142}
143
144pub fn make_web_fetch(options: MakeWebFetchOptions) -> Result<FunctionTool> {
163 make_web_fetch_with(options, LazyClient::default())
164}
165
166pub(crate) fn make_web_fetch_with(options: MakeWebFetchOptions, client: LazyClient) -> Result<FunctionTool> {
167 let mode = options.mode.unwrap_or_default();
168 let max_bytes = options.max_bytes.unwrap_or(DEFAULT_MAX_BYTES);
169 let max_content_chars = options.max_content_chars.unwrap_or(DEFAULT_MAX_CONTENT_CHARS);
170 if max_bytes == 0 {
171 return Err(Error::other("maxBytes must be a positive number, got 0"));
172 }
173 if max_content_chars == 0 {
174 return Err(Error::other("maxContentChars must be a positive number, got 0"));
175 }
176 let description = options.description.unwrap_or_else(|| {
177 match mode {
178 WebFetchMode::Markdown => WEB_FETCH_DESCRIPTION_MARKDOWN,
179 WebFetchMode::Agentic => WEB_FETCH_DESCRIPTION_AGENTIC,
180 }
181 .to_owned()
182 });
183 let name = options.name.unwrap_or_else(|| "web_fetch".to_owned());
184 let settings = Settings {
185 mode,
186 max_bytes,
187 max_content_chars,
188 model: options.model,
189 client,
190 };
191 Ok(build(name, description, settings))
192}
193
194fn build(name: String, description: String, settings: Settings) -> FunctionTool {
195 let schema = input_schema(settings.mode);
196 let settings = Arc::new(settings);
197 FunctionTool::builder(name, description)
198 .input_schema(schema)
199 .callback(move |input, context| {
200 let settings = settings.clone();
201 async move { run(&settings, &input, &context).await.map(JsonValue::String) }
202 })
203}
204
205async fn run(settings: &Settings, input: &JsonValue, context: &ToolContext) -> std::result::Result<String, ToolError> {
206 let mut reader = InputReader::new(input);
207 let url = reader.string("url");
208 let prompt = match settings.mode {
209 WebFetchMode::Agentic => reader.string("prompt"),
210 WebFetchMode::Markdown => None,
211 };
212 reader.finish()?;
213 let url = url.unwrap_or_default();
214 let signal = context.cancel_signal();
215 if settings.mode == WebFetchMode::Markdown {
216 return page_content(settings, url, signal).await;
217 }
218 let prompt = prompt.unwrap_or_default();
219 if prompt.trim().is_empty() {
220 return Err(ToolError::msg("web_fetch: agentic mode requires a non-empty prompt."));
221 }
222 let model = settings
223 .model
224 .clone()
225 .unwrap_or_else(|| context.agent().aux_model().clone());
226 let content = page_content(settings, url, signal).await?;
227 let options = InvokeOptions {
228 cancel_signal: Some(signal.clone()),
229 invocation_context: InvocationContext::auxiliary(context.invocation_context()),
230 ..InvokeOptions::default()
231 };
232 let invoke_prompt = format!("URL: {url}\n\nRequest: {prompt}\n\n--- Content ---\n{content}");
233 analyze(model, invoke_prompt, options)
234 .await
235 .map_err(|error| ToolError::msg(format!("url=<{url}> | web fetch analyst failed: {error}")))
236}
237
238async fn analyze(model: Arc<dyn Model>, prompt: String, options: InvokeOptions) -> Result<String> {
240 let mut analyst = Agent::builder()
241 .model(model)
242 .system_prompt(ANALYST_PROMPT)
243 .printer(false)
244 .build()?;
245 let result = analyst.invoke_with(prompt, options).await?;
246 Ok(result
247 .last_message()
248 .content
249 .iter()
250 .filter_map(|block| match block {
251 ContentBlock::Text(text) => Some(text.text.as_str()),
252 _ => None,
253 })
254 .collect())
255}
256
257async fn page_content(settings: &Settings, url: &str, signal: &CancelSignal) -> std::result::Result<String, ToolError> {
258 let (content_type, raw) = tokio::select! {
259 fetched = fetch_once(&settings.client, url, settings.max_bytes) => fetched?,
260 () = signal.cancelled() => return Err(ToolError::msg("Web fetch tool request cancelled")),
261 };
262 let content_type = content_type.to_lowercase();
263 let content = if content_type.contains("html") || content_type.contains("xml") {
264 extract::html_to_markdown(&raw)
265 } else {
266 raw
267 };
268 Ok(truncate(content, settings.max_content_chars))
269}
270
271fn truncate(content: String, max_chars: usize) -> String {
273 if content.encode_utf16().count() <= max_chars {
274 return content;
275 }
276 let mut units = 0;
277 let end = content
278 .char_indices()
279 .find(|(_, c)| {
280 units += c.len_utf16();
281 units > max_chars
282 })
283 .map_or(content.len(), |(index, _)| index);
284 format!("{}{TRUNCATED}", &content[..end])
285}
286
287async fn fetch_once(
288 client: &LazyClient,
289 url: &str,
290 max_bytes: usize,
291) -> std::result::Result<(String, String), ToolError> {
292 let Ok(parsed) = reqwest::Url::parse(url) else {
293 return Err(ToolError::msg(format!("url=<{url}> | fetch failed: invalid URL")));
294 };
295 if !matches!(parsed.scheme(), "http" | "https") {
296 return Err(ToolError::msg(format!(
297 "url=<{url}> | fetch failed: only http and https URLs are supported"
298 )));
299 }
300 let mut response = client
301 .get()?
302 .get(parsed)
303 .header(reqwest::header::USER_AGENT, USER_AGENT)
304 .header(reqwest::header::ACCEPT, ACCEPT)
305 .send()
306 .await
307 .map_err(|error| ToolError::msg(format!("url=<{url}> | fetch failed: {error}")))?;
308 let status = response.status();
309 if !status.is_success() {
310 return Err(ToolError::msg(format!(
311 "HTTP {} {}: GET {url}",
312 status.as_u16(),
313 status.canonical_reason().unwrap_or_default()
314 )));
315 }
316 let content_type = response
317 .headers()
318 .get(reqwest::header::CONTENT_TYPE)
319 .map(|value| String::from_utf8_lossy(value.as_bytes()).into_owned())
320 .unwrap_or_default();
321 let mut body = Vec::new();
322 while let Some(chunk) = response
323 .chunk()
324 .await
325 .map_err(|error| ToolError::msg(format!("url=<{url}> | fetch failed: {error}")))?
326 {
327 if body.len() + chunk.len() > max_bytes {
328 return Err(ToolError::msg(format!(
329 "Response body exceeded max_bytes={max_bytes}. Refusing to buffer more."
330 )));
331 }
332 body.extend_from_slice(&chunk);
333 }
334 let text = decode(&body, &charset(&content_type));
335 Ok((content_type, text))
336}
337
338fn charset(content_type: &str) -> String {
340 CHARSET
341 .as_ref()
342 .and_then(|pattern| pattern.captures(content_type))
343 .and_then(|captures| captures.get(1).or_else(|| captures.get(2)).or_else(|| captures.get(3)))
344 .map_or_else(|| "utf-8".to_owned(), |value| value.as_str().to_lowercase())
345}
346
347const WINDOWS_1252_LABELS: [&str; 17] = [
349 "ansi_x3.4-1968",
350 "ascii",
351 "cp1252",
352 "cp819",
353 "csisolatin1",
354 "ibm819",
355 "iso-8859-1",
356 "iso-ir-100",
357 "iso8859-1",
358 "iso88591",
359 "iso_8859-1",
360 "iso_8859-1:1987",
361 "l1",
362 "latin1",
363 "us-ascii",
364 "windows-1252",
365 "x-cp1252",
366];
367
368const UTF_16LE_LABELS: [&str; 7] = [
370 "csunicode",
371 "iso-10646-ucs-2",
372 "ucs-2",
373 "unicode",
374 "unicodefeff",
375 "utf-16",
376 "utf-16le",
377];
378
379const UTF_16BE_LABELS: [&str; 2] = ["unicodefffe", "utf-16be"];
381
382const WINDOWS_1252_HIGH: [char; 32] = [
384 '\u{20AC}', '\u{81}', '\u{201A}', '\u{192}', '\u{201E}', '\u{2026}', '\u{2020}', '\u{2021}', '\u{2C6}', '\u{2030}',
385 '\u{160}', '\u{2039}', '\u{152}', '\u{8D}', '\u{17D}', '\u{8F}', '\u{90}', '\u{2018}', '\u{2019}', '\u{201C}',
386 '\u{201D}', '\u{2022}', '\u{2013}', '\u{2014}', '\u{2DC}', '\u{2122}', '\u{161}', '\u{203A}', '\u{153}', '\u{9D}',
387 '\u{17E}', '\u{178}',
388];
389
390fn decode(bytes: &[u8], charset: &str) -> String {
394 match charset {
395 label if WINDOWS_1252_LABELS.contains(&label) => bytes
396 .iter()
397 .map(|&byte| match byte {
398 0x80..=0x9F => WINDOWS_1252_HIGH[usize::from(byte - 0x80)],
399 _ => char::from(byte),
400 })
401 .collect(),
402 label if UTF_16LE_LABELS.contains(&label) || UTF_16BE_LABELS.contains(&label) => {
403 let big_endian = UTF_16BE_LABELS.contains(&label);
404 let units: Vec<u16> = bytes
405 .chunks(2)
406 .map(|pair| {
407 let pair = [pair[0], pair.get(1).copied().unwrap_or_default()];
408 if big_endian {
409 u16::from_be_bytes(pair)
410 } else {
411 u16::from_le_bytes(pair)
412 }
413 })
414 .collect();
415 let text = String::from_utf16_lossy(&units);
416 text.strip_prefix('\u{FEFF}').map(str::to_owned).unwrap_or(text)
417 }
418 _ => {
419 let bytes = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes);
420 String::from_utf8_lossy(bytes).into_owned()
421 }
422 }
423}
424
425#[cfg(test)]
426mod tests;