1use super::traits::Tool;
11use crate::config::constants::tools;
12use anyhow::{Context, Result, anyhow, bail};
13use async_trait::async_trait;
14use futures::stream::StreamExt;
15use hashbrown::HashSet;
16use reqwest::header::{ACCEPT, HeaderMap, HeaderValue, USER_AGENT};
17use serde::Deserialize;
18use serde_json::{Value, json};
19use std::path::PathBuf;
20use url::Url;
21use vtcode_commons::VtCodePaths;
22
23pub mod classify_helpers;
24pub mod domains;
25mod errors;
26mod html_preview;
27mod network_guards;
28pub(crate) mod request_budget;
29pub use classify_helpers::extract_http_status;
30pub use domains::{BUILTIN_BLOCKED_DOMAINS, BUILTIN_BLOCKED_PATTERNS, MALICIOUS_PATTERNS};
31use errors::web_fetch_error_response;
32pub(super) use network_guards::is_private_host;
33use network_guards::{domain_matches_allowed, extract_domain};
34
35const DEFAULT_TIMEOUT_SECS: u64 = 30;
36const MAX_CONTENT_SIZE: usize = 500_000; const MAX_ALLOWED_BYTES: usize = 2_000_000; const MAX_ALLOWED_TIMEOUT_SECS: u64 = 120; const TEMP_SUBDIR: &str = "web_fetch";
42
43const TEMP_MAX_AGE_SECS: u64 = 3600;
45
46pub(crate) const WEB_FETCH_DESCRIPTION: &str = "Fetch a remote URL and return the start of the page inline. The result contains `preview` (readable text for HTML pages, else the first 8000 bytes of the body), `preview_kind` (`text` or `raw`), `content_length`, and a `temp_file` path holding the full fetched body; read `temp_file` only when the preview is not enough. The tool does not analyze the page: `prompt` is returned with the result to guide your own reading. Set format=markdown to get cleaned markdown inline from the defuddle.md extraction service instead; that mode allows 1 call per session. For docs domains, try /llms.txt first: for 'abc.com', fetch https://abc.com/llms.txt before the homepage, then traverse linked URLs for relevant Markdown sources. Prefer llms.txt over llms-full.txt, which can be multi-megabyte. A body larger than max_bytes is cut off and the result reports truncated_by_max_bytes and source_size_bytes, so you can retry with a larger max_bytes. Temp files are ephemeral and may be cleaned up after about an hour.";
47
48pub(crate) fn web_fetch_parameter_schema() -> Value {
55 json!({
56 "type": "object",
57 "properties": {
58 "url": {
59 "type": "string",
60 "description": "URL to fetch (HTTPS required by default)"
61 },
62 "prompt": {
63 "type": "string",
64 "description": "Question or instruction describing what to look for in the fetched content. It is returned with the result to guide your analysis; omit it to get a default summarize instruction."
65 },
66 "format": {
67 "type": "string",
68 "enum": ["summary", "markdown"],
69 "description": "Output mode (default: summary). summary fetches the page directly and returns a preview plus a temp_file path. markdown returns the page as cleaned markdown inline via the defuddle.md extraction service; it allows 1 call per session, accepts only remote http(s) URLs, caps max_bytes at 262144, and ignores prompt and timeout_secs."
70 },
71 "max_bytes": {
72 "type": "integer",
73 "description": "Maximum response body size in bytes (default: 500000, max: 2000000). The default fits most pages, including llms.txt, so set this only to raise the limit after a truncated_by_max_bytes result or to cap a very large page."
74 },
75 "timeout_secs": {
76 "type": "integer",
77 "description": "Request timeout in seconds (default: 30, max: 120)"
78 }
79 },
80 "required": ["url"],
81 "additionalProperties": false
82 })
83}
84
85#[derive(Debug, Deserialize)]
86struct WebFetchArgs {
87 url: String,
88 prompt: String,
89 #[serde(default)]
90 max_bytes: Option<usize>,
91 #[serde(default)]
92 timeout_secs: Option<u64>,
93}
94
95#[derive(Clone)]
97pub struct WebFetchTool {
98 pub mode: vtcode_config::WebFetchMode,
100 pub blocked_domains: HashSet<String>,
102 pub blocked_patterns: Vec<String>,
104 pub allowed_domains: HashSet<String>,
106 pub defuddle: crate::tools::defuddle::DefuddleTool,
109 pub strict_https_only: bool,
111}
112
113struct FetchedWebContent {
114 content: String,
115 truncated_by_max_bytes: bool,
116 source_size_bytes: usize,
117}
118
119fn fetched_content_from_bytes(bytes: &[u8], max_bytes: usize) -> Result<FetchedWebContent> {
120 let source_size_bytes = bytes.len();
121 let truncated_by_max_bytes = source_size_bytes > max_bytes;
122 if !truncated_by_max_bytes {
123 return Ok(FetchedWebContent {
124 content: String::from_utf8(bytes.to_vec()).context("Response body is not valid UTF-8")?,
125 truncated_by_max_bytes,
126 source_size_bytes,
127 });
128 }
129
130 let valid_end = match std::str::from_utf8(&bytes[..max_bytes]) {
135 Ok(_) => max_bytes,
136 Err(err) => err.valid_up_to(),
137 };
138
139 let content = String::from_utf8(bytes[..valid_end].to_vec()).context("Response body is not valid UTF-8")?;
140 Ok(FetchedWebContent { content, truncated_by_max_bytes, source_size_bytes })
141}
142
143async fn web_fetch_temp_dir() -> Result<PathBuf> {
146 VtCodePaths::resolve()
147 .context("Could not resolve VT Code cache directory")?
148 .ensure_cache_child_dir(TEMP_SUBDIR)
149 .context("Failed to create web-fetch cache directory")
150}
151
152async fn write_to_temp_file(content: &str, url: &str) -> Result<PathBuf> {
155 let temp_dir = web_fetch_temp_dir().await?;
156 let timestamp = std::time::SystemTime::now()
157 .duration_since(std::time::UNIX_EPOCH)
158 .unwrap_or_default()
159 .as_micros();
160
161 let url_hash = {
163 use std::collections::hash_map::DefaultHasher;
164 use std::hash::{Hash, Hasher};
165 let mut hasher = DefaultHasher::new();
166 url.hash(&mut hasher);
167 format!("{:016x}", hasher.finish())
168 };
169
170 let filename = format!("{url_hash}_{timestamp}.txt");
171 let file_path = temp_dir.join(&filename);
172
173 let bytes = content.as_bytes().to_vec();
174 let write_path = file_path.clone();
175 tokio::task::spawn_blocking(move || VtCodePaths::write_private_file_atomic(&write_path, &bytes))
176 .await
177 .context("web-fetch cache writer task panicked")?
178 .with_context(|| format!("Failed to write temp file: {}", file_path.display()))?;
179
180 Ok(file_path)
181}
182
183pub async fn cleanup_old_web_fetch_temps(max_age_secs: u64) -> Result<usize> {
185 let temp_dir = match web_fetch_temp_dir().await {
186 Ok(d) => d,
187 Err(_) => return Ok(0),
188 };
189
190 if tokio::fs::metadata(&temp_dir).await.is_err() {
191 return Ok(0);
192 }
193
194 let cutoff = std::time::SystemTime::now()
195 .checked_sub(std::time::Duration::from_secs(max_age_secs))
196 .unwrap_or(std::time::UNIX_EPOCH);
197
198 let mut removed = 0;
199 let mut entries = match tokio::fs::read_dir(&temp_dir).await {
200 Ok(e) => e,
201 Err(_) => return Ok(0),
202 };
203
204 while let Some(entry) = entries.next_entry().await.unwrap_or(None) {
205 let path = entry.path();
206 if !path.is_file() {
207 continue;
208 }
209 if let Ok(metadata) = entry.metadata().await
210 && let Ok(modified) = metadata.modified()
211 && modified <= cutoff
212 && tokio::fs::remove_file(&path).await.is_ok()
213 {
214 removed += 1;
215 }
216 }
217
218 if removed > 0 {
219 tracing::info!(count = removed, "Cleaned up old web_fetch temp files");
220 }
221
222 Ok(removed)
223}
224
225impl WebFetchTool {
226 pub fn new() -> Self {
227 Self {
228 mode: vtcode_config::WebFetchMode::Restricted,
229 blocked_domains: HashSet::new(),
230 blocked_patterns: Vec::new(),
231 allowed_domains: HashSet::new(),
232 defuddle: crate::tools::defuddle::DefuddleTool::new(),
233 strict_https_only: true,
234 }
235 }
236
237 pub fn with_config(
239 mode: vtcode_config::WebFetchMode,
240 blocked_domains: Vec<String>,
241 blocked_patterns: Vec<String>,
242 allowed_domains: Vec<String>,
243 strict_https_only: bool,
244 ) -> Self {
245 Self {
246 mode,
247 blocked_domains: blocked_domains.into_iter().collect(),
248 blocked_patterns,
249 allowed_domains: allowed_domains.into_iter().collect(),
250 defuddle: crate::tools::defuddle::DefuddleTool::new(),
251 strict_https_only,
252 }
253 }
254
255 pub fn from_config(config: &vtcode_config::WebFetchConfig) -> Self {
259 Self::with_config(
260 config.mode,
261 config.blocked_domains.clone(),
262 config.blocked_patterns.clone(),
263 config.allowed_domains.clone(),
264 config.strict_https_only,
265 )
266 }
267
268 async fn fetch_url_content(&self, url: &str, max_bytes: usize, timeout_secs: u64) -> Result<FetchedWebContent> {
269 self.validate_url(url)?;
271
272 let budget = request_budget::RequestBudget::current();
273 let redirect_budget = budget.clone();
274 let default_headers = Self::default_headers();
275
276 let blocked_domains = self.blocked_domains.clone();
279 let blocked_patterns = self.blocked_patterns.clone();
280 let allowed_domains = self.allowed_domains.clone();
281 let strict_https = self.strict_https_only;
282 let redirect_policy = reqwest::redirect::Policy::custom(move |attempt| {
283 if attempt.previous().len() >= 5 {
284 return attempt.stop();
285 }
286 let next_url = attempt.url();
287 let next_str = next_url.as_str();
288
289 if strict_https && !next_str.starts_with("https://") {
291 return attempt.stop();
292 }
293
294 if let Ok(domain) = extract_domain(next_str) {
296 if is_private_host(&domain) {
297 return attempt.stop();
298 }
299 let domain_lower = domain.to_ascii_lowercase();
300 if domain_lower.ends_with(".local")
301 || domain_lower.ends_with(".internal")
302 || domain_lower.ends_with(".localhost")
303 || domain_lower.ends_with(".test")
304 || domain_lower.ends_with(".invalid")
305 || domain_lower.ends_with(".home.arpa")
306 {
307 return attempt.stop();
308 }
309 let mut all_blocked = BUILTIN_BLOCKED_DOMAINS.to_vec();
311 all_blocked.extend(blocked_domains.iter().map(|s| s.as_str()));
312 for blocked in &all_blocked {
313 if next_str.to_lowercase().contains(blocked) {
314 return attempt.stop();
315 }
316 }
317 let mut all_patterns = BUILTIN_BLOCKED_PATTERNS.to_vec();
319 all_patterns.extend(blocked_patterns.iter().map(|s| s.as_str()));
320 for pattern in &all_patterns {
321 if next_str.to_lowercase().contains(pattern) {
322 return attempt.stop();
323 }
324 }
325 for allowed in &allowed_domains {
327 if domain_matches_allowed(&domain, allowed) {
328 return follow_with_budget(attempt, redirect_budget.as_ref());
329 }
330 }
331 }
332 follow_with_budget(attempt, redirect_budget.as_ref())
333 });
334
335 let client = vtcode_commons::http::apply_connect_timeout(
336 reqwest::Client::builder()
337 .default_headers(default_headers)
338 .timeout(std::time::Duration::from_secs(timeout_secs))
339 .redirect(redirect_policy),
340 )
341 .build()?;
342
343 let response = fetch_response(&client, url, max_bytes, timeout_secs, budget.as_ref()).await?;
344
345 let content_type = response
346 .headers()
347 .get("content-type")
348 .and_then(|h| h.to_str().ok())
349 .unwrap_or("")
350 .to_string();
351
352 self.validate_content_type(&content_type)?;
354
355 if let Some(content_length) = response.content_length()
364 && content_length > max_bytes as u64
365 {
366 return Err(anyhow!(
367 "Response Content-Length {} exceeds max_bytes {}; refusing to buffer the full body",
368 content_length,
369 max_bytes
370 ));
371 }
372
373 let mut bytes = Vec::with_capacity(max_bytes.min(64 * 1024));
374 let mut stream = response.bytes_stream();
375 let mut max_reached = false;
376 while let Some(chunk) = stream.next().await {
377 let chunk = chunk.context("Failed to read response body")?;
378 if bytes.len() >= max_bytes {
379 max_reached = true;
380 break;
381 }
382 let take = chunk.len().min(max_bytes - bytes.len());
383 bytes.extend_from_slice(&chunk[..take]);
384 }
385
386 let mut fetched = fetched_content_from_bytes(&bytes, max_bytes)?;
387 if max_reached || bytes.len() >= max_bytes {
392 fetched.truncated_by_max_bytes = true;
393 }
394 Ok(fetched)
395 }
396
397 fn validate_url(&self, url: &str) -> Result<()> {
398 let parsed = Url::parse(url).map_err(|error| {
399 anyhow!(
400 "web_fetch only accepts remote HTTP(S) URLs; use read_file or unified_file to read local files: {error}"
401 )
402 })?;
403 if !matches!(parsed.scheme(), "http" | "https") {
404 bail!("web_fetch only accepts remote HTTP(S) URLs; use read_file or unified_file to read local files");
405 }
406
407 if self.strict_https_only && parsed.scheme() != "https" {
409 return Err(anyhow!("Only HTTPS URLs are allowed for security"));
410 }
411
412 let domain = extract_domain(url).map_err(|e| anyhow!("Failed to parse URL for security validation: {e}"))?;
415
416 if is_private_host(&domain) {
418 return Err(anyhow!("Access to local/private networks is blocked"));
419 }
420
421 let domain_lower = domain.to_ascii_lowercase();
429 if domain_lower.ends_with(".local")
430 || domain_lower.ends_with(".internal")
431 || domain_lower.ends_with(".localhost")
432 || domain_lower.ends_with(".test")
433 || domain_lower.ends_with(".invalid")
434 || domain_lower.ends_with(".home.arpa")
435 {
436 return Err(anyhow!("Access to local/private networks is blocked"));
437 }
438
439 let url_lower = url.to_lowercase();
440
441 match self.mode {
443 vtcode_config::WebFetchMode::Whitelist => self.validate_whitelist_mode(&url_lower)?,
444 vtcode_config::WebFetchMode::Restricted => self.validate_restricted_mode(&url_lower)?,
445 }
446
447 Ok(())
448 }
449
450 fn validate_whitelist_mode(&self, url: &str) -> Result<()> {
451 let domain = extract_domain(url)?;
453
454 if self.allowed_domains.is_empty() {
455 return Err(anyhow!(
456 "Whitelist mode enabled but no domains are whitelisted. Configure allowed_domains in web_fetch settings."
457 ));
458 }
459
460 for allowed in &self.allowed_domains {
462 if domain_matches_allowed(&domain, allowed) {
463 return Ok(());
464 }
465 }
466
467 Err(anyhow!(
468 "Domain '{domain}' is not in the whitelist. Only explicitly allowed domains are permitted in whitelist mode."
469 ))
470 }
471
472 fn validate_restricted_mode(&self, url: &str) -> Result<()> {
473 let url_lower = url.to_lowercase();
475
476 let domain = extract_domain(url)?;
478 for allowed in &self.allowed_domains {
479 if domain_matches_allowed(&domain, allowed) {
480 return Ok(());
481 }
482 }
483
484 self.validate_url_safety(&url_lower)?;
486
487 Ok(())
488 }
489
490 fn validate_url_safety(&self, url: &str) -> Result<()> {
491 let mut all_blocked_domains = BUILTIN_BLOCKED_DOMAINS.to_vec();
493 all_blocked_domains.extend(self.blocked_domains.iter().map(|s| s.as_str()));
494
495 let mut all_blocked_patterns = BUILTIN_BLOCKED_PATTERNS.to_vec();
497 all_blocked_patterns.extend(self.blocked_patterns.iter().map(|s| s.as_str()));
498
499 for domain in &all_blocked_domains {
501 if url.contains(domain) {
502 return Err(anyhow!(
503 "Access to sensitive domain '{domain}' is blocked for privacy and security reasons"
504 ));
505 }
506 }
507
508 for pattern in &all_blocked_patterns {
510 if url.contains(pattern) {
511 return Err(anyhow!(
512 "URL contains sensitive pattern '{pattern}'. Fetching URLs with credentials or sensitive data is blocked"
513 ));
514 }
515 }
516
517 self.check_malicious_indicators(url)?;
519
520 Ok(())
521 }
522
523 fn check_malicious_indicators(&self, url: &str) -> Result<()> {
524 for pattern in MALICIOUS_PATTERNS {
525 if url.contains(pattern) {
526 return Err(anyhow!("URL contains potentially malicious pattern. Access blocked for safety"));
527 }
528 }
529
530 Ok(())
531 }
532
533 fn validate_content_type(&self, content_type: &str) -> Result<()> {
534 if content_type.is_empty() {
535 return Ok(());
536 }
537
538 let allowed_types = [
539 "text/html",
540 "text/plain",
541 "text/markdown",
542 "application/json",
543 "application/xml",
544 "text/xml",
545 "application/javascript",
546 "text/css",
547 "text/javascript",
548 "application/xhtml+xml",
549 ];
550
551 let content_type_lower = content_type.to_lowercase();
554 let media_type = content_type_lower.split(';').next().unwrap_or(&content_type_lower).trim();
555
556 if allowed_types.contains(&media_type) {
557 Ok(())
558 } else {
559 Err(anyhow!(
560 "Content type '{content_type}' is not supported. Only text-based content types are allowed."
561 ))
562 }
563 }
564
565 async fn run(&self, raw_args: Value) -> Result<Value> {
566 let args: WebFetchArgs = serde_json::from_value(raw_args)
567 .context("Invalid arguments for web_fetch tool. Provide 'url' (and optionally 'prompt').")?;
568
569 let max_bytes = args.max_bytes.map(|v| v.min(MAX_ALLOWED_BYTES)).unwrap_or(MAX_CONTENT_SIZE);
570 let timeout_secs = args
571 .timeout_secs
572 .map(|v| v.min(MAX_ALLOWED_TIMEOUT_SECS))
573 .unwrap_or(DEFAULT_TIMEOUT_SECS);
574
575 let fetched = match self.fetch_url_content(&args.url, max_bytes, timeout_secs).await {
577 Ok(fetched) => fetched,
578 Err(e) => {
579 return Ok(web_fetch_error_response(&args.url, max_bytes, timeout_secs, &e));
585 }
586 };
587 let content = fetched.content;
588
589 let content_length = content.len();
590
591 if content_length == 0 {
592 return Ok(json!({
593 "error": format!(
594 "web_fetch: no content fetched from '{}'. The URL may be unreachable, returned empty content, or used an unsupported content-type.",
595 args.url
596 ),
597 "url": args.url,
598 "error_type": "empty_content",
599 "next_action": "The host returned an empty body. This may be a bot block, a JS-only page, or a real empty document. Try web_search to confirm the page exists; if it does, the content is probably JavaScript-rendered and you need a different tool."
600 }));
601 }
602
603 let temp_path = write_to_temp_file(&content, &args.url).await?;
606 let temp_path_str = temp_path.to_string_lossy().to_string();
607
608 let preview_limit = 8000;
612 let extracted_text = if html_preview::looks_like_html(&content) {
613 let text = html_preview::extract_text_preview(&content);
614 (!text.is_empty()).then_some(text)
615 } else {
616 None
617 };
618 let (preview, truncated, preview_kind, preview_basis_len) = match extracted_text {
619 Some(text) => {
620 let basis_len = text.len();
621 let truncated = basis_len > preview_limit;
622 let preview = if truncated {
623 vtcode_commons::formatting::truncate_byte_budget(&text, preview_limit, "...")
624 } else {
625 text
626 };
627 (preview, truncated, "text", basis_len)
628 }
629 None => {
630 let truncated = content_length > preview_limit;
631 let preview = if truncated {
632 vtcode_commons::formatting::truncate_byte_budget(&content, preview_limit, "...")
633 } else {
634 content.clone()
635 };
636 (preview, truncated, "raw", content_length)
637 }
638 };
639
640 if let Err(e) = cleanup_old_web_fetch_temps(TEMP_MAX_AGE_SECS).await {
642 tracing::debug!(error = %e, "Periodic web_fetch temp cleanup failed");
643 }
644
645 let mut response = json!({
652 "url": args.url,
653 "prompt": args.prompt,
654 "temp_file": temp_path_str,
655 "preview": preview,
656 "preview_kind": preview_kind,
657 "content_length": content_length,
658 "truncated": truncated,
659 "no_spool": true,
660 "next_action_hint": if preview_kind == "text" {
661 "Analyze the inline `preview` (readable text extracted from the page; scripts and styles removed) using `prompt` and answer the user directly. Only read `temp_file` (raw HTML) if you need content beyond the preview; it is ephemeral and may already be cleaned up."
662 } else {
663 "Analyze the inline `preview` (the start of the page) using `prompt` and answer the user directly. Only read `temp_file` if you need content beyond the preview; it is ephemeral and may already be cleaned up."
664 }
665 });
666
667 if truncated {
669 response["overflow"] = json!(format!("[+{} more characters]", preview_basis_len - preview_limit));
670 }
671
672 if fetched.truncated_by_max_bytes {
673 response["truncated_by_max_bytes"] = json!(true);
674 response["max_bytes"] = json!(max_bytes);
675 response["source_size_bytes"] = json!(fetched.source_size_bytes);
676 response["next_action_hint"] = json!(
677 "Read `temp_file` to get the fetched content. Analyze it using `prompt`. If it does not contain enough detail, retry web_fetch with a larger max_bytes or a more specific URL."
678 );
679 }
680
681 Ok(response)
682 }
683}
684
685impl WebFetchTool {
686 fn default_headers() -> HeaderMap {
690 let mut headers = HeaderMap::new();
691 headers.insert(ACCEPT, HeaderValue::from_static("text/markdown, */*"));
692 headers.insert(USER_AGENT, HeaderValue::from_static("VT Code/1.0 (compatible; web-fetch tool)"));
693 headers
694 }
695}
696
697async fn fetch_response(
698 client: &reqwest::Client,
699 url: &str,
700 max_bytes: usize,
701 timeout_secs: u64,
702 budget: Option<&request_budget::RequestBudget>,
703) -> Result<reqwest::Response> {
704 let transport = match &budget {
705 Some(budget) => Some(budget.lock_transport().await?),
706 None => None,
707 };
708 if let Some(budget) = &budget {
709 budget.admit(&Url::parse(url)?).map_err(|error| anyhow::Error::new(*error))?;
710 }
711 let response = client.get(url).send().await?;
712
713 if !response.status().is_success() {
714 let failure = errors::HttpFetchFailure {
715 status: response.status().as_u16(),
716 retry_after_ms: response
717 .headers()
718 .get(reqwest::header::RETRY_AFTER)
719 .and_then(|value| value.to_str().ok())
720 .and_then(errors::retry_after_ms),
721 };
722 if let Some(budget) = &budget {
723 let error = web_fetch_error_response(response.url().as_str(), max_bytes, timeout_secs, &failure.into());
724 if let Some(mut error) = crate::tools::registry::ToolExecutionError::from_tool_output(&error) {
725 if let Some(context) = error.debug_context.as_mut() {
726 context
727 .metadata
728 .push(("effective_origin".to_owned(), response.url().origin().ascii_serialization()));
729 }
730 return Err(budget.observe(response.url(), error).into());
731 }
732 bail!("failed to classify HTTP response");
733 }
734 return Err(failure.into());
735 }
736 drop(transport);
738 Ok(response)
739}
740
741fn follow_with_budget(
742 attempt: reqwest::redirect::Attempt<'_>,
743 budget: Option<&request_budget::RequestBudget>,
744) -> reqwest::redirect::Action {
745 if let Some(budget) = budget
746 && let Err(error) = budget.admit(attempt.url())
747 {
748 return attempt.error(*error);
749 }
750 attempt.follow()
751}
752
753impl Default for WebFetchTool {
754 fn default() -> Self {
755 Self::new()
756 }
757}
758
759#[async_trait]
760impl Tool for WebFetchTool {
761 async fn execute(&self, mut args: Value) -> Result<Value> {
762 if let Some(url) = args.get("url").and_then(Value::as_str) {
766 let max_bytes = args
767 .get("max_bytes")
768 .and_then(Value::as_u64)
769 .map(|value| value as usize)
770 .unwrap_or(MAX_CONTENT_SIZE);
771 let timeout_secs = args.get("timeout_secs").and_then(Value::as_u64).unwrap_or(DEFAULT_TIMEOUT_SECS);
772 if let Err(error) = self.validate_url(url) {
773 return Ok(web_fetch_error_response(url, max_bytes, timeout_secs, &error));
774 }
775 }
776
777 if let Some(obj) = args.as_object_mut() {
789 let wants_markdown = obj
790 .get("format")
791 .and_then(Value::as_str)
792 .is_some_and(|f| f.eq_ignore_ascii_case("markdown"));
793 if wants_markdown {
794 let mut defuddle_args = serde_json::Map::new();
795 if let Some(url) = obj.get("url").cloned() {
796 defuddle_args.insert("url".to_string(), url);
797 }
798 if let Some(max_bytes) = obj.get("max_bytes").cloned() {
799 defuddle_args.insert("max_bytes".to_string(), max_bytes);
800 }
801 return self.defuddle.execute(Value::Object(defuddle_args)).await;
802 }
803 }
804
805 if let Some(obj) = args.as_object_mut() {
806 let has_url = obj.get("url").is_some_and(Value::is_string);
807 let has_prompt = obj.get("prompt").is_some_and(Value::is_string);
808
809 if has_url && !has_prompt {
810 obj.insert(
811 "prompt".to_string(),
812 json!("Summarize this page concisely. Read the temp_file to get the full content, then focus on the primary purpose, key information, and any actionable details."),
813 );
814 }
815 }
816
817 self.run(args).await
818 }
819
820 fn name(&self) -> &str {
821 tools::WEB_FETCH
822 }
823
824 fn description(&self) -> &str {
825 WEB_FETCH_DESCRIPTION
826 }
827}
828
829#[cfg(test)]
830mod tests;