fastmcp-server 0.7.0

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

use std::collections::HashMap;
use std::time::Duration;

use asupersync::Cx;
use fastmcp_core::{McpContext, McpOutcome, McpResult, Outcome};
use fastmcp_protocol::common_types::{OpenMetadata, RawIcon};
use fastmcp_protocol::{
    CompleteResult, Content, FinalCallToolResult, FinalTool, Icon, Tool, ToolAnnotations,
};

use crate::bidirectional::MrtrCompletedInputs;
use crate::handler::{
    BoxFuture, BoxedToolHandler, FinalToolOutcome, FinalToolSchemaAuthority, ToolErrorKind,
    ToolHandler, UpstreamFinalToolSchemaRegistration,
};

/// Sentinel value for unset optional fields.
#[derive(Debug, Clone, Copy, Default)]
pub struct NotSet;

/// Transformation rules for a single argument.
///
/// Use the builder methods to specify which aspects of the argument to transform.
/// Any field left as `None` will inherit from the original argument.
#[derive(Debug, Clone, Default)]
pub struct ArgTransform {
    /// New name for the argument.
    pub name: Option<String>,
    /// New description for the argument.
    pub description: Option<String>,
    /// Default value (as JSON) for the argument.
    pub default: Option<serde_json::Value>,
    /// Whether to hide this argument from the schema.
    /// Hidden arguments must have a default value.
    pub hide: bool,
    /// Override the required status.
    /// Only `Some(true)` is meaningful (to make optional → required).
    pub required: Option<bool>,
    /// New type annotation for the argument (as JSON Schema).
    pub type_schema: Option<serde_json::Value>,
}

impl ArgTransform {
    /// Creates a new empty argument transform.
    #[must_use]
    pub fn new() -> Self {
        <Self as Default>::default()
    }

    /// Sets the new name for this argument.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Sets the new description for this argument.
    #[must_use]
    pub fn description(mut self, desc: impl Into<String>) -> Self {
        self.description = Some(desc.into());
        self
    }

    /// Sets the default value for this argument.
    #[must_use]
    pub fn default(mut self, value: impl Into<serde_json::Value>) -> Self {
        self.default = Some(value.into());
        self
    }

    /// Sets a string default value.
    #[must_use]
    pub fn default_str(self, value: impl Into<String>) -> Self {
        self.default(serde_json::Value::String(value.into()))
    }

    /// Sets an integer default value.
    #[must_use]
    pub fn default_int(self, value: i64) -> Self {
        self.default(serde_json::Value::Number(value.into()))
    }

    /// Sets a boolean default value.
    #[must_use]
    pub fn default_bool(self, value: bool) -> Self {
        self.default(serde_json::Value::Bool(value))
    }

    /// Hides this argument from the schema.
    ///
    /// Hidden arguments are not exposed to the LLM but must have a default
    /// value that will be used when the tool is called.
    #[must_use]
    pub fn hide(mut self) -> Self {
        self.hide = true;
        self
    }

    /// Makes this argument required (even if it was optional).
    #[must_use]
    pub fn required(mut self) -> Self {
        self.required = Some(true);
        self
    }

    /// Sets the JSON Schema type for this argument.
    #[must_use]
    pub fn type_schema(mut self, schema: serde_json::Value) -> Self {
        self.type_schema = Some(schema);
        self
    }

    /// Creates a transform that drops (hides) this argument with a default value.
    #[must_use]
    pub fn drop_with_default(value: impl Into<serde_json::Value>) -> Self {
        Self::new().default(value).hide()
    }
}

/// A transformed tool that wraps another tool and applies transformations.
///
/// Transformations can include:
/// - Renaming the tool
/// - Modifying the description
/// - Transforming arguments (rename, add defaults, hide, etc.)
/// - Applying a custom transformation function
pub struct TransformedTool {
    /// The underlying tool being transformed.
    parent: BoxedToolHandler,
    /// Transformed tool definition.
    definition: Tool,
    /// Argument transformations (keyed by original argument name).
    arg_transforms: HashMap<String, ArgTransform>,
    /// Mapping from new arg names to original arg names.
    name_mapping: HashMap<String, String>,
}

impl TransformedTool {
    /// Creates a builder for transforming an existing tool.
    pub fn from_tool<H: ToolHandler + 'static>(tool: H) -> TransformedToolBuilder {
        TransformedToolBuilder::new(Box::new(tool))
    }

    /// Creates a builder from a boxed tool handler.
    pub fn from_boxed(tool: BoxedToolHandler) -> TransformedToolBuilder {
        TransformedToolBuilder::new(tool)
    }

    /// Returns the parent tool's definition.
    #[must_use]
    pub fn parent_definition(&self) -> Tool {
        self.parent.definition()
    }

    /// Returns the argument transforms.
    #[must_use]
    pub fn arg_transforms(&self) -> &HashMap<String, ArgTransform> {
        &self.arg_transforms
    }

    /// Transforms the incoming arguments (with new names) to the original format.
    fn transform_arguments(&self, arguments: serde_json::Value) -> McpResult<serde_json::Value> {
        let mut args = match arguments {
            serde_json::Value::Object(map) => map,
            serde_json::Value::Null => serde_json::Map::new(),
            _ => {
                return Err(fastmcp_core::McpError::invalid_params(
                    "Arguments must be an object",
                ));
            }
        };

        let mut result = serde_json::Map::new();

        // Apply transformations
        for (original_name, transform) in &self.arg_transforms {
            let new_name = transform.name.as_ref().unwrap_or(original_name);

            if transform.hide {
                // Hidden arguments are server-owned. A caller-supplied value
                // under the published name or the original name must not
                // override the configured default, and cannot substitute for
                // a missing one.
                args.remove(new_name);
                args.remove(original_name);
                if let Some(default) = &transform.default {
                    result.insert(original_name.clone(), default.clone());
                    continue;
                }
                return Err(fastmcp_core::McpError::invalid_params(format!(
                    "Hidden argument '{original_name}' requires a default value"
                )));
            }

            if let Some(value) = args.remove(new_name) {
                result.insert(original_name.clone(), value);
            } else if let Some(default) = &transform.default {
                result.insert(original_name.clone(), default.clone());
            }
            // A caller who still sends the original name after a rename must
            // not overwrite the mapped value in the leftover-args pass.
            if new_name != original_name {
                args.remove(original_name);
            }
        }

        // Pass through any remaining arguments that weren't transformed
        for (key, value) in args {
            // Check if this key maps back to an original name
            if let Some(original) = self.name_mapping.get(&key) {
                result.insert(original.clone(), value);
            } else {
                result.insert(key, value);
            }
        }

        Ok(serde_json::Value::Object(result))
    }
}

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

impl ToolHandler for TransformedTool {
    fn definition(&self) -> Tool {
        self.definition.clone()
    }

    fn icon(&self) -> Option<&Icon> {
        self.parent.icon()
    }

    fn version(&self) -> Option<&str> {
        self.parent.version()
    }

    fn tags(&self) -> &[String] {
        self.parent.tags()
    }

    fn annotations(&self) -> Option<&ToolAnnotations> {
        self.parent.annotations()
    }

    fn output_schema(&self) -> Option<serde_json::Value> {
        self.parent.output_schema()
    }

    fn final_title(&self) -> Option<&str> {
        self.parent.final_title()
    }

    fn final_icons(&self) -> Option<&[RawIcon]> {
        self.parent.final_icons()
    }

    fn final_metadata(&self) -> Option<&OpenMetadata> {
        self.parent.final_metadata()
    }

    fn final_definition(&self) -> Option<FinalTool> {
        let mut definition = self.parent.final_definition()?;
        definition.name.clone_from(&self.definition.name);
        definition
            .description
            .clone_from(&self.definition.description);
        definition.input_schema =
            transform_input_schema(&self.arg_transforms, &definition.input_schema);
        Some(definition)
    }

    fn final_tool_schema_authority(&self) -> FinalToolSchemaAuthority {
        self.parent.final_tool_schema_authority()
    }

    fn upstream_final_tool_schema_registration(
        &self,
    ) -> Option<UpstreamFinalToolSchemaRegistration> {
        self.parent.upstream_final_tool_schema_registration()
    }

    fn final_tool_error_structured_content(
        &self,
        kind: ToolErrorKind,
    ) -> Option<serde_json::Value> {
        self.parent.final_tool_error_structured_content(kind)
    }

    fn declares_final_tasks(&self) -> bool {
        self.parent.declares_final_tasks()
    }

    fn declares_final_mrtr(&self) -> bool {
        self.parent.declares_final_mrtr()
    }

    fn timeout(&self) -> Option<Duration> {
        self.parent.timeout()
    }

    fn call(&self, ctx: &McpContext, arguments: serde_json::Value) -> McpResult<Vec<Content>> {
        let transformed_args = self.transform_arguments(arguments)?;
        self.parent.call(ctx, transformed_args)
    }

    fn call_async<'a>(
        &'a self,
        ctx: &'a McpContext,
        arguments: serde_json::Value,
    ) -> BoxFuture<'a, McpOutcome<Vec<Content>>> {
        Box::pin(async move {
            let transformed_args = match self.transform_arguments(arguments) {
                Ok(args) => args,
                Err(error) => return Outcome::Err(error),
            };
            self.parent.call_async(ctx, transformed_args).await
        })
    }

    fn call_async_in_request<'a>(
        &'a self,
        ctx: &'a McpContext,
        request_cx: &'a Cx,
        arguments: serde_json::Value,
    ) -> BoxFuture<'a, McpOutcome<Vec<Content>>> {
        Box::pin(async move {
            let transformed_args = match self.transform_arguments(arguments) {
                Ok(args) => args,
                Err(error) => return Outcome::Err(error),
            };
            self.parent
                .call_async_in_request(ctx, request_cx, transformed_args)
                .await
        })
    }

    fn call_final(
        &self,
        ctx: &McpContext,
        arguments: serde_json::Value,
    ) -> McpResult<CompleteResult<FinalCallToolResult>> {
        self.parent
            .call_final(ctx, self.transform_arguments(arguments)?)
    }

    fn call_final_async<'a>(
        &'a self,
        ctx: &'a McpContext,
        arguments: serde_json::Value,
    ) -> BoxFuture<'a, McpOutcome<CompleteResult<FinalCallToolResult>>> {
        Box::pin(async move {
            let transformed_args = match self.transform_arguments(arguments) {
                Ok(args) => args,
                Err(error) => return Outcome::Err(error),
            };
            self.parent.call_final_async(ctx, transformed_args).await
        })
    }

    fn call_final_async_in_request<'a>(
        &'a self,
        ctx: &'a McpContext,
        request_cx: &'a Cx,
        arguments: serde_json::Value,
    ) -> BoxFuture<'a, McpOutcome<CompleteResult<FinalCallToolResult>>> {
        Box::pin(async move {
            let transformed_args = match self.transform_arguments(arguments) {
                Ok(args) => args,
                Err(error) => return Outcome::Err(error),
            };
            self.parent
                .call_final_async_in_request(ctx, request_cx, transformed_args)
                .await
        })
    }

    fn call_final_outcome(
        &self,
        ctx: &McpContext,
        arguments: serde_json::Value,
    ) -> McpResult<FinalToolOutcome> {
        self.parent
            .call_final_outcome(ctx, self.transform_arguments(arguments)?)
    }

    fn call_final_outcome_async<'a>(
        &'a self,
        ctx: &'a McpContext,
        arguments: serde_json::Value,
    ) -> BoxFuture<'a, McpOutcome<FinalToolOutcome>> {
        Box::pin(async move {
            let transformed_args = match self.transform_arguments(arguments) {
                Ok(args) => args,
                Err(error) => return Outcome::Err(error),
            };
            self.parent
                .call_final_outcome_async(ctx, transformed_args)
                .await
        })
    }

    fn call_final_outcome_async_in_request<'a>(
        &'a self,
        ctx: &'a McpContext,
        request_cx: &'a Cx,
        arguments: serde_json::Value,
    ) -> BoxFuture<'a, McpOutcome<FinalToolOutcome>> {
        Box::pin(async move {
            let transformed_args = match self.transform_arguments(arguments) {
                Ok(args) => args,
                Err(error) => return Outcome::Err(error),
            };
            self.parent
                .call_final_outcome_async_in_request(ctx, request_cx, transformed_args)
                .await
        })
    }

    fn call_final_outcome_async_resuming_in_request<'a>(
        &'a self,
        ctx: &'a McpContext,
        request_cx: &'a Cx,
        arguments: serde_json::Value,
        resume_inputs: Option<&'a MrtrCompletedInputs>,
    ) -> BoxFuture<'a, McpOutcome<FinalToolOutcome>> {
        Box::pin(async move {
            let transformed_args = match self.transform_arguments(arguments) {
                Ok(args) => args,
                Err(error) => return Outcome::Err(error),
            };
            self.parent
                .call_final_outcome_async_resuming_in_request(
                    ctx,
                    request_cx,
                    transformed_args,
                    resume_inputs,
                )
                .await
        })
    }
}

/// Builder for creating transformed tools.
pub struct TransformedToolBuilder {
    parent: BoxedToolHandler,
    name: Option<String>,
    description: Option<String>,
    arg_transforms: HashMap<String, ArgTransform>,
}

impl TransformedToolBuilder {
    /// Creates a new builder for the given parent tool.
    pub fn new(parent: BoxedToolHandler) -> Self {
        Self {
            parent,
            name: None,
            description: None,
            arg_transforms: HashMap::new(),
        }
    }

    /// Sets the new name for the transformed tool.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Sets the new description for the transformed tool.
    #[must_use]
    pub fn description(mut self, desc: impl Into<String>) -> Self {
        self.description = Some(desc.into());
        self
    }

    /// Adds a transformation for the given argument.
    ///
    /// The `original_name` is the name of the argument in the parent tool.
    #[must_use]
    pub fn transform_arg(
        mut self,
        original_name: impl Into<String>,
        transform: ArgTransform,
    ) -> Self {
        self.arg_transforms.insert(original_name.into(), transform);
        self
    }

    /// Renames an argument.
    #[must_use]
    pub fn rename_arg(self, original_name: impl Into<String>, new_name: impl Into<String>) -> Self {
        self.transform_arg(original_name, ArgTransform::new().name(new_name))
    }

    /// Hides an argument and provides a default value.
    #[must_use]
    pub fn hide_arg(
        self,
        original_name: impl Into<String>,
        default: impl Into<serde_json::Value>,
    ) -> Self {
        self.transform_arg(original_name, ArgTransform::drop_with_default(default))
    }

    /// Builds the transformed tool.
    #[must_use]
    pub fn build(self) -> TransformedTool {
        let parent_def = self.parent.definition();

        // Build name mapping (new name -> original name)
        let mut name_mapping = HashMap::new();
        for (original, transform) in &self.arg_transforms {
            if let Some(new_name) = &transform.name {
                name_mapping.insert(new_name.clone(), original.clone());
            }
        }

        // Transform the tool definition
        let definition = self.build_definition(&parent_def);

        TransformedTool {
            parent: self.parent,
            definition,
            arg_transforms: self.arg_transforms,
            name_mapping,
        }
    }

    /// Builds the transformed tool definition.
    fn build_definition(&self, parent: &Tool) -> Tool {
        let name = self.name.clone().unwrap_or_else(|| parent.name.clone());
        let description = self
            .description
            .clone()
            .or_else(|| parent.description.clone());

        // Transform the input schema
        let input_schema = transform_input_schema(&self.arg_transforms, &parent.input_schema);

        Tool {
            name,
            description,
            input_schema,
            output_schema: parent.output_schema.clone(),
            icon: parent.icon.clone(),
            version: parent.version.clone(),
            tags: parent.tags.clone(),
            annotations: parent.annotations.clone(),
        }
    }
}

/// Rewrites a JSON Schema object according to argument rename/hide/default rules.
fn transform_input_schema(
    arg_transforms: &HashMap<String, ArgTransform>,
    original: &serde_json::Value,
) -> serde_json::Value {
    let mut schema = original.clone();

    let Some(obj) = schema.as_object_mut() else {
        return schema;
    };

    // Ensure properties and required exist as the shapes later mutation
    // expects. A parent tool may publish a non-object `properties` or
    // non-array `required`; replacing those malformed members keeps
    // `build()` from panicking on a definition the caller already owns.
    if !obj
        .get("properties")
        .is_some_and(serde_json::Value::is_object)
    {
        obj.insert(String::from("properties"), serde_json::json!({}));
    }
    if !obj.get("required").is_some_and(serde_json::Value::is_array) {
        obj.insert(String::from("required"), serde_json::json!([]));
    }

    // Track changes to apply
    // Pre-allocate based on transform count to avoid reallocations
    let capacity = arg_transforms.len();
    let mut props_to_remove: Vec<String> = Vec::with_capacity(capacity);
    let mut props_to_add: Vec<(String, serde_json::Value)> = Vec::with_capacity(capacity);
    let mut required_renames: Vec<(String, String)> = Vec::with_capacity(capacity);
    let mut required_removes: Vec<String> = Vec::with_capacity(capacity);

    // First pass: collect property transformations
    {
        let Some(props) = obj.get("properties").and_then(serde_json::Value::as_object) else {
            return schema;
        };

        for (original_name, transform) in arg_transforms {
            if transform.hide {
                props_to_remove.push(original_name.clone());
                required_removes.push(original_name.clone());
                continue;
            }

            if let Some(prop_schema) = props.get(original_name).cloned() {
                let new_name = transform.name.as_ref().unwrap_or(original_name);
                let mut new_schema = prop_schema;

                // Apply description override
                if let (Some(desc), Some(schema_obj)) =
                    (&transform.description, new_schema.as_object_mut())
                {
                    schema_obj.insert(String::from("description"), serde_json::json!(desc));
                }

                // Apply type override
                if let Some(type_schema) = &transform.type_schema {
                    new_schema = type_schema.clone();
                }

                // Apply default override
                if let (Some(default), Some(schema_obj)) =
                    (&transform.default, new_schema.as_object_mut())
                {
                    schema_obj.insert(String::from("default"), default.clone());
                }

                if new_name != original_name {
                    props_to_remove.push(original_name.clone());
                    props_to_add.push((new_name.clone(), new_schema));
                    required_renames.push((original_name.clone(), new_name.clone()));
                } else {
                    // Update in place
                    props_to_add.push((original_name.clone(), new_schema));
                }
            }
        }
    }

    // Apply property changes
    if let Some(props) = obj.get_mut("properties").and_then(|p| p.as_object_mut()) {
        for name in &props_to_remove {
            props.remove(name);
        }
        for (name, prop_schema) in props_to_add {
            props.insert(name, prop_schema);
        }
    }

    // Apply required array changes
    if let Some(required) = obj.get_mut("required").and_then(|r| r.as_array_mut()) {
        // Handle renames
        for (old_name, new_name) in required_renames {
            if let Some(idx) = required.iter().position(|v| v.as_str() == Some(&old_name)) {
                required[idx] = serde_json::json!(new_name);
            }
        }
        // Handle removes - compare &str directly to avoid allocation
        required.retain(|v| {
            v.as_str()
                .is_none_or(|s| !required_removes.iter().any(|r| r == s))
        });
    }

    schema
}

#[cfg(test)]
mod tests {
    use super::*;
    use fastmcp_core::block_on;
    use fastmcp_protocol::Content;
    use fastmcp_protocol::common_types::ContentBlock;

    struct SearchToolFixture {
        name: String,
        description: Option<String>,
        schema: serde_json::Value,
    }

    impl SearchToolFixture {
        fn new(name: &str) -> Self {
            Self {
                name: name.to_string(),
                description: Some("Search tool".to_string()),
                schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "q": {
                            "type": "string",
                            "description": "Query"
                        },
                        "n": {
                            "type": "integer",
                            "description": "Limit"
                        }
                    },
                    "required": ["q"]
                }),
            }
        }
    }

    impl ToolHandler for SearchToolFixture {
        fn definition(&self) -> Tool {
            Tool {
                name: self.name.clone(),
                description: self.description.clone(),
                input_schema: self.schema.clone(),
                output_schema: None,
                icon: None,
                version: None,
                tags: vec![],
                annotations: None,
            }
        }

        fn call(&self, _ctx: &McpContext, arguments: serde_json::Value) -> McpResult<Vec<Content>> {
            Ok(vec![Content::Text {
                text: format!("Search called with: {}", arguments),
            }])
        }
    }

    #[test]
    fn test_rename_tool() {
        let tool = SearchToolFixture::new("search");
        let transformed = TransformedTool::from_tool(tool)
            .name("semantic_search")
            .description("Search semantically")
            .build();

        let def = transformed.definition();
        assert_eq!(def.name, "semantic_search");
        assert_eq!(def.description, Some("Search semantically".to_string()));
    }

    #[test]
    fn test_rename_arg() {
        let tool = SearchToolFixture::new("search");
        let transformed = TransformedTool::from_tool(tool)
            .rename_arg("q", "query")
            .build();

        let def = transformed.definition();
        let props = def.input_schema["properties"].as_object().unwrap();

        // Original name should be gone
        assert!(!props.contains_key("q"));
        // New name should exist
        assert!(props.contains_key("query"));
    }

    #[test]
    fn test_hide_arg() {
        let tool = SearchToolFixture::new("search");
        let transformed = TransformedTool::from_tool(tool).hide_arg("n", 10).build();

        let def = transformed.definition();
        let props = def.input_schema["properties"].as_object().unwrap();

        // Hidden arg should not be in schema
        assert!(!props.contains_key("n"));
        // But q should still be there
        assert!(props.contains_key("q"));
    }

    #[test]
    fn test_transform_arguments() {
        let tool = SearchToolFixture::new("search");
        let transformed = TransformedTool::from_tool(tool)
            .rename_arg("q", "query")
            .hide_arg("n", 10)
            .build();

        // Input uses new names
        let input = serde_json::json!({
            "query": "hello world"
        });

        // Transform should map back to original names and add defaults
        let result = transformed.transform_arguments(input).unwrap();
        let obj = result.as_object().unwrap();

        assert_eq!(obj.get("q").unwrap(), "hello world");
        assert_eq!(obj.get("n").unwrap(), 10);
    }

    #[test]
    fn test_arg_transform_builder() {
        let transform = ArgTransform::new()
            .name("search_query")
            .description("The search query string")
            .default_str("*")
            .required();

        assert_eq!(transform.name, Some("search_query".to_string()));
        assert_eq!(
            transform.description,
            Some("The search query string".to_string())
        );
        assert_eq!(transform.default, Some(serde_json::json!("*")));
        assert_eq!(transform.required, Some(true));
        assert!(!transform.hide);
    }

    // ── ArgTransform type helpers ─────────────────────────────────────

    #[test]
    fn arg_transform_default_int() {
        let t = ArgTransform::new().default_int(42);
        assert_eq!(t.default, Some(serde_json::json!(42)));
    }

    #[test]
    fn arg_transform_default_bool() {
        let t = ArgTransform::new().default_bool(true);
        assert_eq!(t.default, Some(serde_json::json!(true)));
    }

    #[test]
    fn arg_transform_type_schema() {
        let schema = serde_json::json!({"type": "number", "minimum": 0});
        let t = ArgTransform::new().type_schema(schema.clone());
        assert_eq!(t.type_schema, Some(schema));
    }

    #[test]
    fn arg_transform_drop_with_default() {
        let t = ArgTransform::drop_with_default("auto");
        assert!(t.hide);
        assert_eq!(t.default, Some(serde_json::json!("auto")));
    }

    #[test]
    fn arg_transform_hide_sets_flag() {
        let t = ArgTransform::new().hide();
        assert!(t.hide);
    }

    #[test]
    fn arg_transform_debug() {
        let t = ArgTransform::new().name("x");
        let debug = format!("{:?}", t);
        assert!(debug.contains("ArgTransform"));
    }

    #[test]
    fn arg_transform_clone() {
        let t = ArgTransform::new().name("x").default_int(5);
        let c = t.clone();
        assert_eq!(c.name, Some("x".to_string()));
        assert_eq!(c.default, Some(serde_json::json!(5)));
    }

    // ── TransformedTool accessors ─────────────────────────────────────

    #[test]
    fn transformed_tool_parent_definition() {
        let tool = SearchToolFixture::new("original");
        let transformed = TransformedTool::from_tool(tool).name("renamed").build();
        let parent_def = transformed.parent_definition();
        assert_eq!(parent_def.name, "original");
    }

    #[test]
    fn transformed_tool_arg_transforms_accessor() {
        let tool = SearchToolFixture::new("search");
        let transformed = TransformedTool::from_tool(tool)
            .rename_arg("q", "query")
            .build();
        let transforms = transformed.arg_transforms();
        assert!(transforms.contains_key("q"));
    }

    #[test]
    fn transformed_tool_debug_format() {
        let tool = SearchToolFixture::new("search");
        let transformed = TransformedTool::from_tool(tool).name("dbg_tool").build();
        let debug = format!("{:?}", transformed);
        assert!(debug.contains("TransformedTool"));
        assert!(debug.contains("dbg_tool"));
    }

    #[test]
    fn transformed_tool_from_boxed() {
        let tool = Box::new(SearchToolFixture::new("boxed")) as BoxedToolHandler;
        let transformed = TransformedTool::from_boxed(tool).name("unboxed").build();
        assert_eq!(transformed.definition().name, "unboxed");
    }

    // ── transform_arguments edge cases ───────────────────────────────

    #[test]
    fn transform_arguments_null_treated_as_empty() {
        let tool = SearchToolFixture::new("search");
        let transformed = TransformedTool::from_tool(tool).hide_arg("n", 10).build();

        let result = transformed
            .transform_arguments(serde_json::Value::Null)
            .unwrap();
        let obj = result.as_object().unwrap();
        assert_eq!(obj.get("n").unwrap(), 10);
    }

    #[test]
    fn transform_arguments_non_object_returns_error() {
        let tool = SearchToolFixture::new("search");
        let transformed = TransformedTool::from_tool(tool).build();

        let result = transformed.transform_arguments(serde_json::json!("bad"));
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.message.contains("Arguments must be an object"));
    }

    #[test]
    fn transform_arguments_passthrough_unknown_args() {
        let tool = SearchToolFixture::new("search");
        let transformed = TransformedTool::from_tool(tool)
            .rename_arg("q", "query")
            .build();

        let input = serde_json::json!({
            "query": "test",
            "extra": "value"
        });
        let result = transformed.transform_arguments(input).unwrap();
        let obj = result.as_object().unwrap();
        assert_eq!(obj.get("q").unwrap(), "test");
        assert_eq!(obj.get("extra").unwrap(), "value");
    }

    #[test]
    fn transform_arguments_rename_ignores_original_name_leftover() {
        let tool = SearchToolFixture::new("search");
        let transformed = TransformedTool::from_tool(tool)
            .rename_arg("q", "query")
            .build();

        let result = transformed
            .transform_arguments(serde_json::json!({
                "query": "mapped",
                "q": "leftover"
            }))
            .unwrap();
        let obj = result.as_object().unwrap();
        assert_eq!(obj.get("q").unwrap(), "mapped");
        assert!(
            obj.len() == 1,
            "the unpublished original name must not leak beside the mapped value: {obj:?}"
        );
    }

    #[test]
    fn transform_arguments_hidden_without_default_errors() {
        let tool = SearchToolFixture::new("search");
        let transformed = TransformedTool::from_tool(tool)
            .transform_arg("q", ArgTransform::new().hide())
            .build();

        let result = transformed.transform_arguments(serde_json::json!({}));
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("Hidden argument 'q' requires a default value")
        );
    }

    #[test]
    fn transform_arguments_hidden_default_ignores_caller_supplied_value() {
        let tool = SearchToolFixture::new("search");
        let transformed = TransformedTool::from_tool(tool).hide_arg("n", 10).build();

        let result = transformed
            .transform_arguments(serde_json::json!({"q": "hello", "n": 999}))
            .unwrap();
        let obj = result.as_object().unwrap();
        assert_eq!(obj.get("q").unwrap(), "hello");
        assert_eq!(
            obj.get("n").unwrap(),
            10,
            "a hidden argument must keep its server default"
        );
    }

    #[test]
    fn transform_arguments_hidden_renamed_strips_both_published_and_original_names() {
        let tool = SearchToolFixture::new("search");
        let transformed = TransformedTool::from_tool(tool)
            .transform_arg(
                "n",
                ArgTransform::new().name("limit").default_int(10).hide(),
            )
            .build();

        let result = transformed
            .transform_arguments(serde_json::json!({
                "q": "hello",
                "n": 1,
                "limit": 2
            }))
            .unwrap();
        let obj = result.as_object().unwrap();
        assert_eq!(obj.get("q").unwrap(), "hello");
        assert_eq!(obj.get("n").unwrap(), 10);
        assert!(
            obj.get("limit").is_none(),
            "the unpublished hidden name must not leak into parent arguments"
        );
    }

    #[test]
    fn transform_arguments_hidden_without_default_rejects_caller_value() {
        let tool = SearchToolFixture::new("search");
        let transformed = TransformedTool::from_tool(tool)
            .transform_arg("q", ArgTransform::new().hide())
            .build();

        let result = transformed.transform_arguments(serde_json::json!({"q": "injected"}));
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .message
                .contains("Hidden argument 'q' requires a default value")
        );
    }

    // ── ToolHandler impl ─────────────────────────────────────────────

    #[test]
    fn transformed_tool_call_delegates_with_mapped_args() {
        let tool = SearchToolFixture::new("search");
        let transformed = TransformedTool::from_tool(tool)
            .rename_arg("q", "query")
            .build();

        let cx = asupersync::Cx::for_testing();
        let ctx = McpContext::new(cx, 1);
        let result = transformed
            .call(&ctx, serde_json::json!({"query": "hello"}))
            .unwrap();
        assert_eq!(result.len(), 1);
    }

    #[test]
    fn transformed_tool_call_with_invalid_args_returns_error() {
        let tool = SearchToolFixture::new("search");
        let transformed = TransformedTool::from_tool(tool).build();

        let cx = asupersync::Cx::for_testing();
        let ctx = McpContext::new(cx, 1);
        let result = transformed.call(&ctx, serde_json::json!("string_not_object"));
        assert!(result.is_err());
    }

    // ── Builder keeps parent properties ──────────────────────────────

    #[test]
    fn builder_no_name_keeps_parent_name() {
        let tool = SearchToolFixture::new("original_name");
        let transformed = TransformedTool::from_tool(tool).build();
        assert_eq!(transformed.definition().name, "original_name");
    }

    #[test]
    fn builder_no_description_keeps_parent_description() {
        let tool = SearchToolFixture::new("s");
        let transformed = TransformedTool::from_tool(tool).build();
        assert_eq!(
            transformed.definition().description,
            Some("Search tool".to_string())
        );
    }

    // ── Schema transform: description override ───────────────────────

    #[test]
    fn transform_schema_applies_description_override() {
        let tool = SearchToolFixture::new("s");
        let transformed = TransformedTool::from_tool(tool)
            .transform_arg("q", ArgTransform::new().description("Full search query"))
            .build();

        let def = transformed.definition();
        let q_schema = &def.input_schema["properties"]["q"];
        assert_eq!(q_schema["description"], "Full search query");
    }

    // ── NotSet sentinel ──────────────────────────────────────────────

    #[test]
    fn not_set_debug() {
        let n = NotSet;
        let debug = format!("{:?}", n);
        assert!(debug.contains("NotSet"));
    }

    #[test]
    fn not_set_clone_copy() {
        let n = NotSet;
        let cloned = n.clone();
        let copied = n; // Copy
        let _ = (cloned, copied);
    }

    #[test]
    fn not_set_default() {
        let _ = NotSet;
    }

    // ── ArgTransform defaults ────────────────────────────────────────

    #[test]
    fn arg_transform_new_is_all_none() {
        let t = ArgTransform::new();
        assert!(t.name.is_none());
        assert!(t.description.is_none());
        assert!(t.default.is_none());
        assert!(!t.hide);
        assert!(t.required.is_none());
        assert!(t.type_schema.is_none());
    }

    #[test]
    fn arg_transform_default_trait() {
        let t = <ArgTransform as Default>::default();
        assert!(t.name.is_none());
        assert!(!t.hide);
    }

    // ── Schema transform: type override ──────────────────────────────

    #[test]
    fn transform_schema_replaces_malformed_properties_without_panicking() {
        struct MalformedSchemaTool;
        impl ToolHandler for MalformedSchemaTool {
            fn definition(&self) -> Tool {
                Tool {
                    name: "malformed".to_string(),
                    description: None,
                    input_schema: serde_json::json!({
                        "type": "object",
                        "properties": true,
                        "required": "q"
                    }),
                    output_schema: None,
                    icon: None,
                    version: None,
                    tags: vec![],
                    annotations: None,
                }
            }
            fn call(&self, _ctx: &McpContext, _args: serde_json::Value) -> McpResult<Vec<Content>> {
                Ok(vec![])
            }
        }

        let transformed = TransformedTool::from_tool(MalformedSchemaTool)
            .hide_arg("secret", "server-owned")
            .build();
        assert_eq!(
            transformed.definition().input_schema["properties"],
            serde_json::json!({})
        );
        assert_eq!(
            transformed.definition().input_schema["required"],
            serde_json::json!([])
        );
    }

    #[test]
    fn transform_schema_applies_type_override() {
        let tool = SearchToolFixture::new("s");
        let transformed = TransformedTool::from_tool(tool)
            .transform_arg(
                "q",
                ArgTransform::new().type_schema(serde_json::json!({"type": "number"})),
            )
            .build();

        let def = transformed.definition();
        let q_schema = &def.input_schema["properties"]["q"];
        assert_eq!(q_schema["type"], "number");
    }

    // ── Schema transform: default value ──────────────────────────────

    #[test]
    fn transform_schema_applies_default_value() {
        let tool = SearchToolFixture::new("s");
        let transformed = TransformedTool::from_tool(tool)
            .transform_arg("n", ArgTransform::new().default_int(25))
            .build();

        let def = transformed.definition();
        let n_schema = &def.input_schema["properties"]["n"];
        assert_eq!(n_schema["default"], 25);
    }

    // ── Schema rename updates required array ─────────────────────────

    #[test]
    fn transform_schema_rename_updates_required() {
        let tool = SearchToolFixture::new("s");
        let transformed = TransformedTool::from_tool(tool)
            .rename_arg("q", "query")
            .build();

        let def = transformed.definition();
        let required = def.input_schema["required"].as_array().unwrap();
        assert!(required.iter().any(|v| v == "query"));
        assert!(!required.iter().any(|v| v == "q"));
    }

    // ── Schema hide removes from required ────────────────────────────

    #[test]
    fn transform_schema_hide_removes_from_required() {
        // Make a tool where "q" is required, then hide it
        let tool = SearchToolFixture::new("s");
        let transformed = TransformedTool::from_tool(tool)
            .hide_arg("q", "default-query")
            .build();

        let def = transformed.definition();
        let required = def.input_schema["required"].as_array().unwrap();
        assert!(!required.iter().any(|v| v == "q"));
    }

    // ── Combined transforms ──────────────────────────────────────────

    #[test]
    fn combined_rename_description_default() {
        let tool = SearchToolFixture::new("search");
        let transformed = TransformedTool::from_tool(tool)
            .transform_arg(
                "n",
                ArgTransform::new()
                    .name("limit")
                    .description("Max results")
                    .default_int(10),
            )
            .build();

        let def = transformed.definition();
        let props = def.input_schema["properties"].as_object().unwrap();
        assert!(!props.contains_key("n"));
        let limit = props.get("limit").unwrap();
        assert_eq!(limit["description"], "Max results");
        assert_eq!(limit["default"], 10);
    }

    // ── build_definition preserves parent metadata ───────────────────

    #[test]
    fn build_definition_preserves_parent_output_schema() {
        struct ToolWithOutputSchema;
        impl ToolHandler for ToolWithOutputSchema {
            fn definition(&self) -> Tool {
                Tool {
                    name: "parent".to_string(),
                    description: None,
                    input_schema: serde_json::json!({"type": "object"}),
                    output_schema: Some(serde_json::json!({"type": "string"})),
                    icon: None,
                    version: Some("2.0".to_string()),
                    tags: vec!["tag1".to_string()],
                    annotations: None,
                }
            }
            fn call(&self, _ctx: &McpContext, _args: serde_json::Value) -> McpResult<Vec<Content>> {
                Ok(vec![])
            }
        }

        let transformed = TransformedTool::from_tool(ToolWithOutputSchema)
            .name("child")
            .build();
        let def = transformed.definition();
        assert_eq!(
            def.output_schema,
            Some(serde_json::json!({"type": "string"}))
        );
        assert_eq!(def.version, Some("2.0".to_string()));
        assert_eq!(def.tags, vec!["tag1".to_string()]);
    }

    // ── transform_schema with non-object schema ──────────────────────

    #[test]
    fn transform_schema_non_object_returned_as_is() {
        struct ArraySchemaTool;
        impl ToolHandler for ArraySchemaTool {
            fn definition(&self) -> Tool {
                Tool {
                    name: "arr".to_string(),
                    description: None,
                    input_schema: serde_json::json!("not an object"),
                    output_schema: None,
                    icon: None,
                    version: None,
                    tags: vec![],
                    annotations: None,
                }
            }
            fn call(&self, _ctx: &McpContext, _args: serde_json::Value) -> McpResult<Vec<Content>> {
                Ok(vec![])
            }
        }

        let transformed = TransformedTool::from_tool(ArraySchemaTool)
            .rename_arg("x", "y")
            .build();
        let def = transformed.definition();
        // Schema is returned as-is since it's not an object
        assert_eq!(def.input_schema, serde_json::json!("not an object"));
    }

    // ── Schema without properties or required ────────────────────────

    #[test]
    fn transform_schema_adds_properties_and_required_if_missing() {
        struct MinimalSchemaTool;
        impl ToolHandler for MinimalSchemaTool {
            fn definition(&self) -> Tool {
                Tool {
                    name: "min".to_string(),
                    description: None,
                    input_schema: serde_json::json!({"type": "object"}),
                    output_schema: None,
                    icon: None,
                    version: None,
                    tags: vec![],
                    annotations: None,
                }
            }
            fn call(&self, _ctx: &McpContext, _args: serde_json::Value) -> McpResult<Vec<Content>> {
                Ok(vec![])
            }
        }

        let transformed = TransformedTool::from_tool(MinimalSchemaTool).build();
        let def = transformed.definition();
        assert!(def.input_schema["properties"].is_object());
        assert!(def.input_schema["required"].is_array());
    }

    // ── TransformedTool call with hidden defaults ─────────────────────

    #[test]
    fn transformed_tool_call_injects_hidden_defaults() {
        let tool = SearchToolFixture::new("search");
        let transformed = TransformedTool::from_tool(tool)
            .rename_arg("q", "query")
            .hide_arg("n", 5)
            .build();

        let cx = asupersync::Cx::for_testing();
        let ctx = McpContext::new(cx, 1);
        let result = transformed
            .call(&ctx, serde_json::json!({"query": "test"}))
            .unwrap();
        // The result should contain the search output with mapped args
        assert_eq!(result.len(), 1);
        if let Content::Text { text } = &result[0] {
            assert!(text.contains("\"n\":5"));
            assert!(text.contains("\"q\":\"test\""));
        } else {
            panic!("expected text content");
        }
    }

    // ── transform_arg with no-op transform ───────────────────────────

    #[test]
    fn transform_arg_with_noop_keeps_original() {
        let tool = SearchToolFixture::new("search");
        let transformed = TransformedTool::from_tool(tool)
            .transform_arg("q", ArgTransform::new())
            .build();

        let def = transformed.definition();
        let props = def.input_schema["properties"].as_object().unwrap();
        // q should still exist unchanged
        assert!(props.contains_key("q"));
    }

    // ── transform_arg for non-existent arg ───────────────────────────

    #[test]
    fn transform_arg_for_nonexistent_arg_is_ignored() {
        let tool = SearchToolFixture::new("search");
        let transformed = TransformedTool::from_tool(tool)
            .rename_arg("nonexistent", "renamed")
            .build();

        let def = transformed.definition();
        let props = def.input_schema["properties"].as_object().unwrap();
        // Original args should be untouched
        assert!(props.contains_key("q"));
        assert!(props.contains_key("n"));
        // Renamed nonexistent shouldn't appear
        assert!(!props.contains_key("renamed"));
    }

    #[test]
    fn call_async_delegates_with_mapped_args() {
        use fastmcp_core::block_on;

        let tool = SearchToolFixture::new("search");
        let transformed = TransformedTool::from_tool(tool)
            .rename_arg("q", "query")
            .hide_arg("n", 7)
            .build();

        let cx = asupersync::Cx::for_testing();
        let ctx = McpContext::new(cx, 1);
        let result = block_on(transformed.call_async(&ctx, serde_json::json!({"query": "async"})));
        let content = result.unwrap();
        assert_eq!(content.len(), 1);
        if let Content::Text { text } = &content[0] {
            assert!(text.contains("\"q\":\"async\""));
            assert!(text.contains("\"n\":7"));
        } else {
            panic!("expected text content");
        }
    }

    #[test]
    fn transform_arguments_no_value_no_default_not_hidden_skipped() {
        let tool = SearchToolFixture::new("search");
        let transformed = TransformedTool::from_tool(tool)
            .transform_arg("n", ArgTransform::new().description("ignored desc"))
            .build();

        // Don't supply "n" at all - should skip it (no default, not hidden)
        let result = transformed
            .transform_arguments(serde_json::json!({"q": "hello"}))
            .unwrap();
        let obj = result.as_object().unwrap();
        assert_eq!(obj.get("q").unwrap(), "hello");
        assert!(
            obj.get("n").is_none(),
            "missing arg without default should be skipped"
        );
    }

    #[test]
    fn transform_arguments_default_used_without_hide() {
        let tool = SearchToolFixture::new("search");
        let transformed = TransformedTool::from_tool(tool)
            .transform_arg("n", ArgTransform::new().default_int(99))
            .build();

        // Don't supply "n" - default should kick in even though not hidden
        let result = transformed
            .transform_arguments(serde_json::json!({"q": "test"}))
            .unwrap();
        let obj = result.as_object().unwrap();
        assert_eq!(obj.get("n").unwrap(), 99);
    }

    #[test]
    fn build_definition_parent_no_description_returns_none() {
        struct NoDescTool;
        impl ToolHandler for NoDescTool {
            fn definition(&self) -> Tool {
                Tool {
                    name: "nodesc".to_string(),
                    description: None,
                    input_schema: serde_json::json!({"type": "object"}),
                    output_schema: None,
                    icon: None,
                    version: None,
                    tags: vec![],
                    annotations: None,
                }
            }
            fn call(&self, _ctx: &McpContext, _args: serde_json::Value) -> McpResult<Vec<Content>> {
                Ok(vec![])
            }
        }

        let transformed = TransformedTool::from_tool(NoDescTool).build();
        assert!(transformed.definition().description.is_none());
    }

    #[test]
    fn transform_schema_preserves_unrenamed_in_required() {
        // Create a tool with two required args; rename only one
        struct TwoReqTool;
        impl ToolHandler for TwoReqTool {
            fn definition(&self) -> Tool {
                Tool {
                    name: "two".to_string(),
                    description: None,
                    input_schema: serde_json::json!({
                        "type": "object",
                        "properties": {
                            "a": {"type": "string"},
                            "b": {"type": "string"}
                        },
                        "required": ["a", "b"]
                    }),
                    output_schema: None,
                    icon: None,
                    version: None,
                    tags: vec![],
                    annotations: None,
                }
            }
            fn call(&self, _ctx: &McpContext, _args: serde_json::Value) -> McpResult<Vec<Content>> {
                Ok(vec![])
            }
        }

        let transformed = TransformedTool::from_tool(TwoReqTool)
            .rename_arg("a", "alpha")
            .build();
        let def = transformed.definition();
        let required = def.input_schema["required"].as_array().unwrap();
        assert!(
            required.iter().any(|v| v == "alpha"),
            "renamed arg in required"
        );
        assert!(
            required.iter().any(|v| v == "b"),
            "unrenamed arg still in required"
        );
        assert!(
            !required.iter().any(|v| v == "a"),
            "old name removed from required"
        );
    }

    #[test]
    fn type_schema_replaces_entire_property() {
        let tool = SearchToolFixture::new("s");
        let transformed = TransformedTool::from_tool(tool)
            .transform_arg(
                "q",
                ArgTransform::new()
                    .type_schema(serde_json::json!({"type": "array", "items": {"type": "string"}})),
            )
            .build();

        let def = transformed.definition();
        let q_schema = &def.input_schema["properties"]["q"];
        // Should have the new type, not the old "string"
        assert_eq!(q_schema["type"], "array");
        assert!(q_schema["items"].is_object());
        // The old description should NOT be present (type_schema replaces entirely)
        assert!(q_schema.get("description").is_none());
    }

    struct FinalAwareParent {
        recorded: std::sync::Arc<std::sync::Mutex<Option<serde_json::Value>>>,
        resume_hook_invoked: std::sync::Arc<std::sync::Mutex<bool>>,
    }

    impl FinalAwareParent {
        fn new() -> Self {
            Self {
                recorded: std::sync::Arc::new(std::sync::Mutex::new(None)),
                resume_hook_invoked: std::sync::Arc::new(std::sync::Mutex::new(false)),
            }
        }

        fn search_schema() -> serde_json::Value {
            serde_json::json!({
                "type": "object",
                "properties": {
                    "q": { "type": "string" },
                    "n": { "type": "integer" }
                },
                "required": ["q"]
            })
        }
    }

    impl ToolHandler for FinalAwareParent {
        fn definition(&self) -> Tool {
            Tool {
                name: "search".to_string(),
                description: Some("Search tool".to_string()),
                input_schema: Self::search_schema(),
                output_schema: None,
                icon: None,
                version: None,
                tags: vec![],
                annotations: None,
            }
        }

        fn timeout(&self) -> Option<Duration> {
            Some(Duration::from_secs(3))
        }

        fn declares_final_mrtr(&self) -> bool {
            true
        }

        fn final_title(&self) -> Option<&str> {
            Some("Search")
        }

        fn final_definition(&self) -> Option<FinalTool> {
            Some(FinalTool {
                name: "search".to_string(),
                title: Some("Search".to_string()),
                description: Some("Search tool".to_string()),
                icons: None,
                input_schema: Self::search_schema(),
                output_schema: None,
                annotations: None,
                meta: None,
            })
        }

        fn call(&self, _ctx: &McpContext, arguments: serde_json::Value) -> McpResult<Vec<Content>> {
            *self
                .recorded
                .lock()
                .expect("final-aware parent argument log is not poisoned") = Some(arguments);
            Ok(vec![Content::text("legacy")])
        }

        fn call_final(
            &self,
            _ctx: &McpContext,
            arguments: serde_json::Value,
        ) -> McpResult<CompleteResult<FinalCallToolResult>> {
            *self
                .recorded
                .lock()
                .expect("final-aware parent argument log is not poisoned") = Some(arguments);
            crate::handler::promote_legacy_tool_content(vec![Content::text("final")])
        }

        fn call_final_outcome_async_resuming_in_request<'a>(
            &'a self,
            ctx: &'a McpContext,
            _request_cx: &'a Cx,
            arguments: serde_json::Value,
            _resume_inputs: Option<&'a MrtrCompletedInputs>,
        ) -> BoxFuture<'a, McpOutcome<FinalToolOutcome>> {
            Box::pin(async move {
                *self
                    .resume_hook_invoked
                    .lock()
                    .expect("final-aware parent resume log is not poisoned") = true;
                match self.call_final(ctx, arguments) {
                    Ok(result) => Outcome::Ok(FinalToolOutcome::Complete(result)),
                    Err(error) => Outcome::Err(error),
                }
            })
        }
    }

    #[test]
    fn transformed_tool_forwards_timeout_and_final_definition() {
        let transformed = TransformedTool::from_tool(FinalAwareParent::new())
            .name("semantic_search")
            .rename_arg("q", "query")
            .hide_arg("n", 10)
            .build();

        assert_eq!(transformed.timeout(), Some(Duration::from_secs(3)));
        assert!(transformed.declares_final_mrtr());
        assert_eq!(transformed.final_title(), Some("Search"));

        let final_definition = transformed
            .final_definition()
            .expect("parent final definition must survive the transform wrapper");
        assert_eq!(final_definition.name, "semantic_search");
        assert_eq!(final_definition.title.as_deref(), Some("Search"));
        let properties = final_definition.input_schema["properties"]
            .as_object()
            .expect("final input schema keeps object properties");
        assert!(
            properties.contains_key("query"),
            "final catalog must publish the renamed argument: {properties:?}"
        );
        assert!(
            !properties.contains_key("q"),
            "final catalog must not keep the unpublished original name: {properties:?}"
        );
        assert!(
            !properties.contains_key("n"),
            "final catalog must hide the dropped argument: {properties:?}"
        );
    }

    #[test]
    fn transformed_tool_call_final_uses_parent_final_hook_with_mapped_args() {
        let parent = FinalAwareParent::new();
        let recorded = std::sync::Arc::clone(&parent.recorded);
        let transformed = TransformedTool::from_tool(parent)
            .name("semantic_search")
            .rename_arg("q", "query")
            .hide_arg("n", 10)
            .build();

        let cx = asupersync::Cx::for_testing();
        let ctx = McpContext::new(cx, 1);
        let result = transformed
            .call_final(&ctx, serde_json::json!({"query": "test"}))
            .expect("transformed final call must succeed");
        match result.payload.content.as_slice() {
            [ContentBlock::Text { text, .. }] => {
                assert_eq!(
                    text, "final",
                    "TransformedTool must invoke the parent final hook instead of promoting call()"
                );
            }
            other => panic!("expected one final text block, got {other:?}"),
        }
        let recorded = recorded
            .lock()
            .expect("final-aware parent argument log is not poisoned")
            .clone()
            .expect("parent final hook must observe mapped arguments");
        assert_eq!(recorded["q"], "test");
        assert_eq!(recorded["n"], 10);
        assert!(
            recorded.get("query").is_none(),
            "parent must see original names, not the published aliases: {recorded}"
        );
    }

    #[test]
    fn transformed_tool_call_final_does_not_promote_legacy_call() {
        let parent = FinalAwareParent::new();
        let transformed = TransformedTool::from_tool(parent)
            .rename_arg("q", "query")
            .build();

        let cx = asupersync::Cx::for_testing();
        let ctx = McpContext::new(cx, 1);
        let legacy = transformed
            .call(&ctx, serde_json::json!({"query": "legacy-path"}))
            .expect("legacy call still works");
        match &legacy[0] {
            Content::Text { text, .. } => assert_eq!(text, "legacy"),
            other => panic!("expected legacy text content, got {other:?}"),
        }

        let final_result = transformed
            .call_final(&ctx, serde_json::json!({"query": "final-path"}))
            .expect("final call still works");
        match final_result.payload.content.as_slice() {
            [ContentBlock::Text { text, .. }] => {
                assert_eq!(text, "final");
                assert_ne!(
                    text, "legacy",
                    "the planted dimension is which parent hook ran"
                );
            }
            other => panic!("expected one final text block, got {other:?}"),
        }
    }

    #[test]
    fn transformed_tool_forwards_mrtr_resume_hook() {
        let parent = FinalAwareParent::new();
        let resume_hook_invoked = std::sync::Arc::clone(&parent.resume_hook_invoked);
        let transformed = TransformedTool::from_tool(parent)
            .rename_arg("q", "query")
            .build();

        let cx = asupersync::Cx::for_testing();
        let ctx = McpContext::new(cx.clone(), 1);
        let outcome = block_on(transformed.call_final_outcome_async_resuming_in_request(
            &ctx,
            &cx,
            serde_json::json!({"query": "resume"}),
            None,
        ));
        match outcome {
            Outcome::Ok(FinalToolOutcome::Complete(result)) => {
                match result.payload.content.as_slice() {
                    [ContentBlock::Text { text, .. }] => {
                        assert_eq!(text, "final");
                    }
                    other => panic!("expected one final text block, got {other:?}"),
                }
            }
            other => panic!(
                "expected a complete final outcome, got {}",
                match other {
                    Outcome::Ok(_) => "Ok(non-complete)",
                    Outcome::Err(_) => "Err",
                    Outcome::Cancelled(_) => "Cancelled",
                    Outcome::Panicked(_) => "Panicked",
                }
            ),
        }
        assert!(
            *resume_hook_invoked
                .lock()
                .expect("final-aware parent resume log is not poisoned"),
            "TransformedTool must call the parent MRTR resume hook instead of dropping resume inputs"
        );
    }
}