multicast 2.0.0

A declarative CLI framework for Rust with typed commands, agent discovery, HTTP, and MCP
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
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
//! Portable MCP client over HTTP.
//!
//! [`McpHttpClient`] speaks MCP to a remote server through one
//! [`crate::outbound::HttpClient`] and `futures`. It spawns no task and reads
//! no clock, thread, or async runtime, so it runs unchanged on
//! `wasm32-unknown-unknown` hosts such as a Cloudflare Worker, where the host
//! supplies the client in [`McpRemoteOptions::http_client`]. Native builds
//! default to [`crate::outbound::ReqwestHttpClient`], which follows no
//! redirect.
//!
//! Two transports are supported:
//!
//! - Streamable HTTP ([`McpHttpClient::connect`]) for every official standard.
//!   Legacy standards use `initialize` and `notifications/initialized`, echo
//!   an `Mcp-Session-Id` when the server issues one, and send
//!   `MCP-Protocol-Version` on every later request. The 2026-07-28 standard
//!   uses `server/discover`, per-request `_meta` from the modern wire codec,
//!   and the `Mcp-Method` and `Mcp-Name` headers. A response body may be
//!   `application/json` or `text/event-stream`.
//! - Legacy HTTP+SSE ([`McpHttpClient::connect_legacy_sse`]): a long-lived GET
//!   event stream announces a POST endpoint, and responses to POSTed messages
//!   arrive on that stream. The stream is read in place while a request waits,
//!   so no background reader is needed.
//!
//! Standard selection goes through [`multicast_mcp_protocol::negotiate`]. A client
//! that enables 2026-07-28 probes with `server/discover` and falls back to a
//! legacy `initialize` only on protocol evidence, the peer answering
//! `-32601 Method not found`. An authentication, server, or transport failure
//! fails closed with a coded [`McpClientError`].
//!
//! Every request has a deadline, [`McpRemoteOptions::request_timeout`], timed
//! by the host client's [`crate::outbound::HttpClient::sleep`]. Response
//! bodies are capped at [`McpRemoteOptions::max_response_bytes`], and a tool
//! listing at [`crate::mcp::MAX_REMOTE_TOOL_PAGES`] pages and
//! [`crate::mcp::MAX_REMOTE_TOOLS`] tools, so a hostile or hung server ends
//! each call with a coded error.

use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

use futures::StreamExt;
use http::header::{ACCEPT, CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue};
use multicast_mcp_protocol::{
    McpClientMetadata, McpLifecycleFamily, McpNegotiationDecision, McpNegotiationError,
    McpNegotiationEvidence, McpStandardSet, McpVersion, McpWireCodecKind,
};
use serde_json::{Map, Value};

use crate::mcp::{MAX_REMOTE_TOOL_PAGES, MAX_REMOTE_TOOLS, McpRemoteOptions};
use crate::outbound::{
    HttpBody, HttpClientError, HttpRequest, HttpResponse, Redirects, SharedHttpClient,
};

const HEADER_SESSION_ID: &str = "mcp-session-id";
const HEADER_PROTOCOL_VERSION: &str = "mcp-protocol-version";
const HEADER_METHOD: &str = "mcp-method";
const HEADER_NAME: &str = "mcp-name";
const HEADER_PARAM_PREFIX: &str = "mcp-param-";
const EVENT_STREAM: &str = "text/event-stream";
const JSON: &str = "application/json";
const METHOD_NOT_FOUND: i64 = -32601;
const INVALID_PARAMS: i64 = -32602;
/// The tasks extension identifier, as advertised in server capabilities.
const TASKS_EXTENSION: &str = "io.modelcontextprotocol/tasks";
/// Poll interval used when a task does not name one.
const DEFAULT_TASK_POLL: Duration = Duration::from_secs(2);
/// Bounds on a server-requested poll interval.
const MIN_TASK_POLL: Duration = Duration::from_millis(10);
const MAX_TASK_POLL: Duration = Duration::from_secs(60);
/// How long a task may stay unknown to its server before it counts as lost.
const TASK_LOST_AFTER: Duration = Duration::from_secs(5 * 60);
/// Largest SSE event accepted before the stream is treated as hostile.
const MAX_EVENT_BYTES: usize = 16 * 1024 * 1024;

// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------

/// Failure while connecting to or calling a remote MCP server.
///
/// Every variant has a stable machine-readable [`code`](Self::code), carried
/// into [`crate::errors::MulticastError`] by the `From` conversion.
#[derive(Debug)]
#[non_exhaustive]
pub enum McpClientError {
    /// A configured header name or value is not valid, or is reserved by the
    /// transport.
    InvalidHeader(String),
    /// The server URL is not an absolute HTTP or HTTPS URL.
    InvalidUrl(String),
    /// The HTTP exchange failed before a response arrived, or no HTTP client
    /// is available on this target.
    Transport(HttpClientError),
    /// The server rejected the credentials with HTTP 401 or 403.
    Unauthorized {
        /// HTTP status code.
        status: u16,
        /// The `WWW-Authenticate` challenge, when the server sent one.
        www_authenticate: Option<String>,
    },
    /// The server discarded the session this client was using (HTTP 404).
    SessionExpired,
    /// The server answered with an unexpected HTTP status.
    Http {
        /// HTTP status code.
        status: u16,
        /// Response body, for diagnosis.
        body: String,
    },
    /// The server answered with a JSON-RPC error.
    JsonRpc {
        /// JSON-RPC error code.
        code: i64,
        /// JSON-RPC error message.
        message: String,
        /// JSON-RPC error data, when present.
        data: Option<Value>,
    },
    /// The server violated the transport or protocol contract.
    Protocol(String),
    /// Client and server share no enabled standard.
    Negotiation(McpNegotiationError),
    /// No response arrived before the request deadline.
    Timeout {
        /// The deadline that elapsed.
        after: Duration,
    },
    /// A tool listing exceeded [`MAX_REMOTE_TOOL_PAGES`] pages or
    /// [`MAX_REMOTE_TOOLS`] tools.
    ToolLimit(String),
    /// A remote task ended in `failed`: the server could not run the call.
    TaskFailed {
        /// The remote task identifier.
        task_id: String,
        /// The error the task reported.
        error: Value,
    },
    /// A remote task was cancelled before it finished.
    TaskCancelled {
        /// The remote task identifier.
        task_id: String,
    },
    /// The server stopped recognizing a task it created for longer than the
    /// lost-task window. Whether the call ran is unknown, so it is not retried.
    TaskLost {
        /// The remote task identifier.
        task_id: String,
    },
    /// A remote task needs input that [`McpHttpClient::call_tool`] cannot
    /// supply. Use [`McpHttpClient::call_tool_outcome`] to answer it.
    TaskInputRequired {
        /// The remote task identifier.
        task_id: String,
    },
    /// A remote skill file did not match its manifest entry.
    SkillIntegrity {
        /// The file's `skill://` URI.
        uri: String,
        /// What differed.
        reason: String,
    },
    /// A file could not be sent out of band; the tool did not run.
    FileUpload {
        /// The file argument's `id`.
        file_id: String,
        /// Why the upload failed.
        reason: String,
    },
    /// A file a tool result offered could not be downloaded, or failed its
    /// size or digest check; every file of that result was discarded.
    FileDownload {
        /// The file's safe base name.
        name: String,
        /// Why the download failed.
        reason: String,
    },
}

impl McpClientError {
    /// Stable machine-readable error code.
    pub fn code(&self) -> &'static str {
        match self {
            // A header supplied by the caller cannot be sent.
            Self::InvalidHeader(_) => "INVALID_HEADER",
            // The configured URL cannot be used.
            Self::InvalidUrl(_) => "MCP_INVALID_URL",
            // The request never produced a response.
            Self::Transport(HttpClientError::Transport { .. }) => "MCP_TRANSPORT_ERROR",
            // No client, or a request the client cannot express, keeps its code.
            Self::Transport(error) => error.code(),
            // Credentials were rejected.
            Self::Unauthorized { .. } => "MCP_UNAUTHORIZED",
            // The session is gone.
            Self::SessionExpired => "MCP_SESSION_EXPIRED",
            // An unexpected HTTP status.
            Self::Http { .. } => "MCP_HTTP_ERROR",
            // A JSON-RPC error response.
            Self::JsonRpc { .. } => "MCP_JSONRPC_ERROR",
            // A malformed or contradictory response.
            Self::Protocol(_) => "MCP_PROTOCOL_ERROR",
            // No common standard.
            Self::Negotiation(_) => "MCP_NEGOTIATION_FAILED",
            // The request deadline elapsed.
            Self::Timeout { .. } => "MCP_TIMEOUT",
            // An unbounded tool listing.
            Self::ToolLimit(_) => "MCP_TOOL_LIMIT_EXCEEDED",
            // A remote task failed.
            Self::TaskFailed { .. } => "MCP_TASK_FAILED",
            // A remote task was cancelled.
            Self::TaskCancelled { .. } => "MCP_TASK_CANCELLED",
            // A remote task disappeared.
            Self::TaskLost { .. } => "MCP_TASK_LOST",
            // A remote task waits for input.
            Self::TaskInputRequired { .. } => "MCP_TASK_INPUT_REQUIRED",
            // A remote skill file was altered.
            Self::SkillIntegrity { .. } => "MCP_SKILL_INTEGRITY",
            // A file upload was refused or failed.
            Self::FileUpload { .. } => "MCP_FILE_UPLOAD_FAILED",
            // A file download was refused, failed, or did not match.
            Self::FileDownload { .. } => "MCP_FILE_DOWNLOAD_FAILED",
        }
    }

    /// Whether repeating the operation may succeed.
    pub fn retryable(&self) -> bool {
        match self {
            // Network failures are transient; a missing client is not.
            Self::Transport(error) => error.retryable(),
            // Lost sessions and hung requests are transient.
            Self::SessionExpired | Self::Timeout { .. } => true,
            // Server-side failures may be transient; client errors are not.
            Self::Http { status, .. } => *status >= 500,
            // Everything else needs a configuration or server change.
            _ => false,
        }
    }

    fn hint(&self) -> Option<String> {
        match self {
            // Point at the credential inputs.
            Self::Unauthorized { .. } => {
                Some("Check the bearer token or the configured Authorization header".to_string())
            }
            // Point at the standard set.
            Self::Negotiation(_) => Some(
                "Enable an MCP standard the server supports in McpRemoteOptions::standards"
                    .to_string(),
            ),
            // Point at the option that takes a client.
            Self::Transport(error) => error.hint(),
            // Point at the deadline.
            Self::Timeout { .. } => Some(
                "Retry, or raise McpRemoteOptions::request_timeout for a slow server".to_string(),
            ),
            // Other failures carry their detail in the message.
            _ => None,
        }
    }
}

impl std::fmt::Display for McpClientError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            // Caller configuration.
            Self::InvalidHeader(message) | Self::InvalidUrl(message) => f.write_str(message),
            // Network failure.
            Self::Transport(error) => write!(f, "MCP request failed: {error}"),
            // Credentials rejected.
            Self::Unauthorized { status, .. } => {
                write!(f, "MCP server rejected the credentials with HTTP {status}")
            }
            // Session lost.
            Self::SessionExpired => f.write_str("MCP server discarded the session"),
            // Unexpected status.
            Self::Http { status, body } => write!(f, "HTTP {status}: {body}"),
            // Same text a JSON-RPC error has through the native rmcp client.
            Self::JsonRpc {
                code,
                message,
                data,
            } => {
                write!(f, "Mcp error: {code}: {message}")?;
                if let Some(data) = data {
                    write!(f, "({data})")?;
                }
                Ok(())
            }
            // Contract violation.
            Self::Protocol(message) => write!(f, "MCP protocol error: {message}"),
            // No common standard.
            Self::Negotiation(error) => write!(f, "{error}"),
            // Deadline elapsed.
            Self::Timeout { after } => write!(
                f,
                "MCP server did not answer within {} ms",
                after.as_millis()
            ),
            // Unbounded listing.
            Self::ToolLimit(message) => f.write_str(message),
            // Task outcomes.
            Self::TaskFailed { task_id, error } => {
                let message = error
                    .get("message")
                    .and_then(Value::as_str)
                    .unwrap_or("no message");
                write!(f, "MCP task {task_id} failed: {message}")
            }
            Self::TaskCancelled { task_id } => write!(f, "MCP task {task_id} was cancelled"),
            Self::TaskLost { task_id } => write!(
                f,
                "MCP server no longer recognizes task {task_id}; whether it ran is unknown"
            ),
            Self::TaskInputRequired { task_id } => {
                write!(f, "MCP task {task_id} requires input")
            }
            Self::SkillIntegrity { uri, reason } => {
                write!(
                    f,
                    "MCP skill file {uri} does not match its manifest: {reason}"
                )
            }
            // The tool was not invoked.
            Self::FileUpload { file_id, reason } => write!(
                f,
                "MCP file {file_id} could not be uploaded, so the tool did not run: {reason}"
            ),
            // The tool already ran.
            Self::FileDownload { name, reason } => {
                write!(f, "MCP file {name} could not be downloaded: {reason}")
            }
        }
    }
}

impl std::error::Error for McpClientError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            // The underlying HTTP failure.
            Self::Transport(error) => Some(error),
            // The underlying negotiation failure.
            Self::Negotiation(error) => Some(error),
            // Everything else is self-describing.
            _ => None,
        }
    }
}

impl From<McpClientError> for crate::errors::Error {
    fn from(error: McpClientError) -> Self {
        crate::errors::Error::Multicast(crate::errors::MulticastError {
            message: error.to_string(),
            code: error.code().to_string(),
            hint: error.hint(),
            retryable: error.retryable(),
            exit_code: None,
            cause: Some(Box::new(error)),
        })
    }
}

// ---------------------------------------------------------------------------
// HTTP exchange
// ---------------------------------------------------------------------------

/// The client every exchange goes through: the supplied one, or the native
/// default that follows no redirect, so configured credentials are never
/// replayed to a redirect target.
fn http_client(options: &McpRemoteOptions) -> Result<SharedHttpClient, McpClientError> {
    crate::outbound::resolve(
        options.http_client.as_ref(),
        "McpRemoteOptions::http_client",
        Redirects::Refuse,
    )
    .map_err(McpClientError::Transport)
}

/// Converts a composed header map into the contract's `(name, value)` pairs.
pub(crate) fn header_pairs(headers: &HeaderMap) -> Vec<(String, String)> {
    headers
        .iter()
        .map(|(name, value)| {
            (
                name.as_str().to_string(),
                String::from_utf8_lossy(value.as_bytes()).into_owned(),
            )
        })
        .collect()
}

/// Sends one request through `http`.
async fn send(
    http: &SharedHttpClient,
    method: &str,
    url: &url::Url,
    headers: &HeaderMap,
    body: Option<Vec<u8>>,
) -> Result<HttpResponse, McpClientError> {
    let request = HttpRequest {
        method: method.to_string(),
        url: url.to_string(),
        headers: header_pairs(headers),
        body,
    };
    http.send(request).await.map_err(McpClientError::Transport)
}

/// Runs `work` against a deadline of `timeout`, timed by `http`'s timer.
/// Without a timeout or a timer, `work` runs without a deadline. On expiry
/// `work` is dropped, which releases anything it holds.
async fn with_deadline<T>(
    http: &SharedHttpClient,
    timeout: Option<Duration>,
    work: impl std::future::Future<Output = Result<T, McpClientError>>,
) -> Result<T, McpClientError> {
    let Some((after, timer)) =
        timeout.and_then(|after| http.sleep(after).map(|timer| (after, timer)))
    else {
        return work.await;
    };
    let work = std::pin::pin!(work);
    match futures::future::select(work, timer).await {
        // The work finished first.
        futures::future::Either::Left((outcome, _)) => outcome,
        // The deadline elapsed first.
        futures::future::Either::Right(((), _)) => Err(McpClientError::Timeout { after }),
    }
}

/// Reads an error response's body for diagnosis, up to `limit` bytes. An
/// oversized body is an error; a body that fails mid-read is reported empty.
async fn error_body(response: HttpResponse, limit: usize) -> Result<String, McpClientError> {
    match response.text_limited(limit).await {
        // The whole body.
        Ok(body) => Ok(body),
        // Stop at the cap.
        Err(error @ HttpClientError::BodyTooLarge { .. }) => Err(McpClientError::Transport(error)),
        // The status is the useful part; keep it.
        Err(_) => Ok(String::new()),
    }
}

// ---------------------------------------------------------------------------
// Server-sent events
// ---------------------------------------------------------------------------

/// One dispatched server-sent event.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub(crate) struct SseEvent {
    /// Event type, when the event named one.
    pub(crate) event: Option<String>,
    /// Data lines joined with `\n`.
    pub(crate) data: String,
}

/// Incremental `text/event-stream` parser.
#[derive(Debug)]
pub(crate) struct SseParser {
    buffer: Vec<u8>,
    event: Option<String>,
    data: Vec<String>,
    data_bytes: usize,
    limit: usize,
}

impl Default for SseParser {
    fn default() -> Self {
        Self {
            buffer: Vec::new(),
            event: None,
            data: Vec::new(),
            data_bytes: 0,
            limit: MAX_EVENT_BYTES,
        }
    }
}

impl SseParser {
    /// Appends received bytes.
    pub(crate) fn push(&mut self, bytes: &[u8]) -> Result<(), McpClientError> {
        if bytes.len()
            > self
                .limit
                .saturating_sub(self.buffer.len().saturating_add(self.data_bytes))
        {
            return Err(McpClientError::Transport(HttpClientError::BodyTooLarge {
                limit: self.limit,
            }));
        }
        self.buffer.extend_from_slice(bytes);
        Ok(())
    }

    /// Returns the next complete event, if the buffer holds one.
    pub(crate) fn next_event(&mut self) -> Option<SseEvent> {
        loop {
            let end = self
                .buffer
                .iter()
                .position(|byte| *byte == b'\n' || *byte == b'\r')?;
            let mut consumed = end + 1;
            if self.buffer[end] == b'\r' {
                match self.buffer.get(end + 1) {
                    // CRLF line ending.
                    Some(b'\n') => consumed += 1,
                    // A lone CR may still be followed by LF in the next chunk.
                    None => return None,
                    // A lone CR line ending.
                    Some(_) => {}
                }
            }
            let line = String::from_utf8_lossy(&self.buffer[..end]).into_owned();
            self.buffer.drain(..consumed);
            if line.is_empty() {
                if self.data.is_empty() {
                    self.event = None;
                    continue;
                }
                let event = SseEvent {
                    event: self.event.take(),
                    data: self.data.join("\n"),
                };
                self.data.clear();
                self.data_bytes = 0;
                return Some(event);
            }
            if line.starts_with(':') {
                continue;
            }
            let (field, value) = match line.split_once(':') {
                // `field: value`, with one optional leading space removed.
                Some((field, value)) => (field, value.strip_prefix(' ').unwrap_or(value)),
                // A bare field name has an empty value.
                None => (line.as_str(), ""),
            };
            match field {
                // Event type for the pending event.
                "event" => self.event = Some(value.to_string()),
                // One data line.
                "data" => {
                    self.data_bytes = self.data_bytes.saturating_add(value.len() + 1);
                    self.data.push(value.to_string());
                }
                // `id`, `retry`, and unknown fields do not affect MCP messages.
                _ => {}
            }
        }
    }
}

/// A response body read as server-sent events.
struct EventReader {
    stream: HttpBody,
    parser: SseParser,
}

impl EventReader {
    fn new(response: HttpResponse, limit: usize) -> Self {
        Self {
            stream: response.body,
            parser: SseParser {
                limit,
                ..SseParser::default()
            },
        }
    }

    async fn next(&mut self) -> Result<Option<SseEvent>, McpClientError> {
        loop {
            if let Some(event) = self.parser.next_event() {
                return Ok(Some(event));
            }
            match self.stream.next().await {
                // More bytes for the parser.
                Some(Ok(bytes)) => self.parser.push(&bytes)?,
                // The body failed mid-stream.
                Some(Err(error)) => return Err(McpClientError::Transport(error)),
                // The body ended; an unterminated event is discarded.
                None => return Ok(None),
            }
        }
    }

    /// Reads events until the JSON-RPC response for `id` arrives, skipping
    /// notifications, server requests, and non-message events.
    async fn response(&mut self, id: u64) -> Result<Value, McpClientError> {
        loop {
            let Some(event) = self.next().await? else {
                return Err(McpClientError::Protocol(
                    "event stream ended before the response arrived".to_string(),
                ));
            };
            if event.event.as_deref().is_some_and(|name| name != "message")
                || event.data.trim().is_empty()
            {
                continue;
            }
            let message: Value = serde_json::from_str(&event.data).map_err(|error| {
                McpClientError::Protocol(format!("event data is not JSON: {error}"))
            })?;
            if let Some(outcome) = find_response(&message, id) {
                return outcome;
            }
        }
    }
}

// ---------------------------------------------------------------------------
// JSON-RPC
// ---------------------------------------------------------------------------

fn id_matches(value: Option<&Value>, id: u64) -> bool {
    match value {
        // Numeric ids are echoed as numbers.
        Some(Value::Number(number)) => number.as_u64() == Some(id),
        // Some servers stringify numeric ids.
        Some(Value::String(text)) => *text == id.to_string(),
        // Anything else is not this request's response.
        _ => false,
    }
}

fn jsonrpc_error(error: &Value) -> McpClientError {
    McpClientError::JsonRpc {
        code: error
            .get("code")
            .and_then(Value::as_i64)
            .unwrap_or_default(),
        message: error
            .get("message")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string(),
        data: error.get("data").cloned(),
    }
}

/// Finds the response for `id` in one message or a batch.
fn find_response(message: &Value, id: u64) -> Option<Result<Value, McpClientError>> {
    if let Some(batch) = message.as_array() {
        return batch.iter().find_map(|message| find_response(message, id));
    }
    if message.get("method").is_some() || !id_matches(message.get("id"), id) {
        return None;
    }
    if let Some(error) = message.get("error") {
        return Some(Err(jsonrpc_error(error)));
    }
    Some(match message.get("result") {
        // A successful response.
        Some(result) => Ok(result.clone()),
        // Neither result nor error.
        None => Err(McpClientError::Protocol(
            "response has neither result nor error".to_string(),
        )),
    })
}

/// Reply to one POSTed message.
struct Reply {
    result: Option<Value>,
    session_id: Option<String>,
}

// ---------------------------------------------------------------------------
// Transports
// ---------------------------------------------------------------------------

/// Per-request limits shared by both transports.
#[derive(Debug, Clone, Copy)]
struct Limits {
    timeout: Option<Duration>,
    max_body: usize,
}

impl Limits {
    fn new(options: &McpRemoteOptions) -> Self {
        Self {
            timeout: options.request_timeout,
            max_body: options.max_response_bytes,
        }
    }
}

#[derive(Clone)]
struct Streamable {
    http: SharedHttpClient,
    url: url::Url,
    headers: HeaderMap,
    session_id: Option<HeaderValue>,
    limits: Limits,
    detach: Option<crate::mcp::McpDetach>,
}

impl Streamable {
    async fn exchange(
        &self,
        message: &Value,
        id: Option<u64>,
        protocol_headers: HeaderMap,
    ) -> Result<Reply, McpClientError> {
        with_deadline(
            &self.http,
            self.limits.timeout,
            self.exchange_unbounded(message, id, protocol_headers),
        )
        .await
    }

    async fn exchange_unbounded(
        &self,
        message: &Value,
        id: Option<u64>,
        protocol_headers: HeaderMap,
    ) -> Result<Reply, McpClientError> {
        let body = serde_json::to_vec(message)
            .map_err(|error| McpClientError::Protocol(error.to_string()))?;
        let mut headers = self.headers.clone();
        headers.extend(protocol_headers);
        headers.append(
            ACCEPT,
            HeaderValue::from_static("text/event-stream, application/json"),
        );
        headers.append(CONTENT_TYPE, HeaderValue::from_static(JSON));
        if let Some(session_id) = &self.session_id {
            headers.append(HEADER_SESSION_ID, session_id.clone());
        }
        let response = send(&self.http, "POST", &self.url, &headers, Some(body)).await?;
        let status = response.status;
        rejected_credentials(&response)?;
        if matches!(status, 202 | 204) {
            return accepted(id, None);
        }
        if status == 404 && self.session_id.is_some() {
            return Err(McpClientError::SessionExpired);
        }
        let content_type = header_text(&response, CONTENT_TYPE.as_str());
        let session_id = header_text(&response, HEADER_SESSION_ID);
        let is_json = content_type
            .as_deref()
            .is_some_and(|value| value.starts_with(JSON));
        if !response.is_success() {
            let body = error_body(response, self.limits.max_body).await?;
            if is_json
                && let Ok(message) = serde_json::from_str::<Value>(&body)
                && let Some(error) = message.get("error")
            {
                return Err(jsonrpc_error(error));
            }
            return Err(McpClientError::Http { status, body });
        }
        if content_type
            .as_deref()
            .is_some_and(|value| value.starts_with(EVENT_STREAM))
        {
            let Some(id) = id else {
                return Ok(Reply {
                    result: None,
                    session_id,
                });
            };
            let result = EventReader::new(response, self.limits.max_body)
                .response(id)
                .await?;
            return Ok(Reply {
                result: Some(result),
                session_id,
            });
        }
        if !is_json {
            return Err(McpClientError::Protocol(format!(
                "unexpected response content type {}",
                content_type.as_deref().unwrap_or("<none>")
            )));
        }
        let bytes = response
            .bytes_limited(self.limits.max_body)
            .await
            .map_err(McpClientError::Transport)?;
        let (Some(id), Ok(message)) = (id, serde_json::from_slice::<Value>(&bytes)) else {
            // A notification's body, or an unparseable body, is an acceptance.
            return accepted(id, session_id);
        };
        match find_response(&message, id) {
            // The matching response.
            Some(outcome) => outcome.map(|result| Reply {
                result: Some(result),
                session_id,
            }),
            // An error that could not be attributed to a request id.
            None if message.get("id").is_none_or(Value::is_null) => Err(message
                .get("error")
                .map(jsonrpc_error)
                .unwrap_or_else(|| McpClientError::Protocol("response has no id".to_string()))),
            // Some other request's response.
            None => Err(McpClientError::Protocol(
                "response id does not match the request".to_string(),
            )),
        }
    }
}

fn accepted(id: Option<u64>, session_id: Option<String>) -> Result<Reply, McpClientError> {
    if id.is_some() {
        return Err(McpClientError::Protocol(
            "server accepted a request without answering it".to_string(),
        ));
    }
    Ok(Reply {
        result: None,
        session_id,
    })
}

fn rejected_credentials(response: &HttpResponse) -> Result<(), McpClientError> {
    let status = response.status;
    if matches!(status, 401 | 403) {
        return Err(McpClientError::Unauthorized {
            status,
            www_authenticate: header_text(response, "www-authenticate"),
        });
    }
    Ok(())
}

fn header_text(response: &HttpResponse, name: &str) -> Option<String> {
    response.header(name).map(ToString::to_string)
}

struct LegacySse {
    http: SharedHttpClient,
    endpoint: url::Url,
    headers: HeaderMap,
    events: futures::lock::Mutex<EventReader>,
    limits: Limits,
}

impl LegacySse {
    async fn exchange(
        &self,
        message: &Value,
        id: Option<u64>,
        protocol_headers: HeaderMap,
    ) -> Result<Reply, McpClientError> {
        // The deadline includes waiting for the stream lock. Dropping the
        // exchange releases the lock; subsequent requests skip late replies.
        with_deadline(&self.http, self.limits.timeout, async {
            let mut events = self.events.lock().await;
            self.exchange_held(&mut events, message, id, protocol_headers)
                .await
        })
        .await
    }

    async fn exchange_held(
        &self,
        events: &mut EventReader,
        message: &Value,
        id: Option<u64>,
        protocol_headers: HeaderMap,
    ) -> Result<Reply, McpClientError> {
        let body = serde_json::to_vec(message)
            .map_err(|error| McpClientError::Protocol(error.to_string()))?;
        let mut headers = self.headers.clone();
        headers.extend(protocol_headers);
        headers.append(ACCEPT, HeaderValue::from_static(JSON));
        headers.append(CONTENT_TYPE, HeaderValue::from_static(JSON));
        let response = send(&self.http, "POST", &self.endpoint, &headers, Some(body)).await?;
        rejected_credentials(&response)?;
        if !response.is_success() {
            let status = response.status;
            return Err(McpClientError::Http {
                status,
                body: error_body(response, self.limits.max_body).await?,
            });
        }
        drop(response);
        let result = match id {
            // Requests are answered on the event stream.
            Some(id) => Some(events.response(id).await?),
            // Notifications are not answered.
            None => None,
        };
        Ok(Reply {
            result,
            session_id: None,
        })
    }
}

enum Wire {
    Streamable(Streamable),
    LegacySse(LegacySse),
}

/// Resolves a legacy SSE `endpoint` event against the configured URL, and
/// rejects endpoints that could leak data: non-HTTP schemes, user
/// information, fragments, and plain HTTP off loopback.
pub(crate) fn resolve_endpoint(
    configured: &url::Url,
    value: &str,
) -> Result<url::Url, McpClientError> {
    let endpoint = configured
        .join(value)
        .map_err(|error| McpClientError::Protocol(format!("endpoint event is invalid: {error}")))?;
    if !matches!(endpoint.scheme(), "http" | "https") {
        return Err(McpClientError::Protocol(
            "endpoint event must contain an HTTP or HTTPS URL".to_string(),
        ));
    }
    if !endpoint.username().is_empty()
        || endpoint.password().is_some()
        || endpoint.fragment().is_some()
    {
        return Err(McpClientError::Protocol(
            "endpoint event URL must not contain user information or a fragment".to_string(),
        ));
    }
    if endpoint.scheme() == "http" && !is_loopback(&endpoint) {
        return Err(McpClientError::Protocol(
            "non-loopback endpoint event URLs must use HTTPS".to_string(),
        ));
    }
    Ok(endpoint)
}

fn is_loopback(url: &url::Url) -> bool {
    let Some(host) = url.host_str() else {
        return false;
    };
    let host = host.trim_start_matches('[').trim_end_matches(']');
    host.eq_ignore_ascii_case("localhost")
        || host
            .parse::<std::net::IpAddr>()
            .is_ok_and(|address| address.is_loopback())
}

/// Whether an endpoint shares the configured URL's origin, so configured
/// headers may follow it.
pub(crate) fn same_origin(configured: &url::Url, endpoint: &url::Url) -> bool {
    configured.scheme() == endpoint.scheme()
        && configured.host_str() == endpoint.host_str()
        && configured.port_or_known_default() == endpoint.port_or_known_default()
}

/// Removes headers the legacy SSE transport sets itself.
pub(crate) fn client_safe_headers(mut headers: HeaderMap) -> HeaderMap {
    headers.remove(ACCEPT);
    headers.remove(CONTENT_TYPE);
    headers
}

// ---------------------------------------------------------------------------
// Client
// ---------------------------------------------------------------------------

/// A connected MCP client that needs no async runtime.
///
/// Connect with [`connect`](Self::connect) for Streamable HTTP or
/// [`connect_legacy_sse`](Self::connect_legacy_sse) for the 2024-11-05
/// HTTP+SSE transport, then list and call tools. Project the tools as multicast
/// commands with [`crate::mcp::remote_commands_from_client`].
///
/// The client is `Send` and `Sync`, and its futures are `Send` on every
/// target: every exchange goes through a `Send` [`crate::outbound::HttpClient`].
pub struct McpHttpClient {
    open_telemetry: bool,
    wire: Wire,
    standard: McpVersion,
    modern: bool,
    metadata: McpClientMetadata,
    next_id: AtomicU64,
    param_headers: std::sync::Mutex<HashMap<String, Vec<(String, String)>>>,
    /// Whether requests opt into the tasks extension.
    tasks: bool,
    /// Whether the server advertised the skills extension.
    skills: bool,
    /// The files extension settings the server advertised, if any.
    #[cfg_attr(not(feature = "mcp-files"), allow(dead_code))]
    files: Option<Value>,
    /// Remote tasks waiting for input that this client returned to a caller.
    pending_tasks: std::sync::Mutex<std::collections::HashSet<String>>,
    /// How long a task may stay unknown before it counts as lost.
    pub(crate) task_lost_after: Duration,
}

/// How a remote tool call ended.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum McpToolOutcome {
    /// The raw MCP `CallToolResult`.
    Complete(Value),
    /// A remote task waits for input. Answer with
    /// [`McpHttpClient::resume_task`].
    InputRequired {
        /// The remote task identifier.
        task_id: String,
        /// The server's `inputRequests` map.
        input_requests: Value,
    },
}

impl std::fmt::Debug for McpHttpClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("McpHttpClient")
            .field("standard", &self.standard)
            .field("session_id", &self.session_id())
            .finish_non_exhaustive()
    }
}

impl McpHttpClient {
    /// Connects to a Streamable HTTP MCP endpoint and negotiates a standard
    /// from `options.standards`.
    ///
    /// Sends `options.auth_token` as a bearer token and `options.headers` on
    /// every request. `Accept`, `Content-Type`, `Mcp-Session-Id`, and
    /// `Mcp-Protocol-Version` are set by the transport and are rejected as
    /// configured headers. Requests go
    /// through `options.http_client`; on wasm32, where there is no default,
    /// a missing client fails with `HTTP_CLIENT_REQUIRED`.
    pub async fn connect(url: &str, options: &McpRemoteOptions) -> Result<Self, McpClientError> {
        let url = parse_url(url)?;
        let headers = configured_headers(options)?;
        for reserved in [
            ACCEPT,
            CONTENT_TYPE,
            HeaderName::from_static(HEADER_SESSION_ID),
            HeaderName::from_static(HEADER_PROTOCOL_VERSION),
        ] {
            if headers.contains_key(&reserved) {
                return Err(McpClientError::InvalidHeader(format!(
                    "`{reserved}` is set by the MCP transport and cannot be configured"
                )));
            }
        }
        let wire = Wire::Streamable(Streamable {
            http: http_client(options)?,
            url,
            headers,
            session_id: None,
            limits: Limits::new(options),
            detach: options.detach.clone(),
        });
        Self::negotiate(wire, &options.standards, options.open_telemetry).await
    }

    /// Connects to a legacy HTTP+SSE MCP endpoint: opens the event stream,
    /// waits for its `endpoint` event, and negotiates a standard from
    /// `options.standards` over it.
    ///
    /// Configured headers follow the POST endpoint only when it shares the
    /// event stream's origin. Opening the stream and receiving its endpoint
    /// event share one request deadline; the open stream itself has none.
    pub async fn connect_legacy_sse(
        url: &str,
        options: &McpRemoteOptions,
    ) -> Result<Self, McpClientError> {
        let configured = parse_url(url)?;
        let headers = client_safe_headers(configured_headers(options)?);
        let http = http_client(options)?;
        let limits = Limits::new(options);
        let (endpoint, events) = with_deadline(
            &http,
            limits.timeout,
            open_legacy_stream(&http, &configured, &headers, limits),
        )
        .await?;
        let headers = if same_origin(&configured, &endpoint) {
            headers
        } else {
            HeaderMap::new()
        };
        let wire = Wire::LegacySse(LegacySse {
            http,
            endpoint,
            headers,
            events: futures::lock::Mutex::new(events),
            limits,
        });
        Self::negotiate(wire, &options.standards, options.open_telemetry).await
    }
}

/// Opens a legacy SSE event stream and reads it up to its `endpoint` event.
async fn open_legacy_stream(
    http: &SharedHttpClient,
    configured: &url::Url,
    headers: &HeaderMap,
    limits: Limits,
) -> Result<(url::Url, EventReader), McpClientError> {
    let mut request_headers = headers.clone();
    request_headers.append(ACCEPT, HeaderValue::from_static(EVENT_STREAM));
    let response = send(http, "GET", configured, &request_headers, None).await?;
    rejected_credentials(&response)?;
    if !response.is_success() {
        let status = response.status;
        return Err(McpClientError::Http {
            status,
            body: error_body(response, limits.max_body).await?,
        });
    }
    let content_type = header_text(&response, CONTENT_TYPE.as_str());
    if !content_type
        .as_deref()
        .and_then(|value| value.split(';').next())
        .is_some_and(|value| value.trim().eq_ignore_ascii_case(EVENT_STREAM))
    {
        return Err(McpClientError::Protocol(
            "SSE endpoint did not return text/event-stream".to_string(),
        ));
    }
    let mut events = EventReader::new(response, limits.max_body);
    let endpoint = loop {
        let Some(event) = events.next().await? else {
            return Err(McpClientError::Protocol(
                "SSE endpoint closed before its endpoint event".to_string(),
            ));
        };
        if event.event.as_deref() == Some("endpoint") {
            break resolve_endpoint(configured, event.data.trim())?;
        }
    };
    Ok((endpoint, events))
}

impl McpHttpClient {
    /// The exact standard negotiated with the server.
    pub fn standard(&self) -> &McpVersion {
        &self.standard
    }

    /// The `Mcp-Session-Id` the server issued, when it issued one.
    pub fn session_id(&self) -> Option<&str> {
        match &self.wire {
            // Only legacy Streamable HTTP sessions carry an id.
            Wire::Streamable(wire) => wire
                .session_id
                .as_ref()
                .and_then(|value| value.to_str().ok()),
            // The legacy SSE transport identifies the session by its stream.
            Wire::LegacySse(_) => None,
        }
    }

    /// Sends one JSON-RPC request and returns its `result`.
    ///
    /// A JSON-RPC error response is returned as [`McpClientError::JsonRpc`].
    pub async fn request(&self, method: &str, params: Value) -> Result<Value, McpClientError> {
        let result = self.request_any(method, params).await?;
        if self.modern
            && let Some(kind) = result.get("resultType").and_then(Value::as_str)
            && kind != "complete"
        {
            return Err(McpClientError::Protocol(format!(
                "result type `{kind}` is not supported by this client"
            )));
        }
        Ok(result)
    }

    /// Sends one JSON-RPC request and returns its `result` of any type.
    async fn request_any(&self, method: &str, params: Value) -> Result<Value, McpClientError> {
        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
        let message = self.envelope(method, Some(params), Some(id));
        let headers = self.protocol_headers(&message, true);
        let reply = self.exchange(&message, Some(id), headers).await?;
        reply
            .result
            .ok_or_else(|| McpClientError::Protocol("request received no response".to_string()))
    }

    /// Lists every tool, following `nextCursor` pagination, as raw MCP tool
    /// objects. The request deadline covers the entire listing, including all pages.
    ///
    /// A listing longer than [`MAX_REMOTE_TOOL_PAGES`] pages or
    /// [`MAX_REMOTE_TOOLS`] tools fails with [`McpClientError::ToolLimit`].
    ///
    /// Under 2026-07-28, a tool with invalid `x-mcp-header` annotations is
    /// dropped, and valid annotations are remembered so later calls send the
    /// matching `Mcp-Param-*` headers.
    pub async fn list_tools(&self) -> Result<Vec<Value>, McpClientError> {
        let (http, limits) = self.http_limits();
        with_deadline(http, limits.timeout, self.list_tools_unbounded()).await
    }

    /// Host timer and deadline shared by projection and paginated discovery.
    pub(crate) fn deadline(&self) -> Option<(Duration, crate::outbound::Sleep)> {
        let (http, limits) = self.http_limits();
        limits
            .timeout
            .and_then(|after| http.sleep(after).map(|timer| (after, timer)))
    }

    fn http_limits(&self) -> (&SharedHttpClient, Limits) {
        match &self.wire {
            Wire::Streamable(wire) => (&wire.http, wire.limits),
            Wire::LegacySse(wire) => (&wire.http, wire.limits),
        }
    }

    async fn list_tools_unbounded(&self) -> Result<Vec<Value>, McpClientError> {
        let mut tools = Vec::new();
        let mut cursor: Option<String> = None;
        let mut pages = 0_usize;
        loop {
            pages += 1;
            let params = match &cursor {
                // Follow-up page.
                Some(cursor) => serde_json::json!({ "cursor": cursor }),
                // First page.
                None => Value::Object(Map::new()),
            };
            let result = self.request("tools/list", params).await?;
            let page = result
                .get("tools")
                .and_then(Value::as_array)
                .ok_or_else(|| {
                    McpClientError::Protocol("tools/list result has no tools array".to_string())
                })?;
            for tool in page {
                if tools.len() >= MAX_REMOTE_TOOLS {
                    return Err(McpClientError::ToolLimit(format!(
                        "tools/list returned more than {MAX_REMOTE_TOOLS} tools"
                    )));
                }
                if self.modern {
                    let Some(annotations) = param_header_annotations(tool) else {
                        continue;
                    };
                    if let (Some(name), Ok(mut cache)) = (
                        tool.get("name").and_then(Value::as_str),
                        self.param_headers.lock(),
                    ) {
                        cache.insert(name.to_string(), annotations);
                    }
                }
                tools.push(tool.clone());
            }
            match result.get("nextCursor").and_then(Value::as_str) {
                // The server repeated a cursor; paging would never end.
                Some(next) if cursor.as_deref() == Some(next) => {
                    return Err(McpClientError::Protocol(
                        "tools/list returned a non-advancing cursor".to_string(),
                    ));
                }
                // The server keeps paging past the cap.
                Some(_) if pages >= MAX_REMOTE_TOOL_PAGES => {
                    return Err(McpClientError::ToolLimit(format!(
                        "tools/list returned more than {MAX_REMOTE_TOOL_PAGES} pages"
                    )));
                }
                // Another page.
                Some(next) => cursor = Some(next.to_string()),
                // Last page.
                None => return Ok(tools),
            }
        }
    }

    /// Calls one tool and returns the raw MCP `CallToolResult` object.
    ///
    /// A tool failure is a successful call whose result has `isError: true`;
    /// an unknown tool or invalid request is [`McpClientError::JsonRpc`].
    ///
    /// When the server runs the call as a task, this follows the task to its
    /// end. A task that asks for input is cancelled and fails with
    /// [`McpClientError::TaskInputRequired`]; use
    /// [`call_tool_outcome`](Self::call_tool_outcome) to answer it instead.
    pub async fn call_tool(
        &self,
        name: &str,
        arguments: Map<String, Value>,
    ) -> Result<Value, McpClientError> {
        match self.call_tool_outcome(name, arguments).await? {
            // The call finished.
            McpToolOutcome::Complete(result) => Ok(result),
            // Nobody can answer: stop the task instead of leaving it waiting.
            McpToolOutcome::InputRequired { task_id, .. } => {
                self.pending_tasks().remove(&task_id);
                let _ = self
                    .request("tasks/cancel", serde_json::json!({ "taskId": task_id }))
                    .await;
                Err(McpClientError::TaskInputRequired { task_id })
            }
        }
    }

    /// Calls one tool and follows a remote task until it completes or asks
    /// for input.
    ///
    /// The client opts into the tasks extension only when the server
    /// advertised it in `server/discover` and the HTTP client has a timer.
    /// Polling honors the task's `pollIntervalMs`. Dropping the returned
    /// future while it follows a task sends `tasks/cancel` through
    /// [`McpRemoteOptions::detach`], or the current Tokio runtime on native
    /// targets; a wasm32 host without `detach` sends nothing, so the task runs
    /// on there.
    ///
    /// A task that ends `failed` or `cancelled` returns
    /// [`McpClientError::TaskFailed`] or [`McpClientError::TaskCancelled`]. A
    /// task the server stops recognizing for five minutes returns
    /// [`McpClientError::TaskLost`], because whether it ran is unknown.
    pub async fn call_tool_outcome(
        &self,
        name: &str,
        arguments: Map<String, Value>,
    ) -> Result<McpToolOutcome, McpClientError> {
        let result = self
            .request_any(
                "tools/call",
                serde_json::json!({ "name": name, "arguments": arguments }),
            )
            .await?;
        self.call_outcome(result).await
    }

    /// Turns a `tools/call` result into an outcome, following a task this
    /// client opted into.
    async fn call_outcome(&self, result: Value) -> Result<McpToolOutcome, McpClientError> {
        if !self.modern {
            return Ok(McpToolOutcome::Complete(result));
        }
        match result.get("resultType").and_then(Value::as_str) {
            // An inline result.
            None | Some("complete") => Ok(McpToolOutcome::Complete(result)),
            // A task this client asked for.
            Some("task") if self.tasks => self.follow_task(result, false).await,
            // A task the client never opted into.
            Some("task") => Err(McpClientError::Protocol(
                "server returned a task although this client did not opt into tasks".to_string(),
            )),
            // Any other result type.
            Some(kind) => Err(McpClientError::Protocol(format!(
                "result type `{kind}` is not supported by this client"
            ))),
        }
    }

    /// Whether this client opts into the server's tasks extension.
    pub fn tasks_enabled(&self) -> bool {
        self.tasks
    }

    /// Answers a remote task that [`call_tool_outcome`](Self::call_tool_outcome)
    /// or an earlier resume returned as waiting for input, then follows it.
    ///
    /// Only task identifiers this client returned are accepted, each once.
    pub async fn resume_task(
        &self,
        task_id: &str,
        input_responses: Value,
    ) -> Result<McpToolOutcome, McpClientError> {
        if !self.pending_tasks().contains(task_id) {
            return Err(McpClientError::Protocol(format!(
                "task {task_id} is not waiting for input from this client"
            )));
        }
        self.request(
            "tasks/update",
            serde_json::json!({ "taskId": task_id, "inputResponses": input_responses }),
        )
        .await?;
        self.pending_tasks().remove(task_id);
        self.follow_task(
            serde_json::json!({ "taskId": task_id, "status": "working" }),
            true,
        )
        .await
    }

    fn pending_tasks(&self) -> std::sync::MutexGuard<'_, std::collections::HashSet<String>> {
        self.pending_tasks
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Polls a task until it leaves `working`. Fetches at once when
    /// `immediate` is set or the known status is not `working`.
    async fn follow_task(
        &self,
        mut task: Value,
        immediate: bool,
    ) -> Result<McpToolOutcome, McpClientError> {
        let task_id = task
            .get("taskId")
            .and_then(Value::as_str)
            .filter(|id| !id.is_empty())
            .ok_or_else(|| McpClientError::Protocol("task result has no taskId".to_string()))?
            .to_string();
        let (http, _) = self.http_limits();
        let mut guard = CancelOnDrop::new(self, &task_id);
        let mut fetch_now = immediate || task_status(&task) != Some("working");
        let mut unknown_for = Duration::ZERO;
        loop {
            let interval = poll_interval(&task);
            if !fetch_now {
                let timer = http.sleep(interval).ok_or_else(|| {
                    McpClientError::Protocol("following a task needs a host timer".to_string())
                })?;
                timer.await;
            }
            fetch_now = false;
            match self
                .request("tasks/get", serde_json::json!({ "taskId": task_id }))
                .await
            {
                // A fresh view of the task.
                Ok(next) => {
                    unknown_for = Duration::ZERO;
                    task = next;
                }
                // The server does not recognize the task, perhaps briefly.
                Err(McpClientError::JsonRpc {
                    code: INVALID_PARAMS,
                    ..
                }) => {
                    if unknown_for >= self.task_lost_after {
                        guard.disarm();
                        return Err(McpClientError::TaskLost { task_id });
                    }
                    unknown_for += interval;
                    continue;
                }
                // Any other failure ends following without cancelling.
                Err(error) => {
                    guard.disarm();
                    return Err(error);
                }
            }
            let outcome = match task_status(&task) {
                // Still running.
                Some("working") => continue,
                // Finished; a tool error is a completed result with isError.
                Some("completed") => task
                    .get("result")
                    .cloned()
                    .map(McpToolOutcome::Complete)
                    .ok_or_else(|| {
                        McpClientError::Protocol("completed task has no result".to_string())
                    }),
                // The server could not run the call.
                Some("failed") => Err(McpClientError::TaskFailed {
                    task_id: task_id.clone(),
                    error: task.get("error").cloned().unwrap_or(Value::Null),
                }),
                // Someone cancelled it.
                Some("cancelled") => Err(McpClientError::TaskCancelled {
                    task_id: task_id.clone(),
                }),
                // The caller must answer before it continues.
                Some("input_required") => {
                    self.pending_tasks().insert(task_id.clone());
                    Ok(McpToolOutcome::InputRequired {
                        task_id: task_id.clone(),
                        input_requests: task
                            .get("inputRequests")
                            .cloned()
                            .unwrap_or_else(|| Value::Object(Map::new())),
                    })
                }
                // A status this client does not know.
                other => Err(McpClientError::Protocol(format!(
                    "task status {other:?} is not recognized"
                ))),
            };
            guard.disarm();
            return outcome;
        }
    }

    async fn negotiate(
        wire: Wire,
        standards: &McpStandardSet,
        open_telemetry: bool,
    ) -> Result<Self, McpClientError> {
        let lifecycle = |version: &McpVersion| {
            multicast_mcp_protocol::standards::known_standard(version)
                .map(|standard| standard.lifecycle())
        };
        let versions = standards.versions();
        let first_modern = versions
            .iter()
            .find(|version| lifecycle(version) == Some(McpLifecycleFamily::Modern))
            .cloned();
        let mut client = Self {
            open_telemetry,
            wire,
            standard: versions[0].clone(),
            modern: false,
            metadata: McpClientMetadata::new(
                "multicast",
                env!("CARGO_PKG_VERSION"),
                Value::Object(Map::new()),
            ),
            next_id: AtomicU64::new(0),
            param_headers: std::sync::Mutex::new(HashMap::new()),
            tasks: false,
            skills: false,
            files: None,
            pending_tasks: std::sync::Mutex::new(std::collections::HashSet::new()),
            task_lost_after: TASK_LOST_AFTER,
        };
        let Some(mut candidate) = first_modern else {
            let legacy = versions[0].clone();
            client.initialize(legacy, standards).await?;
            return Ok(client);
        };
        let mut attempted: Vec<McpVersion> = Vec::new();
        loop {
            attempted.push(candidate.clone());
            client.standard = candidate.clone();
            client.modern = true;
            let outcome = client
                .request("server/discover", Value::Object(Map::new()))
                .await;
            let (evidence, failure, discovery) = match outcome {
                // The peer speaks the modern lifecycle.
                Ok(result) => (discovered(&result), None, Some(result)),
                // Classify the failure as negotiation evidence.
                Err(error) => (evidence_for(&error), Some(error), None),
            };
            match multicast_mcp_protocol::negotiate(standards, &evidence) {
                // A mutually supported modern standard.
                Ok(McpNegotiationDecision::SelectModern(version)) => {
                    client.standard = version;
                    let advertised = discovery
                        .as_ref()
                        .and_then(|result| result.pointer("/capabilities/extensions"))
                        .and_then(|extensions| extensions.get(TASKS_EXTENSION))
                        .is_some();
                    client.skills = discovery
                        .as_ref()
                        .and_then(|result| result.pointer("/capabilities/extensions"))
                        .and_then(|extensions| extensions.get(crate::mcp::SKILLS_EXTENSION))
                        .is_some();
                    client.files = discovery
                        .as_ref()
                        .and_then(|result| result.pointer("/capabilities/extensions"))
                        .and_then(|extensions| extensions.get("io.modelcontextprotocol/files"))
                        .cloned();
                    // Following a task needs a timer between polls.
                    let (http, _) = client.http_limits();
                    if advertised && http.sleep(Duration::ZERO).is_some() {
                        client.tasks = true;
                        client.metadata.capabilities =
                            serde_json::json!({ "extensions": { (TASKS_EXTENSION): {} } });
                    }
                    return Ok(client);
                }
                // Retry discovery once per standard the peer said it supports.
                Ok(McpNegotiationDecision::RetryModern(version)) => {
                    if attempted.iter().filter(|tried| **tried == version).count() >= 2 {
                        return Err(McpClientError::Negotiation(
                            McpNegotiationError::NoCommonStandard,
                        ));
                    }
                    candidate = version;
                }
                // Protocol evidence that the peer is legacy.
                Ok(McpNegotiationDecision::FallBackLegacy(version)) => {
                    client.modern = false;
                    client.initialize(version, standards).await?;
                    return Ok(client);
                }
                // Fail closed with the failure that produced the evidence.
                Err(McpNegotiationError::FailedClosed(reason)) => {
                    return Err(failure.unwrap_or_else(|| {
                        McpClientError::Protocol(format!("server/discover failed: {reason}"))
                    }));
                }
                // No common standard.
                Err(error) => return Err(McpClientError::Negotiation(error)),
            }
        }
    }

    async fn initialize(
        &mut self,
        version: McpVersion,
        standards: &McpStandardSet,
    ) -> Result<(), McpClientError> {
        self.modern = false;
        self.standard = version.clone();
        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
        let message = self.envelope(
            "initialize",
            Some(serde_json::json!({
                "protocolVersion": version,
                "capabilities": self.metadata.capabilities,
                "clientInfo": {
                    "name": self.metadata.name,
                    "version": self.metadata.version,
                },
            })),
            Some(id),
        );
        let headers = self.protocol_headers(&message, false);
        let reply = self.exchange(&message, Some(id), headers).await?;
        let result = reply.result.unwrap_or(Value::Null);
        let negotiated = result
            .get("protocolVersion")
            .and_then(Value::as_str)
            .map(McpVersion::from)
            .ok_or_else(|| {
                McpClientError::Protocol("initialize result has no protocolVersion".to_string())
            })?;
        let legacy = multicast_mcp_protocol::standards::known_standard(&negotiated)
            .is_some_and(|standard| standard.lifecycle() == McpLifecycleFamily::Legacy);
        if !legacy || !standards.versions().contains(&negotiated) {
            return Err(McpClientError::Negotiation(
                McpNegotiationError::NoCommonStandard,
            ));
        }
        self.standard = negotiated;
        if let (Wire::Streamable(wire), Some(session_id)) = (&mut self.wire, reply.session_id) {
            wire.session_id = Some(HeaderValue::from_str(&session_id).map_err(|_| {
                McpClientError::Protocol("Mcp-Session-Id is not a valid header value".to_string())
            })?);
        }
        let notification = self.envelope("notifications/initialized", None, None);
        let headers = self.protocol_headers(&notification, true);
        self.exchange(&notification, None, headers).await?;
        Ok(())
    }

    async fn exchange(
        &self,
        message: &Value,
        id: Option<u64>,
        headers: HeaderMap,
    ) -> Result<Reply, McpClientError> {
        use opentelemetry::trace::FutureExt;
        let mut operation = crate::telemetry::Operation::mcp_client(
            self.open_telemetry,
            message["method"].as_str().unwrap_or("_OTHER"),
            message.get("params"),
            Some(self.standard.as_str()),
        );
        let mut message = message.clone();
        let mut meta = message
            .pointer("/params/_meta")
            .cloned()
            .unwrap_or(Value::Null);
        operation.inject(&mut meta);
        if !meta.is_null() {
            if message.get("params").is_none() {
                message["params"] = Value::Object(Map::new());
            }
            if message["params"].is_object() {
                message["params"]["_meta"] = meta;
            }
        }
        let result = async {
            match &self.wire {
                Wire::Streamable(wire) => wire.exchange(&message, id, headers).await,
                Wire::LegacySse(wire) => wire.exchange(&message, id, headers).await,
            }
        }
        .with_context(operation.context())
        .await;
        match &result {
            Ok(reply) => match &reply.result {
                Some(result) => operation.finish_result(result),
                None => operation.finish(),
            },
            Err(McpClientError::JsonRpc { code, .. }) => operation.rpc_error(*code),
            Err(
                McpClientError::Http { status, .. } | McpClientError::Unauthorized { status, .. },
            ) => operation.fail(status.to_string()),
            Err(error) => operation.fail(error.code()),
        }
        result
    }

    fn envelope(&self, method: &str, params: Option<Value>, id: Option<u64>) -> Value {
        let mut message = Map::new();
        message.insert("jsonrpc".to_string(), Value::from("2.0"));
        if let Some(id) = id {
            message.insert("id".to_string(), Value::from(id));
        }
        message.insert("method".to_string(), Value::from(method));
        if let Some(params) = params {
            message.insert("params".to_string(), params);
        }
        let message = Value::Object(message);
        if self.modern && id.is_some() {
            multicast_mcp_protocol::codec(McpWireCodecKind::Modern).project_outbound_request(
                &self.standard,
                &self.metadata,
                message,
            )
        } else {
            message
        }
    }

    /// Headers that depend on the negotiated standard and the message.
    fn protocol_headers(&self, message: &Value, negotiated: bool) -> HeaderMap {
        let mut headers = HeaderMap::new();
        let mut push = |name: &str, value: &str| {
            if let (Ok(name), Ok(value)) = (
                HeaderName::from_bytes(name.as_bytes()),
                HeaderValue::from_str(value),
            ) {
                headers.insert(name, value);
            }
        };
        if negotiated {
            push(HEADER_PROTOCOL_VERSION, self.standard.as_str());
        }
        if !self.modern {
            return headers;
        }
        let Some(method) = message.get("method").and_then(Value::as_str) else {
            return headers;
        };
        push(HEADER_METHOD, method);
        let params = message.get("params");
        let name_key = match method {
            // Named primitives.
            "tools/call" | "prompts/get" => Some("name"),
            // Resources are named by URI.
            "resources/read" | "resources/subscribe" | "resources/unsubscribe" => Some("uri"),
            // Skills and skill directories are named by URI.
            "skills/get" | "resources/directory/read" => Some("uri"),
            // Tasks are named by id.
            "tasks/get" | "tasks/update" | "tasks/cancel" => Some("taskId"),
            // No name header.
            _ => None,
        };
        let name = name_key
            .and_then(|key| params.and_then(|params| params.get(key)))
            .and_then(Value::as_str);
        if let Some(name) = name {
            push(HEADER_NAME, &encode_header_value(name));
        }
        if method == "tools/call"
            && let (Some(name), Some(arguments)) =
                (name, params.and_then(|params| params.get("arguments")))
            && let Ok(cache) = self.param_headers.lock()
            && let Some(annotations) = cache.get(name)
        {
            for (property, header) in annotations {
                let value = match arguments.get(property) {
                    // Primitive arguments are promoted to headers.
                    Some(Value::String(text)) => text.clone(),
                    Some(Value::Bool(flag)) => flag.to_string(),
                    Some(Value::Number(number)) => number.to_string(),
                    // Absent or structured arguments are not.
                    _ => continue,
                };
                push(
                    &format!("{HEADER_PARAM_PREFIX}{header}"),
                    &encode_header_value(&value),
                );
            }
        }
        headers
    }
}

/// The status of a task object.
fn task_status(task: &Value) -> Option<&str> {
    task.get("status").and_then(Value::as_str)
}

/// The task's requested poll interval, clamped to sane bounds.
fn poll_interval(task: &Value) -> Duration {
    task.get("pollIntervalMs")
        .and_then(Value::as_u64)
        .map_or(DEFAULT_TASK_POLL, Duration::from_millis)
        .clamp(MIN_TASK_POLL, MAX_TASK_POLL)
}

/// Sends `tasks/cancel` for a followed task when its caller drops the call
/// before the task leaves `working`. Only Streamable HTTP clients with
/// somewhere to run a detached request arm it: the host's `detach`
/// function, or the Tokio runtime on native targets.
struct CancelOnDrop {
    pending: Option<(Streamable, Value, u64, HeaderMap)>,
}

impl CancelOnDrop {
    fn new(client: &McpHttpClient, task_id: &str) -> Self {
        let pending = match &client.wire {
            // A Streamable client can send from a detached task.
            Wire::Streamable(wire)
                if wire.detach.is_some() || cfg!(not(target_arch = "wasm32")) =>
            {
                let id = client.next_id.fetch_add(1, Ordering::Relaxed);
                let message = client.envelope(
                    "tasks/cancel",
                    Some(serde_json::json!({ "taskId": task_id })),
                    Some(id),
                );
                let headers = client.protocol_headers(&message, true);
                Some((wire.clone(), message, id, headers))
            }
            // Nothing can run after the caller is gone.
            _ => None,
        };
        Self { pending }
    }

    fn disarm(&mut self) {
        self.pending = None;
    }
}

impl Drop for CancelOnDrop {
    fn drop(&mut self) {
        let Some((wire, message, id, headers)) = self.pending.take() else {
            return;
        };
        let detach = wire.detach.clone();
        let send = Box::pin(async move {
            let _ = wire.exchange(&message, Some(id), headers).await;
        });
        if let Some(detach) = detach {
            detach(send);
        } else {
            #[cfg(not(target_arch = "wasm32"))]
            if let Ok(runtime) = tokio::runtime::Handle::try_current() {
                runtime.spawn(send);
            }
        }
    }
}

fn parse_url(url: &str) -> Result<url::Url, McpClientError> {
    let parsed = url::Url::parse(url).map_err(|error| {
        McpClientError::InvalidUrl(format!("`{url}` is not a valid URL: {error}"))
    })?;
    if !matches!(parsed.scheme(), "http" | "https") {
        return Err(McpClientError::InvalidUrl(format!(
            "`{url}` is not an HTTP or HTTPS URL"
        )));
    }
    Ok(parsed)
}

fn configured_headers(options: &McpRemoteOptions) -> Result<HeaderMap, McpClientError> {
    let mut headers = HeaderMap::with_capacity(options.headers.len() + 1);
    for (name, value) in &options.headers {
        let header = HeaderName::try_from(name.as_str()).map_err(|_| {
            McpClientError::InvalidHeader(format!("`{name}` is not a valid header name"))
        })?;
        let value = HeaderValue::from_str(value).map_err(|_| {
            McpClientError::InvalidHeader(format!("the value for header `{name}` is not valid"))
        })?;
        headers.insert(header, value);
    }
    if let Some(token) = &options.auth_token {
        let mut value = HeaderValue::from_str(&format!("Bearer {token}")).map_err(|_| {
            McpClientError::InvalidHeader(
                "the bearer token is not a valid header value".to_string(),
            )
        })?;
        value.set_sensitive(true);
        headers.insert(http::header::AUTHORIZATION, value);
    }
    Ok(headers)
}

fn discovered(result: &Value) -> McpNegotiationEvidence {
    let supported = result
        .get("supportedVersions")
        .and_then(Value::as_array)
        .map(|versions| {
            versions
                .iter()
                .filter_map(Value::as_str)
                .map(McpVersion::from)
                .collect::<Vec<_>>()
        });
    match supported {
        // A well-formed discovery result.
        Some(supported) => McpNegotiationEvidence::Discovered { supported },
        // A discovery result without supported versions.
        None => McpNegotiationEvidence::InvalidModernResponse,
    }
}

fn evidence_for(error: &McpClientError) -> McpNegotiationEvidence {
    match error {
        // The peer recognized discovery but not the requested standard.
        McpClientError::JsonRpc { code, data, .. }
            if *code
                == i64::from(multicast_mcp_protocol::standards::UNSUPPORTED_PROTOCOL_VERSION) =>
        {
            McpNegotiationEvidence::UnsupportedVersion {
                supported: data
                    .as_ref()
                    .and_then(|data| data.get("supported"))
                    .and_then(Value::as_array)
                    .into_iter()
                    .flatten()
                    .filter_map(Value::as_str)
                    .map(McpVersion::from)
                    .collect(),
            }
        }
        // The peer does not know `server/discover`: it is a legacy server.
        McpClientError::JsonRpc { code, .. } if *code == METHOD_NOT_FOUND => {
            McpNegotiationEvidence::HttpBadRequestUnrecognized
        }
        // Credentials were rejected.
        McpClientError::Unauthorized { .. } => McpNegotiationEvidence::AuthenticationFailure,
        // The server failed.
        McpClientError::Http { status, .. } if *status >= 500 => {
            McpNegotiationEvidence::ServerFailure
        }
        // No response arrived.
        McpClientError::Transport(_) | McpClientError::Timeout { .. } => {
            McpNegotiationEvidence::TransportFailure
        }
        // Anything else is not evidence of a legacy peer.
        _ => McpNegotiationEvidence::InvalidModernResponse,
    }
}

/// Returns a tool's valid `x-mcp-header` annotations, or `None` when any
/// annotation is invalid and the tool must be dropped.
fn param_header_annotations(tool: &Value) -> Option<Vec<(String, String)>> {
    let Some(properties) = tool
        .pointer("/inputSchema/properties")
        .and_then(Value::as_object)
    else {
        return Some(Vec::new());
    };
    let mut annotations = Vec::new();
    let mut seen = std::collections::HashSet::new();
    for (property, schema) in properties {
        if has_nested_annotation(schema) {
            return None;
        }
        let Some(header) = schema.get("x-mcp-header") else {
            continue;
        };
        let header = header.as_str()?;
        let token = !header.is_empty()
            && header
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || "!#$%&'*+-.^_`|~".contains(c));
        let primitive = matches!(
            schema.get("type").and_then(Value::as_str),
            Some("string" | "integer" | "boolean")
        );
        if !token || !primitive || !seen.insert(header.to_ascii_lowercase()) {
            return None;
        }
        annotations.push((property.clone(), header.to_string()));
    }
    Some(annotations)
}

fn has_nested_annotation(schema: &Value) -> bool {
    schema
        .get("properties")
        .and_then(Value::as_object)
        .is_some_and(|nested| {
            nested
                .values()
                .any(|value| value.get("x-mcp-header").is_some() || has_nested_annotation(value))
        })
}

/// Encodes a header value, wrapping it as `=?base64?...?=` when it cannot be
/// sent verbatim.
fn encode_header_value(value: &str) -> String {
    let needs_encoding = !value.is_empty()
        && (value.starts_with([' ', '\t'])
            || value.ends_with([' ', '\t'])
            || value.chars().any(|c| !(' '..='~').contains(&c))
            || (value.starts_with("=?base64?") && value.ends_with("?=")));
    if needs_encoding {
        format!("=?base64?{}?=", base64(value.as_bytes()))
    } else {
        value.to_string()
    }
}

fn base64(bytes: &[u8]) -> String {
    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for chunk in bytes.chunks(3) {
        let triple = (u32::from(chunk[0]) << 16)
            | (u32::from(*chunk.get(1).unwrap_or(&0)) << 8)
            | u32::from(*chunk.get(2).unwrap_or(&0));
        for index in 0..4 {
            if index <= chunk.len() {
                out.push(char::from(
                    ALPHABET[(triple >> (18 - 6 * index)) as usize & 63],
                ));
            } else {
                out.push('=');
            }
        }
    }
    out
}

mod skills;
#[cfg(not(target_arch = "wasm32"))]
pub use skills::McpSkillDirectoryCache;
pub use skills::{ApprovedSkill, MAX_REMOTE_SKILLS, McpSkillCache, RemoteSkill, RemoteSkillFile};

#[cfg(feature = "mcp-files")]
mod files;
#[cfg(feature = "mcp-files")]
pub use files::{
    BoundaryEntropy, DEFAULT_MAX_DOWNLOAD_BYTES, DEFAULT_MAX_DOWNLOAD_TOTAL_BYTES,
    DEFAULT_MAX_DOWNLOADS, DEFAULT_PUT_ATTEMPTS, McpDownloadedFile, McpFileDownloadOptions,
    McpFileUploadOptions, safe_base_name,
};

#[cfg(test)]
pub(crate) mod tests;