web-retrieval 0.3.9

Web fetch and web search MCP tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
// TODO(1): Add optional JS-rendering sidecar for dynamic pages (Playwright/etc.)

use agentic_tools_core::ToolContext;
use agentic_tools_core::error::ToolError;
use chrono::Utc;

use crate::WebTools;
use crate::types::WebFetchInput;
use crate::types::WebFetchOutput;

/// Hard maximum allowed `max_bytes`: 20 MB
pub const HARD_MAX_BYTES: usize = 20 * 1024 * 1024;

/// Execute a web fetch: download URL, convert content, optionally summarize.
///
/// # Errors
/// Returns `ToolError` if the HTTP request fails, the content type is unsupported, or summarization fails.
pub async fn web_fetch(
    tools: &WebTools,
    input: WebFetchInput,
    ctx: &ToolContext,
) -> Result<WebFetchOutput, ToolError> {
    #[expect(clippy::cast_possible_truncation)]
    let default_max_bytes = tools.cfg.default_max_bytes as usize;
    let max_bytes = input.max_bytes.unwrap_or(default_max_bytes);

    if max_bytes > HARD_MAX_BYTES {
        return Err(ToolError::invalid_input(format!(
            "max_bytes must be <= {HARD_MAX_BYTES} (20MB)"
        )));
    }

    if ctx.is_cancelled() {
        return Err(ToolError::cancelled(None));
    }

    // Send GET request
    let mut response = ctx
        .run_cancellable(async {
            tools
                .http
                .get(&input.url)
                .send()
                .await
                .map_err(|e| ToolError::external(format!("HTTP request failed: {e}")))
        })
        .await?;

    let status = response.status();
    if !status.is_success() {
        return Err(ToolError::external(format!(
            "HTTP request failed with status {status} for {}",
            response.url()
        )));
    }

    let final_url = response.url().to_string();
    let content_type = response
        .headers()
        .get(reqwest::header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("")
        .to_string();

    // Download body with size cap (streaming)
    #[expect(clippy::cast_possible_truncation)]
    // max_bytes is already bounded by HARD_MAX_BYTES (20MB)
    let initial_capacity = response
        .content_length()
        .map_or(8 * 1024, |len| len.min(max_bytes as u64) as usize)
        .min(max_bytes);

    let mut bytes: Vec<u8> = Vec::with_capacity(initial_capacity);
    let mut truncated = false;

    loop {
        // Conservative: once we reach the cap, stop without attempting to read more
        if bytes.len() >= max_bytes {
            truncated = true;
            break;
        }

        if ctx.is_cancelled() {
            return Err(ToolError::cancelled(None));
        }

        let Some(chunk) = ctx
            .run_cancellable(async {
                response
                    .chunk()
                    .await
                    .map_err(|e| ToolError::external(format!("Failed to read response body: {e}")))
            })
            .await?
        else {
            break;
        };

        let remaining = max_bytes - bytes.len();
        if chunk.len() > remaining {
            bytes.extend_from_slice(&chunk[..remaining]);
            truncated = true;
            break;
        }

        bytes.extend_from_slice(&chunk);
    }

    // Convert based on content-type
    let (title, content) = decode_and_convert(&bytes, &content_type)?;

    let word_count = content.split_whitespace().count();

    // Optional summarization
    let summary = summarize_content_if_requested(tools, &content, input.summarize, ctx).await?;

    if ctx.is_cancelled() {
        return Err(ToolError::cancelled(None));
    }

    Ok(WebFetchOutput {
        final_url,
        title,
        content_type,
        word_count,
        truncated,
        retrieved_at: Utc::now(),
        content,
        summary,
    })
}

async fn summarize_content_if_requested(
    tools: &WebTools,
    content: &str,
    summarize: bool,
    ctx: &ToolContext,
) -> Result<Option<String>, ToolError> {
    if !summarize {
        return Ok(None);
    }

    match crate::haiku::summarize_markdown(tools, content, ctx).await {
        Ok(summary) => Ok(Some(summary)),
        Err(ToolError::Cancelled { reason }) => Err(ToolError::Cancelled { reason }),
        Err(e) => Err(ToolError::external(format!("Summarization failed: {e}"))),
    }
}

/// Decode bytes and convert to a useful text format based on content-type.
///
/// # Errors
/// Returns `ToolError` if the content type is unsupported or HTML conversion fails.
pub fn decode_and_convert(
    bytes: &[u8],
    content_type: &str,
) -> Result<(Option<String>, String), ToolError> {
    let ct_lower = content_type.to_lowercase();

    // Try to decode as UTF-8
    let text = String::from_utf8_lossy(bytes);

    if ct_lower.contains("text/html") || (ct_lower.is_empty() && looks_like_html(&text)) {
        let title = extract_title(&text);
        let md = htmd::convert(&text)
            .map_err(|e| ToolError::internal(format!("HTML conversion failed: {e}")))?;
        Ok((title, md))
    } else if ct_lower.contains("application/json") || ct_lower.contains("+json") {
        // Pretty-print JSON
        match serde_json::from_str::<serde_json::Value>(&text) {
            Ok(val) => {
                let pretty =
                    serde_json::to_string_pretty(&val).unwrap_or_else(|_| text.into_owned());
                Ok((None, pretty))
            }
            Err(_) => Ok((None, text.into_owned())),
        }
    } else if ct_lower.starts_with("text/") || ct_lower.is_empty() {
        Ok((None, text.into_owned()))
    } else {
        // Binary or unsupported content type
        Err(ToolError::invalid_input(format!(
            "Unsupported content type: {content_type}. Only HTML, text, and JSON are supported."
        )))
    }
}

/// Best-effort `<title>` extraction from HTML.
#[must_use]
pub fn extract_title(html: &str) -> Option<String> {
    let lower = html.to_ascii_lowercase();
    let start = lower.find("<title")?;
    let after_tag = lower[start..].find('>')?;
    let title_start = start + after_tag + 1;
    let title_end = lower[title_start..].find("</title>")?;
    let title = html[title_start..title_start + title_end].trim();
    if title.is_empty() {
        None
    } else {
        Some(title.to_string())
    }
}

/// Simple heuristic to detect HTML content.
fn looks_like_html(text: &str) -> bool {
    let trimmed = text.trim_start();
    trimmed.starts_with("<!DOCTYPE")
        || trimmed.starts_with("<!doctype")
        || trimmed.starts_with("<html")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_decode_html() {
        let html = b"<html><head><title>Test Page</title></head><body><h1>Hello</h1><p>World</p></body></html>";
        let (title, content) = decode_and_convert(html, "text/html").unwrap();
        assert_eq!(title.as_deref(), Some("Test Page"));
        assert!(content.contains("Hello"));
        assert!(content.contains("World"));
    }

    #[test]
    fn test_decode_json() {
        let json = br#"{"key":"value","num":42}"#;
        let (title, content) = decode_and_convert(json, "application/json").unwrap();
        assert!(title.is_none());
        assert!(content.contains("\"key\": \"value\""));
    }

    #[test]
    fn test_decode_plain_text() {
        let text = b"Hello, world!";
        let (title, content) = decode_and_convert(text, "text/plain").unwrap();
        assert!(title.is_none());
        assert_eq!(content, "Hello, world!");
    }

    #[test]
    fn test_decode_binary_errors() {
        let bytes = b"\x00\x01\x02";
        let result = decode_and_convert(bytes, "application/octet-stream");
        assert!(result.is_err());
    }

    #[test]
    fn test_extract_title() {
        assert_eq!(
            extract_title("<html><head><title>My Page</title></head></html>"),
            Some("My Page".into())
        );
        assert_eq!(extract_title("<html><head></head></html>"), None);
        assert_eq!(extract_title("<title></title>"), None);
    }

    #[test]
    fn test_looks_like_html() {
        assert!(looks_like_html("<!DOCTYPE html><html>"));
        assert!(looks_like_html("  <html>"));
        assert!(!looks_like_html("Hello, world!"));
    }

    #[test]
    fn test_extract_title_unicode_before_tag() {
        // Turkish İ (2→3 bytes under to_lowercase) would panic or corrupt with old code
        assert_eq!(
            extract_title("İ<title>Test Page</title>"),
            Some("Test Page".to_string())
        );
    }

    #[test]
    fn test_extract_title_mixed_case_tags() {
        // Verify ASCII case-insensitivity still works
        assert_eq!(
            extract_title("<TITLE>Upper</TITLE>"),
            Some("Upper".to_string())
        );
        assert_eq!(
            extract_title("<TiTlE>Mixed</TiTlE>"),
            Some("Mixed".to_string())
        );
    }

    mod integration {
        use super::*;
        use crate::WebTools;
        use crate::types::WebFetchInput;
        use agentic_tools_core::ToolContext;
        use wiremock::Mock;
        use wiremock::MockServer;
        use wiremock::ResponseTemplate;
        use wiremock::matchers::method;

        #[tokio::test]
        async fn web_fetch_returns_error_on_404() {
            let mock_server = MockServer::start().await;

            Mock::given(method("GET"))
                .respond_with(ResponseTemplate::new(404).set_body_string("Not Found"))
                .mount(&mock_server)
                .await;

            let http = reqwest::Client::new();
            let tools = WebTools::with_http_client(http);

            let input = WebFetchInput {
                url: mock_server.uri(),
                summarize: false,
                max_bytes: None,
            };

            let result = web_fetch(&tools, input, &ToolContext::default()).await;
            assert!(result.is_err(), "Expected error for 404 response");
            let err = result.unwrap_err();
            assert!(
                err.to_string().contains("404"),
                "Error message should mention 404 status"
            );
        }

        #[tokio::test]
        async fn web_fetch_returns_error_on_500() {
            let mock_server = MockServer::start().await;

            Mock::given(method("GET"))
                .respond_with(ResponseTemplate::new(500).set_body_string("Internal Server Error"))
                .mount(&mock_server)
                .await;

            let http = reqwest::Client::new();
            let tools = WebTools::with_http_client(http);

            let input = WebFetchInput {
                url: mock_server.uri(),
                summarize: false,
                max_bytes: None,
            };

            let result = web_fetch(&tools, input, &ToolContext::default()).await;
            assert!(result.is_err(), "Expected error for 500 response");
            let err = result.unwrap_err();
            assert!(
                err.to_string().contains("500"),
                "Error message should mention 500 status"
            );
        }

        #[tokio::test]
        async fn web_fetch_succeeds_on_200() {
            let mock_server = MockServer::start().await;

            Mock::given(method("GET"))
                .respond_with(
                    ResponseTemplate::new(200)
                        .set_body_string("Hello, world!")
                        .insert_header("Content-Type", "text/plain"),
                )
                .mount(&mock_server)
                .await;

            let http = reqwest::Client::new();
            let tools = WebTools::with_http_client(http);

            let input = WebFetchInput {
                url: mock_server.uri(),
                summarize: false,
                max_bytes: None,
            };

            let result = web_fetch(&tools, input, &ToolContext::default()).await;
            assert!(result.is_ok(), "Expected success for 200 response");
            let output = result.unwrap();
            assert_eq!(output.content, "Hello, world!");
        }

        #[tokio::test]
        async fn web_fetch_detects_html_without_content_type() {
            let mock_server = MockServer::start().await;

            let html = b"<!DOCTYPE html><html><head><title>Test Page</title></head><body><p>Hello</p></body></html>";

            // HTML response with NO Content-Type header (misconfigured server)
            // Use set_body_bytes to avoid wiremock's automatic text/plain Content-Type
            Mock::given(method("GET"))
                .respond_with(ResponseTemplate::new(200).set_body_bytes(html.as_slice()))
                .mount(&mock_server)
                .await;

            let http = reqwest::Client::new();
            let tools = WebTools::with_http_client(http);

            let input = WebFetchInput {
                url: mock_server.uri(),
                summarize: false,
                max_bytes: None,
            };

            let result = web_fetch(&tools, input, &ToolContext::default()).await;
            assert!(
                result.is_ok(),
                "Expected success for HTML without Content-Type"
            );
            let output = result.unwrap();

            // Verify content_type is empty (no header)
            assert!(
                output.content_type.is_empty(),
                "Content-Type should be empty, got: {}",
                output.content_type
            );

            // Verify HTML heuristic detected the content and converted to markdown
            assert_eq!(
                output.title.as_deref(),
                Some("Test Page"),
                "Should extract title via looks_like_html heuristic"
            );
            assert!(
                output.content.contains("Hello"),
                "Content should be converted"
            );
            assert!(
                !output.content.contains("<p>"),
                "HTML tags should be removed by markdown conversion"
            );
        }

        #[tokio::test]
        async fn web_fetch_returns_cancelled_before_sending_request() {
            let mock_server = MockServer::start().await;
            let http = reqwest::Client::new();
            let tools = WebTools::with_http_client(http);
            let ctx = ToolContext::default();
            ctx.cancellation_token().cancel();

            let input = WebFetchInput {
                url: mock_server.uri(),
                summarize: false,
                max_bytes: None,
            };

            let result = web_fetch(&tools, input, &ctx).await;
            assert!(matches!(result, Err(ToolError::Cancelled { .. })));
            assert!(mock_server.received_requests().await.unwrap().is_empty());
        }

        #[tokio::test]
        async fn summarization_preserves_cancelled_error() {
            let tools = WebTools::with_http_client(reqwest::Client::new());
            let ctx = ToolContext::default();
            ctx.cancellation_token().cancel();

            let result = summarize_content_if_requested(&tools, "content", true, &ctx).await;

            assert!(matches!(result, Err(ToolError::Cancelled { .. })));
        }
    }
}