Skip to main content

lc_tools/
url_fetch.rs

1// lc-tools/src/url_fetch.rs
2//! Web page fetching tool
3//!
4//! Provides web content fetching and parsing.
5
6use async_trait::async_trait;
7use regex::Regex;
8use schemars::JsonSchema;
9use serde::{Deserialize, Serialize};
10
11use crate::ssrf::guarded_get;
12use lc_core::tools::{BaseTool, Tool, ToolError};
13
14static SCRIPT_REGEX: std::sync::LazyLock<Regex> = std::sync::LazyLock::new(|| {
15    Regex::new(r"<script[^>]*>.*?</script>").expect("static regex literal must compile")
16});
17
18static STYLE_REGEX: std::sync::LazyLock<Regex> = std::sync::LazyLock::new(|| {
19    Regex::new(r"<style[^>]*>.*?</style>").expect("static regex literal must compile")
20});
21
22static TAG_REGEX: std::sync::LazyLock<Regex> =
23    std::sync::LazyLock::new(|| Regex::new(r"<[^>]+>").expect("static regex literal must compile"));
24
25static WHITESPACE_REGEX: std::sync::LazyLock<Regex> =
26    std::sync::LazyLock::new(|| Regex::new(r"\s+").expect("static regex literal must compile"));
27
28static LINK_REGEX: std::sync::LazyLock<Regex> = std::sync::LazyLock::new(|| {
29    Regex::new(r#"<a[^>]+href\s*=\s*['"]([^'"]+)['"][^>]*>"#)
30        .expect("static regex literal must compile")
31});
32
33static IMG_REGEX: std::sync::LazyLock<Regex> = std::sync::LazyLock::new(|| {
34    Regex::new(r#"<img[^>]+src\s*=\s*['"]([^'"]+)['"][^>]*>"#)
35        .expect("static regex literal must compile")
36});
37
38static TITLE_REGEX: std::sync::LazyLock<Regex> = std::sync::LazyLock::new(|| {
39    Regex::new(r"<title[^>]*>(.*?)</title>").expect("static regex literal must compile")
40});
41
42static DESC_REGEX: std::sync::LazyLock<Regex> = std::sync::LazyLock::new(|| {
43    Regex::new(r#"<meta[^>]+name\s*=\s*['"]description['"][^>]+content\s*=\s*['"]([^'"]+)['"]"#)
44        .expect("static regex literal must compile")
45});
46
47static KW_REGEX: std::sync::LazyLock<Regex> = std::sync::LazyLock::new(|| {
48    Regex::new(r#"<meta[^>]+name\s*=\s*['"]keywords['"][^>]+content\s*=\s*['"]([^'"]+)['"]"#)
49        .expect("static regex literal must compile")
50});
51
52/// Extracts links from HTML and dedups them (preserving first-occurrence order).
53///
54/// Returns `(deduped links, raw count)`. The raw count is used by details to show
55/// "before/after dedup". Q4: the old implementation only renamed the Vec to
56/// `unique_links` without actually deduplicating.
57fn extract_unique_links(html: &str) -> (Vec<String>, usize) {
58    let raw: Vec<String> = LINK_REGEX
59        .captures_iter(html)
60        .map(|cap| cap[1].to_string())
61        .collect();
62    let raw_count = raw.len();
63    let mut seen = std::collections::HashSet::new();
64    let unique: Vec<String> = raw
65        .into_iter()
66        .filter(|link| seen.insert(link.clone()))
67        .collect();
68    (unique, raw_count)
69}
70
71/// URLFetch tool input
72#[derive(Debug, Deserialize, JsonSchema)]
73pub struct URLFetchInput {
74    /// Operation type: "fetch", "extract_text", "extract_links", "extract_images", "metadata"
75    pub operation: String,
76
77    /// The URL
78    pub url: String,
79
80    /// Whether to include header info (for the fetch operation)
81    pub include_headers: Option<bool>,
82
83    /// Maximum content length (bytes)
84    pub max_length: Option<usize>,
85}
86
87/// URLFetch tool output
88#[derive(Debug, Serialize)]
89pub struct URLFetchOutput {
90    /// Operation result
91    pub result: String,
92
93    /// Operation type
94    pub operation: String,
95
96    /// URL
97    pub url: String,
98
99    /// Content length
100    pub content_length: usize,
101
102    /// Extra details
103    pub details: Option<String>,
104}
105
106/// Web page fetching tool
107pub struct URLFetchTool {
108    /// Whether access to private/internal IPs is allowed (default false)
109    allow_private_ips: bool,
110}
111
112impl URLFetchTool {
113    /// Creates a web fetching tool (SSRF protection enabled by default).
114    ///
115    /// The HTTP client is built per request inside `guarded_get` so the
116    /// validated DNS answers can be pinned onto it (A3 DNS-rebinding closure).
117    pub fn new() -> Self {
118        Self {
119            allow_private_ips: false,
120        }
121    }
122
123    /// Allow requests to private/internal IP addresses (SSRF opt-in).
124    pub fn with_allow_private_ips(mut self, allow: bool) -> Self {
125        self.allow_private_ips = allow;
126        self
127    }
128
129    /// Fetches web content
130    async fn fetch_url(
131        &self,
132        url: &str,
133        max_length: Option<usize>,
134        include_headers: Option<bool>,
135    ) -> Result<URLFetchOutput, ToolError> {
136        if !url.starts_with("http://") && !url.starts_with("https://") {
137            return Err(ToolError::InvalidInput(
138                "URL must start with http:// or https://".to_string(),
139            ));
140        }
141
142        // SSRF: guarded_get checks each hop, pins the validated IPs, and follows
143        // redirects manually (both the first hop and every redirect target are
144        // re-resolved and re-checked against intranet addresses).
145        let response = guarded_get(
146            url,
147            !self.allow_private_ips,
148            Some(std::time::Duration::from_secs(30)),
149        )
150        .await?;
151
152        let status = response.status();
153        if !status.is_success() {
154            return Err(ToolError::ExecutionFailed(format!(
155                "HTTP error: {} - {}",
156                status.as_u16(),
157                status.canonical_reason().unwrap_or("unknown")
158            )));
159        }
160
161        // Q3: when include_headers = Some(true), merge the response headers into the output
162        // (details) instead of silently ignoring them. Headers must be read before consuming
163        // the response (reqwest's headers() borrows, text() consumes).
164        let header_block: String = if include_headers.unwrap_or(false) {
165            let mut lines: Vec<String> = response
166                .headers()
167                .iter()
168                .map(|(name, value)| format!("{}: {}", name, value.to_str().unwrap_or("<非UTF-8>")))
169                .collect();
170            lines.sort();
171            let mut block = String::from("响应头:\n");
172            for line in lines {
173                block.push_str(&line);
174                block.push('\n');
175            }
176            block
177        } else {
178            String::new()
179        };
180
181        let content = response
182            .text()
183            .await
184            .map_err(|e| ToolError::ExecutionFailed(format!("failed to read response: {}", e)))?;
185
186        let max_len = max_length.unwrap_or(50000);
187        let content_len = content.len();
188        let truncated = content_len > max_len;
189        let result = if truncated {
190            content.chars().take(max_len).collect::<String>() + "\n... [内容已截断]"
191        } else {
192            content
193        };
194
195        let mut details = format!(
196            "状态码: {}, 内容长度: {} 字节{}",
197            status.as_u16(),
198            content_len,
199            if truncated { " (已截断)" } else { "" }
200        );
201        if !header_block.is_empty() {
202            details.push('\n');
203            details.push_str(&header_block);
204        }
205
206        Ok(URLFetchOutput {
207            result,
208            operation: "fetch".to_string(),
209            url: url.to_string(),
210            content_length: content_len,
211            details: Some(details),
212        })
213    }
214
215    /// Extracts plain text content
216    async fn extract_text(&self, url: &str) -> Result<URLFetchOutput, ToolError> {
217        let fetch_result = self.fetch_url(url, Some(100000), None).await?;
218        let html = &fetch_result.result;
219
220        let html = SCRIPT_REGEX.replace_all(html, "");
221        let html = STYLE_REGEX.replace_all(&html, "");
222
223        let text = TAG_REGEX.replace_all(&html, "");
224
225        let clean_text = WHITESPACE_REGEX.replace_all(&text, " ").trim().to_string();
226
227        let max_len = 5000;
228        let clean_len = clean_text.len();
229        let result = if clean_len > max_len {
230            clean_text.chars().take(max_len).collect::<String>() + "..."
231        } else {
232            clean_text
233        };
234
235        Ok(URLFetchOutput {
236            result,
237            operation: "extract_text".to_string(),
238            url: url.to_string(),
239            content_length: clean_len,
240            details: Some(format!("提取了 {} 字符的纯文本", clean_len)),
241        })
242    }
243
244    /// Extracts links (deduped, first-occurrence order preserved)
245    async fn extract_links(&self, url: &str) -> Result<URLFetchOutput, ToolError> {
246        let fetch_result = self.fetch_url(url, Some(100000), None).await?;
247        let html = &fetch_result.result;
248
249        let (unique_links, raw_count) = extract_unique_links(html);
250        let result = unique_links.join("\n");
251
252        Ok(URLFetchOutput {
253            result,
254            operation: "extract_links".to_string(),
255            url: url.to_string(),
256            content_length: html.len(), // Q4: the real body length, not the link count
257            details: Some(format!(
258                "找到 {} 个唯一链接(原始 {} 个)",
259                unique_links.len(),
260                raw_count
261            )),
262        })
263    }
264
265    /// Extracts image links
266    async fn extract_images(&self, url: &str) -> Result<URLFetchOutput, ToolError> {
267        let fetch_result = self.fetch_url(url, Some(100000), None).await?;
268        let html = &fetch_result.result;
269
270        let images: Vec<String> = IMG_REGEX
271            .captures_iter(html)
272            .map(|cap| cap[1].to_string())
273            .collect();
274
275        let result = images.join("\n");
276
277        Ok(URLFetchOutput {
278            result,
279            operation: "extract_images".to_string(),
280            url: url.to_string(),
281            content_length: images.len(),
282            details: Some(format!("找到 {} 张图片", images.len())),
283        })
284    }
285
286    /// Extracts metadata
287    async fn extract_metadata(&self, url: &str) -> Result<URLFetchOutput, ToolError> {
288        let fetch_result = self.fetch_url(url, Some(50000), None).await?;
289        let html = &fetch_result.result;
290
291        let title = TITLE_REGEX
292            .captures(html)
293            .map(|cap| cap[1].trim().to_string())
294            .unwrap_or_default();
295
296        let description = DESC_REGEX
297            .captures(html)
298            .map(|cap| cap[1].to_string())
299            .unwrap_or_default();
300
301        let keywords = KW_REGEX
302            .captures(html)
303            .map(|cap| cap[1].to_string())
304            .unwrap_or_default();
305
306        let result = format!(
307            "标题: {}\n描述: {}\n关键词: {}",
308            title, description, keywords
309        );
310
311        Ok(URLFetchOutput {
312            result,
313            operation: "metadata".to_string(),
314            url: url.to_string(),
315            content_length: title.len() + description.len() + keywords.len(),
316            details: Some("提取了网页元数据".to_string()),
317        })
318    }
319}
320
321impl Default for URLFetchTool {
322    fn default() -> Self {
323        Self::new()
324    }
325}
326
327#[async_trait]
328impl Tool for URLFetchTool {
329    type Input = URLFetchInput;
330    type Output = URLFetchOutput;
331
332    async fn invoke(&self, input: Self::Input) -> Result<Self::Output, ToolError> {
333        match input.operation.as_str() {
334            "fetch" => {
335                self.fetch_url(&input.url, input.max_length, input.include_headers)
336                    .await
337            }
338            "extract_text" => self.extract_text(&input.url).await,
339            "extract_links" => self.extract_links(&input.url).await,
340            "extract_images" => self.extract_images(&input.url).await,
341            "metadata" => self.extract_metadata(&input.url).await,
342            _ => Err(ToolError::InvalidInput(
343                format!("unsupported operation: {}, use: fetch, extract_text, extract_links, extract_images, metadata", input.operation)
344            )),
345        }
346    }
347}
348
349#[async_trait]
350impl BaseTool for URLFetchTool {
351    fn name(&self) -> &str {
352        "url_fetch"
353    }
354
355    fn description(&self) -> &str {
356        "网页抓取工具。支持多种操作:
357
358操作类型:
359- fetch: 抓取完整网页内容
360- extract_text: 提取纯文本内容(去除HTML标签)
361- extract_links: 提取所有链接
362- extract_images: 提取所有图片链接
363- metadata: 提取网页元数据(标题、描述、关键词)
364
365参数:
366- url: 网页地址(必须以 http:// 或 https:// 开头)
367- max_length: 最大内容长度(可选,默认50KB)
368- include_headers: 是否包含头部信息(可选)
369
370示例:
371- 抓取网页: {\"operation\": \"fetch\", \"url\": \"https://example.com\"}
372- 提取文本: {\"operation\": \"extract_text\", \"url\": \"https://example.com\"}
373- 提取链接: {\"operation\": \"extract_links\", \"url\": \"https://example.com\"}"
374    }
375
376    async fn run(&self, input: String) -> Result<String, ToolError> {
377        let parsed: URLFetchInput = serde_json::from_str(&input)
378            .map_err(|e| ToolError::InvalidInput(format!("JSON parse failed: {}", e)))?;
379
380        let output = self.invoke(parsed).await?;
381
382        Ok(format!(
383            "URL: {}\n操作: {}\n内容长度: {} 字节\n\n{}\n详细信息: {}",
384            output.url,
385            output.operation,
386            output.content_length,
387            output.result,
388            output.details.unwrap_or_default()
389        ))
390    }
391
392    fn args_schema(&self) -> Option<serde_json::Value> {
393        use schemars::schema_for;
394        serde_json::to_value(schema_for!(URLFetchInput)).ok()
395    }
396}
397
398#[cfg(test)]
399mod tests {
400    use super::*;
401
402    #[test]
403    fn test_url_validation() {
404        let valid_url = "https://example.com";
405        assert!(valid_url.starts_with("http://") || valid_url.starts_with("https://"));
406
407        let valid_url2 = "http://example.org";
408        assert!(valid_url2.starts_with("http://") || valid_url2.starts_with("https://"));
409    }
410
411    #[tokio::test]
412    async fn test_url_fetch_invalid_url() {
413        let tool = URLFetchTool::new();
414
415        let input = URLFetchInput {
416            operation: "fetch".to_string(),
417            url: "invalid-url".to_string(),
418            include_headers: None,
419            max_length: None,
420        };
421
422        let result = tool.invoke(input).await;
423        assert!(result.is_err());
424        assert!(result.unwrap_err().to_string().contains("http://"));
425    }
426
427    /// Q4: extract_links truly dedups and preserves first-occurrence order; content_length is the body length.
428    #[test]
429    fn test_extract_unique_links_dedups() {
430        let html = r#"
431            <a href="https://a.com/1">first</a>
432            <a href="https://a.com/1">dup</a>
433            <a href="https://a.com/2">second</a>
434            <a href="https://a.com/1">dup2</a>
435        "#;
436        let (unique, raw) = extract_unique_links(html);
437        assert_eq!(raw, 4, "原始链接数应为 4");
438        assert_eq!(
439            unique,
440            vec!["https://a.com/1".to_string(), "https://a.com/2".to_string()],
441            "应去重且保持首次出现顺序"
442        );
443    }
444
445    /// Q1: after SSRF was extracted into a shared module, URLFetch still blocks intranet addresses by default.
446    #[tokio::test]
447    async fn test_url_fetch_blocks_localhost_by_default() {
448        let tool = URLFetchTool::new();
449        let input = URLFetchInput {
450            operation: "fetch".to_string(),
451            url: "http://127.0.0.1:6379/".to_string(),
452            include_headers: None,
453            max_length: None,
454        };
455        let result = tool.invoke(input).await;
456        assert!(result.is_err());
457        let err = result.unwrap_err().to_string();
458        assert!(err.contains("SSRF"), "expected SSRF error, got: {}", err);
459    }
460
461    /// Q3: when include_headers = Some(true), response headers are merged into the output (details).
462    #[tokio::test]
463    async fn test_fetch_include_headers() {
464        use tokio::io::{AsyncReadExt, AsyncWriteExt};
465        use tokio::net::TcpListener;
466
467        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
468        let addr = listener.local_addr().unwrap();
469
470        let server = tokio::spawn(async move {
471            let (mut socket, _) = listener.accept().await.unwrap();
472            let mut buf = [0u8; 4096];
473            let _ = socket.read(&mut buf).await;
474            let body = "hello world";
475            let resp = format!(
476                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nContent-Type: text/plain\r\nX-Test-Header: hello\r\n\r\n{}",
477                body.len(),
478                body
479            );
480            socket.write_all(resp.as_bytes()).await.unwrap();
481            drop(socket);
482        });
483
484        let tool = URLFetchTool::new().with_allow_private_ips(true);
485        let input = URLFetchInput {
486            operation: "fetch".to_string(),
487            url: format!("http://{}/", addr),
488            include_headers: Some(true),
489            max_length: None,
490        };
491
492        let output = tool.invoke(input).await.unwrap();
493        let details = output.details.unwrap();
494        assert!(details.contains("响应头:"), "details: {}", details);
495        // reqwest normalizes response header names to lowercase (HTTP header names are case-insensitive)
496        assert!(
497            details.contains("x-test-header: hello"),
498            "details: {}",
499            details
500        );
501        assert!(output.result.contains("hello world"));
502        server.await.unwrap();
503    }
504
505    /// Q3: when include_headers = false/None, no response headers are returned.
506    #[tokio::test]
507    async fn test_fetch_without_include_headers() {
508        use tokio::io::{AsyncReadExt, AsyncWriteExt};
509        use tokio::net::TcpListener;
510
511        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
512        let addr = listener.local_addr().unwrap();
513
514        let server = tokio::spawn(async move {
515            let (mut socket, _) = listener.accept().await.unwrap();
516            let mut buf = [0u8; 4096];
517            let _ = socket.read(&mut buf).await;
518            let body = "hello world";
519            let resp = format!(
520                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nX-Test-Header: hello\r\n\r\n{}",
521                body.len(),
522                body
523            );
524            socket.write_all(resp.as_bytes()).await.unwrap();
525            drop(socket);
526        });
527
528        let tool = URLFetchTool::new().with_allow_private_ips(true);
529        let input = URLFetchInput {
530            operation: "fetch".to_string(),
531            url: format!("http://{}/", addr),
532            include_headers: Some(false),
533            max_length: None,
534        };
535
536        let output = tool.invoke(input).await.unwrap();
537        let details = output.details.unwrap();
538        assert!(
539            !details.contains("X-Test-Header"),
540            "不应包含响应头, got: {}",
541            details
542        );
543        server.await.unwrap();
544    }
545
546    #[test]
547    fn test_tool_properties() {
548        let tool = URLFetchTool::new();
549
550        assert_eq!(tool.name(), "url_fetch");
551        assert!(tool.description().contains("fetch"));
552        assert!(BaseTool::args_schema(&tool).is_some());
553    }
554}