Skip to main content

vtcode_core/tools/web_fetch/
mod.rs

1//! WebFetch tool for fetching and analyzing web content using AI
2//!
3//! Supports both restricted (blocklist) and whitelist (allowlist) modes
4//! with dynamic configuration loading from vtcode.toml
5//!
6//! Fetched content is written to ephemeral cache files under the user cache
7//! directory's `web-fetch/` path.
8//! and cleaned up periodically. Content is never persisted to the workspace.
9
10use 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;
32use network_guards::{domain_matches_allowed, extract_domain};
33pub(crate) use network_guards::{is_blocked_special_use_tld, is_private_host};
34
35const DEFAULT_TIMEOUT_SECS: u64 = 30;
36const MAX_CONTENT_SIZE: usize = 500_000; // 500KB max content size
37const MAX_ALLOWED_BYTES: usize = 2_000_000; // 2MB hard cap
38const MAX_ALLOWED_TIMEOUT_SECS: u64 = 120; // 2 minutes hard cap
39
40/// Subdirectory under the user cache directory for ephemeral web-fetch artifacts.
41const TEMP_SUBDIR: &str = "web_fetch";
42
43/// Max age in seconds before temp files are cleaned up (1 hour).
44const 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. 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
48/// Parameter schema for `web_fetch`, shared by the distributed builtin
49/// registration and the web tool pack so the two surfaces cannot drift.
50pub(crate) fn web_fetch_parameter_schema() -> Value {
51    json!({
52        "type": "object",
53        "properties": {
54            "url": {
55                "type": "string",
56                "description": "URL to fetch (HTTPS required by default)"
57            },
58            "prompt": {
59                "type": "string",
60                "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."
61            },
62            "max_bytes": {
63                "type": "integer",
64                "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."
65            },
66            "timeout_secs": {
67                "type": "integer",
68                "description": "Request timeout in seconds (default: 30, max: 120)"
69            }
70        },
71        "required": ["url"],
72        "additionalProperties": false
73    })
74}
75
76#[derive(Debug, Deserialize)]
77struct WebFetchArgs {
78    url: String,
79    prompt: String,
80    #[serde(default)]
81    max_bytes: Option<usize>,
82    #[serde(default)]
83    timeout_secs: Option<u64>,
84}
85
86/// WebFetch tool that fetches URL content and processes it with AI
87#[derive(Clone)]
88pub struct WebFetchTool {
89    /// Security mode: restricted (blocklist) or whitelist (allowlist)
90    pub mode: vtcode_config::WebFetchMode,
91    /// Additional blocked domains (merged with builtin)
92    pub blocked_domains: HashSet<String>,
93    /// Additional blocked patterns (merged with builtin)
94    pub blocked_patterns: Vec<String>,
95    /// Allowed domains (for exemptions in restricted mode or primary list in whitelist mode)
96    pub allowed_domains: HashSet<String>,
97    /// Strict HTTPS-only mode
98    pub strict_https_only: bool,
99}
100
101struct FetchedWebContent {
102    content: String,
103    truncated_by_max_bytes: bool,
104    source_size_bytes: usize,
105}
106
107fn fetched_content_from_bytes(bytes: &[u8], max_bytes: usize) -> Result<FetchedWebContent> {
108    let source_size_bytes = bytes.len();
109    let truncated_by_max_bytes = source_size_bytes > max_bytes;
110    if !truncated_by_max_bytes {
111        return Ok(FetchedWebContent {
112            content: String::from_utf8(bytes.to_vec()).context("Response body is not valid UTF-8")?,
113            truncated_by_max_bytes,
114            source_size_bytes,
115        });
116    }
117
118    // Truncate to `max_bytes`, then back off to the nearest valid UTF-8
119    // boundary in a single O(n) pass via `valid_up_to`. The previous per-byte
120    // `end -= 1` loop was O(n^2) on adversarial bodies (e.g. a multi-MB
121    // document whose first max_bytes bytes are not UTF-8-aligned).
122    let valid_end = match std::str::from_utf8(&bytes[..max_bytes]) {
123        Ok(_) => max_bytes,
124        Err(err) => err.valid_up_to(),
125    };
126
127    let content = String::from_utf8(bytes[..valid_end].to_vec()).context("Response body is not valid UTF-8")?;
128    Ok(FetchedWebContent { content, truncated_by_max_bytes, source_size_bytes })
129}
130
131/// Returns the path to the ephemeral temp directory for web_fetch artifacts.
132/// Creates the directory if it doesn't exist.
133async fn web_fetch_temp_dir() -> Result<PathBuf> {
134    VtCodePaths::resolve()
135        .context("Could not resolve VT Code cache directory")?
136        .ensure_cache_child_dir(TEMP_SUBDIR)
137        .context("Failed to create web-fetch cache directory")
138}
139
140/// Write content to an ephemeral temp file and return its path.
141/// Files are named with a timestamp for easy age-based cleanup.
142async fn write_to_temp_file(content: &str, url: &str) -> Result<PathBuf> {
143    let temp_dir = web_fetch_temp_dir().await?;
144    let timestamp = std::time::SystemTime::now()
145        .duration_since(std::time::UNIX_EPOCH)
146        .unwrap_or_default()
147        .as_micros();
148
149    // Create a safe filename from the URL
150    let url_hash = {
151        use std::collections::hash_map::DefaultHasher;
152        use std::hash::{Hash, Hasher};
153        let mut hasher = DefaultHasher::new();
154        url.hash(&mut hasher);
155        format!("{:016x}", hasher.finish())
156    };
157
158    let filename = format!("{url_hash}_{timestamp}.txt");
159    let file_path = temp_dir.join(&filename);
160
161    let bytes = content.as_bytes().to_vec();
162    let write_path = file_path.clone();
163    tokio::task::spawn_blocking(move || VtCodePaths::write_private_file_atomic(&write_path, &bytes))
164        .await
165        .context("web-fetch cache writer task panicked")?
166        .with_context(|| format!("Failed to write temp file: {}", file_path.display()))?;
167
168    Ok(file_path)
169}
170
171/// Clean up old web_fetch temp files.
172pub async fn cleanup_old_web_fetch_temps(max_age_secs: u64) -> Result<usize> {
173    let temp_dir = match web_fetch_temp_dir().await {
174        Ok(d) => d,
175        Err(_) => return Ok(0),
176    };
177
178    if tokio::fs::metadata(&temp_dir).await.is_err() {
179        return Ok(0);
180    }
181
182    let cutoff = std::time::SystemTime::now()
183        .checked_sub(std::time::Duration::from_secs(max_age_secs))
184        .unwrap_or(std::time::UNIX_EPOCH);
185
186    let mut removed = 0;
187    let mut entries = match tokio::fs::read_dir(&temp_dir).await {
188        Ok(e) => e,
189        Err(_) => return Ok(0),
190    };
191
192    while let Some(entry) = entries.next_entry().await.unwrap_or(None) {
193        let path = entry.path();
194        if !path.is_file() {
195            continue;
196        }
197        if let Ok(metadata) = entry.metadata().await
198            && let Ok(modified) = metadata.modified()
199            && modified <= cutoff
200            && tokio::fs::remove_file(&path).await.is_ok()
201        {
202            removed += 1;
203        }
204    }
205
206    if removed > 0 {
207        tracing::info!(count = removed, "Cleaned up old web_fetch temp files");
208    }
209
210    Ok(removed)
211}
212
213impl WebFetchTool {
214    pub fn new() -> Self {
215        Self {
216            mode: vtcode_config::WebFetchMode::Restricted,
217            blocked_domains: HashSet::new(),
218            blocked_patterns: Vec::new(),
219            allowed_domains: HashSet::new(),
220            strict_https_only: true,
221        }
222    }
223
224    /// Create a WebFetchTool with custom configuration
225    pub fn with_config(
226        mode: vtcode_config::WebFetchMode,
227        blocked_domains: Vec<String>,
228        blocked_patterns: Vec<String>,
229        allowed_domains: Vec<String>,
230        strict_https_only: bool,
231    ) -> Self {
232        Self {
233            mode,
234            blocked_domains: blocked_domains.into_iter().collect(),
235            blocked_patterns,
236            allowed_domains: allowed_domains.into_iter().collect(),
237            strict_https_only,
238        }
239    }
240
241    /// Build a `WebFetchTool` from a `WebFetchConfig` value-object. This is
242    /// the entry point the tool registry uses so user-configured
243    /// allow/block lists and HTTPS settings actually take effect.
244    pub fn from_config(config: &vtcode_config::WebFetchConfig) -> Self {
245        Self::with_config(
246            config.mode,
247            config.blocked_domains.clone(),
248            config.blocked_patterns.clone(),
249            config.allowed_domains.clone(),
250            config.strict_https_only,
251        )
252    }
253
254    async fn fetch_url_content(&self, url: &str, max_bytes: usize, timeout_secs: u64) -> Result<FetchedWebContent> {
255        // Validate URL
256        self.validate_url(url)?;
257
258        let budget = request_budget::RequestBudget::current();
259        let redirect_budget = budget.clone();
260        let default_headers = Self::default_headers();
261
262        // Build a redirect policy that validates each redirect target against SSRF rules.
263        // Limits to 5 redirects to bound the chain and re-checks security on each hop.
264        let blocked_domains = self.blocked_domains.clone();
265        let blocked_patterns = self.blocked_patterns.clone();
266        let allowed_domains = self.allowed_domains.clone();
267        let strict_https = self.strict_https_only;
268        let redirect_policy = reqwest::redirect::Policy::custom(move |attempt| {
269            if attempt.previous().len() >= 5 {
270                return attempt.stop();
271            }
272            let next_url = attempt.url();
273            let next_str = next_url.as_str();
274
275            // Re-validate HTTPS if strict mode is on
276            if strict_https && !next_str.starts_with("https://") {
277                return attempt.stop();
278            }
279
280            // Re-validate the redirect target's domain against the same security checks
281            if let Ok(domain) = extract_domain(next_str) {
282                if is_private_host(&domain) {
283                    return attempt.stop();
284                }
285                let domain_lower = domain.to_ascii_lowercase();
286                if domain_lower.ends_with(".local")
287                    || domain_lower.ends_with(".internal")
288                    || domain_lower.ends_with(".localhost")
289                    || domain_lower.ends_with(".test")
290                    || domain_lower.ends_with(".invalid")
291                    || domain_lower.ends_with(".home.arpa")
292                {
293                    return attempt.stop();
294                }
295                // Check blocked domains
296                let mut all_blocked = BUILTIN_BLOCKED_DOMAINS.to_vec();
297                all_blocked.extend(blocked_domains.iter().map(|s| s.as_str()));
298                for blocked in &all_blocked {
299                    if next_str.to_lowercase().contains(blocked) {
300                        return attempt.stop();
301                    }
302                }
303                // Check blocked patterns
304                let mut all_patterns = BUILTIN_BLOCKED_PATTERNS.to_vec();
305                all_patterns.extend(blocked_patterns.iter().map(|s| s.as_str()));
306                for pattern in &all_patterns {
307                    if next_str.to_lowercase().contains(pattern) {
308                        return attempt.stop();
309                    }
310                }
311                // Check allowed domains (exemptions)
312                for allowed in &allowed_domains {
313                    if domain_matches_allowed(&domain, allowed) {
314                        return follow_with_budget(attempt, redirect_budget.as_ref());
315                    }
316                }
317            }
318            follow_with_budget(attempt, redirect_budget.as_ref())
319        });
320
321        let client = vtcode_commons::http::apply_connect_timeout(
322            reqwest::Client::builder()
323                .default_headers(default_headers)
324                .timeout(std::time::Duration::from_secs(timeout_secs))
325                .redirect(redirect_policy),
326        )
327        .build()?;
328
329        let response = fetch_response(&client, url, max_bytes, timeout_secs, budget.as_ref()).await?;
330
331        let content_type = response
332            .headers()
333            .get("content-type")
334            .and_then(|h| h.to_str().ok())
335            .unwrap_or("")
336            .to_string();
337
338        // Validate content type
339        self.validate_content_type(&content_type)?;
340
341        // Limit response body to max_bytes while still returning useful partial
342        // text. Oversized documentation pages are common, and a truncated fetch
343        // gives the agent more signal than an error-only result.
344        //
345        // Reject up-front when Content-Length already exceeds the cap, and
346        // stream `chunk()`s capped at max_bytes instead of buffering the entire
347        // body with `response.bytes()`. This bounds peak memory even for
348        // hostile servers that lie about or omit Content-Length.
349        if let Some(content_length) = response.content_length()
350            && content_length > max_bytes as u64
351        {
352            return Err(anyhow!(
353                "Response Content-Length {} exceeds max_bytes {}; refusing to buffer the full body",
354                content_length,
355                max_bytes
356            ));
357        }
358
359        let mut bytes = Vec::with_capacity(max_bytes.min(64 * 1024));
360        let mut stream = response.bytes_stream();
361        let mut max_reached = false;
362        while let Some(chunk) = stream.next().await {
363            let chunk = chunk.context("Failed to read response body")?;
364            if bytes.len() >= max_bytes {
365                max_reached = true;
366                break;
367            }
368            let take = chunk.len().min(max_bytes - bytes.len());
369            bytes.extend_from_slice(&chunk[..take]);
370        }
371
372        let mut fetched = fetched_content_from_bytes(&bytes, max_bytes)?;
373        // The stream stopped exactly at the cap, so the true body is at least
374        // max_bytes. `fetched_content_from_bytes` compares against `bytes.len()`
375        // and would report "not truncated" for a body that ends precisely at the
376        // cap — override so callers still see the truncation metadata.
377        if max_reached || bytes.len() >= max_bytes {
378            fetched.truncated_by_max_bytes = true;
379        }
380        Ok(fetched)
381    }
382
383    fn validate_url(&self, url: &str) -> Result<()> {
384        let parsed = Url::parse(url).map_err(|error| {
385            anyhow!(
386                "web_fetch only accepts remote HTTP(S) URLs; use read_file or unified_file to read local files: {error}"
387            )
388        })?;
389        if !matches!(parsed.scheme(), "http" | "https") {
390            bail!("web_fetch only accepts remote HTTP(S) URLs; use read_file or unified_file to read local files");
391        }
392
393        // HTTPS enforcement (can be disabled only for testing)
394        if self.strict_https_only && parsed.scheme() != "https" {
395            return Err(anyhow!("Only HTTPS URLs are allowed for security"));
396        }
397
398        // Parse the URL to extract the real host, which correctly separates
399        // userinfo credentials (http://evil@127.0.0.1/) from the host.
400        let domain = extract_domain(url).map_err(|e| anyhow!("Failed to parse URL for security validation: {e}"))?;
401
402        // Reject private, loopback, link-local, and reserved IPs.
403        if is_private_host(&domain) {
404            return Err(anyhow!("Access to local/private networks is blocked"));
405        }
406
407        // Block special-use TLDs per RFC 6761 and mDNS/split-DNS conventions
408        // (shared predicate; also guards the `@<url>` image fetcher).
409        if is_blocked_special_use_tld(&domain) {
410            return Err(anyhow!("Access to local/private networks is blocked"));
411        }
412
413        let url_lower = url.to_lowercase();
414
415        // Apply security policy based on mode
416        match self.mode {
417            vtcode_config::WebFetchMode::Whitelist => self.validate_whitelist_mode(&url_lower)?,
418            vtcode_config::WebFetchMode::Restricted => self.validate_restricted_mode(&url_lower)?,
419        }
420
421        Ok(())
422    }
423
424    fn validate_whitelist_mode(&self, url: &str) -> Result<()> {
425        // In whitelist mode, only explicitly allowed domains are permitted
426        let domain = extract_domain(url)?;
427
428        if self.allowed_domains.is_empty() {
429            return Err(anyhow!(
430                "Whitelist mode enabled but no domains are whitelisted. Configure allowed_domains in web_fetch settings."
431            ));
432        }
433
434        // Check if domain matches any whitelisted domain or pattern
435        for allowed in &self.allowed_domains {
436            if domain_matches_allowed(&domain, allowed) {
437                return Ok(());
438            }
439        }
440
441        Err(anyhow!(
442            "Domain '{domain}' is not in the whitelist. Only explicitly allowed domains are permitted in whitelist mode."
443        ))
444    }
445
446    fn validate_restricted_mode(&self, url: &str) -> Result<()> {
447        // In restricted mode, use a blocklist of known dangerous/sensitive domains
448        let url_lower = url.to_lowercase();
449
450        // Check against allowed exemptions first (exemptions override blocklist)
451        let domain = extract_domain(url)?;
452        for allowed in &self.allowed_domains {
453            if domain_matches_allowed(&domain, allowed) {
454                return Ok(());
455            }
456        }
457
458        // Check for malicious and sensitive URL patterns
459        self.validate_url_safety(&url_lower)?;
460
461        Ok(())
462    }
463
464    fn validate_url_safety(&self, url: &str) -> Result<()> {
465        // Combine built-in and custom blocked domains
466        let mut all_blocked_domains = BUILTIN_BLOCKED_DOMAINS.to_vec();
467        all_blocked_domains.extend(self.blocked_domains.iter().map(|s| s.as_str()));
468
469        // Combine built-in and custom blocked patterns
470        let mut all_blocked_patterns = BUILTIN_BLOCKED_PATTERNS.to_vec();
471        all_blocked_patterns.extend(self.blocked_patterns.iter().map(|s| s.as_str()));
472
473        // Check blocked domains
474        for domain in &all_blocked_domains {
475            if url.contains(domain) {
476                return Err(anyhow!(
477                    "Access to sensitive domain '{domain}' is blocked for privacy and security reasons"
478                ));
479            }
480        }
481
482        // Check for sensitive patterns in URL
483        for pattern in &all_blocked_patterns {
484            if url.contains(pattern) {
485                return Err(anyhow!(
486                    "URL contains sensitive pattern '{pattern}'. Fetching URLs with credentials or sensitive data is blocked"
487                ));
488            }
489        }
490
491        // Check for common malware/phishing indicators
492        self.check_malicious_indicators(url)?;
493
494        Ok(())
495    }
496
497    fn check_malicious_indicators(&self, url: &str) -> Result<()> {
498        for pattern in MALICIOUS_PATTERNS {
499            if url.contains(pattern) {
500                return Err(anyhow!("URL contains potentially malicious pattern. Access blocked for safety"));
501            }
502        }
503
504        Ok(())
505    }
506
507    fn validate_content_type(&self, content_type: &str) -> Result<()> {
508        if content_type.is_empty() {
509            return Ok(());
510        }
511
512        let allowed_types = [
513            "text/html",
514            "text/plain",
515            "text/markdown",
516            "application/json",
517            "application/xml",
518            "text/xml",
519            "application/javascript",
520            "text/css",
521            "text/javascript",
522            "application/xhtml+xml",
523        ];
524
525        // Content-Type headers may include parameters (e.g., "text/html; charset=utf-8").
526        // Extract just the media type (everything before the first ';') for matching.
527        let content_type_lower = content_type.to_lowercase();
528        let media_type = content_type_lower.split(';').next().unwrap_or(&content_type_lower).trim();
529
530        if allowed_types.contains(&media_type) {
531            Ok(())
532        } else {
533            Err(anyhow!(
534                "Content type '{content_type}' is not supported. Only text-based content types are allowed."
535            ))
536        }
537    }
538
539    async fn run(&self, raw_args: Value) -> Result<Value> {
540        let args: WebFetchArgs = serde_json::from_value(raw_args)
541            .context("Invalid arguments for web_fetch tool. Provide 'url' (and optionally 'prompt').")?;
542
543        let max_bytes = args.max_bytes.map(|v| v.min(MAX_ALLOWED_BYTES)).unwrap_or(MAX_CONTENT_SIZE);
544        let timeout_secs = args
545            .timeout_secs
546            .map(|v| v.min(MAX_ALLOWED_TIMEOUT_SECS))
547            .unwrap_or(DEFAULT_TIMEOUT_SECS);
548
549        // Fetch the URL content with detailed error handling
550        let fetched = match self.fetch_url_content(&args.url, max_bytes, timeout_secs).await {
551            Ok(fetched) => fetched,
552            Err(e) => {
553                // Categorize the error so the agent loop can react. We used to
554                // surface a flat string here, which led to the agent in
555                // turn_578 reporting "github.com, npmjs.com, and crates.io are
556                // all blocked" when the actual errors were 403/404 from the
557                // upstream services.
558                return Ok(web_fetch_error_response(&args.url, max_bytes, timeout_secs, &e));
559            }
560        };
561        let content = fetched.content;
562
563        let content_length = content.len();
564
565        if content_length == 0 {
566            return Ok(json!({
567                "error": format!(
568                    "web_fetch: no content fetched from '{}'. The URL may be unreachable, returned empty content, or used an unsupported content-type.",
569                    args.url
570                ),
571                "url": args.url,
572                "error_type": "empty_content",
573                "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."
574            }));
575        }
576
577        // Write content to ephemeral temp file instead of keeping it in the response.
578        // The temp file is auto-cleaned by age-based cleanup.
579        let temp_path = write_to_temp_file(&content, &args.url).await?;
580        let temp_path_str = temp_path.to_string_lossy().to_string();
581
582        // Preview prefers extracted readable text for HTML pages (scripts,
583        // styles, and head metadata removed); other bodies preview raw.
584        // The full body always lands in `temp_file` untouched.
585        let preview_limit = 8000;
586        let extracted_text = if html_preview::looks_like_html(&content) {
587            let text = html_preview::extract_text_preview(&content);
588            (!text.is_empty()).then_some(text)
589        } else {
590            None
591        };
592        let (preview, truncated, preview_kind, preview_basis_len) = match extracted_text {
593            Some(text) => {
594                let basis_len = text.len();
595                let truncated = basis_len > preview_limit;
596                let preview = if truncated {
597                    vtcode_commons::formatting::truncate_byte_budget(&text, preview_limit, "...")
598                } else {
599                    text
600                };
601                (preview, truncated, "text", basis_len)
602            }
603            None => {
604                let truncated = content_length > preview_limit;
605                let preview = if truncated {
606                    vtcode_commons::formatting::truncate_byte_budget(&content, preview_limit, "...")
607                } else {
608                    content.clone()
609                };
610                (preview, truncated, "raw", content_length)
611            }
612        };
613
614        // Cleanup: periodically remove old temp files (every ~50 calls)
615        if let Err(e) = cleanup_old_web_fetch_temps(TEMP_MAX_AGE_SECS).await {
616            tracing::debug!(error = %e, "Periodic web_fetch temp cleanup failed");
617        }
618
619        // Canonical response shape:
620        // - `temp_file`: path to ephemeral temp file containing full fetched body
621        // - `preview`: truncated snippet (8KB by default) for display
622        // - `prompt`: what the user/model wants to know
623        // - `next_action_hint`: explicit instruction so the agent continues the loop correctly
624        // - `no_spool: true` prevents the output spooler from persisting fetched content to disk
625        let mut response = json!({
626            "url": args.url,
627            "prompt": args.prompt,
628            "temp_file": temp_path_str,
629            "preview": preview,
630            "preview_kind": preview_kind,
631            "content_length": content_length,
632            "truncated": truncated,
633            "no_spool": true,
634            "next_action_hint": if preview_kind == "text" {
635                "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."
636            } else {
637                "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."
638            }
639        });
640
641        // Add overflow indicator if preview was truncated
642        if truncated {
643            response["overflow"] = json!(format!("[+{} more characters]", preview_basis_len - preview_limit));
644        }
645
646        if fetched.truncated_by_max_bytes {
647            response["truncated_by_max_bytes"] = json!(true);
648            response["max_bytes"] = json!(max_bytes);
649            response["source_size_bytes"] = json!(fetched.source_size_bytes);
650            response["next_action_hint"] = json!(
651                "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."
652            );
653        }
654
655        Ok(response)
656    }
657}
658
659impl WebFetchTool {
660    /// Returns default headers used by the WebFetch client. This keeps Accept set to
661    /// prefer 'text/markdown' so documentation sites can provide token-efficient markdown
662    /// content as a preference.
663    fn default_headers() -> HeaderMap {
664        let mut headers = HeaderMap::new();
665        headers.insert(ACCEPT, HeaderValue::from_static("text/markdown, */*"));
666        headers.insert(USER_AGENT, HeaderValue::from_static("VT Code/1.0 (compatible; web-fetch tool)"));
667        headers
668    }
669}
670
671async fn fetch_response(
672    client: &reqwest::Client,
673    url: &str,
674    max_bytes: usize,
675    timeout_secs: u64,
676    budget: Option<&request_budget::RequestBudget>,
677) -> Result<reqwest::Response> {
678    let transport = match &budget {
679        Some(budget) => Some(budget.lock_transport().await?),
680        None => None,
681    };
682    if let Some(budget) = &budget {
683        budget.admit(&Url::parse(url)?).map_err(|error| anyhow::Error::new(*error))?;
684    }
685    let response = client.get(url).send().await?;
686
687    if !response.status().is_success() {
688        let failure = errors::HttpFetchFailure {
689            status: response.status().as_u16(),
690            retry_after_ms: response
691                .headers()
692                .get(reqwest::header::RETRY_AFTER)
693                .and_then(|value| value.to_str().ok())
694                .and_then(errors::retry_after_ms),
695        };
696        if let Some(budget) = &budget {
697            let error = web_fetch_error_response(response.url().as_str(), max_bytes, timeout_secs, &failure.into());
698            if let Some(mut error) = crate::tools::registry::ToolExecutionError::from_tool_output(&error) {
699                if let Some(context) = error.debug_context.as_mut() {
700                    context
701                        .metadata
702                        .push(("effective_origin".to_owned(), response.url().origin().ascii_serialization()));
703                }
704                return Err(budget.observe(response.url(), error).into());
705            }
706            bail!("failed to classify HTTP response");
707        }
708        return Err(failure.into());
709    }
710    // Body streaming does not hold the shared header-acquisition permit.
711    drop(transport);
712    Ok(response)
713}
714
715fn follow_with_budget(
716    attempt: reqwest::redirect::Attempt<'_>,
717    budget: Option<&request_budget::RequestBudget>,
718) -> reqwest::redirect::Action {
719    if let Some(budget) = budget
720        && let Err(error) = budget.admit(attempt.url())
721    {
722        return attempt.error(*error);
723    }
724    attempt.follow()
725}
726
727impl Default for WebFetchTool {
728    fn default() -> Self {
729        Self::new()
730    }
731}
732
733#[async_trait]
734impl Tool for WebFetchTool {
735    async fn execute(&self, mut args: Value) -> Result<Value> {
736        // Validate before dispatching to either backend. The markdown path is
737        // a convenience route through Defuddle, but it must have the same
738        // remote-only and SSRF policy as the normal fetch path.
739        if let Some(url) = args.get("url").and_then(Value::as_str) {
740            let max_bytes = args
741                .get("max_bytes")
742                .and_then(Value::as_u64)
743                .map(|value| value as usize)
744                .unwrap_or(MAX_CONTENT_SIZE);
745            let timeout_secs = args.get("timeout_secs").and_then(Value::as_u64).unwrap_or(DEFAULT_TIMEOUT_SECS);
746            if let Err(error) = self.validate_url(url) {
747                return Ok(web_fetch_error_response(url, max_bytes, timeout_secs, &error));
748            }
749        }
750
751        // Backwards-compatible argument normalization:
752        // - If called with only { "url": "..." } (no prompt), interpret as:
753        //   "Fetch this URL and return a concise natural language summary."
754        //
755        // This ensures:
756        // - Simple "fetch https://..." style calls are handled natively by VT Code.
757        // - We do not force upstream agents or MCP tools to construct a full prompt.
758        // - MCP tools like `get_current_time` remain unaffected (they are separate).
759        if let Some(obj) = args.as_object_mut() {
760            let has_url = obj.get("url").is_some_and(Value::is_string);
761            let has_prompt = obj.get("prompt").is_some_and(Value::is_string);
762
763            if has_url && !has_prompt {
764                obj.insert(
765                    "prompt".to_string(),
766                    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."),
767                );
768            }
769        }
770
771        self.run(args).await
772    }
773
774    fn name(&self) -> &str {
775        tools::WEB_FETCH
776    }
777
778    fn description(&self) -> &str {
779        WEB_FETCH_DESCRIPTION
780    }
781}
782
783#[cfg(test)]
784mod tests;