mentra 0.18.3

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
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
//! 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};

const REMOTE_CANARY: &str = "REMOTE_CANARY_MUST_NOT_SURFACE";

fn assert_remote_canary_absent(error: &McpSseError) {
    let display = error.to_string();
    let debug = format!("{error:?}");
    assert!(!display.contains(REMOTE_CANARY), "got {display}");
    assert!(!debug.contains(REMOTE_CANARY), "got {debug}");
}

/// 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": REMOTE_CANARY}], "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(REMOTE_CANARY));
}

#[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": REMOTE_CANARY,
            "data": {"forged": REMOTE_CANARY}
        }
    }));

    let (result, _client) = calling.await.expect("no panic");
    let error = result.expect_err("a JSON-RPC error is a failure");
    let McpSseError::JsonRpc(rpc) = &error else {
        panic!("got {error:?}");
    };
    assert_eq!(rpc.code, -32602);
    assert_eq!(rpc.message, "server message omitted");
    assert!(rpc.data.is_none(), "server data must be discarded");
    assert_remote_canary_absent(&error);
    assert!(error.to_string().contains("-32602"), "got {error}");
}

#[tokio::test(flavor = "multi_thread")]
async fn response_decode_errors_do_not_retain_server_text() {
    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": REMOTE_CANARY, "isError": false}
    }));

    let (result, _client) = calling.await.expect("no panic");
    let error = result.expect_err("the response shape is invalid");
    assert!(matches!(error, McpSseError::ParseError(_)), "got {error:?}");
    assert_remote_canary_absent(&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://remote-canary-must-not-surface.invalid/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_remote_canary_absent(&error);
    assert!(
        !format!("{error:?}").contains("remote-canary-must-not-surface"),
        "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:?}"
    );
    assert!(!error.to_string().contains("remote-canary"), "got {error}");
    assert!(
        !format!("{error:?}").contains("remote-canary"),
        "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:?}"
    );
}

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

    server.wait_for_stream();
    server.queue_post_reply(PostReply::StallBeforeHeaders);
    server.send_endpoint("/messages/?session_id=abc");
    server.wait_for_posts(1);

    let error = tokio::time::timeout(std::time::Duration::from_secs(2), connecting)
        .await
        .expect("the configured initialize deadline must include its POST response head")
        .expect("no panic")
        .expect_err("the initialize POST never receives response headers");
    server.release_stalled_posts();

    assert!(matches!(error, McpSseError::Timeout(_)), "got {error:?}");
    assert_eq!(
        server.posts().len(),
        1,
        "an initialize timeout must not send a second request"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn bounds_the_initialized_notification_post() {
    let server = SseTestServer::start();
    let mut config = config(&server);
    config.limits = McpSseLimits {
        initialize_timeout: std::time::Duration::from_millis(150),
        ..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.queue_post_reply(PostReply::StallBeforeHeaders);
    server.send_message(&initialize_result(1));
    server.wait_for_posts(2);

    let error = tokio::time::timeout(std::time::Duration::from_secs(2), connecting)
        .await
        .expect("the configured initialize deadline must bound the notification POST")
        .expect("no panic")
        .expect_err("a notification POST that never answers must fail connect");
    server.release_stalled_posts();

    assert!(matches!(error, McpSseError::Timeout(_)), "got {error:?}");
    assert_eq!(
        server.posts().len(),
        2,
        "tools/list must not start after the initialized notification timed out"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn bounds_the_entire_tool_call_when_post_headers_never_arrive() {
    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 = std::sync::Arc::new(connect(&server, config).await);

    server.queue_post_reply(PostReply::StallBeforeHeaders);
    let calling = {
        let client = std::sync::Arc::clone(&client);
        tokio::spawn(async move { client.call_tool("charge_card", None).await })
    };
    server.wait_for_posts(4);

    let error = tokio::time::timeout(std::time::Duration::from_secs(2), calling)
        .await
        .expect("the configured call deadline must include the POST response head")
        .expect("no panic")
        .expect_err("the server withheld its response head");
    assert!(
        matches!(error, McpSseError::RequestIndeterminate { .. }),
        "the server read the request body, so delivery is ambiguous: {error:?}"
    );
    assert_eq!(
        server
            .posts()
            .iter()
            .filter(|request| request.rpc_method().as_deref() == Some("tools/call"))
            .count(),
        1,
        "the ambiguous tool call must never be replayed"
    );

    // The timeout removes only this request's correlation state. Once the
    // fixture releases the abandoned POST connection, the SSE session remains
    // able to correlate a later, explicitly requested call.
    server.release_stalled_posts();
    let calling = {
        let client = std::sync::Arc::clone(&client);
        tokio::spawn(async move { client.call_tool("search", None).await })
    };
    server.wait_for_posts(5);
    server.send_message(&json!({
        "jsonrpc": "2.0",
        "id": 4,
        "result": {"content": [{"type": "text", "text": "still usable"}], "isError": false}
    }));
    assert_eq!(
        calling
            .await
            .expect("no panic")
            .expect("a later explicit call should succeed")
            .content[0]
            .text
            .as_deref(),
        Some("still usable")
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn bounds_the_entire_tool_call_while_draining_the_post_body() {
    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;

    server.queue_post_reply(PostReply::StallAfterHeaders);
    let calling =
        tokio::spawn(async move { (client.call_tool("charge_card", None).await, client) });
    server.wait_for_posts(4);
    server.wait_for_post_response_headers(4);

    let (result, _client) = tokio::time::timeout(std::time::Duration::from_secs(2), calling)
        .await
        .expect("the configured call deadline must include response-body drain")
        .expect("no panic");
    server.release_stalled_posts();

    let error = result.expect_err("the declared response body never arrived");
    assert!(
        matches!(error, McpSseError::RequestIndeterminate { .. }),
        "the tool may have run before the POST response body stalled: {error:?}"
    );
    assert_eq!(
        server
            .posts()
            .iter()
            .filter(|request| request.rpc_method().as_deref() == Some("tools/call"))
            .count(),
        1,
        "the ambiguous tool call must never be replayed"
    );
}

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

    server.queue_post_reply(PostReply::Drop);
    let error = client
        .call_tool("charge_card", None)
        .await
        .expect_err("the fixture drops the POST connection after reading its body");

    assert!(
        matches!(error, McpSseError::RequestIndeterminate { .. }),
        "a transport failure cannot prove non-delivery: {error:?}"
    );
    assert_eq!(
        server
            .posts()
            .iter()
            .filter(|request| request.rpc_method().as_deref() == Some("tools/call"))
            .count(),
        1,
        "the dropped tool call must never be replayed"
    );
}

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

    server.queue_post_reply(PostReply::Status {
        code: 503,
        body: "failed after dispatch".to_string(),
    });
    let error = client
        .call_tool("charge_card", None)
        .await
        .expect_err("a non-success POST status fails the call");

    assert!(
        matches!(error, McpSseError::RequestIndeterminate { .. }),
        "HTTP status cannot prove that the server did no work: {error:?}"
    );
    assert_eq!(
        server
            .posts()
            .iter()
            .filter(|request| request.rpc_method().as_deref() == Some("tools/call"))
            .count(),
        1,
        "the failed tool call must never be replayed"
    );
}

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

    server.queue_post_reply(PostReply::Redirect {
        location: "http://evil.example/messages".to_string(),
    });
    let error = client
        .call_tool("charge_card", None)
        .await
        .expect_err("a redirected POST fails the call");

    assert!(
        matches!(error, McpSseError::RequestIndeterminate { .. }),
        "a redirect response cannot prove that the original server did no work: {error:?}"
    );
    assert_eq!(
        server
            .posts()
            .iter()
            .filter(|request| request.rpc_method().as_deref() == Some("tools/call"))
            .count(),
        1,
        "the client must neither follow nor replay the redirected tool call"
    );
}

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

    server.queue_post_reply(PostReply::StallBeforeHeaders);
    let calling = {
        let client = std::sync::Arc::clone(&client);
        tokio::spawn(async move { client.call_tool("charge_card", None).await })
    };
    server.wait_for_posts(4);
    calling.abort();
    assert!(
        calling
            .await
            .expect_err("the call task was cancelled")
            .is_cancelled()
    );

    assert!(
        super::lock_pending(&client.pending).waiters.is_empty(),
        "cancelling the future must remove its pending correlation entry"
    );
    assert_eq!(
        server
            .posts()
            .iter()
            .filter(|request| request.rpc_method().as_deref() == Some("tools/call"))
            .count(),
        1,
        "cancellation must not cause an automatic replay"
    );
    server.release_stalled_posts();
}

// ---------------------------------------------------------------------------
// 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"
    );
}