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;
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; // 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. 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
48/// Parameter schema for `web_fetch`, shared by the distributed builtin
49/// registration and the web tool pack so the two surfaces cannot drift.
50///
51/// `format` must be declared here: argument validation rejects unknown
52/// properties (`additionalProperties: false`), so an undeclared `format`
53/// would make the markdown route in [`WebFetchTool::execute`] unreachable.
54pub(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/// WebFetch tool that fetches URL content and processes it with AI
96#[derive(Clone)]
97pub struct WebFetchTool {
98    /// Security mode: restricted (blocklist) or whitelist (allowlist)
99    pub mode: vtcode_config::WebFetchMode,
100    /// Additional blocked domains (merged with builtin)
101    pub blocked_domains: HashSet<String>,
102    /// Additional blocked patterns (merged with builtin)
103    pub blocked_patterns: Vec<String>,
104    /// Allowed domains (for exemptions in restricted mode or primary list in whitelist mode)
105    pub allowed_domains: HashSet<String>,
106    /// Defuddle markdown-extraction backend (used when `format: "markdown"`).
107    /// Shared session-cap state survives clones (Arc counter inside).
108    pub defuddle: crate::tools::defuddle::DefuddleTool,
109    /// Strict HTTPS-only mode
110    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    // Truncate to `max_bytes`, then back off to the nearest valid UTF-8
131    // boundary in a single O(n) pass via `valid_up_to`. The previous per-byte
132    // `end -= 1` loop was O(n^2) on adversarial bodies (e.g. a multi-MB
133    // document whose first max_bytes bytes are not UTF-8-aligned).
134    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
143/// Returns the path to the ephemeral temp directory for web_fetch artifacts.
144/// Creates the directory if it doesn't exist.
145async 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
152/// Write content to an ephemeral temp file and return its path.
153/// Files are named with a timestamp for easy age-based cleanup.
154async 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    // Create a safe filename from the URL
162    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
183/// Clean up old web_fetch temp files.
184pub 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    /// Create a WebFetchTool with custom configuration
238    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    /// Build a `WebFetchTool` from a `WebFetchConfig` value-object. This is
256    /// the entry point the tool registry uses so user-configured
257    /// allow/block lists and HTTPS settings actually take effect.
258    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        // Validate URL
270        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        // Build a redirect policy that validates each redirect target against SSRF rules.
277        // Limits to 5 redirects to bound the chain and re-checks security on each hop.
278        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            // Re-validate HTTPS if strict mode is on
290            if strict_https && !next_str.starts_with("https://") {
291                return attempt.stop();
292            }
293
294            // Re-validate the redirect target's domain against the same security checks
295            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                // Check blocked domains
310                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                // Check blocked patterns
318                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                // Check allowed domains (exemptions)
326                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        // Validate content type
351        self.validate_content_type(&content_type)?;
352
353        // Limit response body to max_bytes while still returning useful partial
354        // text. Oversized documentation pages are common, and a truncated fetch
355        // gives the agent more signal than an error-only result.
356        //
357        // Reject up-front when Content-Length already exceeds the cap, and
358        // stream `chunk()`s capped at max_bytes instead of buffering the entire
359        // body with `response.bytes()`. This bounds peak memory even for
360        // hostile servers that lie about or omit Content-Length.
361        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        // The stream stopped exactly at the cap, so the true body is at least
386        // max_bytes. `fetched_content_from_bytes` compares against `bytes.len()`
387        // and would report "not truncated" for a body that ends precisely at the
388        // cap — override so callers still see the truncation metadata.
389        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        // HTTPS enforcement (can be disabled only for testing)
406        if self.strict_https_only && parsed.scheme() != "https" {
407            return Err(anyhow!("Only HTTPS URLs are allowed for security"));
408        }
409
410        // Parse the URL to extract the real host, which correctly separates
411        // userinfo credentials (http://evil@127.0.0.1/) from the host.
412        let domain = extract_domain(url).map_err(|e| anyhow!("Failed to parse URL for security validation: {e}"))?;
413
414        // Reject private, loopback, link-local, and reserved IPs.
415        if is_private_host(&domain) {
416            return Err(anyhow!("Access to local/private networks is blocked"));
417        }
418
419        // Block special-use TLDs per RFC 6761 and mDNS/split-DNS conventions:
420        // - .local (mDNS)
421        // - .internal (private split-DNS)
422        // - .localhost (loopback)
423        // - .test (testing, RFC 6761)
424        // - .invalid (always fails, RFC 6761)
425        // - .home.arpa (home networking, RFC 7788)
426        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        // Apply security policy based on mode
440        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        // In whitelist mode, only explicitly allowed domains are permitted
450        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        // Check if domain matches any whitelisted domain or pattern
459        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        // In restricted mode, use a blocklist of known dangerous/sensitive domains
472        let url_lower = url.to_lowercase();
473
474        // Check against allowed exemptions first (exemptions override blocklist)
475        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        // Check for malicious and sensitive URL patterns
483        self.validate_url_safety(&url_lower)?;
484
485        Ok(())
486    }
487
488    fn validate_url_safety(&self, url: &str) -> Result<()> {
489        // Combine built-in and custom blocked domains
490        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        // Combine built-in and custom blocked patterns
494        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        // Check blocked domains
498        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        // Check for sensitive patterns in URL
507        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        // Check for common malware/phishing indicators
516        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        // Content-Type headers may include parameters (e.g., "text/html; charset=utf-8").
550        // Extract just the media type (everything before the first ';') for matching.
551        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        // Fetch the URL content with detailed error handling
574        let fetched = match self.fetch_url_content(&args.url, max_bytes, timeout_secs).await {
575            Ok(fetched) => fetched,
576            Err(e) => {
577                // Categorize the error so the agent loop can react. We used to
578                // surface a flat string here, which led to the agent in
579                // turn_578 reporting "github.com, npmjs.com, and crates.io are
580                // all blocked" when the actual errors were 403/404 from the
581                // upstream services.
582                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        // Write content to ephemeral temp file instead of keeping it in the response.
602        // The temp file is auto-cleaned by age-based cleanup.
603        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        // Preview prefers extracted readable text for HTML pages (scripts,
607        // styles, and head metadata removed); other bodies preview raw.
608        // The full body always lands in `temp_file` untouched.
609        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        // Cleanup: periodically remove old temp files (every ~50 calls)
639        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        // Canonical response shape:
644        // - `temp_file`: path to ephemeral temp file containing full fetched body
645        // - `preview`: truncated snippet (8KB by default) for display
646        // - `prompt`: what the user/model wants to know
647        // - `next_action_hint`: explicit instruction so the agent continues the loop correctly
648        // - `no_spool: true` prevents the output spooler from persisting fetched content to disk
649        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        // Add overflow indicator if preview was truncated
666        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    /// Returns default headers used by the WebFetch client. This keeps Accept set to
685    /// prefer 'text/markdown' so documentation sites can provide token-efficient markdown
686    /// content as a preference.
687    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    // Body streaming does not hold the shared header-acquisition permit.
735    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        // Validate before dispatching to either backend. The markdown path is
761        // a convenience route through Defuddle, but it must have the same
762        // remote-only and SSRF policy as the normal fetch path.
763        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        // Backwards-compatible argument normalization:
776        // - If called with only { "url": "..." } (no prompt), interpret as:
777        //   "Fetch this URL and return a concise natural language summary."
778        //
779        // This ensures:
780        // - Simple "fetch https://..." style calls are handled natively by VT Code.
781        // - We do not force upstream agents or MCP tools to construct a full prompt.
782        // - MCP tools like `get_current_time` remain unaffected (they are separate).
783        // `format: "markdown"` routes to the defuddle.md extraction backend
784        // (absorbs the former standalone `defuddle_fetch` tool). Session cap
785        // and URL validation are enforced by the backend itself.
786        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;