merry-tools 0.1.4

Workspace file, search, patch, web fetch, and document tools for the Merry agent runtime.
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
//! Lightweight HTTP fetcher with dual-gate SSRF protection and HTML-to-Markdown conversion.

use crate::ssrf::{check_ssrf_url, check_ssrf_url_static, is_explicit_local_host, strip_brackets};
use merry_core::{ErrorInfo, PendingToolCall};
use merry_runtime::{
    LivePolicyHandle, NetworkAccessDecision, PermissionedAction, RegisteredTool,
    RequestedCapability, ToolActionKind, ToolBuildError, ToolExecutionContext, ToolExecutionError,
    ToolExecutionOutcome, ToolExecutor, ToolExecutorFuture, ToolPermissionRequirement,
    normalize_network_domain,
};
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::json;
use std::{net::SocketAddr, sync::Arc, time::Duration};
use url::Url;

mod html;

/// Registered tool name for lightweight HTTP/HTML fetching.
pub const WEB_FETCH_TOOL: &str = "web_fetch";

const DEFAULT_TIMEOUT_SECS: u64 = 20;
const DEFAULT_MAX_RESPONSE_BYTES: usize = 2 * 1024 * 1024;
const DEFAULT_MAX_OUTPUT_CHARS: usize = 32_000;
const MAX_REDIRECTS: usize = 10;

/// Configuration for [`WebFetchTool`].
#[derive(Debug, Clone)]
pub struct WebFetchConfig {
    allow_local: bool,
    timeout: Duration,
    max_response_bytes: usize,
    max_output_chars: usize,
    live_network_policy: Option<LivePolicyHandle>,
}

impl Default for WebFetchConfig {
    fn default() -> Self {
        Self {
            allow_local: true,
            timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
            max_response_bytes: DEFAULT_MAX_RESPONSE_BYTES,
            max_output_chars: DEFAULT_MAX_OUTPUT_CHARS,
            live_network_policy: None,
        }
    }
}

impl WebFetchConfig {
    /// Sets whether explicit loopback targets (`localhost`, `127.0.0.1`, `::1`) are permitted.
    #[must_use]
    pub fn with_allow_local(mut self, allow_local: bool) -> Self {
        self.allow_local = allow_local;
        self
    }

    /// Attaches the live unified [`LivePolicyHandle`] shared with
    /// session permissions, workspace `allowed_domains`, and `network` policy.
    #[must_use]
    pub fn with_live_network_policy(mut self, policy: LivePolicyHandle) -> Self {
        self.live_network_policy = Some(policy);
        self
    }

    /// Overrides the per-request timeout.
    #[must_use]
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Overrides the maximum response body size downloaded in bytes.
    #[must_use]
    pub fn with_max_response_bytes(mut self, max_response_bytes: usize) -> Self {
        self.max_response_bytes = max_response_bytes;
        self
    }

    /// Overrides the maximum model-visible output characters.
    #[must_use]
    pub fn with_max_output_chars(mut self, max_output_chars: usize) -> Self {
        self.max_output_chars = max_output_chars;
        self
    }
}

#[merry_tools_macros::tool(
    crate = "crate",
    name = "web_fetch",
    description = "Fetch a static web page, API JSON endpoint, or plain text document over HTTP/HTTPS and return clean extracted Markdown or text. Use this instead of browser tools when reading documentation or non-interactive URLs. Authenticated or private URLs fail. An SSRF refusal is final for that URL. Cross-host redirects stop and return the redirect URL instead of following automatically."
)]
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct WebFetchInput {
    #[schemars(
        description = "Target http:// or https:// URL to fetch.",
        length(min = 1)
    )]
    url: String,
    #[serde(default)]
    #[schemars(
        description = "Optional maximum character length for returned extracted content.",
        range(min = 100)
    )]
    max_chars: Option<usize>,
}

/// Built-in SSRF-guarded HTTP/HTML fetch tool.
#[derive(Debug, Clone)]
pub struct WebFetchTool {
    config: Arc<WebFetchConfig>,
}

impl WebFetchTool {
    /// Creates a `web_fetch` tool with the supplied configuration.
    #[must_use]
    pub fn new(config: WebFetchConfig) -> Self {
        Self {
            config: Arc::new(config),
        }
    }

    /// Converts this tool into a registered runtime tool.
    pub fn into_registered_tool(self) -> Result<RegisteredTool, ToolBuildError> {
        let spec = WebFetchInput::tool_spec()?;
        Ok(
            RegisteredTool::new(spec, Arc::new(self), ToolActionKind::Network)
                .with_permissioned_network_lane()
                .with_parallel_safe_execution(),
        )
    }
}

impl Default for WebFetchTool {
    fn default() -> Self {
        Self::new(WebFetchConfig::default())
    }
}

impl ToolExecutor for WebFetchTool {
    fn execute<'a>(
        &'a self,
        call: PendingToolCall,
        context: ToolExecutionContext,
    ) -> ToolExecutorFuture<'a> {
        Box::pin(async move {
            if context.cancellation_token().is_cancelled() {
                return Err(ToolExecutionError::Cancelled);
            }
            let input: WebFetchInput = match call.arguments().deserialize_as() {
                Ok(input) => input,
                Err(error) => {
                    return Ok(web_fetch_failed(
                        "web_fetch_invalid_arguments",
                        format!("invalid web_fetch arguments: {error}"),
                        None,
                    ));
                }
            };
            tokio::select! {
                biased;
                () = context.cancellation_token().cancelled() => Err(ToolExecutionError::Cancelled),
                result = execute_fetch(&self.config, input, context.approved_network_domains()) => result,
            }
        })
    }
}

async fn execute_fetch(
    config: &WebFetchConfig,
    input: WebFetchInput,
    approved_once_domains: &[String],
) -> Result<ToolExecutionOutcome, ToolExecutionError> {
    let mut url = match Url::parse(input.url.trim()) {
        Ok(url) => url,
        Err(error) => {
            return Ok(web_fetch_failed(
                "web_fetch_invalid_url",
                format!("invalid URL {:?}: {error}", input.url),
                None,
            ));
        }
    };

    if url.scheme() == "http"
        && let Some(host) = url.host_str()
        && !is_explicit_local_host(host)
    {
        let _ = url.set_scheme("https");
    }

    let effective_allow_local = config.allow_local
        && config
            .live_network_policy
            .as_ref()
            .is_none_or(LivePolicyHandle::network_allow_local);

    // 1. Unbypassable static SSRF checks before any policy prompt or DNS lookup.
    if let Err(reason) = check_ssrf_url_static(&url, effective_allow_local) {
        return Ok(web_fetch_failed(
            "web_fetch_ssrf_blocked",
            reason,
            Some(url.as_str()),
        ));
    }

    // 2. Unified network & domain admission before issuing DNS or HTTP traffic.
    if let Some(policy) = config.live_network_policy.as_ref()
        && let Some(raw_host) = url.host_str()
    {
        match policy.evaluate_network_host(raw_host, approved_once_domains) {
            NetworkAccessDecision::Allow => {}
            NetworkAccessDecision::Deny => {
                return Ok(web_fetch_failed(
                    "web_fetch_network_denied",
                    format!(
                        "outbound network access to {:?} is denied by current network policy",
                        raw_host
                    ),
                    Some(url.as_str()),
                ));
            }
            NetworkAccessDecision::RequireReview => {
                let normalized_host =
                    normalize_network_domain(raw_host).unwrap_or_else(|| raw_host.to_owned());
                return Err(ToolExecutionError::permission_required(
                    ToolPermissionRequirement::new(
                        PermissionedAction::NetworkUrl {
                            tool: WEB_FETCH_TOOL.to_owned(),
                            url: url.to_string(),
                            host: normalized_host.clone(),
                        },
                        vec![RequestedCapability::NetworkDomain(normalized_host)],
                        Some(format!("Fetch {url}")),
                    ),
                ));
            }
        }
    }

    // 3. Full DNS-resolving SSRF gate and pinned connection.
    let initial_addrs = match check_ssrf_url(&url, effective_allow_local).await {
        Ok(addrs) => addrs,
        Err(reason) => {
            return Ok(web_fetch_failed(
                "web_fetch_ssrf_blocked",
                reason,
                Some(url.as_str()),
            ));
        }
    };

    let client = match build_pinned_client(config, &url, &initial_addrs) {
        Ok(client) => client,
        Err(error) => {
            return Ok(web_fetch_failed(
                "web_fetch_client_error",
                error,
                Some(url.as_str()),
            ));
        }
    };

    let mut current_url = url.clone();
    let response = match follow_same_host_redirects(
        &client,
        effective_allow_local,
        &mut current_url,
    )
    .await
    {
        Ok(RedirectStep::Response(resp)) => resp,
        Ok(RedirectStep::CrossHostRedirect {
            status_code,
            redirect_url,
        }) => {
            let summary = format!(
                "Stopped at cross-host redirect ({status_code}) from {current_url} to {redirect_url}. Inspect the destination URL and fetch it directly if intended."
            );
            return Ok(ToolExecutionOutcome::succeeded_text(summary));
        }
        Err(outcome) => return Ok(*outcome),
    };

    let status_code = response.status().as_u16();
    let content_type = response
        .headers()
        .get(reqwest::header::CONTENT_TYPE)
        .and_then(|value| value.to_str().ok())
        .map(str::to_owned);

    let (raw_bytes, body_truncated) =
        match read_bounded_body(response, config.max_response_bytes).await {
            Ok(data) => data,
            Err(error) => {
                return Ok(web_fetch_failed(
                    "web_fetch_read_failed",
                    error,
                    Some(current_url.as_str()),
                ));
            }
        };

    let (title, full_extracted) = format_response_content(&raw_bytes, content_type.as_deref());
    let limit = input
        .max_chars
        .unwrap_or(config.max_output_chars)
        .min(config.max_output_chars);
    let (model_body, text_truncated) = truncate_chars(&full_extracted, limit);
    let truncated = body_truncated || text_truncated;

    if status_code >= 400 {
        let detail = format!("HTTP {status_code} fetching {current_url}\n\n{model_body}");
        return Ok(web_fetch_failed(
            "web_fetch_http_error",
            detail,
            Some(current_url.as_str()),
        ));
    }

    let mut model_summary = format!("URL: {current_url}\nStatus: {status_code}\n");
    if let Some(title_text) = title.as_deref() {
        model_summary.push_str(&format!("Title: {title_text}\n"));
    }
    model_summary.push('\n');
    model_summary.push_str(&model_body);
    if truncated {
        model_summary.push_str("\n\n[truncated]");
    }

    Ok(ToolExecutionOutcome::succeeded_text(model_summary))
}

enum RedirectStep {
    Response(reqwest::Response),
    CrossHostRedirect {
        status_code: u16,
        redirect_url: String,
    },
}

async fn follow_same_host_redirects(
    client: &reqwest::Client,
    allow_local: bool,
    current_url: &mut Url,
) -> Result<RedirectStep, Box<ToolExecutionOutcome>> {
    for hop in 0..=MAX_REDIRECTS {
        let response = client
            .get(current_url.clone())
            .send()
            .await
            .map_err(|error| {
                Box::new(web_fetch_failed(
                    "web_fetch_request_failed",
                    format!("HTTP request failed: {error}"),
                    Some(current_url.as_str()),
                ))
            })?;
        let status = response.status();
        if !status.is_redirection() {
            return Ok(RedirectStep::Response(response));
        }
        let Some(location) = response
            .headers()
            .get(reqwest::header::LOCATION)
            .and_then(|value| value.to_str().ok())
        else {
            return Ok(RedirectStep::Response(response));
        };
        let next_url = current_url.join(location).map_err(|error| {
            Box::new(web_fetch_failed(
                "web_fetch_invalid_redirect",
                format!("invalid redirect location {location:?}: {error}"),
                Some(current_url.as_str()),
            ))
        })?;
        let https_downgrade = current_url.scheme() == "https"
            && next_url.scheme() == "http"
            && !next_url.host_str().is_some_and(is_explicit_local_host);
        if !same_host(current_url, &next_url) || https_downgrade {
            return Ok(RedirectStep::CrossHostRedirect {
                status_code: status.as_u16(),
                redirect_url: next_url.to_string(),
            });
        }
        if hop == MAX_REDIRECTS {
            return Err(Box::new(web_fetch_failed(
                "web_fetch_too_many_redirects",
                format!("exceeded {MAX_REDIRECTS} same-host redirects"),
                Some(next_url.as_str()),
            )));
        }
        if let Err(reason) = check_ssrf_url(&next_url, allow_local).await {
            return Err(Box::new(web_fetch_failed(
                "web_fetch_ssrf_blocked",
                reason,
                Some(next_url.as_str()),
            )));
        }
        *current_url = next_url;
    }
    unreachable!("redirect loop returns within bounded hops")
}

fn build_pinned_client(
    config: &WebFetchConfig,
    url: &Url,
    addrs: &[SocketAddr],
) -> Result<reqwest::Client, String> {
    let mut builder = reqwest::Client::builder()
        .redirect(reqwest::redirect::Policy::none())
        .timeout(config.timeout)
        .user_agent("MerryWebFetch/0.1");

    if let Some(host) = url.host_str()
        && !addrs.is_empty()
    {
        builder = builder.resolve_to_addrs(strip_brackets(host), addrs);
    }

    builder
        .build()
        .map_err(|error| format!("failed to build HTTP client: {error}"))
}

fn same_host(a: &Url, b: &Url) -> bool {
    let normalize = |u: &Url| u.host_str().and_then(normalize_network_domain);
    matches!((normalize(a), normalize(b)), (Some(left), Some(right)) if left == right)
}

async fn read_bounded_body(
    mut response: reqwest::Response,
    max_bytes: usize,
) -> Result<(Vec<u8>, bool), String> {
    let mut out = Vec::new();
    let mut truncated = false;
    while let Some(chunk) = response
        .chunk()
        .await
        .map_err(|error| format!("error reading response body: {error}"))?
    {
        let remaining = max_bytes.saturating_sub(out.len());
        if remaining == 0 {
            truncated = true;
            break;
        }
        if chunk.len() > remaining {
            out.extend_from_slice(&chunk[..remaining]);
            truncated = true;
            break;
        }
        out.extend_from_slice(&chunk);
    }
    Ok((out, truncated))
}

fn format_response_content(bytes: &[u8], content_type: Option<&str>) -> (Option<String>, String) {
    let mime = content_type
        .unwrap_or("text/plain")
        .split(';')
        .next()
        .unwrap_or("text/plain")
        .trim()
        .to_ascii_lowercase();

    let text = String::from_utf8_lossy(bytes);
    if mime == "text/html" || mime == "application/xhtml+xml" {
        let title = html::extract_html_title(&text);
        let md = html::html_to_markdown(&text);
        let content = if md.trim().is_empty() {
            "[HTML page had no extractable text content]".to_owned()
        } else {
            md
        };
        return (title, content);
    }
    if mime == "application/json" || mime.ends_with("+json") {
        let formatted = serde_json::from_slice::<serde_json::Value>(bytes)
            .and_then(|v| serde_json::to_string_pretty(&v))
            .unwrap_or_else(|_| text.into_owned());
        return (None, html::strip_base64_data_uris(&formatted));
    }
    if mime.starts_with("text/")
        || mime.contains("xml")
        || mime.contains("javascript")
        || mime.contains("yaml")
    {
        let cleaned = html::strip_base64_data_uris(&text);
        let content = if cleaned.trim().is_empty() {
            "[empty text response]".to_owned()
        } else {
            cleaned
        };
        return (None, content);
    }
    (
        None,
        format!("[non-text content type={mime} bytes={}]", bytes.len()),
    )
}

fn truncate_chars(text: &str, max_chars: usize) -> (String, bool) {
    if text.chars().count() <= max_chars {
        return (text.to_owned(), false);
    }
    let truncated: String = text.chars().take(max_chars).collect();
    (truncated, true)
}

fn web_fetch_failed(
    code: &'static str,
    message: String,
    url: Option<&str>,
) -> ToolExecutionOutcome {
    let payload = json!({
        "ok": false,
        "tool": WEB_FETCH_TOOL,
        "url": url,
        "error": {
            "code": code,
            "message": message,
        }
    });
    let safe_diag_msg: String = message
        .chars()
        .filter(|c| !c.is_control())
        .take(512)
        .collect();
    let diagnostic = ErrorInfo::new(
        code,
        if safe_diag_msg.trim().is_empty() {
            "web_fetch failed"
        } else {
            &safe_diag_msg
        },
    )
    .expect("sanitized web_fetch diagnostic is valid");
    ToolExecutionOutcome::failed_json(payload.to_string(), diagnostic)
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::{
        Router,
        http::StatusCode,
        response::{Html, IntoResponse, Redirect},
        routing::get,
    };
    use merry_core::{
        PendingToolCall, ToolCallArguments, ToolCallId, ToolCallResultStatus, ToolName,
    };
    use tokio::net::TcpListener;
    use tokio_util::sync::CancellationToken;

    fn test_call(args: serde_json::Value) -> PendingToolCall {
        PendingToolCall::new(
            ToolCallId::new("call-web-fetch").expect("valid id"),
            ToolName::new(WEB_FETCH_TOOL).expect("valid name"),
            ToolCallArguments::try_from(args).expect("object args"),
        )
    }

    #[tokio::test]
    async fn blocks_ssrf_targets_and_fetches_loopback_html_when_allowed() {
        let blocked_tool = WebFetchTool::new(WebFetchConfig::default().with_allow_local(false));
        let blocked = blocked_tool
            .execute(
                test_call(json!({"url": "http://127.0.0.1:8080/"})),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect("returns failed outcome");
        assert_eq!(blocked.status(), ToolCallResultStatus::Failed);
        assert_eq!(
            blocked.diagnostic().expect("diag").code(),
            "web_fetch_ssrf_blocked"
        );

        let app = Router::new()
            .route(
                "/docs",
                get(|| async {
                    Html("<html><head><title>Test Page</title></head><body><h1>Hello</h1><p>World</p><script>bad()</script></body></html>")
                }),
            )
            .route(
                "/bounce",
                get(|| async { Redirect::temporary("https://other.example.com/target").into_response() }),
            )
            .route(
                "/local-redirect",
                get(|| async { (StatusCode::FOUND, [("location", "/docs")]).into_response() }),
            );
        let listener = TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind loopback");
        let addr = listener.local_addr().expect("addr");
        let server = tokio::spawn(async move {
            axum::serve(listener, app).await.expect("serve");
        });

        let local_tool = WebFetchTool::default();
        let ok = local_tool
            .execute(
                test_call(
                    json!({"url": format!("http://127.0.0.1:{}/local-redirect", addr.port())}),
                ),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect("fetch succeeds");
        assert_eq!(ok.status(), ToolCallResultStatus::Succeeded);
        assert!(ok.model_content().is_none());
        let text = ok.content().as_str();
        assert!(text.contains("Title: Test Page"));
        assert!(text.contains("# Hello"));
        assert!(!text.contains("bad()"));

        let cross_host = local_tool
            .execute(
                test_call(json!({"url": format!("http://127.0.0.1:{}/bounce", addr.port())})),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect("cross-host redirect returns cleanly");
        assert_eq!(cross_host.status(), ToolCallResultStatus::Succeeded);
        assert!(cross_host.model_content().is_none());
        assert!(
            cross_host
                .content()
                .as_str()
                .contains("https://other.example.com/target")
        );

        server.abort();
    }

    #[tokio::test]
    async fn web_fetch_enforces_live_network_policy_domain_grants_and_ssrf_floor() {
        use merry_core::CapabilityPolicy;
        use merry_runtime::{
            LivePolicyHandle, NetworkAccessPolicy, PermissionedAction, ProcessSessionPermissions,
            RequestedCapability, ToolExecutionError,
        };

        // 1. network = "deny" hard-denies external domains before review (and without DNS).
        let deny_policy =
            LivePolicyHandle::for_network(NetworkAccessPolicy::new(CapabilityPolicy::Deny, true));
        let deny_tool =
            WebFetchTool::new(WebFetchConfig::default().with_live_network_policy(deny_policy));
        let denied = deny_tool
            .execute(
                test_call(json!({"url": "https://docs.rs/serde"})),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect("network deny returns failed outcome without review");
        assert_eq!(denied.status(), ToolCallResultStatus::Failed);
        assert_eq!(
            denied.diagnostic().expect("diag").code(),
            "web_fetch_network_denied"
        );

        // 2. network = "ask" triggers structured domain-level PermissionRequired.
        let session_permissions = ProcessSessionPermissions::new();
        let ask_policy = LivePolicyHandle::for_network(
            NetworkAccessPolicy::new(CapabilityPolicy::Ask, true)
                .with_session_permissions(session_permissions.view()),
        );
        let ask_tool = WebFetchTool::new(
            WebFetchConfig::default().with_live_network_policy(ask_policy.clone()),
        );
        let err = ask_tool
            .execute(
                test_call(json!({"url": "https://Docs.RS/serde"})),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect_err("ask policy should require domain approval");
        match err {
            ToolExecutionError::PermissionRequired(requirement) => {
                assert_eq!(
                    requirement.action(),
                    &PermissionedAction::NetworkUrl {
                        tool: WEB_FETCH_TOOL.to_owned(),
                        url: "https://docs.rs/serde".to_owned(),
                        host: "docs.rs".to_owned(),
                    }
                );
                assert_eq!(
                    requirement.requested(),
                    &[RequestedCapability::NetworkDomain("docs.rs".to_owned())]
                );
            }
            other => panic!("expected PermissionRequired, got {other:?}"),
        }

        // 3. Exact hostname match only: approving docs.rs does NOT approve www.docs.rs.
        session_permissions
            .retain_domain_grants(["docs.rs".to_owned()])
            .expect("domain grant recorded");
        let www_err = ask_tool
            .execute(
                test_call(json!({"url": "https://www.docs.rs/serde"})),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect_err("www.docs.rs must not inherit docs.rs grant");
        assert!(matches!(www_err, ToolExecutionError::PermissionRequired(_)));

        // 4. SSRF floor cannot be bypassed even when network = "allow".
        let allow_policy =
            LivePolicyHandle::for_network(NetworkAccessPolicy::new(CapabilityPolicy::Allow, true));
        let allow_tool =
            WebFetchTool::new(WebFetchConfig::default().with_live_network_policy(allow_policy));
        for blocked_url in [
            "file:///etc/passwd",
            "http://169.254.169.254/latest/meta-data",
            "http://10.0.0.1/secret",
        ] {
            let outcome = allow_tool
                .execute(
                    test_call(json!({"url": blocked_url})),
                    ToolExecutionContext::new(CancellationToken::new()),
                )
                .await
                .expect("ssrf returns failed outcome");
            assert_eq!(outcome.status(), ToolCallResultStatus::Failed);
            assert!(
                matches!(
                    outcome.diagnostic().expect("diag").code(),
                    "web_fetch_ssrf_blocked" | "web_fetch_invalid_url"
                ),
                "unexpected code for {blocked_url}: {:?}",
                outcome.diagnostic()
            );
        }

        // 5. allow_local = true still permits explicit loopback even when network = "deny".
        let app = Router::new().route("/ping", get(|| async { Html("<h1>pong</h1>") }));
        let listener = TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind loopback");
        let addr = listener.local_addr().expect("addr");
        let server = tokio::spawn(async move {
            axum::serve(listener, app).await.expect("serve");
        });
        let local_ok = deny_tool
            .execute(
                test_call(json!({"url": format!("http://127.0.0.1:{}/ping", addr.port())})),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect("loopback stays allowed when allow_local=true");
        assert_eq!(local_ok.status(), ToolCallResultStatus::Succeeded);
        assert!(local_ok.content().as_str().contains("pong"));

        // 6. Disabling allow_local in the live network policy blocks loopback.
        let no_local_policy =
            LivePolicyHandle::for_network(NetworkAccessPolicy::new(CapabilityPolicy::Allow, false));
        let no_local_tool =
            WebFetchTool::new(WebFetchConfig::default().with_live_network_policy(no_local_policy));
        let local_blocked = no_local_tool
            .execute(
                test_call(json!({"url": format!("http://127.0.0.1:{}/ping", addr.port())})),
                ToolExecutionContext::new(CancellationToken::new()),
            )
            .await
            .expect("loopback denied when allow_local=false");
        assert_eq!(local_blocked.status(), ToolCallResultStatus::Failed);
        assert_eq!(
            local_blocked.diagnostic().expect("diag").code(),
            "web_fetch_ssrf_blocked"
        );
        server.abort();
    }
}