eggsearch 0.1.2

Lightweight MCP metasearch server for AI agents
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
//! Integration tests for the MCP server tool surface.
//!
//! These tests build a `ServerState` either with the real default
//! engines (no network) or with a set of mock engines injected via
//! the `mock` feature. They verify the on-the-wire behavior of the
//! `web_search` and `provider_status` tools without requiring any
//! network access.
//!
//! Covered behavior:
//!
//! - Server `initialize` returns the documented server info and
//!   capabilities.
//! - `tools/list` returns exactly `web_search`, `web_fetch`, and
//!   `provider_status` and never returns the legacy `local_search` or
//!   `search_and_fetch` tools.
//! - `web_search` happy path returns a structured payload with
//!   deduplicated cards and the documented trust label.
//! - `web_search` with an empty / whitespace-only query returns a
//!   validation error.
//! - `web_search` with a query longer than `max_query_chars` returns
//!   a validation error.
//! - `web_search` with `max_results = 0` returns a validation error.
//! - `web_search` with `max_results > cap` returns a validation
//!   error.
//! - `web_search` with an unknown provider id returns an error.
//! - `web_search` when `mode = "off"` is denied by policy.
//! - `web_search` with one failing provider returns partial results
//!   and a non-empty `providers_failed`.
//! - `web_search` with all providers failing returns a structured
//!   error.
//! - `web_search` with a global timeout (mock engines that hang)
//!   reports the timeout per provider.
//! - `web_search` cards are deduplicated when the same URL appears
//!   in multiple engines.
//! - `web_search` cards carry a per-card `id` of the form `src_<uuid>`
//!   and the id is unique within a response.
//! - `provider_status` returns one entry per configured provider with
//!   the documented field shape.

use std::sync::Arc;

use eggsearch::core::config::{AppConfig, Mode};
use eggsearch::core::fetch::ExtractMode;
use eggsearch::mcp::state::ServerState;
use eggsearch::mcp::tools::{
    run_provider_status, run_web_fetch, run_web_search, ProviderStatusArgs, WebFetchArgs,
    WebSearchArgs,
};
use rmcp::ServerHandler;

#[cfg(feature = "mock")]
use eggsearch::meta::mock::{mock_engines, MockEngine, MockFailure, MockResult};
#[cfg(feature = "mock")]
use eggsearch::meta::MetadataSearchAdapter;
#[cfg(feature = "mock")]
use std::time::Duration;

fn state_with_default() -> Arc<ServerState> {
    Arc::new(ServerState::build(AppConfig::default()).expect("default state"))
}

fn state_with_mode_off() -> Arc<ServerState> {
    let mut cfg = AppConfig::default();
    cfg.search.mode = Mode::Off;
    Arc::new(ServerState::build(cfg).expect("off state"))
}

#[cfg(feature = "mock")]
fn state_with_engines(
    cfg: AppConfig,
    engines: Vec<MockEngine>,
    timeout: Duration,
) -> Arc<ServerState> {
    let adapter = MetadataSearchAdapter::from_engines(mock_engines(engines), timeout);
    Arc::new(ServerState::with_adapter(cfg, Arc::new(adapter)))
}

#[cfg(feature = "mock")]
fn test_cfg() -> AppConfig {
    let mut cfg = AppConfig::default();
    cfg.search.timeout_ms = 2_000;
    cfg.search.max_query_chars = 256;
    cfg.search.max_results = 10;
    cfg.search.max_results_cap = 50;
    cfg
}

/// Build a `WebSearchArgs` that uses the given mock provider ids
/// instead of the configured defaults.
#[cfg(feature = "mock")]
fn args_for(providers: &[&'static str], query: &'static str) -> WebSearchArgs {
    WebSearchArgs {
        query: query.into(),
        max_results: None,
        providers: providers.iter().map(|s| s.to_string()).collect(),
        safe_search: None,
        timeout_ms: None,
    }
}

#[test]
fn mcp_server_get_info() {
    let state = state_with_default();
    let server = eggsearch::mcp::EggsearchServer::new(state);
    let info = server.get_info();
    assert_eq!(info.server_info.name, "eggsearch");
    assert_eq!(info.server_info.version, env!("CARGO_PKG_VERSION"));
    assert!(
        info.capabilities.tools.is_some(),
        "tools capability must be enabled"
    );
    // Server instructions should mention both tools by name so a host
    // agent can discover them from the initialize handshake.
    let instructions = info.instructions.unwrap_or_default();
    assert!(
        instructions.contains("web_search"),
        "instructions should mention web_search: {instructions}"
    );
    assert!(
        instructions.contains("provider_status"),
        "instructions should mention provider_status: {instructions}"
    );
}

#[test]
fn mcp_server_lists_three_tools() {
    let state = state_with_default();
    let server = eggsearch::mcp::EggsearchServer::new(state);
    let tools = server.tool_definitions();
    let names: Vec<String> = tools.iter().map(|t| t.name.to_string()).collect();
    assert!(
        names.contains(&"web_search".to_string()),
        "tools: {names:?}"
    );
    assert!(names.contains(&"web_fetch".to_string()), "tools: {names:?}");
    assert!(
        names.contains(&"provider_status".to_string()),
        "tools: {names:?}"
    );
    // Legacy tools must not be exposed.
    for legacy in ["local_search", "search_and_fetch"] {
        assert!(
            !names.contains(&legacy.to_string()),
            "legacy tool {legacy} must not be exposed: {names:?}"
        );
    }
}

#[tokio::test]
async fn web_search_empty_query_returns_validation_error() {
    let state = state_with_default();
    let res = run_web_search(
        state,
        WebSearchArgs {
            query: "   ".into(),
            max_results: None,
            providers: vec![],
            safe_search: None,
            timeout_ms: None,
        },
    )
    .await;
    let err = res.expect_err("expected validation error");
    assert!(err.to_string().contains("invalid query"), "got: {err}");
}

#[tokio::test]
async fn web_search_oversized_query_returns_validation_error() {
    let state = state_with_default();
    let too_long = "a".repeat(2_000);
    let res = run_web_search(
        state,
        WebSearchArgs {
            query: too_long,
            max_results: None,
            providers: vec![],
            safe_search: None,
            timeout_ms: None,
        },
    )
    .await;
    let err = res.expect_err("expected validation error");
    assert!(err.to_string().contains("invalid query"), "got: {err}");
    assert!(err.to_string().contains("characters"), "got: {err}");
}

#[tokio::test]
async fn web_search_zero_max_results_returns_validation_error() {
    let state = state_with_default();
    let res = run_web_search(
        state,
        WebSearchArgs {
            query: "rust".into(),
            max_results: Some(0),
            providers: vec![],
            safe_search: None,
            timeout_ms: None,
        },
    )
    .await;
    let err = res.expect_err("expected validation error");
    assert!(
        err.to_string().contains("max_results must be > 0"),
        "got: {err}"
    );
}

#[tokio::test]
async fn web_search_oversized_max_results_returns_validation_error() {
    let state = state_with_default();
    let res = run_web_search(
        state,
        WebSearchArgs {
            query: "rust".into(),
            max_results: Some(10_000),
            providers: vec![],
            safe_search: None,
            timeout_ms: None,
        },
    )
    .await;
    let err = res.expect_err("expected validation error");
    assert!(
        err.to_string().contains("max_results must be <="),
        "got: {err}"
    );
}

#[tokio::test]
async fn web_search_blocked_when_mode_off() {
    let state = state_with_mode_off();
    let res = run_web_search(
        state,
        WebSearchArgs {
            query: "rust".into(),
            max_results: None,
            providers: vec![],
            safe_search: None,
            timeout_ms: None,
        },
    )
    .await;
    let err = res.expect_err("expected policy denial");
    assert!(err.to_string().contains("disabled by policy"), "got: {err}");
}

#[tokio::test]
async fn web_search_unknown_provider_returns_error() {
    let state = state_with_default();
    let res = run_web_search(
        state,
        WebSearchArgs {
            query: "rust".into(),
            max_results: None,
            providers: vec!["nope".into()],
            safe_search: None,
            timeout_ms: None,
        },
    )
    .await;
    let err = res.expect_err("expected unknown provider error");
    assert!(err.to_string().contains("unknown provider"), "got: {err}");
    assert!(err.to_string().contains("nope"), "got: {err}");
}

#[test]
fn provider_status_returns_configured_providers() {
    let state = state_with_default();
    let v = run_provider_status(state, ProviderStatusArgs { probe: false }).expect("ok");
    let arr = v["providers"].as_array().expect("providers is array");
    let ids: Vec<&str> = arr
        .iter()
        .map(|p| p["id"].as_str().unwrap_or(""))
        .filter(|s| !s.is_empty())
        .collect();
    for expected in ["duckduckgo", "brave", "startpage", "yahoo"] {
        assert!(
            ids.contains(&expected),
            "expected provider id {expected} in status, got {ids:?}"
        );
    }
}

#[test]
fn provider_status_payload_shape_is_stable() {
    let state = state_with_default();
    let v = run_provider_status(state, ProviderStatusArgs { probe: false }).expect("ok");
    assert!(v["mode"].is_string());
    let arr = v["providers"].as_array().unwrap();
    for p in arr {
        assert!(p["id"].is_string(), "missing id: {p}");
        assert!(p["enabled"].is_boolean(), "missing enabled: {p}");
        assert!(p["kind"].is_string(), "missing kind: {p}");
        assert!(
            p["requires_api_key"].is_boolean(),
            "missing requires_api_key: {p}"
        );
    }
}

#[cfg(feature = "mock")]
#[tokio::test]
async fn web_search_happy_path_dedupes_across_engines() {
    let engines = vec![
        MockEngine::success(
            "mock_a",
            vec![
                MockResult::new("Title A", "https://example.com/a", "mock_a"),
                MockResult::new("Title B", "https://example.com/b", "mock_a"),
            ],
        ),
        MockEngine::success(
            "mock_b",
            vec![MockResult::new(
                "Title A",
                "https://example.com/a",
                "mock_b",
            )],
        ),
    ];
    let state = state_with_engines(test_cfg(), engines, Duration::from_secs(5));
    let v = run_web_search(state, args_for(&["mock_a", "mock_b"], "rust"))
        .await
        .expect("ok");

    assert_eq!(v["query"], "rust");
    assert_eq!(v["mode"], "live_metasearch");
    let results = v["results"].as_array().expect("results is array");
    // Two unique URLs across the two engines; one of them appears in
    // both, so we expect 2 cards, not 3.
    assert_eq!(results.len(), 2, "results: {results:?}");

    // Card for https://example.com/a should be present in both
    // providers.
    let a_card = results
        .iter()
        .find(|c| c["url"] == "https://example.com/a")
        .expect("card a");
    let providers = a_card["providers"].as_array().unwrap();
    let provider_ids: Vec<&str> = providers.iter().filter_map(|v| v.as_str()).collect();
    assert!(provider_ids.contains(&"mock_a"));
    assert!(provider_ids.contains(&"mock_b"));
    assert_eq!(a_card["trust"], "external_untrusted");
    assert_eq!(a_card["fetched"], false);

    // Each card must have a unique id of the form src_<uuid>.
    let ids: Vec<&str> = results.iter().filter_map(|c| c["id"].as_str()).collect();
    for id in &ids {
        assert!(id.starts_with("src_"), "id format: {id}");
    }
    let unique: std::collections::HashSet<&str> = ids.iter().copied().collect();
    assert_eq!(unique.len(), ids.len(), "ids must be unique: {ids:?}");

    // Warnings array should contain the untrusted-content warning.
    let warnings = v["warnings"].as_array().unwrap();
    assert!(
        warnings
            .iter()
            .any(|w| w.as_str().unwrap_or("").contains("untrusted")),
        "warnings: {warnings:?}"
    );
}

#[cfg(feature = "mock")]
#[tokio::test]
async fn web_search_partial_failure_returns_results_and_failures() {
    let engines = vec![
        MockEngine::success(
            "mock_a",
            vec![MockResult::new("A", "https://example.com/a", "mock_a")],
        ),
        MockEngine::failure("mock_b", MockFailure::Parse),
    ];
    let state = state_with_engines(test_cfg(), engines, Duration::from_secs(5));
    let v = run_web_search(state, args_for(&["mock_a", "mock_b"], "rust"))
        .await
        .expect("ok");

    let results = v["results"].as_array().unwrap();
    assert_eq!(results.len(), 1, "partial results: {results:?}");

    let failed = v["providers_failed"].as_array().unwrap();
    assert_eq!(failed.len(), 1, "failed: {failed:?}");
    assert_eq!(failed[0]["id"], "mock_b");
    assert_eq!(failed[0]["error_class"], "parse_error");
}

#[cfg(feature = "mock")]
#[tokio::test]
async fn web_search_all_providers_fail_returns_error() {
    let engines = vec![
        MockEngine::failure("mock_a", MockFailure::HttpStatus(503)),
        MockEngine::failure("mock_b", MockFailure::Network),
    ];
    let state = state_with_engines(test_cfg(), engines, Duration::from_secs(5));
    let err = run_web_search(state, args_for(&["mock_a", "mock_b"], "rust"))
        .await
        .expect_err("expected all-fail error");
    assert!(
        err.to_string().contains("all providers failed"),
        "expected all-fail error, got: {err}"
    );
}

#[cfg(feature = "mock")]
#[tokio::test]
async fn web_search_global_timeout_returns_all_fail_error() {
    // Both engines hang forever; adapter timeout is 200 ms. With all
    // providers timing out, the tool surface returns a structured
    // "all providers failed" error rather than a soft partial result.
    let engines = vec![MockEngine::hang("mock_a"), MockEngine::hang("mock_b")];
    let state = state_with_engines(test_cfg(), engines, Duration::from_millis(200));
    let err = run_web_search(state, args_for(&["mock_a", "mock_b"], "rust"))
        .await
        .expect_err("expected all-fail error after global timeout");
    assert!(
        err.to_string().contains("all providers failed"),
        "expected all-fail error, got: {err}"
    );
    assert!(
        err.to_string().contains("timed out"),
        "error should mention the timeout: {err}"
    );
}

#[cfg(feature = "mock")]
#[tokio::test]
async fn web_search_provider_override_queries_only_requested_providers() {
    // mock_b is enabled in the adapter but we explicitly ask for
    // mock_a only. mock_b must not appear in providers_queried.
    let engines = vec![
        MockEngine::success(
            "mock_a",
            vec![MockResult::new("A", "https://example.com/a", "mock_a")],
        ),
        MockEngine::success(
            "mock_b",
            vec![MockResult::new("B", "https://example.com/b", "mock_b")],
        ),
    ];
    let state = state_with_engines(test_cfg(), engines, Duration::from_secs(5));
    let v = run_web_search(state, args_for(&["mock_a"], "rust"))
        .await
        .expect("ok");

    let queried = v["providers_queried"].as_array().unwrap();
    let queried_ids: Vec<&str> = queried.iter().filter_map(|q| q.as_str()).collect();
    assert_eq!(queried_ids, vec!["mock_a"]);
}

#[cfg(feature = "mock")]
#[tokio::test]
async fn web_search_provider_override_with_unknown_id_errors() {
    let engines = vec![MockEngine::success(
        "mock_a",
        vec![MockResult::new("A", "https://example.com/a", "mock_a")],
    )];
    let state = state_with_engines(test_cfg(), engines, Duration::from_secs(5));
    let err = run_web_search(state, args_for(&["mock_a", "mock_does_not_exist"], "rust"))
        .await
        .expect_err("expected unknown provider error");
    assert!(err.to_string().contains("unknown provider"), "got: {err}");
    assert!(
        err.to_string().contains("mock_does_not_exist"),
        "unknown id should be named in error: {err}"
    );
}

#[cfg(feature = "mock")]
#[tokio::test]
async fn web_search_partial_timeout_preserves_successful_results() {
    // mock_a returns instantly, mock_b hangs forever. With a tight
    // global timeout, mock_a's results must still be returned.
    let engines = vec![
        MockEngine::success(
            "mock_a",
            vec![MockResult::new(
                "Fast",
                "https://example.com/fast",
                "mock_a",
            )],
        ),
        MockEngine::hang("mock_b"),
    ];
    let state = state_with_engines(test_cfg(), engines, Duration::from_millis(200));
    let v = run_web_search(state, args_for(&["mock_a", "mock_b"], "rust"))
        .await
        .expect("ok");

    let results = v["results"].as_array().unwrap();
    assert_eq!(
        results.len(),
        1,
        "should have 1 result from mock_a: {results:?}"
    );
    assert_eq!(results[0]["title"], "Fast");

    // mock_b should appear in providers_failed as timed out.
    let failed = v["providers_failed"].as_array().unwrap();
    let failed_ids: Vec<&str> = failed.iter().filter_map(|f| f["id"].as_str()).collect();
    assert!(
        failed_ids.contains(&"mock_b"),
        "mock_b should be in providers_failed: {failed:?}"
    );
    assert!(
        !failed_ids.contains(&"mock_a"),
        "mock_a should NOT be in providers_failed: {failed:?}"
    );
}

#[cfg(feature = "mock")]
#[tokio::test]
async fn web_search_per_request_timeout_ms_shorter_than_global() {
    // Global timeout is 5s but per-request timeout_ms is 100ms.
    // Both engines hang. The per-request timeout should trigger.
    let engines = vec![MockEngine::hang("mock_a"), MockEngine::hang("mock_b")];
    let mut cfg = test_cfg();
    cfg.search.timeout_ms = 5_000;
    let state = state_with_engines(cfg, engines, Duration::from_secs(5));
    let mut args = args_for(&["mock_a", "mock_b"], "rust");
    args.timeout_ms = Some(100);
    let err = run_web_search(state, args)
        .await
        .expect_err("expected timeout error");
    assert!(
        err.to_string().contains("all providers failed"),
        "expected all-fail error, got: {err}"
    );
    assert!(
        err.to_string().contains("timed out"),
        "error should mention timeout: {err}"
    );
}

#[cfg(feature = "mock")]
#[tokio::test]
async fn web_search_all_providers_fail_returns_error_when_no_results() {
    // Both providers report failure with no results, so the tool
    // surface returns a structured "all providers failed" error.
    let engines = vec![
        MockEngine::failure("mock_a", MockFailure::Parse),
        MockEngine::failure("mock_b", MockFailure::HttpStatus(503)),
    ];
    let state = state_with_engines(test_cfg(), engines, Duration::from_secs(5));
    let err = run_web_search(state, args_for(&["mock_a", "mock_b"], "rust"))
        .await
        .expect_err("expected all-fail error");
    assert!(
        err.to_string().contains("all providers failed"),
        "got: {err}"
    );
}

#[cfg(feature = "mock")]
#[tokio::test]
async fn provider_status_with_mixed_enabled_disabled() {
    use eggsearch::core::config::{AppConfig, Mode};

    let engines = vec![
        MockEngine::success("mock_a", vec![]),
        MockEngine::success("mock_b", vec![]),
    ];
    let mut cfg = AppConfig::default();
    cfg.search.mode = Mode::Live;
    cfg.search.providers.clear();
    cfg.search.providers.insert("mock_a".to_string(), true);
    cfg.search.providers.insert("mock_b".to_string(), false);
    let adapter = eggsearch::meta::MetadataSearchAdapter::from_engines(
        eggsearch::meta::mock::mock_engines(engines),
        Duration::from_secs(5),
    );
    let state = Arc::new(eggsearch::mcp::state::ServerState::with_adapter(
        cfg,
        Arc::new(adapter),
    ));
    let v = run_provider_status(state, ProviderStatusArgs { probe: false }).expect("ok");
    // provider_status lists KNOWN_PROVIDERS (duckduckgo, brave, startpage, yahoo),
    // not mock engine names. The mock engines aren't in that list.
    let arr = v["providers"].as_array().unwrap();
    let ids: Vec<&str> = arr.iter().filter_map(|p| p["id"].as_str()).collect();
    assert!(ids.contains(&"duckduckgo"));
    assert!(ids.contains(&"brave"));
    assert!(ids.contains(&"startpage"));
    assert!(ids.contains(&"yahoo"));
    // All four should be listed, even though only mock_a and mock_b
    // are loaded in the adapter.
    assert_eq!(ids.len(), 4);
}

#[cfg(feature = "mock")]
#[tokio::test]
async fn web_fetch_tool_listed() {
    let state = state_with_default();
    let server = eggsearch::mcp::EggsearchServer::new(state);
    let tools = server.tool_definitions();
    let tool_names: Vec<String> = tools.iter().map(|t| t.name.to_string()).collect();
    assert!(
        tool_names.contains(&"web_fetch".to_string()),
        "web_fetch should be in tools list: {:?}",
        tool_names
    );
}

fn fetch_disabled_state() -> Arc<ServerState> {
    let mut cfg = AppConfig::default();
    cfg.fetch.enabled = false;
    Arc::new(ServerState::build(cfg).expect("state with fetch disabled"))
}

#[tokio::test]
async fn web_fetch_disabled_by_policy_returns_error() {
    let state = fetch_disabled_state();
    let res = run_web_fetch(
        state,
        WebFetchArgs {
            url: "https://example.com/".into(),
            max_chars: None,
            timeout_ms: None,
            extract_mode: None,
            include_links: None,
        },
    )
    .await;
    let err = res.expect_err("expected policy denial");
    assert!(err.to_string().contains("disabled by policy"), "got: {err}");
    assert!(err.to_string().contains("[fetch].enabled"), "got: {err}");
    assert!(err.to_string().contains("web_fetch"), "got: {err}");
}

#[tokio::test]
async fn web_fetch_rejects_markdown_extract_mode() {
    let state = state_with_default();
    let res = run_web_fetch(
        state,
        WebFetchArgs {
            url: "https://example.com/".into(),
            max_chars: None,
            timeout_ms: None,
            extract_mode: Some(ExtractMode::Markdown),
            include_links: None,
        },
    )
    .await;
    let err = res.expect_err("expected markdown rejection");
    assert!(err.to_string().contains("markdown"), "got: {err}");
    assert!(
        err.to_string().contains("not yet implemented"),
        "got: {err}"
    );
}

#[tokio::test]
async fn web_fetch_zero_max_chars_returns_validation_error() {
    let state = state_with_default();
    let res = run_web_fetch(
        state,
        WebFetchArgs {
            url: "https://example.com/".into(),
            max_chars: Some(0),
            timeout_ms: None,
            extract_mode: None,
            include_links: None,
        },
    )
    .await;
    let err = res.expect_err("expected max_chars validation error");
    assert!(
        err.to_string().contains("max_chars must be > 0"),
        "got: {err}"
    );
}

#[tokio::test]
async fn web_fetch_respects_include_links_default() {
    use httpmock::prelude::*;
    let server = MockServer::start();
    server.mock(|when, then| {
        when.method(GET).path("/page");
        then.status(200)
            .header("content-type", "text/html; charset=utf-8")
            .body(
                b"<!DOCTYPE html><html><head><title>Hi</title></head>\
                  <body><p>hello</p><a href=\"/path\">Link text</a></body></html>",
            );
    });

    let mut cfg = AppConfig::default();
    cfg.fetch.allow_localhost = true;
    cfg.fetch.allow_private_network = true;
    cfg.fetch.include_links_default = true;
    let state = Arc::new(ServerState::build(cfg).expect("state builds"));

    let v = run_web_fetch(
        state,
        WebFetchArgs {
            url: server.url("/page"),
            max_chars: None,
            timeout_ms: None,
            extract_mode: None,
            include_links: None,
        },
    )
    .await
    .expect("ok");

    let links = v["links"].as_array().expect("links is array");
    assert!(
        !links.is_empty(),
        "links should be populated when include_links_default = true, got: {v:?}"
    );
    let link = &links[0];
    assert_eq!(link["text"], "Link text");
    assert!(
        link["url"]
            .as_str()
            .unwrap_or("")
            .ends_with("/path"),
        "link url should be resolved, got: {}",
        link["url"]
    );
}

#[cfg(feature = "mock")]
#[tokio::test]
async fn web_search_threads_effective_per_request_timeout() {
    use std::sync::Mutex;

    let sink: Arc<Mutex<Option<Duration>>> = Arc::new(Mutex::new(None));
    let engines = vec![MockEngine::record_timeout("mock_a", Arc::clone(&sink))];
    let mut cfg = test_cfg();
    cfg.search.timeout_ms = 5_000;
    let state = state_with_engines(cfg, engines, Duration::from_secs(5));

    let mut args = args_for(&["mock_a"], "rust");
    args.timeout_ms = Some(3_500);
    let v = run_web_search(state, args).await.expect("ok");
    assert!(v["results"].is_array());

    let recorded = sink.lock().unwrap().expect("timeout was recorded");
    assert_eq!(
        recorded,
        Duration::from_millis(3_500),
        "engine should receive the per-request timeout, got: {recorded:?}"
    );
}

#[cfg(feature = "mock")]
#[tokio::test]
async fn web_search_uses_global_timeout_when_no_per_request_override() {
    use std::sync::Mutex;

    let sink: Arc<Mutex<Option<Duration>>> = Arc::new(Mutex::new(None));
    let engines = vec![MockEngine::record_timeout("mock_a", Arc::clone(&sink))];
    let mut cfg = test_cfg();
    cfg.search.timeout_ms = 2_500;
    let state = state_with_engines(cfg, engines, Duration::from_millis(2_500));

    let _ = run_web_search(state, args_for(&["mock_a"], "rust"))
        .await
        .expect("ok");

    let recorded = sink.lock().unwrap().expect("timeout was recorded");
    assert_eq!(
        recorded,
        Duration::from_millis(2_500),
        "engine should receive the global timeout when no override is set, got: {recorded:?}"
    );
}