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 = reqwest::Client::builder()
336 .default_headers(default_headers)
337 .timeout(std::time::Duration::from_secs(timeout_secs))
338 .redirect(redirect_policy)
339 .build()?;
340
341 let response = fetch_response(&client, url, max_bytes, timeout_secs, budget.as_ref()).await?;
342
343 let content_type = response
344 .headers()
345 .get("content-type")
346 .and_then(|h| h.to_str().ok())
347 .unwrap_or("")
348 .to_string();
349
350 self.validate_content_type(&content_type)?;
352
353 if let Some(content_length) = response.content_length()
362 && content_length > max_bytes as u64
363 {
364 return Err(anyhow!(
365 "Response Content-Length {} exceeds max_bytes {}; refusing to buffer the full body",
366 content_length,
367 max_bytes
368 ));
369 }
370
371 let mut bytes = Vec::with_capacity(max_bytes.min(64 * 1024));
372 let mut stream = response.bytes_stream();
373 let mut max_reached = false;
374 while let Some(chunk) = stream.next().await {
375 let chunk = chunk.context("Failed to read response body")?;
376 if bytes.len() >= max_bytes {
377 max_reached = true;
378 break;
379 }
380 let take = chunk.len().min(max_bytes - bytes.len());
381 bytes.extend_from_slice(&chunk[..take]);
382 }
383
384 let mut fetched = fetched_content_from_bytes(&bytes, max_bytes)?;
385 if max_reached || bytes.len() >= max_bytes {
390 fetched.truncated_by_max_bytes = true;
391 }
392 Ok(fetched)
393 }
394
395 fn validate_url(&self, url: &str) -> Result<()> {
396 let parsed = Url::parse(url).map_err(|error| {
397 anyhow!(
398 "web_fetch only accepts remote HTTP(S) URLs; use read_file or unified_file to read local files: {error}"
399 )
400 })?;
401 if !matches!(parsed.scheme(), "http" | "https") {
402 bail!("web_fetch only accepts remote HTTP(S) URLs; use read_file or unified_file to read local files");
403 }
404
405 if self.strict_https_only && parsed.scheme() != "https" {
407 return Err(anyhow!("Only HTTPS URLs are allowed for security"));
408 }
409
410 let domain = extract_domain(url).map_err(|e| anyhow!("Failed to parse URL for security validation: {e}"))?;
413
414 if is_private_host(&domain) {
416 return Err(anyhow!("Access to local/private networks is blocked"));
417 }
418
419 let domain_lower = domain.to_ascii_lowercase();
427 if domain_lower.ends_with(".local")
428 || domain_lower.ends_with(".internal")
429 || domain_lower.ends_with(".localhost")
430 || domain_lower.ends_with(".test")
431 || domain_lower.ends_with(".invalid")
432 || domain_lower.ends_with(".home.arpa")
433 {
434 return Err(anyhow!("Access to local/private networks is blocked"));
435 }
436
437 let url_lower = url.to_lowercase();
438
439 match self.mode {
441 vtcode_config::WebFetchMode::Whitelist => self.validate_whitelist_mode(&url_lower)?,
442 vtcode_config::WebFetchMode::Restricted => self.validate_restricted_mode(&url_lower)?,
443 }
444
445 Ok(())
446 }
447
448 fn validate_whitelist_mode(&self, url: &str) -> Result<()> {
449 let domain = extract_domain(url)?;
451
452 if self.allowed_domains.is_empty() {
453 return Err(anyhow!(
454 "Whitelist mode enabled but no domains are whitelisted. Configure allowed_domains in web_fetch settings."
455 ));
456 }
457
458 for allowed in &self.allowed_domains {
460 if domain_matches_allowed(&domain, allowed) {
461 return Ok(());
462 }
463 }
464
465 Err(anyhow!(
466 "Domain '{domain}' is not in the whitelist. Only explicitly allowed domains are permitted in whitelist mode."
467 ))
468 }
469
470 fn validate_restricted_mode(&self, url: &str) -> Result<()> {
471 let url_lower = url.to_lowercase();
473
474 let domain = extract_domain(url)?;
476 for allowed in &self.allowed_domains {
477 if domain_matches_allowed(&domain, allowed) {
478 return Ok(());
479 }
480 }
481
482 self.validate_url_safety(&url_lower)?;
484
485 Ok(())
486 }
487
488 fn validate_url_safety(&self, url: &str) -> Result<()> {
489 let mut all_blocked_domains = BUILTIN_BLOCKED_DOMAINS.to_vec();
491 all_blocked_domains.extend(self.blocked_domains.iter().map(|s| s.as_str()));
492
493 let mut all_blocked_patterns = BUILTIN_BLOCKED_PATTERNS.to_vec();
495 all_blocked_patterns.extend(self.blocked_patterns.iter().map(|s| s.as_str()));
496
497 for domain in &all_blocked_domains {
499 if url.contains(domain) {
500 return Err(anyhow!(
501 "Access to sensitive domain '{domain}' is blocked for privacy and security reasons"
502 ));
503 }
504 }
505
506 for pattern in &all_blocked_patterns {
508 if url.contains(pattern) {
509 return Err(anyhow!(
510 "URL contains sensitive pattern '{pattern}'. Fetching URLs with credentials or sensitive data is blocked"
511 ));
512 }
513 }
514
515 self.check_malicious_indicators(url)?;
517
518 Ok(())
519 }
520
521 fn check_malicious_indicators(&self, url: &str) -> Result<()> {
522 for pattern in MALICIOUS_PATTERNS {
523 if url.contains(pattern) {
524 return Err(anyhow!("URL contains potentially malicious pattern. Access blocked for safety"));
525 }
526 }
527
528 Ok(())
529 }
530
531 fn validate_content_type(&self, content_type: &str) -> Result<()> {
532 if content_type.is_empty() {
533 return Ok(());
534 }
535
536 let allowed_types = [
537 "text/html",
538 "text/plain",
539 "text/markdown",
540 "application/json",
541 "application/xml",
542 "text/xml",
543 "application/javascript",
544 "text/css",
545 "text/javascript",
546 "application/xhtml+xml",
547 ];
548
549 let content_type_lower = content_type.to_lowercase();
552 let media_type = content_type_lower.split(';').next().unwrap_or(&content_type_lower).trim();
553
554 if allowed_types.contains(&media_type) {
555 Ok(())
556 } else {
557 Err(anyhow!(
558 "Content type '{content_type}' is not supported. Only text-based content types are allowed."
559 ))
560 }
561 }
562
563 async fn run(&self, raw_args: Value) -> Result<Value> {
564 let args: WebFetchArgs = serde_json::from_value(raw_args)
565 .context("Invalid arguments for web_fetch tool. Provide 'url' (and optionally 'prompt').")?;
566
567 let max_bytes = args.max_bytes.map(|v| v.min(MAX_ALLOWED_BYTES)).unwrap_or(MAX_CONTENT_SIZE);
568 let timeout_secs = args
569 .timeout_secs
570 .map(|v| v.min(MAX_ALLOWED_TIMEOUT_SECS))
571 .unwrap_or(DEFAULT_TIMEOUT_SECS);
572
573 let fetched = match self.fetch_url_content(&args.url, max_bytes, timeout_secs).await {
575 Ok(fetched) => fetched,
576 Err(e) => {
577 return Ok(web_fetch_error_response(&args.url, max_bytes, timeout_secs, &e));
583 }
584 };
585 let content = fetched.content;
586
587 let content_length = content.len();
588
589 if content_length == 0 {
590 return Ok(json!({
591 "error": format!(
592 "web_fetch: no content fetched from '{}'. The URL may be unreachable, returned empty content, or used an unsupported content-type.",
593 args.url
594 ),
595 "url": args.url,
596 "error_type": "empty_content",
597 "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."
598 }));
599 }
600
601 let temp_path = write_to_temp_file(&content, &args.url).await?;
604 let temp_path_str = temp_path.to_string_lossy().to_string();
605
606 let preview_limit = 8000;
610 let extracted_text = if html_preview::looks_like_html(&content) {
611 let text = html_preview::extract_text_preview(&content);
612 (!text.is_empty()).then_some(text)
613 } else {
614 None
615 };
616 let (preview, truncated, preview_kind, preview_basis_len) = match extracted_text {
617 Some(text) => {
618 let basis_len = text.len();
619 let truncated = basis_len > preview_limit;
620 let preview = if truncated {
621 vtcode_commons::formatting::truncate_byte_budget(&text, preview_limit, "...")
622 } else {
623 text
624 };
625 (preview, truncated, "text", basis_len)
626 }
627 None => {
628 let truncated = content_length > preview_limit;
629 let preview = if truncated {
630 vtcode_commons::formatting::truncate_byte_budget(&content, preview_limit, "...")
631 } else {
632 content.clone()
633 };
634 (preview, truncated, "raw", content_length)
635 }
636 };
637
638 if let Err(e) = cleanup_old_web_fetch_temps(TEMP_MAX_AGE_SECS).await {
640 tracing::debug!(error = %e, "Periodic web_fetch temp cleanup failed");
641 }
642
643 let mut response = json!({
650 "url": args.url,
651 "prompt": args.prompt,
652 "temp_file": temp_path_str,
653 "preview": preview,
654 "preview_kind": preview_kind,
655 "content_length": content_length,
656 "truncated": truncated,
657 "no_spool": true,
658 "next_action_hint": if preview_kind == "text" {
659 "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."
660 } else {
661 "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."
662 }
663 });
664
665 if truncated {
667 response["overflow"] = json!(format!("[+{} more characters]", preview_basis_len - preview_limit));
668 }
669
670 if fetched.truncated_by_max_bytes {
671 response["truncated_by_max_bytes"] = json!(true);
672 response["max_bytes"] = json!(max_bytes);
673 response["source_size_bytes"] = json!(fetched.source_size_bytes);
674 response["next_action_hint"] = json!(
675 "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."
676 );
677 }
678
679 Ok(response)
680 }
681}
682
683impl WebFetchTool {
684 fn default_headers() -> HeaderMap {
688 let mut headers = HeaderMap::new();
689 headers.insert(ACCEPT, HeaderValue::from_static("text/markdown, */*"));
690 headers.insert(USER_AGENT, HeaderValue::from_static("VT Code/1.0 (compatible; web-fetch tool)"));
691 headers
692 }
693}
694
695async fn fetch_response(
696 client: &reqwest::Client,
697 url: &str,
698 max_bytes: usize,
699 timeout_secs: u64,
700 budget: Option<&request_budget::RequestBudget>,
701) -> Result<reqwest::Response> {
702 let transport = match &budget {
703 Some(budget) => Some(budget.lock_transport().await?),
704 None => None,
705 };
706 if let Some(budget) = &budget {
707 budget.admit(&Url::parse(url)?).map_err(|error| anyhow::Error::new(*error))?;
708 }
709 let response = client.get(url).send().await?;
710
711 if !response.status().is_success() {
712 let failure = errors::HttpFetchFailure {
713 status: response.status().as_u16(),
714 retry_after_ms: response
715 .headers()
716 .get(reqwest::header::RETRY_AFTER)
717 .and_then(|value| value.to_str().ok())
718 .and_then(errors::retry_after_ms),
719 };
720 if let Some(budget) = &budget {
721 let error = web_fetch_error_response(response.url().as_str(), max_bytes, timeout_secs, &failure.into());
722 if let Some(mut error) = crate::tools::registry::ToolExecutionError::from_tool_output(&error) {
723 if let Some(context) = error.debug_context.as_mut() {
724 context
725 .metadata
726 .push(("effective_origin".to_owned(), response.url().origin().ascii_serialization()));
727 }
728 return Err(budget.observe(response.url(), error).into());
729 }
730 bail!("failed to classify HTTP response");
731 }
732 return Err(failure.into());
733 }
734 drop(transport);
736 Ok(response)
737}
738
739fn follow_with_budget(
740 attempt: reqwest::redirect::Attempt<'_>,
741 budget: Option<&request_budget::RequestBudget>,
742) -> reqwest::redirect::Action {
743 if let Some(budget) = budget
744 && let Err(error) = budget.admit(attempt.url())
745 {
746 return attempt.error(*error);
747 }
748 attempt.follow()
749}
750
751impl Default for WebFetchTool {
752 fn default() -> Self {
753 Self::new()
754 }
755}
756
757#[async_trait]
758impl Tool for WebFetchTool {
759 async fn execute(&self, mut args: Value) -> Result<Value> {
760 if let Some(url) = args.get("url").and_then(Value::as_str) {
764 let max_bytes = args
765 .get("max_bytes")
766 .and_then(Value::as_u64)
767 .map(|value| value as usize)
768 .unwrap_or(MAX_CONTENT_SIZE);
769 let timeout_secs = args.get("timeout_secs").and_then(Value::as_u64).unwrap_or(DEFAULT_TIMEOUT_SECS);
770 if let Err(error) = self.validate_url(url) {
771 return Ok(web_fetch_error_response(url, max_bytes, timeout_secs, &error));
772 }
773 }
774
775 if let Some(obj) = args.as_object_mut() {
787 let wants_markdown = obj
788 .get("format")
789 .and_then(Value::as_str)
790 .is_some_and(|f| f.eq_ignore_ascii_case("markdown"));
791 if wants_markdown {
792 let mut defuddle_args = serde_json::Map::new();
793 if let Some(url) = obj.get("url").cloned() {
794 defuddle_args.insert("url".to_string(), url);
795 }
796 if let Some(max_bytes) = obj.get("max_bytes").cloned() {
797 defuddle_args.insert("max_bytes".to_string(), max_bytes);
798 }
799 return self.defuddle.execute(Value::Object(defuddle_args)).await;
800 }
801 }
802
803 if let Some(obj) = args.as_object_mut() {
804 let has_url = obj.get("url").is_some_and(Value::is_string);
805 let has_prompt = obj.get("prompt").is_some_and(Value::is_string);
806
807 if has_url && !has_prompt {
808 obj.insert(
809 "prompt".to_string(),
810 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."),
811 );
812 }
813 }
814
815 self.run(args).await
816 }
817
818 fn name(&self) -> &str {
819 tools::WEB_FETCH
820 }
821
822 fn description(&self) -> &str {
823 WEB_FETCH_DESCRIPTION
824 }
825}
826
827#[cfg(test)]
828mod tests;