rmcp-server-kit 3.10.1

Reusable MCP server framework with auth, RBAC, and Streamable HTTP transport (built on the rmcp SDK)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
//! Opt-in tool-call instrumentation for `ServerHandler` implementations.
//!
//! [`crate::tool_hooks::HookedHandler`] wraps any [`rmcp::ServerHandler`] with:
//!
//! - **Before hooks** (async) that observe `(tool_name, arguments, identity,
//!   role, sub, request_id)` and may [`HookOutcome::Continue`](crate::tool_hooks::HookOutcome::Continue),
//!   [`HookOutcome::Deny`](crate::tool_hooks::HookOutcome::Deny), or
//!   [`HookOutcome::Replace`](crate::tool_hooks::HookOutcome::Replace) the call.
//! - **After hooks** (async) that observe the same context plus a
//!   [`HookDisposition`](crate::tool_hooks::HookDisposition) describing how the call resolved and the
//!   approximate result size in bytes.  After-hooks are spawned via
//!   `tokio::spawn` and never block the response path.
//! - **Result-size capping**: serialized tool results larger than
//!   `max_result_bytes` are replaced with a structured error, preventing
//!   token-expensive or memory-expensive payloads from reaching clients.
//!   The cap applies both to inner-handler results and to
//!   [`HookOutcome::Replace`](crate::tool_hooks::HookOutcome::Replace) payloads.
//!
//! # Cancel safety
//!
//! The transparent `ServerHandler` delegation methods are cancel-safe with
//! respect to this wrapper: cancellation only drops the delegated inner
//! future, so the wrapped handler's own cancel-safety contract is inherited
//! unchanged.  The `call_tool` implementation on
//! [`crate::tool_hooks::HookedHandler`] is the exception and is documented
//! as **NOT cancel-safe** at its definition: once a before-hook or the
//! inner handler has been awaited, cancellation can prevent the paired
//! after-hook from being spawned.
//!
//! This is entirely **opt-in** at the application layer - `rmcp_server_kit::serve()`
//! does not wrap handlers automatically.  Applications that want hooks do:
//!
//! ```no_run
//! use std::sync::Arc;
//! use rmcp_server_kit::tool_hooks::{HookedHandler, HookOutcome, ToolHooks, with_hooks};
//!
//! # #[derive(Clone, Default)]
//! # struct MyHandler;
//! # impl rmcp::ServerHandler for MyHandler {}
//! let handler = MyHandler::default();
//! let hooks = Arc::new(
//!     ToolHooks::new()
//!         .with_max_result_bytes(256 * 1024)
//!         .with_before(Arc::new(|_ctx| Box::pin(async { HookOutcome::Continue })))
//!         .with_after(Arc::new(|_ctx, _disp, _bytes| Box::pin(async {}))),
//! );
//! let _wrapped = with_hooks(handler, hooks);
//! ```

use std::{borrow::Cow, fmt, future::Future, io, pin::Pin, sync::Arc};

#[allow(
    deprecated,
    reason = "transparent ServerHandler delegation must import legacy logging/subscription parameter types until rmcp removes those methods"
)]
use rmcp::{
    ErrorData, RoleServer, ServerHandler,
    model::{
        CallToolRequestParams, CallToolResponse, CallToolResult, CancelTaskParams,
        CancelledNotificationParam, CompleteRequestParams, CompleteResult, ContentBlock,
        CustomNotification, CustomRequest, CustomResult, DiscoverResult, GetPromptRequestParams,
        GetPromptResponse, GetTaskParams, GetTaskResult, InitializeRequestParams, InitializeResult,
        ListPromptsResult, ListResourceTemplatesResult, ListResourcesResult, ListToolsResult,
        PaginatedRequestParams, ProgressNotificationParam, ProtocolVersion,
        ReadResourceRequestParams, ReadResourceResponse, ServerInfo, SetLevelRequestParams,
        SubscribeRequestParams, SubscriptionFilter, Tool, UnsubscribeRequestParams,
        UpdateTaskParams,
    },
    service::{NotificationContext, RequestContext, SubscriptionContext},
};

/// Context passed to before/after hooks for a single tool call.
#[derive(Clone)]
#[non_exhaustive]
pub struct ToolCallContext {
    /// Tool name being invoked.
    pub tool_name: String,
    /// JSON arguments as sent by the client (may be `None`).
    pub arguments: Option<serde_json::Value>,
    /// Identity name from the authenticated request, if any.
    pub identity: Option<String>,
    /// RBAC role associated with the request, if any.
    pub role: Option<String>,
    /// OAuth `sub` claim, if present.
    pub sub: Option<String>,
    /// Raw JSON-RPC request id rendered as a string, if available.
    pub request_id: Option<String>,
}

impl ToolCallContext {
    /// Construct a [`ToolCallContext`] with the given tool name and all
    /// optional fields cleared.  Primarily for use in unit tests and
    /// benchmarks of user-supplied hooks; the runtime path populates
    /// these fields from the request and task-local RBAC state.
    #[must_use]
    pub fn for_tool(tool_name: impl Into<String>) -> Self {
        Self {
            tool_name: tool_name.into(),
            arguments: None,
            identity: None,
            role: None,
            sub: None,
            request_id: None,
        }
    }
}

impl fmt::Debug for ToolCallContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self {
            tool_name,
            arguments,
            identity,
            role,
            sub,
            request_id,
        } = self;
        let mut debug = f.debug_struct("ToolCallContext");
        debug.field("tool_name", tool_name);
        if crate::diagnostics::tool_call_arguments() {
            debug
                .field("arguments", arguments)
                .field("identity", identity)
                .field("role", role)
                .field("sub", sub);
        } else {
            debug
                .field("arguments", &"[REDACTED]")
                .field("identity", &"[REDACTED]")
                .field("role", &"[REDACTED]")
                .field("sub", &"[REDACTED]");
        }
        debug.field("request_id", request_id).finish()
    }
}

/// Outcome returned by a [`BeforeHook`] to control invocation flow.
///
/// - [`HookOutcome::Continue`] - proceed with the wrapped handler.
/// - [`HookOutcome::Deny`] - reject the call with the supplied
///   [`ErrorData`]; the inner handler is **not** called.
/// - [`HookOutcome::Replace`] - return the supplied result instead of
///   invoking the inner handler.  The result is still subject to
///   `max_result_bytes` capping.
#[derive(Debug)]
#[non_exhaustive]
pub enum HookOutcome {
    /// Proceed with the wrapped handler.
    Continue,
    /// Reject the call.  The error is propagated to the client as-is.
    Deny(ErrorData),
    /// Skip the inner handler and return the supplied result instead.
    Replace(Box<CallToolResult>),
}

/// How a tool call resolved, passed to the [`AfterHook`].
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub enum HookDisposition {
    /// The inner handler ran and returned `Ok`.
    InnerExecuted,
    /// The inner handler ran and returned `Err`.
    InnerErrored,
    /// The before-hook returned [`HookOutcome::Deny`].
    DeniedBefore,
    /// The before-hook returned [`HookOutcome::Replace`].
    ReplacedBefore,
    /// The result (from inner or replace) exceeded `max_result_bytes`
    /// and was substituted with a structured error.
    ResultTooLarge,
}

/// Async before-hook callback type.
///
/// Returns a [`HookOutcome`] controlling whether the inner handler runs.
/// The borrow of `ToolCallContext` is held for the duration of the
/// returned future, which avoids forcing implementations to clone the
/// context for every invocation.
pub type BeforeHook = Arc<
    dyn for<'a> Fn(&'a ToolCallContext) -> Pin<Box<dyn Future<Output = HookOutcome> + Send + 'a>>
        + Send
        + Sync
        + 'static,
>;

/// Async after-hook callback type.
///
/// Receives the call context, a [`HookDisposition`] describing how the
/// call resolved, and the approximate serialized result size in bytes
/// (`0` for `DeniedBefore` and `InnerErrored`).  Spawned via
/// `tokio::spawn`, so it must not assume it runs before the response is
/// flushed.
pub type AfterHook = Arc<
    dyn for<'a> Fn(
            &'a ToolCallContext,
            HookDisposition,
            usize,
        ) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>>
        + Send
        + Sync
        + 'static,
>;

/// Opt-in hooks applied by [`crate::tool_hooks::HookedHandler`].
#[allow(clippy::struct_field_names, reason = "before/after read naturally")]
#[derive(Clone, Default)]
#[non_exhaustive]
pub struct ToolHooks {
    /// Hard cap on serialized `CallToolResult` size in bytes.  When
    /// exceeded, the result is replaced with an `is_error=true` result
    /// carrying a `result_too_large` structured error.  `None` disables
    /// the cap.
    pub max_result_bytes: Option<usize>,
    /// Optional before-hook invoked after arg deserialization, before
    /// the wrapped handler is called.
    pub before: Option<BeforeHook>,
    /// Optional after-hook invoked once per normally-resolved call - that
    /// is, on the Deny / Replace / Ok / Err paths.  Spawned via
    /// `tokio::spawn` and never blocks the response path.
    ///
    /// **Not guaranteed under cancellation.**  If the `call_tool` future is
    /// dropped after a before-hook has run but before the call resolves,
    /// the paired after-hook is never spawned.  Do not use before/after
    /// pairing as a mandatory resource guard; make the after-hook
    /// idempotent or tolerant of missing closes (see [`crate::cancel`]).
    pub after: Option<AfterHook>,
}

impl ToolHooks {
    /// Construct an empty [`ToolHooks`] with no cap and no hooks.
    ///
    /// Use the `with_*` builder methods to populate fields; this avoids
    /// the `#[non_exhaustive]` restriction that prevents struct-literal
    /// construction from outside the crate.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the serialized result size cap in bytes.
    #[must_use]
    pub fn with_max_result_bytes(mut self, max: usize) -> Self {
        self.max_result_bytes = Some(max);
        self
    }

    /// Set the before-hook.
    #[must_use]
    pub fn with_before(mut self, before: BeforeHook) -> Self {
        self.before = Some(before);
        self
    }

    /// Set the after-hook.
    #[must_use]
    pub fn with_after(mut self, after: AfterHook) -> Self {
        self.after = Some(after);
        self
    }
}

const _HOOKED_HANDLER_DOC_ANCHOR: &str = "HookedHandler";

impl fmt::Debug for ToolHooks {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ToolHooks")
            .field("max_result_bytes", &self.max_result_bytes)
            .field("before", &self.before.as_ref().map(|_| "<fn>"))
            .field("after", &self.after.as_ref().map(|_| "<fn>"))
            .finish()
    }
}

/// `ServerHandler` wrapper that applies [`ToolHooks`].
#[derive(Clone)]
pub struct HookedHandler<H: ServerHandler> {
    inner: Arc<H>,
    hooks: Arc<ToolHooks>,
}

impl<H: ServerHandler> fmt::Debug for HookedHandler<H> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HookedHandler")
            .field("hooks", &self.hooks)
            .finish_non_exhaustive()
    }
}

/// Construct a [`crate::tool_hooks::HookedHandler`] from an inner handler and hooks.
///
/// Returning the wrapped handler is the entire point of this function;
/// dropping it on the floor would silently disable the supplied hooks.
#[must_use = "HookedHandler must be wired into a ServerHandler (e.g. via \
              `serve(..., || hooked)`) to take effect; dropping the returned \
              value silently disables the supplied hooks"]
pub fn with_hooks<H: ServerHandler>(inner: H, hooks: Arc<ToolHooks>) -> HookedHandler<H> {
    HookedHandler {
        inner: Arc::new(inner),
        hooks,
    }
}

impl<H: ServerHandler> HookedHandler<H> {
    /// Access the wrapped handler.
    #[must_use]
    pub fn inner(&self) -> &H {
        &self.inner
    }

    fn build_context(request: &CallToolRequestParams, req_id: Option<String>) -> ToolCallContext {
        ToolCallContext {
            tool_name: request.name.to_string(),
            arguments: request.arguments.clone().map(serde_json::Value::Object),
            identity: crate::rbac::current_identity(),
            role: crate::rbac::current_role(),
            sub: crate::rbac::current_sub(),
            request_id: req_id,
        }
    }

    /// Spawn the after-hook on the current Tokio runtime.  The future
    /// captures clones of `ctx` and the `Arc<AfterHook>` so it can run
    /// independently of the request task; panics inside the after-hook
    /// are caught by Tokio and never poison the response path.
    ///
    /// The spawned task is **instrumented** with the request span via
    /// [`tracing::Instrument`] and re-establishes the per-request RBAC
    /// task-locals (role, identity, token, sub) via
    /// [`crate::rbac::with_rbac_scope`]. Without this, after-hooks lose
    /// their parent span (breaking trace correlation) and observe
    /// `current_role()` / `current_identity()` as `None`.
    fn spawn_after(
        after: Option<&Arc<AfterHookHolder>>,
        ctx: ToolCallContext,
        disposition: HookDisposition,
        size: usize,
    ) {
        if let Some(after) = after {
            use tracing::Instrument;

            let after = Arc::clone(after);
            // Capture the request span before leaving the request task so
            // after-hook log lines are correlated with the originating call.
            let span = tracing::Span::current();
            // Snapshot RBAC task-locals; defaults are empty strings so the
            // re-established scope is a no-op when the request had no
            // authenticated identity (e.g. health checks, anonymous tools).
            let role = crate::rbac::current_role().unwrap_or_default();
            let identity = crate::rbac::current_identity().unwrap_or_default();
            let token = crate::rbac::current_token()
                .unwrap_or_else(|| secrecy::SecretString::from(String::new()));
            let sub = crate::rbac::current_sub().unwrap_or_default();
            tokio::spawn(
                async move {
                    crate::rbac::with_rbac_scope(role, identity, token, sub, async move {
                        let fut = (after.f)(&ctx, disposition, size);
                        fut.await;
                    })
                    .await;
                }
                .instrument(span),
            );
        }
    }
}

/// Internal newtype that owns the [`AfterHook`] so we can `Arc::clone`
/// the *holder* and let the spawned task borrow `ctx` for the lifetime
/// of the future without lifetime acrobatics in `tokio::spawn`.
struct AfterHookHolder {
    f: AfterHook,
}

/// Structured error body returned when a result exceeds `max_result_bytes`.
///
/// `actual` is `None` when the result could not be serialized, so its true
/// size is unknown. It is rendered as `"unknown"` rather than a fabricated
/// number -- operators read `actual_bytes` as a measurement.
fn too_large_result(limit: usize, actual: Option<usize>, tool: &str) -> CallToolResult {
    let actual_desc =
        actual.map_or_else(|| "an unmeasurable number of".to_owned(), |n| n.to_string());
    let body = serde_json::json!({
        "error": "result_too_large",
        "message": format!(
            "tool '{tool}' result of {actual_desc} bytes exceeds the configured \
             max_result_bytes={limit}; ask for a narrower query"
        ),
        "limit_bytes": limit,
        "actual_bytes": actual.map_or_else(
            || serde_json::Value::from("unknown"),
            serde_json::Value::from,
        ),
    });
    let mut r = CallToolResult::error(vec![ContentBlock::text(body.to_string())]);
    r.structured_content = None;
    r
}

/// Outcome of the `max_result_bytes` policy for a measured -- or
/// unmeasurable -- result.
#[derive(Debug, PartialEq, Eq)]
enum SizeVerdict {
    /// Within the cap, or no cap configured. Carries the measured size.
    Pass { size: usize },
    /// Over the cap, or unmeasurable while a cap is configured.
    Replace { limit: usize, actual: Option<usize> },
    /// Unmeasurable and no cap configured: nothing to enforce.
    PassUnmeasured,
}

/// Decide what the size cap does, given an optional size-measurement outcome.
const fn decide_size(size: Option<SizeMeasure>, max: Option<usize>) -> SizeVerdict {
    match size {
        Some(SizeMeasure::Exact(size)) => match max {
            Some(limit) if size > limit => SizeVerdict::Replace {
                limit,
                actual: Some(size),
            },
            Some(_) | None => SizeVerdict::Pass { size },
        },
        Some(SizeMeasure::Exceeded { limit }) => SizeVerdict::Replace {
            limit,
            actual: None,
        },
        None => match max {
            Some(limit) => SizeVerdict::Replace {
                limit,
                actual: None,
            },
            None => SizeVerdict::PassUnmeasured,
        },
    }
}

/// Apply the `max_result_bytes` cap to a result.  Returns the (possibly
/// replaced) result, the size used for accounting, and whether the cap
/// fired.
fn apply_size_cap(
    result: CallToolResult,
    max: Option<usize>,
    tool: &str,
) -> (CallToolResult, usize, bool) {
    let size = if max.is_some() {
        Some(serialized_size(&result, max))
    } else {
        None
    };
    match decide_size(size, max) {
        SizeVerdict::Pass { size } => (result, size, false),
        SizeVerdict::PassUnmeasured => (result, 0, false),
        SizeVerdict::Replace { limit, actual } => {
            tracing::warn!(
                tool = %tool,
                size_bytes = actual.unwrap_or_default(),
                size_measured = actual.is_some(),
                limit_bytes = limit,
                "tool result exceeds max_result_bytes; replacing with structured error"
            );
            let accounted = actual.unwrap_or_else(|| limit.saturating_add(1));
            (too_large_result(limit, actual, tool), accounted, true)
        }
    }
}

#[allow(
    deprecated,
    reason = "transparent ServerHandler delegation must include legacy logging/subscription methods until rmcp removes them"
)]
impl<H: ServerHandler> ServerHandler for HookedHandler<H> {
    async fn ping(&self, context: RequestContext<RoleServer>) -> Result<(), ErrorData> {
        self.inner.ping(context).await
    }

    fn get_info(&self) -> ServerInfo {
        self.inner.get_info()
    }

    async fn initialize(
        &self,
        request: InitializeRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<InitializeResult, ErrorData> {
        self.inner.initialize(request, context).await
    }

    async fn list_tools(
        &self,
        request: Option<PaginatedRequestParams>,
        context: RequestContext<RoleServer>,
    ) -> Result<ListToolsResult, ErrorData> {
        self.inner.list_tools(request, context).await
    }

    async fn complete(
        &self,
        request: CompleteRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<CompleteResult, ErrorData> {
        self.inner.complete(request, context).await
    }

    async fn set_level(
        &self,
        request: SetLevelRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<(), ErrorData> {
        self.inner.set_level(request, context).await
    }

    fn get_tool(&self, name: &str) -> Option<Tool> {
        self.inner.get_tool(name)
    }

    async fn list_prompts(
        &self,
        request: Option<PaginatedRequestParams>,
        context: RequestContext<RoleServer>,
    ) -> Result<ListPromptsResult, ErrorData> {
        self.inner.list_prompts(request, context).await
    }

    async fn get_prompt(
        &self,
        request: GetPromptRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<GetPromptResponse, ErrorData> {
        self.inner.get_prompt(request, context).await
    }

    async fn list_resources(
        &self,
        request: Option<PaginatedRequestParams>,
        context: RequestContext<RoleServer>,
    ) -> Result<ListResourcesResult, ErrorData> {
        self.inner.list_resources(request, context).await
    }

    async fn list_resource_templates(
        &self,
        request: Option<PaginatedRequestParams>,
        context: RequestContext<RoleServer>,
    ) -> Result<ListResourceTemplatesResult, ErrorData> {
        self.inner.list_resource_templates(request, context).await
    }

    async fn read_resource(
        &self,
        request: ReadResourceRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<ReadResourceResponse, ErrorData> {
        self.inner.read_resource(request, context).await
    }

    // NOT cancel-safe: this awaits consumer-supplied before-hooks and the
    // consumer's inner handler. After-hooks are dispatched only on the normal
    // Deny/Replace/Ok/Err paths, so a cancellation between the before-hook and
    // the response drops the paired after-hook -- an audit hook can therefore
    // record a started call that is never closed out. Consumers needing
    // guaranteed pairing should make the after-hook idempotent or run the tool
    // body detached (see `crate::cancel`).
    #[allow(
        clippy::wildcard_enum_match_arm,
        reason = "CallToolResponse is #[non_exhaustive]; the non-Complete MRTR variants (InputRequired/Task) are passed through unchanged"
    )]
    async fn call_tool(
        &self,
        request: CallToolRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<CallToolResponse, ErrorData> {
        let req_id = Some(format!("{:?}", context.id));
        let ctx = Self::build_context(&request, req_id);
        let max = self.hooks.max_result_bytes;
        let after_holder = self
            .hooks
            .after
            .as_ref()
            .map(|f| Arc::new(AfterHookHolder { f: Arc::clone(f) }));

        // Before hook: may Continue, Deny, or Replace.
        if let Some(before) = self.hooks.before.as_ref() {
            let outcome = before(&ctx).await;
            match outcome {
                HookOutcome::Continue => {}
                HookOutcome::Deny(err) => {
                    Self::spawn_after(after_holder.as_ref(), ctx, HookDisposition::DeniedBefore, 0);
                    return Err(err);
                }
                HookOutcome::Replace(boxed) => {
                    let (final_result, size, capped) = apply_size_cap(*boxed, max, &ctx.tool_name);
                    let disposition = if capped {
                        HookDisposition::ResultTooLarge
                    } else {
                        HookDisposition::ReplacedBefore
                    };
                    Self::spawn_after(after_holder.as_ref(), ctx, disposition, size);
                    return Ok(final_result.into());
                }
            }
        }

        // Inner handler.
        match self.inner.call_tool(request, context).await {
            // Completed tool result: subject to the size cap + after hook.
            Ok(CallToolResponse::Complete(result)) => {
                let (final_result, size, capped) = apply_size_cap(result, max, &ctx.tool_name);
                let disposition = if capped {
                    HookDisposition::ResultTooLarge
                } else {
                    HookDisposition::InnerExecuted
                };
                Self::spawn_after(after_holder.as_ref(), ctx, disposition, size);
                Ok(final_result.into())
            }
            // MRTR input-required / task responses (rmcp 3.0): no CallToolResult
            // to size-cap, so pass them through unchanged.
            Ok(other) => {
                Self::spawn_after(
                    after_holder.as_ref(),
                    ctx,
                    HookDisposition::InnerExecuted,
                    0,
                );
                Ok(other)
            }
            Err(e) => {
                Self::spawn_after(after_holder.as_ref(), ctx, HookDisposition::InnerErrored, 0);
                Err(e)
            }
        }
    }

    // rmcp 3.0 added task/subscription/discovery request handlers with defaults;
    // delegate them to `inner` so wrapping a handler that implements those stays
    // transparent (otherwise the default would shadow the inner implementation).
    fn supported_protocol_versions(&self) -> Cow<'static, [ProtocolVersion]> {
        self.inner.supported_protocol_versions()
    }

    async fn discover(
        &self,
        context: RequestContext<RoleServer>,
    ) -> Result<DiscoverResult, ErrorData> {
        self.inner.discover(context).await
    }

    fn accepted_subscription_filter(
        &self,
        requested: &SubscriptionFilter,
    ) -> Option<SubscriptionFilter> {
        self.inner.accepted_subscription_filter(requested)
    }

    async fn listen(&self, context: SubscriptionContext) -> Result<(), ErrorData> {
        self.inner.listen(context).await
    }

    async fn subscribe(
        &self,
        request: SubscribeRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<(), ErrorData> {
        self.inner.subscribe(request, context).await
    }

    async fn unsubscribe(
        &self,
        request: UnsubscribeRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<(), ErrorData> {
        self.inner.unsubscribe(request, context).await
    }

    async fn get_task(
        &self,
        request: GetTaskParams,
        context: RequestContext<RoleServer>,
    ) -> Result<GetTaskResult, ErrorData> {
        self.inner.get_task(request, context).await
    }

    async fn update_task(
        &self,
        request: UpdateTaskParams,
        context: RequestContext<RoleServer>,
    ) -> Result<(), ErrorData> {
        self.inner.update_task(request, context).await
    }

    async fn cancel_task(
        &self,
        request: CancelTaskParams,
        context: RequestContext<RoleServer>,
    ) -> Result<(), ErrorData> {
        self.inner.cancel_task(request, context).await
    }

    async fn on_custom_request(
        &self,
        request: CustomRequest,
        context: RequestContext<RoleServer>,
    ) -> Result<CustomResult, ErrorData> {
        self.inner.on_custom_request(request, context).await
    }

    async fn on_cancelled(
        &self,
        notification: CancelledNotificationParam,
        context: NotificationContext<RoleServer>,
    ) {
        self.inner.on_cancelled(notification, context).await;
    }

    async fn on_progress(
        &self,
        notification: ProgressNotificationParam,
        context: NotificationContext<RoleServer>,
    ) {
        self.inner.on_progress(notification, context).await;
    }

    async fn on_initialized(&self, context: NotificationContext<RoleServer>) {
        self.inner.on_initialized(context).await;
    }

    async fn on_roots_list_changed(&self, context: NotificationContext<RoleServer>) {
        self.inner.on_roots_list_changed(context).await;
    }

    async fn on_custom_notification(
        &self,
        notification: CustomNotification,
        context: NotificationContext<RoleServer>,
    ) {
        self.inner
            .on_custom_notification(notification, context)
            .await;
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct SizeLimitExceeded;

impl fmt::Display for SizeLimitExceeded {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("serialized result exceeded configured size cap")
    }
}

impl std::error::Error for SizeLimitExceeded {}

struct CountingWriter {
    bytes: usize,
    limit: Option<usize>,
}

impl CountingWriter {
    const fn unbounded() -> Self {
        Self {
            bytes: 0,
            limit: None,
        }
    }

    const fn bounded(limit: usize) -> Self {
        Self {
            bytes: 0,
            limit: Some(limit),
        }
    }
}

impl io::Write for CountingWriter {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let next = self.bytes.saturating_add(buf.len());
        if self.limit.is_some_and(|limit| next > limit) {
            Err(io::Error::other(SizeLimitExceeded))
        } else {
            self.bytes = next;
            Ok(buf.len())
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

/// Outcome of measuring serialized result size.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SizeMeasure {
    /// Exact serialized size in bytes.
    Exact(usize),
    /// Serialization crossed the configured size cap and stopped early.
    Exceeded { limit: usize },
}

/// Serialized byte length, or a deliberate cap-abort outcome.
fn serialized_size(result: &CallToolResult, max: Option<usize>) -> SizeMeasure {
    let mut writer = max.map_or_else(CountingWriter::unbounded, CountingWriter::bounded);
    match serde_json::to_writer(&mut writer, result) {
        Ok(()) => SizeMeasure::Exact(writer.bytes),
        Err(error) if error.io_error_kind() == Some(io::ErrorKind::Other) => {
            SizeMeasure::Exceeded {
                limit: max.unwrap_or(writer.bytes),
            }
        }
        Err(_error) => {
            // `CallToolResult` is made only of infallibly serializable fields
            // (`String`, `bool`, arrays/maps, and serde_json::Value`). There is
            // no inhabitable production value that can reach this branch.
            SizeMeasure::Exact(writer.bytes)
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    };

    #[allow(
        deprecated,
        reason = "delegation tests cover legacy logging/subscription methods"
    )]
    use rmcp::{
        ErrorData, RoleServer, ServerHandler,
        model::{
            CallToolRequestParams, CallToolResponse, CallToolResult, CancelledNotificationParam,
            CompleteRequestParams, CompleteResult, CompletionInfo, ContentBlock,
            CustomNotification, CustomRequest, CustomResult, ProgressNotificationParam, ServerInfo,
            SetLevelRequestParams, SubscribeRequestParams, UnsubscribeRequestParams,
        },
        service::RequestContext,
    };
    use serde_json::json;
    use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, DuplexStream};

    use super::*;

    type DelegationTransport = (
        DelegationProbe,
        BufReader<tokio::io::ReadHalf<DuplexStream>>,
        tokio::io::WriteHalf<DuplexStream>,
        rmcp::service::RunningService<RoleServer, HookedHandler<DelegationProbe>>,
    );

    /// Maintenance aid only: rmcp gives every `ServerHandler` method a default,
    /// so this count cannot guarantee compile-time completeness. It makes future
    /// upstream method additions visible in review alongside the delegation impl.
    const HOOKED_HANDLER_DELEGATED_METHODS: &[&str] = &[
        "ping",
        "initialize",
        "supported_protocol_versions",
        "discover",
        "complete",
        "set_level",
        "get_prompt",
        "list_prompts",
        "list_resources",
        "list_resource_templates",
        "read_resource",
        "accepted_subscription_filter",
        "listen",
        "subscribe",
        "unsubscribe",
        "call_tool",
        "list_tools",
        "get_tool",
        "on_custom_request",
        "on_cancelled",
        "on_progress",
        "on_initialized",
        "on_roots_list_changed",
        "on_custom_notification",
        "get_info",
        "get_task",
        "update_task",
        "cancel_task",
    ];

    #[derive(Clone, Default)]
    struct CapturedLogs(Arc<std::sync::Mutex<Vec<u8>>>);

    impl CapturedLogs {
        fn contents(&self) -> String {
            let bytes = self.0.lock().map(|guard| guard.clone()).unwrap_or_default();
            String::from_utf8(bytes).unwrap_or_default()
        }
    }

    struct CapturedLogsWriter(Arc<std::sync::Mutex<Vec<u8>>>);

    impl io::Write for CapturedLogsWriter {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            if let Ok(mut guard) = self.0.lock() {
                guard.extend_from_slice(buf);
            }
            Ok(buf.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for CapturedLogs {
        type Writer = CapturedLogsWriter;

        fn make_writer(&'a self) -> Self::Writer {
            CapturedLogsWriter(Arc::clone(&self.0))
        }
    }

    /// Minimal in-process `ServerHandler` for tests.
    #[derive(Clone, Default)]
    struct TestHandler {
        /// When Some, `call_tool` returns a body of this many 'x' bytes.
        body_bytes: Option<usize>,
    }

    impl ServerHandler for TestHandler {
        fn get_info(&self) -> ServerInfo {
            ServerInfo::default()
        }

        #[allow(
            clippy::unused_async_trait_impl,
            reason = "async is mandated by the rmcp ServerHandler trait signature; this test handler does not await"
        )]
        async fn call_tool(
            &self,
            _request: CallToolRequestParams,
            _context: RequestContext<RoleServer>,
        ) -> Result<CallToolResponse, ErrorData> {
            let body = "x".repeat(self.body_bytes.unwrap_or(4));
            Ok(CallToolResult::success(vec![ContentBlock::text(body)]).into())
        }
    }

    #[derive(Clone, Default)]
    struct DelegationProbe {
        seen: Arc<std::sync::Mutex<Vec<&'static str>>>,
        notify: Arc<tokio::sync::Notify>,
    }

    impl DelegationProbe {
        fn record(&self, method: &'static str) {
            if let Ok(mut seen) = self.seen.lock() {
                seen.push(method);
            }
            self.notify.notify_waiters();
        }

        fn seen(&self) -> Vec<&'static str> {
            self.seen
                .lock()
                .map(|seen| seen.clone())
                .unwrap_or_default()
        }

        async fn wait_for_seen_count(&self, count: usize) {
            tokio::time::timeout(std::time::Duration::from_secs(1), async {
                while self.seen().len() < count {
                    self.notify.notified().await;
                }
            })
            .await
            .expect("delegated handler methods should be observed");
        }
    }

    #[allow(
        clippy::unused_async_trait_impl,
        deprecated,
        reason = "delegation tests cover rmcp async trait methods whose probe implementations return immediately"
    )]
    impl ServerHandler for DelegationProbe {
        fn get_info(&self) -> ServerInfo {
            ServerInfo::default()
        }

        async fn ping(&self, _context: RequestContext<RoleServer>) -> Result<(), ErrorData> {
            self.record("ping");
            Ok(())
        }

        async fn complete(
            &self,
            _request: CompleteRequestParams,
            _context: RequestContext<RoleServer>,
        ) -> Result<CompleteResult, ErrorData> {
            self.record("complete");
            let completion = CompletionInfo::with_all_values(vec!["delegated".to_owned()])
                .expect("single completion is within rmcp max");
            Ok(CompleteResult::new(completion))
        }

        async fn set_level(
            &self,
            _request: SetLevelRequestParams,
            _context: RequestContext<RoleServer>,
        ) -> Result<(), ErrorData> {
            self.record("set_level");
            Ok(())
        }

        async fn subscribe(
            &self,
            _request: SubscribeRequestParams,
            _context: RequestContext<RoleServer>,
        ) -> Result<(), ErrorData> {
            self.record("subscribe");
            Ok(())
        }

        async fn unsubscribe(
            &self,
            _request: UnsubscribeRequestParams,
            _context: RequestContext<RoleServer>,
        ) -> Result<(), ErrorData> {
            self.record("unsubscribe");
            Ok(())
        }

        async fn call_tool(
            &self,
            _request: CallToolRequestParams,
            _context: RequestContext<RoleServer>,
        ) -> Result<CallToolResponse, ErrorData> {
            self.record("call_tool");
            Ok(CallToolResult::success(vec![ContentBlock::text("inner")]).into())
        }

        async fn on_custom_request(
            &self,
            _request: CustomRequest,
            _context: RequestContext<RoleServer>,
        ) -> Result<CustomResult, ErrorData> {
            self.record("on_custom_request");
            Ok(CustomResult::new(json!({ "delegated": true })))
        }

        async fn on_cancelled(
            &self,
            _notification: CancelledNotificationParam,
            _context: NotificationContext<RoleServer>,
        ) {
            self.record("on_cancelled");
        }

        async fn on_progress(
            &self,
            _notification: ProgressNotificationParam,
            _context: NotificationContext<RoleServer>,
        ) {
            self.record("on_progress");
        }

        async fn on_initialized(&self, _context: NotificationContext<RoleServer>) {
            self.record("on_initialized");
        }

        async fn on_roots_list_changed(&self, _context: NotificationContext<RoleServer>) {
            self.record("on_roots_list_changed");
        }

        async fn on_custom_notification(
            &self,
            _notification: CustomNotification,
            _context: NotificationContext<RoleServer>,
        ) {
            self.record("on_custom_notification");
        }
    }

    fn delegation_transport(probe: DelegationProbe, hooks: Arc<ToolHooks>) -> DelegationTransport {
        let (client, server) = tokio::io::duplex(16 * 1024);
        let (client_read, client_write) = tokio::io::split(client);
        let service = rmcp::service::serve_directly::<RoleServer, _, _, io::Error, _>(
            with_hooks(probe.clone(), hooks),
            server,
            None,
        );
        (probe, BufReader::new(client_read), client_write, service)
    }

    async fn send_json_rpc(
        writer: &mut tokio::io::WriteHalf<DuplexStream>,
        reader: &mut BufReader<tokio::io::ReadHalf<DuplexStream>>,
        request: serde_json::Value,
    ) -> serde_json::Value {
        writer
            .write_all(request.to_string().as_bytes())
            .await
            .expect("write request");
        writer.write_all(b"\n").await.expect("write newline");
        writer.flush().await.expect("flush request");

        let mut line = String::new();
        reader.read_line(&mut line).await.expect("read response");
        serde_json::from_str(&line).expect("response is JSON")
    }

    async fn send_notification(
        writer: &mut tokio::io::WriteHalf<DuplexStream>,
        notification: serde_json::Value,
    ) {
        writer
            .write_all(notification.to_string().as_bytes())
            .await
            .expect("write notification");
        writer.write_all(b"\n").await.expect("write newline");
        writer.flush().await.expect("flush notification");
    }

    #[test]
    fn hooked_handler_delegation_count_is_maintenance_aid() {
        assert_eq!(
            HOOKED_HANDLER_DELEGATED_METHODS.len(),
            28,
            "maintenance aid only: update this list and the HookedHandler impl when rmcp adds ServerHandler methods"
        );
    }

    #[tokio::test]
    async fn hooked_handler_delegates_ping() {
        let (probe, mut reader, mut writer, _service) =
            delegation_transport(DelegationProbe::default(), Arc::new(ToolHooks::new()));

        let response = send_json_rpc(
            &mut writer,
            &mut reader,
            json!({ "jsonrpc": "2.0", "id": 1, "method": "ping" }),
        )
        .await;

        assert_eq!(response["result"], json!({}));
        assert_eq!(probe.seen(), vec!["ping"]);
    }

    #[tokio::test]
    async fn hooked_handler_delegates_notifications() {
        let (probe, _reader, mut writer, _service) =
            delegation_transport(DelegationProbe::default(), Arc::new(ToolHooks::new()));

        send_notification(
            &mut writer,
            json!({
                "jsonrpc": "2.0",
                "method": "notifications/cancelled",
                "params": { "requestId": 1, "reason": "test" }
            }),
        )
        .await;
        send_notification(
            &mut writer,
            json!({
                "jsonrpc": "2.0",
                "method": "notifications/progress",
                "params": { "progressToken": 1, "progress": 0.5 }
            }),
        )
        .await;
        send_notification(
            &mut writer,
            json!({ "jsonrpc": "2.0", "method": "notifications/initialized" }),
        )
        .await;
        send_notification(
            &mut writer,
            json!({ "jsonrpc": "2.0", "method": "notifications/roots/list_changed" }),
        )
        .await;
        send_notification(
            &mut writer,
            json!({ "jsonrpc": "2.0", "method": "notifications/custom/probe" }),
        )
        .await;

        probe.wait_for_seen_count(5).await;
        assert_eq!(
            probe.seen(),
            vec![
                "on_cancelled",
                "on_progress",
                "on_initialized",
                "on_roots_list_changed",
                "on_custom_notification"
            ]
        );
    }

    #[tokio::test]
    #[allow(
        deprecated,
        reason = "set_level is deprecated by rmcp but must delegate"
    )]
    async fn hooked_handler_delegates_completion_and_level() {
        let (probe, mut reader, mut writer, _service) =
            delegation_transport(DelegationProbe::default(), Arc::new(ToolHooks::new()));

        let completion = send_json_rpc(
            &mut writer,
            &mut reader,
            json!({
                "jsonrpc": "2.0",
                "id": 1,
                "method": "completion/complete",
                "params": {
                    "ref": { "type": "ref/prompt", "name": "prompt" },
                    "argument": { "name": "arg", "value": "de" }
                }
            }),
        )
        .await;
        let level = send_json_rpc(
            &mut writer,
            &mut reader,
            json!({
                "jsonrpc": "2.0",
                "id": 2,
                "method": "logging/setLevel",
                "params": { "level": "debug" }
            }),
        )
        .await;

        assert_eq!(
            completion["result"]["completion"]["values"],
            json!(["delegated"])
        );
        assert_eq!(level["result"], json!({}));
        assert_eq!(probe.seen(), vec!["complete", "set_level"]);
    }

    #[tokio::test]
    #[allow(
        deprecated,
        reason = "subscribe/unsubscribe are deprecated by rmcp but must delegate"
    )]
    async fn hooked_handler_delegates_subscriptions() {
        let (probe, mut reader, mut writer, _service) =
            delegation_transport(DelegationProbe::default(), Arc::new(ToolHooks::new()));

        let subscribe = send_json_rpc(
            &mut writer,
            &mut reader,
            json!({
                "jsonrpc": "2.0",
                "id": 1,
                "method": "resources/subscribe",
                "params": { "uri": "file:///tmp/a" }
            }),
        )
        .await;
        let unsubscribe = send_json_rpc(
            &mut writer,
            &mut reader,
            json!({
                "jsonrpc": "2.0",
                "id": 2,
                "method": "resources/unsubscribe",
                "params": { "uri": "file:///tmp/a" }
            }),
        )
        .await;

        assert_eq!(subscribe["result"], json!({}));
        assert_eq!(unsubscribe["result"], json!({}));
        assert_eq!(probe.seen(), vec!["subscribe", "unsubscribe"]);
    }

    #[tokio::test]
    async fn hooked_handler_delegates_custom_request() {
        let (probe, mut reader, mut writer, _service) =
            delegation_transport(DelegationProbe::default(), Arc::new(ToolHooks::new()));

        let response = send_json_rpc(
            &mut writer,
            &mut reader,
            json!({
                "jsonrpc": "2.0",
                "id": 1,
                "method": "requests/custom/probe",
                "params": { "x": true }
            }),
        )
        .await;

        assert_eq!(response["result"], json!({ "delegated": true }));
        assert_eq!(probe.seen(), vec!["on_custom_request"]);
    }

    #[tokio::test]
    async fn hooked_handler_still_applies_hooks_to_call_tool() {
        let before_count = Arc::new(AtomicUsize::new(0));
        let before_seen = Arc::clone(&before_count);
        let before: BeforeHook = Arc::new(move |_ctx| {
            let before_seen = Arc::clone(&before_seen);
            Box::pin(async move {
                before_seen.fetch_add(1, Ordering::Relaxed);
                HookOutcome::Continue
            })
        });
        let after_count = Arc::new(AtomicUsize::new(0));
        let after_seen = Arc::clone(&after_count);
        let after_notify = Arc::new(tokio::sync::Notify::new());
        let after_notify_seen = Arc::clone(&after_notify);
        let after: AfterHook = Arc::new(move |_ctx, _disp, _size| {
            let after_seen = Arc::clone(&after_seen);
            let after_notify_seen = Arc::clone(&after_notify_seen);
            Box::pin(async move {
                after_seen.fetch_add(1, Ordering::Relaxed);
                after_notify_seen.notify_waiters();
            })
        });
        let hooks = Arc::new(
            ToolHooks::new()
                .with_before(before)
                .with_after(after)
                .with_max_result_bytes(1024),
        );
        let (probe, mut reader, mut writer, _service) =
            delegation_transport(DelegationProbe::default(), hooks);

        let response = send_json_rpc(
            &mut writer,
            &mut reader,
            json!({
                "jsonrpc": "2.0",
                "id": 1,
                "method": "tools/call",
                "params": { "name": "probe", "arguments": {} }
            }),
        )
        .await;

        tokio::time::timeout(std::time::Duration::from_secs(1), async {
            while after_count.load(Ordering::Relaxed) == 0 {
                after_notify.notified().await;
            }
        })
        .await
        .expect("after hook should run");
        assert_eq!(response["result"]["content"][0]["text"], "inner");
        assert_eq!(probe.seen(), vec!["call_tool"]);
        assert_eq!(before_count.load(Ordering::Relaxed), 1);
        assert_eq!(after_count.load(Ordering::Relaxed), 1);
    }

    fn ctx(name: &str) -> ToolCallContext {
        ToolCallContext {
            tool_name: name.to_owned(),
            arguments: None,
            identity: None,
            role: None,
            sub: None,
            request_id: None,
        }
    }

    fn sensitive_ctx() -> ToolCallContext {
        ToolCallContext {
            tool_name: "safe-tool-name".to_owned(),
            arguments: Some(serde_json::json!({ "password": "argument-secret" })),
            identity: Some("identity-secret".to_owned()),
            role: Some("role-secret".to_owned()),
            sub: Some("sub-secret".to_owned()),
            request_id: Some("request-id-visible".to_owned()),
        }
    }

    #[test]
    fn tool_call_context_debug_redacts_sensitive_fields_by_default() {
        let _guard = crate::diagnostics::ExposureTestGuard::acquire();
        crate::diagnostics::set_diagnostic_exposure(
            &crate::diagnostics::DiagnosticExposure::default(),
        );

        let rendered = format!("{:?}", sensitive_ctx());

        assert!(rendered.contains("safe-tool-name"));
        assert!(rendered.contains("request-id-visible"));
        assert!(rendered.contains("[REDACTED]"));
        for secret in [
            "argument-secret",
            "identity-secret",
            "role-secret",
            "sub-secret",
        ] {
            assert!(
                !rendered.contains(secret),
                "ToolCallContext Debug must not contain {secret}: {rendered}"
            );
        }
    }

    #[test]
    fn tool_call_context_debug_can_show_sensitive_fields_when_enabled() {
        let _guard = crate::diagnostics::ExposureTestGuard::acquire();
        crate::diagnostics::set_diagnostic_exposure(&crate::diagnostics::DiagnosticExposure {
            tool_call_arguments: true,
            ..crate::diagnostics::DiagnosticExposure::default()
        });

        let rendered = format!("{:?}", sensitive_ctx());

        for secret in [
            "argument-secret",
            "identity-secret",
            "role-secret",
            "sub-secret",
        ] {
            assert!(
                rendered.contains(secret),
                "ToolCallContext Debug must contain {secret} when enabled: {rendered}"
            );
        }
    }

    #[tokio::test]
    async fn size_cap_replaces_oversized_result() {
        let inner = TestHandler {
            body_bytes: Some(8_192),
        };
        let hooks = Arc::new(ToolHooks {
            max_result_bytes: Some(256),
            before: None,
            after: None,
        });
        let hooked = with_hooks(inner, hooks);

        let small = CallToolResult::success(vec![ContentBlock::text("ok".to_owned())]);
        assert!(exact_size(&small) < 256);

        let big = CallToolResult::success(vec![ContentBlock::text("x".repeat(8_192))]);
        let size = exact_size(&big);
        assert!(size > 256);

        let (replaced, accounted, capped) = apply_size_cap(big, Some(256), "whatever");
        assert!(capped);
        assert_eq!(accounted, 257);
        assert_eq!(replaced.is_error, Some(true));
        assert!(matches!(
            replaced.content.first(),
            Some(rmcp::model::ContentBlock::Text(t)) if t.text.contains("result_too_large")
        ));

        // Compile-check that HookedHandler instantiates with the test inner.
        let _ = hooked;
    }

    fn exact_size(result: &CallToolResult) -> usize {
        match serialized_size(result, None) {
            SizeMeasure::Exact(size) => size,
            SizeMeasure::Exceeded { limit } => {
                panic!("unbounded measurement exceeded impossible limit {limit}");
            }
        }
    }

    #[test]
    fn serialized_size_under_cap_is_exact() {
        let result = CallToolResult::success(vec![ContentBlock::text("ok".to_owned())]);
        let exact = serde_json::to_vec(&result).unwrap().len();

        let measured = serialized_size(&result, Some(exact));

        assert_eq!(measured, SizeMeasure::Exact(exact));
    }

    #[test]
    fn serialized_size_over_cap_stops_with_exceeded() {
        let result = CallToolResult::success(vec![ContentBlock::text("x".repeat(8_192))]);

        let measured = serialized_size(&result, Some(256));

        assert_eq!(measured, SizeMeasure::Exceeded { limit: 256 });
    }

    #[test]
    fn over_cap_replacement_does_not_log_serialization_failure() {
        let logs = CapturedLogs::default();
        let subscriber = tracing_subscriber::fmt()
            .with_max_level(tracing::Level::TRACE)
            .with_writer(logs.clone())
            .with_ansi(false)
            .without_time()
            .finish();
        let _guard = tracing::subscriber::set_default(subscriber);
        let result = CallToolResult::success(vec![ContentBlock::text("x".repeat(8_192))]);

        let (_final_result, accounted, capped) = apply_size_cap(result, Some(256), "big_tool");

        assert!(capped);
        assert_eq!(accounted, 257);
        assert!(
            logs.contents()
                .contains("tool result exceeds max_result_bytes")
        );
        assert!(
            !logs.contents().contains("failed to serialize"),
            "cap-abort must not be logged as serialization failure: {}",
            logs.contents()
        );
    }

    #[test]
    fn disabled_result_cap_skips_measurement() {
        let result = CallToolResult::success(vec![ContentBlock::text("x".repeat(8_192))]);

        let (_final_result, accounted, capped) = apply_size_cap(result, None, "uncapped_tool");

        assert!(!capped);
        assert_eq!(accounted, 0);
    }

    #[tokio::test]
    async fn before_hook_deny_builds_error() {
        let counter = Arc::new(AtomicUsize::new(0));
        let c = Arc::clone(&counter);
        let before: BeforeHook = Arc::new(move |ctx_ref| {
            let c = Arc::clone(&c);
            let name = ctx_ref.tool_name.clone();
            Box::pin(async move {
                c.fetch_add(1, Ordering::Relaxed);
                if name == "forbidden" {
                    HookOutcome::Deny(ErrorData::invalid_request("nope", None))
                } else {
                    HookOutcome::Continue
                }
            })
        });

        let hooks = Arc::new(ToolHooks {
            max_result_bytes: None,
            before: Some(before),
            after: None,
        });
        let hooked = with_hooks(TestHandler::default(), hooks);

        let bad_ctx = ctx("forbidden");
        let before_fn = hooked.hooks.before.as_ref().unwrap();
        let outcome = before_fn(&bad_ctx).await;
        assert!(matches!(outcome, HookOutcome::Deny(_)));
        assert_eq!(counter.load(Ordering::Relaxed), 1);

        let ok_ctx = ctx("allowed");
        let outcome2 = before_fn(&ok_ctx).await;
        assert!(matches!(outcome2, HookOutcome::Continue));
        assert_eq!(counter.load(Ordering::Relaxed), 2);
    }

    #[test]
    fn too_large_result_mentions_limit_and_actual() {
        let r = too_large_result(100, Some(500), "my_tool");
        let body = serde_json::to_string(&r).unwrap();
        assert!(body.contains("result_too_large"));
        assert!(body.contains("my_tool"));
        assert!(body.contains("100"));
        assert!(body.contains("500"));
    }

    #[test]
    fn decide_size_truth_table() {
        assert_eq!(
            decide_size(Some(SizeMeasure::Exact(10)), Some(100)),
            SizeVerdict::Pass { size: 10 }
        );
        assert_eq!(
            decide_size(Some(SizeMeasure::Exact(100)), Some(100)),
            SizeVerdict::Pass { size: 100 },
            "cap is inclusive: size == limit passes"
        );
        assert_eq!(
            decide_size(Some(SizeMeasure::Exact(101)), Some(100)),
            SizeVerdict::Replace {
                limit: 100,
                actual: Some(101)
            }
        );
        assert_eq!(
            decide_size(Some(SizeMeasure::Exact(999)), None),
            SizeVerdict::Pass { size: 999 }
        );
        assert_eq!(
            decide_size(None, Some(100)),
            SizeVerdict::Replace {
                limit: 100,
                actual: None
            },
            "unmeasurable result must fail closed when a cap is configured"
        );
        assert_eq!(decide_size(None, None), SizeVerdict::PassUnmeasured);
        assert_eq!(
            decide_size(Some(SizeMeasure::Exceeded { limit: 100 }), Some(100)),
            SizeVerdict::Replace {
                limit: 100,
                actual: None
            },
            "cap-abort is not an exact measurement"
        );
    }

    #[test]
    fn too_large_result_does_not_fabricate_a_size_when_unmeasurable() {
        let r = too_large_result(100, None, "my_tool");
        let body = serde_json::to_string(&r).unwrap();
        assert!(body.contains("result_too_large"));
        assert!(body.contains("unknown"));
        assert!(
            !body.contains("101"),
            "the over-limit accounting sentinel must not leak into the client payload"
        );
    }

    #[tokio::test]
    async fn replace_outcome_skips_inner_and_returns_payload() {
        // Returning Replace from before-hook must yield the supplied
        // CallToolResult directly, with no need for the inner handler.
        let before: BeforeHook = Arc::new(|_ctx| {
            Box::pin(async {
                HookOutcome::Replace(Box::new(CallToolResult::success(vec![ContentBlock::text(
                    "from-replace".to_owned(),
                )])))
            })
        });
        let hooks = Arc::new(ToolHooks {
            max_result_bytes: None,
            before: Some(before),
            after: None,
        });
        let _hooked = with_hooks(TestHandler::default(), Arc::clone(&hooks));

        // Exercise the before-hook closure + apply_size_cap helper directly,
        // matching the established test pattern in this module.
        let outcome = (hooks.before.as_ref().unwrap())(&ctx("any")).await;
        let HookOutcome::Replace(boxed) = outcome else {
            panic!("expected HookOutcome::Replace");
        };
        let (result, size, capped) = apply_size_cap(*boxed, None, "any");
        assert!(!capped);
        assert_eq!(size, 0);
        assert!(!result.is_error.unwrap_or(false));
        assert!(matches!(
            result.content.first(),
            Some(rmcp::model::ContentBlock::Text(t)) if t.text == "from-replace"
        ));
    }

    #[tokio::test]
    async fn replace_outcome_subject_to_size_cap() {
        // A Replace payload that exceeds max_result_bytes must be rewritten
        // to result_too_large just like an inner-handler result would be,
        // and the disposition must reflect ResultTooLarge.
        let huge = CallToolResult::success(vec![ContentBlock::text("y".repeat(8_192))]);
        let huge_size = serde_json::to_vec(&huge).unwrap().len();
        assert!(huge_size > 256);

        let (final_result, accounted, capped) = apply_size_cap(huge, Some(256), "replaced_tool");
        assert!(capped);
        assert_eq!(accounted, 257);
        assert_eq!(final_result.is_error, Some(true));
        assert!(matches!(
            final_result.content.first(),
            Some(rmcp::model::ContentBlock::Text(t)) if t.text.contains("result_too_large")
        ));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn after_hook_fires_exactly_once_via_spawn() {
        // spawn_after must enqueue the after-hook exactly one time per
        // invocation and never block the caller; we wait for the spawned
        // task to run by polling the counter with a short timeout.
        let counter = Arc::new(AtomicUsize::new(0));
        let c = Arc::clone(&counter);
        let after: AfterHook = Arc::new(move |_ctx, _disp, _size| {
            let c = Arc::clone(&c);
            Box::pin(async move {
                c.fetch_add(1, Ordering::Relaxed);
            })
        });
        let holder = Arc::new(AfterHookHolder { f: after });

        HookedHandler::<TestHandler>::spawn_after(
            Some(&holder),
            ctx("t"),
            HookDisposition::InnerExecuted,
            42,
        );

        // Wait up to 1s for the spawned task to run.
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(1);
        while counter.load(Ordering::Relaxed) == 0 && std::time::Instant::now() < deadline {
            tokio::task::yield_now().await;
            tokio::time::sleep(std::time::Duration::from_millis(5)).await;
        }
        assert_eq!(counter.load(Ordering::Relaxed), 1);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn after_hook_panic_is_isolated_from_response_path() {
        // A panicking after-hook must not affect the request task.  We
        // spawn a panicking after-hook and then verify the current task
        // can still complete an unrelated future to completion.
        let after: AfterHook = Arc::new(|_ctx, _disp, _size| {
            Box::pin(async {
                panic!("intentional panic in after-hook");
            })
        });
        let holder = Arc::new(AfterHookHolder { f: after });

        HookedHandler::<TestHandler>::spawn_after(
            Some(&holder),
            ctx("boom"),
            HookDisposition::InnerExecuted,
            0,
        );

        // Give Tokio a chance to run + abort the panicking task, then
        // confirm we're still alive and the runtime is healthy.
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        let still_alive = tokio::spawn(async { 1_u32 + 2 }).await.unwrap();
        assert_eq!(still_alive, 3);
    }
}