mentra 0.12.0

An agent runtime for tool-using LLM applications
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
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
//! Tests for the legacy MCP HTTP+SSE client, driven by a local fixture.

use serde_json::json;

use super::{McpSseClient, McpSseError};
use crate::mcp::sse::config::{McpSseLimits, McpSseServerConfig};
use crate::mcp::sse::testing::{PostReply, SseTestServer, StreamOpening};

/// The `initialize` result every handshake test replies with.
fn initialize_result(id: u64) -> serde_json::Value {
    json!({
        "jsonrpc": "2.0",
        "id": id,
        "result": {
            "protocolVersion": "2024-11-05",
            "capabilities": {"tools": {}},
            "serverInfo": {"name": "fixture", "version": "1.2.3"}
        }
    })
}

/// A single-page `tools/list` result.
fn tools_result(id: u64, tools: serde_json::Value) -> serde_json::Value {
    json!({"jsonrpc": "2.0", "id": id, "result": {"tools": tools}})
}

fn config(server: &SseTestServer) -> McpSseServerConfig {
    McpSseServerConfig::new("fixture", server.sse_url())
}

/// Drives the fixture through the handshake so a test can reach a connected
/// client without repeating the three scripted replies.
async fn connect(server: &SseTestServer, config: McpSseServerConfig) -> McpSseClient {
    let connecting = tokio::spawn(async move { McpSseClient::connect(&config).await });

    server.wait_for_stream();
    server.send_endpoint("/messages/?session_id=abc");

    server.wait_for_posts(1);
    server.send_message(&initialize_result(1));

    // The initialized notification and tools/list follow.
    server.wait_for_posts(3);
    server.send_message(&tools_result(
        2,
        json!([{
            "name": "search",
            "description": "Search the corpus",
            "inputSchema": {"type": "object", "properties": {"q": {"type": "string"}}}
        }]),
    ));

    connecting
        .await
        .expect("the connect task should not panic")
        .expect("the handshake should succeed")
}

// ---------------------------------------------------------------------------
// Lifecycle
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread")]
async fn completes_the_initialize_initialized_and_tools_list_handshake() {
    let server = SseTestServer::start();
    let client = connect(&server, config(&server)).await;

    assert_eq!(
        client.server_info().map(|info| info.name.as_str()),
        Some("fixture")
    );
    assert_eq!(client.tools().len(), 1);
    assert_eq!(client.tools()[0].name, "search");

    let methods: Vec<Option<String>> = server
        .posts()
        .iter()
        .map(|request| request.rpc_method())
        .collect();
    assert_eq!(
        methods,
        vec![
            Some("initialize".to_string()),
            Some("notifications/initialized".to_string()),
            Some("tools/list".to_string()),
        ],
        "the handshake must follow the 2024-11-05 order"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn the_initialized_notification_carries_no_request_id() {
    let server = SseTestServer::start();
    let _client = connect(&server, config(&server)).await;

    let notification = server
        .posts()
        .into_iter()
        .find(|request| request.rpc_method().as_deref() == Some("notifications/initialized"))
        .expect("the notification should be sent");
    assert!(
        notification.rpc_id().is_none(),
        "a notification must not carry an id"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn opens_the_stream_with_the_event_stream_accept_header() {
    let server = SseTestServer::start();
    let _client = connect(&server, config(&server)).await;

    let stream_request = server
        .requests()
        .into_iter()
        .find(|request| request.method == "GET")
        .expect("the stream should be opened with GET");
    assert_eq!(
        stream_request.header("accept"),
        Some("text/event-stream"),
        "the GET must advertise the event stream"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn posts_json_rpc_messages_as_application_json() {
    let server = SseTestServer::start();
    let _client = connect(&server, config(&server)).await;

    let post = server.posts().into_iter().next().expect("a POST is sent");
    assert_eq!(post.header("content-type"), Some("application/json"));
}

#[tokio::test(flavor = "multi_thread")]
async fn posts_to_the_endpoint_named_by_the_server() {
    let server = SseTestServer::start();
    let _client = connect(&server, config(&server)).await;

    let post = server.posts().into_iter().next().expect("a POST is sent");
    assert_eq!(
        post.target, "/messages/?session_id=abc",
        "the session id query must be preserved verbatim"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn accepts_a_202_response_to_the_message_post() {
    let server = SseTestServer::start();
    // 202 Accepted is what both reference servers return.
    server.queue_post_reply(PostReply::Accepted);
    let client = connect(&server, config(&server)).await;
    assert_eq!(client.tools().len(), 1);
}

#[tokio::test(flavor = "multi_thread")]
async fn accepts_a_200_response_to_the_message_post() {
    let server = SseTestServer::start();
    server.queue_post_reply(PostReply::Ok);
    let client = connect(&server, config(&server)).await;
    assert_eq!(client.tools().len(), 1);
}

#[tokio::test(flavor = "multi_thread")]
async fn walks_every_page_of_a_paginated_tools_list() {
    let server = SseTestServer::start();
    let config = config(&server);
    let connecting = tokio::spawn(async move { McpSseClient::connect(&config).await });

    server.wait_for_stream();
    server.send_endpoint("/messages/?session_id=abc");
    server.wait_for_posts(1);
    server.send_message(&initialize_result(1));

    server.wait_for_posts(3);
    server.send_message(&json!({
        "jsonrpc": "2.0",
        "id": 2,
        "result": {
            "tools": [{"name": "first", "inputSchema": {"type": "object"}}],
            "nextCursor": "page-2"
        }
    }));

    server.wait_for_posts(4);
    server.send_message(&tools_result(
        3,
        json!([{"name": "second", "inputSchema": {"type": "object"}}]),
    ));

    let client = connecting
        .await
        .expect("no panic")
        .expect("the handshake should succeed");

    let names: Vec<&str> = client
        .tools()
        .iter()
        .map(|tool| tool.name.as_str())
        .collect();
    assert_eq!(names, vec!["first", "second"]);

    let cursors: Vec<Option<String>> = server
        .posts()
        .iter()
        .filter(|request| request.rpc_method().as_deref() == Some("tools/list"))
        .map(|request| {
            serde_json::from_str::<serde_json::Value>(&request.body)
                .ok()?
                .get("params")?
                .get("cursor")?
                .as_str()
                .map(str::to_string)
        })
        .collect();
    assert_eq!(
        cursors,
        vec![None, Some("page-2".to_string())],
        "the second page must echo the server's opaque cursor"
    );
}

/// A server that keeps returning a cursor must not loop forever. Cursors are
/// opaque, so a repeat cannot be detected by value; only a page bound stops it.
#[tokio::test(flavor = "multi_thread")]
async fn stops_paginating_a_server_that_never_ends_its_tools_list() {
    let server = SseTestServer::start();
    let mut config = config(&server);
    config.limits = McpSseLimits {
        max_tool_pages: 4,
        ..McpSseLimits::default()
    };
    let connecting = tokio::spawn(async move { McpSseClient::connect(&config).await });

    server.wait_for_stream();
    server.send_endpoint("/messages/?session_id=abc");
    server.wait_for_posts(1);
    server.send_message(&initialize_result(1));

    // Answer each tools/list with the same cursor. Replies must follow their
    // request, not precede it: a response for an unregistered id is dropped.
    // With a bound of 4 the client asks exactly four times and then gives up,
    // so the count is exact rather than open-ended.
    for page in 0..4 {
        server.wait_for_posts(3 + page);
        server.send_message(&json!({
            "jsonrpc": "2.0",
            "id": 2 + page,
            "result": {"tools": [], "nextCursor": "always-more"}
        }));
    }

    let error = tokio::time::timeout(std::time::Duration::from_secs(10), connecting)
        .await
        .expect("the client must give up rather than paginate forever")
        .expect("no panic")
        .expect_err("an endless cursor must fail");
    assert!(
        matches!(error, McpSseError::TooManyToolPages { limit: 4 }),
        "got {error:?}"
    );

    let pages = server
        .posts()
        .into_iter()
        .filter(|request| request.rpc_method().as_deref() == Some("tools/list"))
        .count();
    assert_eq!(
        pages, 4,
        "the client must stop at the configured page bound"
    );
}

// ---------------------------------------------------------------------------
// Tool calls
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread")]
async fn calls_a_tool_and_returns_its_content() {
    let server = SseTestServer::start();
    let client = connect(&server, config(&server)).await;

    let calling = tokio::spawn(async move {
        (
            client.call_tool("search", Some(json!({"q": "logs"}))).await,
            client,
        )
    });

    server.wait_for_posts(4);
    server.send_message(&json!({
        "jsonrpc": "2.0",
        "id": 3,
        "result": {"content": [{"type": "text", "text": "found it"}], "isError": false}
    }));

    let (result, _client) = calling.await.expect("no panic");
    let result = result.expect("the call should succeed");
    assert!(!result.is_error);
    assert_eq!(result.content[0].text.as_deref(), Some("found it"));

    let call = server
        .posts()
        .into_iter()
        .find(|request| request.rpc_method().as_deref() == Some("tools/call"))
        .expect("the call should be posted");
    let body: serde_json::Value = serde_json::from_str(&call.body).expect("valid JSON");
    assert_eq!(body["params"]["name"], "search");
    assert_eq!(body["params"]["arguments"]["q"], "logs");
}

#[tokio::test(flavor = "multi_thread")]
async fn surfaces_a_tool_result_flagged_as_an_error() {
    let server = SseTestServer::start();
    let client = connect(&server, config(&server)).await;

    let calling = tokio::spawn(async move { (client.call_tool("search", None).await, client) });

    server.wait_for_posts(4);
    server.send_message(&json!({
        "jsonrpc": "2.0",
        "id": 3,
        "result": {"content": [{"type": "text", "text": "upstream down"}], "isError": true}
    }));

    let (result, _client) = calling.await.expect("no panic");
    let result = result.expect("an isError result is still a successful response");
    assert!(
        result.is_error,
        "isError must be preserved rather than turned into a transport failure"
    );
    assert_eq!(result.content[0].text.as_deref(), Some("upstream down"));
}

#[tokio::test(flavor = "multi_thread")]
async fn surfaces_a_json_rpc_error_response() {
    let server = SseTestServer::start();
    let client = connect(&server, config(&server)).await;

    let calling = tokio::spawn(async move { (client.call_tool("missing", None).await, client) });

    server.wait_for_posts(4);
    server.send_message(&json!({
        "jsonrpc": "2.0",
        "id": 3,
        "error": {"code": -32602, "message": "Unknown tool"}
    }));

    let (result, _client) = calling.await.expect("no panic");
    let error = result.expect_err("a JSON-RPC error is a failure");
    assert!(matches!(error, McpSseError::JsonRpc(_)), "got {error:?}");
}

#[tokio::test(flavor = "multi_thread")]
async fn resolves_concurrent_calls_whose_responses_arrive_in_reverse_order() {
    let server = SseTestServer::start();
    let client = std::sync::Arc::new(connect(&server, config(&server)).await);

    let first = {
        let client = std::sync::Arc::clone(&client);
        tokio::spawn(async move { client.call_tool("search", Some(json!({"q": "one"}))).await })
    };
    let second = {
        let client = std::sync::Arc::clone(&client);
        tokio::spawn(async move { client.call_tool("search", Some(json!({"q": "two"}))).await })
    };

    // Both calls must be in flight before either is answered.
    server.wait_for_posts(5);

    // Answer the second request first: the stream carries no ordering guarantee.
    server.send_message(&json!({
        "jsonrpc": "2.0",
        "id": 4,
        "result": {"content": [{"type": "text", "text": "second"}], "isError": false}
    }));
    server.send_message(&json!({
        "jsonrpc": "2.0",
        "id": 3,
        "result": {"content": [{"type": "text", "text": "first"}], "isError": false}
    }));

    let first = first
        .await
        .expect("no panic")
        .expect("first should resolve");
    let second = second
        .await
        .expect("no panic")
        .expect("second should resolve");

    assert_eq!(
        first.content[0].text.as_deref(),
        Some("first"),
        "each caller must receive the response matching its own id"
    );
    assert_eq!(second.content[0].text.as_deref(), Some("second"));
}

// ---------------------------------------------------------------------------
// Authentication
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread")]
async fn sends_configured_headers_on_both_the_stream_and_the_posts() {
    let server = SseTestServer::start();
    let config = McpSseServerConfig::new("fixture", server.sse_url())
        .with_bearer_token("super-secret-token")
        .with_header("x-tenant", "acme")
        .allowing_plaintext_credentials();
    let _client = connect(&server, config).await;

    let requests = server.requests();
    let stream_request = requests
        .iter()
        .find(|request| request.method == "GET")
        .expect("the stream is opened");
    assert_eq!(
        stream_request.header("authorization"),
        Some("Bearer super-secret-token"),
        "the GET must carry the credential"
    );
    assert_eq!(stream_request.header("x-tenant"), Some("acme"));

    let post = requests
        .iter()
        .find(|request| request.method == "POST")
        .expect("a message is posted");
    assert_eq!(
        post.header("authorization"),
        Some("Bearer super-secret-token"),
        "the POST must carry the credential too"
    );
    assert_eq!(post.header("x-tenant"), Some("acme"));
}

#[tokio::test(flavor = "multi_thread")]
async fn header_values_never_appear_in_client_debug_output() {
    let server = SseTestServer::start();
    let config = McpSseServerConfig::new("fixture", server.sse_url())
        .with_bearer_token("super-secret-token")
        .allowing_plaintext_credentials();
    let client = connect(&server, config).await;

    let rendered = format!("{client:?}");
    assert!(
        !rendered.contains("super-secret-token"),
        "the client must not render its credentials: {rendered}"
    );
}

// ---------------------------------------------------------------------------
// Endpoint handling
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread")]
async fn rejects_an_endpoint_pointing_at_another_origin() {
    let server = SseTestServer::start();
    let config = config(&server);
    let connecting = tokio::spawn(async move { McpSseClient::connect(&config).await });

    server.wait_for_stream();
    server.send_endpoint("https://evil.example/messages");

    let error = connecting
        .await
        .expect("no panic")
        .expect_err("a cross-origin endpoint must be refused");
    assert!(matches!(error, McpSseError::Endpoint(_)), "got {error:?}");

    assert!(
        server.posts().is_empty(),
        "nothing may be sent once the endpoint is refused"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn rejects_a_protocol_relative_endpoint() {
    let server = SseTestServer::start();
    let config = config(&server);
    let connecting = tokio::spawn(async move { McpSseClient::connect(&config).await });

    server.wait_for_stream();
    // Looks like a path but replaces the whole authority.
    server.send_endpoint("//evil.example/messages");

    let error = connecting
        .await
        .expect("no panic")
        .expect_err("a protocol-relative endpoint must be refused");
    assert!(matches!(error, McpSseError::Endpoint(_)), "got {error:?}");
    assert!(server.posts().is_empty());
}

#[tokio::test(flavor = "multi_thread")]
async fn honors_only_the_first_endpoint_event() {
    let server = SseTestServer::start();
    let config = config(&server);
    let connecting = tokio::spawn(async move { McpSseClient::connect(&config).await });

    server.wait_for_stream();
    server.send_endpoint("/messages/?session_id=first");
    // A later endpoint event must not redirect traffic mid-session.
    server.send_endpoint("/messages/?session_id=second");

    server.wait_for_posts(1);
    server.send_message(&initialize_result(1));
    server.wait_for_posts(3);
    server.send_message(&tools_result(2, json!([])));

    let _client = connecting.await.expect("no panic").expect("handshake");

    for post in server.posts() {
        assert_eq!(
            post.target, "/messages/?session_id=first",
            "every POST must use the first endpoint"
        );
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn rejects_an_oversized_endpoint_event() {
    let server = SseTestServer::start();
    let mut config = config(&server);
    config.limits = McpSseLimits {
        max_endpoint_bytes: 64,
        ..McpSseLimits::default()
    };
    let connecting = tokio::spawn(async move { McpSseClient::connect(&config).await });

    server.wait_for_stream();
    server.send_endpoint(&format!("/messages/?session_id={}", "x".repeat(512)));

    let error = connecting
        .await
        .expect("no panic")
        .expect_err("an oversized endpoint must be refused");
    assert!(
        matches!(error, McpSseError::EndpointTooLarge { limit: 64 }),
        "got {error:?}"
    );
    assert!(server.posts().is_empty());
}

// ---------------------------------------------------------------------------
// Stream framing
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread")]
async fn reassembles_an_endpoint_event_split_across_chunks() {
    let server = SseTestServer::start();
    let config = config(&server);
    let connecting = tokio::spawn(async move { McpSseClient::connect(&config).await });

    server.wait_for_stream();
    // One logical event delivered as three separate TCP chunks.
    server.send_raw("event: end");
    server.send_raw("point\ndata: /messa");
    server.send_raw("ges/?session_id=abc\n\n");

    server.wait_for_posts(1);
    server.send_message(&initialize_result(1));
    server.wait_for_posts(3);
    server.send_message(&tools_result(2, json!([])));

    let _client = connecting.await.expect("no panic").expect("handshake");
    assert_eq!(
        server.posts()[0].target,
        "/messages/?session_id=abc",
        "a split event must reassemble exactly"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn reads_a_stream_using_crlf_terminators_and_heartbeats() {
    let server = SseTestServer::start();
    let config = config(&server);
    let connecting = tokio::spawn(async move { McpSseClient::connect(&config).await });

    server.wait_for_stream();
    // sse-starlette, used by most Python MCP servers, defaults to CRLF and
    // sends comment-only heartbeats.
    server.send_raw(": ping - keepalive\r\n\r\n");
    server.send_raw("event: endpoint\r\ndata: /messages/?session_id=abc\r\n\r\n");

    server.wait_for_posts(1);
    server.send_raw(": ping - keepalive\r\n\r\n");
    server.send_raw(format!(
        "event: message\r\ndata: {}\r\n\r\n",
        initialize_result(1)
    ));

    server.wait_for_posts(3);
    server.send_raw(format!(
        "event: message\r\ndata: {}\r\n\r\n",
        tools_result(
            2,
            json!([{"name": "search", "inputSchema": {"type": "object"}}])
        )
    ));

    let client = connecting.await.expect("no panic").expect("handshake");
    assert_eq!(client.tools().len(), 1);
}

#[tokio::test(flavor = "multi_thread")]
async fn reads_a_message_split_across_several_data_lines() {
    let server = SseTestServer::start();
    let client = connect(&server, config(&server)).await;

    let calling = tokio::spawn(async move { (client.call_tool("search", None).await, client) });

    server.wait_for_posts(4);
    // A JSON payload containing newlines is emitted as multiple data lines.
    server.send_raw(
        "event: message\ndata: {\"jsonrpc\":\"2.0\",\"id\":3,\"result\":\ndata: {\"content\":[{\"type\":\"text\",\"text\":\"ok\"}],\"isError\":false}}\n\n",
    );

    let (result, _client) = calling.await.expect("no panic");
    let result = result.expect("multi-line data must rejoin into one payload");
    assert_eq!(result.content[0].text.as_deref(), Some("ok"));
}

#[tokio::test(flavor = "multi_thread")]
async fn ignores_unknown_event_names_such_as_ping() {
    let server = SseTestServer::start();
    let config = config(&server);
    let connecting = tokio::spawn(async move { McpSseClient::connect(&config).await });

    server.wait_for_stream();
    // Older sse-starlette emits a real event with non-JSON data.
    server.send_raw("event: ping\ndata: 2026-08-08 12:00:00\n\n");
    server.send_endpoint("/messages/?session_id=abc");

    server.wait_for_posts(1);
    server.send_raw("event: ping\ndata: 2026-08-08 12:00:15\n\n");
    server.send_message(&initialize_result(1));
    server.wait_for_posts(3);
    server.send_message(&tools_result(2, json!([])));

    let client = connecting.await.expect("no panic").expect("handshake");
    assert!(client.tools().is_empty());
}

#[tokio::test(flavor = "multi_thread")]
async fn ignores_a_server_initiated_request_rather_than_treating_it_as_a_response() {
    let server = SseTestServer::start();
    let client = connect(&server, config(&server)).await;

    let calling = tokio::spawn(async move { (client.call_tool("search", None).await, client) });

    server.wait_for_posts(4);
    // A ping request carries method and id but is not a response to id 3.
    server.send_message(&json!({"jsonrpc": "2.0", "id": 3, "method": "ping"}));
    server.send_message(&json!({
        "jsonrpc": "2.0",
        "id": 3,
        "result": {"content": [{"type": "text", "text": "real"}], "isError": false}
    }));

    let (result, _client) = calling.await.expect("no panic");
    let result = result.expect("the real response must still resolve the call");
    assert_eq!(result.content[0].text.as_deref(), Some("real"));
}

#[tokio::test(flavor = "multi_thread")]
async fn ignores_a_repeated_response_for_an_already_answered_id() {
    let server = SseTestServer::start();
    let client = connect(&server, config(&server)).await;

    let calling = tokio::spawn(async move { (client.call_tool("search", None).await, client) });

    server.wait_for_posts(4);
    server.send_message(&json!({
        "jsonrpc": "2.0",
        "id": 3,
        "result": {"content": [{"type": "text", "text": "first"}], "isError": false}
    }));
    // A second result for the same id must not reach the caller.
    server.send_message(&json!({
        "jsonrpc": "2.0",
        "id": 3,
        "result": {"content": [{"type": "text", "text": "second"}], "isError": false}
    }));

    let (result, client) = calling.await.expect("no panic");
    assert_eq!(
        result.expect("the first response wins").content[0]
            .text
            .as_deref(),
        Some("first")
    );

    // The connection stays usable rather than being corrupted by the duplicate.
    client.shutdown().await;
}

#[tokio::test(flavor = "multi_thread")]
async fn ignores_malformed_json_rpc_without_failing_other_calls() {
    let server = SseTestServer::start();
    let client = connect(&server, config(&server)).await;

    let calling = tokio::spawn(async move { (client.call_tool("search", None).await, client) });

    server.wait_for_posts(4);
    server.send_raw("event: message\ndata: {not json at all\n\n");
    server.send_message(&json!({
        "jsonrpc": "2.0",
        "id": 3,
        "result": {"content": [{"type": "text", "text": "ok"}], "isError": false}
    }));

    let (result, _client) = calling.await.expect("no panic");
    assert_eq!(
        result
            .expect("a malformed frame must not break the stream")
            .content[0]
            .text
            .as_deref(),
        Some("ok")
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn tears_down_the_stream_when_an_event_exceeds_the_size_limit() {
    let server = SseTestServer::start();
    let mut config = config(&server);
    config.limits = McpSseLimits {
        max_event_bytes: 256,
        ..McpSseLimits::default()
    };
    let client = connect(&server, config).await;

    let calling = tokio::spawn(async move { (client.call_tool("search", None).await, client) });

    server.wait_for_posts(4);
    server.send_raw(format!("event: message\ndata: {}\n\n", "x".repeat(4096)));

    let (result, _client) = calling.await.expect("no panic");
    let error = result.expect_err("an oversized event must fail the call");
    assert!(
        matches!(error, McpSseError::RequestIndeterminate { .. }),
        "an accepted call that never answered is indeterminate, got {error:?}"
    );
}

// ---------------------------------------------------------------------------
// Connection failures
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread")]
async fn rejects_a_stream_response_that_is_not_an_event_stream() {
    let server = SseTestServer::with_opening(StreamOpening::WrongContentType);
    let error = McpSseClient::connect(&config(&server))
        .await
        .expect_err("a JSON response is not a stream");
    assert!(
        matches!(error, McpSseError::UnexpectedContentType { .. }),
        "got {error:?}"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn accepts_an_event_stream_content_type_carrying_a_charset() {
    // The fixture answers `text/event-stream; charset=utf-8`, which is what
    // real servers send; a strict equality check would reject it.
    let server = SseTestServer::start();
    let client = connect(&server, config(&server)).await;
    assert_eq!(client.tools().len(), 1);
}

#[tokio::test(flavor = "multi_thread")]
async fn rejects_a_non_success_status_on_the_stream() {
    let server = SseTestServer::with_opening(StreamOpening::Status {
        code: 404,
        body: "not found".to_string(),
    });
    let error = McpSseClient::connect(&config(&server))
        .await
        .expect_err("404 is not a stream");
    assert!(
        matches!(error, McpSseError::HttpStatus { status, .. } if status == 404),
        "got {error:?}"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn refuses_to_follow_a_redirect_on_the_stream() {
    let server = SseTestServer::with_opening(StreamOpening::Redirect {
        location: "http://evil.example/sse".to_string(),
    });
    let error = McpSseClient::connect(&config(&server))
        .await
        .expect_err("a redirect must not be followed");
    assert!(
        matches!(error, McpSseError::RedirectRefused),
        "got {error:?}"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn reports_a_rejected_post_without_quoting_the_response_body() {
    let server = SseTestServer::start();
    let config = config(&server);
    let connecting = tokio::spawn(async move { McpSseClient::connect(&config).await });

    server.wait_for_stream();
    server.queue_post_reply(PostReply::Status {
        code: 400,
        body: "SESSION-SECRET-LEAK".to_string(),
    });
    server.send_endpoint("/messages/?session_id=abc");

    let error = connecting
        .await
        .expect("no panic")
        .expect_err("a 400 fails the handshake");
    assert!(
        matches!(error, McpSseError::HttpStatus { status, .. } if status == 400),
        "got {error:?}"
    );
    assert!(
        !error.to_string().contains("SESSION-SECRET-LEAK"),
        "server text must never reach an error: {error}"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn reports_a_server_error_on_the_message_post() {
    let server = SseTestServer::start();
    let config = config(&server);
    let connecting = tokio::spawn(async move { McpSseClient::connect(&config).await });

    server.wait_for_stream();
    server.queue_post_reply(PostReply::Status {
        code: 503,
        body: "unavailable".to_string(),
    });
    server.send_endpoint("/messages/?session_id=abc");

    let error = connecting
        .await
        .expect("no panic")
        .expect_err("a 503 fails the handshake");
    assert!(
        matches!(error, McpSseError::HttpStatus { status, .. } if status == 503),
        "got {error:?}"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn refuses_to_follow_a_redirect_on_a_message_post() {
    let server = SseTestServer::start();
    let config = config(&server);
    let connecting = tokio::spawn(async move { McpSseClient::connect(&config).await });

    server.wait_for_stream();
    server.queue_post_reply(PostReply::Redirect {
        location: "http://evil.example/messages".to_string(),
    });
    server.send_endpoint("/messages/?session_id=abc");

    let error = connecting
        .await
        .expect("no panic")
        .expect_err("a redirected POST must not be followed");
    assert!(
        matches!(error, McpSseError::RedirectRefused),
        "got {error:?}"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn rejects_an_absolute_endpoint_on_the_fixture_origin_with_a_different_port() {
    let server = SseTestServer::start();
    let config = config(&server);
    let connecting = tokio::spawn(async move { McpSseClient::connect(&config).await });

    server.wait_for_stream();
    // Same host, different port: still a different origin.
    let other_port = server
        .base_url()
        .rsplit(':')
        .next()
        .and_then(|port| port.parse::<u16>().ok())
        .map(|port| port.wrapping_add(1))
        .expect("the fixture URL carries a port");
    server.send_endpoint(&format!("http://127.0.0.1:{other_port}/messages/"));

    let error = connecting
        .await
        .expect("no panic")
        .expect_err("a different port is a different origin");
    assert!(matches!(error, McpSseError::Endpoint(_)), "got {error:?}");
    assert!(server.posts().is_empty());
}

#[tokio::test(flavor = "multi_thread")]
async fn accepts_an_absolute_endpoint_on_the_configured_origin() {
    let server = SseTestServer::start();
    let base_url = server.base_url().to_string();
    let config = config(&server);
    let connecting = tokio::spawn(async move { McpSseClient::connect(&config).await });

    server.wait_for_stream();
    // The specification permits an absolute URL as long as the origin matches.
    server.send_endpoint(&format!("{base_url}/messages/?session_id=abc"));

    server.wait_for_posts(1);
    server.send_message(&initialize_result(1));
    server.wait_for_posts(3);
    server.send_message(&tools_result(2, json!([])));

    let _client = connecting.await.expect("no panic").expect("handshake");
    assert_eq!(server.posts()[0].target, "/messages/?session_id=abc");
}

#[tokio::test(flavor = "multi_thread")]
async fn reports_a_post_the_server_never_answers() {
    let server = SseTestServer::start();
    let config = config(&server);
    let connecting = tokio::spawn(async move { McpSseClient::connect(&config).await });

    server.wait_for_stream();
    // The server accepts the connection then closes it without responding.
    server.queue_post_reply(PostReply::Drop);
    server.send_endpoint("/messages/?session_id=abc");

    let error = connecting
        .await
        .expect("no panic")
        .expect_err("a dropped POST fails the handshake");
    assert!(
        matches!(error, McpSseError::Transport(_)),
        "a dropped connection is a transport failure, got {error:?}"
    );
}

// ---------------------------------------------------------------------------
// Teardown
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread")]
async fn fails_every_pending_call_when_the_stream_reaches_eof() {
    let server = SseTestServer::start();
    let client = std::sync::Arc::new(connect(&server, config(&server)).await);

    let first = {
        let client = std::sync::Arc::clone(&client);
        tokio::spawn(async move { client.call_tool("search", Some(json!({"q": "a"}))).await })
    };
    let second = {
        let client = std::sync::Arc::clone(&client);
        tokio::spawn(async move { client.call_tool("search", Some(json!({"q": "b"}))).await })
    };

    server.wait_for_posts(5);
    server.close_stream();

    let first = first
        .await
        .expect("no panic")
        .expect_err("EOF must fail the call rather than hang");
    let second = second
        .await
        .expect("no panic")
        .expect_err("EOF must fail every call");

    assert!(
        matches!(first, McpSseError::RequestIndeterminate { .. }),
        "got {first:?}"
    );
    assert!(
        matches!(second, McpSseError::RequestIndeterminate { .. }),
        "got {second:?}"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn an_accepted_call_lost_to_a_stream_drop_is_reported_as_indeterminate() {
    let server = SseTestServer::start();
    let client = connect(&server, config(&server)).await;

    let calling =
        tokio::spawn(async move { (client.call_tool("charge_card", None).await, client) });

    server.wait_for_posts(4);
    // The POST was accepted, so the tool may well have run.
    server.abort_stream();

    let (result, _client) = calling.await.expect("no panic");
    let error = result.expect_err("a lost response is a failure");
    match error {
        McpSseError::RequestIndeterminate { method } => assert_eq!(method, "tools/call"),
        other => panic!("an accepted-but-unanswered call must be indeterminate, got {other:?}"),
    }
    assert!(
        error_says_do_not_retry(&McpSseError::RequestIndeterminate {
            method: "tools/call".to_string()
        }),
        "the message must warn against automatic retry"
    );
}

fn error_says_do_not_retry(error: &McpSseError) -> bool {
    let rendered = error.to_string();
    rendered.contains("may have executed") && rendered.contains("must not be retried")
}

#[tokio::test(flavor = "multi_thread")]
async fn never_replays_a_tool_call_after_an_ambiguous_failure() {
    let server = SseTestServer::start();
    let client = connect(&server, config(&server)).await;

    let calling =
        tokio::spawn(async move { (client.call_tool("charge_card", None).await, client) });

    server.wait_for_posts(4);
    server.abort_stream();

    let (result, _client) = calling.await.expect("no panic");
    result.expect_err("the call fails");

    // Give any (incorrect) retry a chance to appear before asserting.
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;

    let calls = server
        .posts()
        .into_iter()
        .filter(|request| request.rpc_method().as_deref() == Some("tools/call"))
        .count();
    assert_eq!(
        calls, 1,
        "a tools/call may have side effects and must never be re-sent"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn shutting_down_fails_calls_that_are_still_in_flight() {
    let server = SseTestServer::start();
    let client = std::sync::Arc::new(connect(&server, config(&server)).await);

    let calling = {
        let client = std::sync::Arc::clone(&client);
        tokio::spawn(async move { client.call_tool("search", None).await })
    };

    server.wait_for_posts(4);
    client.shutdown().await;

    let error = calling
        .await
        .expect("no panic")
        .expect_err("shutdown must resolve outstanding calls");
    assert!(
        matches!(error, McpSseError::RequestIndeterminate { .. }),
        "got {error:?}"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn a_request_made_after_shutdown_fails_immediately() {
    let server = SseTestServer::start();
    let client = connect(&server, config(&server)).await;
    client.shutdown().await;

    let error = client
        .call_tool("search", None)
        .await
        .expect_err("a shut-down client accepts no work");
    assert!(matches!(error, McpSseError::StreamClosed), "got {error:?}");
}

#[tokio::test(flavor = "multi_thread")]
async fn a_timed_out_request_does_not_leak_its_pending_entry() {
    let server = SseTestServer::start();
    let mut config = config(&server);
    config.limits = McpSseLimits {
        call_tool_timeout: std::time::Duration::from_millis(150),
        ..McpSseLimits::default()
    };
    let client = connect(&server, config).await;

    // Time out several calls, then confirm a later one still succeeds.
    for _ in 0..3 {
        let error = client
            .call_tool("search", None)
            .await
            .expect_err("no response arrives");
        assert!(
            matches!(error, McpSseError::RequestIndeterminate { .. }),
            "got {error:?}"
        );
    }

    let calling = tokio::spawn(async move { (client.call_tool("search", None).await, client) });
    server.wait_for_posts(7);
    server.send_message(&json!({
        "jsonrpc": "2.0",
        "id": 6,
        "result": {"content": [{"type": "text", "text": "late but fine"}], "isError": false}
    }));

    let (result, _client) = calling.await.expect("no panic");
    assert_eq!(
        result.expect("the connection remains usable").content[0]
            .text
            .as_deref(),
        Some("late but fine")
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn connecting_times_out_when_the_endpoint_event_never_arrives() {
    let server = SseTestServer::start();
    let mut config = config(&server);
    config.limits = McpSseLimits {
        connect_timeout: std::time::Duration::from_millis(200),
        ..McpSseLimits::default()
    };

    let connecting = tokio::spawn(async move { McpSseClient::connect(&config).await });
    server.wait_for_stream();
    // A buffering proxy is the common cause; no endpoint event is ever sent.

    let error = connecting
        .await
        .expect("no panic")
        .expect_err("the handshake cannot proceed without an endpoint");
    assert!(matches!(error, McpSseError::Timeout(_)), "got {error:?}");
}

#[tokio::test(flavor = "multi_thread")]
async fn connecting_fails_when_the_stream_closes_before_the_endpoint_arrives() {
    let server = SseTestServer::start();
    let config = config(&server);
    let connecting = tokio::spawn(async move { McpSseClient::connect(&config).await });

    server.wait_for_stream();
    server.close_stream();

    let error = connecting
        .await
        .expect("no panic")
        .expect_err("a closed stream cannot complete the handshake");
    assert!(matches!(error, McpSseError::StreamClosed), "got {error:?}");
}

/// A rejected endpoint must not leave the reader task running.
///
/// The task owns the response body, so leaking it also leaks the connection.
/// Because the reader is what consumes the stream, a leaked one keeps draining
/// events the abandoned client can never deliver — observable here as the
/// fixture continuing to accept writes long after connect returned.
#[tokio::test(flavor = "multi_thread")]
async fn a_refused_endpoint_leaves_no_reader_consuming_the_stream() {
    let server = SseTestServer::start();
    let config = config(&server);
    let connecting = tokio::spawn(async move { McpSseClient::connect(&config).await });

    server.wait_for_stream();
    server.send_endpoint("https://evil.example/messages");

    let error = connecting
        .await
        .expect("no panic")
        .expect_err("a cross-origin endpoint is refused");
    assert!(matches!(error, McpSseError::Endpoint(_)), "got {error:?}");

    // Nothing was ever sent to the server, and nothing may be sent later.
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;
    assert!(
        server.posts().is_empty(),
        "a refused endpoint must not produce any request"
    );
}