ibridge-server 1.1.0

MCP server, tool routers and error mapping.
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
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
// SPDX-License-Identifier: Apache-2.0

//! End to end over rmcp: a real client talks to the server through an
//! in-memory transport. The mail backend is a scripted fake.

use std::sync::{Arc, Mutex};

use ibridge_core::{
    AppleId, Attachment, AttachmentInfo, CoreError, Draft, FlagChange, MailSearch, Mailbox,
    Message, MessageId, MessageSummary, OneClickFailure, Uid, UidValidity, Unsubscribe,
    UnsubscribeMail, UnsubscribeMethod, encode,
};
use ibridge_server::{
    AccountSnapshot, IbridgeServer, MailApi, MailBody, MailDest, MailHitPage, MailPart, SentMail,
    ServiceStatus, Unsubscribed,
};
use rmcp::model::{CallToolRequestParams, CallToolResult};
use rmcp::service::RunningService;
use rmcp::{RoleClient, ServiceExt};

/// The one message with an unsubscribe header: one-click, mailto and a link.
fn unsubscribe_for(id: &MessageId) -> Option<Unsubscribe> {
    (id.uid.get() == 42).then(|| Unsubscribe {
        mailto: Some(UnsubscribeMail {
            to: "unsub@example.com".to_owned(),
            subject: Some("unsubscribe".to_owned()),
            body: None,
        }),
        links: vec!["https://example.com/u".to_owned()],
        one_click: true,
    })
}

/// A second message with no unsubscribe header.
fn other_message_id() -> MessageId {
    MessageId {
        uid: Uid::try_from(43).expect("uid"),
        ..message_id()
    }
}

fn message_id() -> MessageId {
    MessageId {
        mailbox: ibridge_core::MailboxPath::try_from("INBOX").expect("inbox path"),
        validity: UidValidity::try_from(7).expect("validity"),
        uid: Uid::try_from(42).expect("uid"),
    }
}

/// Backend with one message in the inbox. Sends are recorded.
#[derive(Default)]
struct Scripted {
    sent: Mutex<Vec<Draft>>,
    unsubscribed: Mutex<Vec<MessageId>>,
    unsubscribe_methods: Mutex<Vec<Option<UnsubscribeMethod>>>,
}

#[expect(
    clippy::unused_async_trait_impl,
    reason = "the scripted backend answers without waiting"
)]
impl MailApi for Scripted {
    async fn list_mailboxes(&self) -> Result<Vec<Mailbox>, CoreError> {
        Ok(Vec::new())
    }

    async fn search(&self, _query: &MailSearch) -> Result<MailHitPage, CoreError> {
        Ok(MailHitPage {
            messages: vec![MessageSummary {
                id: message_id(),
                from: "bob@example.com".to_owned(),
                subject: "Picnic".to_owned(),
                date: "2026-11-01".to_owned(),
                unread: true,
                flagged: false,
            }],
            next_cursor: None,
            warnings: 0,
        })
    }

    async fn get_message(&self, id: &MessageId, _offset: usize) -> Result<MailBody, CoreError> {
        if *id != message_id() && *id != other_message_id() {
            return Err(CoreError::NotFound);
        }
        Ok(MailBody {
            message: Message {
                id: id.clone(),
                from: "Bob\u{202E}\u{E0049} <bob@example.com>".to_owned(),
                to: vec!["Ada\u{200B} <ada@icloud.com>".to_owned()],
                subject: "Pic\u{FEFF}nic\u{202E}".to_owned(),
                date: "2026-11-01".to_owned(),
                body: "Bring\u{200B} napkins.\u{E0049}\u{E0067}\u{2066}".to_owned(),
                attachments: Vec::new(),
                unsubscribe: unsubscribe_for(id),
            },
            next_offset: None,
        })
    }

    async fn get_attachment(
        &self,
        _id: &MessageId,
        _part: &str,
        _offset: usize,
    ) -> Result<MailPart, CoreError> {
        Err(CoreError::NotFound)
    }

    async fn get_attachment_bytes(
        &self,
        id: &MessageId,
        part: &str,
    ) -> Result<Attachment, CoreError> {
        if *id != message_id() || part != "2" {
            return Err(CoreError::NotFound);
        }
        Ok(Attachment {
            info: AttachmentInfo {
                part: "2".to_owned(),
                content_type: "text/plain".to_owned(),
                size: 16,
                // A hostile name: a path that climbs out of the download folder.
                name: "../../evil name.txt".to_owned(),
            },
            text: None,
            bytes: Some(b"hello attachment".to_vec()),
        })
    }

    async fn create_draft(&self, _draft: &Draft) -> Result<MessageId, CoreError> {
        Ok(message_id())
    }

    async fn send(&self, draft: &Draft) -> Result<SentMail, CoreError> {
        self.sent.lock().expect("sent lock").push(Draft {
            to: draft.to.clone(),
            subject: draft.subject.clone(),
            body: draft.body.clone(),
            from: draft.from.clone(),
            reply_to: draft.reply_to.clone(),
        });
        Ok(SentMail { id: None })
    }

    async fn unsubscribe(
        &self,
        id: &MessageId,
        method: Option<UnsubscribeMethod>,
    ) -> Result<Unsubscribed, CoreError> {
        self.unsubscribe_methods
            .lock()
            .expect("methods lock")
            .push(method);
        self.unsubscribed
            .lock()
            .expect("unsubscribed lock")
            .push(id.clone());
        match id.uid.get() {
            42 => Ok(Unsubscribed::Emailed(SentMail {
                id: Some(message_id()),
            })),
            43 => Ok(Unsubscribed::NotOffered),
            44 => Ok(Unsubscribed::Links(vec![
                "https://example.com/u?id=9\u{200B}\u{E0049}".to_owned(),
            ])),
            45 => Ok(Unsubscribed::Emailed(SentMail { id: None })),
            46 => Ok(Unsubscribed::OneClicked),
            47 => Ok(Unsubscribed::OneClickFailed {
                failure: OneClickFailure::Rejected,
                mailto_offered: true,
            }),
            48 => Ok(Unsubscribed::OneClickFailed {
                failure: OneClickFailure::Blocked,
                mailto_offered: false,
            }),
            49 => Ok(Unsubscribed::MethodNotOffered(UnsubscribeMethod::Mailto)),
            _ => Err(CoreError::NotFound),
        }
    }

    async fn move_message(
        &self,
        _id: &MessageId,
        _destination: &MailDest,
    ) -> Result<(), CoreError> {
        Ok(())
    }

    async fn set_flags(&self, _id: &MessageId, _flags: &FlagChange) -> Result<(), CoreError> {
        Ok(())
    }
}

fn account() -> AccountSnapshot {
    AccountSnapshot {
        apple_id: AppleId::try_from("ada@icloud.com").expect("apple id"),
        mail: ServiceStatus::On,
        calendar: ServiceStatus::On,
        contacts: ServiceStatus::On,
    }
}

/// Connects a client to `server` over a duplex pipe.
async fn connect(server: IbridgeServer<Scripted>) -> RunningService<RoleClient, ()> {
    let (server_io, client_io) = tokio::io::duplex(64 * 1024);
    tokio::spawn(async move {
        let running = server.serve(server_io).await.expect("server starts");
        let _quit = running.waiting().await;
    });
    ().serve(client_io).await.expect("client starts")
}

fn arguments(value: &serde_json::Value) -> rmcp::model::JsonObject {
    value.as_object().expect("an object").clone()
}

async fn call(
    client: &RunningService<RoleClient, ()>,
    name: &'static str,
    args: serde_json::Value,
) -> CallToolResult {
    let mut params = CallToolRequestParams::new(name);
    params.arguments = Some(arguments(&args));
    client.call_tool(params).await.expect("tool call")
}

#[tokio::test]
async fn e2e_search_then_get() {
    let client = connect(IbridgeServer::read_write(
        account(),
        Arc::new(Scripted::default()),
    ))
    .await;

    let found = call(&client, "mail_search", serde_json::json!({})).await;
    let structured = found.structured_content.expect("search structured content");
    let id = structured["messages"][0]["id"]
        .as_str()
        .expect("the hit carries an id")
        .to_owned();
    assert_eq!(id, encode(&message_id()), "the id is the opaque token");

    let fetched = call(&client, "mail_get_message", serde_json::json!({ "id": id })).await;
    assert_eq!(fetched.is_error, Some(false), "get succeeds: {fetched:?}");
    let message = fetched
        .structured_content
        .expect("message structured content");
    assert_eq!(
        message["body"].as_str(),
        Some("Bring napkins."),
        "the body arrives as plain text with hidden characters stripped"
    );
    assert_eq!(
        message["subject"].as_str(),
        Some("Picnic"),
        "the subject arrives as plain text with hidden characters stripped"
    );
    assert_eq!(
        message["from"].as_str(),
        Some("Bob <bob@example.com>"),
        "the sender's display name has hidden characters stripped"
    );
    assert_eq!(
        message["to"][0].as_str(),
        Some("Ada <ada@icloud.com>"),
        "recipient display names have hidden characters stripped"
    );
    assert!(
        !message.to_string().contains("untrusted"),
        "no untrusted marker, got {message}"
    );
}

#[tokio::test]
async fn e2e_get_message_reports_how_to_unsubscribe() {
    let client = connect(IbridgeServer::read_write(
        account(),
        Arc::new(Scripted::default()),
    ))
    .await;
    let offered = call(
        &client,
        "mail_get_message",
        serde_json::json!({ "id": encode(&message_id()) }),
    )
    .await;
    let message = offered.structured_content.expect("structured content");
    assert_eq!(
        message["unsubscribe"],
        serde_json::json!({ "available": true, "methods": ["one_click", "mailto", "link"] }),
        "a message with the header lists its methods best first, got {message}"
    );
    assert!(
        !message.to_string().contains("unsub@example.com"),
        "the sender's address is not shown, got {message}"
    );
    let plain = call(
        &client,
        "mail_get_message",
        serde_json::json!({ "id": encode(&other_message_id()) }),
    )
    .await;
    let message = plain.structured_content.expect("structured content");
    assert_eq!(
        message["unsubscribe"],
        serde_json::json!({ "available": false, "methods": [] }),
        "a message without the header says so, got {message}"
    );
}

fn id_with_uid(uid: u32) -> String {
    encode(&MessageId {
        uid: Uid::try_from(uid).expect("uid"),
        ..message_id()
    })
}

#[tokio::test]
async fn e2e_unsubscribe_reports_the_email_it_sent() {
    let mail = Arc::new(Scripted::default());
    let client = connect(IbridgeServer::read_write(account(), Arc::clone(&mail))).await;
    let result = call(
        &client,
        "mail_unsubscribe",
        serde_json::json!({ "id": id_with_uid(42), "to": "attacker@example.net" }),
    )
    .await;
    assert_eq!(
        result.is_error,
        Some(false),
        "unsubscribe works: {result:?}"
    );
    let out = result.structured_content.expect("structured content");
    assert_eq!(out["status"], "emailed", "got {out}");
    assert_eq!(out["id"].as_str(), Some(id_with_uid(42).as_str()));
    assert_eq!(out["warning"], serde_json::Value::Null);
    assert_eq!(out["links"], serde_json::json!([]));
    assert_eq!(
        *mail.unsubscribed.lock().expect("lock"),
        vec![MessageId {
            uid: Uid::try_from(42).expect("uid"),
            ..message_id()
        }],
        "the backend is asked about the message id and nothing else"
    );
    let warned = call(
        &client,
        "mail_unsubscribe",
        serde_json::json!({ "id": id_with_uid(45) }),
    )
    .await;
    let out = warned.structured_content.expect("structured content");
    assert_eq!(out["status"], "emailed");
    assert_eq!(out["id"], serde_json::Value::Null);
    assert_eq!(
        out["warning"].as_str(),
        Some("sent, but the copy was not saved to Sent Messages"),
        "a failed Sent copy is a warning on a sent email, got {out}"
    );
}

#[tokio::test]
async fn e2e_unsubscribe_says_when_the_message_offers_nothing() {
    let client = connect(IbridgeServer::read_write(
        account(),
        Arc::new(Scripted::default()),
    ))
    .await;
    let result = call(
        &client,
        "mail_unsubscribe",
        serde_json::json!({ "id": id_with_uid(43) }),
    )
    .await;
    assert_eq!(result.is_error, Some(true), "a tool error, got {result:?}");
    let text = text_blocks(&result).join(" ");
    assert!(
        text.contains("does not offer") && text.contains("unsubscribe"),
        "the error says unsubscribe isn't offered, got {text:?}"
    );
}

#[tokio::test]
async fn e2e_unsubscribe_link_only_returns_the_link_and_sends_nothing() {
    let mail = Arc::new(Scripted::default());
    let client = connect(IbridgeServer::read_write(account(), Arc::clone(&mail))).await;
    let result = call(
        &client,
        "mail_unsubscribe",
        serde_json::json!({ "id": id_with_uid(44) }),
    )
    .await;
    assert_eq!(result.is_error, Some(false), "not an error: {result:?}");
    let out = result.structured_content.expect("structured content");
    assert_eq!(out["status"], "link_only", "got {out}");
    assert_eq!(
        out["links"],
        serde_json::json!(["https://example.com/u?id=9"]),
        "the link comes back with hidden characters stripped"
    );
    assert!(
        out["note"].as_str().is_some_and(|note| {
            note.contains("does not support one-click") && note.contains("open it in a browser")
        }),
        "the note says why nothing was posted and what to do, got {out}"
    );
    assert!(
        mail.sent.lock().expect("sent lock").is_empty(),
        "nothing was sent"
    );
}

#[tokio::test]
async fn e2e_unsubscribe_reports_an_accepted_one_click_post() {
    let client = connect(IbridgeServer::read_write(
        account(),
        Arc::new(Scripted::default()),
    ))
    .await;
    let result = call(
        &client,
        "mail_unsubscribe",
        serde_json::json!({ "id": id_with_uid(46) }),
    )
    .await;
    assert_eq!(result.is_error, Some(false), "not an error: {result:?}");
    let out = result.structured_content.expect("structured content");
    assert_eq!(out["status"], "one_click", "got {out}");
    assert_eq!(out["id"], serde_json::Value::Null);
    assert_eq!(out["links"], serde_json::json!([]));
    assert!(
        out["note"]
            .as_str()
            .is_some_and(|note| note.contains("accepted") && note.contains("one-click")),
        "the note says the sender accepted the request, got {out}"
    );
}

#[tokio::test]
async fn e2e_a_failed_one_click_is_a_tool_error_that_names_the_class_and_the_mailto() {
    let client = connect(IbridgeServer::read_write(
        account(),
        Arc::new(Scripted::default()),
    ))
    .await;
    let refused = call(
        &client,
        "mail_unsubscribe",
        serde_json::json!({ "id": id_with_uid(47) }),
    )
    .await;
    assert_eq!(
        refused.is_error,
        Some(true),
        "a tool error, got {refused:?}"
    );
    let text = text_blocks(&refused).join(" ");
    assert!(
        text.contains("refused the request")
            && text.contains("unsubscribe email")
            && text.contains("not sent"),
        "names the class, says the mailto exists and was not sent, got {text:?}"
    );
    let blocked = call(
        &client,
        "mail_unsubscribe",
        serde_json::json!({ "id": id_with_uid(48) }),
    )
    .await;
    assert_eq!(
        blocked.is_error,
        Some(true),
        "a tool error, got {blocked:?}"
    );
    let text = text_blocks(&blocked).join(" ");
    assert!(
        text.contains("private or local network") && !text.contains("unsubscribe email"),
        "names the class and offers no mailto when there is none, got {text:?}"
    );
}

#[tokio::test]
async fn e2e_unsubscribe_passes_the_chosen_method_to_the_backend() {
    let mail = Arc::new(Scripted::default());
    let client = connect(IbridgeServer::read_write(account(), Arc::clone(&mail))).await;
    for params in [
        serde_json::json!({ "id": id_with_uid(42) }),
        serde_json::json!({ "id": id_with_uid(42), "method": "mailto" }),
        serde_json::json!({ "id": id_with_uid(42), "method": "one_click" }),
    ] {
        let result = call(&client, "mail_unsubscribe", params).await;
        assert_eq!(result.is_error, Some(false), "works: {result:?}");
    }
    assert_eq!(
        *mail.unsubscribe_methods.lock().expect("lock"),
        vec![
            None,
            Some(UnsubscribeMethod::Mailto),
            Some(UnsubscribeMethod::OneClick)
        ],
        "an omitted method stays omitted, so the backend keeps its own preference"
    );
}

#[tokio::test]
async fn e2e_unsubscribe_refuses_a_method_it_does_not_know() {
    let mail = Arc::new(Scripted::default());
    let client = connect(IbridgeServer::read_write(account(), Arc::clone(&mail))).await;
    for method in ["link", "https://evil.example/u", "attacker@example.net"] {
        let result = call(
            &client,
            "mail_unsubscribe",
            serde_json::json!({ "id": id_with_uid(42), "method": method }),
        )
        .await;
        assert_eq!(
            result.is_error,
            Some(true),
            "{method:?} is refused, got {result:?}"
        );
    }
    assert!(
        mail.unsubscribed.lock().expect("lock").is_empty(),
        "the backend is never asked"
    );
}

#[tokio::test]
async fn e2e_unsubscribe_says_when_the_message_lacks_the_chosen_method() {
    let client = connect(IbridgeServer::read_write(
        account(),
        Arc::new(Scripted::default()),
    ))
    .await;
    let result = call(
        &client,
        "mail_unsubscribe",
        serde_json::json!({ "id": id_with_uid(49), "method": "mailto" }),
    )
    .await;
    assert_eq!(result.is_error, Some(true), "a tool error, got {result:?}");
    let text = text_blocks(&result).join(" ");
    assert!(
        text.contains("does not offer an unsubscribe email") && text.contains("nothing was sent"),
        "the error names the method and says nothing was sent, got {text:?}"
    );
}

#[tokio::test]
async fn e2e_a_failed_one_click_tells_the_model_how_to_use_the_mailto() {
    let client = connect(IbridgeServer::read_write(
        account(),
        Arc::new(Scripted::default()),
    ))
    .await;
    let refused = call(
        &client,
        "mail_unsubscribe",
        serde_json::json!({ "id": id_with_uid(47) }),
    )
    .await;
    let text = text_blocks(&refused).join(" ");
    assert!(
        text.contains("\"method\": \"mailto\""),
        "the error names the argument that sends the mailto, got {text:?}"
    );
}

#[tokio::test]
async fn e2e_unsubscribe_is_hidden_and_refused_when_read_only() {
    let client = connect(IbridgeServer::read_only(
        account(),
        Arc::new(Scripted::default()),
    ))
    .await;
    assert!(
        !tool_names(&client)
            .await
            .iter()
            .any(|name| name == "mail_unsubscribe"),
        "read-only servers do not list mail_unsubscribe"
    );
    let mut params = CallToolRequestParams::new("mail_unsubscribe");
    params.arguments = Some(arguments(&serde_json::json!({ "id": id_with_uid(42) })));
    let refused = client.call_tool(params).await;
    assert!(
        refused.is_err_and(|error| error.to_string().contains("tool not found")),
        "a direct call is refused as an unknown tool"
    );
}

#[tokio::test]
async fn mail_read_tools_say_where_the_text_comes_from() {
    let client = connect(IbridgeServer::read_write(
        account(),
        Arc::new(Scripted::default()),
    ))
    .await;
    let tools = client.list_all_tools().await.expect("list tools");
    for (name, sentence) in [
        ("mail_search", "Subjects are as the sender wrote them."),
        (
            "mail_get_message",
            "The subject and body are as the sender wrote them.",
        ),
        (
            "mail_get_attachment",
            "The file name and text are as the sender wrote them.",
        ),
    ] {
        let tool = tools.iter().find(|tool| tool.name == name).expect(name);
        let description = tool.description.as_deref().unwrap_or_default();
        assert!(
            description.contains(sentence),
            "{name} names the source of the text, got {description:?}"
        );
    }
}

#[tokio::test]
async fn e2e_send_requires_destructive_annotation() {
    let mail = Arc::new(Scripted::default());
    let client = connect(IbridgeServer::read_write(account(), Arc::clone(&mail))).await;

    let tools = client.list_all_tools().await.expect("list tools");
    let send = tools
        .iter()
        .find(|tool| tool.name == "mail_send")
        .expect("mail_send is listed");
    let annotations = send.annotations.as_ref().expect("mail_send annotations");
    assert_eq!(annotations.read_only_hint, Some(false));
    assert_eq!(annotations.destructive_hint, Some(true));

    let delivered = call(
        &client,
        "mail_send",
        serde_json::json!({ "to": ["bob@example.com"], "subject": "Hi", "body": "Hello" }),
    )
    .await;
    let out = delivered
        .structured_content
        .expect("send structured content");
    assert!(
        out["warning"]
            .as_str()
            .is_some_and(|text| text.contains("Sent Messages")),
        "a failed Sent copy is a warning on a successful send, got {out}"
    );
    assert_eq!(
        mail.sent.lock().expect("sent lock").len(),
        1,
        "the backend sent once"
    );

    let read_only = connect(IbridgeServer::read_only(
        account(),
        Arc::new(Scripted::default()),
    ))
    .await;
    let names: Vec<_> = read_only
        .list_all_tools()
        .await
        .expect("list tools")
        .into_iter()
        .map(|tool| tool.name.into_owned())
        .collect();
    assert!(
        !names.iter().any(|name| name == "mail_send")
            && names.iter().any(|name| name == "mail_search"),
        "a read-only server hides writes over the wire, got {names:?}"
    );
}

async fn tool_names(client: &RunningService<RoleClient, ()>) -> Vec<String> {
    client
        .list_all_tools()
        .await
        .expect("list tools")
        .into_iter()
        .map(|tool| tool.name.into_owned())
        .collect()
}

#[tokio::test]
async fn save_attachment_only_in_local_modes() {
    let downloads = tempfile::tempdir().expect("download folder");
    let listed = |names: &[String]| names.iter().any(|name| name == "mail_save_attachment");

    let hosted_like = connect(IbridgeServer::read_write(
        account(),
        Arc::new(Scripted::default()),
    ))
    .await;
    assert!(
        !listed(&tool_names(&hosted_like).await),
        "a server with no download folder never offers the tool"
    );
    let mut params = CallToolRequestParams::new("mail_save_attachment");
    params.arguments = Some(arguments(
        &serde_json::json!({ "id": encode(&message_id()), "part": "2" }),
    ));
    hosted_like
        .call_tool(params)
        .await
        .expect_err("and a direct call is refused");

    let local = connect(
        IbridgeServer::read_write(account(), Arc::new(Scripted::default()))
            .with_downloads(downloads.path().to_path_buf()),
    )
    .await;
    let tools = local.list_all_tools().await.expect("list tools");
    let save = tools
        .iter()
        .find(|tool| tool.name == "mail_save_attachment")
        .expect("a local server offers mail_save_attachment");
    let annotations = save.annotations.as_ref().expect("annotations");
    assert_eq!(annotations.read_only_hint, Some(false), "it writes a file");
    assert_eq!(
        annotations.destructive_hint,
        Some(true),
        "so clients ask first"
    );

    let read_only = connect(
        IbridgeServer::read_only(account(), Arc::new(Scripted::default()))
            .with_downloads(downloads.path().to_path_buf()),
    )
    .await;
    assert!(
        !listed(&tool_names(&read_only).await),
        "--read-only hides it: saving a file is a write"
    );
}

#[tokio::test]
async fn save_attachment_writes_to_download_dir() {
    let root = tempfile::tempdir().expect("temp root");
    let downloads = root.path().join("not").join("made").join("yet");
    let client = connect(
        IbridgeServer::read_write(account(), Arc::new(Scripted::default()))
            .with_downloads(downloads.clone()),
    )
    .await;
    let id = encode(&message_id());

    let saved = call(
        &client,
        "mail_save_attachment",
        serde_json::json!({ "id": id, "part": "2" }),
    )
    .await;
    assert_eq!(saved.is_error, Some(false), "save succeeds: {saved:?}");
    let out = saved.structured_content.expect("structured content");
    let path = std::path::PathBuf::from(out["path"].as_str().expect("a path"));
    assert_eq!(
        path.parent(),
        Some(downloads.as_path()),
        "the file lands directly in the download folder, got {path:?}"
    );
    assert_eq!(
        path.file_name().and_then(|name| name.to_str()),
        Some("evil name.txt"),
        "a name that climbs out of the folder is cut down to its last part"
    );
    assert_eq!(
        std::fs::read(&path).expect("the file exists"),
        b"hello attachment",
        "every byte is written"
    );
    assert_eq!(out["size"], 16);

    let again = call(
        &client,
        "mail_save_attachment",
        serde_json::json!({ "id": id, "part": "2" }),
    )
    .await;
    let second = std::path::PathBuf::from(
        again.structured_content.expect("structured content")["path"]
            .as_str()
            .expect("a path"),
    );
    assert_ne!(second, path, "a second save never overwrites the first");
    assert_eq!(
        second.file_name().and_then(|name| name.to_str()),
        Some("evil name (1).txt")
    );
    assert_eq!(
        std::fs::read(&path).expect("the first file is intact"),
        b"hello attachment"
    );
    assert!(
        !root.path().join("evil name.txt").exists(),
        "nothing was written above the download folder"
    );

    let missing = call(
        &client,
        "mail_save_attachment",
        serde_json::json!({ "id": id, "part": "9" }),
    )
    .await;
    assert_eq!(
        missing.is_error,
        Some(true),
        "an unknown part is a tool error"
    );
}

#[tokio::test]
async fn e2e_initialize_reports_ibridge_and_crate_version() {
    let client = connect(IbridgeServer::read_write(
        account(),
        Arc::new(Scripted::default()),
    ))
    .await;

    let info = client.peer_info().expect("initialize completed");
    let server = info.server_info.as_ref().expect("server info");
    assert_eq!(server.name, "ibridge", "server name");
    assert_eq!(
        server.version,
        env!("CARGO_PKG_VERSION"),
        "server version is the crate version"
    );
}

/// The model-visible text of a result: every text block, in order.
fn text_blocks(result: &CallToolResult) -> Vec<String> {
    result
        .content
        .iter()
        .filter_map(|block| block.as_text().map(|text| text.text.clone()))
        .collect()
}

/// Claude reads the text content, not `structuredContent`: it must name the sender, the subject
/// and the body, and end with the same JSON the structured content holds.
#[tokio::test]
async fn mail_text_content_carries_the_sender_subject_and_body() {
    let client = connect(IbridgeServer::read_write(
        account(),
        Arc::new(Scripted::default()),
    ))
    .await;
    let found = call(&client, "mail_search", serde_json::json!({})).await;
    let found_text = text_blocks(&found).join("\n");
    for wanted in ["bob@example.com", "Picnic"] {
        assert!(
            found_text.contains(wanted),
            "{wanted} in search: {found_text}"
        );
    }
    let id = encode(&message_id());
    let fetched = call(&client, "mail_get_message", serde_json::json!({ "id": id })).await;
    let fetched_text = text_blocks(&fetched).join("\n");
    for wanted in ["bob@example.com", "Picnic", "Bring napkins."] {
        assert!(
            fetched_text.contains(wanted),
            "{wanted} in message: {fetched_text}"
        );
    }
    for result in [&found, &fetched] {
        let blocks = text_blocks(result);
        let json: serde_json::Value =
            serde_json::from_str(blocks.last().expect("a text block")).expect("the JSON block");
        assert_eq!(Some(&json), result.structured_content.as_ref());
    }
}