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
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
//! Terminal User Interface for MCP Probe
//!
//! This module provides a rich interactive TUI for debugging MCP servers,
//! allowing real-time inspection of the negotiation process and server capabilities.
use anyhow::Result;
use mcp_probe_core::{
client::McpClient,
messages::{
prompts::{
GetPromptRequest, GetPromptResponse, ListPromptsRequest, ListPromptsResponse, Prompt,
},
resources::{
ListResourcesRequest, ListResourcesResponse, ReadResourceRequest, ReadResourceResponse,
Resource,
},
tools::{CallToolRequest, CallToolResponse, ListToolsRequest, ListToolsResponse},
Implementation, JsonRpcRequest, JsonRpcResponse,
},
transport::TransportConfig,
McpResult,
};
use ratatui::crossterm::{
event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind},
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{
backend::{Backend, CrosstermBackend},
layout::{Alignment, Constraint, Direction, Layout, Margin, Rect},
style::{Color, Style},
text::{Line, Span, Text},
widgets::{
Block, Borders, Clear, List, ListItem, ListState, Paragraph, Scrollbar,
ScrollbarOrientation, ScrollbarState, Wrap,
},
Frame, Terminal,
};
use serde_json::Value;
use std::{
collections::HashMap,
io,
time::{Duration, Instant},
};
use tui_textarea::{Input, TextArea};
use crate::search::{SearchCategory, SearchEngine, SearchResult};
/// Extension trait to add higher-level methods to McpClient
trait McpClientExt {
async fn list_resources(&mut self) -> McpResult<Vec<Resource>>;
async fn list_prompts(&mut self) -> McpResult<Vec<Prompt>>;
async fn call_tool(&mut self, name: &str, arguments: Value) -> McpResult<CallToolResponse>;
async fn read_resource(&mut self, uri: &str) -> McpResult<ReadResourceResponse>;
async fn get_prompt(
&mut self,
name: &str,
arguments: Option<Value>,
) -> McpResult<GetPromptResponse>;
}
impl McpClientExt for McpClient {
async fn list_resources(&mut self) -> McpResult<Vec<Resource>> {
let request = ListResourcesRequest { cursor: None };
let response = self.send_request("resources/list", request).await?;
if let Some(result) = response.result {
let list_response: ListResourcesResponse = serde_json::from_value(result)?;
Ok(list_response.resources)
} else {
Ok(Vec::new())
}
}
async fn list_prompts(&mut self) -> McpResult<Vec<Prompt>> {
let request = ListPromptsRequest { cursor: None };
let response = self.send_request("prompts/list", request).await?;
if let Some(result) = response.result {
let list_response: ListPromptsResponse = serde_json::from_value(result)?;
Ok(list_response.prompts)
} else {
Ok(Vec::new())
}
}
async fn call_tool(&mut self, name: &str, arguments: Value) -> McpResult<CallToolResponse> {
let request = CallToolRequest {
name: name.to_string(),
arguments: Some(arguments),
};
let response = self.send_request("tools/call", request).await?;
// Log the raw response for debugging
tracing::info!("=== RAW TOOL CALL RESPONSE ===");
tracing::info!(
"Full response: {}",
serde_json::to_string_pretty(&response)
.unwrap_or_else(|_| "Failed to serialize response".to_string())
);
if let Some(result) = response.result {
tracing::info!("=== RESULT FIELD ANALYSIS ===");
tracing::info!(
"Result field: {}",
serde_json::to_string_pretty(&result)
.unwrap_or_else(|_| "Failed to serialize result".to_string())
);
// Try to parse as standard MCP CallToolResponse first
if let Ok(call_response) = serde_json::from_value::<CallToolResponse>(result.clone()) {
tracing::info!("✅ Successfully parsed as standard MCP CallToolResponse");
tracing::info!("Content items: {}", call_response.content.len());
// Check if we got a "successful" parse but with empty content
// This happens when the tool returns non-MCP format like {"a": 30, "b": 40}
if call_response.content.is_empty() && result.is_object() {
tracing::warn!("⚠️ Parsed as CallToolResponse but content is empty - tool likely returned non-MCP format");
tracing::warn!("🔄 Falling back to custom parsing...");
// Force custom parsing
let result_text = serde_json::to_string_pretty(&result)
.unwrap_or_else(|_| result.to_string());
tracing::info!("📝 Custom parsed result text: {}", result_text);
Ok(CallToolResponse {
content: vec![mcp_probe_core::messages::tools::ToolResult::Text {
text: result_text,
}],
is_error: Some(false),
})
} else {
Ok(call_response)
}
} else {
tracing::info!(
"❌ Failed to parse as standard MCP CallToolResponse, using custom parsing"
);
// Handle non-standard tool responses (like add_numbers)
// Convert the raw result into a text-based ToolResult
let result_text = if result.is_object() || result.is_array() {
serde_json::to_string_pretty(&result).unwrap_or_else(|_| result.to_string())
} else {
result.to_string()
};
tracing::info!("📝 Custom parsed result text: {}", result_text);
Ok(CallToolResponse {
content: vec![mcp_probe_core::messages::tools::ToolResult::Text {
text: result_text,
}],
is_error: Some(false),
})
}
} else {
Err(mcp_probe_core::McpError::Protocol(
mcp_probe_core::error::ProtocolError::RequestFailed {
reason: "No result in tool call response".to_string(),
},
))
}
}
async fn read_resource(&mut self, uri: &str) -> McpResult<ReadResourceResponse> {
let request = ReadResourceRequest {
uri: uri.to_string(),
};
let response = self.send_request("resources/read", request).await?;
if let Some(result) = response.result {
let read_response: ReadResourceResponse = serde_json::from_value(result)?;
Ok(read_response)
} else {
Err(mcp_probe_core::McpError::Protocol(
mcp_probe_core::error::ProtocolError::RequestFailed {
reason: "No result in resource read response".to_string(),
},
))
}
}
async fn get_prompt(
&mut self,
name: &str,
arguments: Option<Value>,
) -> McpResult<GetPromptResponse> {
let request = GetPromptRequest {
name: name.to_string(),
arguments,
};
let response = self.send_request("prompts/get", request).await?;
if let Some(result) = response.result {
let prompt_response: GetPromptResponse = serde_json::from_value(result)?;
Ok(prompt_response)
} else {
Err(mcp_probe_core::McpError::Protocol(
mcp_probe_core::error::ProtocolError::RequestFailed {
reason: "No result in prompt get response".to_string(),
},
))
}
}
}
/// Main TUI application for interactive debugging
pub struct DebuggerApp {
/// Transport configuration
transport_config: TransportConfig,
/// Client implementation info
client_info: Implementation,
/// Current application state
state: AppState,
/// UI state manager
ui_state: UiState,
/// Message history
message_history: Vec<MessageEntry>,
/// Current server capabilities
capabilities: ServerCapabilities,
/// Environment variables for capability invocation
env_variables: HashMap<String, String>,
/// MCP client instance
client: Option<McpClient>,
/// Session ID from server
session_id: Option<String>,
/// Session start time
session_start: Instant,
/// Message counter
message_count: usize,
/// Error counter
error_count: usize,
/// Discovery progress
discovery_step: String,
/// Search engine for capabilities
search_engine: SearchEngine,
}
/// Application state
#[derive(Debug, Clone, PartialEq)]
pub enum AppState {
/// Initial state
Initializing,
/// Connecting to server
Connecting,
/// Discovering capabilities
Discovering,
/// Ready for interaction
Ready,
/// Error state
Error(String),
/// Shutting down
ShuttingDown,
}
/// UI state for managing focus and interactions
#[derive(Debug)]
pub struct UiState {
/// Currently focused panel
current_focus: FocusedPanel,
/// List states for different panels
protocol_flow_state: ListState,
capabilities_state: ListState,
message_history_state: ListState,
/// Input state
input_area: TextArea<'static>,
/// Environment variables input area
env_input_area: TextArea<'static>,
/// Whether environment variables dialog is open
env_dialog_open: bool,
/// Scroll states
message_scroll: ScrollbarState,
capability_details_scroll: ScrollbarState,
search_results_scroll: ScrollbarState,
env_vars_scroll: ScrollbarState,
response_viewer_scroll: ScrollbarState,
response_viewer_horizontal_scroll: ScrollbarState,
/// Response viewer scroll positions
response_viewer_vertical_pos: usize,
response_viewer_horizontal_pos: usize,
/// Ordered list of parameter field names for consistent access
param_field_names: Vec<String>,
/// Whether help dialog is open
help_dialog_open: bool,
/// Whether to show raw JSON
show_raw_json: bool,
/// Current selected message index for inspection
selected_message_index: Option<usize>,
/// Capability selection tracking
capability_indices: Vec<Option<CapabilityRef>>,
/// Current capability view state
capability_view: CapabilityView,
capability_detail_state: ListState,
capability_page: usize,
capability_page_size: usize,
/// Parameter form dialog state
parameter_dialog_open: bool,
selected_capability: Option<CapabilityRef>,
/// New enhanced parameter form state
param_fields: HashMap<String, ParamField>,
param_selected_field: usize,
param_edit_mode: bool,
/// Search functionality
search_input: TextArea<'static>,
search_active: bool,
search_results: Vec<SearchResult>,
search_results_state: ListState,
/// Response viewer
response_viewer_open: bool,
response_viewer_mode: ResponseViewMode,
selected_response: Option<Value>,
}
#[derive(Debug, Clone)]
pub struct ParamField {
pub value: String,
pub required: bool,
pub description: Option<String>,
pub param_type: Option<String>,
}
/// Which panel is currently focused
#[derive(Debug, Clone, PartialEq)]
pub enum FocusedPanel {
ProtocolFlow,
MessageInspector,
Capabilities,
Input,
EnvVariables,
}
/// Reference to a specific capability
#[derive(Debug, Clone)]
pub enum CapabilityRef {
Tool(usize),
Resource(usize),
Prompt(usize),
}
/// Capability category for navigation
#[derive(Debug, Clone, PartialEq)]
pub enum CapabilityCategory {
Tools,
Resources,
Prompts,
}
/// Current view state for capabilities
#[derive(Debug, Clone)]
pub enum CapabilityView {
Categories,
DetailedList(CapabilityCategory),
}
/// Response viewer display modes
#[derive(Debug, Clone, PartialEq)]
pub enum ResponseViewMode {
Formatted, // Nicely formatted with syntax highlighting
RawJson, // Raw JSON view
TreeView, // Tree-like structure view
Summary, // Summary with key information
}
/// Message entry for history tracking
#[derive(Debug, Clone)]
pub struct MessageEntry {
/// Timestamp
timestamp: Instant,
/// Message type
message_type: MessageType,
/// Request data
request: Option<JsonRpcRequest>,
/// Response data
response: Option<JsonRpcResponse>,
/// Raw response data for better viewing
raw_response: Option<Value>,
/// Error information
error: Option<String>,
/// Success information
success: Option<String>,
}
/// Message type classification
#[derive(Debug, Clone)]
pub enum MessageType {
Initialize,
ListTools,
ListResources,
ListPrompts,
CallTool,
GetResource,
GetPrompt,
Other(String),
}
impl std::fmt::Display for MessageType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
MessageType::Initialize => write!(f, "Initialize"),
MessageType::ListTools => write!(f, "List Tools"),
MessageType::ListResources => write!(f, "List Resources"),
MessageType::ListPrompts => write!(f, "List Prompts"),
MessageType::CallTool => write!(f, "Call Tool"),
MessageType::GetResource => write!(f, "Get Resource"),
MessageType::GetPrompt => write!(f, "Get Prompt"),
MessageType::Other(s) => write!(f, "{}", s),
}
}
}
/// Server capabilities
#[derive(Debug, Clone, Default)]
pub struct ServerCapabilities {
/// Available tools
tools: Vec<ToolInfo>,
/// Available resources
resources: Vec<ResourceInfo>,
/// Available prompts
prompts: Vec<PromptInfo>,
}
/// Tool information
#[derive(Debug, Clone)]
pub struct ToolInfo {
pub name: String, // Clean display name (without prefix)
pub full_name: String, // Original full name with prefix (for API calls)
pub description: Option<String>,
pub parameters: Option<Value>,
}
/// Resource information
#[derive(Debug, Clone)]
pub struct ResourceInfo {
pub uri: String,
pub name: Option<String>,
pub description: Option<String>,
pub mime_type: Option<String>,
}
/// Prompt information
#[derive(Debug, Clone)]
pub struct PromptInfo {
pub name: String,
pub description: Option<String>,
pub arguments: Option<Value>,
}
impl DebuggerApp {
/// Create a new debugger application
pub fn new(transport_config: TransportConfig, client_info: Implementation) -> Result<Self> {
eprintln!(
"Creating DebuggerApp with transport: {:?}",
transport_config
);
tracing::info!("Creating DebuggerApp");
tracing::debug!("Transport config: {:?}", transport_config);
let mut input_area = TextArea::default();
input_area.set_placeholder_text(
"Enter MCP command (e.g., tools.calculator {\"a\": 5, \"b\": 3})",
);
let mut env_input_area = TextArea::default();
env_input_area
.set_placeholder_text("Enter environment variables (KEY=value,KEY2=value2...)");
let mut search_input = TextArea::default();
search_input.set_placeholder_text(
"Type to search by name, description, or keywords (supports fuzzy matching)",
);
let ui_state = UiState {
current_focus: FocusedPanel::Capabilities,
protocol_flow_state: ListState::default().with_selected(Some(0)),
capabilities_state: ListState::default().with_selected(Some(0)),
message_history_state: ListState::default(),
input_area,
env_input_area,
env_dialog_open: false,
message_scroll: ScrollbarState::new(0),
capability_details_scroll: ScrollbarState::new(0),
search_results_scroll: ScrollbarState::new(0),
env_vars_scroll: ScrollbarState::new(0),
response_viewer_scroll: ScrollbarState::new(0),
response_viewer_horizontal_scroll: ScrollbarState::new(0),
response_viewer_vertical_pos: 0,
response_viewer_horizontal_pos: 0,
param_field_names: Vec::new(),
help_dialog_open: false,
show_raw_json: false,
selected_message_index: None,
capability_indices: Vec::new(),
capability_view: CapabilityView::Categories,
capability_detail_state: ListState::default(),
capability_page: 0,
capability_page_size: 10,
parameter_dialog_open: false,
selected_capability: None,
param_fields: HashMap::new(),
param_selected_field: 0,
param_edit_mode: false,
search_input,
search_active: false,
search_results: Vec::new(),
search_results_state: ListState::default(),
response_viewer_open: false,
response_viewer_mode: ResponseViewMode::Formatted,
selected_response: None,
};
Ok(Self {
transport_config,
client_info,
state: AppState::Initializing,
ui_state,
message_history: Vec::new(),
capabilities: ServerCapabilities::default(),
env_variables: HashMap::new(),
client: None,
session_id: None,
session_start: Instant::now(),
message_count: 0,
error_count: 0,
discovery_step: String::new(),
search_engine: SearchEngine::new(),
})
}
/// Run the TUI application
pub async fn run(&mut self) -> Result<()> {
// Setup terminal
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
// Start the main event loop
let result = self.run_app(&mut terminal).await;
// Restore terminal
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
result
}
/// Run the main application loop
async fn run_app<B: Backend>(&mut self, terminal: &mut Terminal<B>) -> Result<()> {
// Start client initialization in background
let mut client_initialized = false;
let mut initialization_task: Option<tokio::task::JoinHandle<anyhow::Result<McpClient>>> =
None;
loop {
// Start client initialization if not already started
if !client_initialized && initialization_task.is_none() {
let transport_config = self.transport_config.clone();
let client_info = self.client_info.clone();
tracing::info!("Starting MCP client initialization");
tracing::debug!("Transport config: {:?}", transport_config);
tracing::debug!("Client info: {:?}", client_info);
initialization_task = Some(tokio::spawn(async move {
tracing::debug!("Creating MCP client with defaults");
let mut client =
McpClient::with_defaults(transport_config)
.await
.map_err(|e| {
tracing::error!("Failed to create MCP client: {}", e);
anyhow::anyhow!("Failed to create MCP client: {}", e)
})?;
tracing::debug!("Attempting to connect to MCP server");
let _server_info = client.connect(client_info).await.map_err(|e| {
tracing::error!("Failed to connect to MCP server: {}", e);
anyhow::anyhow!("Failed to connect to MCP server: {}", e)
})?;
tracing::info!("MCP client connected successfully");
Ok(client)
}));
self.state = AppState::Connecting;
tracing::info!("State changed to Connecting");
}
// Check if client initialization completed
if let Some(ref mut task) = initialization_task {
if task.is_finished() {
match task.await {
Ok(Ok(mut client)) => {
// Client connected successfully - extract session ID
tracing::info!("Client initialization completed successfully");
self.state = AppState::Discovering;
self.discovery_step = "Extracting session...".to_string();
tracing::debug!(
"State changed to Discovering, step: Extracting session..."
);
// Add initialization message to history
self.add_message(MessageEntry {
timestamp: std::time::Instant::now(),
message_type: MessageType::Initialize,
request: None,
response: None,
raw_response: None,
error: None,
success: None,
});
// Extract session ID from the transport
let transport_info = client.transport_info();
tracing::debug!("Transport info: {:?}", transport_info);
if let Some(session_value) = transport_info.metadata.get("session_id") {
tracing::debug!(
"Found session_id in metadata: {:?}",
session_value
);
if let Some(session_str) = session_value.as_str() {
if !session_str.is_empty() && session_str != "null" {
self.session_id = Some(session_str.to_string());
tracing::info!("Extracted session ID: {}", session_str);
} else {
tracing::warn!(
"Session ID is empty or null: {}",
session_str
);
}
} else {
tracing::warn!(
"Session ID metadata is not a string: {:?}",
session_value
);
}
} else {
tracing::warn!("No session_id found in transport metadata");
}
// Debug: Show what we extracted
let session_debug = self.session_id.as_deref().unwrap_or("none");
self.add_message(MessageEntry {
timestamp: std::time::Instant::now(),
message_type: MessageType::Other("Debug".to_string()),
request: None,
response: None,
raw_response: None,
error: None,
success: Some(format!("Session ID extracted: {}", session_debug)),
});
// Discover capabilities step by step
self.discovery_step = "Listing tools...".to_string();
tracing::debug!("Starting tools discovery");
// Let's get the raw JSON response first
let request = ListToolsRequest { cursor: None };
match client.send_request("tools/list", request).await {
Ok(raw_response) => {
tracing::debug!("Raw tools/list response: {:?}", raw_response);
if let Some(result) = raw_response.result {
tracing::debug!("Raw result field: {:?}", result);
match serde_json::from_value::<ListToolsResponse>(result) {
Ok(list_response) => {
let tools = list_response.tools;
tracing::info!(
"Successfully listed {} tools",
tools.len()
);
// Let's examine the first few tools in detail
for (i, tool) in tools.iter().take(3).enumerate() {
tracing::debug!(
"Tool #{}: name={}, desc={}",
i,
tool.name,
tool.description
);
tracing::debug!(
"Tool #{} input_schema: {:?}",
i,
tool.input_schema
);
if let Some(ref schema) = tool.input_schema {
tracing::debug!(
"Tool #{} schema JSON: {}",
i,
serde_json::to_string_pretty(schema)
.unwrap_or_else(
|_| "Invalid JSON".to_string()
)
);
}
}
self.capabilities.tools = tools
.into_iter()
.map(|tool| {
ToolInfo {
name: Self::strip_tool_prefix(
&tool.name,
)
.to_string(),
full_name: tool.name, // Use the exact name from server
description: Some(tool.description),
parameters: tool.input_schema,
}
})
.collect();
// Add success message to history
self.add_message(MessageEntry {
timestamp: std::time::Instant::now(),
message_type: MessageType::ListTools,
request: None,
response: None,
raw_response: None,
error: None,
success: Some(format!(
"Found {} tools",
self.capabilities.tools.len()
)),
});
}
Err(e) => {
tracing::error!(
"Failed to deserialize tools list response: {}",
e
);
self.add_error(format!(
"Failed to parse tools: {}",
e
));
self.add_message(MessageEntry {
timestamp: std::time::Instant::now(),
message_type: MessageType::ListTools,
request: None,
response: None,
raw_response: None,
error: Some(format!(
"Tools parse error: {}",
e
)),
success: None,
});
}
}
} else {
tracing::error!("No result field in tools/list response");
self.add_error("No result in tools response".to_string());
self.add_message(MessageEntry {
timestamp: std::time::Instant::now(),
message_type: MessageType::ListTools,
request: None,
response: None,
raw_response: None,
error: Some("No result in tools response".to_string()),
success: None,
});
}
}
Err(e) => {
tracing::error!("Failed to get raw tools response: {}", e);
self.add_error(format!("Failed to list tools: {}", e));
self.add_message(MessageEntry {
timestamp: std::time::Instant::now(),
message_type: MessageType::ListTools,
request: None,
response: None,
raw_response: None,
error: Some(format!("Tools error: {}", e)),
success: None,
});
}
}
self.discovery_step = "Listing resources...".to_string();
match client.list_resources().await {
Ok(resources) => {
self.capabilities.resources = resources
.into_iter()
.map(|resource| ResourceInfo {
uri: resource.uri,
name: Some(resource.name),
description: resource.description,
mime_type: resource.mime_type,
})
.collect();
// Add success message to history
self.add_message(MessageEntry {
timestamp: std::time::Instant::now(),
message_type: MessageType::ListResources,
request: None,
response: None,
raw_response: None,
error: None,
success: Some(format!(
"Found {} resources",
self.capabilities.resources.len()
)),
});
}
Err(e) => {
self.add_error(format!("Failed to list resources: {}", e));
self.add_message(MessageEntry {
timestamp: std::time::Instant::now(),
message_type: MessageType::ListResources,
request: None,
response: None,
raw_response: None,
error: Some(format!("Resources error: {}", e)),
success: None,
});
}
}
self.discovery_step = "Listing prompts...".to_string();
match client.list_prompts().await {
Ok(prompts) => {
self.capabilities.prompts = prompts
.into_iter()
.map(|prompt| PromptInfo {
name: prompt.name,
description: Some(prompt.description),
arguments: prompt.arguments,
})
.collect();
// Add success message to history
self.add_message(MessageEntry {
timestamp: std::time::Instant::now(),
message_type: MessageType::ListPrompts,
request: None,
response: None,
raw_response: None,
error: None,
success: Some(format!(
"Found {} prompts",
self.capabilities.prompts.len()
)),
});
}
Err(e) => {
self.add_error(format!("Failed to list prompts: {}", e));
self.add_message(MessageEntry {
timestamp: std::time::Instant::now(),
message_type: MessageType::ListPrompts,
request: None,
response: None,
raw_response: None,
error: Some(format!("Prompts error: {}", e)),
success: None,
});
}
}
self.discovery_step = "Discovery complete".to_string();
tracing::info!("All discovery completed successfully, client ready");
// Index capabilities for search
self.search_engine.index_tools(&self.capabilities.tools);
self.search_engine
.index_resources(&self.capabilities.resources);
self.search_engine.index_prompts(&self.capabilities.prompts);
tracing::info!(
"Indexed {} items for search",
self.search_engine.total_items()
);
self.client = Some(client);
self.state = AppState::Ready;
client_initialized = true;
tracing::info!(
"State changed to Ready, client initialization complete"
);
}
Ok(Err(e)) => {
// Connection failed
tracing::error!("Client initialization failed: {}", e);
let error_msg = format!("Connection failed: {}", e);
self.state = AppState::Error(error_msg.clone());
self.add_error(format!("Failed to connect to MCP server: {}", e));
// Add detailed error to message history
self.add_message(MessageEntry {
timestamp: std::time::Instant::now(),
message_type: MessageType::Initialize,
request: None,
response: None,
raw_response: None,
error: Some(format!("Connection error: {}", e)),
success: None,
});
client_initialized = true; // Don't retry automatically
}
Err(e) => {
// Task panicked
tracing::error!("Client initialization task panicked: {}", e);
let error_msg = format!("Client task failed: {}", e);
self.state = AppState::Error(error_msg.clone());
self.add_error(format!("Client initialization task failed: {}", e));
// Add detailed error to message history
self.add_message(MessageEntry {
timestamp: std::time::Instant::now(),
message_type: MessageType::Initialize,
request: None,
response: None,
raw_response: None,
error: Some(format!("Task panic: {}", e)),
success: None,
});
client_initialized = true;
}
}
initialization_task = None;
}
}
// Draw the UI
terminal.draw(|f| self.draw_ui(f))?;
// Handle events
if event::poll(Duration::from_millis(100))? {
if let Event::Key(key) = event::read()? {
if key.kind == KeyEventKind::Press && self.handle_key_event(key.code).await? {
break; // Exit requested
}
}
}
// Check for shutdown
if self.state == AppState::ShuttingDown {
break;
}
}
Ok(())
}
/// Handle keyboard events (with enhanced safety checks)
async fn handle_key_event(&mut self, key: KeyCode) -> Result<bool> {
// Handle search mode first
if self.ui_state.search_active {
match key {
KeyCode::Esc => {
self.ui_state.search_active = false;
self.ui_state.search_results.clear();
self.ui_state.current_focus = FocusedPanel::Capabilities;
return Ok(false);
}
KeyCode::Enter => {
// Select from search results
if let Some(selected) = self.ui_state.search_results_state.selected() {
if let Some(result) = self.ui_state.search_results.get(selected) {
self.select_search_result(result.clone());
}
}
return Ok(false);
}
KeyCode::Up => {
if !self.ui_state.search_results.is_empty() {
let current = self.ui_state.search_results_state.selected().unwrap_or(0);
if current > 0 {
self.ui_state.search_results_state.select(Some(current - 1));
} else {
self.ui_state
.search_results_state
.select(Some(self.ui_state.search_results.len() - 1));
}
}
return Ok(false);
}
KeyCode::Down => {
if !self.ui_state.search_results.is_empty() {
let current = self.ui_state.search_results_state.selected().unwrap_or(0);
if current + 1 < self.ui_state.search_results.len() {
self.ui_state.search_results_state.select(Some(current + 1));
} else {
self.ui_state.search_results_state.select(Some(0));
}
}
return Ok(false);
}
_ => {
// Handle search input
let key_event = crossterm::event::KeyEvent::new(
key,
crossterm::event::KeyModifiers::empty(),
);
self.ui_state.search_input.input(Input::from(key_event));
self.perform_search();
return Ok(false);
}
}
}
match key {
KeyCode::Char('q') if !self.ui_state.env_dialog_open => {
self.state = AppState::ShuttingDown;
return Ok(true);
}
KeyCode::Char('/') => {
// Activate search mode (available from any panel)
self.ui_state.search_active = true;
self.ui_state.current_focus = FocusedPanel::Capabilities;
// Clear any previous search
self.ui_state.search_input.select_all();
self.ui_state.search_input.cut();
return Ok(false);
}
KeyCode::Char('r') | KeyCode::Char('R') => {
// Open response viewer for selected message
if let Some(selected_idx) = self.ui_state.message_history_state.selected() {
if let Some(message) = self.message_history.get(selected_idx) {
if let Some(ref response) = message.raw_response {
self.ui_state.selected_response = Some(response.clone());
self.ui_state.response_viewer_open = true;
// Reset scroll positions to start from top
self.ui_state.response_viewer_vertical_pos = 0;
self.ui_state.response_viewer_horizontal_pos = 0;
return Ok(false);
}
}
}
return Ok(false);
}
KeyCode::Char('v') | KeyCode::Char('V') => {
// Cycle response view modes
if self.ui_state.response_viewer_open {
self.ui_state.response_viewer_mode = match self.ui_state.response_viewer_mode {
ResponseViewMode::Formatted => ResponseViewMode::RawJson,
ResponseViewMode::RawJson => ResponseViewMode::TreeView,
ResponseViewMode::TreeView => ResponseViewMode::Summary,
ResponseViewMode::Summary => ResponseViewMode::Formatted,
};
}
return Ok(false);
}
KeyCode::F(1) => {
self.ui_state.help_dialog_open = !self.ui_state.help_dialog_open;
}
KeyCode::F(2) => {
// Save session
self.save_session().await?;
}
KeyCode::F(3) => {
// Toggle raw JSON view
self.ui_state.show_raw_json = !self.ui_state.show_raw_json;
}
KeyCode::F(4) => {
// Clear messages
self.message_history.clear();
self.message_count = 0;
self.error_count = 0;
}
KeyCode::F(5) => {
// Open environment variables dialog
self.ui_state.env_dialog_open = !self.ui_state.env_dialog_open;
if self.ui_state.env_dialog_open {
self.ui_state.current_focus = FocusedPanel::EnvVariables;
} else {
self.ui_state.current_focus = FocusedPanel::Input;
}
}
KeyCode::Enter => {
if self.ui_state.parameter_dialog_open {
if self.ui_state.param_field_names.is_empty() {
// No parameters - execute directly
self.execute_selected_capability().await?;
} else if self.ui_state.param_edit_mode {
// Exit edit mode and move to next field
self.ui_state.param_edit_mode = false;
self.navigate_parameter_form_down();
} else {
// Enter edit mode for current field (fallback case)
self.ui_state.param_edit_mode = true;
}
} else if self.ui_state.env_dialog_open
&& self.ui_state.current_focus == FocusedPanel::EnvVariables
{
self.parse_env_variables();
self.ui_state.env_dialog_open = false;
self.ui_state.current_focus = FocusedPanel::Input;
} else if self.ui_state.current_focus == FocusedPanel::Capabilities {
self.select_capability();
} else if self.ui_state.current_focus == FocusedPanel::Input {
self.execute_command().await?;
}
}
KeyCode::Esc => {
if self.ui_state.response_viewer_open {
self.ui_state.response_viewer_open = false;
self.ui_state.selected_response = None;
} else if self.ui_state.parameter_dialog_open {
if self.ui_state.param_edit_mode {
// Exit edit mode
self.ui_state.param_edit_mode = false;
} else {
// Close parameter dialog
self.ui_state.parameter_dialog_open = false;
self.ui_state.selected_capability = None;
self.ui_state.current_focus = FocusedPanel::Capabilities;
}
} else if self.ui_state.env_dialog_open {
self.ui_state.env_dialog_open = false;
self.ui_state.current_focus = FocusedPanel::Input;
} else if self.ui_state.help_dialog_open {
self.ui_state.help_dialog_open = false;
} else if matches!(
self.ui_state.capability_view,
CapabilityView::DetailedList(_)
) {
// Go back from detailed list to categories
self.ui_state.capability_view = CapabilityView::Categories;
self.ui_state.current_focus = FocusedPanel::Capabilities;
}
}
KeyCode::Tab => {
if self.ui_state.parameter_dialog_open
&& !self.ui_state.param_field_names.is_empty()
{
// Execute with current parameter values
self.execute_selected_capability().await?;
} else {
// Auto-open response viewer for latest message with results
self.open_latest_response_viewer();
}
}
KeyCode::Up => {
if self.ui_state.response_viewer_open {
self.navigate_response_viewer_up();
} else if self.ui_state.parameter_dialog_open && !self.ui_state.param_edit_mode {
self.navigate_parameter_form_up();
} else if self.ui_state.current_focus == FocusedPanel::Capabilities {
self.navigate_capabilities_up();
}
}
KeyCode::Down => {
if self.ui_state.response_viewer_open {
self.navigate_response_viewer_down();
} else if self.ui_state.parameter_dialog_open && !self.ui_state.param_edit_mode {
self.navigate_parameter_form_down();
} else if self.ui_state.current_focus == FocusedPanel::Capabilities {
self.navigate_capabilities_down();
}
}
KeyCode::Left => {
if self.ui_state.response_viewer_open {
self.navigate_response_viewer_left();
} else if matches!(
self.ui_state.capability_view,
CapabilityView::DetailedList(_)
) {
self.navigate_page_left();
}
}
KeyCode::Right => {
if self.ui_state.response_viewer_open {
self.navigate_response_viewer_right();
} else if matches!(
self.ui_state.capability_view,
CapabilityView::DetailedList(_)
) {
self.navigate_page_right();
}
}
KeyCode::PageUp => {
if self.ui_state.response_viewer_open {
self.navigate_response_viewer_page_up();
}
}
KeyCode::PageDown => {
if self.ui_state.response_viewer_open {
self.navigate_response_viewer_page_down();
}
}
KeyCode::Home => {
if self.ui_state.response_viewer_open {
self.navigate_response_viewer_home();
}
}
KeyCode::End => {
if self.ui_state.response_viewer_open {
self.navigate_response_viewer_end();
}
}
_ => {
// Handle input for focused text areas
match self.ui_state.current_focus {
FocusedPanel::Input => {
self.ui_state.input_area.input(Input::from(
crossterm::event::KeyEvent::new(key, event::KeyModifiers::empty()),
));
}
FocusedPanel::EnvVariables if self.ui_state.env_dialog_open => {
self.ui_state.env_input_area.input(Input::from(
crossterm::event::KeyEvent::new(key, event::KeyModifiers::empty()),
));
}
_ => {
// Handle parameter form text input when in edit mode
if self.ui_state.parameter_dialog_open && self.ui_state.param_edit_mode {
// Enhanced safety checks with proper error handling
if self.ui_state.param_field_names.is_empty() {
tracing::debug!("No parameter fields available for input");
return Ok(false);
}
if self.ui_state.param_selected_field
>= self.ui_state.param_field_names.len()
{
tracing::warn!(
"param_selected_field {} is out of bounds (len: {}), resetting to 0",
self.ui_state.param_selected_field,
self.ui_state.param_field_names.len()
);
self.ui_state.param_selected_field = 0;
return Ok(false);
}
// Safe indexing with bounds check
let field_name = match self
.ui_state
.param_field_names
.get(self.ui_state.param_selected_field)
{
Some(name) => name.clone(),
None => {
tracing::error!(
"No field name at index {} despite bounds check",
self.ui_state.param_selected_field
);
return Ok(false);
}
};
// Safe field mutation with error handling
if let Some(field) = self.ui_state.param_fields.get_mut(&field_name) {
match key {
KeyCode::Char(c) => {
// Validate character input to prevent crashes
if c.is_control() && c != '\t' && c != '\n' {
tracing::debug!("Ignoring control character: {:?}", c);
return Ok(false);
}
// Limit field length to prevent memory issues
if field.value.len() >= 1000 {
tracing::warn!(
"Field '{}' has reached maximum length",
field_name
);
return Ok(false);
}
field.value.push(c);
tracing::debug!(
"Added char '{}' to field '{}', value now has {} chars",
c,
field_name,
field.value.len()
);
}
KeyCode::Backspace => {
if !field.value.is_empty() {
field.value.pop();
tracing::debug!(
"Removed char from field '{}', value now has {} chars",
field_name,
field.value.len()
);
}
}
_ => {
// Ignore other keys safely
tracing::debug!(
"Ignoring key in parameter form: {:?}",
key
);
}
}
} else {
tracing::error!(
"Field '{}' not found in param_fields HashMap",
field_name
);
// Don't crash, just log the error
return Ok(false);
}
}
}
}
}
}
Ok(false)
}
/// Cycle through focusable panels
fn cycle_focus(&mut self) {
if self.ui_state.env_dialog_open || self.ui_state.parameter_dialog_open {
return; // Don't cycle when dialogs are open
}
self.ui_state.current_focus = match self.ui_state.current_focus {
FocusedPanel::ProtocolFlow => FocusedPanel::MessageInspector,
FocusedPanel::MessageInspector => FocusedPanel::Capabilities,
FocusedPanel::Capabilities => FocusedPanel::Input,
FocusedPanel::Input => FocusedPanel::ProtocolFlow,
FocusedPanel::EnvVariables => FocusedPanel::Input,
};
}
/// Parse environment variables from input
fn parse_env_variables(&mut self) {
let input = self.ui_state.env_input_area.lines().join("");
self.env_variables.clear();
for pair in input.split(',') {
let pair = pair.trim();
if let Some((key, value)) = pair.split_once('=') {
self.env_variables
.insert(key.trim().to_string(), value.trim().to_string());
}
}
// Clear the input area
self.ui_state.env_input_area = TextArea::default();
self.ui_state
.env_input_area
.set_placeholder_text("Enter environment variables (KEY=value,KEY2=value2...)");
}
/// Navigate capabilities up
fn navigate_capabilities_up(&mut self) {
match self.ui_state.capability_view {
CapabilityView::Categories => {
let current = self.ui_state.capabilities_state.selected().unwrap_or(0);
if current > 0 {
self.ui_state.capabilities_state.select(Some(current - 1));
}
}
CapabilityView::DetailedList(_) => {
let current = self
.ui_state
.capability_detail_state
.selected()
.unwrap_or(0);
if current > 0 {
self.ui_state
.capability_detail_state
.select(Some(current - 1));
}
}
}
}
/// Navigate capabilities down
fn navigate_capabilities_down(&mut self) {
match self.ui_state.capability_view {
CapabilityView::Categories => {
let current = self.ui_state.capabilities_state.selected().unwrap_or(0);
if current < 2 {
// We have 3 categories (0, 1, 2)
self.ui_state.capabilities_state.select(Some(current + 1));
}
}
CapabilityView::DetailedList(_) => {
let current = self
.ui_state
.capability_detail_state
.selected()
.unwrap_or(0);
let max_items = self.ui_state.capability_indices.len();
if current + 1 < max_items {
self.ui_state
.capability_detail_state
.select(Some(current + 1));
}
}
}
}
/// Navigate parameter form up
fn navigate_parameter_form_up(&mut self) {
if self.ui_state.param_selected_field > 0 {
self.ui_state.param_selected_field -= 1;
// Automatically enter edit mode for better UX
self.ui_state.param_edit_mode = true;
}
}
/// Navigate parameter form down
fn navigate_parameter_form_down(&mut self) {
if self.ui_state.param_selected_field + 1 < self.ui_state.param_field_names.len() {
self.ui_state.param_selected_field += 1;
// Automatically enter edit mode for better UX
self.ui_state.param_edit_mode = true;
}
}
/// Navigate response viewer up (vertical scrolling)
fn navigate_response_viewer_up(&mut self) {
if self.ui_state.response_viewer_vertical_pos > 0 {
self.ui_state.response_viewer_vertical_pos -= 1;
}
}
/// Navigate response viewer down (vertical scrolling)
fn navigate_response_viewer_down(&mut self) {
self.ui_state.response_viewer_vertical_pos += 1;
// Max bounds will be checked in the draw function
}
/// Navigate response viewer left (horizontal scrolling)
fn navigate_response_viewer_left(&mut self) {
if self.ui_state.response_viewer_horizontal_pos > 0 {
self.ui_state.response_viewer_horizontal_pos -= 1;
}
}
/// Navigate response viewer right (horizontal scrolling)
fn navigate_response_viewer_right(&mut self) {
self.ui_state.response_viewer_horizontal_pos += 1;
// Max bounds will be checked in the draw function
}
/// Navigate response viewer page up (fast vertical scrolling)
fn navigate_response_viewer_page_up(&mut self) {
self.ui_state.response_viewer_vertical_pos = self
.ui_state
.response_viewer_vertical_pos
.saturating_sub(10);
}
/// Navigate response viewer page down (fast vertical scrolling)
fn navigate_response_viewer_page_down(&mut self) {
self.ui_state.response_viewer_vertical_pos += 10;
// Max bounds will be checked in the draw function
}
/// Navigate response viewer to home (top)
fn navigate_response_viewer_home(&mut self) {
self.ui_state.response_viewer_vertical_pos = 0;
self.ui_state.response_viewer_horizontal_pos = 0;
}
/// Navigate response viewer to end (bottom)
fn navigate_response_viewer_end(&mut self) {
// Set to a large value, will be clamped in draw function
self.ui_state.response_viewer_vertical_pos = usize::MAX;
}
/// Perform search based on current search input
fn perform_search(&mut self) {
let query = self
.ui_state
.search_input
.lines()
.join(" ")
.trim()
.to_string();
if query.is_empty() {
self.ui_state.search_results.clear();
return;
}
// Perform search with limit of 20 results
self.ui_state.search_results = self.search_engine.search(&query, 20);
// Reset selection to first result
if !self.ui_state.search_results.is_empty() {
self.ui_state.search_results_state.select(Some(0));
} else {
self.ui_state.search_results_state.select(None);
}
}
/// Select a result from search results
fn select_search_result(&mut self, result: SearchResult) {
if let Some(item) = self.search_engine.get_item(result.index) {
// Determine the capability reference based on category and index
match item.category {
SearchCategory::Tool => {
// Find the tool index in our capabilities
if let Some(tool_index) = self
.capabilities
.tools
.iter()
.position(|t| t.name == item.name)
{
self.ui_state.selected_capability = Some(CapabilityRef::Tool(tool_index));
self.ui_state.capability_view =
CapabilityView::DetailedList(CapabilityCategory::Tools);
self.open_parameter_form();
}
}
SearchCategory::Resource => {
// Find the resource index in our capabilities
if let Some(resource_index) = self
.capabilities
.resources
.iter()
.position(|r| r.uri == item.name)
{
self.ui_state.selected_capability =
Some(CapabilityRef::Resource(resource_index));
self.ui_state.capability_view =
CapabilityView::DetailedList(CapabilityCategory::Resources);
// Resources don't typically need parameter forms, so just select them
}
}
SearchCategory::Prompt => {
// Find the prompt index in our capabilities
if let Some(prompt_index) = self
.capabilities
.prompts
.iter()
.position(|p| p.name == item.name)
{
self.ui_state.selected_capability =
Some(CapabilityRef::Prompt(prompt_index));
self.ui_state.capability_view =
CapabilityView::DetailedList(CapabilityCategory::Prompts);
self.open_parameter_form();
}
}
}
}
// Deactivate search mode
self.ui_state.search_active = false;
self.ui_state.search_results.clear();
}
/// Navigate page left (previous page)
fn navigate_page_left(&mut self) {
if self.ui_state.capability_page > 0 {
self.ui_state.capability_page -= 1;
self.ui_state.capability_detail_state.select(Some(0));
}
}
/// Navigate page right (next page)
fn navigate_page_right(&mut self) {
if let CapabilityView::DetailedList(ref category) = self.ui_state.capability_view {
let total_count = match category {
CapabilityCategory::Tools => self.capabilities.tools.len(),
CapabilityCategory::Resources => self.capabilities.resources.len(),
CapabilityCategory::Prompts => self.capabilities.prompts.len(),
};
let max_pages = total_count.div_ceil(self.ui_state.capability_page_size);
if self.ui_state.capability_page + 1 < max_pages {
self.ui_state.capability_page += 1;
self.ui_state.capability_detail_state.select(Some(0));
}
}
}
/// Select a capability category or individual capability
fn select_capability(&mut self) {
match self.ui_state.capability_view {
CapabilityView::Categories => {
if let Some(selected) = self.ui_state.capabilities_state.selected() {
let category = match selected {
0 => CapabilityCategory::Tools,
1 => CapabilityCategory::Resources,
2 => CapabilityCategory::Prompts,
_ => return,
};
self.ui_state.capability_view = CapabilityView::DetailedList(category);
self.ui_state.capability_page = 0;
self.ui_state.capability_detail_state.select(Some(0));
}
}
CapabilityView::DetailedList(_) => {
if let Some(selected) = self.ui_state.capability_detail_state.selected() {
if let Some(Some(capability_ref)) =
self.ui_state.capability_indices.get(selected)
{
self.ui_state.selected_capability = Some(capability_ref.clone());
self.open_parameter_form();
}
}
}
}
}
/// Open parameter form for selected capability
fn open_parameter_form(&mut self) {
if let Some(ref capability_ref) = self.ui_state.selected_capability {
// Clear existing form data
self.ui_state.param_fields.clear();
self.ui_state.param_field_names.clear();
self.ui_state.param_selected_field = 0;
self.ui_state.param_edit_mode = false;
match capability_ref {
CapabilityRef::Tool(index) => {
if let Some(tool) = self.capabilities.tools.get(*index) {
tracing::debug!(
"Opening parameter form for tool: {} - {}",
tool.name,
tool.description.as_deref().unwrap_or("No description")
);
tracing::debug!("Tool parameters field: {:?}", tool.parameters);
if let Some(ref params) = tool.parameters {
tracing::debug!("Tool has parameters, building form from schema");
let params_clone = params.clone();
self.build_parameter_form_from_schema(¶ms_clone);
} else {
tracing::debug!("Tool has no parameters field");
}
} else {
tracing::debug!("Tool not found at index {}", index);
}
}
CapabilityRef::Resource(_index) => {
// Resources typically don't have parameters in the same way
tracing::debug!("Opening parameter form for resource (not implemented)");
}
CapabilityRef::Prompt(_index) => {
// Prompts may have arguments
tracing::debug!("Opening parameter form for prompt (not implemented)");
}
}
tracing::debug!(
"Final param_fields count: {}",
self.ui_state.param_fields.len()
);
// Auto-enter edit mode if we have parameters for better UX
if !self.ui_state.param_field_names.is_empty() {
self.ui_state.param_edit_mode = true;
}
self.ui_state.parameter_dialog_open = true;
}
}
/// Build parameter form from JSON schema using validation utility
fn build_parameter_form_from_schema(&mut self, schema: &Value) {
// Debug: Log the schema to see its structure
tracing::debug!(
"Building parameter form from schema: {}",
serde_json::to_string_pretty(schema).unwrap_or_else(|_| "Invalid JSON".to_string())
);
// Use the validation utility to extract parameter hints
use mcp_probe_core::validation::ParameterValidator;
let validator = ParameterValidator::new();
let parameter_hints = validator.extract_parameter_hints(schema);
if parameter_hints.is_empty() {
tracing::debug!("No parameter hints extracted from schema");
return;
}
tracing::debug!(
"Extracted {} parameter hints from schema",
parameter_hints.len()
);
// Collect and sort parameters (required first, then alphabetical)
let mut sorted_params: Vec<_> = parameter_hints.iter().collect();
sorted_params.sort_by(|(a_name, a_hint), (b_name, b_hint)| {
match (a_hint.required, b_hint.required) {
(true, false) => std::cmp::Ordering::Less,
(false, true) => std::cmp::Ordering::Greater,
_ => a_name.cmp(b_name),
}
});
// Build parameter form from sorted hints
for (param_name, hint) in sorted_params {
tracing::debug!(
"Adding parameter: {} (type: {}, required: {}, desc: {:?})",
param_name,
hint.param_type,
hint.required,
hint.description
);
// Add to ordered list for consistent access
self.ui_state.param_field_names.push(param_name.clone());
// Determine default value
let default_value = if let Some(default) = &hint.default_value {
match default {
Value::String(s) => s.clone(),
Value::Number(n) => n.to_string(),
Value::Bool(b) => b.to_string(),
_ => String::new(),
}
} else {
String::new()
};
// Enhanced description with additional schema info
let enhanced_description = if let Some(base_desc) = &hint.description {
let mut desc = base_desc.clone();
if let Some(format) = &hint.format {
desc.push_str(&format!(" (format: {})", format));
}
if let Some(pattern) = &hint.pattern {
desc.push_str(&format!(" (pattern: {})", pattern));
}
if let Some(min_len) = hint.min_length {
desc.push_str(&format!(" (min length: {})", min_len));
}
if let Some(max_len) = hint.max_length {
desc.push_str(&format!(" (max length: {})", max_len));
}
if let Some(enum_vals) = &hint.enum_values {
let enum_str = enum_vals
.iter()
.map(|v| v.as_str().unwrap_or("?"))
.collect::<Vec<_>>()
.join(", ");
desc.push_str(&format!(" (options: {})", enum_str));
}
Some(desc)
} else {
None
};
// Create parameter field
self.ui_state.param_fields.insert(
param_name.clone(),
ParamField {
value: default_value,
required: hint.required,
description: enhanced_description,
param_type: Some(hint.param_type.clone()),
},
);
}
tracing::debug!(
"Final param_fields count: {}",
self.ui_state.param_fields.len()
);
}
/// Execute selected capability with form parameters
async fn execute_selected_capability(&mut self) -> Result<()> {
if let Some(ref capability_ref) = self.ui_state.selected_capability.clone() {
// Build parameters object from form fields
let mut params = serde_json::Map::new();
for (param_name, field) in &self.ui_state.param_fields {
if !field.value.is_empty() {
// Try to parse as JSON first, then fall back to string
let param_value =
if let Ok(json_value) = serde_json::from_str::<Value>(&field.value) {
json_value
} else {
Value::String(field.value.clone())
};
params.insert(param_name.clone(), param_value);
}
}
let params_value = Value::Object(params);
match capability_ref {
CapabilityRef::Tool(index) => {
if let Some(tool) = self.capabilities.tools.get(*index) {
let tool_name = tool.full_name.clone(); // Use full name with prefix for API call
let params_str = params_value.to_string();
self.execute_tool(&tool_name, ¶ms_str).await?;
}
}
CapabilityRef::Resource(index) => {
if let Some(resource) = self.capabilities.resources.get(*index) {
let resource_uri = resource.uri.clone();
self.get_resource(&resource_uri).await?;
}
}
CapabilityRef::Prompt(index) => {
if let Some(prompt) = self.capabilities.prompts.get(*index) {
let prompt_name = prompt.name.clone();
let params_str = params_value.to_string();
self.get_prompt(&prompt_name, ¶ms_str).await?;
}
}
}
// Close the parameter dialog
self.ui_state.parameter_dialog_open = false;
self.ui_state.selected_capability = None;
}
Ok(())
}
/// Execute a command from the input area
async fn execute_command(&mut self) -> Result<()> {
let input = self.ui_state.input_area.lines().join(" ");
if input.trim().is_empty() {
return Ok(());
}
// Parse command (simplified parser for demo)
// Format: tools.toolname {"param": "value"}
// Or: resources.resourcename
// Or: prompts.promptname {"param": "value"}
let parts: Vec<&str> = input.trim().splitn(2, ' ').collect();
if parts.is_empty() {
return Ok(());
}
let command_parts: Vec<&str> = parts[0].split('.').collect();
if command_parts.len() != 2 {
self.add_error("Invalid command format. Use: tools.toolname {params}".to_string());
return Ok(());
}
let (category, name) = (command_parts[0], command_parts[1]);
let params = if parts.len() > 1 { parts[1] } else { "{}" };
match category {
"tools" => {
// Find the tool by clean name and use full name for execution
if let Some(tool) = self.capabilities.tools.iter().find(|t| t.name == name) {
let full_name = tool.full_name.clone();
self.execute_tool(&full_name, params).await?;
} else {
self.add_error(format!("Tool '{}' not found", name));
}
}
"resources" => {
self.get_resource(name).await?;
}
"prompts" => {
self.get_prompt(name, params).await?;
}
_ => {
self.add_error(format!("Unknown category: {}", category));
}
}
// Clear input
self.ui_state.input_area = TextArea::default();
self.ui_state.input_area.set_placeholder_text(
"Enter MCP command (e.g., tools.calculator {\"a\": 5, \"b\": 3})",
);
self.ui_state.input_area.set_block(
Block::default()
.borders(Borders::ALL)
.title("Interactive Terminal"),
);
Ok(())
}
/// Execute a tool with parameters
async fn execute_tool(&mut self, tool_name: &str, params_str: &str) -> Result<()> {
if let Some(client) = &mut self.client {
// Parse parameters
let mut params: Value = serde_json::from_str(params_str)
.unwrap_or_else(|_| serde_json::Value::Object(serde_json::Map::new()));
// Inject environment variables
if let Value::Object(ref mut map) = params {
for (key, value) in &self.env_variables {
if !map.contains_key(key) {
map.insert(key.clone(), Value::String(value.clone()));
}
}
}
// Find tool schema for validation
let tool_schema = self
.capabilities
.tools
.iter()
.find(|t| t.full_name == tool_name || t.name == tool_name)
.and_then(|t| t.parameters.as_ref());
// Apply schema-based parameter validation and transformation
if let Some(schema) = tool_schema {
use mcp_probe_core::validation::ParameterValidator;
let validator = ParameterValidator::new();
let validation_result = validator.validate(schema, ¶ms);
if !validation_result.is_valid {
let error_msg = format!(
"Parameter validation failed for tool '{}': {}",
tool_name,
validation_result
.errors
.iter()
.map(|e| e.to_string())
.collect::<Vec<_>>()
.join(", ")
);
self.add_error(error_msg);
return Ok(());
}
// Use validated and transformed parameters
params = validation_result.validated_params;
// Log transformations for user awareness
for transformation in &validation_result.transformations {
tracing::info!("🔧 {}", transformation);
}
}
tracing::info!("=== EXECUTING TOOL ===");
tracing::info!("Tool name: '{}'", tool_name);
tracing::info!(
"Parameters: {}",
serde_json::to_string_pretty(¶ms)
.unwrap_or_else(|_| "Failed to serialize params".to_string())
);
match client.call_tool(tool_name, params.clone()).await {
Ok(result) => {
tracing::info!("=== TOOL EXECUTION RESULT DEBUG ===");
tracing::info!("Tool: '{}'", tool_name);
tracing::info!("Content items: {}", result.content.len());
tracing::info!("is_error: {:?}", result.is_error);
// Log the raw result structure for debugging
tracing::debug!("Raw result structure: {:#?}", result);
// Log the actual content for debugging
if result.content.is_empty() {
tracing::warn!(
"⚠️ Tool returned EMPTY content array - this might indicate:"
);
tracing::warn!(" - Tool executed but produced no output");
tracing::warn!(" - Response parsing issue");
tracing::warn!(" - Server-side tool implementation issue");
} else {
tracing::info!("📄 Tool returned {} content items:", result.content.len());
for (i, content_item) in result.content.iter().enumerate() {
match content_item {
mcp_probe_core::messages::tools::ToolResult::Text { text } => {
tracing::info!(
"Content[{}]: Text with {} chars: '{}'",
i,
text.len(),
if text.len() > 200 { &text[..200] } else { text }
);
}
mcp_probe_core::messages::tools::ToolResult::Image {
mime_type,
data,
} => {
tracing::info!(
"Content[{}]: Image {} with {} bytes",
i,
mime_type,
data.len()
);
}
mcp_probe_core::messages::tools::ToolResult::Resource {
resource,
} => {
tracing::info!("Content[{}]: Resource {}", i, resource.uri);
}
}
}
}
// Convert result to JSON value for better handling
let result_json = match serde_json::to_value(&result) {
Ok(json) => {
tracing::info!("=== SERIALIZED RESULT JSON ===");
tracing::info!(
"{}",
serde_json::to_string_pretty(&json)
.unwrap_or_else(|_| "Failed to pretty print".to_string())
);
// Check if there are any unexpected fields
if let Some(obj) = json.as_object() {
tracing::debug!(
"Response contains {} top-level fields:",
obj.len()
);
for (key, value) in obj {
tracing::debug!(
" {}: {}",
key,
if value.is_string()
|| value.is_number()
|| value.is_boolean()
{
value.to_string()
} else {
format!(
"{} (type: {})",
if value.is_array() {
"array"
} else if value.is_object() {
"object"
} else {
"other"
},
if value.is_array() {
format!(
"length {}",
value.as_array().map_or(0, |arr| arr.len())
)
} else {
"".to_string()
}
)
}
);
}
}
json
}
Err(e) => {
tracing::error!("Failed to serialize tool result: {}", e);
self.add_error(format!("Failed to serialize tool result: {}", e));
return Ok(());
}
};
let success_summary = self.format_tool_response_summary(&result);
tracing::info!("=== SUCCESS SUMMARY ===");
tracing::info!("{}", success_summary);
// Additional analysis for empty responses
if result.content.is_empty() {
tracing::warn!("🔍 INVESTIGATING EMPTY RESPONSE:");
tracing::warn!(" - Tool name used: '{}'", tool_name);
tracing::warn!(
" - Parameters sent: {}",
serde_json::to_string(¶ms)
.unwrap_or_else(|_| "Failed to serialize".to_string())
);
tracing::warn!(" - is_error flag: {:?}", result.is_error);
tracing::warn!(" - This suggests the tool executed successfully but returned no content");
tracing::warn!(" - Check if the tool implementation on the server actually returns content");
}
self.add_message(MessageEntry {
timestamp: Instant::now(),
message_type: MessageType::CallTool,
request: None,
response: None,
raw_response: Some(result_json.clone()),
error: None,
success: Some(success_summary),
});
// Auto-open response viewer for successful tool execution
self.ui_state.selected_response = Some(result_json);
self.ui_state.response_viewer_open = true;
// Reset scroll positions to start from top
self.ui_state.response_viewer_vertical_pos = 0;
self.ui_state.response_viewer_horizontal_pos = 0;
// Select the latest message in history
if !self.message_history.is_empty() {
self.ui_state
.message_history_state
.select(Some(self.message_history.len() - 1));
}
tracing::info!(
"Tool '{}' executed successfully - response viewer opened",
tool_name
);
}
Err(e) => {
tracing::error!("=== TOOL EXECUTION FAILED ===");
tracing::error!("Tool: '{}'", tool_name);
tracing::error!("Error: {}", e);
tracing::error!("Error debug: {:?}", e);
// Try to get more specific error information
let error_msg = if e.to_string().contains("Serialization error") {
format!("🔧 Tool '{}' execution failed with SERIALIZATION ERROR: {}\n💡 This usually means:\n - Parameter format is incorrect\n - Tool name is malformed\n - Server rejected the request format", tool_name, e)
} else {
format!("Tool '{}' execution failed: {}", tool_name, e)
};
self.add_error(error_msg);
}
}
}
Ok(())
}
/// Format a tool response summary for display
fn format_tool_response_summary(
&self,
result: &mcp_probe_core::messages::tools::CallToolResponse,
) -> String {
use mcp_probe_core::messages::tools::ToolResult;
let content_summary = if result.content.is_empty() {
"No content returned (empty response)".to_string()
} else {
let mut summaries = Vec::new();
for (i, content_item) in result.content.iter().enumerate() {
let item_summary = match content_item {
ToolResult::Text { text } => {
if text.is_empty() {
format!("[{}] Empty text", i)
} else if text.len() > 100 {
format!("[{}] Text ({} chars): {}...", i, text.len(), &text[..97])
} else {
format!("[{}] Text: {}", i, text)
}
}
ToolResult::Image { data, mime_type } => {
format!("[{}] Image {} ({} bytes)", i, mime_type, data.len())
}
ToolResult::Resource { resource } => {
format!("[{}] Resource: {}", i, resource.uri)
}
};
summaries.push(item_summary);
}
summaries.join(", ")
};
let meta_info = if result.is_error == Some(true) {
" [ERROR]".to_string()
} else {
"".to_string()
};
format!(
"✅ Tool executed successfully{} - {}",
meta_info, content_summary
)
}
/// Format a resource response summary for display
fn format_resource_response_summary(
&self,
result: &mcp_probe_core::messages::resources::ReadResourceResponse,
) -> String {
let content_count = result.contents.len();
if content_count == 0 {
"✅ Resource retrieved (no content)".to_string()
} else if content_count == 1 {
let content = &result.contents[0];
let mime_info = content
.mime_type()
.map(|m| format!(" ({})", m))
.unwrap_or_default();
// Check content type and format accordingly
let content_desc = match content {
mcp_probe_core::messages::resources::ResourceContent::Text { text, .. } => {
if text.len() > 100 {
format!("{} chars", text.len())
} else {
text.clone()
}
}
mcp_probe_core::messages::resources::ResourceContent::Blob { blob, .. } => {
format!("{} bytes (binary)", blob.len())
}
};
format!("✅ Resource retrieved: {}{}", content_desc, mime_info)
} else {
format!("✅ Resource retrieved: {} content items", content_count)
}
}
/// Format a prompt response summary for display
fn format_prompt_response_summary(
&self,
result: &mcp_probe_core::messages::prompts::GetPromptResponse,
) -> String {
let msg_count = result.messages.len();
if msg_count == 0 {
"✅ Prompt retrieved (no messages)".to_string()
} else if msg_count == 1 {
let message = &result.messages[0];
// Get the content to describe the message
match &message.content {
mcp_probe_core::messages::prompts::PromptContent::Text { text } => {
if text.len() > 100 {
format!("✅ Prompt retrieved: {} chars", text.len())
} else {
format!("✅ Prompt retrieved: {}", text)
}
}
mcp_probe_core::messages::prompts::PromptContent::Image { .. } => {
"✅ Prompt retrieved: Image message".to_string()
}
mcp_probe_core::messages::prompts::PromptContent::Resource { .. } => {
"✅ Prompt retrieved: Resource message".to_string()
}
}
} else {
format!("✅ Prompt retrieved: {} messages", msg_count)
}
}
/// Get a resource
async fn get_resource(&mut self, resource_uri: &str) -> Result<()> {
if let Some(client) = &mut self.client {
match client.read_resource(resource_uri).await {
Ok(result) => {
let result_json = match serde_json::to_value(&result) {
Ok(json) => json,
Err(e) => {
self.add_error(format!("Failed to serialize resource result: {}", e));
return Ok(());
}
};
let summary = self.format_resource_response_summary(&result);
self.add_message(MessageEntry {
timestamp: Instant::now(),
message_type: MessageType::GetResource,
request: None,
response: None,
raw_response: Some(result_json.clone()),
error: None,
success: Some(summary),
});
// Auto-open response viewer for successful resource retrieval
self.ui_state.selected_response = Some(result_json);
self.ui_state.response_viewer_open = true;
// Reset scroll positions to start from top
self.ui_state.response_viewer_vertical_pos = 0;
self.ui_state.response_viewer_horizontal_pos = 0;
// Select the latest message in history
if !self.message_history.is_empty() {
self.ui_state
.message_history_state
.select(Some(self.message_history.len() - 1));
}
tracing::info!(
"Resource '{}' retrieved successfully - response viewer opened",
resource_uri
);
}
Err(e) => {
self.add_error(format!(
"Resource '{}' retrieval failed: {}",
resource_uri, e
));
}
}
}
Ok(())
}
/// Get a prompt
async fn get_prompt(&mut self, prompt_name: &str, params_str: &str) -> Result<()> {
if let Some(client) = &mut self.client {
let params: Value = serde_json::from_str(params_str)
.unwrap_or_else(|_| serde_json::Value::Object(serde_json::Map::new()));
match client.get_prompt(prompt_name, Some(params)).await {
Ok(result) => {
let result_json = match serde_json::to_value(&result) {
Ok(json) => json,
Err(e) => {
self.add_error(format!("Failed to serialize prompt result: {}", e));
return Ok(());
}
};
let summary = self.format_prompt_response_summary(&result);
self.add_message(MessageEntry {
timestamp: Instant::now(),
message_type: MessageType::GetPrompt,
request: None,
response: None,
raw_response: Some(result_json.clone()),
error: None,
success: Some(summary),
});
// Auto-open response viewer for successful prompt retrieval
self.ui_state.selected_response = Some(result_json);
self.ui_state.response_viewer_open = true;
// Reset scroll positions to start from top
self.ui_state.response_viewer_vertical_pos = 0;
self.ui_state.response_viewer_horizontal_pos = 0;
// Select the latest message in history
if !self.message_history.is_empty() {
self.ui_state
.message_history_state
.select(Some(self.message_history.len() - 1));
}
tracing::info!(
"Prompt '{}' retrieved successfully - response viewer opened",
prompt_name
);
}
Err(e) => {
self.add_error(format!("Prompt '{}' retrieval failed: {}", prompt_name, e));
}
}
}
Ok(())
}
/// Add a message to history
fn add_message(&mut self, message: MessageEntry) {
self.message_history.push(message);
self.message_count += 1;
// Limit history size
if self.message_history.len() > 1000 {
self.message_history.remove(0);
}
}
/// Add an error message
fn add_error(&mut self, error: String) {
self.error_count += 1;
self.add_message(MessageEntry {
timestamp: Instant::now(),
message_type: MessageType::Other("Error".to_string()),
request: None,
response: None,
raw_response: None,
error: Some(error),
success: None,
});
}
/// Save current session
async fn save_session(&self) -> Result<()> {
// TODO: Implement session saving
tracing::info!("Session saved (not implemented yet)");
Ok(())
}
/// Draw the main UI
fn draw_ui(&mut self, f: &mut Frame) {
let size = f.area();
// Main layout
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(3), // Header
Constraint::Min(0), // Main content
Constraint::Length(3), // Status bar
])
.split(size);
// Draw header
self.draw_header(f, chunks[0]);
// Draw main content
self.draw_main_content(f, chunks[1]);
// Draw status bar
self.draw_status_bar(f, chunks[2]);
// Draw dialogs
if self.ui_state.help_dialog_open {
self.draw_help_dialog(f, size);
}
if self.ui_state.env_dialog_open {
self.draw_env_dialog(f, size);
}
if self.ui_state.parameter_dialog_open {
self.draw_parameter_form_dialog(f, size);
}
if self.ui_state.search_active {
self.draw_search_popup(f, size);
}
if self.ui_state.response_viewer_open {
self.draw_response_viewer_dialog(f, size);
}
}
/// Draw the header
fn draw_header(&self, f: &mut Frame, area: Rect) {
let server_info = match &self.transport_config {
TransportConfig::Stdio(config) => format!("stdio:{}", config.command),
TransportConfig::HttpSse(config) => format!("http+sse:{}", config.base_url),
TransportConfig::HttpStream(config) => format!("http-stream:{}", config.base_url),
};
let status = match &self.state {
AppState::Initializing => "Initializing".to_string(),
AppState::Connecting => "Connecting".to_string(),
AppState::Discovering => {
if self.discovery_step.is_empty() {
"Discovering".to_string()
} else {
format!("Discovering: {}", self.discovery_step)
}
}
AppState::Ready => "Connected".to_string(),
AppState::Error(_) => "Error".to_string(),
AppState::ShuttingDown => "Shutting Down".to_string(),
};
let session_info = if let Some(ref session_id) = self.session_id {
format!(
" | Session: {}",
if session_id.len() > 16 {
&session_id[..16]
} else {
session_id
}
)
} else {
String::new()
};
let header_text = format!(
"Server: {} | Transport: {} | Status: {} | Protocol: MCP-2024-11-05{}",
server_info,
self.transport_config.transport_type(),
status,
session_info
);
let header = Paragraph::new(header_text)
.style(Style::default().fg(Color::White).bg(Color::Blue))
.alignment(Alignment::Center)
.block(
Block::default()
.borders(Borders::ALL)
.title("MCP Client Debugger"),
);
f.render_widget(header, area);
}
/// Draw the main content area
fn draw_main_content(&mut self, f: &mut Frame, area: Rect) {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Percentage(50), // Top row
Constraint::Percentage(50), // Bottom row
])
.split(area);
// Top row layout
let top_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(25), // Protocol Flow
Constraint::Percentage(50), // Message Inspector
Constraint::Percentage(25), // Controls
])
.split(chunks[0]);
// Bottom row layout
let bottom_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(25), // Capabilities
Constraint::Percentage(75), // Interactive Terminal
])
.split(chunks[1]);
// Draw panels
self.draw_protocol_flow(f, top_chunks[0]);
self.draw_message_inspector(f, top_chunks[1]);
self.draw_controls(f, top_chunks[2]);
self.draw_capabilities(f, bottom_chunks[0]);
self.draw_interactive_terminal(f, bottom_chunks[1]);
}
/// Draw protocol flow panel
fn draw_protocol_flow(&mut self, f: &mut Frame, area: Rect) {
let steps = [
"1. ✓ Initialize",
"2. ✓ Negotiate",
"3. ✓ Discover",
"4. → Test Tools",
"5. Validate",
];
let items: Vec<ListItem> = steps.iter().map(|step| ListItem::new(*step)).collect();
let list = List::new(items)
.block(
Block::default()
.borders(Borders::ALL)
.title("Protocol Flow"),
)
.highlight_style(Style::default().fg(Color::Yellow));
f.render_stateful_widget(list, area, &mut self.ui_state.protocol_flow_state);
}
/// Draw message inspector panel - shows detailed capability lists or message inspection
fn draw_message_inspector(&mut self, f: &mut Frame, area: Rect) {
match &self.ui_state.capability_view {
CapabilityView::DetailedList(category) => {
self.draw_capability_details(f, area, category.clone());
}
CapabilityView::Categories => {
self.draw_message_details(f, area);
}
}
}
/// Draw detailed capability list for selected category
fn draw_capability_details(&mut self, f: &mut Frame, area: Rect, category: CapabilityCategory) {
let mut items = Vec::new();
let mut capability_refs = Vec::new();
let selected_detail_index = self
.ui_state
.capability_detail_state
.selected()
.unwrap_or(0);
let (title, total_count) = match category {
CapabilityCategory::Tools => {
let start = self.ui_state.capability_page * self.ui_state.capability_page_size;
for (display_idx, (i, tool)) in self
.capabilities
.tools
.iter()
.enumerate()
.skip(start)
.take(self.ui_state.capability_page_size)
.enumerate()
{
// Format description with truncation
let desc = tool
.description
.as_ref()
.map(|d| {
if d.len() > 80 {
format!("{}...", &d[..77])
} else {
d.clone()
}
})
.unwrap_or_else(|| "No description available".to_string());
// Extract parameter information
let params_info = if let Some(ref params) = tool.parameters {
if let Some(properties) = params.get("properties") {
if let Some(obj) = properties.as_object() {
let required_params: Vec<String> = params
.get("required")
.and_then(|r| r.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
})
.unwrap_or_default();
let param_count = obj.len();
let required_count = required_params.len();
if param_count > 0 {
format!(
"📋 {} params ({} required)",
param_count, required_count
)
} else {
"📋 No parameters".to_string()
}
} else {
"📋 Parameters available".to_string()
}
} else {
"📋 No parameters".to_string()
}
} else {
"📋 No parameters".to_string()
};
// Create multi-line item with selection indicator
let selection_indicator = if display_idx == selected_detail_index {
"→ "
} else {
" "
};
let tool_name_style = if display_idx == selected_detail_index {
Style::default()
.fg(Color::Yellow)
.add_modifier(ratatui::style::Modifier::BOLD)
} else {
Style::default()
.fg(Color::Cyan)
.add_modifier(ratatui::style::Modifier::BOLD)
};
let item_text = vec![
Line::from(vec![
Span::raw(selection_indicator),
Span::styled(format!("🔧 {}", tool.name), tool_name_style),
]),
Line::from(vec![
Span::raw(" "),
Span::styled(params_info, Style::default().fg(Color::Green)),
]),
Line::from(vec![
Span::raw(" "),
Span::styled(desc, Style::default().fg(Color::White)),
]),
Line::from(""), // Empty line for spacing
];
items.push(ListItem::new(item_text));
capability_refs.push(CapabilityRef::Tool(i));
}
(format!("🔧 Tools - Page {}/{} [↑/↓ Navigate, Enter Select & Configure, ←/→ Page, Esc Back]",
self.ui_state.capability_page + 1,
self.capabilities.tools.len().div_ceil(self.ui_state.capability_page_size)),
self.capabilities.tools.len())
}
CapabilityCategory::Resources => {
let start = self.ui_state.capability_page * self.ui_state.capability_page_size;
for (display_idx, (i, resource)) in self
.capabilities
.resources
.iter()
.enumerate()
.skip(start)
.take(self.ui_state.capability_page_size)
.enumerate()
{
let name = resource.name.as_ref().unwrap_or(&resource.uri);
let desc = resource
.description
.as_ref()
.map(|d| {
if d.len() > 80 {
format!("{}...", &d[..77])
} else {
d.clone()
}
})
.unwrap_or_else(|| "No description available".to_string());
let mime_info = resource
.mime_type
.as_ref()
.map(|m| format!("📄 Type: {}", m))
.unwrap_or_else(|| "📄 Type: Unknown".to_string());
let selection_indicator = if display_idx == selected_detail_index {
"→ "
} else {
" "
};
let resource_name_style = if display_idx == selected_detail_index {
Style::default()
.fg(Color::Yellow)
.add_modifier(ratatui::style::Modifier::BOLD)
} else {
Style::default()
.fg(Color::Green)
.add_modifier(ratatui::style::Modifier::BOLD)
};
let item_text = vec![
Line::from(vec![
Span::raw(selection_indicator),
Span::styled(format!("📁 {}", name), resource_name_style),
]),
Line::from(vec![
Span::raw(" "),
Span::styled(
format!("🔗 URI: {}", resource.uri),
Style::default().fg(Color::Blue),
),
]),
Line::from(vec![
Span::raw(" "),
Span::styled(mime_info, Style::default().fg(Color::Green)),
]),
Line::from(vec![
Span::raw(" "),
Span::styled(desc, Style::default().fg(Color::White)),
]),
Line::from(""), // Empty line for spacing
];
items.push(ListItem::new(item_text));
capability_refs.push(CapabilityRef::Resource(i));
}
(
format!(
"📁 Resources - Page {}/{} [↑/↓ Navigate, Enter Read, ←/→ Page, Esc Back]",
self.ui_state.capability_page + 1,
self.capabilities
.resources
.len()
.div_ceil(self.ui_state.capability_page_size)
),
self.capabilities.resources.len(),
)
}
CapabilityCategory::Prompts => {
let start = self.ui_state.capability_page * self.ui_state.capability_page_size;
for (display_idx, (i, prompt)) in self
.capabilities
.prompts
.iter()
.enumerate()
.skip(start)
.take(self.ui_state.capability_page_size)
.enumerate()
{
let desc = prompt
.description
.as_ref()
.map(|d| {
if d.len() > 80 {
format!("{}...", &d[..77])
} else {
d.clone()
}
})
.unwrap_or_else(|| "No description available".to_string());
let args_info = if let Some(ref args) = prompt.arguments {
if let Some(properties) = args.get("properties") {
if let Some(obj) = properties.as_object() {
let required_args: Vec<String> = args
.get("required")
.and_then(|r| r.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
})
.unwrap_or_default();
let arg_count = obj.len();
let required_count = required_args.len();
if arg_count > 0 {
format!(
"📝 {} arguments ({} required)",
arg_count, required_count
)
} else {
"📝 No arguments".to_string()
}
} else {
"📝 Arguments available".to_string()
}
} else {
"📝 No arguments".to_string()
}
} else {
"📝 No arguments".to_string()
};
let selection_indicator = if display_idx == selected_detail_index {
"→ "
} else {
" "
};
let prompt_name_style = if display_idx == selected_detail_index {
Style::default()
.fg(Color::Yellow)
.add_modifier(ratatui::style::Modifier::BOLD)
} else {
Style::default()
.fg(Color::Magenta)
.add_modifier(ratatui::style::Modifier::BOLD)
};
let item_text = vec![
Line::from(vec![
Span::raw(selection_indicator),
Span::styled(format!("💬 {}", prompt.name), prompt_name_style),
]),
Line::from(vec![
Span::raw(" "),
Span::styled(args_info, Style::default().fg(Color::Green)),
]),
Line::from(vec![
Span::raw(" "),
Span::styled(desc, Style::default().fg(Color::White)),
]),
Line::from(""), // Empty line for spacing
];
items.push(ListItem::new(item_text));
capability_refs.push(CapabilityRef::Prompt(i));
}
(format!("💬 Prompts - Page {}/{} [↑/↓ Navigate, Enter Configure & Run, ←/→ Page, Esc Back]",
self.ui_state.capability_page + 1,
self.capabilities.prompts.len().div_ceil(self.ui_state.capability_page_size)),
self.capabilities.prompts.len())
}
};
// Store capability references for selection
self.ui_state.capability_indices = capability_refs.into_iter().map(Some).collect();
let border_style = if self.ui_state.current_focus == FocusedPanel::Capabilities {
Style::default().fg(Color::Yellow)
} else {
Style::default()
};
let list = List::new(items.clone())
.block(
Block::default()
.borders(Borders::ALL)
.title(title)
.border_style(border_style),
)
.highlight_style(Style::default().fg(Color::Black).bg(Color::Green));
// Update scrollbar state for capability details
let item_count = items.len().saturating_sub(1);
self.ui_state.capability_details_scroll = self
.ui_state
.capability_details_scroll
.content_length(item_count);
let scroll_pos = self
.ui_state
.capability_detail_state
.selected()
.unwrap_or(0);
self.ui_state.capability_details_scroll =
self.ui_state.capability_details_scroll.position(scroll_pos);
f.render_stateful_widget(list, area, &mut self.ui_state.capability_detail_state);
// Render the scrollbar for capability details
f.render_stateful_widget(
Scrollbar::default()
.orientation(ScrollbarOrientation::VerticalRight)
.begin_symbol(Some("↑"))
.end_symbol(Some("↓")),
area,
&mut self.ui_state.capability_details_scroll,
);
// Show additional info at bottom
if total_count > self.ui_state.capability_page_size {
let info_area = Rect {
x: area.x + 2,
y: area.y + area.height - 2,
width: area.width - 4,
height: 1,
};
let page_info = format!(
"📊 Showing {} of {} capabilities | Use ← → to navigate pages",
std::cmp::min(
self.ui_state.capability_page_size,
total_count
- (self.ui_state.capability_page * self.ui_state.capability_page_size)
),
total_count
);
let paragraph = Paragraph::new(page_info).style(Style::default().fg(Color::Cyan));
f.render_widget(paragraph, info_area);
}
}
/// Draw message details (original message inspector functionality)
fn draw_message_details(&mut self, f: &mut Frame, area: Rect) {
let _inner = area.inner(Margin {
vertical: 1,
horizontal: 1,
});
let content = if let Some(index) = self.ui_state.selected_message_index {
if let Some(message) = self.message_history.get(index) {
let mut text = Vec::new();
if let Some(request) = &message.request {
text.push(Line::from(vec![Span::styled(
"Request:",
Style::default().fg(Color::Green),
)]));
text.push(Line::from(
serde_json::to_string_pretty(request).unwrap_or_default(),
));
}
if let Some(response) = &message.response {
text.push(Line::from(""));
text.push(Line::from(vec![Span::styled(
"Response:",
Style::default().fg(Color::Blue),
)]));
text.push(Line::from(
serde_json::to_string_pretty(response).unwrap_or_default(),
));
}
if let Some(error) = &message.error {
text.push(Line::from(""));
text.push(Line::from(vec![Span::styled(
"Error:",
Style::default().fg(Color::Red),
)]));
text.push(Line::from(error.clone()));
}
if let Some(success) = &message.success {
text.push(Line::from(""));
text.push(Line::from(vec![Span::styled(
"Success:",
Style::default().fg(Color::Green),
)]));
text.push(Line::from(success.clone()));
}
Text::from(text)
} else {
Text::from("No message selected")
}
} else {
Text::from("Select a message to inspect or capability category to explore")
};
let paragraph = Paragraph::new(content)
.block(
Block::default()
.borders(Borders::ALL)
.title("Message Inspector"),
)
.wrap(Wrap { trim: true });
f.render_widget(paragraph, area);
}
/// Draw controls panel
fn draw_controls(&self, f: &mut Frame, area: Rect) {
let controls = [
"[F1] Help",
"[F2] Save",
"[F3] Raw JSON",
"[F4] Clear",
"[F5] Env Vars",
"[Q] Quit",
];
let items: Vec<ListItem> = controls
.iter()
.map(|control| ListItem::new(*control))
.collect();
let list = List::new(items).block(Block::default().borders(Borders::ALL).title("Controls"));
f.render_widget(list, area);
}
/// Draw capabilities panel - shows categories
fn draw_capabilities(&mut self, f: &mut Frame, area: Rect) {
let mut items = Vec::new();
// Show capability categories with better visual cues
let tools_count = self.capabilities.tools.len();
let resources_count = self.capabilities.resources.len();
let prompts_count = self.capabilities.prompts.len();
// Add visual indicators for selected item
let selected_index = self.ui_state.capabilities_state.selected().unwrap_or(0);
items.push(ListItem::new(Line::from(vec![
if selected_index == 0 { "→ " } else { " " }.into(),
Span::styled(
"🔧 Tools",
Style::default()
.fg(Color::Cyan)
.add_modifier(ratatui::style::Modifier::BOLD),
),
Span::styled(
format!(" ({}) ", tools_count),
Style::default().fg(Color::White),
),
if tools_count > 0 {
Span::styled(
"- GitHub API, calculations, etc.",
Style::default().fg(Color::DarkGray),
)
} else {
Span::styled("- No tools available", Style::default().fg(Color::Red))
},
])));
items.push(ListItem::new(Line::from(vec![
if selected_index == 1 { "→ " } else { " " }.into(),
Span::styled(
"📁 Resources",
Style::default()
.fg(Color::Green)
.add_modifier(ratatui::style::Modifier::BOLD),
),
Span::styled(
format!(" ({}) ", resources_count),
Style::default().fg(Color::White),
),
if resources_count > 0 {
Span::styled(
"- Files, documents, data sources",
Style::default().fg(Color::DarkGray),
)
} else {
Span::styled("- No resources available", Style::default().fg(Color::Red))
},
])));
items.push(ListItem::new(Line::from(vec![
if selected_index == 2 { "→ " } else { " " }.into(),
Span::styled(
"💬 Prompts",
Style::default()
.fg(Color::Magenta)
.add_modifier(ratatui::style::Modifier::BOLD),
),
Span::styled(
format!(" ({}) ", prompts_count),
Style::default().fg(Color::White),
),
if prompts_count > 0 {
Span::styled(
"- Templates, conversations, queries",
Style::default().fg(Color::DarkGray),
)
} else {
Span::styled("- No prompts available", Style::default().fg(Color::Red))
},
])));
// Add a search prompt
items.push(ListItem::new(Line::from(""))); // Empty line
items.push(ListItem::new(Line::from(vec![
Span::styled("🔍 Press ", Style::default().fg(Color::Yellow)),
Span::styled(
"/",
Style::default()
.fg(Color::Yellow)
.add_modifier(ratatui::style::Modifier::BOLD),
),
Span::styled(
" to search all capabilities instantly!",
Style::default().fg(Color::Yellow),
),
])));
let title = if self.ui_state.current_focus == FocusedPanel::Capabilities {
match self.ui_state.capability_view {
CapabilityView::Categories => {
"🎯 Select Category [↑/↓ Navigate, Enter Browse, / Search, Tab Switch Panel]"
}
CapabilityView::DetailedList(_) => {
"📋 Capability Browser [Esc Back to Categories, / Search]"
}
}
} else {
"Categories [Tab to Focus, / Search]"
};
let border_style = if self.ui_state.current_focus == FocusedPanel::Capabilities {
Style::default().fg(Color::Yellow)
} else {
Style::default()
};
let list = List::new(items)
.block(
Block::default()
.borders(Borders::ALL)
.title(title)
.border_style(border_style),
)
.highlight_style(Style::default().fg(Color::Black).bg(Color::Yellow));
f.render_stateful_widget(list, area, &mut self.ui_state.capabilities_state);
}
/// Draw search popup
fn draw_search_popup(&mut self, f: &mut Frame, area: Rect) {
let popup_area = centered_rect(90, 80, area);
f.render_widget(Clear, popup_area);
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(3), // Search input
Constraint::Min(0), // Search results
Constraint::Length(3), // Instructions
])
.split(popup_area);
// Draw search input
let search_block = Block::default()
.borders(Borders::ALL)
.title("🔍 Search MCP Capabilities - Instant Fuzzy Search")
.border_style(Style::default().fg(Color::Yellow));
self.ui_state.search_input.set_block(search_block);
f.render_widget(&self.ui_state.search_input, chunks[0]);
// Draw search results
if self.ui_state.search_results.is_empty() {
let no_results_text = if self
.ui_state
.search_input
.lines()
.join("")
.trim()
.is_empty()
{
format!("💡 Start typing to search across {} capabilities...\n\n🎯 Search Features:\n• Exact name matches (highest priority)\n• Prefix matches (e.g., 'git' finds 'github_*')\n• Description keywords\n• Fuzzy matching (handles typos)\n• Token-based search\n\n📊 Available:\n• 🔧 {} Tools\n• 📁 {} Resources\n• 💬 {} Prompts",
self.search_engine.total_items(),
self.capabilities.tools.len(),
self.capabilities.resources.len(),
self.capabilities.prompts.len())
} else {
"❌ No results found.\n\n💡 Try:\n• Different keywords\n• Checking spelling\n• Using partial names\n• Searching by description terms".to_string()
};
let no_results = Paragraph::new(no_results_text)
.style(Style::default().fg(Color::Cyan))
.alignment(ratatui::layout::Alignment::Center)
.block(
Block::default()
.borders(Borders::ALL)
.title("Search Results")
.border_style(Style::default().fg(Color::Yellow)),
)
.wrap(ratatui::widgets::Wrap { trim: true });
f.render_widget(no_results, chunks[1]);
} else {
// Show search results
let results_items: Vec<ListItem> = self
.ui_state
.search_results
.iter()
.map(|result| {
if let Some(item) = self.search_engine.get_item(result.index) {
let category_icon = match item.category {
SearchCategory::Tool => "🔧",
SearchCategory::Resource => "📁",
SearchCategory::Prompt => "💬",
};
let category_color = match item.category {
SearchCategory::Tool => Color::Cyan,
SearchCategory::Resource => Color::Green,
SearchCategory::Prompt => Color::Magenta,
};
let score_display = format!("{:.0}%", result.score);
let description_preview = if item.description.len() > 120 {
format!("{}...", &item.description[..117])
} else {
item.description.clone()
};
// Create multi-line item for better readability
let content = vec![
Line::from(vec![
Span::styled(category_icon, Style::default().fg(category_color)),
Span::styled(" ", Style::default()),
Span::styled(
&item.name,
Style::default()
.fg(category_color)
.add_modifier(ratatui::style::Modifier::BOLD),
),
Span::styled(" ", Style::default()),
Span::styled(
format!("(Match: {})", score_display),
Style::default().fg(Color::Yellow),
),
Span::styled(
format!(" - {}", result.match_reason),
Style::default().fg(Color::Cyan),
),
]),
Line::from(vec![
Span::styled(" ", Style::default()),
Span::styled(
description_preview,
Style::default().fg(Color::White),
),
]),
Line::from(""), // Empty line for spacing
];
ListItem::new(content)
} else {
ListItem::new("❌ Invalid result")
}
})
.collect();
let results_list = List::new(results_items)
.block(
Block::default()
.borders(Borders::ALL)
.title(format!(
"🎯 Search Results ({} matches found, best matches first)",
self.ui_state.search_results.len()
))
.border_style(Style::default().fg(Color::Yellow)),
)
.highlight_style(Style::default().fg(Color::Black).bg(Color::Yellow));
// Update scrollbar state for search results
let results_count = self.ui_state.search_results.len().saturating_sub(1);
self.ui_state.search_results_scroll = self
.ui_state
.search_results_scroll
.content_length(results_count);
let scroll_pos = self.ui_state.search_results_state.selected().unwrap_or(0);
self.ui_state.search_results_scroll =
self.ui_state.search_results_scroll.position(scroll_pos);
f.render_stateful_widget(
results_list,
chunks[1],
&mut self.ui_state.search_results_state,
);
// Render the scrollbar for search results
f.render_stateful_widget(
Scrollbar::default()
.orientation(ScrollbarOrientation::VerticalRight)
.begin_symbol(Some("↑"))
.end_symbol(Some("↓")),
chunks[1],
&mut self.ui_state.search_results_scroll,
);
}
// Draw instructions
let instructions = "🔍 Advanced Search: Exact names, partial matches, keywords, and fuzzy matching | [↑/↓] Navigate | [Enter] Select & Configure | [Esc] Close";
let instructions_paragraph = Paragraph::new(instructions)
.style(
Style::default()
.fg(Color::Yellow)
.add_modifier(ratatui::style::Modifier::BOLD),
)
.alignment(ratatui::layout::Alignment::Center)
.block(Block::default().borders(Borders::ALL).title("Instructions"));
f.render_widget(instructions_paragraph, chunks[2]);
}
/// Draw interactive terminal panel
fn draw_interactive_terminal(&mut self, f: &mut Frame, area: Rect) {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Min(0), // History
Constraint::Length(3), // Input
])
.split(area);
// Draw message history with scrollbar
let history_items: Vec<ListItem> = self
.message_history
.iter()
.map(|msg| {
let timestamp = msg.timestamp.duration_since(self.session_start);
let time_str = format!(
"{:02}:{:02}",
timestamp.as_secs() / 60,
timestamp.as_secs() % 60
);
// Add response indicator
let response_indicator = if msg.raw_response.is_some() {
" [R]" // R indicates response available for viewing
} else {
""
};
let (content, style) = if let Some(error) = &msg.error {
(
format!("[{}] ERROR: {}{}", time_str, error, response_indicator),
Style::default().fg(Color::Red),
)
} else if let Some(success) = &msg.success {
(
format!("[{}] SUCCESS: {}{}", time_str, success, response_indicator),
Style::default().fg(Color::Green),
)
} else {
(
format!("[{}] {}{}", time_str, msg.message_type, response_indicator),
Style::default(),
)
};
ListItem::new(content).style(style)
})
.collect();
let history_list = List::new(history_items)
.block(Block::default().borders(Borders::ALL).title("Message History [↑/↓ Navigate, ←/→ Scroll, R Response Viewer, Tab Latest Response]"))
.highlight_style(Style::default().fg(Color::Yellow));
// Update scrollbar state based on content length and area
self.ui_state.message_scroll = self
.ui_state
.message_scroll
.content_length(self.message_history.len().saturating_sub(1));
let scroll_pos = self.ui_state.message_history_state.selected().unwrap_or(0);
self.ui_state.message_scroll = self.ui_state.message_scroll.position(scroll_pos);
f.render_stateful_widget(
history_list,
chunks[0],
&mut self.ui_state.message_history_state,
);
// Render the scrollbar
f.render_stateful_widget(
Scrollbar::default()
.orientation(ScrollbarOrientation::VerticalRight)
.begin_symbol(Some("↑"))
.end_symbol(Some("↓")),
chunks[0],
&mut self.ui_state.message_scroll,
);
// Draw input area
let input_style = if self.ui_state.current_focus == FocusedPanel::Input {
Style::default().fg(Color::Yellow)
} else {
Style::default()
};
let input_block = Block::default()
.borders(Borders::ALL)
.title("Interactive Terminal")
.style(input_style);
self.ui_state.input_area.set_block(input_block);
f.render_widget(&self.ui_state.input_area, chunks[1]);
}
/// Draw status bar
fn draw_status_bar(&self, f: &mut Frame, area: Rect) {
let uptime = self.session_start.elapsed();
let status_text = match &self.state {
AppState::Ready => "Ready".to_string(),
AppState::Connecting => "Connecting".to_string(),
AppState::Discovering => {
if self.discovery_step.is_empty() {
"Discovering".to_string()
} else {
format!("Discovering: {}", self.discovery_step)
}
}
AppState::Error(e) => format!("Error: {}", e),
AppState::Initializing => "Initializing".to_string(),
AppState::ShuttingDown => "Shutting down".to_string(),
};
let session_info = if let Some(ref session_id) = self.session_id {
format!(
" | Session: {}",
if session_id.len() > 12 {
&session_id[..12]
} else {
session_id
}
)
} else {
String::new()
};
let search_status = if self.ui_state.search_active {
" | 🔍 SEARCH ACTIVE"
} else {
" | Press / to search"
};
let response_status = if self.ui_state.response_viewer_open {
" | 📊 RESPONSE VIEWER (Press V to cycle views, Esc to close)"
} else {
" | Press Tab for latest results"
};
let full_status = format!(
"Status: {} | Messages: {} | Errors: {} | Uptime: {:02}:{:02}:{:02} | Env Vars: {}{}{}{}",
status_text,
self.message_count,
self.error_count,
uptime.as_secs() / 3600,
(uptime.as_secs() % 3600) / 60,
uptime.as_secs() % 60,
self.env_variables.len(),
session_info,
search_status,
response_status
);
let status_bar = Paragraph::new(full_status)
.style(Style::default().fg(Color::White).bg(Color::Black))
.alignment(Alignment::Left)
.block(Block::default().borders(Borders::ALL));
f.render_widget(status_bar, area);
}
/// Draw help dialog
fn draw_help_dialog(&self, f: &mut Frame, area: Rect) {
let popup_area = centered_rect(80, 60, area);
let help_text = vec![
Line::from("MCP Probe Help"),
Line::from(""),
Line::from("🔍 SEARCH CAPABILITIES:"),
Line::from(" / - Activate smart search (fuzzy matching)"),
Line::from(" ↑/↓ - Navigate search results"),
Line::from(" Enter - Select and configure capability"),
Line::from(" Esc - Exit search mode"),
Line::from(""),
Line::from("📊 RESPONSE VIEWER:"),
Line::from(" Tab - Open latest response automatically"),
Line::from(" R - Open response viewer for selected message [R]"),
Line::from(" V - Cycle view modes (Formatted/Raw/Tree/Summary)"),
Line::from(" ↑/↓ - Scroll vertically"),
Line::from(" ←/→ - Scroll horizontally"),
Line::from(" PgUp/PgDn - Fast vertical scrolling"),
Line::from(" Home/End - Jump to top/bottom"),
Line::from(" Esc - Close response viewer"),
Line::from(""),
Line::from("📝 PARAMETER FORMS:"),
Line::from(" ↑/↓ - Navigate fields (auto-edit mode)"),
Line::from(" Type - Edit field values directly"),
Line::from(" Enter - Save field and move to next"),
Line::from(" Tab - Execute with current values"),
Line::from(" Esc - Cancel and go back"),
Line::from(""),
Line::from("Navigation:"),
Line::from(" Tab - Auto-open latest results / Cycle panels"),
Line::from(" Enter - Execute command / Confirm"),
Line::from(" Esc - Close dialogs"),
Line::from(""),
Line::from("Function Keys:"),
Line::from(" F1 - Toggle this help"),
Line::from(" F2 - Save session"),
Line::from(" F3 - Toggle raw JSON view"),
Line::from(" F4 - Clear message history"),
Line::from(" F5 - Environment variables"),
Line::from(" Q - Quit application"),
Line::from(""),
Line::from("Commands:"),
Line::from(" tools.name {\"param\": \"value\"}"),
Line::from(" resources.uri"),
Line::from(" prompts.name {\"param\": \"value\"}"),
Line::from(""),
Line::from("Environment Variables:"),
Line::from(" Set KEY=value,KEY2=value2 format"),
Line::from(" Variables are auto-injected into tool calls"),
];
let help_paragraph = Paragraph::new(help_text)
.block(Block::default().borders(Borders::ALL).title("Help"))
.wrap(Wrap { trim: true });
f.render_widget(Clear, popup_area);
f.render_widget(help_paragraph, popup_area);
}
/// Draw environment variables dialog
fn draw_env_dialog(&mut self, f: &mut Frame, area: Rect) {
let popup_area = centered_rect(70, 50, area);
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(3), // Title
Constraint::Length(3), // Input
Constraint::Min(0), // Current variables
Constraint::Length(3), // Instructions
])
.split(popup_area);
// Title
let title = Paragraph::new("Environment Variables Configuration")
.block(Block::default().borders(Borders::ALL))
.alignment(Alignment::Center);
f.render_widget(Clear, popup_area);
f.render_widget(title, chunks[0]);
// Input area
let input_style = if self.ui_state.current_focus == FocusedPanel::EnvVariables {
Style::default().fg(Color::Yellow)
} else {
Style::default()
};
let input_block = Block::default()
.borders(Borders::ALL)
.title("Environment Variables")
.style(input_style);
self.ui_state.env_input_area.set_block(input_block);
f.render_widget(&self.ui_state.env_input_area, chunks[1]);
// Current variables with scrollbar
let current_vars: Vec<ListItem> = self
.env_variables
.iter()
.map(|(key, value)| ListItem::new(format!("{}={}", key, value)))
.collect();
let vars_list = List::new(current_vars).block(
Block::default()
.borders(Borders::ALL)
.title("Current Variables"),
);
// Update scrollbar state for environment variables
let env_count = self.env_variables.len().saturating_sub(1);
self.ui_state.env_vars_scroll = self.ui_state.env_vars_scroll.content_length(env_count);
// No selection state for env vars, so we'll keep position at 0
self.ui_state.env_vars_scroll = self.ui_state.env_vars_scroll.position(0);
f.render_widget(vars_list, chunks[2]);
// Render the scrollbar for environment variables
if !self.env_variables.is_empty() {
f.render_stateful_widget(
Scrollbar::default()
.orientation(ScrollbarOrientation::VerticalRight)
.begin_symbol(Some("↑"))
.end_symbol(Some("↓")),
chunks[2],
&mut self.ui_state.env_vars_scroll,
);
}
// Instructions
let instructions = Paragraph::new(
"Enter variables as KEY=value,KEY2=value2... | Press Enter to apply | Esc to cancel",
)
.block(Block::default().borders(Borders::ALL))
.alignment(Alignment::Center);
f.render_widget(instructions, chunks[3]);
}
/// Draw parameter form dialog
fn draw_parameter_form_dialog(&mut self, f: &mut Frame, area: Rect) {
let popup_area = centered_rect(90, 80, area);
f.render_widget(Clear, popup_area);
if let Some(capability_ref) = self.ui_state.selected_capability.clone() {
// Use the new enhanced parameter form
self.draw_parameter_form(f, popup_area, &capability_ref);
} else {
// Fallback for unknown capability
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(3), // Title
Constraint::Min(0), // Content
Constraint::Length(3), // Instructions
])
.split(popup_area);
let title = Paragraph::new("❌ Error: Unknown Capability")
.block(
Block::default()
.borders(Borders::ALL)
.border_style(Style::default().fg(Color::Red)),
)
.alignment(Alignment::Center)
.style(
Style::default()
.fg(Color::Red)
.add_modifier(ratatui::style::Modifier::BOLD),
);
f.render_widget(title, chunks[0]);
let content = Paragraph::new("No capability selected for parameter configuration.\nThis shouldn't happen - please report this bug.")
.block(Block::default().borders(Borders::ALL))
.alignment(Alignment::Center)
.wrap(Wrap { trim: true })
.style(Style::default().fg(Color::White));
f.render_widget(content, chunks[1]);
let instructions = Paragraph::new("🔙 [Esc] Go Back")
.block(Block::default().borders(Borders::ALL))
.alignment(Alignment::Center)
.style(Style::default().fg(Color::Yellow));
f.render_widget(instructions, chunks[2]);
}
}
/// Draw parameter input form
fn draw_parameter_form(&mut self, f: &mut Frame, area: Rect, capability_ref: &CapabilityRef) {
// Split area for form header and fields
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(3), // Header with capability info
Constraint::Min(1), // Parameter fields
Constraint::Length(3), // Instructions/controls
])
.split(area);
// Draw header with capability information
let (header_text, header_style) = match capability_ref {
CapabilityRef::Tool(i) => {
if let Some(tool) = self.capabilities.tools.get(*i) {
(
format!("🔧 Configure Tool: {}", tool.name),
Style::default().fg(Color::Cyan),
)
} else {
(
"🔧 Tool Configuration".to_string(),
Style::default().fg(Color::Cyan),
)
}
}
CapabilityRef::Resource(i) => {
if let Some(resource) = self.capabilities.resources.get(*i) {
let name = resource.name.as_ref().unwrap_or(&resource.uri);
(
format!("📁 Read Resource: {}", name),
Style::default().fg(Color::Green),
)
} else {
(
"📁 Resource Access".to_string(),
Style::default().fg(Color::Green),
)
}
}
CapabilityRef::Prompt(i) => {
if let Some(prompt) = self.capabilities.prompts.get(*i) {
(
format!("💬 Configure Prompt: {}", prompt.name),
Style::default().fg(Color::Magenta),
)
} else {
(
"💬 Prompt Configuration".to_string(),
Style::default().fg(Color::Magenta),
)
}
}
};
let header_block = Block::default()
.borders(Borders::ALL)
.title("Parameter Configuration")
.border_style(Style::default().fg(Color::Yellow));
let header_paragraph = Paragraph::new(header_text)
.style(header_style.add_modifier(ratatui::style::Modifier::BOLD))
.alignment(ratatui::layout::Alignment::Center)
.block(header_block);
f.render_widget(header_paragraph, chunks[0]);
// Draw parameter fields
if self.ui_state.param_field_names.is_empty() {
// No parameters needed
let no_params_text = match capability_ref {
CapabilityRef::Tool(_) => "✅ This tool requires no parameters.\n\nPress Enter to execute immediately, or Esc to cancel.",
CapabilityRef::Resource(_) => "✅ This resource requires no parameters.\n\nPress Enter to read the resource, or Esc to cancel.",
CapabilityRef::Prompt(_) => "✅ This prompt requires no arguments.\n\nPress Enter to run the prompt, or Esc to cancel.",
};
let no_params_paragraph = Paragraph::new(no_params_text)
.style(Style::default().fg(Color::Green))
.alignment(ratatui::layout::Alignment::Center)
.block(Block::default().borders(Borders::ALL))
.wrap(ratatui::widgets::Wrap { trim: true });
f.render_widget(no_params_paragraph, chunks[1]);
} else {
// Show parameter input fields
let field_height = 3; // Each field takes 3 lines
let available_height = chunks[1].height as usize;
let max_visible_fields = available_height / field_height;
let selected_field = self.ui_state.param_selected_field;
let scroll_start = if selected_field >= max_visible_fields {
selected_field - max_visible_fields + 1
} else {
0
};
let mut y_offset = 0;
for (field_idx, param_name) in self
.ui_state
.param_field_names
.iter()
.enumerate()
.skip(scroll_start)
.take(max_visible_fields)
{
let field = match self.ui_state.param_fields.get(param_name) {
Some(f) => f,
None => {
tracing::error!("Field '{}' not found in param_fields", param_name);
continue;
}
};
if y_offset + field_height > available_height {
break;
}
let field_area = Rect {
x: chunks[1].x,
y: chunks[1].y + y_offset as u16,
width: chunks[1].width,
height: field_height as u16,
};
// Determine field styling based on selection and requirement status
let is_selected = field_idx == selected_field;
let is_required = field.required;
let has_value = !field.value.is_empty();
let border_style = if is_selected {
Style::default().fg(Color::Yellow)
} else if is_required && !has_value {
Style::default().fg(Color::Red)
} else if has_value {
Style::default().fg(Color::Green)
} else {
Style::default().fg(Color::DarkGray)
};
// Create title with requirement indicator
let field_title = if is_required {
format!("📋 {} (REQUIRED)", param_name)
} else {
format!("📝 {} (optional)", param_name)
};
// Add type information if available
let type_info = if let Some(ref param_type) = field.param_type {
format!(" [{}]", param_type)
} else {
String::new()
};
let full_title = format!("{}{}", field_title, type_info);
let field_block = Block::default()
.borders(Borders::ALL)
.title(full_title)
.border_style(border_style);
// Show field content with placeholder or value
let field_content = if field.value.is_empty() {
if let Some(ref desc) = field.description {
if is_selected {
format!("💡 {}\n\n{}", desc, "Type your input here...")
} else {
format!("💡 {}", desc)
}
} else if is_selected {
"Type your input here...".to_string()
} else {
"(empty)".to_string()
}
} else {
field.value.clone()
};
let content_style = if field.value.is_empty() {
if is_selected {
Style::default().fg(Color::Yellow)
} else {
Style::default().fg(Color::DarkGray)
}
} else {
Style::default().fg(Color::White)
};
let field_paragraph = Paragraph::new(field_content)
.style(content_style)
.block(field_block)
.wrap(ratatui::widgets::Wrap { trim: true });
f.render_widget(field_paragraph, field_area);
// Show cursor if this field is selected and in edit mode
if is_selected && self.ui_state.param_edit_mode {
let cursor_x = field_area.x + 1 + field.value.len() as u16;
let cursor_y = field_area.y + 1;
if cursor_x < field_area.x + field_area.width - 1 {
f.set_cursor_position((cursor_x, cursor_y));
}
}
y_offset += field_height;
}
// Show scroll indicator if needed
if self.ui_state.param_field_names.len() > max_visible_fields {
let scroll_info = format!(
"Showing fields {}-{} of {} | ↑/↓ to scroll",
scroll_start + 1,
std::cmp::min(
scroll_start + max_visible_fields,
self.ui_state.param_field_names.len()
),
self.ui_state.param_field_names.len()
);
let scroll_area = Rect {
x: chunks[1].x + 2,
y: chunks[1].y + chunks[1].height - 1,
width: chunks[1].width - 4,
height: 1,
};
let scroll_paragraph =
Paragraph::new(scroll_info).style(Style::default().fg(Color::Cyan));
f.render_widget(scroll_paragraph, scroll_area);
}
}
// Draw instructions at bottom
let instructions = if self.ui_state.param_field_names.is_empty() {
"🚀 [Enter] Execute | [Esc] Cancel & Go Back"
} else if self.ui_state.param_edit_mode {
"✏️ EDITING MODE | [Enter] Save & Move to Next | [Esc] Stop Editing | [Tab] Execute with Current Values"
} else {
"📝 [↑/↓] Navigate & Edit Fields | [Tab] Execute | [Esc] Cancel & Go Back"
};
let instructions_block = Block::default()
.borders(Borders::ALL)
.title("🎮 Controls")
.border_style(Style::default().fg(Color::Cyan));
let instructions_paragraph = Paragraph::new(instructions)
.style(
Style::default()
.fg(Color::Yellow)
.add_modifier(ratatui::style::Modifier::BOLD),
)
.alignment(ratatui::layout::Alignment::Center)
.block(instructions_block);
f.render_widget(instructions_paragraph, chunks[2]);
}
/// Draw response viewer dialog
fn draw_response_viewer_dialog(&mut self, f: &mut Frame, area: Rect) {
if let Some(ref response) = self.ui_state.selected_response {
let popup_area = centered_rect(90, 80, area);
// Mode selection display
let mode_display = match self.ui_state.response_viewer_mode {
ResponseViewMode::Formatted => "📖 Formatted",
ResponseViewMode::RawJson => "📄 Raw JSON",
ResponseViewMode::TreeView => "🌳 Tree View",
ResponseViewMode::Summary => "📋 Summary",
};
let mode_help =
" | Press 'V' to cycle view modes | ↑/↓ ←/→ PgUp/PgDn to scroll | ESC to close";
let title = format!("Response Viewer - {}{}", mode_display, mode_help);
// Generate content based on view mode
let content = self.format_response_content(response);
// Split content into lines and calculate dimensions for scrolling
let lines: Vec<&str> = content.lines().collect();
let total_lines = lines.len();
let visible_area = Rect {
x: popup_area.x + 1,
y: popup_area.y + 1,
width: popup_area.width.saturating_sub(2),
height: popup_area.height.saturating_sub(2),
};
let visible_lines = visible_area.height as usize;
// Calculate maximum line width for horizontal scrolling
let max_line_width = lines.iter().map(|line| line.len()).max().unwrap_or(0);
let visible_chars = visible_area.width as usize;
// Clamp scroll positions to valid ranges
let max_vertical_scroll = total_lines.saturating_sub(visible_lines);
let max_horizontal_scroll = max_line_width.saturating_sub(visible_chars);
if self.ui_state.response_viewer_vertical_pos > max_vertical_scroll {
self.ui_state.response_viewer_vertical_pos = max_vertical_scroll;
}
if self.ui_state.response_viewer_horizontal_pos > max_horizontal_scroll {
self.ui_state.response_viewer_horizontal_pos = max_horizontal_scroll;
}
// Update scroll states based on content dimensions and current positions
self.ui_state.response_viewer_scroll = self
.ui_state
.response_viewer_scroll
.content_length(max_vertical_scroll)
.position(self.ui_state.response_viewer_vertical_pos);
self.ui_state.response_viewer_horizontal_scroll = self
.ui_state
.response_viewer_horizontal_scroll
.content_length(max_horizontal_scroll)
.position(self.ui_state.response_viewer_horizontal_pos);
// Get current scroll positions
let vertical_scroll = self.ui_state.response_viewer_vertical_pos;
let horizontal_scroll = self.ui_state.response_viewer_horizontal_pos;
let block = Block::default()
.borders(Borders::ALL)
.title(title)
.border_style(Style::default().fg(Color::Cyan));
let text = Text::from(content);
let paragraph = Paragraph::new(text)
.block(block)
.wrap(Wrap { trim: false }) // Disable wrapping for proper horizontal scroll
.scroll((vertical_scroll as u16, horizontal_scroll as u16));
f.render_widget(Clear, popup_area);
f.render_widget(paragraph, popup_area);
// Render vertical scrollbar
if total_lines > visible_lines {
let scrollbar_area = Rect {
x: popup_area.x + popup_area.width - 1,
y: popup_area.y + 1,
width: 1,
height: popup_area.height.saturating_sub(2),
};
let vertical_scrollbar = Scrollbar::default()
.orientation(ScrollbarOrientation::VerticalRight)
.begin_symbol(Some("↑"))
.end_symbol(Some("↓"));
f.render_stateful_widget(
vertical_scrollbar,
scrollbar_area,
&mut self.ui_state.response_viewer_scroll,
);
}
// Render horizontal scrollbar
if max_line_width > visible_chars {
let h_scrollbar_area = Rect {
x: popup_area.x + 1,
y: popup_area.y + popup_area.height - 1,
width: popup_area.width.saturating_sub(2),
height: 1,
};
let horizontal_scrollbar = Scrollbar::default()
.orientation(ScrollbarOrientation::HorizontalBottom)
.begin_symbol(Some("←"))
.end_symbol(Some("→"));
f.render_stateful_widget(
horizontal_scrollbar,
h_scrollbar_area,
&mut self.ui_state.response_viewer_horizontal_scroll,
);
}
}
}
/// Format response content based on current view mode
fn format_response_content(&self, response: &Value) -> String {
match self.ui_state.response_viewer_mode {
ResponseViewMode::Formatted => self.format_response_formatted(response),
ResponseViewMode::RawJson => serde_json::to_string_pretty(response)
.unwrap_or_else(|_| "Invalid JSON".to_string()),
ResponseViewMode::TreeView => Self::format_response_tree(response, 0),
ResponseViewMode::Summary => self.format_response_summary(response),
}
}
/// Format response in a structured, readable way
fn format_response_formatted(&self, response: &Value) -> String {
match response {
Value::Object(obj) => {
let mut lines = Vec::new();
lines.push("📋 RESPONSE ANALYSIS:".to_string());
lines.push(format!(" Total fields: {}", obj.len()));
lines.push("".to_string());
// Handle common MCP response fields
if let Some(content) = obj.get("content") {
lines.push("📝 CONTENT:".to_string());
match content {
Value::Array(arr) => {
if arr.is_empty() {
lines.push(" ⚠️ Content array is EMPTY".to_string());
} else {
lines.push(format!(" {} items in content array:", arr.len()));
lines.push(self.format_content_array(content));
}
}
_ => {
lines.push(" Content is not an array:".to_string());
lines.push(format!(
" {}",
serde_json::to_string_pretty(content).unwrap_or_default()
));
}
}
lines.push("".to_string());
}
if let Some(is_error) = obj.get("isError").or_else(|| obj.get("is_error")) {
if is_error.as_bool() == Some(true) {
lines.push("⚠️ ERROR FLAG: true".to_string());
lines.push("".to_string());
}
}
if let Some(meta) = obj.get("_meta") {
lines.push("🔍 METADATA:".to_string());
lines.push(format!(
" {}",
serde_json::to_string_pretty(meta).unwrap_or_default()
));
lines.push("".to_string());
}
// Handle other fields
for (key, value) in obj {
if !matches!(key.as_str(), "content" | "isError" | "is_error" | "_meta") {
lines.push(format!("📊 {}:", key.to_uppercase()));
lines.push(format!(" {}", Self::format_value_indented(value, 1)));
lines.push("".to_string());
}
}
if lines.len() == 3 {
// Only header + empty lines
lines.push(
"⚠️ This response appears to be empty or contain no useful data."
.to_string(),
);
lines.push("".to_string());
lines.push("🔍 RAW OBJECT FIELDS:".to_string());
for (key, value) in obj {
lines.push(format!(
" {}: {}",
key,
serde_json::to_string(value).unwrap_or_default()
));
}
}
lines.join("\n")
}
_ => {
format!(
"📊 Non-object response:\n{}",
serde_json::to_string_pretty(response).unwrap_or_default()
)
}
}
}
/// Format content array in a readable way
fn format_content_array(&self, content: &Value) -> String {
match content {
Value::Array(arr) => {
let mut lines = Vec::new();
for (i, item) in arr.iter().enumerate() {
lines.push(format!(" [{}] {}", i + 1, self.format_content_item(item)));
}
lines.join("\n")
}
_ => format!(
" {}",
serde_json::to_string_pretty(content).unwrap_or_default()
),
}
}
/// Format a single content item
fn format_content_item(&self, item: &Value) -> String {
if let Value::Object(obj) = item {
if let Some(text) = obj.get("text") {
if let Some(text_str) = text.as_str() {
return format!("Text: {}", text_str);
}
}
if let Some(data) = obj.get("data") {
if let Some(mime_type) = obj.get("mimeType").or_else(|| obj.get("mime_type")) {
return format!(
"Binary data ({}): {} bytes",
mime_type.as_str().unwrap_or("unknown"),
data.as_str().map(|s| s.len()).unwrap_or(0)
);
}
}
if let Some(resource) = obj.get("resource") {
return format!(
"Resource: {}",
serde_json::to_string_pretty(resource).unwrap_or_default()
);
}
}
serde_json::to_string_pretty(item).unwrap_or_default()
}
/// Format value with indentation
fn format_value_indented(value: &Value, indent: usize) -> String {
let indent_str = " ".repeat(indent);
match value {
Value::String(s) => s.clone(),
Value::Number(n) => n.to_string(),
Value::Bool(b) => b.to_string(),
Value::Null => "null".to_string(),
Value::Array(arr) => {
let mut lines = vec!["[".to_string()];
for item in arr {
lines.push(format!(
"{}{},",
indent_str,
Self::format_value_indented(item, indent + 1)
));
}
lines.push("]".to_string());
lines.join("\n")
}
Value::Object(obj) => {
let mut lines = vec!["{".to_string()];
for (key, val) in obj {
lines.push(format!(
"{}\"{}\": {},",
indent_str,
key,
Self::format_value_indented(val, indent + 1)
));
}
lines.push("}".to_string());
lines.join("\n")
}
}
}
/// Format response as a tree structure
fn format_response_tree(value: &Value, depth: usize) -> String {
let indent = " ".repeat(depth);
let connector = if depth == 0 { "" } else { "├─ " };
match value {
Value::Object(obj) => {
let mut lines = Vec::new();
if depth == 0 {
lines.push("📦 Response Object".to_string());
}
for (i, (key, val)) in obj.iter().enumerate() {
let is_last = i == obj.len() - 1;
let branch = if is_last { "└─ " } else { "├─ " };
match val {
Value::Object(_) => {
lines.push(format!("{}{}{} 📁", indent, branch, key));
lines.push(Self::format_response_tree(val, depth + 1));
}
Value::Array(arr) => {
lines.push(format!("{}{}{} 📚 [{}]", indent, branch, key, arr.len()));
if !arr.is_empty() {
lines.push(Self::format_response_tree(val, depth + 1));
}
}
Value::String(s) => {
let preview = if s.len() > 50 {
format!("{}...", &s[..47])
} else {
s.clone()
};
lines.push(format!("{}{}{} 📝 \"{}\"", indent, branch, key, preview));
}
Value::Number(n) => {
lines.push(format!("{}{}{} 🔢 {}", indent, branch, key, n));
}
Value::Bool(b) => {
lines.push(format!("{}{}{} ✓ {}", indent, branch, key, b));
}
Value::Null => {
lines.push(format!("{}{}{} ∅ null", indent, branch, key));
}
}
}
lines.join("\n")
}
Value::Array(arr) => {
let mut lines = Vec::new();
for (i, item) in arr.iter().enumerate() {
let is_last = i == arr.len() - 1;
let branch = if is_last { "└─ " } else { "├─ " };
lines.push(format!("{}{}[{}]", indent, branch, i));
lines.push(Self::format_response_tree(item, depth + 1));
}
lines.join("\n")
}
_ => format!("{}{}{:?}", indent, connector, value),
}
}
/// Format response summary with key statistics
fn format_response_summary(&self, response: &Value) -> String {
let mut lines = Vec::new();
lines.push("📊 RESPONSE SUMMARY".to_string());
lines.push("─".repeat(50));
lines.push("".to_string());
match response {
Value::Object(obj) => {
lines.push(format!("🔍 Type: Object ({} fields)", obj.len()));
lines.push("".to_string());
// Analyze content
if let Some(content) = obj.get("content") {
match content {
Value::Array(arr) => {
lines.push(format!("📝 Content Items: {}", arr.len()));
for (i, item) in arr.iter().enumerate() {
if let Value::Object(content_obj) = item {
if let Some(text) = content_obj.get("text") {
if let Some(text_str) = text.as_str() {
lines.push(format!(
" [{}] Text: {} chars",
i + 1,
text_str.len()
));
}
} else if content_obj.get("data").is_some() {
lines.push(format!(" [{}] Binary data", i + 1));
}
}
}
lines.push("".to_string());
}
_ => {
lines.push("📝 Content: Single item".to_string());
lines.push("".to_string());
}
}
}
// Check for error status
if let Some(is_error) = obj.get("isError").or_else(|| obj.get("is_error")) {
if is_error.as_bool() == Some(true) {
lines.push("⚠️ Status: Error".to_string());
} else {
lines.push("✅ Status: Success".to_string());
}
lines.push("".to_string());
}
// Field breakdown
lines.push("🏗️ Fields:".to_string());
for (key, value) in obj {
let value_type = match value {
Value::String(_) => "String",
Value::Number(_) => "Number",
Value::Bool(_) => "Boolean",
Value::Array(arr) => &format!("Array[{}]", arr.len()),
Value::Object(obj) => &format!("Object[{}]", obj.len()),
Value::Null => "Null",
};
lines.push(format!(" • {}: {}", key, value_type));
}
}
Value::Array(arr) => {
lines.push(format!("🔍 Type: Array ({} items)", arr.len()));
}
_ => {
lines.push("🔍 Type: Primitive value".to_string());
}
}
lines.push("".to_string());
lines.push("─".repeat(50));
let json_size = serde_json::to_string(response)
.map(|s| s.len())
.unwrap_or(0);
lines.push(format!("📏 JSON Size: {} bytes", json_size));
lines.join("\n")
}
/// Open response viewer for the latest message with results
fn open_latest_response_viewer(&mut self) {
// Find the latest message with raw_response data
if let Some((index, message)) = self
.message_history
.iter()
.enumerate()
.rev()
.find(|(_idx, msg)| msg.raw_response.is_some())
{
if let Some(ref response) = message.raw_response {
self.ui_state.selected_response = Some(response.clone());
self.ui_state.response_viewer_open = true;
// Reset scroll positions to start from top
self.ui_state.response_viewer_vertical_pos = 0;
self.ui_state.response_viewer_horizontal_pos = 0;
// Auto-select this message in the history for context
self.ui_state.message_history_state.select(Some(index));
tracing::info!("Opened response viewer for latest message with results");
}
} else {
// No results found, just cycle focus as fallback
self.cycle_focus();
}
}
/// Strip the implementation prefix from tool names
/// Handles formats like: "Z2l0aHViX2FwaTpnaXRodWJfYXBpOjAuMS4w.github.repos/list-for-user"
/// Or: "prefix::actual.tool.name"
fn strip_tool_prefix(name: &str) -> &str {
// First try :: separator (old format)
if let Some(pos) = name.find("::") {
return &name[pos + 2..];
}
// Then try . separator with base64-looking prefix
if let Some(pos) = name.find('.') {
let prefix = &name[..pos];
// Check if prefix looks like base64 (alphanumeric + / + =)
if prefix.len() > 10
&& prefix
.chars()
.all(|c| c.is_alphanumeric() || c == '+' || c == '/' || c == '=')
{
return &name[pos + 1..];
}
}
// If no recognizable prefix pattern, return as-is
name
}
}
/// Helper function to create centered rect
fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
let popup_layout = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Percentage((100 - percent_y) / 2),
Constraint::Percentage(percent_y),
Constraint::Percentage((100 - percent_y) / 2),
])
.split(r);
Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage((100 - percent_x) / 2),
Constraint::Percentage(percent_x),
Constraint::Percentage((100 - percent_x) / 2),
])
.split(popup_layout[1])[1]
}
#[cfg(test)]
mod tests {
use super::*;
use mcp_probe_core::transport::TransportConfig;
#[test]
fn test_debugger_app_creation() -> Result<()> {
let transport_config = TransportConfig::stdio("test", &["arg1"]);
let client_info = Implementation {
name: "test-client".to_string(),
version: "0.1.0".to_string(),
metadata: std::collections::HashMap::new(),
};
let app = DebuggerApp::new(transport_config, client_info)?;
assert_eq!(app.state, AppState::Initializing);
Ok(())
}
#[test]
fn test_env_variables_parsing() {
let mut app = create_test_app();
// Simulate environment variable input
app.ui_state
.env_input_area
.insert_str("API_KEY=test123,DEBUG=true,PORT=8080");
app.parse_env_variables();
assert_eq!(
app.env_variables.get("API_KEY"),
Some(&"test123".to_string())
);
assert_eq!(app.env_variables.get("DEBUG"), Some(&"true".to_string()));
assert_eq!(app.env_variables.get("PORT"), Some(&"8080".to_string()));
}
fn create_test_app() -> DebuggerApp {
let transport_config = TransportConfig::stdio("test", &["arg1"]);
let client_info = Implementation {
name: "test-client".to_string(),
version: "0.1.0".to_string(),
metadata: std::collections::HashMap::new(),
};
DebuggerApp::new(transport_config, client_info).unwrap()
}
}