polyc-tools 2026.8.3

The in-process tool core for polychrome agents: local executors (coding, web fetch, wallet, ...), the tool registry, and MCP composition. The networked connectors live in polyc-connectors.
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
//! Consume a remote Model Context Protocol server as a local
//! [`polyc_agent::ToolExecutor`].
//!
//! Connects via the streamable-HTTP transport and caches the remote's tool
//! specs. Each [`McpToolSource::execute`] forwards to `tools/call` on the remote
//! and turns the result back into a JSON string the agent loop already knows
//! how to wire into the next turn.
//!
//! A source obtains its live session in one of two ways:
//! [`McpToolSource::connect`] dials eagerly and OWNS the session for its
//! lifetime (the controller health check and the tests take this path);
//! [`McpToolSource::pooled`] draws the session from a shared
//! [`ConnectionPool`] keyed by (connector, principal), so
//! a later turn of the same conversation reuses one live session instead of
//! cold-dialing. A catalog-shipped pooled source composes WITHOUT any network
//! at all and dials lazily on its first `execute`.
//!
//! Multiple sources (plus the in-process pure-tool registry) compose via
//! [`CompositeRegistry`]; first source to claim a name wins, so
//! locally-defined tools shadow any colliding remote name by default.
//!
//! Each connector namespaces its tools by its own label: a source dialed for
//! connector `standup` advertises the remote's `post_update` as
//! `standup__post_update` (see [`CONNECTOR_TOOL_SEPARATOR`]). The remote keeps
//! receiving the raw name it registered — [`McpToolSource::execute`] strips the
//! prefix before the outbound `tools/call`. Built-in tools keep their bare
//! names. Namespacing attributes every advertised tool to its connector and, as
//! a side effect, makes two connectors advertising the same raw name coexist
//! instead of the second being shadowed.

use std::{
    sync::Arc,
    time::{Duration, Instant},
};

use async_trait::async_trait;
use polyc_agent::{ToolDecision, ToolExecutor};
use polyc_crypto::sensitive::Sensitive;
use polyc_llm::ToolSpec;
use rmcp::{
    ClientCacheConfig, ClientLifecycleMode, ClientServiceExt,
    model::{CallToolRequestParams, ProtocolVersion},
    service::{RoleClient, RunningService},
    transport::{
        StreamableHttpClientTransport, streamable_http_client::StreamableHttpClientTransportConfig,
    },
};

use crate::connection_pool::{ConnectionKey, ConnectionPool, PooledSession, SessionHandle};
use crate::connector_error::{
    CallRetryPolicy, ConnectorErrorKind, call_error_message, classify_call_error, dial_error,
    dial_failure_message, failure_json, result_message, success_json, transport_failure_message,
    transport_source_is_auth,
};

/// Default connect budget ([`ConnectOptions::timeout`]'s default).
///
/// A turn must not stall on a slow or dead connector: the harness composes
/// remote sources at turn start and a hung dial would block the whole
/// function-calling loop. Picked generous enough for a cold MCP server's
/// `server/discover` + `list_tools` round-trip yet tight enough that a single
/// unreachable connector degrades to "local tools only" promptly. Covers the
/// WHOLE dial: discovery (the `server/discover` round trip that replaces the
/// legacy `initialize` handshake) plus the initial `list_tools` catalog fetch,
/// not either leg alone.
pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);

/// Per-dial TCP connect budget for the injected reqwest client.
///
/// Bounds the TCP handshake so a dead/terminating toolservice fails fast
/// instead of blackholing the SYN for the kernel `tcp_syn_retries` (~130s).
/// Mirrors the `.connect_timeout(CONNECT_TIMEOUT)` idiom in `llm-vertex` /
/// `llm-openai`. Complements (does not replace) [`DEFAULT_CONNECT_TIMEOUT`],
/// the coarse outer budget over the whole `server/discover` + `list_tools`
/// round-trip.
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);

/// HTTP header carrying the turn's caller (persona id) to a dialed connector.
///
/// Set from [`ConnectOptions::caller`] — the control plane's own attribution
/// (`ToolServiceDescriptor.caller` on the wire), never a model-supplied
/// argument — so a connector enforcing per-caller isolation (e.g. the scaffold
/// connector's owner filter, `#789`) reads a value the calling agent cannot
/// forge by choosing tool arguments. Absent when the turn carries no
/// attributed persona (a smoke/listener path).
pub const CALLER_HEADER: &str = "x-polychrome-caller";

/// Separator between a connector's label and a remote tool's raw name in the
/// advertised tool name: connector `standup` + remote tool `post_update` →
/// `standup__post_update`.
///
/// A double underscore is chosen because a connector label is a Kubernetes
/// resource name (lowercase alphanumeric plus `-`), so `__` can never occur
/// inside a well-formed label — the boundary between label and tool name stays
/// unambiguous, and [`McpToolSource::execute`] can strip exactly the
/// `<label>__` prefix to recover the raw name the remote registered. The
/// charset is not assumed: [`is_valid_connector_label`] enforces it wherever a
/// label enters, and [`McpToolSource::connect`] fails closed on a violation.
pub const CONNECTOR_TOOL_SEPARATOR: &str = "__";

/// Whether `label` is a well-formed connector label: non-empty, lowercase
/// ASCII alphanumerics and `-` only — the Kubernetes resource-name charset.
///
/// This is the invariant that keeps the advertised `<label>__<tool>` name
/// unambiguous (no `_` in a label means [`CONNECTOR_TOOL_SEPARATOR`] cannot
/// occur inside one), collision-free (no two distinct labels reduce to the
/// same prefix), and inside every provider's tool-name charset. Kubernetes
/// enforces it on `ToolService` resource names; deployment-config labels
/// (`POLYCHROME_TOOL_SERVICES`) are checked against it at parse, and
/// [`McpToolSource::connect`] fails closed on a violation as the backstop.
#[must_use]
pub fn is_valid_connector_label(label: &str) -> bool {
    !label.is_empty()
        && label
            .chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
}

/// Errors that can occur connecting to a remote MCP server.
#[derive(Debug, thiserror::Error)]
pub enum McpClientError {
    /// Failed to initialise the underlying client (discovery or transport).
    #[error("MCP client initialise failed: {0}")]
    Init(String),
    /// Remote `list_tools` call failed.
    #[error("MCP list_tools failed: {0}")]
    ListTools(String),
    /// Connecting did not complete within the supplied budget.
    #[error("MCP connect timed out after {0:?}")]
    Timeout(Duration),
    /// The connector rejected the dial's credentials (HTTP 401/403 during
    /// discovery or the initial `list_tools`). Terminal — retrying the dial
    /// with the same token never helps — so it is a distinct variant the
    /// harness can route to credential renewal (`#636`) rather than a
    /// generic init failure.
    #[error("MCP connector rejected the credentials: {0}")]
    AuthRejected(String),
    /// A resource/connector URI could not be parsed into a canonical audience.
    #[error("invalid resource URI: {0}")]
    InvalidResource(String),
    /// The Control-owned trusted connector target failed SSRF validation
    /// before any socket was opened. This is a registry/configuration error,
    /// never a transport condition that a retry can make safe.
    #[error("trusted connector destination refused: {0}")]
    BlockedDestination(String),
    /// The connector label is outside the Kubernetes resource-name charset
    /// (see [`is_valid_connector_label`]). Refused rather than rewritten: a
    /// silent rewrite could collide two distinct labels into one advertised
    /// prefix, or let a label containing `__` make the namespaced tool name
    /// ambiguous.
    #[error(
        "invalid connector label {0:?}: a label is a Kubernetes resource name \
         (lowercase ASCII alphanumerics and `-`)"
    )]
    InvalidLabel(String),
    /// A bearer token bound to one audience was about to be presented to a
    /// different resource. Refused so a token minted for connector A cannot be
    /// passed through to connector B (token-passthrough / confused-deputy).
    #[error("bearer token audience {audience} does not match target resource {resource}")]
    AudienceMismatch {
        /// Canonical resource the token was minted for.
        audience: String,
        /// Canonical resource of the connector being dialed.
        resource: String,
    },
}

impl McpClientError {
    /// Classify this dial failure into the shared [`ConnectorErrorKind`] so the
    /// caller acts on the kind, not the message — mirroring the provider path's
    /// `LlmErrorKind`.
    ///
    /// A rejected credential ([`Self::AuthRejected`]) or a token bound to the
    /// wrong resource ([`Self::AudienceMismatch`]) classifies to
    /// [`ConnectorErrorKind::Auth`] — the fix is credential renewal. A malformed
    /// connector label ([`Self::InvalidLabel`]) or an unparseable connector URI
    /// ([`Self::InvalidResource`]) is the deployment's own configuration and
    /// classifies to [`ConnectorErrorKind::Config`] — terminal, but renewal
    /// would never fix it. A timeout or a plain handshake/`list_tools` failure
    /// is a reachability issue: [`ConnectorErrorKind::Transport`].
    #[must_use]
    pub const fn kind(&self) -> ConnectorErrorKind {
        match self {
            Self::AuthRejected(_) | Self::AudienceMismatch { .. } => ConnectorErrorKind::Auth,
            Self::InvalidLabel(_) | Self::InvalidResource(_) | Self::BlockedDestination(_) => {
                ConnectorErrorKind::Config
            }
            Self::Init(_) | Self::ListTools(_) | Self::Timeout(_) => ConnectorErrorKind::Transport,
        }
    }
}

/// Thin local error mirror so we don't leak `thiserror` re-exports.
type Result<T> = std::result::Result<T, McpClientError>;

/// Approval policy for one connector, resolved by the control plane from the
/// `ToolService` spec and applied at connect time.
///
/// Per-tool gating is the OR of this policy with the tool's own MCP
/// `destructiveHint`: `connector` gates everything from the server,
/// `tools` gates the named tools regardless of what the server self-declares
/// — the operator-side trust anchor.
#[derive(Debug, Clone, Default)]
pub struct ApprovalPolicy {
    /// Gate every tool from this connector (`ToolService.spec.needsApproval`).
    pub connector: bool,
    /// Gate exactly these tool names (`ToolService.spec.approvalTools`).
    pub tools: Vec<String>,
}

impl ApprovalPolicy {
    /// Connector-level-only policy (no per-tool operator list).
    #[must_use]
    pub const fn connector(connector: bool) -> Self {
        Self {
            connector,
            tools: Vec::new(),
        }
    }
}

/// Whether the operator registered this connector — the registry-provenance
/// half of capability classification (`#592`).
///
/// Taint-immune classification (fixed-connector read) is EARNED only by
/// operator registration: the control plane resolved the connector from the
/// `ToolService` registry, an operator act. A connector's own annotation
/// hints are load-bearing inputs only once the operator vouched for the
/// server — the MCP specification requires clients to treat tool annotations
/// as untrusted otherwise. The default is [`Self::SelfDeclared`] (fail
/// closed): a source nobody vouched for classifies to the privileged set no
/// matter how benign its self-declared hints look.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ConnectorProvenance {
    /// Resolved from the operator-maintained connector registry; annotations
    /// are trusted classification inputs.
    OperatorRegistered,
    /// Dialed without registry provenance (a dev/test dial, an ad-hoc URI);
    /// self-declared annotations never earn taint-immunity.
    #[default]
    SelfDeclared,
}

/// Options for one connector dial ([`McpToolSource::connect`]).
///
/// Every dial is the same operation with four independent knobs; this struct
/// replaces the constructor-per-combination matrix so a call site states only
/// what it varies from the default.
#[derive(Debug)]
pub struct ConnectOptions {
    /// The connector's identity. `Some(label)` namespaces every advertised
    /// tool as `<label>__<tool>` (see [`CONNECTOR_TOOL_SEPARATOR`]) and must
    /// satisfy [`is_valid_connector_label`]. `None` advertises the raw remote
    /// names unchanged — the single-connector introspection mode (the
    /// controller's health check reports the remote's own catalogue).
    pub label: Option<String>,
    /// Bearer presented in the `Authorization` header, audience-bound to the
    /// connector it was minted for (RFC 8707). The raw token reaches the wire
    /// only if its bound audience matches the dialed URI — a token minted for
    /// connector A presented against connector B fails closed with
    /// [`McpClientError::AudienceMismatch`] (confused-deputy). It rides the
    /// header rmcp's transport does NOT log — never the connector URL. `None`
    /// dials without auth.
    pub bearer: Option<AudienceBoundToken>,
    /// The turn's caller (persona id), presented to the connector as the
    /// [`CALLER_HEADER`] on every request over this dial. Sourced from the
    /// control plane's own per-turn attribution — never from a tool argument
    /// the model supplies — so a connector can trust it as the identity to
    /// enforce ownership against. `None` sends no header (an anonymous dial,
    /// or a turn with no attributed persona).
    pub caller: Option<String>,
    /// Approval policy resolved from the `ToolService` spec; see
    /// [`ApprovalPolicy`].
    pub approval: ApprovalPolicy,
    /// Outer budget over the whole `initialize` + `list_tools` round-trip, so
    /// a slow or dead connector cannot hang a turn. `None` dials unbounded
    /// (in-process test servers).
    pub timeout: Option<Duration>,
    /// Where the advertised specs come from: a live `list_tools`
    /// ([`SpecSource::List`], the default) or a control-plane–shipped catalog
    /// ([`SpecSource::Shipped`]).
    pub source: SpecSource,
    /// Bare (unprefixed) remote tool names this dial may advertise — the
    /// per-connector tool ceiling threaded straight off the wire
    /// (`ToolServiceDescriptor.allowed_tools`, #1219). Applied to the raw
    /// spec list BEFORE the approval gate and connector prefix, on both
    /// [`SpecSource`] variants alike, so a name outside the ceiling is never
    /// even prefixed into an advertised tool. Empty means no restriction —
    /// the default, and today's behavior for every open-grant connector and
    /// every dial this crate's other callers (the controller's health check,
    /// `mcp_roundtrip`) make.
    pub allowed_tools: Vec<String>,
}

impl Default for ConnectOptions {
    /// An anonymous, unlabeled, ungated, unrestricted dial bounded by
    /// [`DEFAULT_CONNECT_TIMEOUT`].
    fn default() -> Self {
        Self {
            label: None,
            bearer: None,
            caller: None,
            approval: ApprovalPolicy::default(),
            timeout: Some(DEFAULT_CONNECT_TIMEOUT),
            source: SpecSource::List,
            allowed_tools: Vec::new(),
        }
    }
}

/// Canonical resource indicator (RFC 8707 §2) for `uri`: the identity an MCP
/// access token is audience-bound to.
///
/// The `url` crate already lowercases the scheme + host and elides a
/// scheme-default port on parse; we additionally strip the fragment, which a
/// resource indicator MUST NOT carry. Both the token's bound audience and the
/// dial target are reduced through this so equal connectors compare equal
/// regardless of case or an explicit default port.
fn canonical_resource(uri: &str) -> Result<String> {
    let mut url = reqwest::Url::parse(uri)
        .map_err(|e| McpClientError::InvalidResource(format!("{uri}: {e}")))?;
    url.set_fragment(None);
    Ok(String::from(url))
}

/// A bearer token bound to the single audience it was minted for.
///
/// MCP's auth model (RFC 8707 Resource Indicators) requires an access token to
/// be scoped to one resource server so it cannot be replayed against another.
/// The control plane resolves a connector's token from that connector's own
/// secret, so its audience is the connector's canonical resource URI. Carrying
/// the audience *with* the token lets the dial path fail closed — refusing to
/// put the token on the wire toward any other resource — which is the
/// client-side half of closing the token-passthrough / confused-deputy hole.
#[derive(Debug, Clone)]
pub struct AudienceBoundToken {
    /// Raw bearer value presented in the `Authorization` header.
    token: Sensitive<String>,
    /// Canonical resource indicator (RFC 8707) this token is scoped to.
    audience: String,
}

impl AudienceBoundToken {
    /// Bind `token` to the connector identified by `resource_uri`.
    ///
    /// `resource_uri` is reduced to its canonical resource indicator (RFC 8707)
    /// so the later audience check is case- and default-port-insensitive.
    ///
    /// # Errors
    ///
    /// Returns [`McpClientError::InvalidResource`] if `resource_uri` is not a
    /// parseable absolute URI.
    pub fn new(token: impl Into<String>, resource_uri: &str) -> Result<Self> {
        Ok(Self {
            token: Sensitive::new(token.into()),
            audience: canonical_resource(resource_uri)?,
        })
    }

    /// The canonical resource indicator (RFC 8707) this token is bound to —
    /// the `resource` value a token request for it would carry.
    #[must_use]
    pub fn resource(&self) -> &str {
        &self.audience
    }

    /// Release the raw bearer **only** when `target_uri` canonicalises to this
    /// token's bound audience; otherwise refuse, so a token minted for one
    /// connector is never forwarded to another.
    ///
    /// # Errors
    ///
    /// Returns [`McpClientError::InvalidResource`] if `target_uri` does not
    /// parse, or [`McpClientError::AudienceMismatch`] if its canonical resource
    /// differs from this token's audience.
    pub fn bearer_for(&self, target_uri: &str) -> Result<&str> {
        let resource = canonical_resource(target_uri)?;
        if resource == self.audience {
            Ok(self.token.expose())
        } else {
            Err(McpClientError::AudienceMismatch {
                audience: self.audience.clone(),
                resource,
            })
        }
    }
}

/// Where a source's advertised tool specs come from.
///
/// This is the ONLY axis on which the two variants differ, and both dial paths
/// — the eager [`McpToolSource::connect`] and the pooled
/// [`McpToolSource::pooled`] — branch on it identically: [`Self::Shipped`] takes
/// the catalog as-is, [`Self::List`] enumerates the just-acquired session via
/// the shared `list_specs` helper. Every other step — label validation
/// (`validate_prefix`), bearer audience-binding, and the tool-ceiling filter,
/// approval gating, and namespacing (all three folded into the ONE seam
/// `finish_specs`) — is shared, so the two dial paths themselves diverge only
/// in HOW the session is acquired.
#[derive(Debug, Default)]
pub enum SpecSource {
    /// Enumerate the connector live: the dial performs the one-time
    /// `list_tools` after the handshake. The default.
    #[default]
    List,
    /// Compose from a control-plane–shipped catalog (the connector's
    /// version-keyed `ToolService` status, forwarded in the turn input) — no
    /// `list_tools` is ever sent. Specs are pre-gate: `needs_approval` is
    /// (re)derived here from the dial's [`ApprovalPolicy`], exactly as on the
    /// listed path. Execution still dials the connector; only the listing is
    /// skipped.
    Shipped(Vec<ToolSpec>),
}

/// Whether `name` is a BARE built-in name the agent's always-on core pins.
///
/// True when `name` is present in `core` and is not a namespaced
/// `<label>__<tool>` connector name (#637, invariant 3 of the tool-retrieval
/// design). The single owner of the "core wins over built-in scoping" union:
/// the harness widens its per-agent built-in allowlist with it and the
/// control plane's trusted call re-check admits with it, so the two sides
/// cannot drift. A namespaced core name is a connector tool governed by the
/// grant and is never admitted here.
#[must_use]
pub fn core_admits_builtin(name: &str, core: &[String]) -> bool {
    !name.contains(CONNECTOR_TOOL_SEPARATOR) && core.iter().any(|n| n == name)
}

/// The ONE shared admission predicate for a built-in NAME.
///
/// Consumed by both the harness's advertisement composition
/// (`build_tool_executor`) and the control plane's execution-time re-check
/// (`harness_dialer::tool_allowed`) — so a tool that isn't composed can never
/// be admitted at call time, and vice versa (`#1137`'s cross-layer parity
/// fix).
///
/// `core` always wins first, via [`core_admits_builtin`]: an always-on core
/// built-in is admitted regardless of `allow` or family. Past that, the
/// policy forks on [`crate::capability::management::is_management_builtin`]:
///
/// - **Management built-ins** (the wallet and email-linking families, the
///   roster-admin trio, and the deliberate memory write
///   `memory_write` — `#1139` Decision A) are admitted ONLY when `allow`
///   explicitly names them. `allow: None` (a turn that carried no grant
///   resolution) admits NONE of them — `Builtin` origin is not a blanket
///   advertisement/execution right for this family (INV-C7/INV-C19).
/// - **Every other built-in** (the coding core, the fetchers,
///   history-navigation, `peer_call`) defaults ON: `allow: None` admits it,
///   and `allow: Some(names)` admits it only when `names` contains it — the
///   ordinary opt-out allowlist behavior every built-in had before `#1137`.
#[must_use]
pub fn builtin_admits(name: &str, allow: Option<&[String]>, core: &[String]) -> bool {
    if core_admits_builtin(name, core) {
        return true;
    }
    if crate::capability::management::is_management_builtin(name) {
        allow.is_some_and(|allow| allow.iter().any(|n| n == name))
    } else {
        allow.is_none_or(|allow| allow.iter().any(|n| n == name))
    }
}

/// Dial a streamable-HTTP MCP server and DISCOVER its capabilities, returning
/// the live client WITHOUT listing its tools.
///
/// No `initialize`/`initialized` handshake and no `Mcp-Session-Id` are ever
/// exchanged: this workspace dials modern-only, so the ONLY lifecycle mode is
/// [`ClientLifecycleMode::Discover`] against protocol version
/// [`ProtocolVersion::V_2026_07_28`] — a single self-contained `server/discover`
/// request, after which every subsequent request on this session carries its
/// own per-request `_meta` (`RunningService::peer_info`/`set_client_request_metadata`,
/// done inside rmcp). There is no dual-protocol fallback and no legacy dial
/// path left to fall back to.
///
/// The caller supplies the tool catalog — either by listing (`list_all_tools`)
/// or from a shipped catalog — so this shared dial serves both the live-list and
/// catalog-composed constructors.
///
/// `caller`, when present, rides every request over this session as the
/// [`CALLER_HEADER`] — a malformed value (not a valid HTTP header value; the
/// control plane's own persona ids never are) is dropped with a `warn!`
/// rather than failing the whole dial, since the header is an enforcement
/// input for connectors that opt into reading it, not a wire requirement.
pub(crate) async fn dial_service(
    uri: Arc<str>,
    auth_header: Option<String>,
    caller: Option<String>,
    trusted_transport: Option<reqwest::Client>,
) -> Result<RunningService<RoleClient, ()>> {
    // Inject our own reqwest client so the dial carries a bounded
    // `connect_timeout` — rmcp's `from_uri`/`from_config` build a
    // `default_http_client()` with NO connect timeout, so a dead peer would
    // blackhole the SYN for ~130s. Redirects are disabled because this client
    // is the D7 trusted connector transport: a registry-approved destination
    // cannot become an arbitrary second destination by returning 3xx. The
    // `pool_max_idle_per_host(0)` setting preserves rmcp's default-client
    // Delayed-ACK mitigation.
    let http = match trusted_transport {
        // The trusted caller owns DNS classification, pinning, redirect
        // policy, and deadline selection. This component only consumes the
        // already-bound transport, so it cannot acquire ambient egress.
        Some(http) => http,
        None => reqwest::Client::builder()
            .pool_max_idle_per_host(0)
            .connect_timeout(CONNECT_TIMEOUT)
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .map_err(|e| McpClientError::Init(e.to_string()))?,
    };
    // rmcp's `auth_header` takes the raw token; the transport prepends
    // `Bearer `. Without a token we leave the header unset.
    let mut config = match auth_header {
        Some(token) => StreamableHttpClientTransportConfig::with_uri(uri).auth_header(token),
        None => StreamableHttpClientTransportConfig::with_uri(uri),
    };
    if let Some(caller) = caller {
        match http::HeaderValue::from_str(&caller) {
            Ok(value) => {
                config
                    .custom_headers
                    .insert(http::HeaderName::from_static(CALLER_HEADER), value);
            }
            Err(_) => {
                tracing::warn!(
                    "caller identity is not a valid HTTP header value; dialing without it"
                );
            }
        }
    }
    let transport = StreamableHttpClientTransport::with_client(http, config);
    // `()` is the canonical "anonymous" client; the SDK fills in a default
    // `ClientInfo`. We don't need any custom client-side handlers (sampling,
    // roots, elicitation) for tool routing — a server that issues an MRTR
    // sampling/elicitation request against this session gets a clean typed
    // `method_not_found` rejection rather than a hang (`()`'s blanket
    // `ClientHandler`).
    //
    // Modern-only dial (no dual-protocol mode): `Discover` sends one
    // `server/discover` request and never mints or reuses a transport-level
    // session. A rejected credential during discovery classifies as
    // AuthRejected (legible for credential renewal), not a generic Init
    // failure.
    let service = ()
        .serve_with_lifecycle(
            transport,
            ClientLifecycleMode::Discover {
                preferred_versions: vec![ProtocolVersion::V_2026_07_28],
            },
        )
        .await
        .map_err(dial_error)?;
    service
        .peer()
        .set_response_cache_config(catalog_cache_config())
        .await;
    Ok(service)
}

/// The SEP-2549 response-cache policy every dial on this surface runs under.
///
/// rmcp's defaults are kept except for `serve_stale_on_error`, which this
/// workspace turns OFF. The default serves an EXPIRED `tools/list` response
/// when the re-fetch fails — permitted by SEP-2549, and reasonable for a
/// client that merely displays a catalog. Here the catalog is the input to an
/// approval gate (a tool's `destructiveHint` becomes
/// [`ToolSpec::needs_approval`]), and "the connector is unreachable" is not
/// evidence that its old, more permissive declaration still holds. A failed
/// re-fetch therefore surfaces as a failure rather than as a silently expired
/// catalog presented to the model as current (INV-14).
///
/// `private_partition` is deliberately left unset. It exists for clients that
/// change principals on ONE connection; this workspace never does — the
/// connection pool keys every session by (connector, principal), so each rmcp
/// peer (and therefore each response cache) already belongs to exactly one
/// principal (INV-7, `crates/tools/src/connection_pool.rs`). Setting a
/// partition here would restate that isolation without adding any.
///
/// The freshness window itself stays the REMOTE's call: `default_ttl` is zero,
/// so a connector that omits `ttlMs` is treated as immediately stale, and
/// `max_ttl` caps anything a connector asks for.
fn catalog_cache_config() -> ClientCacheConfig {
    ClientCacheConfig::default().with_serve_stale_on_error(false)
}

/// Derive the per-tool approval gate on `spec` from its annotations under
/// `approval`, returning the gated spec.
///
/// Shared by the live-`list_tools` dial path and the shipped-catalog path so
/// both apply IDENTICAL approval semantics. Per-tool approval is the OR of three
/// signals: the connector-level `needs_approval` (a sensitive connector gates
/// ALL of its tools), the tool's own MCP `destructiveHint`, and the
/// OPERATOR-declared `approvalTools` list from the `ToolService` spec. The last
/// is the trust anchor: it holds even if a connector build stops self-declaring
/// a tool destructive.
fn gate_spec(mut spec: ToolSpec, approval: &ApprovalPolicy) -> ToolSpec {
    let operator_gated = approval.tools.contains(&spec.name);
    spec.needs_approval = approval.connector || spec.destructive || operator_gated;
    spec
}

/// Map one live-listed rmcp [`rmcp::model::Tool`] onto the unified
/// [`ToolSpec`], carrying the MCP `title` / `readOnlyHint` / `destructiveHint`
/// / `openWorldHint` annotations straight through — pre-gate, pre-prefix.
fn spec_from_rmcp_tool(t: rmcp::model::Tool) -> ToolSpec {
    // Only an *explicit* `destructiveHint: true` gates here — rmcp's
    // `is_destructive` default-of-true is deliberately NOT used, so an
    // un-annotated read-only tool stays ungated.
    let destructive = t
        .annotations
        .as_ref()
        .and_then(|a| a.destructive_hint)
        .unwrap_or(false);
    let read_only = t
        .annotations
        .as_ref()
        .and_then(|a| a.read_only_hint)
        .unwrap_or(false);
    // `openWorldHint` drives the untrusted-content (trifecta) leg: a tool that
    // interacts with an open world of external entities returns content of
    // uncontrolled provenance. FAIL CLOSED on a MISSING hint, matching the MCP
    // spec's own conservative default ("a tool with no annotations is assumed
    // ... open-world") and the annotation-security guidance ("no annotations
    // means review-required"): an unannotated connector is treated as
    // open-world, so it still seeds the leg. A connector that is genuinely
    // first-party / closed-domain must EXPLICITLY declare `openWorldHint:
    // false` to opt out — and that is a server-supplied CLAIM, so it only
    // narrows this hint-driven leg; it is not an exfiltration guarantee (that
    // lives in the egress leg + the network-egress-less sandbox).
    let open_world = t
        .annotations
        .as_ref()
        .and_then(|a| a.open_world_hint)
        .unwrap_or(true);
    let mut spec = ToolSpec::new(
        t.name.clone().into_owned(),
        t.description
            .map(std::borrow::Cow::into_owned)
            .unwrap_or_default(),
        serde_json::Value::Object((*t.input_schema).clone()),
    );
    spec.title = t.title;
    spec.read_only = read_only;
    spec.destructive = destructive;
    spec.open_world = open_world;
    spec
}

/// Validate `label` and reduce it to the `<label>__` prefix stamped onto every
/// advertised tool name — or the empty string for an unlabeled (raw-name) dial.
/// The one fail-closed label check both dial paths make before anything touches
/// the network.
///
/// # Errors
///
/// Returns [`McpClientError::InvalidLabel`] if `label` is `Some` but violates
/// [`is_valid_connector_label`].
fn validate_prefix(label: Option<String>) -> Result<String> {
    match label {
        Some(label) if !is_valid_connector_label(&label) => {
            Err(McpClientError::InvalidLabel(label))
        }
        Some(label) => Ok(format!("{label}{CONNECTOR_TOOL_SEPARATOR}")),
        None => Ok(String::new()),
    }
}

/// Enumerate `service`'s tools once and map each onto a pre-gate, pre-prefix
/// [`ToolSpec`]. Owns the auth-vs-transport classification of a failed
/// `list_tools`, so both dial paths report a rejected credential during the
/// initial listing as [`McpClientError::AuthRejected`] (legible for credential
/// renewal) rather than a generic [`McpClientError::ListTools`].
///
/// # Errors
///
/// Returns [`McpClientError::AuthRejected`] on a credential rejection, otherwise
/// [`McpClientError::ListTools`], if the remote refuses to enumerate its tools.
async fn list_specs(service: &RunningService<RoleClient, ()>) -> Result<Vec<ToolSpec>> {
    Ok(service
        .peer()
        .list_all_tools()
        .await
        .map_err(|e| {
            // A rejected credential during the initial `list_tools` is an auth
            // failure the same as one during the handshake — classify it so the
            // dial path stays legible, not a generic `ListTools`.
            if transport_source_is_auth(&e) {
                McpClientError::AuthRejected(e.to_string())
            } else {
                McpClientError::ListTools(e.to_string())
            }
        })?
        .into_iter()
        .map(spec_from_rmcp_tool)
        .collect())
}

/// Restrict `raw` (bare, pre-prefix) specs to `allowed`'s named tools — the
/// per-connector tool ceiling (#1219), folded into [`finish_specs`] so it is
/// applied BEFORE the approval gate and connector prefix on every spec
/// [`finish_specs`] ever finishes. `allowed` empty means no restriction:
/// `raw` passes through unchanged, matching every dial this crate served
/// before the ceiling existed (an open-grant connector, the controller's
/// single-connector health check, or any other caller that never sets
/// [`ConnectOptions::allowed_tools`]).
fn restrict_to_allowed(raw: Vec<ToolSpec>, allowed: &[String]) -> Vec<ToolSpec> {
    if allowed.is_empty() {
        return raw;
    }
    raw.into_iter()
        .filter(|spec| allowed.iter().any(|name| name == &spec.name))
        .collect()
}

/// Restrict to the tool ceiling, then apply the approval gate and the
/// connector prefix to every surviving spec — the ONE shared tail both dial
/// paths run once they hold `raw` (listed live or from a shipped catalog).
/// Folding [`restrict_to_allowed`] in HERE (rather than leaving it a call the
/// two dial paths each repeat) means a future third dial path inherits the
/// ceiling for free — it cannot forget the filter because there is no
/// separate step to forget.
///
/// Operator-declared `approvalTools` are RAW remote names, so gating happens
/// BEFORE the `<label>__` prefix is stamped (the prefix is a harness-side
/// namespace, invisible to the operator who authored the list);
/// [`McpToolSource::execute`] strips the prefix to recover the raw name at the
/// outbound `tools/call`.
fn finish_specs(
    raw: Vec<ToolSpec>,
    allowed: &[String],
    approval: &ApprovalPolicy,
    prefix: &str,
) -> Vec<ToolSpec> {
    restrict_to_allowed(raw, allowed)
        .into_iter()
        .map(|spec| {
            let mut spec = gate_spec(spec, approval);
            spec.name = format!("{prefix}{}", spec.name);
            spec
        })
        .collect()
}

/// An external MCP server, exposed as a local [`ToolExecutor`].
///
/// `clone` is cheap (`Arc` inside). The cached spec list is built once at
/// construction time so [`ToolExecutor::specs`] stays a hot-path getter.
pub struct McpToolSource {
    /// How this source reaches its live MCP session (owned, or pooled).
    session: SessionHandle,
    /// Cached tool catalogue, populated once during `connect`/`pooled`.
    specs: Vec<ToolSpec>,
    /// Whether every tool this source exposes requires signed human approval
    /// before [`ToolExecutor::execute`] runs. Set once at connect from the
    /// resolving `ToolService.spec.needs_approval`; the harness's HITL gate
    /// reads it via [`ToolExecutor::needs_approval`]. Connector-level (not
    /// per-tool) because the wire `ToolServiceDescriptor` carries one flag per
    /// connector — a sensitive MCP server gates all of its tools.
    needs_approval: bool,
    /// Registry provenance (`#592`): whether the operator registered this
    /// connector. Defaults to [`ConnectorProvenance::SelfDeclared`] (fail
    /// closed); the harness marks the sources it resolved from the registry
    /// via [`Self::operator_registered`].
    provenance: ConnectorProvenance,
    /// The `<label>__` string prepended to every remote tool name in the cached
    /// [`Self::specs`]. Empty when the source was dialed without a label (the
    /// controller's single-connector health check, which reports the raw
    /// catalogue). [`Self::execute`] strips exactly this prefix before the
    /// outbound `tools/call` so the remote receives the raw name it registered.
    prefix: String,
    /// Retry envelope for a single tool call. Only a transport failure retries,
    /// within [`CallRetryPolicy::budget`]; defaults to the shared
    /// [`CallRetryPolicy::DEFAULT`], overridable via [`Self::with_call_retry_policy`].
    retry: CallRetryPolicy,
}

impl std::fmt::Debug for McpToolSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("McpToolSource")
            .field("session", &"<SessionHandle>")
            .field(
                "specs",
                &self.specs.iter().map(|s| &s.name).collect::<Vec<_>>(),
            )
            .field("needs_approval", &self.needs_approval)
            .field("provenance", &self.provenance)
            .field("prefix", &self.prefix)
            .field("retry", &self.retry)
            .finish()
    }
}

impl McpToolSource {
    /// Connect to a streamable-HTTP MCP server at `uri` and eagerly cache its
    /// tool catalogue. Discovery (`server/discover`) plus `list_tools` runs
    /// once here — no `initialize`/`initialized` handshake, no session — so
    /// subsequent `specs()` calls are O(1). Each knob — connector label,
    /// bearer auth, approval policy, connect budget — is an
    /// [`options`](ConnectOptions) field.
    ///
    /// On budget expiry the in-flight dial is dropped (cancelled) and
    /// [`McpClientError::Timeout`] is returned so the caller can `warn!` +
    /// skip and fall back to whatever connected.
    ///
    /// # Errors
    ///
    /// Returns [`McpClientError::InvalidLabel`] (before any dial) if
    /// `options.label` violates [`is_valid_connector_label`],
    /// [`McpClientError::AudienceMismatch`] if `options.bearer`'s audience
    /// does not match `uri`, [`McpClientError::Timeout`] if the connect +
    /// initial `list_tools` exceed `options.timeout`, [`McpClientError::Init`]
    /// if discovery or the transport fails, and [`McpClientError::ListTools`]
    /// if the remote refuses to enumerate its tools.
    pub async fn connect(uri: impl Into<Arc<str>>, options: ConnectOptions) -> Result<Self> {
        // `timeout` is read (not destructured) so the rest of `options` travels
        // into `dial` as one struct instead of being pulled apart into
        // positional args the callee re-assembles.
        let timeout = options.timeout;
        let dial = Self::dial(uri.into(), options, None);
        match timeout {
            Some(budget) => tokio::time::timeout(budget, dial)
                .await
                .map_err(|_elapsed| McpClientError::Timeout(budget))?,
            None => dial.await,
        }
    }

    /// Connect with a transport already bound by the trusted caller.
    ///
    /// D7 callers resolve and pin a connector from trusted registry data before
    /// constructing `transport`. Raw Execution input is not accepted here: the
    /// URI and bearer remain the already-admitted [`ConnectOptions`] supplied
    /// by the trusted broker.
    ///
    /// # Errors
    ///
    /// Returns a connection, protocol, or transport error from the MCP dial.
    pub async fn connect_with_transport(
        uri: impl Into<Arc<str>>,
        options: ConnectOptions,
        transport: reqwest::Client,
    ) -> Result<Self> {
        let timeout = options.timeout;
        let dial = Self::dial(uri.into(), options, Some(transport));
        match timeout {
            Some(budget) => tokio::time::timeout(budget, dial)
                .await
                .map_err(|_elapsed| McpClientError::Timeout(budget))?,
            None => dial.await,
        }
    }

    /// The un-budgeted dial behind [`Self::connect`]: label validation, bearer
    /// audience-binding, discovery, and the one-time `list_tools` that builds
    /// the cached namespaced spec set.
    ///
    /// Takes the whole [`ConnectOptions`] (rather than its fields pulled apart
    /// into positional args) since every knob but `timeout` — already consumed
    /// by [`Self::connect`] to bound this call — travels straight through.
    async fn dial(
        uri: Arc<str>,
        options: ConnectOptions,
        trusted_transport: Option<reqwest::Client>,
    ) -> Result<Self> {
        let ConnectOptions {
            label,
            bearer,
            caller,
            approval,
            source,
            allowed_tools,
            timeout: _,
        } = options;
        // Validate the label → prefix and audience-bind the bearer before
        // anything touches the network: release the raw token only if it was
        // minted for THIS connector's resource, otherwise fail closed so a token
        // meant for another resource is never forwarded.
        let prefix = validate_prefix(label)?;
        let auth_header = match bearer {
            Some(token) => Some(Sensitive::new(token.bearer_for(&uri)?.to_owned())),
            None => None,
        };
        // The only divergence from the pooled path: this path OWNS the session it
        // dials. The `SpecSource` branch and the gate + prefix tail are shared.
        // `dial_service` needs an owned `String` (it hands the header straight
        // to rmcp's transport config) — exposed only at this, its one call site.
        let service = dial_service(
            uri,
            auth_header.map(|h| h.expose().clone()),
            caller,
            trusted_transport,
        )
        .await?;
        let raw = match source {
            SpecSource::List => list_specs(&service).await?,
            SpecSource::Shipped(specs) => specs,
        };
        let specs = finish_specs(raw, &allowed_tools, &approval, &prefix);

        Ok(Self {
            session: SessionHandle::Direct(Arc::new(service)),
            specs,
            needs_approval: approval.connector,
            provenance: ConnectorProvenance::default(),
            prefix,
            retry: CallRetryPolicy::default(),
        })
    }

    /// Compose a source that draws its live session from a shared
    /// [`ConnectionPool`], keyed by (connector,
    /// `principal`), so a later turn of the same conversation reuses one live
    /// session instead of cold-dialing.
    ///
    /// The `principal` is load-bearing: a session is never shared across
    /// principals, so a stateful server cannot leak one conversation's
    /// server-side context into another. It is the conversation routing key the
    /// turn carries.
    ///
    /// Laziness follows [`ConnectOptions::source`]. A
    /// [`SpecSource::Shipped`] catalog composes with ZERO network — the specs
    /// ride the catalog and the connector is dialed only on the first
    /// [`Self::execute`], through the pool. A [`SpecSource::List`] source must
    /// enumerate the remote, so it dials-through-the-pool here to `list_tools`;
    /// that dial warms the same session `execute` reuses.
    ///
    /// # Errors
    ///
    /// Returns [`McpClientError::InvalidLabel`] or
    /// [`McpClientError::AudienceMismatch`]/[`McpClientError::InvalidResource`]
    /// before any dial (fail closed on a bad label or a token bound to a
    /// different resource), and — on the [`SpecSource::List`] path only — the
    /// classified discovery/`list_tools` failure ([`McpClientError::Timeout`],
    /// [`McpClientError::AuthRejected`], [`McpClientError::Init`],
    /// [`McpClientError::ListTools`]).
    pub async fn pooled(
        pool: ConnectionPool,
        principal: impl Into<String>,
        uri: impl Into<Arc<str>>,
        options: ConnectOptions,
    ) -> Result<Self> {
        let ConnectOptions {
            label,
            bearer,
            caller,
            approval,
            timeout,
            source,
            allowed_tools,
        } = options;
        let uri: Arc<str> = uri.into();
        // Validate the label → prefix and audience-bind the bearer before
        // anything touches the network — the same fail-closed checks the eager
        // dial makes. The released header is what the pool re-presents on every
        // real dial. `label` is retained separately for the pool's connect log.
        let prefix = validate_prefix(label.clone())?;
        let auth_header = match bearer {
            Some(token) => Some(Sensitive::new(token.bearer_for(&uri)?.to_owned())),
            None => None,
        };
        let key = ConnectionKey::new(canonical_resource(&uri)?, principal);
        let pooled = PooledSession {
            pool: pool.clone(),
            key: key.clone(),
            uri: Arc::clone(&uri),
            // Clone the wrapper (cheap), not the exposed value — the pool
            // re-presents this header on every future re-dial for this
            // source's whole lifetime, so it stays `Sensitive` for as long as
            // it's held.
            auth_header: auth_header.clone(),
            caller: caller.clone(),
            connect_timeout: timeout,
            label: label.unwrap_or_default(),
        };
        // The only divergence from the eager dial: a live list dials THROUGH the
        // pool, so the warmed session is the one `execute` will reuse (a shipped
        // catalog composes with no network at all). The `SpecSource` branch and
        // the gate + prefix tail are shared.
        let raw = match source {
            SpecSource::Shipped(specs) => specs,
            SpecSource::List => {
                // `pool.acquire` needs a borrowed `&str` — exposed only at this
                // call site.
                let service = pool
                    .acquire(
                        &key,
                        &uri,
                        auth_header.as_ref().map(|h| h.expose().as_str()),
                        caller.as_deref(),
                        &pooled.label,
                        timeout,
                    )
                    .await?;
                // Every turn lists. Reusing a warm session is a transport
                // optimisation; reusing its CATALOG would be a freshness
                // claim the pool has no standing to make (INV-14). What
                // bounds the round trips instead is the remote's own
                // SEP-2549 hint, honoured by rmcp's per-peer response cache
                // (configured in `dial_service`): a connector that stamps a
                // real `ttlMs` is served from that cache within its own
                // declared window, and one that stamps `ttlMs: 0` — as every
                // server in this surface does — is re-listed here.
                list_specs(&service).await?
            }
        };
        let specs = finish_specs(raw, &allowed_tools, &approval, &prefix);

        Ok(Self {
            session: SessionHandle::Pooled(pooled),
            specs,
            needs_approval: approval.connector,
            provenance: ConnectorProvenance::default(),
            prefix,
            retry: CallRetryPolicy::default(),
        })
    }

    /// Tool names advertised by the remote server. Cheap clone-free view.
    pub fn names(&self) -> impl Iterator<Item = &str> {
        self.specs.iter().map(|s| s.name.as_str())
    }

    /// Whether tools from this source are gated behind human approval. Set at
    /// connect from the resolving `ToolService.spec.needs_approval`.
    #[must_use]
    pub const fn requires_approval(&self) -> bool {
        self.needs_approval
    }

    /// Mark this source as resolved from the operator-maintained connector
    /// registry (`#592`), making its self-declared annotations trusted
    /// classification inputs. Only the paths that genuinely resolved the
    /// connector from the registry may call this — an unmarked source stays
    /// [`ConnectorProvenance::SelfDeclared`] and classifies fail-closed.
    #[must_use]
    pub const fn operator_registered(mut self) -> Self {
        self.provenance = ConnectorProvenance::OperatorRegistered;
        self
    }

    /// The registry provenance this source was constructed with.
    #[must_use]
    pub const fn provenance(&self) -> ConnectorProvenance {
        self.provenance
    }

    /// Override the retry envelope this source applies to a single tool call
    /// (default: [`CallRetryPolicy::DEFAULT`]). Builder-style; used to tune the
    /// bounded budget or to shrink it in tests.
    #[must_use]
    pub const fn with_call_retry_policy(mut self, retry: CallRetryPolicy) -> Self {
        self.retry = retry;
        self
    }

    /// Fold a connector's re-declared tool list into the cached catalog,
    /// monotonically (`#598`): a runtime re-declaration may only ever ADD
    /// requirements, never shed one or earn taint-immunity mid-conversation.
    ///
    /// A source's own catalog is immutable for its lifetime (specs are listed
    /// once at construction), which satisfies the invariant trivially — a
    /// catalog change is observed by composing a NEW source next turn, not by
    /// mutating this one, and the freshness of that listing is bounded by the
    /// remote's SEP-2549 hint (INV-14). This stays the ONE mutation seam, so
    /// any future in-place re-declaration must route through it.
    ///
    /// Per re-declared tool matching a cached
    /// name, each security-relevant annotation is clamped to its less-trusted
    /// value (`read_only`/`cacheable_approval` can only be lost,
    /// `destructive`/`open_world`/`needs_approval` can only be gained —
    /// mirroring [`polyc_capability::monotonic_redeclaration`]); description,
    /// title, and schema follow the re-declaration (presentation, not
    /// security). A newly declared tool is appended as-declared (it is a new
    /// requirement, gated per the connector's approval policy); a cached tool
    /// missing from the re-declaration is KEPT — disappearing is not a
    /// downgrade path.
    pub fn merge_redeclared_specs(&mut self, redeclared: Vec<ToolSpec>) {
        for new in redeclared {
            if let Some(old) = self.specs.iter_mut().find(|s| s.name == new.name) {
                old.description = new.description;
                old.title = new.title;
                old.schema_json = new.schema_json;
                old.read_only = old.read_only && new.read_only;
                old.cacheable_approval = old.cacheable_approval && new.cacheable_approval;
                old.destructive = old.destructive || new.destructive;
                old.open_world = old.open_world || new.open_world;
                old.needs_approval = old.needs_approval || new.needs_approval;
            } else {
                let mut spec = new;
                // A brand-new tool from a gated connector inherits the
                // connector-level gate, exactly as it would at connect.
                spec.needs_approval = spec.needs_approval || self.needs_approval;
                self.specs.push(spec);
            }
        }
    }

    /// Politely close the underlying MCP service. Cancels any background
    /// transport tasks the streamable-HTTP client keeps alive. Safe to
    /// call multiple times — subsequent calls are no-ops.
    ///
    /// A pooled source leaves this to the pool, which may still be lending the
    /// session to another turn of the same conversation.
    pub fn shutdown(&self) {
        self.session.shutdown();
    }
}

impl Drop for McpToolSource {
    fn drop(&mut self) {
        // Best-effort: an owned (Direct) session whose last clone is dropping
        // has its transport cancelled so background tasks exit promptly. A
        // pooled session's lifecycle belongs to the pool, so dropping a source
        // that borrowed it is a no-op.
        if let SessionHandle::Direct(service) = &self.session
            && Arc::strong_count(service) == 1
        {
            service.cancellation_token().cancel();
        }
    }
}

#[async_trait]
impl ToolExecutor for McpToolSource {
    fn specs(&self) -> Vec<ToolSpec> {
        self.specs.clone()
    }

    /// Cheap membership check against the cached catalogue — no clone, unlike
    /// the default that materialises [`Self::specs`].
    fn owns(&self, name: &str) -> bool {
        self.specs.iter().any(|s| s.name == name)
    }

    /// Capability classification for a dialed connector tool (`#592`): the
    /// cached spec's annotations under this source's registry provenance. An
    /// operator-registered connector classifies from its annotations (a
    /// read-only tool needs only the fixed-connector read); a self-declared
    /// source — and any name this source does not advertise — fails closed to
    /// the privileged set, so a server nobody vouched for can never vouch for
    /// itself.
    fn required_capabilities(&self, name: &str) -> polyc_capability::CapabilitySet {
        let Some(spec) = self.specs.iter().find(|s| s.name == name) else {
            return polyc_capability::CapabilitySet::all();
        };
        let origin = match self.provenance {
            ConnectorProvenance::OperatorRegistered => {
                polyc_capability::ToolOrigin::RegisteredConnector
            }
            ConnectorProvenance::SelfDeclared => polyc_capability::ToolOrigin::Unknown,
        };
        polyc_capability::required_capabilities(polyc_capability::ToolProfile::for_spec(
            spec, origin,
        ))
    }

    /// Per-tool gate read from the cached spec's
    /// [`ToolSpec::needs_approval`](polyc_llm::ToolSpec::needs_approval).
    ///
    /// At connect time each spec's flag was set to the connector-level
    /// `needs_approval` OR the tool's MCP `destructiveHint` annotation, so this
    /// covers both a sensitive connector (gates all of its tools) and a single
    /// destructive tool on an otherwise-ungated connector. A name this source
    /// does not advertise is never gated.
    fn needs_approval(&self, name: &str) -> bool {
        self.specs
            .iter()
            .find(|s| s.name == name)
            .is_some_and(|s| s.needs_approval)
    }

    async fn execute(&self, name: &str, args_json: &str) -> String {
        // Wire is `Option<Map<...>>`. An empty/invalid args string maps to
        // `None`, which is what most remotes expect for a no-arg call.
        let arguments = serde_json::from_str::<serde_json::Value>(args_json)
            .ok()
            .and_then(|v| v.as_object().cloned());

        // The model calls the namespaced `<label>__<tool>` name (that is what
        // `owns` matched and routed here); strip the connector prefix so the
        // remote receives the raw name it registered. An empty prefix (health
        // check) leaves the name unchanged.
        let raw_name = name.strip_prefix(self.prefix.as_str()).unwrap_or(name);
        // Acquire the live session: a Direct source hands back its own client; a
        // pooled source reuses (or dials, warming the cache) through the pool. A
        // failed (lazy) dial is a typed connector failure the model can act on.
        let service = match self.session.acquire().await {
            Ok(service) => service,
            Err(err) => {
                let kind = err.kind();
                return failure_json(kind, &dial_failure_message(kind));
            }
        };
        // A transport failure retries with jittered backoff inside the bounded
        // budget; an auth or application failure returns on the first attempt.
        // Every outcome — success or a typed failure — folds into the same JSON
        // shape the agent loop already knows how to wire into the next turn.
        let started = Instant::now();
        let mut attempt: u32 = 0;
        // Whether a full backoff still fits inside the remaining retry budget;
        // shared by both places an attempt can fail (the remote answering with a
        // transport-classified error, and this attempt simply timing out), so the
        // two failure sources retry identically instead of drifting.
        let should_retry = |attempt: &mut u32| -> Option<Duration> {
            let delay = polyc_agent::retry::backoff_delay(
                *attempt,
                self.retry.base_delay,
                self.retry.max_delay,
                polyc_agent::retry::Clock::jitter_frac(&polyc_agent::retry::RealClock),
            );
            (started.elapsed() + delay <= self.retry.budget).then(|| {
                *attempt = attempt.saturating_add(1);
                delay
            })
        };
        loop {
            // `CallToolRequestParams` is `#[non_exhaustive]`; build it fresh each
            // attempt (retries re-send the same call) via its constructor.
            let mut request = CallToolRequestParams::new(raw_name.to_owned());
            request.arguments = arguments.clone();

            // Bound this ONE attempt: `tools/call` itself carries no timeout (the
            // injected reqwest client deliberately has none either, to keep rmcp's
            // long-lived SSE listen stream alive — see `CONNECT_TIMEOUT`'s doc), so
            // without this a stalled connector would hold the pooled session (and,
            // pre-#753, the whole streamed turn) open until the caller's own outer
            // deadline killed the entire turn instead of just this call.
            //
            // `RunningService::call_tool` (NOT `peer().call_tool_once`) drives
            // SEP-2322 MRTR: an `input_required` round is fulfilled through the
            // local `()` `ClientHandler` and retried automatically, echoing the
            // server's `requestState` back on the retry VERBATIM — this code never
            // reads, parses, or reconstructs it (INV-13). One logical call can
            // therefore span up to `DEFAULT_MRTR_MAX_ROUNDS` round trips plus the
            // SDK's own bounded inter-round backoff, all inside `call_timeout`.
            match tokio::time::timeout(self.retry.call_timeout, service.call_tool(request)).await {
                Ok(Ok(result)) if result.is_error == Some(true) => {
                    // The connector answered and reported a per-call failure — its
                    // own considered answer, so it goes to the model untried.
                    return failure_json(ConnectorErrorKind::Application, &result_message(&result));
                }
                Ok(Ok(result)) => return success_json(result),
                Ok(Err(err)) => {
                    let kind = classify_call_error(&err);
                    // Only a transport failure retries, and only while a full
                    // backoff still fits inside the remaining budget.
                    if kind == ConnectorErrorKind::Transport
                        && let Some(delay) = should_retry(&mut attempt)
                    {
                        tokio::time::sleep(delay).await;
                        continue;
                    }
                    // Terminal transport (budget spent) or auth: evict the pooled
                    // session so the next call re-dials a fresh one — a dead peer
                    // is not reused, and an auth rejection re-dials with whatever
                    // token the next turn ships. A Direct source's evict is inert.
                    if matches!(
                        kind,
                        ConnectorErrorKind::Transport | ConnectorErrorKind::Auth
                    ) {
                        self.session.evict();
                    }
                    return failure_json(kind, &call_error_message(kind, &err));
                }
                Err(_elapsed) => {
                    // A stalled attempt is classified exactly like an unreachable
                    // connector — retried the same way and, once terminal, evicting
                    // the same dead pooled session — since from the caller's side
                    // the two are indistinguishable (no answer either way).
                    if let Some(delay) = should_retry(&mut attempt) {
                        tokio::time::sleep(delay).await;
                        continue;
                    }
                    self.session.evict();
                    return failure_json(
                        ConnectorErrorKind::Transport,
                        transport_failure_message(),
                    );
                }
            }
        }
    }
}

/// Composes the local [`crate::ToolRegistry`] with any number of remote
/// [`McpToolSource`]s into a single [`ToolExecutor`] for the agent loop.
///
/// Lookup is *first-match-wins*: locally-defined tools shadow remote
/// duplicates, and earlier sources win against later ones. Duplicates are
/// elided from the advertised [`Self::specs`] so the provider never sees
/// two tools with the same name.
pub struct CompositeRegistry {
    sources: Vec<Arc<dyn ToolExecutor>>,
    /// The always-on tool core (#637): tool names advertised FIRST in
    /// [`Self::specs`], in this declared order, so the core forms a stable
    /// prefix regardless of source composition order (invariant 3 of #582).
    /// A declared name that no source advertises is simply absent — the core
    /// orders what exists, it does not manufacture a spec. Empty ⇒ no
    /// reordering (specs stay in composition order).
    core: Vec<String>,
}

impl std::fmt::Debug for CompositeRegistry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CompositeRegistry")
            .field("sources", &self.sources.len())
            .field("core", &self.core)
            .finish()
    }
}

impl Default for CompositeRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl CompositeRegistry {
    /// Empty registry. Add executors with [`Self::push`].
    #[must_use]
    pub fn new() -> Self {
        Self {
            sources: Vec::new(),
            core: Vec::new(),
        }
    }

    /// Pin an always-on tool core (#637): the named tools are advertised FIRST
    /// by [`Self::specs`], in this order, so they form a stable prefix ahead of
    /// every other advertised tool. Names a source does not advertise are
    /// ignored (the core orders what exists). Returns `self` for builder-style
    /// chaining.
    #[must_use]
    pub fn with_core(mut self, core: Vec<String>) -> Self {
        self.core = core;
        self
    }

    /// Append `executor` as a lower-precedence source. Returns `self` for
    /// builder-style chaining.
    #[must_use]
    pub fn with(mut self, executor: Arc<dyn ToolExecutor>) -> Self {
        self.sources.push(executor);
        self
    }

    /// Append `executor` in place.
    pub fn push(&mut self, executor: Arc<dyn ToolExecutor>) {
        self.sources.push(executor);
    }

    /// First source (in precedence order) that advertises `name`, or `None`
    /// if no source owns it. The single first-match-wins lookup shared by
    /// [`ToolExecutor::execute`] and [`ToolExecutor::needs_approval`] so the
    /// two never disagree on which source owns a tool.
    fn owner_of(&self, name: &str) -> Option<&Arc<dyn ToolExecutor>> {
        // `owns` is the cheap membership check — `McpToolSource` answers it from
        // its cached spec list without cloning, so this stays O(sources) on the
        // hot path (every `execute`/`needs_approval`) instead of cloning every
        // source's full spec vec per call.
        self.sources.iter().find(|source| source.owns(name))
    }
}

#[async_trait]
impl ToolExecutor for CompositeRegistry {
    fn specs(&self) -> Vec<ToolSpec> {
        let mut seen = std::collections::HashSet::new();
        let mut out = Vec::new();
        for source in &self.sources {
            for spec in source.specs() {
                if seen.insert(spec.name.clone()) {
                    out.push(spec);
                }
            }
        }
        if self.core.is_empty() {
            return out;
        }
        // #637: float the always-on core to the front, in its declared order,
        // keeping every non-core spec in composition order behind it. `sort_by`
        // is stable, so non-core relative order is preserved; a core name no
        // source advertised has no spec to move and is simply absent.
        let rank = |name: &str| self.core.iter().position(|c| c == name);
        out.sort_by(|a, b| match (rank(&a.name), rank(&b.name)) {
            (Some(x), Some(y)) => x.cmp(&y),
            (Some(_), None) => std::cmp::Ordering::Less,
            (None, Some(_)) => std::cmp::Ordering::Greater,
            (None, None) => std::cmp::Ordering::Equal,
        });
        out
    }

    /// Delegate to the source that owns `name` (same first-match-wins lookup
    /// as [`Self::execute`]). A tool is gated iff its owning source gates it,
    /// so a local pure tool shadowing a remote name keeps the local (not
    /// remote) approval policy. Unknown names are not gated — the
    /// `execute` path reports them as errors rather than pausing the loop.
    fn needs_approval(&self, name: &str) -> bool {
        self.owner_of(name)
            .is_some_and(|source| source.needs_approval(name))
    }

    /// Delegate the argument-aware dispatch decision (`#67`) to the owning
    /// source, mirroring [`Self::needs_approval`].
    ///
    /// Without this override the registry inherits the trait default, which
    /// derives the decision from [`Self::needs_approval`] alone — a bool. That
    /// silently collapses every richer decision a source makes on ARGUMENTS:
    /// a [`ToolDecision::Deny`] becomes `RequireApproval`, and a rewrite or
    /// injection is dropped. Since the harness always runs tools through a
    /// `CompositeRegistry`, that made argument-aware policy a no-op on the
    /// only production path — the control-plane proxy's routine classifiers
    /// (`#1497`, `#1495`) `Deny` a spec admission would reject precisely so a
    /// human approval card never shows an uncreatable routine (INV-RL2/RL3),
    /// and the human saw the card anyway.
    ///
    /// An unowned name is allowed, matching the inherited behavior it
    /// replaces: the `execute` path reports an unknown tool as an error
    /// rather than pausing the loop.
    fn pre_dispatch(&self, name: &str, args_json: &str) -> ToolDecision {
        self.owner_of(name).map_or(ToolDecision::Allow, |source| {
            source.pre_dispatch(name, args_json)
        })
    }

    /// Delegate result rewriting (`#67`, `#540`) to the owning source,
    /// mirroring [`Self::pre_dispatch`]. Inheriting the trait default `None`
    /// here would silently discard an owner's redaction on the only
    /// production path, so a secret the owner meant to strip would re-enter
    /// the model's context verbatim. An unowned name rewrites nothing.
    fn post_dispatch(&self, name: &str, args_json: &str, result_json: &str) -> Option<String> {
        self.owner_of(name)
            .and_then(|source| source.post_dispatch(name, args_json, result_json))
    }

    /// Fan the unadvertised-call recovery hatch (`#582`) out across every
    /// source, first-advertiser-wins on a duplicate name, mirroring
    /// [`Self::specs`].
    ///
    /// Owner routing cannot work here: the call named no advertised tool, so
    /// by construction it has no owner. No source opts into the hatch today —
    /// the retrieval gate does, and it wraps this registry from OUTSIDE — but
    /// inheriting the empty default would silently swallow one that did.
    fn recover_unadvertised(&self, name: &str, args_json: &str) -> Vec<ToolSpec> {
        let mut seen = std::collections::HashSet::new();
        let mut out = Vec::new();
        for source in &self.sources {
            for spec in source.recover_unadvertised(name, args_json) {
                if seen.insert(spec.name.clone()) {
                    out.push(spec);
                }
            }
        }
        out
    }

    /// Delegate the sandbox-denial escalation predicate (`#301`) to the owning
    /// source, mirroring [`Self::needs_approval`]. Without this override the
    /// registry inherits the trait default `false`, and since the harness ALWAYS
    /// runs tools through a `CompositeRegistry` (see `build_tool_executor`), the
    /// per-caller escalation would be a silent no-op on the only production path
    /// — a sandbox-denied destructive call would run-then-flat-deny instead of
    /// pausing for an unsandboxed retry. Unknown names never escalate (the
    /// `execute` path reports them as errors).
    fn sandbox_would_deny(&self, name: &str, args_json: &str) -> bool {
        self.owner_of(name)
            .is_some_and(|source| source.sandbox_would_deny(name, args_json))
    }

    /// Owner-delegating capability classification (`#592`), OR-ed with the
    /// static fail-safe floor ([`crate::capability::floor_requirements`]).
    ///
    /// Routing through the OWNER is what makes classification collision-proof
    /// for an *aliased* connector tool: a connector advertising a tool named
    /// like a reserved coding tool (e.g. `file_read`) on an agent where that
    /// built-in is scoped out is owned by the connector — `execute` forwards
    /// to the remote service — so its requirements must come from the
    /// connector's classification (fail-closed unless operator-registered),
    /// never from the benign local name. The floor catches the complementary
    /// direction: a brokering owner that under-reports a fetcher the static
    /// catalog knows reaches model-controlled destinations cannot shed that
    /// requirement. An unowned name fails closed to the privileged set.
    fn required_capabilities(&self, name: &str) -> polyc_capability::CapabilitySet {
        self.owner_of(name)
            .map_or_else(polyc_capability::CapabilitySet::all, |source| {
                source
                    .required_capabilities(name)
                    .union(crate::capability::floor_requirements(name))
            })
    }

    // `ingests_untrusted_content` is intentionally NOT overridden: the taint
    // ingress rides the per-tool `ToolSpec::open_world` annotation, not an
    // owner's runtime claim, so the trait's spec-derived default over the
    // aggregated `specs()` is already correct and collision-proof — the same
    // reasoning as `cacheable_approval`.
    // No fail-safe floor is needed because the provenance travels IN the spec
    // (set from the connector's `openWorldHint` at connect), not inferred from
    // who executes the call.

    // `cacheable_approval` is intentionally NOT overridden: this registry's
    // `specs()` aggregates every source's specs (each carrying its own
    // `ToolSpec::cacheable_approval`), so the trait's spec-derived default is
    // already correct. It is only ever queried for a tool being called (rare,
    // post "don't ask again"), so the per-call aggregation is not a hot path.

    /// Re-root every source that owns a workspace, for a delegated worker
    /// (`#2286`).
    ///
    /// Maps [`ToolExecutor::for_worker`] over `sources` in order: a source
    /// that returns `Some` is replaced by its re-rooted version; one that
    /// returns `None` (no workspace of its own — a remote [`McpToolSource`],
    /// say) is kept AS-IS rather than dropped — sources are already `Arc`, so
    /// reusing one unchanged is cheap. Returns `Some` (a new composite,
    /// `core` preserved) iff at least one source actually re-rooted;
    /// otherwise `None`, so a composite with nothing to re-root behaves
    /// exactly like the trait default and the caller falls back to running
    /// through the parent's own composite unre-rooted.
    ///
    /// A source that REFUSES the share-in request (`#2295`) fails the whole
    /// composite: the refusal propagates as `Some(Err(_))` and no source is
    /// re-rooted. Swallowing it to keep the other sources would run the worker
    /// against a partial view of what its task named, which is precisely the
    /// outcome the ceiling's hard refusals exist to avoid.
    fn for_worker(
        &self,
        scope: &polyc_agent::delegate::WorkerScope<'_>,
    ) -> Option<
        std::result::Result<
            polyc_agent::delegate::WorkerHandoff,
            polyc_agent::delegate::ShareInError,
        >,
    > {
        let rerooted: Vec<Option<polyc_agent::delegate::WorkerHandoff>> = match self
            .sources
            .iter()
            .map(|source| source.for_worker(scope).transpose())
            .collect::<std::result::Result<Vec<_>, _>>()
        {
            Ok(rerooted) => rerooted,
            Err(err) => return Some(Err(err)),
        };
        if rerooted.iter().all(Option::is_none) {
            return None;
        }
        let mut seeded = Vec::new();
        let sources: Vec<Arc<dyn ToolExecutor>> = rerooted
            .into_iter()
            .zip(self.sources.iter())
            .map(|(re, original)| {
                re.map_or_else(
                    || Arc::clone(original),
                    |handoff| {
                        seeded.extend(handoff.seeded);
                        handoff.tools
                    },
                )
            })
            .collect();
        Some(Ok(polyc_agent::delegate::WorkerHandoff {
            tools: Arc::new(Self {
                sources,
                core: self.core.clone(),
            }),
            seeded,
        }))
    }

    async fn execute(&self, name: &str, args_json: &str) -> String {
        if let Some(source) = self.owner_of(name) {
            return source.execute(name, args_json).await;
        }
        failure_json(
            ConnectorErrorKind::Application,
            &format!("unknown tool: {name}"),
        )
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]
    use serde_json::json;

    use super::*;

    /// The label charset is exactly the Kubernetes resource-name set: lowercase
    /// ASCII alphanumerics and `-`, non-empty. Everything else — including `_`,
    /// which would let [`CONNECTOR_TOOL_SEPARATOR`] occur inside a label — is
    /// rejected rather than rewritten.
    /// The one owner of the core/built-in union: bare core names admit, and a
    /// namespaced connector name NEVER does — it is grant-governed, so neither
    /// the harness widen nor the control plane's re-check may admit it.
    #[test]
    fn core_admits_only_bare_builtin_names() {
        let core = vec!["grep".to_owned(), "vcs__repo_list".to_owned()];
        assert!(core_admits_builtin("grep", &core));
        assert!(
            !core_admits_builtin("vcs__repo_list", &core),
            "namespaced = grant-governed"
        );
        assert!(!core_admits_builtin("file_read", &core), "not declared");
    }

    // #1137: the shared admission predicate's management-vs-default-on fork.
    #[test]
    fn builtin_admits_gates_management_names_on_explicit_allow_only() {
        let no_core: Vec<String> = Vec::new();
        // `None` (no grant resolution) admits none of the management family —
        // the parity fix: this must match what the harness composes.
        assert!(!builtin_admits("wallet_status", None, &no_core));
        assert!(!builtin_admits("invite", None, &no_core));
        // Named in `allow`: admitted.
        let allow = vec!["wallet_status".to_owned()];
        assert!(builtin_admits("wallet_status", Some(&allow), &no_core));
        // A management name NOT named in a `Some` allow stays refused.
        assert!(!builtin_admits("wallet_link", Some(&allow), &no_core));
    }

    #[test]
    fn builtin_admits_defaults_non_management_names_on() {
        let no_core: Vec<String> = Vec::new();
        // `None` defaults every non-management built-in ON.
        assert!(builtin_admits("history_search", None, &no_core));
        assert!(builtin_admits("shell_exec", None, &no_core));
        // `Some` scopes it to an ordinary allowlist check.
        let allow = vec!["history_search".to_owned()];
        assert!(builtin_admits("history_search", Some(&allow), &no_core));
        assert!(!builtin_admits("history_peek", Some(&allow), &no_core));
    }

    #[test]
    fn builtin_admits_core_wins_over_both_policies() {
        let core = vec!["wallet_status".to_owned()];
        // A core-pinned management name is admitted even with `allow: None`.
        assert!(builtin_admits("wallet_status", None, &core));
        // And even when an explicit `allow` doesn't name it.
        let allow: Vec<String> = Vec::new();
        assert!(builtin_admits("wallet_status", Some(&allow), &core));
    }

    #[test]
    fn connector_label_charset_is_the_k8s_resource_name_set() {
        for ok in ["standup", "calc-svc", "a", "svc2"] {
            assert!(is_valid_connector_label(ok), "{ok:?} must be valid");
        }
        for bad in [
            "",
            "a.b",
            "a_b",
            "my__svc",
            "MixedCase",
            "spa ce",
            "emoji✨",
        ] {
            assert!(!is_valid_connector_label(bad), "{bad:?} must be rejected");
        }
    }

    /// Stub source standing in for an [`McpToolSource`] in the composition
    /// tests: the real source holds a live transport that can't be built
    /// in-process, so this fake mirrors the one behavior under test — it OWNS
    /// the tools it advertises, exactly as `execute` would forward each call
    /// to an external `ToolService`.
    #[derive(Debug)]
    struct FakeConnector {
        names: Vec<String>,
    }

    #[async_trait]
    impl ToolExecutor for FakeConnector {
        fn specs(&self) -> Vec<ToolSpec> {
            self.names
                .iter()
                .map(|n| ToolSpec::new(n, "remote tool", json!({})))
                .collect()
        }

        fn owns(&self, name: &str) -> bool {
            self.names.iter().any(|n| n == name)
        }

        async fn execute(&self, _name: &str, _args_json: &str) -> String {
            json!({ "ok": true }).to_string()
        }
    }

    #[test]
    fn aliased_connector_tool_classifies_through_its_owner() {
        use crate::ToolRegistry;
        use polyc_capability::{Capability, CapabilitySet};

        // Agent scoped so the `file_read` built-in is NOT granted — the supported
        // builtinTools-allowlist config that omits it. The local registry then
        // does not own `file_read`, so lookup falls through to the connector.
        let local = ToolRegistry::scoped(["shell_exec".to_owned()]);
        // A connector advertises a tool ALIASED to the reserved coding name.
        let connector = FakeConnector {
            names: vec!["file_read".to_owned()],
        };

        let registry = CompositeRegistry::new()
            .with(Arc::new(local))
            .with(Arc::new(connector));

        // Owner-aware delegation routes to the connector, whose classification
        // fails closed (no override on the fake — the trait default) — so the
        // aliased call requires the privileged set and gates under taint,
        // instead of inheriting the local name's benign local-read set (the
        // aliased-egress evasion the old name-based rule allowed).
        assert_eq!(
            registry.required_capabilities("file_read"),
            CapabilitySet::all(),
            "an aliased connector tool must classify via its owner, fail closed"
        );

        // `file_read` GRANTED locally: the local registry owns it (first-match
        // wins) and classifies it as the sandbox-confined read. The connector's
        // colliding alias is shadowed, so the composite honors the LOCAL answer.
        let local = ToolRegistry::scoped(["file_read".to_owned()]);
        let connector = FakeConnector {
            names: vec!["file_read".to_owned()],
        };
        let registry = CompositeRegistry::new()
            .with(Arc::new(local))
            .with(Arc::new(connector));
        assert_eq!(
            registry.required_capabilities("file_read"),
            CapabilitySet::of(Capability::LocalRead),
            "a granted local coding tool keeps its local classification"
        );
    }

    // #592: the composite's capability floor mirrors the egress floor — an
    // owner that under-reports a known fetcher cannot shed its requirements.
    #[test]
    fn capability_floor_pins_an_under_reported_fetcher() {
        use polyc_capability::{Capability, CapabilitySet};

        #[derive(Debug)]
        struct MisclassifyingProxy;
        #[async_trait]
        impl ToolExecutor for MisclassifyingProxy {
            fn specs(&self) -> Vec<ToolSpec> {
                vec![ToolSpec::new("web_fetch", "fetch", json!({})).read_only()]
            }
            fn owns(&self, name: &str) -> bool {
                name == "web_fetch"
            }
            // BUG under test: claims the fetcher is a mere local read.
            fn required_capabilities(&self, _name: &str) -> CapabilitySet {
                CapabilitySet::of(Capability::LocalRead)
            }
            async fn execute(&self, _name: &str, _args_json: &str) -> String {
                json!({ "ok": true }).to_string()
            }
        }

        let registry = CompositeRegistry::new().with(Arc::new(MisclassifyingProxy));
        let required = registry.required_capabilities("web_fetch");
        assert!(
            required.contains(Capability::ArbitraryEgress),
            "the floor must keep the fetcher's requirement: {:?}",
            required.names()
        );
        // An unowned name fails closed to the privileged set.
        assert_eq!(
            registry.required_capabilities("no_such_tool"),
            CapabilitySet::all()
        );
        // A connector alias of a local name classifies through its OWNER: the
        // fake connector doesn't override the classification, so its trait
        // default (fail closed, privileged set) is what the gate sees — never
        // the local built-in's benign local-read set.
        let aliased = CompositeRegistry::new().with(Arc::new(FakeConnector {
            names: vec!["file_read".to_owned()],
        }));
        assert_eq!(
            aliased.required_capabilities("file_read"),
            CapabilitySet::all()
        );
    }

    #[test]
    fn resource_indicator_is_canonical_per_rfc8707() {
        // The bound audience is the connector's canonical resource indicator:
        // lowercased scheme + host, default port elided, fragment stripped.
        let token = AudienceBoundToken::new("secret", "HTTPS://Conn.Example:443/mcp#frag")
            .expect("valid resource URI");
        assert_eq!(token.resource(), "https://conn.example/mcp");
    }

    #[test]
    fn token_forwarded_only_to_its_bound_audience() {
        let token =
            AudienceBoundToken::new("secret", "https://a.example/mcp").expect("valid resource");

        // Same resource (port-canonicalised) → the raw bearer is released.
        assert_eq!(
            token
                .bearer_for("https://a.example:443/mcp")
                .expect("match"),
            "secret"
        );

        // A token minted for connector A must never be forwarded to B: refuse
        // it instead, closing the token-passthrough / confused-deputy hole.
        let err = token
            .bearer_for("https://b.example/mcp")
            .expect_err("cross-audience forward must be rejected");
        assert!(
            matches!(err, McpClientError::AudienceMismatch { .. }),
            "expected AudienceMismatch, got {err:?}"
        );
    }

    /// The raw bearer never prints from a derived `Debug` (#1276): the
    /// `token` field is `Sensitive<String>`, so even a full-struct dump
    /// redacts it.
    #[test]
    fn debug_redacts_the_raw_bearer() {
        let token = AudienceBoundToken::new("super-secret-bearer", "https://a.example/mcp")
            .expect("valid resource");
        assert!(!format!("{token:?}").contains("super-secret-bearer"));
    }

    #[test]
    fn invalid_resource_uri_is_rejected() {
        assert!(matches!(
            AudienceBoundToken::new("secret", "not a url"),
            Err(McpClientError::InvalidResource(_))
        ));
    }
}