Skip to main content

matrixcode_core/tools/
webfetch.rs

1use anyhow::Result;
2use async_trait::async_trait;
3use serde_json::{Value, json};
4
5use super::{Tool, ToolDefinition};
6
7pub struct WebFetchTool;
8
9#[async_trait]
10impl Tool for WebFetchTool {
11    fn definition(&self) -> ToolDefinition {
12        ToolDefinition {
13            name: "webfetch".to_string(),
14            description: "Fetch content from a URL and return it as text".to_string(),
15            parameters: json!({
16                "type": "object",
17                "properties": {
18                    "url": {
19                        "type": "string",
20                        "description": "The URL to fetch"
21                    },
22                    "max_length": {
23                        "type": "integer",
24                        "description": "Maximum response length in characters (default 10000)"
25                    }
26                },
27                "required": ["url"]
28            }),
29        }
30    }
31
32    async fn execute(&self, params: Value) -> Result<String> {
33        let url = params["url"].as_str().ok_or_else(|| anyhow::anyhow!("missing 'url'"))?;
34        let max_length = params["max_length"].as_u64().unwrap_or(10000) as usize;
35
36        // Show spinner while fetching - RAII guard ensures cleanup on error
37        // let mut spinner = ToolSpinner::new(&format!("fetching {}", url));
38
39        let response = reqwest::get(url).await?;
40        let status = response.status();
41
42        if !status.is_success() {
43            // spinner.finish_error(&format!("HTTP {}", status));
44            anyhow::bail!("HTTP {} for {}", status, url);
45        }
46
47        let body = response.text().await?;
48
49        let truncated = if body.len() > max_length {
50            // 找到不超过 max_length 的最后一个有效字符边界
51            let end = body.floor_char_boundary(max_length);
52            format!("{}...\n\n(truncated, {} total bytes)", &body[..end], body.len())
53        } else {
54            body
55        };
56
57        // spinner.finish_success(&format!("{} bytes", bytes));
58        Ok(truncated)
59    }
60}