ironmonitor 7.1.0

IronMonitor: hardware monitoring for CPUs, GPUs, NPUs, memory, I/O and network silicon on Linux, Windows and macOS, which reports what it cannot read as well as what it can
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
//! AI API Tool Implementations
//!
//! This module contains the actual tool implementations that query system data.

use super::types::*;
use super::{AiDataApi, ToolCategory, ToolDefinition};
use crate::error::{IronError, Result};
use serde_json::json;

/// `"WIDTHxHEIGHT"`, or `null` when the display's mode was not read.
///
/// This was `format!("{}x{}", d.width, d.height)` over two `u32`s that were
/// zero when unreadable, so an agent asking about displays was told a monitor
/// was `"0x0"` — a resolution no display has, indistinguishable from a measured
/// one.
/// The display connection as text, or `None` for `Unknown`. The `Debug` form
/// used to reach agents as "Unknown" for a connection nobody identified.
fn connection_text(connection: crate::display::DisplayConnection) -> Option<String> {
    use crate::display::DisplayConnection;
    (connection != DisplayConnection::Unknown).then(|| format!("{connection:?}"))
}

/// The HDR mode as text, or `None` where it was not read or is `Unknown`.
fn hdr_text(hdr: Option<crate::display::HdrMode>) -> Option<String> {
    use crate::display::HdrMode;
    hdr.filter(|mode| *mode != HdrMode::Unknown)
        .map(|mode| format!("{mode:?}"))
}

/// The USB class as text, or `None` for `Unknown`, which the reader uses for
/// "no class was declared" and which agents received as the word "Unknown".
fn usb_class_text(class: crate::usb::UsbDeviceClass) -> Option<String> {
    use crate::usb::UsbDeviceClass;
    (class != UsbDeviceClass::Unknown).then(|| format!("{class:?}"))
}

/// The USB negotiated speed as text, or `None` where no hub reported one.
fn usb_speed_text(speed: crate::usb::UsbSpeed) -> Option<String> {
    use crate::usb::UsbSpeed;
    (speed != UsbSpeed::Unknown).then(|| format!("{speed:?}"))
}

/// One USB device as the tools report it. Shared by the list and the details
/// tool so both carry the same reasons for an unknown class or speed.
fn usb_device_json(device: &crate::usb::UsbDevice) -> serde_json::Value {
    use crate::usb::{UsbDeviceClass, UsbSpeed};
    json!({
        "address": device.address,
        "vendor_id": device.vendor_id.map(|v| format!("{v:04x}")),
        "product_id": device.product_id.map(|p| format!("{p:04x}")),
        "vendor_name": device.manufacturer,
        "product_name": device.product,
        "class": usb_class_text(device.class),
        "class_unavailable_reason": (device.class == UsbDeviceClass::Unknown).then_some("no class was declared by the device"),
        "speed": usb_speed_text(device.speed),
        "speed_unavailable_reason": (device.speed == UsbSpeed::Unknown).then_some("no hub reported a negotiated speed"),
    })
}

/// The disk type as text, or `None` for `Unknown`. The `Debug` form of
/// `Unknown` used to reach agents as the string "Unknown", a classification
/// nobody made.
fn disk_type_text(disk_type: crate::disk::DiskType) -> Option<String> {
    (disk_type != crate::disk::DiskType::Unknown).then(|| format!("{disk_type:?}"))
}

fn resolution_text(d: &crate::display::DisplayInfo) -> Option<String> {
    match (d.width, d.height) {
        (Some(w), Some(h)) => Some(format!("{w}x{h}")),
        _ => None,
    }
}

/// Get all tool definitions
pub fn get_all_tool_definitions() -> Vec<ToolDefinition> {
    let mut tools = Vec::new();

    // System tools
    tools.push(ToolDefinition {
        name: "get_system_summary".to_string(),
        description: "Get a comprehensive summary of the entire system including GPUs, CPU, memory, disk, network, and top processes. This is the best tool to start with for an overall view.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {},
            "required": []
        }),
        category: ToolCategory::System,
        example: Some("get_system_summary()".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_system_info".to_string(),
        description: "Get system identification info: hostname, OS, kernel version, architecture, BIOS, manufacturer.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {},
            "required": []
        }),
        category: ToolCategory::System,
        example: Some("get_system_info()".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_platform_info".to_string(),
        description:
            "Get platform-specific capabilities and what monitoring features are available."
                .to_string(),
        parameters: json!({
            "type": "object",
            "properties": {},
            "required": []
        }),
        category: ToolCategory::System,
        example: Some("get_platform_info()".to_string()),
    });

    // GPU tools
    tools.push(ToolDefinition {
        name: "get_gpu_status".to_string(),
        description: "Get current status of all GPUs: utilization, memory, temperature, power. Best for quick GPU health check.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {},
            "required": []
        }),
        category: ToolCategory::Gpu,
        example: Some("get_gpu_status()".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_gpu_list".to_string(),
        description: "List all detected GPUs with basic info (name, vendor, memory size)."
            .to_string(),
        parameters: json!({
            "type": "object",
            "properties": {},
            "required": []
        }),
        category: ToolCategory::Gpu,
        example: Some("get_gpu_list()".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_gpu_details".to_string(),
        description:
            "Get detailed information about a specific GPU by index, including clocks, processes."
                .to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "gpu_index": {
                    "type": "integer",
                    "description": "GPU index (0-based). Use get_gpu_list to see available indices."
                }
            },
            "required": ["gpu_index"]
        }),
        category: ToolCategory::Gpu,
        example: Some("get_gpu_details({\"gpu_index\": 0})".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_gpu_processes".to_string(),
        description: "Get all processes currently using GPU resources with their memory usage."
            .to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "gpu_index": {
                    "type": "integer",
                    "description": "Optional: specific GPU index. Omit for all GPUs."
                }
            },
            "required": []
        }),
        category: ToolCategory::Gpu,
        example: Some("get_gpu_processes()".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_gpu_utilization".to_string(),
        description: "Get GPU utilization percentages.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "gpu_index": {
                    "type": "integer",
                    "description": "Optional: specific GPU index. Omit for all GPUs."
                }
            },
            "required": []
        }),
        category: ToolCategory::Gpu,
        example: Some("get_gpu_utilization()".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_gpu_memory".to_string(),
        description: "Get GPU memory usage (used, free, total) for each GPU.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "gpu_index": {
                    "type": "integer",
                    "description": "Optional: specific GPU index. Omit for all GPUs."
                }
            },
            "required": []
        }),
        category: ToolCategory::Gpu,
        example: Some("get_gpu_memory()".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_gpu_temperature".to_string(),
        description: "Get GPU temperatures and thermal status.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "gpu_index": {
                    "type": "integer",
                    "description": "Optional: specific GPU index. Omit for all GPUs."
                }
            },
            "required": []
        }),
        category: ToolCategory::Gpu,
        example: Some("get_gpu_temperature()".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_gpu_power".to_string(),
        description: "Get GPU power consumption and limits.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "gpu_index": {
                    "type": "integer",
                    "description": "Optional: specific GPU index. Omit for all GPUs."
                }
            },
            "required": []
        }),
        category: ToolCategory::Gpu,
        example: Some("get_gpu_power()".to_string()),
    });

    // CPU tools
    tools.push(ToolDefinition {
        name: "get_cpu_status".to_string(),
        description: "Get CPU utilization and status for all cores.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {},
            "required": []
        }),
        category: ToolCategory::Cpu,
        example: Some("get_cpu_status()".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_cpu_cores".to_string(),
        description: "Get detailed per-core CPU information.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {},
            "required": []
        }),
        category: ToolCategory::Cpu,
        example: Some("get_cpu_cores()".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_cpu_frequency".to_string(),
        description: "Get CPU frequency information (current, min, max) for each core.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {},
            "required": []
        }),
        category: ToolCategory::Cpu,
        example: Some("get_cpu_frequency()".to_string()),
    });

    // Memory tools
    tools.push(ToolDefinition {
        name: "get_memory_status".to_string(),
        description: "Get RAM and swap usage summary.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {},
            "required": []
        }),
        category: ToolCategory::Memory,
        example: Some("get_memory_status()".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_memory_breakdown".to_string(),
        description: "Get detailed memory breakdown (buffers, cached, shared, etc.).".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {},
            "required": []
        }),
        category: ToolCategory::Memory,
        example: Some("get_memory_breakdown()".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_swap_status".to_string(),
        description: "Get swap space usage.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {},
            "required": []
        }),
        category: ToolCategory::Memory,
        example: Some("get_swap_status()".to_string()),
    });

    // Disk tools
    tools.push(ToolDefinition {
        name: "get_disk_list".to_string(),
        description: "List all disk devices in the system.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {},
            "required": []
        }),
        category: ToolCategory::Disk,
        example: Some("get_disk_list()".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_disk_details".to_string(),
        description: "Get detailed info about a specific disk.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "disk_name": {
                    "type": "string",
                    "description": "Disk device name (e.g., 'sda', 'nvme0n1')"
                }
            },
            "required": ["disk_name"]
        }),
        category: ToolCategory::Disk,
        example: Some("get_disk_details({\"disk_name\": \"nvme0n1\"})".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_disk_io".to_string(),
        description: "Get disk I/O statistics (reads, writes).".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "disk_name": {
                    "type": "string",
                    "description": "Optional: specific disk name. Omit for all disks."
                }
            },
            "required": []
        }),
        category: ToolCategory::Disk,
        example: Some("get_disk_io()".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_disk_health".to_string(),
        description: "Get disk health status.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "disk_name": {
                    "type": "string",
                    "description": "Optional: specific disk name. Omit for all disks."
                }
            },
            "required": []
        }),
        category: ToolCategory::Disk,
        example: Some("get_disk_health()".to_string()),
    });

    // Network tools
    tools.push(ToolDefinition {
        name: "get_network_interfaces".to_string(),
        description: "List all network interfaces with their status.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "active_only": {
                    "type": "boolean",
                    "description": "Only show active interfaces. Default: true"
                }
            },
            "required": []
        }),
        category: ToolCategory::Network,
        example: Some("get_network_interfaces()".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_network_bandwidth".to_string(),
        description: "Get current network bandwidth usage (receive/transmit rates).".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "interface_name": {
                    "type": "string",
                    "description": "Optional: specific interface name. Omit for all interfaces."
                }
            },
            "required": []
        }),
        category: ToolCategory::Network,
        example: Some("get_network_bandwidth()".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_interface_details".to_string(),
        description: "Get detailed info about a specific network interface.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "interface_name": {
                    "type": "string",
                    "description": "Interface name (e.g., 'eth0', 'wlan0')"
                }
            },
            "required": ["interface_name"]
        }),
        category: ToolCategory::Network,
        example: Some("get_interface_details({\"interface_name\": \"eth0\"})".to_string()),
    });

    // Process tools
    tools.push(ToolDefinition {
        name: "get_process_list".to_string(),
        description: "Get running processes with CPU and memory usage. The default ordering is CPU, not RAM. For the largest RAM consumer, prefer get_top_memory_processes with count 1; otherwise specify sort_by memory explicitly.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "limit": {
                    "type": "integer",
                    "description": "Maximum number of processes to return. Default: 50"
                },
                "sort_by": {
                    "type": "string",
                    "enum": ["cpu", "memory", "gpu_memory", "name", "pid"],
                    "description": "Sort order. Default: cpu"
                }
            },
            "required": []
        }),
        category: ToolCategory::Process,
        example: Some("get_process_list({\"limit\": 20, \"sort_by\": \"memory\"})".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_process_details".to_string(),
        description: "Get detailed information about a specific process.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "pid": {
                    "type": "integer",
                    "description": "Process ID"
                }
            },
            "required": ["pid"]
        }),
        category: ToolCategory::Process,
        example: Some("get_process_details({\"pid\": 1234})".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_top_cpu_processes".to_string(),
        description: "Get top N processes by CPU usage.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "count": {
                    "type": "integer",
                    "description": "Number of processes to return. Default: 10"
                }
            },
            "required": []
        }),
        category: ToolCategory::Process,
        example: Some("get_top_cpu_processes({\"count\": 5})".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_top_memory_processes".to_string(),
        description: "Get processes ranked by resident RAM usage, largest first. Use count 1 to identify the largest RAM consumer. Copy the returned process name and memory_display verbatim. memory_mb is in MiB (1024 squared bytes).".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "count": {
                    "type": "integer",
                    "description": "Number of processes to return. Default: 10"
                }
            },
            "required": []
        }),
        category: ToolCategory::Process,
        example: Some("get_top_memory_processes({\"count\": 5})".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_top_gpu_processes".to_string(),
        description: "Get top N processes by GPU memory usage.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "count": {
                    "type": "integer",
                    "description": "Number of processes to return. Default: 10"
                },
                "gpu_index": {
                    "type": "integer",
                    "description": "Optional: filter to specific GPU"
                }
            },
            "required": []
        }),
        category: ToolCategory::Process,
        example: Some("get_top_gpu_processes({\"count\": 10})".to_string()),
    });

    tools.push(ToolDefinition {
        name: "search_processes".to_string(),
        description: "Search for processes by name pattern.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "pattern": {
                    "type": "string",
                    "description": "Search pattern (case-insensitive substring match)"
                }
            },
            "required": ["pattern"]
        }),
        category: ToolCategory::Process,
        example: Some("search_processes({\"pattern\": \"chrome\"})".to_string()),
    });

    // Hardware tools
    tools.push(ToolDefinition {
        name: "get_motherboard_sensors".to_string(),
        description: "Get all motherboard sensor readings (temperatures, voltages, fans). Returns {\"readings\": [...], \"errors\": [{source, error}]}; a failed source is listed under errors, never read as an empty list."
            .to_string(),
        parameters: json!({
            "type": "object",
            "properties": {},
            "required": []
        }),
        category: ToolCategory::Hardware,
        example: Some("get_motherboard_sensors()".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_system_temperatures".to_string(),
        description: "Get all temperature sensors in the system. Returns {\"temperatures\": [...], \"errors\": [{source, error}]}; a failed source is listed under errors, never read as an empty list.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {},
            "required": []
        }),
        category: ToolCategory::Hardware,
        example: Some("get_system_temperatures()".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_fan_speeds".to_string(),
        description: "Get all fan speeds and status. Returns {\"fans\": [...], \"errors\": [{source, error}]}; a failed source is listed under errors, never read as an empty list.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {},
            "required": []
        }),
        category: ToolCategory::Hardware,
        example: Some("get_fan_speeds()".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_voltage_rails".to_string(),
        description: "Get motherboard voltage rail readings. Returns {\"voltage_rails\": [...], \"errors\": [{source, error}]}; a failed source is listed under errors, never read as an empty list.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {},
            "required": []
        }),
        category: ToolCategory::Hardware,
        example: Some("get_voltage_rails()".to_string()),
    });

    tools.push(ToolDefinition {
        name: "get_driver_info".to_string(),
        description: "Get installed driver versions (GPU, network, storage).".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "driver_type": {
                    "type": "string",
                    "enum": ["gpu", "network", "storage", "all"],
                    "description": "Type of drivers to query. Default: all"
                }
            },
            "required": []
        }),
        category: ToolCategory::Hardware,
        example: Some("get_driver_info({\"driver_type\": \"gpu\"})".to_string()),
    });

    // Audio tools
    tools.push(ToolDefinition {
        name: "get_audio_devices".to_string(),
        description: "List all audio devices (speakers, microphones, headphones) with their status.".to_string(),
        parameters: json!({"type": "object", "properties": {"device_type": {"type": "string", "enum": ["output", "input", "all"], "description": "Filter by device type. Default: all"}}, "required": []}),
        category: ToolCategory::Audio,
        example: Some("get_audio_devices()".to_string()),
    });
    tools.push(ToolDefinition {
        name: "get_audio_status".to_string(),
        description: "Get current audio status including master volume and mute state.".to_string(),
        parameters: json!({"type": "object", "properties": {}, "required": []}),
        category: ToolCategory::Audio,
        example: Some("get_audio_status()".to_string()),
    });
    // Bluetooth tools
    tools.push(ToolDefinition {
        name: "get_bluetooth_adapters".to_string(),
        description: "List all Bluetooth adapters in the system.".to_string(),
        parameters: json!({"type": "object", "properties": {}, "required": []}),
        category: ToolCategory::Bluetooth,
        example: Some("get_bluetooth_adapters()".to_string()),
    });
    tools.push(ToolDefinition {
        name: "get_bluetooth_devices".to_string(),
        description: "List all paired/discovered Bluetooth devices with connection status.".to_string(),
        parameters: json!({"type": "object", "properties": {"connected_only": {"type": "boolean", "description": "Only show connected devices. Default: false"}}, "required": []}),
        category: ToolCategory::Bluetooth,
        example: Some("get_bluetooth_devices()".to_string()),
    });
    // Display tools
    tools.push(ToolDefinition {
        name: "get_display_list".to_string(),
        description: "List all connected displays/monitors with resolution and refresh rate."
            .to_string(),
        parameters: json!({"type": "object", "properties": {}, "required": []}),
        category: ToolCategory::Display,
        example: Some("get_display_list()".to_string()),
    });
    tools.push(ToolDefinition {
        name: "get_display_details".to_string(),
        description: "Get detailed information about a specific display.".to_string(),
        parameters: json!({"type": "object", "properties": {"display_id": {"type": "string", "description": "Display identifier"}}, "required": ["display_id"]}),
        category: ToolCategory::Display,
        example: Some("get_display_details()".to_string()),
    });
    // USB tools
    tools.push(ToolDefinition {
        name: "get_usb_devices".to_string(),
        description: "List all connected USB devices with vendor/product info.".to_string(),
        parameters: json!({"type": "object", "properties": {"class": {"type": "string", "enum": ["audio", "hid", "storage", "hub", "video", "all"], "description": "Filter by USB device class. Default: all"}}, "required": []}),
        category: ToolCategory::Usb,
        example: Some("get_usb_devices()".to_string()),
    });
    tools.push(ToolDefinition {
        name: "get_usb_device_details".to_string(),
        description: concat!(
            "Get detailed information about a specific USB device, addressed ",
            "by the `address` field from `get_usb_devices`."
        )
        .to_string(),
        // Was `bus` and `address` as integers. Bus and port do not identify a
        // device -- on Windows every device reports bus 0 port 0 -- so the
        // catalogue was telling agents to ask a question that could only ever
        // return the first device.
        parameters: json!({"type": "object", "properties": {"address": {"type": "string", "description": "Device address, as returned in the `address` field of get_usb_devices"}}, "required": ["address"]}),
        category: ToolCategory::Usb,
        example: Some(
            "get_usb_device_details(address=\"usb_vid_046d_pid_c548_mi_01_9_24c94812_0_0001\")"
                .to_string(),
        ),
    });

    // `get_historical_data` and `compare_metrics` were advertised here with full
    // descriptions and worked examples, and neither had an implementation --- no
    // `tool_*` function and no arm in `call_tool`, so an agent that read the
    // catalogue and called one got "Unknown tool", which reads as the agent's
    // own mistake rather than as ironmon's. The only other mention of the name was
    // a label pushed into a text blob, which is not the tool.
    //
    // Those legacy names stay removed. query_metric_history now uses the bounded,
    // timestamped observation service, with session retention and explicit gaps.

    // Profile inspector tools (NVPI / XTU / Ryzen Master / nvme-cli style)
    tools.push(ToolDefinition {
        name: "list_profile_subsystems".to_string(),
        description: "List hardware subsystems with readable driver/firmware profile data (gpu, cpu, nvme, display, memory). Use this to discover what tunable settings can be inspected on this machine.".to_string(),
        parameters: json!({"type": "object", "properties": {}, "required": []}),
        category: ToolCategory::Hardware,
        example: Some("list_profile_subsystems()".to_string()),
    });
    tools.push(ToolDefinition {
        name: "get_profile_settings".to_string(),
        description: "Get all profile groups and settings for one subsystem. Each group is a device (GPU/DIMM/NVMe/display) with its current driver settings. Read-only; mirrors the data shown by NVIDIA Profile Inspector, Intel XTU, AMD Ryzen Master, and nvme-cli.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "subsystem": {
                    "type": "string",
                    "enum": ["gpu", "cpu", "nvme", "display", "memory"],
                    "description": "Subsystem to inspect"
                }
            },
            "required": ["subsystem"]
        }),
        category: ToolCategory::Hardware,
        example: Some(r#"get_profile_settings({"subsystem": "gpu"})"#.to_string()),
    });
    tools.push(ToolDefinition {
        name: "get_profile_deviations".to_string(),
        description: "List every hardware setting whose current value differs from its declared default — the 'what's been changed from stock' report. Sorted with dangerous risk first. Use this to audit a system after a BIOS update, driver reinstall, or to verify a clean baseline.".to_string(),
        parameters: json!({"type": "object", "properties": {}, "required": []}),
        category: ToolCategory::Hardware,
        example: Some("get_profile_deviations()".to_string()),
    });
    tools.push(ToolDefinition {
        name: "benchmark_profile_providers".to_string(),
        description: "Benchmark each profile subsystem provider: wall-clock ms, group/setting counts, throughput. Use this to decide whether to call get_profile_settings(subsystem) selectively when a full snapshot is too slow.".to_string(),
        parameters: json!({"type": "object", "properties": {}, "required": []}),
        category: ToolCategory::Hardware,
        example: Some("benchmark_profile_providers()".to_string()),
    });
    tools.push(ToolDefinition {
        name: "list_writable_profile_settings".to_string(),
        description: "Return the list of profile setting ids that this build can actually write to. Use this before suggesting any apply operation — only ids in this list have a real backing ApplyHandler.".to_string(),
        parameters: json!({"type": "object", "properties": {}, "required": []}),
        category: ToolCategory::Hardware,
        example: Some("list_writable_profile_settings()".to_string()),
    });
    tools.push(ToolDefinition {
        name: "apply_profile_setting".to_string(),
        description: "Write a profile setting (e.g. enable NVIDIA persistence mode). REQUIRES BOTH (a) confirm=true and (b) the environment variable IRONMON_ALLOW_AGENT_WRITES=1 to actually attempt the write. Without those, the call returns a planned-but-not-applied outcome. Every attempt is JSON-logged to the audit log regardless.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "setting_id": {"type": "string", "description": "Exact setting id; must be in list_writable_profile_settings()."},
                "value": {"description": "New value. Booleans use true/false; ints/floats are numeric; otherwise a string."},
                "confirm": {"type": "boolean", "description": "Must be true to attempt the write."}
            },
            "required": ["setting_id", "value"]
        }),
        category: ToolCategory::Hardware,
        example: Some(r#"apply_profile_setting({"setting_id": "scaling_governor", "value": "performance", "confirm": true})"#.to_string()),
    });
    tools.push(ToolDefinition {
        name: "explain_profile_setting".to_string(),
        description: "Return full metadata for a single profile setting by exact id: description, default, range, choices, risk, source, and related settings in the same group. Use this when a user asks 'what does setting X mean'.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "setting_id": {
                    "type": "string",
                    "description": "Exact setting id (e.g. 'power_limit_mw', 'pl1_w', 'feat.write_cache.enabled')."
                }
            },
            "required": ["setting_id"]
        }),
        category: ToolCategory::Hardware,
        example: Some(r#"explain_profile_setting({"setting_id": "pl1_w"})"#.to_string()),
    });
    tools.push(ToolDefinition {
        name: "get_active_app_profiles".to_string(),
        description: "List running processes alongside whether each has a known per-application driver profile (NVIDIA DRS database). Use this to identify apps that could benefit from a tuned profile (DLSS, V-Sync, framerate cap) or to confirm an existing profile applies to the current run.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "matched_only": {
                    "type": "boolean",
                    "description": "If true, return only processes with a known driver profile."
                }
            },
            "required": []
        }),
        category: ToolCategory::Hardware,
        example: Some(r#"get_active_app_profiles({"matched_only": true})"#.to_string()),
    });
    tools.push(ToolDefinition {
        name: "search_profile_settings".to_string(),
        description: "Search all hardware profile settings by case-insensitive substring (matches setting id, display name, description, or value). Useful for questions like 'is XMP enabled', 'what's my CPU power limit', or 'find DLSS setting'.".to_string(),
        parameters: json!({
            "type": "object",
            "properties": {
                "query": {"type": "string", "description": "Search term"}
            },
            "required": ["query"]
        }),
        category: ToolCategory::Hardware,
        example: Some(r#"search_profile_settings({"query": "xmp"})"#.to_string()),
    });

    tools.extend(super::observation_tools::definitions());
    tools.extend(super::diagnostic_tools::definitions());
    tools
}

// Tool implementations for AiDataApi
impl AiDataApi {
    // ============== System Tools ==============

    pub(crate) fn tool_get_system_summary(
        &mut self,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let summary = self.system_summary()?;
        Ok(serde_json::to_value(summary)?)
    }

    pub(crate) fn tool_get_system_info(
        &mut self,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let info = crate::motherboard::get_system_info()
            .map_err(|e| IronError::NotImplemented(e.to_string()))?;

        let uptime = crate::stats::uptime().ok().map(|d| d.as_secs());

        let details = SystemInfoDetails {
            hostname: info.hostname.clone(),
            os_name: info.os_name.clone(),
            os_version: info.os_version.clone(),
            kernel_version: info.kernel_version.clone(),
            architecture: info.architecture.clone(),
            bios_vendor: info.bios.vendor.clone(),
            bios_version: info.bios.version.clone(),
            manufacturer: info.manufacturer.clone(),
            model: info.product_name.clone(),
            // `read_uptime` has had a platform-specific implementation on
            // Linux, Windows and macOS the whole time; what was missing was a
            // way to call it without building a `IronMonitor`. Boot time follows from
            // uptime, so both are present or both absent -- deriving one from a
            // clock that failed would be worse than reporting neither.
            uptime_seconds: uptime,
            boot_time: uptime.and_then(|u| {
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .ok()
                    .map(|now| now.as_secs().saturating_sub(u))
            }),
        };

        Ok(serde_json::to_value(details)?)
    }

    pub(crate) fn tool_get_platform_info(
        &mut self,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let mut capabilities = serde_json::Map::new();

        capabilities.insert("os".to_string(), json!(std::env::consts::OS));
        capabilities.insert("arch".to_string(), json!(std::env::consts::ARCH));
        capabilities.insert("family".to_string(), json!(std::env::consts::FAMILY));

        // Check GPU support
        capabilities.insert("gpu_nvidia".to_string(), json!(cfg!(feature = "nvidia")));
        capabilities.insert("gpu_amd".to_string(), json!(cfg!(feature = "amd")));
        capabilities.insert("gpu_intel".to_string(), json!(cfg!(feature = "intel")));
        capabilities.insert("gpu_apple".to_string(), json!(cfg!(feature = "apple")));

        // Check what's actually available
        // Each of these is `true` when the component exists, and null when it
        // does not, with the reason beside it. `false` used to be published for
        // a component whose creation had failed, which says it is absent.
        capabilities.insert(
            "gpus_detected".to_string(),
            json!(self.gpus.is_some().then_some(true)),
        );
        capabilities.insert("gpu_detection_error".to_string(), json!(self.gpu_error));
        capabilities.insert(
            "gpu_count".to_string(),
            // `null` when no GPU monitor exists. `0` here said the machine
            // has no GPUs, which is a claim about hardware not yet read.
            json!(self.gpus.as_ref().map(|g| g.device_count())),
        );
        capabilities.insert(
            "process_monitor".to_string(),
            json!(self.process_monitor.is_some().then_some(true)),
        );
        capabilities.insert(
            "process_monitor_error".to_string(),
            json!(self.process_monitor_error),
        );
        capabilities.insert(
            "network_monitor".to_string(),
            json!(self.network_monitor.is_some().then_some(true)),
        );
        capabilities.insert(
            "network_monitor_error".to_string(),
            json!(self.network_monitor_error),
        );

        Ok(json!(capabilities))
    }

    // ============== GPU Tools ==============

    pub(crate) fn tool_get_gpu_status(
        &mut self,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let gpus = self.gpus.as_ref().ok_or_else(|| self.gpu_unavailable())?;

        let snapshots = gpus
            .snapshot_all()
            .map_err(|e| IronError::GpuError(e.to_string()))?;

        let status: Vec<_> = snapshots
            .iter()
            .enumerate()
            .map(|(idx, s)| {
                json!({
                    "index": idx,
                    "name": s.static_info.name,
                    "vendor": format!("{:?}", s.static_info.vendor),
                    "utilization_percent": s.dynamic_info.utilization,
                    // `null` rather than `0` for a device that reported no
                    // memory figures. `usage_percent` is the derived field on
                    // `GpuMemory`, which is absent whenever either input is --
                    // the arithmetic used to run against a total that could be
                    // zero and answer `0.0`.
                    "memory": {
                        "used_mb": s.dynamic_info.memory.used.map(|v| v / 1024 / 1024),
                        "total_mb": s.dynamic_info.memory.total.map(|v| v / 1024 / 1024),
                        "free_mb": s.dynamic_info.memory.free.map(|v| v / 1024 / 1024),
                        "usage_percent": s.dynamic_info.memory.utilization,
                    },
                    "temperature_c": s.dynamic_info.thermal.temperature,
                    "power_watts": s.dynamic_info.power.draw.map(|p| p as f32 / 1000.0),
                    "power_limit_watts": s.dynamic_info.power.limit.map(|p| p as f32 / 1000.0),
                })
            })
            .collect();

        Ok(json!({
            "gpu_count": status.len(),
            "gpus": status
        }))
    }

    pub(crate) fn tool_get_gpu_list(
        &mut self,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let gpus = self.gpus.as_ref().ok_or_else(|| self.gpu_unavailable())?;

        let snapshots = gpus
            .snapshot_all()
            .map_err(|e| IronError::GpuError(e.to_string()))?;

        let list: Vec<_> = snapshots
            .iter()
            .enumerate()
            .map(|(idx, s)| {
                json!({
                    "index": idx,
                    "name": s.static_info.name,
                    "vendor": format!("{:?}", s.static_info.vendor),
                    "total_memory_mb": s.dynamic_info.memory.total.map(|v| v / 1024 / 1024),
                })
            })
            .collect();

        Ok(json!(list))
    }

    pub(crate) fn tool_get_gpu_details(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let gpu_index = params
            .get("gpu_index")
            .and_then(|v| v.as_u64())
            .ok_or_else(|| IronError::InvalidArgument("gpu_index is required".to_string()))?
            as usize;

        let gpus = self.gpus.as_ref().ok_or_else(|| self.gpu_unavailable())?;

        let snapshots = gpus
            .snapshot_all()
            .map_err(|e| IronError::GpuError(e.to_string()))?;

        let info = snapshots.get(gpu_index).ok_or_else(|| {
            IronError::InvalidArgument(format!("GPU index {} not found", gpu_index))
        })?;

        Ok(json!({
            "index": gpu_index,
            "name": info.static_info.name,
            "vendor": format!("{:?}", info.static_info.vendor),
            "pci_bus_id": info.static_info.pci_bus_id,
            "uuid": info.static_info.uuid,
            "driver_version": info.static_info.driver_version,
            "utilization": {
                "gpu_percent": info.dynamic_info.utilization,
            },
            "memory": {
                "total_bytes": info.dynamic_info.memory.total,
                "used_bytes": info.dynamic_info.memory.used,
                "free_bytes": info.dynamic_info.memory.free,
                "total_mb": info.dynamic_info.memory.total.map(|v| v / 1024 / 1024),
                "used_mb": info.dynamic_info.memory.used.map(|v| v / 1024 / 1024),
                "usage_percent": info.dynamic_info.memory.utilization,
            },
            "thermal": {
                "temperature_c": info.dynamic_info.thermal.temperature,
                "max_temperature_c": info.dynamic_info.thermal.max_temperature,
                "critical_temperature_c": info.dynamic_info.thermal.critical_temperature,
                "fan_speed_percent": info.dynamic_info.thermal.fan_speed,
                "fan_rpm": info.dynamic_info.thermal.fan_rpm,
            },
            "power": {
                "current_watts": info.dynamic_info.power.draw.map(|p| p as f32 / 1000.0),
                "limit_watts": info.dynamic_info.power.limit.map(|p| p as f32 / 1000.0),
                "default_limit_watts": info.dynamic_info.power.default_limit.map(|p| p as f32 / 1000.0),
            },
            "clocks": {
                "graphics_mhz": info.dynamic_info.clocks.graphics,
                "memory_mhz": info.dynamic_info.clocks.memory,
                "sm_mhz": info.dynamic_info.clocks.sm,
                "max_graphics_mhz": info.dynamic_info.clocks.graphics_max,
                "max_memory_mhz": info.dynamic_info.clocks.memory_max,
            },
            "processes": info.dynamic_info.processes.iter().map(|p| {
                json!({
                    "pid": p.pid,
                    "name": p.name,
                    "memory_bytes": p.memory_usage,
                    "gpu_usage_percent": p.gpu_usage,
                })
            }).collect::<Vec<_>>(),
        }))
    }

    pub(crate) fn tool_get_gpu_processes(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let gpu_index = params.get("gpu_index").and_then(|v| v.as_u64());

        let proc_mon = self.process_monitor.as_mut().ok_or_else(|| {
            IronError::NotImplemented("Process monitor not available".to_string())
        })?;

        let gpu_procs = proc_mon
            .gpu_processes()
            .map_err(|e| IronError::ProcessError(e.to_string()))?;

        let filtered: Vec<_> = gpu_procs
            .iter()
            .filter(|p| {
                gpu_index.is_none_or(|idx| {
                    p.gpu_indices
                        .as_ref()
                        .is_some_and(|gpus| gpus.contains(&(idx as usize)))
                })
            })
            .map(|p| {
                json!({
                    "pid": p.pid,
                    "name": p.name,
                    "gpu_indices": p.gpu_indices,
                    "gpu_memory_bytes": p.total_gpu_memory_bytes,
                    "gpu_memory_mb": p.total_gpu_memory_bytes.map(|b| b / 1024 / 1024),
                    "cpu_percent": p.cpu_percent,
                    "system_memory_mb": p.memory_bytes / 1024 / 1024,
                })
            })
            .collect();

        Ok(json!({
            "count": filtered.len(),
            "processes": filtered
        }))
    }

    /// Reject an explicit `gpu_index` that names no device.
    ///
    /// The tools taking an optional index filtered the snapshot list by it and
    /// returned whatever survived, so asking about a GPU that does not exist produced
    /// `{"success": true, "data": []}`. An agent renders that as "nothing to report"
    /// — silence that reads as reassurance — when the truthful answer is that there
    /// is no such device. `get_gpu_details`, which takes a required index, already
    /// errors with this wording; these now match it.
    fn check_gpu_index(gpu_index: Option<u64>, count: usize) -> Result<()> {
        match gpu_index {
            Some(i) if i as usize >= count => Err(IronError::InvalidArgument(format!(
                "GPU index {} not found",
                i
            ))),
            _ => Ok(()),
        }
    }

    pub(crate) fn tool_get_gpu_utilization(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let gpu_index = params.get("gpu_index").and_then(|v| v.as_u64());

        let gpus = self.gpus.as_ref().ok_or_else(|| self.gpu_unavailable())?;

        let snapshots = gpus
            .snapshot_all()
            .map_err(|e| IronError::GpuError(e.to_string()))?;
        Self::check_gpu_index(gpu_index, snapshots.len())?;

        let util: Vec<_> = snapshots
            .iter()
            .enumerate()
            .filter(|(idx, _)| gpu_index.map(|i| *idx == i as usize).unwrap_or(true))
            .map(|(idx, s)| {
                json!({
                    "index": idx,
                    "name": s.static_info.name,
                    "gpu_percent": s.dynamic_info.utilization,
                })
            })
            .collect();

        Ok(json!(util))
    }

    pub(crate) fn tool_get_gpu_memory(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let gpu_index = params.get("gpu_index").and_then(|v| v.as_u64());

        let gpus = self.gpus.as_ref().ok_or_else(|| self.gpu_unavailable())?;

        let snapshots = gpus
            .snapshot_all()
            .map_err(|e| IronError::GpuError(e.to_string()))?;
        Self::check_gpu_index(gpu_index, snapshots.len())?;

        let mem: Vec<_> = snapshots
            .iter()
            .enumerate()
            .filter(|(idx, _)| gpu_index.map(|i| *idx == i as usize).unwrap_or(true))
            .map(|(idx, s)| {
                json!({
                    "index": idx,
                    "name": s.static_info.name,
                    "total_bytes": s.dynamic_info.memory.total,
                    "used_bytes": s.dynamic_info.memory.used,
                    "free_bytes": s.dynamic_info.memory.free,
                    "total_mb": s.dynamic_info.memory.total.map(|v| v / 1024 / 1024),
                    "used_mb": s.dynamic_info.memory.used.map(|v| v / 1024 / 1024),
                    "free_mb": s.dynamic_info.memory.free.map(|v| v / 1024 / 1024),
                    "usage_percent": s.dynamic_info.memory.utilization
                })
            })
            .collect();

        Ok(json!(mem))
    }

    pub(crate) fn tool_get_gpu_temperature(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let gpu_index = params.get("gpu_index").and_then(|v| v.as_u64());

        let gpus = self.gpus.as_ref().ok_or_else(|| self.gpu_unavailable())?;

        let snapshots = gpus
            .snapshot_all()
            .map_err(|e| IronError::GpuError(e.to_string()))?;
        Self::check_gpu_index(gpu_index, snapshots.len())?;

        let temps: Vec<_> = snapshots
            .iter()
            .enumerate()
            .filter(|(idx, _)| gpu_index.map(|i| *idx == i as usize).unwrap_or(true))
            .map(|(idx, s)| {
                json!({
                    "index": idx,
                    "name": s.static_info.name,
                    "temperature_c": s.dynamic_info.thermal.temperature,
                    "max_temperature_c": s.dynamic_info.thermal.max_temperature,
                    "critical_temperature_c": s.dynamic_info.thermal.critical_temperature,
                    "fan_speed_percent": s.dynamic_info.thermal.fan_speed,
                    "fan_rpm": s.dynamic_info.thermal.fan_rpm,
                })
            })
            .collect();

        Ok(json!(temps))
    }

    pub(crate) fn tool_get_gpu_power(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let gpu_index = params.get("gpu_index").and_then(|v| v.as_u64());

        let gpus = self.gpus.as_ref().ok_or_else(|| self.gpu_unavailable())?;

        let snapshots = gpus
            .snapshot_all()
            .map_err(|e| IronError::GpuError(e.to_string()))?;
        Self::check_gpu_index(gpu_index, snapshots.len())?;

        let power: Vec<_> = snapshots
            .iter()
            .enumerate()
            .filter(|(idx, _)| gpu_index.map(|i| *idx == i as usize).unwrap_or(true))
            .map(|(idx, s)| {
                json!({
                    "index": idx,
                    "name": s.static_info.name,
                    "current_watts": s.dynamic_info.power.draw.map(|p| p as f32 / 1000.0),
                    "limit_watts": s.dynamic_info.power.limit.map(|p| p as f32 / 1000.0),
                    "default_limit_watts": s.dynamic_info.power.default_limit.map(|p| p as f32 / 1000.0),
                })
            })
            .collect();

        Ok(json!(power))
    }

    // ============== CPU Tools ==============

    pub(crate) fn tool_get_cpu_status(
        &mut self,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        #[cfg(target_os = "linux")]
        {
            use crate::platform::linux::cpu;
            let stats = cpu::read_cpu_stats().map_err(|e| IronError::CpuError(e.to_string()))?;

            Ok(json!({
                "core_count": stats.cores.len(),
                "total": {
                    "user_percent": stats.total.user,
                    "system_percent": stats.total.system,
                    "nice_percent": stats.total.nice,
                    "idle_percent": stats.total.idle,
                    "usage_percent": 100.0 - stats.total.idle,
                },
                "model": stats.cores.first().and_then(|c| c.model.clone()),
                // Null `model` carries its reason, as the other nullable
                // fields in this file do.
                "model_unavailable_reason": stats.cores.first().and_then(|c| c.model.as_ref()).is_none().then_some("the platform reported no CPU model name"),
            }))
        }

        #[cfg(target_os = "windows")]
        {
            use crate::platform::windows;
            let stats =
                windows::read_cpu_stats().map_err(|e| IronError::CpuError(e.to_string()))?;

            Ok(json!({
                "core_count": stats.cores.len(),
                "total": {
                    "user_percent": stats.total.user,
                    "system_percent": stats.total.system,
                    "nice_percent": stats.total.nice,
                    "idle_percent": stats.total.idle,
                    "usage_percent": 100.0 - stats.total.idle,
                },
                "model": stats.cores.first().and_then(|c| c.model.clone()),
                // Null `model` carries its reason, as the other nullable
                // fields in this file do.
                "model_unavailable_reason": stats.cores.first().and_then(|c| c.model.as_ref()).is_none().then_some("the platform reported no CPU model name"),
            }))
        }

        // macOS. This arm used to shell out to `sysctl vm.loadavg` and publish
        // `load / ncpu * 100` as `usage_percent`. Load average is not
        // utilization: it counts runnable and uninterruptible tasks, so a box
        // blocked on disk reads high while its cores idle, and a saturated one
        // with no queue reads low. It also fell back to 0.0 when the sysctl
        // failed, reporting an idle machine, and named an unreadable CPU
        // literally "CPU".
        //
        // `platform::macos::read_cpu_stats` has existed since 5.2.0 and was
        // wired only into the ontology. This is the fourth consumer found
        // fabricating alongside a real reader it never adopted. Adding a
        // reader is not the same as adopting it.
        #[cfg(not(any(target_os = "linux", target_os = "windows")))]
        {
            let stats = crate::platform::macos::read_cpu_stats()
                .map_err(|e| IronError::CpuError(e.to_string()))?;

            Ok(json!({
                "core_count": stats.cores.len(),
                "total": {
                    "user_percent": stats.total.user,
                    "system_percent": stats.total.system,
                    "nice_percent": stats.total.nice,
                    "idle_percent": stats.total.idle,
                    "usage_percent": 100.0 - stats.total.idle,
                },
                "model": stats.cores.first().and_then(|c| c.model.clone()),
                // Null `model` carries its reason, as the other nullable
                // fields in this file do.
                "model_unavailable_reason": stats.cores.first().and_then(|c| c.model.as_ref()).is_none().then_some("the platform reported no CPU model name"),
            }))
        }
    }

    pub(crate) fn tool_get_cpu_cores(
        &mut self,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        #[cfg(target_os = "linux")]
        {
            use crate::platform::linux::cpu;
            let stats = cpu::read_cpu_stats().map_err(|e| IronError::CpuError(e.to_string()))?;

            let cores: Vec<_> = stats
                .cores
                .iter()
                .map(|c| {
                    json!({
                        "id": c.id,
                        "online": c.online,
                        "online_unavailable_reason": c.online.is_none().then_some("core online state was not read"),
                        "governor": c.governor,
                        "model": c.model,
                        "model_unavailable_reason": c.model.is_none().then_some("the platform reported no CPU model name"),
                        "frequency_mhz": c.frequency.as_ref().map(|f| f.current),
                        "user_percent": c.user,
                        "system_percent": c.system,
                        "idle_percent": c.idle,
                    })
                })
                .collect();

            Ok(json!(cores))
        }

        #[cfg(target_os = "windows")]
        {
            use crate::platform::windows;
            let stats =
                windows::read_cpu_stats().map_err(|e| IronError::CpuError(e.to_string()))?;

            let cores: Vec<_> = stats
                .cores
                .iter()
                .map(|c| {
                    json!({
                        "id": c.id,
                        "online": c.online,
                        "online_unavailable_reason": c.online.is_none().then_some("core online state was not read"),
                        "governor": c.governor,
                        "model": c.model,
                        "model_unavailable_reason": c.model.is_none().then_some("the platform reported no CPU model name"),
                        "frequency_mhz": c.frequency.as_ref().map(|f| f.current),
                        "user_percent": c.user,
                        "system_percent": c.system,
                        "idle_percent": c.idle,
                    })
                })
                .collect();

            Ok(json!(cores))
        }

        #[cfg(not(any(target_os = "linux", target_os = "windows")))]
        {
            use std::process::Command;
            let sysctl = |key: &str| -> Option<String> {
                Command::new("sysctl")
                    .args(["-n", key])
                    .output()
                    .ok()
                    .filter(|o| o.status.success())
                    .and_then(|o| String::from_utf8(o.stdout).ok())
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
            };

            // `null`, not the literal string "CPU". A placeholder model name
            // handed to an agent is a name it will repeat back.
            let model = sysctl("machdep.cpu.brand_string");

            // `hw.cpufrequency` does not exist on Apple Silicon -- Apple removed
            // it with the ARM transition -- so this parsed to `None` and
            // `unwrap_or(0)` published `"frequency_mhz": 0` for every core of
            // every M-series Mac. Zero hertz is not a clock, and this is the
            // agent surface, where a fabricated number becomes a premise.
            //
            // It is also one figure repeated across every core, which is the
            // defect `24a7314` fixed on the macOS silicon reader and `f5a54ee`
            // fixed on the Windows one. The value is per-machine, so it is
            // reported once per core only because the shape demands it; when it
            // is absent every core says so rather than saying zero.
            let freq_mhz = sysctl("hw.cpufrequency")
                .and_then(|s| s.parse::<u64>().ok())
                .map(|hz| hz / 1_000_000);

            // `"online": true` was a literal on every core. Nothing on this
            // platform reads core state, so the field is `null` (unknown)
            // rather than an assertion that each core is up.
            let ncpu = num_cpus::get();
            let cores: Vec<_> = (0..ncpu)
                .map(|i| {
                    json!({
                        "id": i, "online": null, "model": model,
                        "online_unavailable_reason": "core online state is not read on this platform",
                        "model_unavailable_reason": model.is_none().then_some("machdep.cpu.brand_string was not readable"),
                        "frequency_mhz": freq_mhz,
                    })
                })
                .collect();
            Ok(json!(cores))
        }
    }

    pub(crate) fn tool_get_cpu_frequency(
        &mut self,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        #[cfg(target_os = "linux")]
        {
            use crate::platform::linux::cpu;
            let stats = cpu::read_cpu_stats().map_err(|e| IronError::CpuError(e.to_string()))?;

            let freqs: Vec<_> = stats
                .cores
                .iter()
                .filter_map(|c| {
                    c.frequency.as_ref().map(|f| {
                        json!({
                            "core_id": c.id,
                            "current_mhz": f.current,
                            "min_mhz": f.min,
                            "max_mhz": f.max,
                        })
                    })
                })
                .collect();

            Ok(json!(freqs))
        }

        #[cfg(target_os = "windows")]
        {
            use crate::platform::windows;
            let stats =
                windows::read_cpu_stats().map_err(|e| IronError::CpuError(e.to_string()))?;

            let freqs: Vec<_> = stats
                .cores
                .iter()
                .filter_map(|c| {
                    c.frequency.as_ref().map(|f| {
                        json!({
                            "core_id": c.id,
                            "current_mhz": f.current,
                            "min_mhz": f.min,
                            "max_mhz": f.max,
                        })
                    })
                })
                .collect();

            Ok(json!(freqs))
        }

        // macOS, through the same reader the other two arms use.
        //
        // This shelled out to `hw.cpufrequency`, an Intel-era sysctl that does
        // not exist on Apple Silicon at all, and fell back to `0` -- so every
        // core of every M-series Mac was published to an agent as
        // `current_mhz: 0, min_mhz: 0, max_mhz: 0`. `min` fell back to
        // `freq_hz / 2` and `max` to `freq_hz`, so the zero propagated into all
        // three.
        //
        // `platform::macos::read_cpu_stats` sets `frequency: None` and says why
        // in a comment: "No unelevated source of live per-core frequency on
        // macOS. `None` says that; a nominal figure would repeat the mistake
        // Windows makes with `CurrentMhz`." The tool surface was making exactly
        // that mistake, one function away from the reader that had decided not
        // to. **A reader is not adopted until its callers use it**, and this is
        // the fifth consumer in this crate found fabricating beside one.
        //
        // The `filter_map` is the same as the Linux and Windows arms above, so
        // a platform reporting no per-core frequency yields an empty array --
        // the honest answer, and one an agent can act on.
        #[cfg(not(any(target_os = "linux", target_os = "windows")))]
        {
            let stats = crate::platform::macos::read_cpu_stats()
                .map_err(|e| IronError::CpuError(e.to_string()))?;

            let freqs: Vec<_> = stats
                .cores
                .iter()
                .filter_map(|c| {
                    c.frequency.as_ref().map(|f| {
                        json!({
                            "core_id": c.id,
                            "current_mhz": f.current,
                            "min_mhz": f.min,
                            "max_mhz": f.max,
                        })
                    })
                })
                .collect();

            Ok(json!(freqs))
        }
    }

    // ============== Memory Tools ==============

    pub(crate) fn tool_get_memory_status(
        &mut self,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        #[cfg(target_os = "linux")]
        {
            use crate::platform::linux::memory;
            let stats =
                memory::read_memory_stats().map_err(|e| IronError::MemoryError(e.to_string()))?;

            Ok(json!({
                "ram": {
                    "total_mb": stats.ram.total / 1024,
                    "used_mb": stats.ram.used / 1024,
                    "free_mb": stats.ram.free.map(|v| v / 1024),
                    "usage_percent": stats.ram_usage_percent(),
                },
                // `null`, not `0`. `SwapInfo` carries `Option` since 15a60ab
                // precisely so an unread pagefile is distinguishable from an
                // empty one, and `used_or_zero()` throws that away at the point
                // where an agent reads it. A zero here is the sentence "nothing
                // is paged out", which is a measurement nobody took.
                "swap": {
                    "total_mb": stats.swap.total.map(|v| v / 1024),
                    "used_mb": stats.swap.used.map(|v| v / 1024),
                    "usage_percent": match (stats.swap.total, stats.swap.used) {
                        (Some(t), Some(u)) if t > 0 => json!(u as f64 / t as f64 * 100.0),
                        _ => serde_json::Value::Null,
                    },
                }
            }))
        }

        #[cfg(target_os = "windows")]
        {
            use crate::platform::windows;
            let stats =
                windows::read_memory_stats().map_err(|e| IronError::MemoryError(e.to_string()))?;

            Ok(json!({
                "ram": {
                    "total_mb": stats.ram.total / 1024,
                    "used_mb": stats.ram.used / 1024,
                    "free_mb": stats.ram.free.map(|v| v / 1024),
                    "usage_percent": stats.ram_usage_percent(),
                },
                // `null`, not `0`. `SwapInfo` carries `Option` since 15a60ab
                // precisely so an unread pagefile is distinguishable from an
                // empty one, and `used_or_zero()` throws that away at the point
                // where an agent reads it. A zero here is the sentence "nothing
                // is paged out", which is a measurement nobody took.
                "swap": {
                    "total_mb": stats.swap.total.map(|v| v / 1024),
                    "used_mb": stats.swap.used.map(|v| v / 1024),
                    "usage_percent": match (stats.swap.total, stats.swap.used) {
                        (Some(t), Some(u)) if t > 0 => json!(u as f64 / t as f64 * 100.0),
                        _ => serde_json::Value::Null,
                    },
                }
            }))
        }

        // Was hand-rolled from `sysctl` and `vm_stat`, with four defects an
        // agent had no way to see: a hardcoded 16384-byte page size ("Apple
        // Silicon default") that reports memory 4x too large on an Intel Mac; a
        // failed `vm_stat` falling to zero pages, which publishes 100% memory
        // used; a failed `hw.memsize` giving a total of 0; and an unreadable
        // `vm.swapusage` reported as no swap -- the exact claim the `SwapInfo`
        // `Option` refactor was done to stop making.
        //
        // `platform::macos::read_memory_stats` has existed since 5.2.0. This is
        // the third consumer found still fabricating around it, after the
        // ontology resolver adopted it and `MonitoringBackend` did not.
        #[cfg(target_os = "macos")]
        {
            let stats = crate::platform::macos::read_memory_stats()
                .map_err(|e| IronError::MemoryError(e.to_string()))?;

            Ok(json!({
                "ram": {
                    "total_mb": stats.ram.total / 1024,
                    "used_mb": stats.ram.used / 1024,
                    "free_mb": stats.ram.free.map(|v| v / 1024),
                    "usage_percent": stats.ram_usage_percent(),
                },
                // `null` rather than 0 where the platform reported no swap
                // figure. An agent reading 0 cannot tell "no swap configured"
                // from "swap was not readable"; `null` says which.
                "swap": {
                    "total_mb": stats.swap.total.map(|t| t / 1024),
                    "used_mb": stats.swap.used.map(|u| u / 1024),
                    "usage_percent": stats.swap_usage_percent(),
                }
            }))
        }

        #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
        {
            Err(IronError::UnsupportedPlatform(
                "memory is read through per-platform APIs and this platform has none implemented"
                    .into(),
            ))
        }
    }

    pub(crate) fn tool_get_memory_breakdown(
        &mut self,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        #[cfg(target_os = "linux")]
        {
            use crate::platform::linux::memory;
            let stats =
                memory::read_memory_stats().map_err(|e| IronError::MemoryError(e.to_string()))?;

            Ok(json!({
                "total_kb": stats.ram.total,
                "used_kb": stats.ram.used,
                "free_kb": stats.ram.free,
                "buffers_kb": stats.ram.buffers,
                "cached_kb": stats.ram.cached,
                "shared_kb": stats.ram.shared,
                "total_mb": stats.ram.total / 1024,
                "used_mb": stats.ram.used / 1024,
                "free_mb": stats.ram.free.map(|v| v / 1024),
                "buffers_mb": stats.ram.buffers.map(|v| v / 1024),
                "cached_mb": stats.ram.cached.map(|v| v / 1024),
            }))
        }

        #[cfg(target_os = "windows")]
        {
            use crate::platform::windows;
            let stats =
                windows::read_memory_stats().map_err(|e| IronError::MemoryError(e.to_string()))?;

            Ok(json!({
                "total_kb": stats.ram.total,
                "used_kb": stats.ram.used,
                "free_kb": stats.ram.free,
                "buffers_kb": stats.ram.buffers,
                "cached_kb": stats.ram.cached,
                "shared_kb": stats.ram.shared,
                "total_mb": stats.ram.total / 1024,
                "used_mb": stats.ram.used / 1024,
                "free_mb": stats.ram.free.map(|v| v / 1024),
                "buffers_mb": stats.ram.buffers.map(|v| v / 1024),
                "cached_mb": stats.ram.cached.map(|v| v / 1024),
            }))
        }

        // macOS, through the same reader the other two arms use.
        //
        // This arm hand-rolled `sysctl hw.memsize` and `vm_stat` and carried
        // every defect the handoff records fixing in `tool_get_memory_status`,
        // which is the function immediately above it: a hardcoded
        // `page_size = 16384` that reports memory four times too large on an
        // Intel Mac, a failed `hw.memsize` giving a total of 0, and a failed
        // `vm_stat` falling to zero free pages -- which publishes 100% memory
        // used, on a machine nobody measured.
        //
        // It also emitted `buffers_kb: 0` and `shared_kb: 0` where the Linux
        // and Windows arms publish `Option`s, so two absences arrived as
        // measurements of zero.
        //
        // The fix there was to adopt `platform::macos::read_memory_stats`. The
        // fix here is the same, and the fact that it had to be made twice is
        // the point: **the defect was fixed per function rather than per
        // cause**, and the function next door kept it.
        #[cfg(not(any(target_os = "linux", target_os = "windows")))]
        {
            let stats = crate::platform::macos::read_memory_stats()
                .map_err(|e| IronError::MemoryError(e.to_string()))?;

            Ok(json!({
                "total_kb": stats.ram.total,
                "used_kb": stats.ram.used,
                "free_kb": stats.ram.free,
                "buffers_kb": stats.ram.buffers,
                "cached_kb": stats.ram.cached,
                "shared_kb": stats.ram.shared,
                "total_mb": stats.ram.total / 1024,
                "used_mb": stats.ram.used / 1024,
                "free_mb": stats.ram.free.map(|v| v / 1024),
                "buffers_mb": stats.ram.buffers.map(|v| v / 1024),
                "cached_mb": stats.ram.cached.map(|v| v / 1024),
            }))
        }
    }

    pub(crate) fn tool_get_swap_status(
        &mut self,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        #[cfg(target_os = "linux")]
        {
            use crate::platform::linux::memory;
            let stats =
                memory::read_memory_stats().map_err(|e| IronError::MemoryError(e.to_string()))?;

            Ok(json!({
                "total_kb": stats.swap.total,
                "used_kb": stats.swap.used,
                "cached_kb": stats.swap.cached,
                // See the memory tool: absent rather than zero, because an
                // unread pagefile is not an idle one.
                "total_mb": stats.swap.total.map(|v| v / 1024),
                "used_mb": stats.swap.used.map(|v| v / 1024),
                "usage_percent": match (stats.swap.total, stats.swap.used) {
                    (Some(t), Some(u)) if t > 0 => json!(u as f64 / t as f64 * 100.0),
                    _ => serde_json::Value::Null,
                },
            }))
        }

        #[cfg(target_os = "windows")]
        {
            use crate::platform::windows;
            let stats =
                windows::read_memory_stats().map_err(|e| IronError::MemoryError(e.to_string()))?;

            Ok(json!({
                "total_kb": stats.swap.total,
                "used_kb": stats.swap.used,
                "cached_kb": stats.swap.cached,
                // See the memory tool: absent rather than zero, because an
                // unread pagefile is not an idle one.
                "total_mb": stats.swap.total.map(|v| v / 1024),
                "used_mb": stats.swap.used.map(|v| v / 1024),
                "usage_percent": match (stats.swap.total, stats.swap.used) {
                    (Some(t), Some(u)) if t > 0 => json!(u as f64 / t as f64 * 100.0),
                    _ => serde_json::Value::Null,
                },
            }))
        }

        // macOS, through the same reader the other two arms use.
        //
        // This arm was already honest -- every figure an `Option`, `None` where
        // the sysctl did not answer, after the fix whose comment it carried:
        // "a failed `sysctl` used to land in `unwrap_or_default()`, giving an
        // empty string that both parses read as `0`". What it still had was a
        // **second parser for `vm.swapusage`**, beside `platform::macos`'s
        // `parse_swapusage`, which `read_memory_stats` already calls.
        //
        // Two parsers for one sysctl is how the two Prometheus renderers came
        // to disagree by a factor of 1024 (`367429a`): both were correct when
        // written, and only one of them was corrected. The rule from `a42350d`
        // applies to a *right* duplicate as much as a wrong one -- the question
        // is where else the reader is hand-rolled, not where else it is broken.
        #[cfg(not(any(target_os = "linux", target_os = "windows")))]
        {
            let stats = crate::platform::macos::read_memory_stats()
                .map_err(|e| IronError::MemoryError(e.to_string()))?;

            Ok(json!({
                "total_kb": stats.swap.total,
                "used_kb": stats.swap.used,
                "cached_kb": stats.swap.cached,
                "total_mb": stats.swap.total.map(|v| v / 1024),
                "used_mb": stats.swap.used.map(|v| v / 1024),
                "usage_percent": match (stats.swap.total, stats.swap.used) {
                    (Some(t), Some(u)) if t > 0 => json!(u as f64 / t as f64 * 100.0),
                    // A machine with a zero-sized swap file is not 0% used, it
                    // has no ratio to report.
                    _ => serde_json::Value::Null,
                },
            }))
        }
    }

    // ============== Disk Tools ==============

    pub(crate) fn tool_get_disk_list(
        &mut self,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let disks =
            crate::disk::enumerate_disks().map_err(|e| IronError::DiskError(e.to_string()))?;

        // A disk that was enumerated but whose query failed is reported as
        // that disk, with its index and the error. Dropping it with
        // `filter_map` made it indistinguishable from a disk that is absent.
        let list: Vec<_> = disks
            .iter()
            .enumerate()
            .map(|(index, d)| match d.info() {
                Ok(info) => json!({
                    "name": info.name,
                    "model": info.model,
                    // Integer division truncated every drive smaller than a
                    // gibibyte to `size_gb: 0`. The USB gadget on the
                    // development machine is 16,450,560 bytes and reported
                    // as sizeless, which is a different claim from small.
                    // The exact figure goes alongside so the answer is
                    // never rounded away.
                    "size_bytes": info.capacity,
                    "size_gb": info.capacity.map(|c| c as f64 / 1024.0 / 1024.0 / 1024.0),
                    // `Unknown` is a classification nobody made, so it is null.
                    "disk_type": disk_type_text(info.disk_type),
"disk_type_unavailable_reason": (info.disk_type == crate::disk::DiskType::Unknown).then_some("the driver did not classify this disk"),
                }),
                Err(e) => json!({
                    "index": index,
                    "name": null,
                    "error": e.to_string(),
                }),
            })
            .collect();

        Ok(json!(list))
    }

    pub(crate) fn tool_get_disk_details(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let disk_name = params
            .get("disk_name")
            .and_then(|v| v.as_str())
            .ok_or_else(|| IronError::InvalidArgument("disk_name is required".to_string()))?;

        let disks =
            crate::disk::enumerate_disks().map_err(|e| IronError::DiskError(e.to_string()))?;

        let disk = disks
            .iter()
            .find(|d| {
                d.info()
                    .map(|i| i.name.contains(disk_name))
                    .unwrap_or(false)
            })
            .ok_or_else(|| IronError::InvalidArgument(format!("Disk {} not found", disk_name)))?;

        let info = disk
            .info()
            .map_err(|e| IronError::DiskError(e.to_string()))?;

        Ok(json!({
            "name": info.name,
            "model": info.model,
            "serial": info.serial,
            "firmware": info.firmware,
            // See `tool_get_disk_list`: the exact byte count alongside a
            // figure that would otherwise truncate small media to zero.
            "size_bytes": info.capacity,
            "size_gb": info.capacity.map(|c| c as f64 / 1024.0 / 1024.0 / 1024.0),
            "disk_type": disk_type_text(info.disk_type),
        "disk_type_unavailable_reason": (info.disk_type == crate::disk::DiskType::Unknown).then_some("the driver did not classify this disk"),
            "temperature_c": disk.temperature().ok().flatten(),
        }))
    }

    pub(crate) fn tool_get_disk_io(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let disk_name = params.get("disk_name").and_then(|v| v.as_str());

        let disks =
            crate::disk::enumerate_disks().map_err(|e| IronError::DiskError(e.to_string()))?;

        // A disk whose name or counters cannot be read cannot be matched
        // against the filter, so it is reported with its error rather than
        // silently left out of the answer.
        let io_stats: Vec<_> = disks
            .iter()
            .enumerate()
            .filter_map(|(index, d)| {
                let info = match d.info() {
                    Ok(info) => info,
                    Err(e) => {
                        return Some(json!({
                            "index": index,
                            "name": null,
                            "error": e.to_string(),
                        }))
                    }
                };
                if let Some(name) = disk_name {
                    if !info.name.contains(name) {
                        return None;
                    }
                }
                Some(match d.io_stats() {
                    Ok(io) => json!({
                        "name": info.name,
                        "bytes_read": io.read_bytes,
                        "bytes_written": io.write_bytes,
                        "read_ops": io.read_ops,
                        "write_ops": io.write_ops,
                    }),
                    Err(e) => json!({
                        "name": info.name,
                        "error": e.to_string(),
                    }),
                })
            })
            .collect();

        Ok(json!(io_stats))
    }

    pub(crate) fn tool_get_disk_health(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let disk_name = params.get("disk_name").and_then(|v| v.as_str());

        let disks =
            crate::disk::enumerate_disks().map_err(|e| IronError::DiskError(e.to_string()))?;

        // As in `tool_get_disk_io`: an unreadable disk is reported as that
        // disk, with its error, not dropped.
        let health: Vec<_> = disks
            .iter()
            .enumerate()
            .filter_map(|(index, d)| {
                let info = match d.info() {
                    Ok(info) => info,
                    Err(e) => {
                        return Some(json!({
                            "index": index,
                            "name": null,
                            "error": e.to_string(),
                        }))
                    }
                };
                if let Some(name) = disk_name {
                    if !info.name.contains(name) {
                        return None;
                    }
                }
                Some(match d.health() {
                    Ok(h) => json!({
                        "name": info.name,
                        // `Unknown` means the health was not determined, so it is null.
                        "overall_health": (h != crate::disk::DiskHealth::Unknown).then(|| format!("{:?}", h)),
                        "temperature_c": d.temperature().ok().flatten(),
                    }),
                    Err(e) => json!({
                        "name": info.name,
                        "error": e.to_string(),
                    }),
                })
            })
            .collect();

        Ok(json!(health))
    }

    // ============== Network Tools ==============

    pub(crate) fn tool_get_network_interfaces(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let active_only = params
            .get("active_only")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);

        let net_mon = self.network_monitor.as_mut().ok_or_else(|| {
            IronError::NotImplemented("Network monitor not available".to_string())
        })?;

        let interfaces = if active_only {
            net_mon
                .active_interfaces()
                .map_err(|e| IronError::Network(e.to_string()))?
        } else {
            net_mon
                .interfaces()
                .map_err(|e| IronError::Network(e.to_string()))?
        };

        let list: Vec<_> = interfaces
            .iter()
            .map(|i| {
                json!({
                    "name": i.name,
                    "is_up": i.is_up,
                    "is_running": i.is_running,
                    "rx_bytes": i.rx_bytes,
                    "tx_bytes": i.tx_bytes,
                    "rx_mb": i.rx_bytes / 1024 / 1024,
                    "tx_mb": i.tx_bytes / 1024 / 1024,
                })
            })
            .collect();

        Ok(json!(list))
    }

    pub(crate) fn tool_get_network_bandwidth(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let interface_name = params.get("interface_name").and_then(|v| v.as_str());

        let net_mon = self.network_monitor.as_mut().ok_or_else(|| {
            IronError::NotImplemented("Network monitor not available".to_string())
        })?;

        let interfaces = net_mon
            .active_interfaces()
            .map_err(|e| IronError::Network(e.to_string()))?;

        let bandwidth: Vec<_> = interfaces
            .iter()
            .filter(|i| interface_name.map(|name| i.name == name).unwrap_or(true))
            .map(|i| {
                // `null` on the first call for an interface: a rate needs two
                // samples. This used to report `0.0`, which reads as an idle
                // link rather than as an unanswered question -- and because the
                // baseline was overwritten before the subtraction, it reported
                // `0.0` on every call, forever.
                let rate = net_mon.bandwidth_rate(&i.name, i);
                json!({
                    "name": i.name,
                    "rx_bytes_per_sec": rate.map(|(rx, _)| rx),
                    "tx_bytes_per_sec": rate.map(|(_, tx)| tx),
                    "rx_mbps": rate.map(|(rx, _)| rx / 1_000_000.0 * 8.0),
                    "tx_mbps": rate.map(|(_, tx)| tx / 1_000_000.0 * 8.0),
                })
            })
            .collect();

        Ok(json!(bandwidth))
    }

    pub(crate) fn tool_get_interface_details(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let interface_name = params
            .get("interface_name")
            .and_then(|v| v.as_str())
            .ok_or_else(|| IronError::InvalidArgument("interface_name is required".to_string()))?;

        let net_mon = self.network_monitor.as_mut().ok_or_else(|| {
            IronError::NotImplemented("Network monitor not available".to_string())
        })?;

        let iface = net_mon
            .interface_by_name(interface_name)
            .map_err(|e| IronError::Network(e.to_string()))?
            .ok_or_else(|| {
                IronError::InvalidArgument(format!("Interface {} not found", interface_name))
            })?;

        // See `tool_get_network_bandwidth`: absent until a second sample.
        let rate = net_mon.bandwidth_rate(&iface.name, &iface);

        Ok(json!({
            "name": iface.name,
            "is_up": iface.is_up,
            "is_running": iface.is_running,
            "rx_bytes": iface.rx_bytes,
            "tx_bytes": iface.tx_bytes,
            "rx_packets": iface.rx_packets,
            "tx_packets": iface.tx_packets,
            "rx_errors": iface.rx_errors,
            "tx_errors": iface.tx_errors,
            "rx_drops": iface.rx_drops,
            "tx_drops": iface.tx_drops,
            "rx_rate_bytes_sec": rate.map(|(rx, _)| rx),
            "tx_rate_bytes_sec": rate.map(|(_, tx)| tx),
        }))
    }

    // ============== Process Tools ==============

    pub(crate) fn tool_get_process_list(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let limit = params.get("limit").and_then(|v| v.as_u64()).unwrap_or(50) as usize;
        let sort_by = params
            .get("sort_by")
            .and_then(|v| v.as_str())
            .unwrap_or("cpu");

        let proc_mon = self.process_monitor.as_mut().ok_or_else(|| {
            IronError::NotImplemented("Process monitor not available".to_string())
        })?;

        let mut procs = proc_mon
            .processes()
            .map_err(|e| IronError::ProcessError(e.to_string()))?;

        // Sort
        match sort_by {
            "cpu" => procs.sort_by(|a, b| {
                b.cpu_percent
                    .partial_cmp(&a.cpu_percent)
                    .unwrap_or(std::cmp::Ordering::Equal)
            }),
            "memory" => procs.sort_by_key(|p| std::cmp::Reverse(p.memory_bytes)),
            "gpu_memory" => procs.sort_by_key(|p| std::cmp::Reverse(p.total_gpu_memory_bytes)),
            "name" => procs.sort_by(|a, b| a.name.cmp(&b.name)),
            "pid" => procs.sort_by_key(|a| a.pid),
            _ => {}
        }

        let list: Vec<_> = procs
            .iter()
            .take(limit)
            .map(|p| {
                json!({
                    "pid": p.pid,
                    "name": p.name,
                    "cpu_percent": p.cpu_percent,
                    "memory_mb": p.memory_bytes / 1024 / 1024,
                    "gpu_memory_mb": p.total_gpu_memory_bytes.map(|b| b / 1024 / 1024),
                    "thread_count": p.thread_count,
                    "state": p.state,
                })
            })
            .collect();

        Ok(json!({
            "total_count": procs.len(),
            "returned_count": list.len(),
            "sort_by": sort_by,
            "processes": list
        }))
    }

    pub(crate) fn tool_get_process_details(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let pid = params
            .get("pid")
            .and_then(|v| v.as_u64())
            .ok_or_else(|| IronError::InvalidArgument("pid is required".to_string()))?
            as u32;

        let proc_mon = self.process_monitor.as_mut().ok_or_else(|| {
            IronError::NotImplemented("Process monitor not available".to_string())
        })?;

        let proc = proc_mon
            .process_by_pid(pid)
            .map_err(|e| IronError::ProcessError(e.to_string()))?
            .ok_or_else(|| IronError::InvalidArgument(format!("Process {} not found", pid)))?;

        Ok(json!({
            "pid": proc.pid,
            "name": proc.name,
            "state": proc.state,
            "parent_pid": proc.parent_pid,
            "cpu_percent": proc.cpu_percent,
            "memory_bytes": proc.memory_bytes,
            "memory_mb": proc.memory_bytes / 1024 / 1024,
            "virtual_memory_bytes": proc.virtual_memory_bytes,
            "thread_count": proc.thread_count,
            "gpu_indices": proc.gpu_indices,
            "gpu_memory_bytes": proc.total_gpu_memory_bytes,
            "gpu_memory_mb": proc.total_gpu_memory_bytes.map(|b| b / 1024 / 1024),
        }))
    }

    pub(crate) fn tool_get_top_cpu_processes(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let count = params.get("count").and_then(|v| v.as_u64()).unwrap_or(10) as usize;

        let proc_mon = self.process_monitor.as_mut().ok_or_else(|| {
            IronError::NotImplemented("Process monitor not available".to_string())
        })?;

        let top = proc_mon
            .processes_by_cpu()
            .map_err(|e| IronError::ProcessError(e.to_string()))?;

        let list: Vec<_> = top
            .iter()
            .take(count)
            .map(|p| {
                json!({
                    "pid": p.pid,
                    "name": p.name,
                    "cpu_percent": p.cpu_percent,
                    "memory_mb": p.memory_bytes / 1024 / 1024,
                })
            })
            .collect();

        Ok(json!(list))
    }

    pub(crate) fn tool_get_top_memory_processes(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let count = params.get("count").and_then(|v| v.as_u64()).unwrap_or(10) as usize;

        let proc_mon = self.process_monitor.as_mut().ok_or_else(|| {
            IronError::NotImplemented("Process monitor not available".to_string())
        })?;

        let top = proc_mon
            .processes_by_memory()
            .map_err(|e| IronError::ProcessError(e.to_string()))?;

        let list: Vec<_> = top
            .iter()
            .take(count)
            .map(|p| {
                json!({
                    "pid": p.pid,
                    "name": p.name,
                    "memory_bytes": p.memory_bytes,
                    "memory_mb": p.memory_bytes / 1024 / 1024,
                    "memory_display": format!("{} MiB", p.memory_bytes / 1024 / 1024),
                    "cpu_percent": p.cpu_percent,
                })
            })
            .collect();

        Ok(json!(list))
    }

    pub(crate) fn tool_get_top_gpu_processes(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let count = params.get("count").and_then(|v| v.as_u64()).unwrap_or(10) as usize;
        let gpu_index = params.get("gpu_index").and_then(|v| v.as_u64());

        let proc_mon = self.process_monitor.as_mut().ok_or_else(|| {
            IronError::NotImplemented("Process monitor not available".to_string())
        })?;

        let top = proc_mon
            .processes_by_gpu_memory()
            .map_err(|e| IronError::ProcessError(e.to_string()))?;

        let list: Vec<_> = top
            .iter()
            .filter(|p| {
                gpu_index.is_none_or(|idx| {
                    p.gpu_indices
                        .as_ref()
                        .is_some_and(|gpus| gpus.contains(&(idx as usize)))
                })
            })
            .take(count)
            .map(|p| {
                json!({
                    "pid": p.pid,
                    "name": p.name,
                    "gpu_indices": p.gpu_indices,
                    "gpu_memory_bytes": p.total_gpu_memory_bytes,
                    "gpu_memory_mb": p.total_gpu_memory_bytes.map(|b| b / 1024 / 1024),
                    "cpu_percent": p.cpu_percent,
                    "system_memory_mb": p.memory_bytes / 1024 / 1024,
                })
            })
            .collect();

        Ok(json!(list))
    }

    pub(crate) fn tool_search_processes(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let pattern = params
            .get("pattern")
            .and_then(|v| v.as_str())
            .ok_or_else(|| IronError::InvalidArgument("pattern is required".to_string()))?
            .to_lowercase();

        let proc_mon = self.process_monitor.as_mut().ok_or_else(|| {
            IronError::NotImplemented("Process monitor not available".to_string())
        })?;

        let procs = proc_mon
            .processes()
            .map_err(|e| IronError::ProcessError(e.to_string()))?;

        let matches: Vec<_> = procs
            .iter()
            .filter(|p| p.name.to_lowercase().contains(&pattern))
            .map(|p| {
                json!({
                    "pid": p.pid,
                    "name": p.name,
                    "cpu_percent": p.cpu_percent,
                    "memory_mb": p.memory_bytes / 1024 / 1024,
                    "gpu_memory_mb": p.total_gpu_memory_bytes.map(|b| b / 1024 / 1024),
                })
            })
            .collect();

        Ok(json!({
            "pattern": pattern,
            "match_count": matches.len(),
            "processes": matches
        }))
    }

    // ============== Hardware Tools ==============

    pub(crate) fn tool_get_motherboard_sensors(
        &mut self,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let sensors = crate::motherboard::enumerate_sensors()
            .map_err(|e| IronError::HardwareError(e.to_string()))?;

        let mut readings = Vec::new();
        let mut errors = Vec::new();

        // Collect temperature sensors
        for sensor in &sensors {
            match sensor.temperature_sensors() {
                Ok(temps) => {
                    for t in temps {
                        readings.push(json!({
                            "name": t.label,
                            "sensor_type": "temperature",
                            "value": t.temperature,
                            "unit": "°C",
                            "max": t.max,
                            "critical": t.critical,
                        }));
                    }
                }
                Err(e) => errors.push(sensor_error(&format!("{}/temperatures", sensor.name()), e)),
            }

            // Collect voltage rails
            match sensor.voltage_rails() {
                Ok(volts) => {
                    for v in volts {
                        readings.push(json!({
                            "name": v.label,
                            "sensor_type": "voltage",
                            "value": v.voltage,
                            "unit": "V",
                            "min": v.min,
                            "max": v.max,
                        }));
                    }
                }
                Err(e) => errors.push(sensor_error(&format!("{}/voltages", sensor.name()), e)),
            }

            // Collect fan info
            match sensor.fans() {
                Ok(fans) => {
                    for f in fans {
                        readings.push(json!({
                            "name": f.label,
                            "sensor_type": "fan",
                            "value": f.rpm,
                            "unit": "RPM",
                            "min": f.min_rpm,
                            "max": f.max_rpm,
                        }));
                    }
                }
                Err(e) => errors.push(sensor_error(&format!("{}/fans", sensor.name()), e)),
            }
        }

        Ok(sensor_listing("readings", readings, errors))
    }

    pub(crate) fn tool_get_system_temperatures(
        &mut self,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let sensors = crate::motherboard::enumerate_sensors()
            .map_err(|e| IronError::HardwareError(e.to_string()))?;

        let mut temps = Vec::new();
        let mut errors = Vec::new();

        // Get temperatures from motherboard sensors
        for sensor in &sensors {
            match sensor.temperature_sensors() {
                Ok(temp_sensors) => {
                    for t in temp_sensors {
                        temps.push(json!({
                            "name": t.label,
                            "temperature_c": t.temperature,
                            "max_c": t.max,
                            "critical_c": t.critical,
                            "sensor_type": format!("{:?}", t.sensor_type),
                        }));
                    }
                }
                Err(e) => errors.push(sensor_error(&format!("{}/temperatures", sensor.name()), e)),
            }
        }

        // Add GPU temperatures
        if let Some(ref gpus) = self.gpus {
            match gpus.snapshot_all() {
                Ok(snapshots) => {
                    for (idx, s) in snapshots.iter().enumerate() {
                        if let Some(temp) = s.dynamic_info.thermal.temperature {
                            temps.push(json!({
                                "name": format!("GPU {} ({})", idx, s.static_info.name),
                                "temperature_c": temp,
                            }));
                        }
                    }
                }
                Err(e) => errors.push(sensor_error("gpu/snapshot", e)),
            }
        }

        // Add disk temperatures
        match crate::disk::enumerate_disks() {
            Ok(disks) => {
                for (idx, disk) in disks.iter().enumerate() {
                    match (disk.info(), disk.temperature()) {
                        (Ok(info), Ok(Some(temp))) => {
                            temps.push(json!({
                                "name": format!("Disk ({})", info.name),
                                "temperature_c": temp,
                            }));
                        }
                        // A disk with no temperature sensor is an absence, not a failure.
                        (Ok(_), Ok(None)) => {}
                        (Err(e), _) | (_, Err(e)) => {
                            errors.push(sensor_error(&format!("disk[{}]/temperature", idx), e))
                        }
                    }
                }
            }
            Err(e) => errors.push(sensor_error("disks/enumerate", e)),
        }

        Ok(sensor_listing("temperatures", temps, errors))
    }

    pub(crate) fn tool_get_fan_speeds(
        &mut self,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let sensors = crate::motherboard::enumerate_sensors()
            .map_err(|e| IronError::HardwareError(e.to_string()))?;

        let mut fans = Vec::new();
        let mut errors = Vec::new();

        for sensor in &sensors {
            match sensor.fans() {
                Ok(fan_info) => {
                    for f in fan_info {
                        fans.push(json!({
                            "name": f.label,
                            "rpm": f.rpm,
                            "pwm": f.pwm,
                            "controllable": f.controllable,
                        }));
                    }
                }
                Err(e) => errors.push(sensor_error(&format!("{}/fans", sensor.name()), e)),
            }
        }

        Ok(sensor_listing("fans", fans, errors))
    }

    pub(crate) fn tool_get_voltage_rails(
        &mut self,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let sensors = crate::motherboard::enumerate_sensors()
            .map_err(|e| IronError::HardwareError(e.to_string()))?;

        let mut voltages = Vec::new();
        let mut errors = Vec::new();

        for sensor in &sensors {
            match sensor.voltage_rails() {
                Ok(voltage_rails) => {
                    for v in voltage_rails {
                        voltages.push(json!({
                            "name": v.label,
                            "voltage_v": v.voltage,
                            "min_v": v.min,
                            "max_v": v.max,
                        }));
                    }
                }
                Err(e) => errors.push(sensor_error(&format!("{}/voltages", sensor.name()), e)),
            }
        }

        Ok(sensor_listing("voltage_rails", voltages, errors))
    }

    pub(crate) fn tool_get_driver_info(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let driver_type = params
            .get("driver_type")
            .and_then(|v| v.as_str())
            .unwrap_or("all");

        let drivers = crate::motherboard::get_driver_versions()
            .map_err(|e| IronError::HardwareError(e.to_string()))?;

        let filtered: Vec<_> = drivers
            .iter()
            .filter(|d| {
                driver_type == "all"
                    || matches!(
                        (&d.driver_type, driver_type),
                        (crate::motherboard::DriverType::Gpu, "gpu")
                            | (crate::motherboard::DriverType::Network, "network")
                            | (crate::motherboard::DriverType::Storage, "storage")
                    )
            })
            .map(|d| {
                json!({
                    "name": d.name,
                    "driver_type": format!("{:?}", d.driver_type),
                    "version": d.version,
                    "vendor": d.vendor,
                    "date": d.date,
                })
            })
            .collect();

        Ok(json!(filtered))
    }

    // ============== Audio Tools ==============
    pub(crate) fn tool_get_audio_devices(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        use crate::audio::{AudioDeviceType, AudioMonitor};
        let device_type = params
            .get("device_type")
            .and_then(|v| v.as_str())
            .unwrap_or("all");
        let monitor = AudioMonitor::new().map_err(|e| IronError::HardwareError(e.to_string()))?;
        let devices: Vec<_> = monitor.devices().iter()
            .filter(|d| device_type == "all" || matches!((d.device_type, device_type), (Some(AudioDeviceType::Output), "output") | (Some(AudioDeviceType::Input), "input") | (Some(AudioDeviceType::Duplex), "output") | (Some(AudioDeviceType::Duplex), "input")))
            // `state` is `Option` and was formatted with `{:?}` directly, so an
            // unread state reached agents as the text "None" and a read one as
            // "Some(Active)". Both are null now when not read.
            .map(|d| json!({"id": d.id, "name": d.name, "name_unavailable_reason": d.name.is_none().then_some("the endpoint name was not read"), "type": d.device_type.map(|t| format!("{t:?}")), "state": d.state.map(|s| format!("{s:?}")), "state_unavailable_reason": d.state.is_none().then_some("the endpoint state was not read"), "type_unavailable_reason": d.device_type.is_none().then_some("the device type was not established by the platform"), "is_default": d.is_default, "volume": d.volume, "muted": d.muted}))
            .collect();
        Ok(json!(devices))
    }
    pub(crate) fn tool_get_audio_status(
        &mut self,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        use crate::audio::AudioMonitor;
        let monitor = AudioMonitor::new().map_err(|e| IronError::HardwareError(e.to_string()))?;
        Ok(
            json!({"master_volume": monitor.master_volume(), "is_muted": monitor.is_muted(), "device_count": monitor.devices().len()}),
        )
    }
    // ============== Bluetooth Tools ==============
    pub(crate) fn tool_get_bluetooth_adapters(
        &mut self,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        use crate::bluetooth::BluetoothMonitor;
        let monitor =
            BluetoothMonitor::new().map_err(|e| IronError::HardwareError(e.to_string()))?;
        let adapters: Vec<_> = monitor
            .adapters()
            .iter()
            .map(
                |a| json!({"id": a.id, "name": a.name, "address": a.address, "powered": a.powered}),
            )
            .collect();
        // `available` is null where the adapter walk did not run, with the reason
        // beside it. It was `false` in that case, which says there is no radio.
        let unavailable_reason = (!monitor.adapters_read()).then(|| {
            monitor
                .note()
                .unwrap_or("no Bluetooth reader runs on this platform")
                .to_string()
        });
        Ok(
            json!({"available": monitor.is_available(), "unavailable_reason": unavailable_reason, "adapters": adapters}),
        )
    }
    pub(crate) fn tool_get_bluetooth_devices(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        use crate::bluetooth::{BluetoothDeviceType, BluetoothMonitor, BluetoothState};
        let connected_only = params
            .get("connected_only")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        let monitor =
            BluetoothMonitor::new().map_err(|e| IronError::HardwareError(e.to_string()))?;
        let devices: Vec<_> = monitor.devices().iter().filter(|d| !connected_only || d.state == BluetoothState::Connected).map(|d| json!({"address": d.address, "name": d.name, "type": d.device_type.filter(|t| *t != BluetoothDeviceType::Unknown).map(|t| format!("{t:?}")), "state": (d.state != BluetoothState::Unknown).then(|| format!("{:?}", d.state)), "state_unavailable_reason": (d.state == BluetoothState::Unknown).then_some("the connection state was not read"), "type_unavailable_reason": d.device_type.filter(|t| *t != BluetoothDeviceType::Unknown).is_none().then_some("the device type was not read, or its class of device names no known kind"), "battery_percent": d.battery_percent})).collect();
        Ok(json!(devices))
    }
    // ============== Display Tools ==============
    pub(crate) fn tool_get_display_list(
        &mut self,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        use crate::display::DisplayMonitor;
        let monitor = DisplayMonitor::new().map_err(|e| IronError::HardwareError(e.to_string()))?;
        // `"resolution": "0x0"` went out to agents for any display whose mode
        // was not readable, and `refresh_rate: 0.0` for every display on Linux
        // and macOS, where no reader parses a rate. Both are null now, which an
        // agent can act on; a zero it cannot.
        let displays: Vec<_> = monitor
            .displays()
            .iter()
            .map(|d| {
                json!({
                    "id": d.id,
                    "name": d.name,
                    "manufacturer": d.manufacturer,
                    "connection": connection_text(d.connection),
                    "connection_unavailable_reason": (d.connection == crate::display::DisplayConnection::Unknown).then_some("the display query did not identify the connection"),
                    "is_primary": d.is_primary,
                    "resolution": resolution_text(d),
                    "aspect_ratio": d.aspect_ratio(),
                    "refresh_rate": d.refresh_rate,
                    "brightness": d.brightness,
                    // Null where HDR state was not read, never a mode.
                    "hdr": hdr_text(d.hdr),
                    "hdr_unavailable_reason": hdr_text(d.hdr).is_none().then_some("HDR state was not read"),
                })
            })
            .collect();
        Ok(json!({"count": monitor.count(), "displays": displays}))
    }
    pub(crate) fn tool_get_display_details(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        use crate::display::DisplayMonitor;
        let display_id = params
            .get("display_id")
            .and_then(|v| v.as_str())
            .ok_or_else(|| IronError::InvalidArgument("display_id required".to_string()))?;
        let monitor = DisplayMonitor::new().map_err(|e| IronError::HardwareError(e.to_string()))?;
        let display = monitor
            .displays()
            .iter()
            .find(|d| d.id == display_id)
            .ok_or_else(|| {
                IronError::DeviceNotFound(format!("Display {} not found", display_id))
            })?;
        Ok(json!({
            "id": display.id,
            "name": display.name,
            "manufacturer": display.manufacturer,
            "connection": connection_text(display.connection),
            "connection_unavailable_reason": (display.connection == crate::display::DisplayConnection::Unknown).then_some("the display query did not identify the connection"),
            "is_primary": display.is_primary,
            "width": display.width,
            "height": display.height,
            "resolution": resolution_text(display),
            "aspect_ratio": display.aspect_ratio(),
            "refresh_rate": display.refresh_rate,
            "brightness": display.brightness,
            "hdr": hdr_text(display.hdr),
        }))
    }
    // ============== USB Tools ==============
    pub(crate) fn tool_get_usb_devices(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        use crate::usb::{UsbDeviceClass, UsbMonitor};
        let class_filter = params
            .get("class")
            .and_then(|v| v.as_str())
            .unwrap_or("all");
        let monitor = UsbMonitor::new().map_err(|e| IronError::HardwareError(e.to_string()))?;
        let devices: Vec<_> = monitor
            .devices()
            .iter()
            .filter(|d| {
                class_filter == "all"
                    || matches!(
                        (&d.class, class_filter),
                        (UsbDeviceClass::Audio, "audio")
                            | (UsbDeviceClass::Hid, "hid")
                            | (UsbDeviceClass::MassStorage, "storage")
                            | (UsbDeviceClass::Hub, "hub")
                            | (UsbDeviceClass::Video, "video")
                    )
            })
            .map(usb_device_json)
            .collect();
        Ok(json!(devices))
    }
    pub(crate) fn tool_get_usb_device_details(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        use crate::usb::UsbMonitor;

        // Addressed by `UsbDevice::address`, the same string the ontology uses
        // for `usb.{addr}` and the same one `get_usb_devices` returns.
        //
        // This took a `bus` and an `address` and matched them against
        // `bus_number` and `port_number`. When the id scheme moved to the
        // platform device path, the Windows reader stopped filling those two --
        // they are `0` and `0` for every device it enumerates -- and this
        // lookup silently collapsed: **39 devices, one distinct (bus, port)
        // pair**, so the tool could only ever return whichever device came
        // first and every other one on the machine became unreachable.
        //
        // I introduced that when I changed the id scheme, having written the
        // note two commits earlier that says to ask "what else stores this?"
        // after a reader change. Asking it of `bus_number` would have found
        // this immediately.
        let address = params
            .get("address")
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                IronError::InvalidArgument(
                    "address required: the device address from get_usb_devices, \
                     e.g. \"usb_vid_046d_pid_c548_mi_01_9_24c94812_0_0001\""
                        .to_string(),
                )
            })?;
        let monitor = UsbMonitor::new().map_err(|e| IronError::HardwareError(e.to_string()))?;
        let device = monitor
            .devices()
            .iter()
            .find(|d| d.address == address)
            .ok_or_else(|| {
                IronError::DeviceNotFound(format!("no USB device with address {address}"))
            })?;
        Ok(usb_device_json(device))
    }

    // ============== Profile Inspector Tools ==============
    pub(crate) fn tool_list_profile_subsystems(
        &mut self,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        use crate::profile::{ProfileInspector, Subsystem};
        let mut inspector = ProfileInspector::new();
        let snapshot = inspector.snapshot_all();
        let subsystems: Vec<_> = Subsystem::ALL
            .iter()
            .map(|s| {
                // No provider is registered for this subsystem on this build or
                // platform, so the counts are unknown. Reporting `0` would say
                // the subsystem was read and holds nothing.
                match snapshot.providers.get(s) {
                    Some(g) => json!({
                        "subsystem": s.as_str(),
                        "groups": g.len(),
                        "settings": g.iter().map(|x| x.settings.len()).sum::<usize>(),
                    }),
                    None => json!({
                        "subsystem": s.as_str(),
                        "groups": null,
                        "settings": null,
                        "reason": "no profile provider is registered for this subsystem on this build or platform",
                    }),
                }
            })
            .collect();
        Ok(json!({"timestamp": snapshot.timestamp, "subsystems": subsystems}))
    }

    pub(crate) fn tool_get_profile_settings(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        use crate::profile::{ProfileInspector, Subsystem};
        let name = params
            .get("subsystem")
            .and_then(|v| v.as_str())
            .ok_or_else(|| IronError::InvalidArgument("subsystem required".into()))?;
        let sub = Subsystem::parse(name)
            .ok_or_else(|| IronError::InvalidArgument(format!("unknown subsystem: {}", name)))?;
        let mut inspector = ProfileInspector::new();
        // A failed read is an error to the caller, not an empty group list.
        let groups = inspector
            .snapshot(sub)
            .map_err(|reason| IronError::CommandFailed(format!("{name}: not read: {reason}")))?;
        Ok(serde_json::to_value(groups)?)
    }

    pub(crate) fn tool_get_profile_deviations(
        &mut self,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        use crate::profile::{deviation::deviations_from_default, ProfileInspector};
        let mut inspector = ProfileInspector::new();
        let snapshot = inspector.snapshot_all();
        let devs = deviations_from_default(&snapshot);
        Ok(json!({"count": devs.len(), "deviations": devs}))
    }

    pub(crate) fn tool_benchmark_profile_providers(
        &mut self,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let report = crate::profile::bench::run_bench();
        Ok(serde_json::to_value(report)?)
    }

    pub(crate) fn tool_list_writable_profile_settings(
        &mut self,
        _params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let ids = crate::profile::apply::writable_setting_ids();
        Ok(json!({"count": ids.len(), "ids": ids}))
    }

    pub(crate) fn tool_apply_profile_setting(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let id = params
            .get("setting_id")
            .and_then(|v| v.as_str())
            .ok_or_else(|| IronError::InvalidArgument("setting_id required".into()))?
            .to_string();
        let confirm = params
            .get("confirm")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        let value: crate::profile::SettingValue = match params.get("value") {
            Some(serde_json::Value::Bool(b)) => crate::profile::SettingValue::Bool(*b),
            Some(serde_json::Value::Number(n)) => {
                if let Some(i) = n.as_i64() {
                    crate::profile::SettingValue::Int(i)
                } else if let Some(u) = n.as_u64() {
                    crate::profile::SettingValue::Uint(u)
                } else if let Some(f) = n.as_f64() {
                    crate::profile::SettingValue::Float(f)
                } else {
                    return Err(IronError::InvalidArgument(
                        "unsupported numeric value".into(),
                    ));
                }
            }
            Some(serde_json::Value::String(s)) => crate::profile::SettingValue::Text(s.clone()),
            Some(other) => {
                return Err(IronError::InvalidArgument(format!(
                    "unsupported value type: {}",
                    other
                )))
            }
            None => {
                return Err(IronError::InvalidArgument("value required".into()));
            }
        };

        // Belt-and-suspenders: AI agent writes also require the env-var gate
        // in addition to confirm. Operators must opt-in deliberately.
        let agent_allowed = std::env::var("IRONMON_ALLOW_AGENT_WRITES")
            .map(|v| v == "1")
            .unwrap_or(false);
        let effective_confirm = confirm && agent_allowed;

        let outcome = crate::profile::apply::apply_setting(&id, value, effective_confirm);
        let mut response = serde_json::to_value(&outcome)?;
        if confirm && !agent_allowed {
            if let Some(obj) = response.as_object_mut() {
                obj.insert("agent_write_blocked".to_string(), json!(true));
                obj.insert(
                    "agent_write_message".to_string(),
                    json!("Agent write was suppressed because IRONMON_ALLOW_AGENT_WRITES is not set to 1. Operator must enable this env-var to allow MCP tools to mutate hardware state."),
                );
            }
        }
        Ok(response)
    }

    pub(crate) fn tool_explain_profile_setting(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        use crate::profile::{explain, explain::candidates, ProfileInspector};
        let id = params
            .get("setting_id")
            .and_then(|v| v.as_str())
            .ok_or_else(|| IronError::InvalidArgument("setting_id required".into()))?;
        let mut inspector = ProfileInspector::new();
        let snapshot = inspector.snapshot_all();
        match explain::explain(&snapshot, id) {
            Some(exp) => Ok(serde_json::to_value(exp)?),
            None => Ok(json!({
                "found": false,
                "candidates": candidates(&snapshot, id),
            })),
        }
    }

    pub(crate) fn tool_get_active_app_profiles(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let matched_only = params
            .get("matched_only")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        let entries = if matched_only {
            crate::profile::active::matched_active_profiles()?
        } else {
            crate::profile::active::active_profiles_for_processes()?
        };
        let total = entries.len();
        // The DRS database is either checked for every entry or for none. When
        // it was not checked, `matched_count` is null, not zero.
        let drs_checked = entries.iter().any(|e| e.has_nvidia_drs_profile.is_some());
        let matched = drs_checked.then(|| entries.iter().filter(|e| e.has_any_profile()).count());
        Ok(json!({
            "total_processes": total,
            "nvidia_drs_checked": drs_checked,
            "matched_count": matched,
            "entries": entries,
        }))
    }

    pub(crate) fn tool_search_profile_settings(
        &mut self,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        use crate::profile::ProfileInspector;
        let query = params
            .get("query")
            .and_then(|v| v.as_str())
            .ok_or_else(|| IronError::InvalidArgument("query required".into()))?;
        let mut inspector = ProfileInspector::new();
        let snapshot = inspector.snapshot_all();
        let hits: Vec<_> = snapshot
            .search(query)
            .into_iter()
            .map(|(sub, group, setting)| {
                json!({
                    "subsystem": sub.as_str(),
                    "device": &group.device,
                    "profile": &group.display_name,
                    "setting": setting,
                })
            })
            .collect();
        Ok(json!({"query": query, "match_count": hits.len(), "matches": hits}))
    }
}

/// Shapes a sensor listing so a failed read cannot pass for an empty one.
///
/// The rows sit under `key` beside an `errors` array, empty when every source
/// answered, so an agent sees "unreadable" rather than `[]` and can tell it from
/// "none here". The shape does not change with the outcome.
fn sensor_listing(
    key: &str,
    rows: Vec<serde_json::Value>,
    errors: Vec<serde_json::Value>,
) -> serde_json::Value {
    let mut out = serde_json::Map::new();
    out.insert(key.to_string(), serde_json::Value::Array(rows));
    out.insert("errors".to_string(), serde_json::Value::Array(errors));
    serde_json::Value::Object(out)
}

/// One failed source for `sensor_listing`. `source` names the device and the reading
/// that was wanted from it, e.g. `nct6798/fans`.
fn sensor_error(source: &str, error: impl std::fmt::Display) -> serde_json::Value {
    json!({ "source": source, "error": error.to_string() })
}

#[cfg(test)]
mod tests {
    use super::*;

    /// An index naming no device is an error, not an empty success.
    ///
    /// `get_gpu_temperature`, `_memory`, `_power` and `_utilization` take an optional
    /// index and used to filter the snapshot list by it, so `gpu_index: 99` on a
    /// three-GPU machine returned `{"success": true, "data": []}`. An agent reports
    /// that as "nothing to report" rather than "there is no GPU 99". Verified live
    /// against the MCP server before and after.
    #[test]
    fn absent_gpu_index_is_rejected_not_answered_empty() {
        // Present indices pass, including the last valid one.
        assert!(AiDataApi::check_gpu_index(Some(0), 3).is_ok());
        assert!(AiDataApi::check_gpu_index(Some(2), 3).is_ok());
        // Omitted index means "all GPUs" and stays valid.
        assert!(AiDataApi::check_gpu_index(None, 3).is_ok());
        assert!(AiDataApi::check_gpu_index(None, 0).is_ok());

        // One past the end, and far past it.
        for absent in [3u64, 99] {
            let err = AiDataApi::check_gpu_index(Some(absent), 3)
                .expect_err("index {absent} does not exist and must be refused");
            assert!(
                err.to_string()
                    .contains(&format!("GPU index {absent} not found")),
                "unexpected message for index {absent}: {err}"
            );
        }

        // A machine with no GPUs refuses index 0 rather than reporting an empty win.
        assert!(AiDataApi::check_gpu_index(Some(0), 0).is_err());
    }

    /// A sensor source that fails to read is reported, not folded into an empty listing.
    ///
    /// The sensor tools used to skip a failed `temperature_sensors()`, `fans()` or
    /// `voltage_rails()` call with `if let Ok`, so an unreadable device and a device with
    /// no fans both produced `[]`.
    #[test]
    fn failed_sensor_source_is_reported_not_empty() {
        // The shape is the same with or without failures, so a caller reads one form.
        let clean = sensor_listing("fans", vec![json!({"name": "cpu"})], vec![]);
        assert_eq!(clean, json!({"fans": [{"name": "cpu"}], "errors": []}));

        // A failure names its source rather than leaving an empty list.
        let failed = sensor_error("nct6798/fans", "driver not loaded");
        let partial = sensor_listing("fans", vec![], vec![failed]);
        assert!(
            partial.is_object(),
            "a failed read must not look like an empty array"
        );
        assert_eq!(partial["fans"], json!([]));
        assert_eq!(partial["errors"][0]["source"], "nct6798/fans");
        assert_eq!(partial["errors"][0]["error"], "driver not loaded");
    }

    /// An unclassified USB device carries a null class and speed, each with a reason.
    ///
    /// The reason key is always present, as the other `*_unavailable_reason` keys in this
    /// file are, and is null when the field it explains was read.
    #[test]
    fn usb_device_json_gives_a_reason_for_each_null_field() {
        use crate::usb::{UsbDevice, UsbDeviceClass, UsbSpeed};
        let device = |class, speed| UsbDevice {
            address: "usb_test_0_1".into(),
            bus_number: None,
            port_number: None,
            vendor_id: Some(0x046d),
            product_id: None,
            manufacturer: None,
            product: None,
            description: None,
            serial_number: None,
            class,
            speed,
        };

        let unknown = usb_device_json(&device(UsbDeviceClass::Unknown, UsbSpeed::Unknown));
        assert!(unknown["class"].is_null());
        assert_eq!(
            unknown["class_unavailable_reason"],
            "no class was declared by the device"
        );
        assert!(unknown["speed"].is_null());
        assert_eq!(
            unknown["speed_unavailable_reason"],
            "no hub reported a negotiated speed"
        );

        let read = usb_device_json(&device(UsbDeviceClass::Hub, UsbSpeed::High));
        assert_eq!(read["speed"], "High");
        assert_eq!(read["class"], "Hub");
        assert!(read["speed_unavailable_reason"].is_null());
        assert!(read["class_unavailable_reason"].is_null());
    }
}