McpServices.xml 156 KB
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
<?xml version="1.0" encoding="UTF-8"?>
<!-- This software is in the public domain under CC0 1.0 Universal plus a 
     Grant of Patent License.

     To the extent possible under law, the author(s) have dedicated all
     copyright and related and neighboring rights to this software to the
     public domain worldwide. This software is distributed without any warranty.

     You should have received a copy of the CC0 Public Domain Dedication
     along with this software (see the LICENSE.md file). If not, see
     <https://creativecommons.org/publicdomain/zero/1.0/>. -->

<services xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="http://moqui.org/xsd/service-definition-3.xsd">

    <!-- MCP Services using Moqui's built-in JSON-RPC support -->
    
    
    <service verb="mcp" noun="Initialize" authenticate="true" allow-remote="true" transaction-timeout="30">
        <description>Handle MCP initialize request using Moqui authentication</description>
        <in-parameters>
            <parameter name="sessionId" required="false"/>
            <parameter name="protocolVersion" required="true"/>
            <parameter name="capabilities" type="Map"/>
            <parameter name="clientInfo" type="Map"/>
        </in-parameters>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                import org.moqui.impl.context.UserFacadeImpl.UserInfo
                
                ExecutionContext ec = context.ec
                
                // Permissions are handled by Moqui's artifact authorization system
                // Users must be in appropriate groups (McpUser, MCP_BUSINESS) with access to McpServices artifact group
                
                // Disable authz to prevent automatic Visit updates during MCP operations
                ec.artifactExecution.disableAuthz()
                
                // Get Visit (session) created by servlet and validate access
                def visit = ec.entity.find("moqui.server.Visit")
                    .condition("visitId", sessionId)
                    .one()
                
                if (!visit) {
                    throw new Exception("Invalid session: ${sessionId}")
                }
                
                if (visit.userId != ec.user.userId) {
                    throw new Exception("Access denied for session: ${sessionId}")
                }
                
                // Update Visit with MCP initialization data
                UserInfo adminUserInfo = null
                try {
                    adminUserInfo = ec.user.pushUser("ADMIN")
                    def metadata = [:]
                    try {
                        metadata = groovy.json.JsonSlurper().parseText(visit.initialRequest ?: "{}") as Map
                    } catch (Exception e) {
                        ec.logger.debug("Failed to parse Visit metadata: ${e.message}")
                    }
                    
                    metadata.mcpInitialized = true
                    metadata.mcpProtocolVersion = protocolVersion
                    metadata.mcpCapabilities = capabilities
                    metadata.mcpClientInfo = clientInfo
                    metadata.mcpInitializedAt = System.currentTimeMillis()
                    
                    // Session metadata stored in memory only - no Visit updates to prevent lock contention
                    ec.logger.info("SESSIONID: ${sessionId} - metadata stored in memory")
                } finally {
                    if (adminUserInfo != null) {
                        ec.user.popUser()
                    }
                }
                
                // Validate protocol version - support common MCP versions with version negotiation
                def supportedVersions = ["2025-11-25", "2025-06-18", "2024-11-05", "2024-10-07", "2023-06-05"]
                if (!supportedVersions.contains(protocolVersion)) {
                    throw new Exception("Unsupported protocol version: ${protocolVersion}. Supported versions: ${supportedVersions.join(', ')}")
                }

                // Get current user context (if authenticated)
                def userId = ec.user.userId
                def userAccountId = userId ? userId : null

                // Try to load root instructions from wiki
                def instructions = null
                try {
                    def wikiPage = ec.entity.find("moqui.resource.wiki.WikiPage")
                        .condition("wikiSpaceId", "MCP_SCREEN_DOCS")
                        .condition("pagePath", "root")
                        .useCache(true)
                        .one()

                    if (wikiPage) {
                        def wikiSpace = ec.entity.find("moqui.resource.wiki.WikiSpace")
                            .condition("wikiSpaceId", wikiPage.wikiSpaceId)
                            .one()

                        if (wikiSpace) {
                            def pageLocation = wikiSpace.rootPageLocation
                            if (!pageLocation.endsWith('/')) pageLocation += '/'
                            pageLocation += wikiPage.pagePath + '.md'

                            def pageRef = ec.resource.getLocationReference(pageLocation)
                            def wikiText = pageRef?.getText()
                            if (wikiText) {
                                instructions = wikiText
                                ec.logger.info("MCP Initialize: Loaded root instructions from wiki")
                            }
                        }
                    }
                } catch (Exception e) {
                    ec.logger.debug("Could not load root instructions from wiki: ${e.message}")
                }

                // Fallback to hardcoded instructions if wiki not available
                if (!instructions) {
                    instructions = "This server provides access to Moqui ERP through MCP. Use moqui_browse_screens(path='/PopCommerce') to begin. Key screens include: /PopCommerce/Catalog/Product/FindProduct for products, /PopCommerce/Order/FindOrder for orders, and /PopCommerce/Customer for customer management. All screens support parameterized queries for filtering results."
                }
                
                // Build server capabilities - don't fetch actual tools/resources during init
                // Tools and resources will be discovered via separate list requests per MCP spec
                def serverCapabilities = [
                    tools: [listChanged: true],
                    resources: [subscribe: true, listChanged: true],
                    logging: [:]
                ]
                
                // Build server info with useful metadata
                def moquiVersion = ec.factory.moquiVersion ?: "Unknown"
                def runtimePath = ec.factory.runtimePath ?: "Unknown"
                
                // Get hostname and IP
                def hostname = "Unknown"
                def ipAddress = "Unknown"
                try {
                    def localhost = java.net.InetAddress.getLocalHost()
                    hostname = localhost.getHostName()
                    ipAddress = localhost.getHostAddress()
                } catch (Exception e) { /* ignore */ }
                
                // Get Java/JVM info
                def javaVersion = System.getProperty("java.version") ?: "Unknown"
                def javaVendor = System.getProperty("java.vendor") ?: "Unknown"
                
                // Get server start time from Runtime MXBean
                def serverStartTime = null
                try {
                    def runtimeMXBean = java.lang.management.ManagementFactory.getRuntimeMXBean()
                    serverStartTime = runtimeMXBean.getStartTime()
                } catch (Exception e) { /* ignore */ }
                
                def serverInfo = [
                    name: "Moqui MCP Server",
                    version: "2.0.2",
                    moquiVersion: moquiVersion,
                    hostname: hostname,
                    ipAddress: ipAddress,
                    javaVersion: javaVersion,
                    javaVendor: javaVendor,
                    serverStartTime: serverStartTime,
                    runtimePath: runtimePath,
                    currentUser: ec.user?.username,
                    currentUserId: ec.user?.userId
                ]
                
                result = [
                    protocolVersion: "2025-06-18",
                    capabilities: serverCapabilities,
                    serverInfo: serverInfo,
                    sessionId: sessionId,
                    instructions: instructions
                ]
                
                ec.logger.info("MCP Initialize for user ${userId} (session ${sessionId}): capabilities negotiated")
            ]]></script>
        </actions>
    </service>

    <service verb="mcp" noun="ToolsCall" authenticate="true" allow-remote="true" transaction-timeout="300">
        <description>Handle MCP tools/call request with direct Moqui service execution</description>
        <in-parameters>
            <parameter name="sessionId" required="false"/>
            <parameter name="name" required="true"/>
            <parameter name="arguments" type="Map"/>
        </in-parameters>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                import groovy.json.JsonBuilder
                
                ExecutionContext ec = context.ec
                
                // Start timing for execution metrics
                def startTime = System.currentTimeMillis()
                def isError = false
                
                try {
                    // Consolidated Tool Dispatching

                    ec.logger.info("MCP ToolsCall: Dispatching tool name=${name}, arguments=${arguments}")
                    ec.logger.info("MCP ToolsCall: CODE VERSION: 2025-01-09 - FIXED NULL CHECK")

                    if (name == "moqui_render_screen" || name == "moqui_browse_screens") {
                        def targetServiceName = name == "moqui_browse_screens" ? "McpServices.mcp#BrowseScreens" : "McpServices.execute#ScreenAsMcpTool"
                        def serviceResult = ec.service.sync().name(targetServiceName).parameters(arguments ?: [:]).call()
                        
                        // Ensure standard MCP response format with content array
                        def actualRes = serviceResult?.result ?: serviceResult
                        if (actualRes instanceof Map && actualRes.content && actualRes.content instanceof List) {
                            result = actualRes
                        } else {
                            result = [ content: [[type: "text", text: new groovy.json.JsonBuilder(actualRes).toString()]], isError: false ]
                        }
                        return
                    }
                    
                    // Handle internal discovery/utility tools
                    def internalToolMappings = [
                        "moqui_search_screens": "McpServices.mcp#SearchScreens",
                        "moqui_get_screen_details": "McpServices.mcp#GetScreenDetails",
                        "moqui_get_help": "McpServices.mcp#GetHelp",
                        "moqui_batch_operations": "McpServices.mcp#BatchOperations"
                    ]
                    
                    def targetServiceName = internalToolMappings[name]
                    if (targetServiceName) {
                        def serviceResult = ec.service.sync().name(targetServiceName).parameters(arguments ?: [:]).call()
                        def actualRes = serviceResult?.result ?: serviceResult
                        // Ensure standard MCP response format with content array
                        if (actualRes instanceof Map && actualRes.content && actualRes.content instanceof List) {
                            result = actualRes
                        } else {
                            result = [ content: [[type: "text", text: new groovy.json.JsonBuilder(actualRes).toString()]], isError: false ]
                        }
                        return
                     }

                    // Fallback: check if it's a general Moqui service (non-screen-based tools)
                    if (ec.service.isServiceDefined(name)) {
                        // Execute service with current user context
                        def serviceResult = ec.service.sync().name(name).parameters(arguments ?: [:]).call()
                        // Convert result to MCP format for general services
                        result = [content: [[type: "text", text: new JsonBuilder(serviceResult).toString()]], isError: false]
                        return
                    }

                    throw new Exception("Unknown tool name: ${name}")
                } catch (Exception e) {
                    isError = true
                    
                    result = [
                        content: [
                            [
                                type: "text",
                                text: "Error executing tool ${name}: ${e.message}"
                            ]
                        ],
                        isError: true
                    ]
                    
                    ec.logger.error("MCP tool execution error", e)
                } finally {
                    // Send a simple notification about tool execution
                    try {
                        def servlet = ec.web.getServletContext().getAttribute("enhancedMcpServlet")
                        if (servlet && sessionId) {
                            def notification = [
                                method: "notifications/tool_execution",
                                params: [
                                    toolName: name,
                                    executionTime: (System.currentTimeMillis() - startTime) / 1000.0,
                                    success: !isError,
                                    timestamp: System.currentTimeMillis()
                                ]
                            ]
                            //servlet.queueNotification(sessionId, notification)
                        }
                    } catch (Exception e) {
                        ec.logger.warn("Failed to send tool execution notification: ${e.message}")
                    }
                }
            ]]></script>
        </actions>
    </service>

    <service verb="mcp" noun="ResourcesList" authenticate="false" allow-remote="true" transaction-timeout="60">
        <description>Handle MCP resources/list request with Moqui entity discovery based on user permissions</description>
        <in-parameters>
            <parameter name="sessionId"/>
            <parameter name="cursor"/>
        </in-parameters>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                
                ExecutionContext ec = context.ec
                def userGroups = ec.user.getUserGroupIdSet().collect { it }
                def availableResources = []
                
                ec.logger.debug("MCP ResourcesList: Discovering entities for user groups: ${userGroups}")
                
                // Use ArtifactAuthzCheckView to find all entities user has permission for
                // This is the "Moqui Way" - rely on the security system to tell us what is accessible
                def aacvList = ec.entity.find("moqui.security.ArtifactAuthzCheckView")
                    .condition("userGroupId", userGroups)
                    .condition("artifactTypeEnumId", "AT_ENTITY")
                    .condition("authzActionEnumId", "AUTHZA_VIEW")
                    .useCache(true)
                    .disableAuthz()
                    .list()
                
                for (def aacv in aacvList) {
                    def entityName = aacv.artifactName
                    // Basic sanity check to ensure entity is actually defined
                    if (ec.entity.isEntityDefined(entityName)) {
                        def description = "Moqui entity: ${entityName}"
                        if (entityName.contains("View")) {
                            description = "Moqui ViewEntity: ${entityName}"
                        }
                        
                        availableResources << [
                            uri: "entity://${entityName}",
                            name: entityName,
                            description: description,
                            mimeType: "application/json"
                        ]
                    }
                }
                
                // Add instructions resource for MCP_USER role
                if (userGroups.contains("McpUser")) {
                    availableResources << [
                        uri: "moqui://mcp/instructions",
                        name: "instructions",
                        description: "MCP server usage instructions",
                        mimeType: "text/plain"
                    ]
                }
                
                result = [resources: availableResources]
            ]]></script>
        </actions>
    </service>

    <service verb="mcp" noun="ResourcesRead" authenticate="true" allow-remote="true" transaction-timeout="120">
        <description>Handle MCP resources/read request with Moqui entity queries</description>
        <in-parameters>
            <parameter name="sessionId"/>
            <parameter name="uri" required="true"/>
        </in-parameters>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                import groovy.json.JsonBuilder
                
                ExecutionContext ec = context.ec
                def startTime = System.currentTimeMillis()
                
                // Handle special moqui://mcp/instructions resource
                if (uri == "moqui://mcp/instructions") {
                    // Try to load from wiki
                    def instructionsText = null
                    try {
                        def wikiPage = ec.entity.find("moqui.resource.wiki.WikiPage")
                            .condition("wikiSpaceId", "MCP_SCREEN_DOCS")
                            .condition("pagePath", "root")
                            .useCache(true)
                            .one()

                        if (wikiPage) {
                            def wikiSpace = ec.entity.find("moqui.resource.wiki.WikiSpace")
                                .condition("wikiSpaceId", wikiPage.wikiSpaceId)
                                .one()

                            if (wikiSpace) {
                                def pageLocation = wikiSpace.rootPageLocation
                                if (!pageLocation.endsWith('/')) pageLocation += '/'
                                pageLocation += wikiPage.pagePath + '.md'

                                def pageRef = ec.resource.getLocationReference(pageLocation)
                                instructionsText = pageRef?.getText()
                            }
                        }
                    } catch (Exception e) {
                        ec.logger.debug("Could not load instructions from wiki: ${e.message}")
                    }

                    // Fallback to hardcoded instructions
                    if (!instructionsText) {
                        instructionsText = "This server provides access to Moqui ERP through MCP. Use moqui_browse_screens(path='/PopCommerce') to begin. Key screens include: /PopCommerce/Catalog/Product/FindProduct for products, /PopCommerce/Order/FindOrder for orders, and /PopCommerce/Customer for customer management. All screens support parameterized queries for filtering results."
                    }

                    result = [
                        content: [[
                            uri: "moqui://mcp/instructions",
                            mimeType: "text/plain",
                            text: instructionsText
                        ]],
                        isError: false
                    ]
                    return
                }
                
                // Parse entity URI (format: entity://EntityName)
                if (!uri.startsWith("entity://")) {
                    throw new Exception("Invalid resource URI: ${uri}")
                }
                
                def entityName = uri.substring(9)
                
                if (!ec.entity.isEntityDefined(entityName)) {
                    throw new Exception("Entity not found: ${entityName}")
                }
                
                try {
                    def entityDef = null
                    try {
                        def entityInfoList = ec.entity.getAllEntityInfo(-1, true)
                        entityDef = entityInfoList.find { it.entityName == entityName }
                    } catch (Exception e) {
                        ec.logger.debug("Error getting detailed entity info: ${e.message}")
                    }
                    
                    if (!entityDef) {
                        entityDef = [
                            entityName: entityName,
                            packageName: entityName.contains('.') ? entityName.split('\\.')[0] : "",
                            description: "Entity: ${entityName}",
                            isViewEntity: entityName.contains('View'),
                            allFieldInfoList: []
                        ]
                    }
                    
                    // Query entity data
                    def entityList = ec.entity.find(entityName).limit(100).list()
                    
                    // Format response for MCP - create multiple content objects
                    def contentList = []
                    
                    // Add main content with entity data as text
                    contentList << [
                        type: "text",
                        text: new JsonBuilder([
                            entityName: entityName,
                            description: entityDef.description,
                            packageName: entityDef.packageName,
                            recordCount: entityList.size(),
                            data: entityList
                        ]).toString()
                    ]
                    
                    def responseMap = [
                        content: contentList,
                        isError: false
                    ]
                    
                    def jsonOutput = new JsonBuilder(responseMap).toString()
                    
                    // Size protection
                    def maxResponseSize = 1024 * 1024 // 1MB
                    if (jsonOutput.length() > maxResponseSize) {
                         def truncatedList = entityList.take(10)
                         responseMap.data = truncatedList
                         responseMap.truncated = true
                         responseMap.message = "Truncated to 10 records due to size."
                         jsonOutput = new JsonBuilder(responseMap).toString()
                    }
                    
                    result = [
                        content: [[
                            uri: uri,
                            mimeType: "application/json",
                            text: jsonOutput
                        ]],
                        isError: false
                    ]
                    
                } catch (Exception e) {
                    ec.logger.error("Error reading resource ${uri}", e)
                    result = [isError: true, content: [[type:"text", text: e.message]]]
                }
            ]]></script>
        </actions>
    </service>

    <service verb="mcp" noun="Ping" authenticate="true" allow-remote="true" transaction-timeout="10">
        <description>Handle MCP ping request for health check</description>
        <in-parameters>
            <parameter name="sessionId"/>
            <parameter name="cursor"/>
        </in-parameters>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
          <script><![CDATA[
                import org.moqui.impl.context.UserFacadeImpl.UserInfo
                
                // Get current user information
                def currentUser = ec.user.username
                def currentUserId = ec.user.userId
                
                // Try to get visit information if sessionId is provided
                def visitInfo = null
                if (sessionId) {
                    try {
                        ec.artifactExecution.disableAuthz()
                        def adminUserInfo = ec.user.pushUser("ADMIN")
                        try {
                            def visit = ec.entity.find("moqui.server.Visit")
                                .condition("visitId", sessionId)
                                .one()
                            
                            if (visit) {
                                visitInfo = [
                                    visitId: visit.visitId,
                                    userId: visit.userId,
                                    fromDate: visit.fromDate,
                                    lastUpdatedStamp: visit.lastUpdatedStamp
                                ]
                            }
                        } finally {
                            ec.user.popUser()
                        }
                        ec.artifactExecution.enableAuthz()
                    } catch (Exception e) {
                        // Log but don't fail the ping
                        ec.logger.warn("Error getting visit info for sessionId ${sessionId}: ${e.message}")
                    }
                }
                
                result = [
                    timestamp: ec.user.getNowTimestamp(),
                    status: "healthy",
                    version: "2.0.2",
                    sessionId: sessionId,
                    currentUser: currentUser,
                    currentUserId: currentUserId,
                    visitInfo: visitInfo,
                    architecture: "Visit-based sessions"
                ]
            ]]></script>
        </actions>
    </service>

    <!-- Debug Service -->
    
    <service verb="debug" noun="ComponentStatus" authenticate="false" allow-remote="true">
        <description>Debug service to verify component is loaded and working</description>
        <in-parameters/>
        <out-parameters>
            <parameter name="status" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                import org.moqui.impl.context.UserFacadeImpl.UserInfo
                
                ExecutionContext ec = context.ec
                
                def status = [
                    componentLoaded: true,
                    componentName: "mo-mcp",
                    timestamp: ec.user.getNowTimestamp(),
                    user: ec.user.username,
                    userId: ec.user.userId,
                    serviceNames: ec.service.getKnownServiceNames().findAll { it.contains("Mcp") },
                    entityNames: ec.entity.getAllEntityNames().findAll { it.contains("ArtifactHit") }
                ]
                
                ec.logger.info("=== MCP COMPONENT DEBUG ===")
                ec.logger.info("Component status: ${status}")
                ec.logger.info("All service names count: ${ec.service.getKnownServiceNames().size()}")
                ec.logger.info("All entity names count: ${ec.entity.getAllEntityNames().size()}")
                ec.logger.info("=== END MCP COMPONENT DEBUG ===")
                
                result.status = status
            ]]></script>
        </actions>
    </service>

    <service verb="execute" noun="ScreenAsMcpTool" authenticate="true" allow-remote="true" transaction-timeout="120">
        <description>Execute a screen as an MCP tool</description>
        <in-parameters>
            <parameter name="path" required="true"/>
            <parameter name="parameters" type="Map"><description>Parameters to pass to screen</description></parameter>
            <parameter name="action"><description>Action being processed: if not null, use real screen rendering instead of test mock</description></parameter>
            <parameter name="renderMode" default="compact"><description>Render mode: compact (default), aria (accessibility tree), text, html</description></parameter>
            <parameter name="sessionId"><description>Session ID for user context restoration</description></parameter>
        </in-parameters>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
import org.moqui.context.ExecutionContext
import groovy.json.JsonBuilder

ExecutionContext ec = context.ec

def startTime = System.currentTimeMillis()

// Set parameters in context
if (parameters) {
    ec.context.putAll(parameters)
}

// Map path parameter to screenPath for consistency
def screenPath = path

// Helper function to get simple path from component path
def getSimplePath = { fullPath ->
    if (!fullPath || fullPath == "root") return "root"
    String cleanPath = fullPath
    if (cleanPath.startsWith("component://")) cleanPath = cleanPath.substring(12)
    if (cleanPath.endsWith(".xml")) cleanPath = cleanPath.substring(0, cleanPath.length() - 4)
    List<String> parts = cleanPath.split('/').toList()
    if (parts.size() > 1 && parts[1] == "screen") parts.remove(1)
    return parts.join('/')
}

// Helper to extract short description/summary from wiki content
def extractSummary = { wikiText ->
    if (!wikiText) return null
    def textString = wikiText instanceof String ? wikiText : new String(wikiText, "UTF-8")
    def lines = textString.split('\n')
    for (def line : lines) {
        def trimmed = line.trim()
        // Skip empty lines and headers
        if (trimmed && !trimmed.startsWith('#')) {
            return trimmed.take(200)
        }
    }
    return null
}

// Helper function to load wiki instructions for a screen
// Walks up the path hierarchy to find the most specific wiki doc available
// e.g., for "Catalog/Product/EditProduct/Assocs", tries in order:
//   1. Catalog/Product/EditProduct/Assocs (most specific)
//   2. Catalog/Product/EditProduct
//   3. Catalog/Product
//   4. Catalog
def getWikiInstructions = { lookupPath ->
    if (!lookupPath) return null
    
    // Normalize path - remove leading/trailing slashes
    def normalizedPath = lookupPath.replaceAll('^/+', '').replaceAll('/+$', '')
    if (!normalizedPath) return null
    
    // Build list of paths from most specific to least specific
    def pathsToTry = []
    def segments = normalizedPath.split('/')
    for (int i = segments.length; i > 0; i--) {
        pathsToTry.add(segments[0..i-1].join('/'))
    }
    
    ec.logger.debug("Wiki lookup: trying paths ${pathsToTry} for ${lookupPath}")
    
    for (def tryPath in pathsToTry) {
        try {
            def wikiPage = ec.entity.find("moqui.resource.wiki.WikiPage")
                .condition("wikiSpaceId", "MCP_SCREEN_DOCS")
                .condition("pagePath", tryPath)
                .useCache(true)
                .one()

            if (!wikiPage) continue

            def wikiSpace = ec.entity.find("moqui.resource.wiki.WikiSpace")
                .condition("wikiSpaceId", wikiPage.wikiSpaceId)
                .one()

            if (!wikiSpace) continue

            // Build the resource location for the page
            def pageLocation = wikiSpace.rootPageLocation
            if (!pageLocation.endsWith('/')) {
                pageLocation += '/'
            }
            pageLocation += wikiPage.pagePath + '.md'

            // Get the resource reference and text content
            def pageRef = ec.resource.getLocationReference(pageLocation)
            def wikiText = pageRef?.getText()

            if (wikiText) {
                if (tryPath != normalizedPath) {
                    ec.logger.debug("Wiki lookup: found inherited docs at ${tryPath} for ${lookupPath}")
                }
                return wikiText
            }
        } catch (Exception e) {
            ec.logger.debug("Could not load wiki instructions for ${tryPath}: ${e.message}")
        }
    }
    return null
}

// Recursive serializer for Moqui/Java objects to JSON-friendly Map/List
// Applies reasonable safety limits to prevent massive payloads
def serializeMoquiObject
serializeMoquiObject = { obj, depth = 0 ->
    if (depth > 8) return "..." // Prevent deep recursion
    
    if (obj == null) return null
    if (obj instanceof Map) {
        def newMap = [:]
        obj.each { k, v ->
            def keyStr = k.toString()
            // Skip internal framework keys and metadata fields
            if (keyStr.startsWith("_") || keyStr == "ec" || keyStr == "sri") return
            // Skip audit fields to reduce payload
            if (keyStr in ["lastUpdatedStamp", "lastUpdatedTxStamp", "createdDate", "createdTxStamp", "createdByUserLogin"]) return
            def value = serializeMoquiObject(v, depth + 1)
            if (value != null) newMap[keyStr] = value
        }
        return newMap
    }
    if (obj instanceof Iterable) {
        def list = obj.collect()
        // Safety limit: truncate very large lists (10000+ items)
        def maxItems = 10000
        if (list.size() > maxItems) {
            ec.logger.info("serializeMoquiObject: Truncating large list from ${list.size()} to ${maxItems} items")
            def truncated = list.take(maxItems)
            def resultList = truncated.collect { serializeMoquiObject(it, depth + 1) }
            return [
                _items: resultList,
                _totalCount: list.size(),
                _truncated: true,
                _hasMore: true,
                _message: "Showing first ${maxItems} of ${list.size()} items. Use pagination for more."
            ]
        }
        return list.collect { serializeMoquiObject(it, depth + 1) }
    }
    if (obj instanceof org.moqui.entity.EntityValue) {
        return serializeMoquiObject(obj.getMap(), depth + 1)
    }
    if (obj instanceof java.sql.Timestamp || obj instanceof java.util.Date) {
        return obj.toString()
    }
    if (obj instanceof Number || obj instanceof Boolean) {
        return obj
    }
    if (obj instanceof String) {
        // Safety limit: truncate very large strings (1MB+)
        if (obj.length() > 1000000) {
            return [
                _value: obj.substring(0, 1000000) + "...",
                _fullLength: obj.length(),
                _truncated: true,
                _message: "Truncated to 1MB for safety."
            ]
        }
        return obj
    }
    if (obj.getClass().getName().startsWith("org.moqui.impl.screen.ScreenDefinition")) {
        return [location: obj.location]
    }
    // Skip EntityFind objects entirely - they're query definitions, not actual data
    if (obj instanceof org.moqui.entity.EntityFind) {
        return null
    }
    // Fallback for unknown types
    def str = obj.toString()
    if (str.length() > 10000) {
        return [
            _value: str.substring(0, 10000) + "...",
            _fullLength: str.length(),
            _truncated: true
        ]
    }
    return str
}

// Convert MCP semantic state to ARIA accessibility tree format
// This produces a compact, standard representation matching W3C ARIA roles
// Following ARIA naming guidelines: name (short label), description (brief explanation), details (extended help)
def convertToAriaTree = { semanticState, targetScreenPath ->
    if (!semanticState) return null
    
    def data = semanticState.data
    if (!data) return [role: "document", name: targetScreenPath, children: []]
    
    def children = []
    def formMetadata = data.formMetadata ?: [:]
    
    // Map Moqui field types to ARIA roles
    def fieldToAriaRole = { field ->
        switch (field.type) {
            case "dropdown": return "combobox"
            case "text": return "textbox"
            case "textarea": return "textbox"
            case "checkbox": return "checkbox"
            case "radio": return "radio"
            case "date": return "textbox"  // with date semantics
            case "date-time": return "textbox"
            case "number": return "spinbutton"
            case "password": return "textbox"
            case "hidden": return null  // skip hidden fields
            case "display": return "text"  // read-only display
            case "link": return "link"
            default: return "textbox"
        }
    }
    
    // Convert a field to ARIA node with full attributes
    def fieldToAriaNode = { field, formDataMap ->
        def role = fieldToAriaRole(field)
        if (!role) return null
        
        def node = [
            role: role,
            name: field.title ?: field.name,
            ref: field.name  // Reference for interaction
        ]
        
        // Add current value if available from form data
        if (formDataMap && formDataMap[field.name] != null) {
            node.value = formDataMap[field.name]?.toString()
        }
        
        // Add required attribute
        if (field.required) node.required = true
        
        // For dropdowns, just indicate type - use get_screen_details for options
        if (field.type == "dropdown") {
            node.description = "dropdown - use moqui_get_screen_details for options"
            // Check for dynamic options (autocomplete)
            if (field.dynamicOptions) {
                node.description = "autocomplete - type to search"
            }
        }
        
        return node
    }
    
    // Generate description for an action based on its name and service
    def actionDescription = { actionName, serviceName ->
        def verb = actionName.replaceAll(/([A-Z])/, ' $1').trim().toLowerCase()
        if (serviceName) {
            // Extract entity/operation from service name like "create#mantle.product.Product"
            def parts = serviceName.split('#')
            if (parts.length == 2) {
                def operation = parts[0]
                def entity = parts[1].split('\\.').last()
                return "${operation} ${entity}"
            }
            return serviceName.split('\\.').last()
        }
        return verb
    }
    
    // Process forms (form-single types become form landmarks)
    formMetadata.each { formName, formData ->
        if (formData.type == "form-list") return  // Handle separately
        
        // Look for form data (current values)
        def formDataKey = "${formName}_data"
        def formDataMap = data[formDataKey] ?: [:]
        
        def formNode = [
            role: "form",
            name: formData.name ?: formName,
            ref: formName,
            children: []
        ]
        
        // Add fields with values
        formData.fields?.each { field ->
            def fieldNode = fieldToAriaNode(field, formDataMap)
            if (fieldNode) formNode.children << fieldNode
        }
        
        // Find submit button by matching form name pattern
        // e.g., CreatePersonForm -> createPerson action
        def formBaseName = formName.replaceAll(/Form$/, "")
        def expectedActionName = formBaseName.substring(0,1).toLowerCase() + formBaseName.substring(1)
        def submitAction = semanticState.actions?.find { a -> 
            a.name == expectedActionName || a.name?.equalsIgnoreCase(expectedActionName)
        }
        if (submitAction) {
            def btnNode = [
                role: "button", 
                name: submitAction.name,
                ref: submitAction.name
            ]
            if (submitAction.service) {
                btnNode.description = actionDescription(submitAction.name, submitAction.service)
            }
            formNode.children << btnNode
        }
        
        if (formNode.children) children << formNode
    }
    
    // Process form-lists (become grids with optional search section)
    formMetadata.findAll { k, v -> v.type == "form-list" }.each { formName, formData ->
        def listData = data[formName]
        def itemCount = 0
        if (listData instanceof List) {
            itemCount = listData.size()
        } else if (listData?._totalCount) {
            itemCount = listData._totalCount
        }
        
        // Extract searchable fields from header-fields and create a search landmark
        def searchableFields = formData.fields?.findAll { it.searchable == true }
        if (searchableFields && searchableFields.size() > 0) {
            def searchNode = [
                role: "search",
                name: "Filter ${formData.name ?: formName}",
                description: "Pass these as parameters to filter results",
                children: searchableFields.collect { field ->
                    def searchField = [
                        role: (field.type == "dropdown" || field.dynamicOptions) ? "combobox" : "searchbox",
                        name: field.title ?: field.name,
                        ref: field.name
                    ]
                    if (field.type == "dropdown" || field.dynamicOptions) {
                        searchField.description = "dropdown - use moqui_get_screen_details for options"
                    }
                    searchField
                }
            ]
            children << searchNode
        }
        
        // Get pagination info from formData
        def pageIndex = formData.pageIndex ?: 0
        def pageSize = formData.pageSize ?: 20
        def pageMaxIndex = formData.pageMaxIndex ?: 0
        def listCount = formData.listCount ?: itemCount
        
        def gridNode = [
            role: "grid",
            name: formData.name ?: formName,
            ref: formName,
            rowcount: listCount
        ]
        
        // Add pagination cursor if there are more pages
        if (pageIndex < pageMaxIndex) {
            gridNode.nextCursor = [
                pageIndex: pageIndex + 1,
                pageSize: pageSize,
                hasMore: (pageIndex + 1) < pageMaxIndex
            ]
        }
        
        // Add column info (only non-searchable display columns)
        def displayColumns = formData.fields?.findAll { !it.searchable }?.collect { it.title ?: it.name }
        if (displayColumns) gridNode.columns = displayColumns
        
        // Add all rows with detail (no truncation - model needs complete data)
        if (listData instanceof List && listData.size() > 0) {
            gridNode.children = []
            listData.each { row ->
                def rowNode = [role: "row"]
                // Extract key identifying info - prefer specific IDs over generic productId
                // For features: productFeatureId, for assocs: toProductId, etc.
                def id = row.pseudoId ?: row.toProductId ?: row.productFeatureId ?: 
                         row.partyId ?: row.orderId ?: row.id
                // Avoid using productId as ref when it's the same for all rows (e.g., feature list)
                if (!id && row.productId) {
                    // Only use productId if there's no better identifier
                    id = row.productId
                }
                def name = row.combinedName ?: row.name ?: row.productName ?: 
                           row.description ?: row.abbrev
                if (id) rowNode.ref = id
                if (name) rowNode.name = name
                if (id && name && id != name) rowNode.description = id
                gridNode.children << rowNode
            }
        }
        
        children << gridNode
    }
    
    // Process navigation links - filter out noise
    def navLinks = semanticState.data?.links?.findAll { it.type == "navigation" }
    if (navLinks && navLinks.size() > 0) {
        // Determine current app from target path
        def currentApp = targetScreenPath?.split('/')?.find { it.startsWith('Popc') || it.startsWith('marble') || it.startsWith('hm') || it.startsWith('my') || it.startsWith('system') || it.startsWith('tools') }
        
        def filteredLinks = navLinks.findAll { link ->
            def path = link.path?.toString() ?: ""
            
            // Skip links with encoded timestamps (delete/update action URLs) - these are action URLs, not navigation
            if (path.contains("fromDate=") || path.contains("thruDate=")) {
                return false
            }
            
            // Skip cross-app navigation links (apps/marble, apps/hm, etc.) unless they're current app
            if (path.startsWith("apps/")) {
                def linkApp = path.split('/')[1]
                // Keep if same app or if it's a my/User link (global nav)
                return linkApp == currentApp || path.startsWith("apps/my/")
            }
            
            return true
        }
        
        if (filteredLinks.size() > 0) {
            def navNode = [
                role: "navigation",
                name: "Links",
                children: filteredLinks.collect { link ->
                    def linkNode = [role: "link", name: link.text, ref: link.path]
                    linkNode
                }
            ]
            children << navNode
        }
    }
    
    // Process ALL actions as buttons (unified - no separate transitions/actions, no truncation)
    def allActions = semanticState.actions ?: []
    if (allActions && allActions.size() > 0) {
        def toolbarNode = [
            role: "toolbar",
            name: "Actions",
            description: "Available operations on this screen",
            children: allActions.collect { action ->
                def btnNode = [
                    role: "button", 
                    name: action.name,
                    ref: action.name
                ]
                // Add description based on action type (no service names - they confuse models)
                if (action.service) {
                    btnNode.description = actionDescription(action.name, action.service)
                    // Add help reference for moqui_get_help tool
                    def serviceParts = action.service.split('\\.')
                    if (serviceParts.length > 0) {
                        btnNode.help = "wiki:service:${serviceParts[-1]}"
                    }
                } else if (action.type == "screen-transition") {
                    btnNode.description = "Navigate"
                } else if (action.type == "form-action") {
                    btnNode.description = "Form operation"
                }
                btnNode
            }
        ]
        children << toolbarNode
    }
    
    // Build the main node
    def mainNode = [
        role: "main",
        name: targetScreenPath?.split('/')?.last() ?: "Screen",
        description: "Use ref values with action parameter to interact",
        children: children
    ]
    
    // Note: Removed wiki:screen references - models can't usefully act on them
    // Wiki instructions are already included in the response when available
    
    return mainNode
}

// Convert MCP semantic state to compact actionable format
// Designed for LLM efficiency: enough info to act without fetching more
def convertToCompactFormat = { semanticState, targetScreenPath ->
    if (!semanticState) return null
    
    def data = semanticState.data
    def formMetadata = data?.formMetadata ?: [:]
    def actions = semanticState.actions ?: []
    def params = semanticState.parameters ?: [:]
    
    def result = [
        screen: targetScreenPath?.split('/')?.last() ?: "Screen"
    ]
    
    // Check for missing required parameters
    def missingRequired = params.findAll { name, info -> 
        info.required == true && info.value == null
    }
    if (missingRequired) {
        result.missingRequired = missingRequired.keySet().toList()
        result.error = "Required parameters missing: ${missingRequired.keySet().join(', ')}. Pass these parameters to view the screen."
    }
    
    // Build summary
    def formCount = formMetadata.count { k, v -> v.type != "form-list" }
    def listCount = formMetadata.count { k, v -> v.type == "form-list" }
    def actionNames = actions.findAll { it.type == "service-action" }.collect { it.name }.take(5)
    
    def summaryParts = []
    if (formCount > 0) summaryParts << "${formCount} form${formCount > 1 ? 's' : ''}"
    if (listCount > 0) {
        // Get total row count
        def totalRows = 0
        formMetadata.findAll { k, v -> v.type == "form-list" }.each { formName, formData ->
            def listData = data[formName]
            if (listData instanceof List) totalRows += listData.size()
        }
        summaryParts << "${totalRows} result${totalRows != 1 ? 's' : ''}"
    }
    if (actionNames) summaryParts << "actions: ${actionNames.join(', ')}"
    result.summary = summaryParts.join(". ")
    
    // Process forms (non-list)
    def forms = [:]
    formMetadata.findAll { k, v -> v.type != "form-list" }.each { formName, formData ->
        def formInfo = [:]
        def fields = []
        
        formData.fields?.each { field ->
            if (field.type == "hidden") return
            
            def fieldInfo
            def fieldName = field.name
            def displayName = field.title ?: field.name
            
            if (field.type == "dropdown") {
                // Just indicate it's a dropdown - use get_screen_details for actual options
                fieldInfo = [(fieldName): [type: "dropdown"]]
                if (field.dynamicOptions) {
                    fieldInfo[fieldName].autocomplete = true
                }
                if (displayName != fieldName) fieldInfo[fieldName].label = displayName
            } else {
                // Simple field - just use name, add label if different
                if (displayName != fieldName) {
                    fieldInfo = [(fieldName): displayName]
                } else {
                    fieldInfo = fieldName
                }
            }
            
            if (field.required) {
                if (fieldInfo instanceof String) {
                    fieldInfo = [(fieldName): [required: true]]
                } else if (fieldInfo instanceof Map && fieldInfo[fieldName] instanceof String) {
                    fieldInfo[fieldName] = [label: fieldInfo[fieldName], required: true]
                } else if (fieldInfo instanceof Map && fieldInfo[fieldName] instanceof Map) {
                    fieldInfo[fieldName].required = true
                }
            }
            
            fields << fieldInfo
        }
        
        formInfo.fields = fields
        
        // Find matching action for this form
        def formBaseName = formName.replaceAll(/Form$/, "")
        def expectedActionName = formBaseName.substring(0,1).toLowerCase() + formBaseName.substring(1)
        def submitAction = actions.find { a -> 
            a.name == expectedActionName || a.name?.equalsIgnoreCase(expectedActionName)
        }
        if (submitAction) {
            formInfo.submit = submitAction.name
            // Note: Removed service name - it confuses models into trying to call services directly
        }
        
        forms[formName] = formInfo
    }
    if (forms) result.forms = forms
    
    // Process grids (form-lists) - include searchable parameters
    def grids = [:]
    def searchParams = []  // Collect all searchable params across grids
    formMetadata.findAll { k, v -> v.type == "form-list" }.each { formName, formData ->
        def listData = data[formName]
        def gridInfo = [:]
        
        // Extract searchable fields and add to searchParams
        def searchableFields = formData.fields?.findAll { it.searchable == true }
        searchableFields?.each { field ->
            def paramInfo = [name: field.name]
            if (field.title && field.title != field.name) paramInfo.label = field.title
            if (field.type) paramInfo.type = field.type
            if (field.dynamicOptions) paramInfo.autocomplete = true
            searchParams << paramInfo
        }
        
        // Column names (display columns only, not search fields)
        def columns = formData.fields?.findAll { it.type != "hidden" && !it.searchable }?.collect { it.title ?: it.name }
        if (columns) gridInfo.columns = columns
        
        // Rows with key data and links
        if (listData instanceof List && listData.size() > 0) {
            gridInfo.rowCount = listData.size()
            
            // Get field names from form definition for determining key fields
            def fieldNames = formData.fields?.collect { it.name } ?: []
            
            gridInfo.rows = listData.take(10).collect { row ->
                def rowInfo = [:]
                
                // Get identifying info - prefer specific IDs over generic productId
                // For features: productFeatureId, for assocs: toProductId, etc.
                def id = row.pseudoId ?: row.toProductId ?: row.productFeatureId ?: 
                         row.partyId ?: row.orderId ?: row.communicationEventId ?: row.id
                // Avoid using productId as id when it's the same for all rows (e.g., feature list)
                if (!id && row.productId) id = row.productId
                def name = row.combinedName ?: row.productName ?: row.organizationName ?: 
                           row.subject ?: row.name ?: row.description ?: row.abbrev
                
                if (id) rowInfo.id = id
                if (name && name != id) rowInfo.name = name
                
                // Add key display values (2-3 additional fields beyond id/name)
                // Priority: status, type, date, amount, role, class fields
                def keyFieldPriority = [
                    'statusId', 'status', 'productTypeEnumId', 'productAssocTypeEnumId', 
                    'communicationEventTypeId', 'roleTypeId', 'partyClassificationId',
                    'orderPartStatusId', 'placedDate', 'entryDate', 'fromDate', 'thruDate',
                    'grandTotal', 'quantity', 'price', 'amount',
                    'username', 'emailAddress', 'fromPartyId', 'toPartyId'
                ]
                
                def extraFields = [:]
                def extraCount = 0
                for (fieldName in keyFieldPriority) {
                    if (extraCount >= 3) break
                    def value = row[fieldName]
                    if (value != null && value != '' && value != id && value != name) {
                        // Simplify enumId suffixes for display
                        def displayKey = fieldName.replaceAll(/EnumId$/, '').replaceAll(/Id$/, '')
                        extraFields[displayKey] = value.toString()
                        extraCount++
                    }
                }
                
                // If no priority fields found, add first 2-3 non-empty visible fields
                if (extraCount == 0) {
                    for (fieldDef in formData.fields?.take(8)) {
                        if (extraCount >= 3) break
                        def fieldName = fieldDef.name
                        if (fieldDef.type == 'hidden') continue
                        if (fieldName in ['id', 'pseudoId', 'name', 'productId', 'partyId', 'submitButton']) continue
                        def value = row[fieldName]
                        if (value != null && value != '' && value != id && value != name) {
                            extraFields[fieldName] = value.toString()
                            extraCount++
                        }
                    }
                }
                
                if (extraFields) rowInfo.data = extraFields
                
                // Find link for this row
                def rowLinks = data.links?.findAll { link ->
                    link.path?.contains(id?.toString()) && link.type == "navigation"
                }
                if (rowLinks && rowLinks.size() > 0) {
                    // Pick the most relevant link (edit/view)
                    def editLink = rowLinks.find { it.path?.contains("Edit") }
                    rowInfo.link = (editLink ?: rowLinks[0]).path
                }
                
                rowInfo
            }
            // Add pagination cursor if there are more pages
            def gridPageIndex = formData.pageIndex ?: 0
            def gridPageSize = formData.pageSize ?: 20
            def gridPageMaxIndex = formData.pageMaxIndex ?: 0
            def gridListCount = formData.listCount ?: listData.size()
            
            if (gridPageIndex < gridPageMaxIndex) {
                // There are more pages - provide nextCursor
                gridInfo.nextCursor = [
                    pageIndex: gridPageIndex + 1,
                    pageSize: gridPageSize,
                    hasMore: (gridPageIndex + 1) < gridPageMaxIndex
                ]
            }
            gridInfo.totalCount = gridListCount
        } else {
            gridInfo.rowCount = 0
        }
        
        grids[formName] = gridInfo
    }
    if (grids) result.grids = grids
    
    // Actions - just action names with help references (no service names)
    def actionMap = [:]
    actions.findAll { it.type == "service-action" && it.service }.each { action ->
        def actionInfo = [:]
        
        // Add help reference for moqui_get_help tool
        def serviceParts = action.service.split('\\.')
        if (serviceParts.length > 0) {
            actionInfo.help = "wiki:service:${serviceParts[-1]}"
        }
        
        // Find form that uses this action to get parameter hints
        def matchingForm = forms.find { k, v -> v.submit == action.name }
        if (matchingForm) {
            def requiredFields = matchingForm.value.fields?.findAll { f ->
                (f instanceof Map && f.values().any { v -> 
                    (v instanceof Map && v.required) || v == "required"
                })
            }?.collect { f ->
                f instanceof Map ? f.keySet()[0] : f
            }
            if (requiredFields) actionInfo.required = requiredFields
        }
        
        if (actionInfo) actionMap[action.name] = actionInfo
    }
    if (actionMap) result.actions = actionMap
    
    // Add searchParams if any were collected from form-lists
    if (searchParams) result.searchParams = searchParams
    
    // Transitions - screen navigation actions (toolbar buttons, row actions)
    // Filter out autocomplete/helper transitions that aren't user actions
    def transitionList = actions.findAll { 
        it.type == "screen-transition" && 
        it.name && 
        !it.name.startsWith("form") &&  // Skip formSelectColumns, formSaveFind
        !it.name.startsWith("get") &&   // Skip getProductList, getFeatureList etc (autocomplete helpers)
        it.name != "actions" &&          // Skip generic 'actions'
        it.name != "screenDoc"           // Skip documentation link
    }.collect { it.name }
    if (transitionList) result.transitions = transitionList
    
    // Navigation - only external/important links
    def navLinks = data?.links?.findAll { link ->
        link.type == "navigation" && link.path && !link.path.contains("?")
    }?.take(5)?.collect { [name: it.text, path: it.path] }
    if (navLinks) result.nav = navLinks
    
    return result
}

// Resolve input screen path to simple path for lookup
def inputScreenPath = screenPath
if (screenPath.startsWith("component://")) {
    inputScreenPath = getSimplePath(screenPath)
}
ec.logger.info("MCP Screen Execution: Looking up wiki docs for ${inputScreenPath}")

// Try to get wiki instructions
def wikiInstructions = getWikiInstructions(inputScreenPath)
        
        // Try to render screen content for LLM consumption
        def output = null
        def screenUrl = "http://localhost:8080/${screenPath}"
        def isError = false
        def resolvedScreenDef = null
         
        try {
            ec.logger.info("MCP Screen Execution: Attempting to render screen ${screenPath}")
            
            def rootScreen = "component://webroot/screen/webroot.xml"
            def testScreenPath = screenPath
            
            if (screenPath.startsWith("component://")) {
                // Component path handling
                resolvedScreenDef = ec.screen.getScreenDefinition(screenPath)
                rootScreen = screenPath
                testScreenPath = ""
            } else {
                // Forward slash path handling (e.g. /PopCommerce/Catalog)
                def testPath = screenPath.startsWith('/') ? screenPath : "/" + screenPath
                def pathSegments = []
                testPath.split('/').each { if (it && it.trim()) pathSegments.add(it) }
                
                // 1. Try literal resolution from webroot
                rootScreen = "component://webroot/screen/webroot.xml"
                def webrootSd = ec.screen.getScreenDefinition(rootScreen)
                def screenPathList = org.moqui.impl.screen.ScreenUrlInfo.parseSubScreenPath(
                    webrootSd, webrootSd, pathSegments, testPath, [:], ec.screenFacade
                )
                
                def currentSd = webrootSd
                def reachedIndex = -1
                if (screenPathList) {
                    for (int i = 0; i < screenPathList.size(); i++) {
                        def screenName = screenPathList[i]
                        def ssi = currentSd?.getSubscreensItem(screenName)
                        if (ssi && ssi.getLocation()) {
                            currentSd = ec.screen.getScreenDefinition(ssi.getLocation())
                            reachedIndex = i
                        } else {
                            break
                        }
                    }
                }
                
                // Set resolvedScreenDef if we successfully traversed the path
                if (reachedIndex >= 0 && currentSd && reachedIndex == (screenPathList.size() - 1)) {
                    resolvedScreenDef = currentSd
                    ec.logger.info("MCP Path Resolution: Resolved to screen '${resolvedScreenDef?.getScreenName()}' via literal path")
                }
                
                // 2. If literal resolution failed, try Component-based resolution
                if (reachedIndex == -1 && pathSegments.size() >= 2) {
                    def componentName = pathSegments[0]
                    def rootScreenName = pathSegments[1]
                    def compRootLoc = "component://${componentName}/screen/${rootScreenName}.xml"
                    
                    if (ec.resource.getLocationReference(compRootLoc).exists) {
                        ec.logger.info("MCP Path Resolution: Found component root at ${compRootLoc}")
                        rootScreen = compRootLoc
                        testScreenPath = pathSegments.size() > 2 ? pathSegments[2..-1].join('/') : ""
                        resolvedScreenDef = ec.screen.getScreenDefinition(rootScreen)
                        
                        // Resolve further if there are remaining segments
                        if (testScreenPath) {
                            def remainingSegments = pathSegments[2..-1]
                            def compPathList = org.moqui.impl.screen.ScreenUrlInfo.parseSubScreenPath(
                                resolvedScreenDef, resolvedScreenDef, remainingSegments, testScreenPath, [:], ec.screenFacade
                            )
                            if (compPathList) {
                                for (String screenName in compPathList) {
                                    def ssi = resolvedScreenDef?.getSubscreensItem(screenName)
                                    if (ssi && ssi.getLocation()) {
                                        resolvedScreenDef = ec.screen.getScreenDefinition(ssi.getLocation())
                                    } else {
                                        break
                                    }
                                }
                            }
                        }
                    }
                }
                
                // 3. Fallback to double-slash search if still not found
                if (reachedIndex == -1 && !resolvedScreenDef && pathSegments.size() > 0 && !testPath.startsWith("//")) {
                    def searchPath = "//" + pathSegments.join('/')
                    ec.logger.info("MCP Path Resolution: Fallback to search path ${searchPath}")
                    
                    rootScreen = "component://webroot/screen/webroot.xml"
                    def searchPathList = org.moqui.impl.screen.ScreenUrlInfo.parseSubScreenPath(
                        webrootSd, webrootSd, pathSegments, searchPath, [:], ec.screenFacade
                    )
                    
                    if (searchPathList) {
                        testScreenPath = searchPath
                        resolvedScreenDef = webrootSd
                        for (String screenName in searchPathList) {
                            def ssi = resolvedScreenDef?.getSubscreensItem(screenName)
                            if (ssi && ssi.getLocation()) {
                                resolvedScreenDef = ec.screen.getScreenDefinition(ssi.getLocation())
                            } else {
                                break
                            }
                        }
                    }
                }
                
                // If we found a specific target, we're good. 
                // If not, default to webroot with full path (original behavior, but now we know it failed)
                if (!resolvedScreenDef) {
                    rootScreen = "component://webroot/screen/webroot.xml"
                    resolvedScreenDef = webrootSd
                    testScreenPath = testPath
                }
            }

            // Regular screen rendering with current user context - use our custom ScreenTestImpl
            // For compact/ARIA modes, we still render internally with MCP to get semantic data, then convert
            // Note: "mcp" is not exposed to users - if requested, treat as "compact"
            def userRenderMode = (renderMode == "mcp") ? "compact" : renderMode
            def actualScreenRenderMode = (userRenderMode == "aria" || userRenderMode == "compact" || userRenderMode == null) ? "mcp" : userRenderMode
            def screenTest = new org.moqui.mcp.CustomScreenTestImpl(ec.ecfi)
                .rootScreen(rootScreen)
                .renderMode(actualScreenRenderMode)
                .auth(ec.user.username)

            def renderParams = parameters ?: [:]
            // Note: Don't inject userId/username into renderParams as they may conflict with
            // screen search fields (e.g., FindCustomer has a 'username' search field).
            // User context is already available via ec.user for authorization purposes.

            // Build the screen path - append action/transition if specified
            // This lets the framework handle transition execution properly (inheritance, pre/post actions, etc.)
            def relativePath = testScreenPath
            def actionResult = [:]
            
            if (action && resolvedScreenDef) {
                // Find the transition - must traverse default subscreens like discovery does
                // because transitions may be defined on default subscreens, not the parent screen
                def transition = null
                def transitionScreenDef = null
                def subscreenPath = ""  // Track the path through default subscreens
                
                def currentScreenDef = resolvedScreenDef
                def depth = 0
                while (currentScreenDef && depth < 5 && !transition) {
                    // Check this screen for the transition
                    transition = currentScreenDef.getAllTransitions().find { it.getName() == action }
                    if (transition) {
                        transitionScreenDef = currentScreenDef
                        ec.logger.info("MCP: Found transition '${action}' on screen '${currentScreenDef.getScreenName()}' at depth ${depth}")
                        break
                    }
                    
                    // Check for default subscreen to continue traversal
                    def defaultSubscreenName = currentScreenDef.getDefaultSubscreensItem()
                    if (defaultSubscreenName) {
                        def subscreenItem = currentScreenDef.getSubscreensItem(defaultSubscreenName)
                        if (subscreenItem?.location) {
                            try {
                                def subscreenDef = currentScreenDef.sfi.getScreenDefinition(subscreenItem.location)
                                if (subscreenDef) {
                                    subscreenPath += "/" + defaultSubscreenName
                                    currentScreenDef = subscreenDef
                                    depth++
                                } else {
                                    currentScreenDef = null
                                }
                            } catch (Exception e) {
                                ec.logger.warn("MCP: Could not load subscreen for transition lookup: ${e.message}")
                                currentScreenDef = null
                            }
                        } else {
                            currentScreenDef = null
                        }
                    } else {
                        currentScreenDef = null
                    }
                }
                
                if (transition) {
                    // Append subscreen path and transition to the render path
                    // The framework needs the full path including default subscreens to find the transition
                    relativePath = testScreenPath + subscreenPath + "/" + action
                    def serviceName = transition.getSingleServiceName()
                    actionResult = [
                        action: action,
                        service: serviceName,
                        status: "pending"  // Will be updated after render based on errors
                    ]
                    ec.logger.info("MCP Screen Execution: Will execute transition '${action}' via framework path '${relativePath}' (service: ${serviceName ?: 'none'})")
                } else {
                    ec.logger.warn("MCP Screen Execution: Action '${action}' not found in screen transitions (checked ${depth + 1} screens in hierarchy)")
                    actionResult = [
                        action: action,
                        status: "error",
                        message: "Transition '${action}' not found on screen"
                    ]
                }
            }
            
            // Clear entity cache before rendering to ensure fresh data
            ec.cache.clearAllCaches()
            ec.logger.info("MCP Screen Execution: Entity cache cleared before rendering")
            
            ec.logger.info("TESTRENDER root=${rootScreen} path=${relativePath} params=${renderParams}")
            
            def testRender = screenTest.render(relativePath, renderParams, "POST")
            output = testRender.getOutput()
            
            // --- Capture Action Result from Framework Execution ---
            def postContext = testRender.getPostRenderContext()
            
            if (action && actionResult.status == "pending") {
                // Check for errors from transition execution
                def errorMessages = testRender.getErrorMessages()
                def hasError = errorMessages && errorMessages.size() > 0
                
                // Also check JSON response for validation errors (more structured)
                def jsonResponse = testRender.getJsonObject()
                def validationErrors = []
                def jsonErrors = []
                if (jsonResponse instanceof Map) {
                    // Extract structured validation errors from JSON response
                    if (jsonResponse.validationErrors) {
                        validationErrors = jsonResponse.validationErrors.collect { ve ->
                            // ValidationError.getMap() returns: form, field, serviceName, message
                            [
                                field: ve.field ?: ve.fieldPretty,
                                form: ve.form,
                                service: ve.serviceName,
                                message: ve.message ?: ve.messageWithFieldPretty ?: ve.toString()
                            ]
                        }
                        hasError = true
                    }
                    // Also capture general errors from JSON
                    if (jsonResponse.errors) {
                        jsonErrors = jsonResponse.errors
                        hasError = true
                    }
                }
                
                if (hasError) {
                    actionResult.status = "error"
                    
                    // Build comprehensive error message
                    def allMessages = []
                    if (errorMessages) allMessages.addAll(errorMessages)
                    if (jsonErrors) allMessages.addAll(jsonErrors)
                    actionResult.message = allMessages.join("; ") ?: "Validation failed"
                    
                    // Add structured validation errors for field-level feedback
                    if (validationErrors) {
                        actionResult.validationErrors = validationErrors
                        // Also add field-specific summary
                        def fieldSummary = validationErrors.collect { ve ->
                            ve.field ? "${ve.field}: ${ve.message}" : ve.message
                        }.join("; ")
                        if (!actionResult.message || actionResult.message == "Validation failed") {
                            actionResult.message = fieldSummary
                        }
                    }
                    
                    ec.logger.error("MCP Screen Execution: Transition '${action}' completed with errors: ${actionResult.message}")
                } else {
                    actionResult.status = "executed"
                    actionResult.message = "Transition '${action}' executed successfully"
                    
                    // Try to extract result from context (services often put results in context)
                    // Common patterns: result, serviceResult, *Id (for create operations)
                    def result = [:]
                    if (postContext) {
                        // Look for common result patterns
                        ['result', 'serviceResult', 'createResult'].each { key ->
                            if (postContext.containsKey(key)) {
                                result[key] = postContext.get(key)
                            }
                        }
                        // Look for created IDs (common pattern: partyId, productId, orderId, etc.)
                        postContext.each { key, value ->
                            if (key.toString().endsWith('Id') && value && !key.toString().startsWith('_')) {
                                // Only include if it looks like a created/returned ID
                                def keyStr = key.toString()
                                if (!['userId', 'username', 'sessionId', 'requestId'].contains(keyStr)) {
                                    result[keyStr] = value
                                }
                            }
                        }
                    }
                    
                    // Also check JSON response for result data
                    if (jsonResponse instanceof Map) {
                        // Copy any IDs from JSON response
                        jsonResponse.each { key, value ->
                            if (key.toString().endsWith('Id') && value && !key.toString().startsWith('_')) {
                                def keyStr = key.toString()
                                if (!['userId', 'username', 'sessionId', 'requestId'].contains(keyStr)) {
                                    result[keyStr] = value
                                }
                            }
                        }
                        // Copy messages if present
                        if (jsonResponse.messages) {
                            actionResult.messages = jsonResponse.messages
                        }
                    }
                    
                    if (result) {
                        actionResult.result = result
                    }
                    ec.logger.info("MCP Screen Execution: Transition '${action}' executed successfully, result: ${result}")
                }
            }

            // --- Semantic State Extraction ---
            def semanticState = [:]

            // Get final screen definition - prefer the actual rendered screen from ScreenRender
            // This ensures we get the deepest screen in the path, not just the root
            def finalScreenDef = resolvedScreenDef
            try {
                def screenRender = testRender.getScreenRender()
                if (screenRender?.screenUrlInfo?.screenPathDefList) {
                    def pathDefList = screenRender.screenUrlInfo.screenPathDefList
                    if (pathDefList.size() > 0) {
                        // Get the last (deepest) screen in the path
                        finalScreenDef = pathDefList.get(pathDefList.size() - 1)
                        ec.logger.info("MCP: Using actual rendered screen '${finalScreenDef?.getScreenName()}' from screenPathDefList (${pathDefList.size()} screens in path)")
                    }
                }
            } catch (Exception e) {
                ec.logger.warn("MCP: Could not get screen from ScreenRender, using resolved: ${e.message}")
            }

            if (finalScreenDef && postContext) {
                semanticState.screenPath = inputScreenPath
                semanticState.data = [:]
                
                // Use the explicit semantic data captured by macros if available
                def explicitData = postContext.get("mcpSemanticData")
                if (explicitData instanceof Map) {
                    explicitData.each { k, v ->
                        semanticState.data[k] = serializeMoquiObject(v, 0)
                    }
                }
                
                // Extract transitions (Actions) with type classification and metadata
                // Collect from current screen AND active subscreens (iterative traversal)
                semanticState.actions = []
                def collectedTransitionNames = [] as Set
                
                // Build list of screens to process (current + default subscreens chain)
                def screensToProcess = []
                def currentScreenDef = finalScreenDef
                def depth = 0
                while (currentScreenDef && depth < 5) {
                    screensToProcess << currentScreenDef
                    
                    // Check for default subscreen
                    def defaultSubscreenName = currentScreenDef.getDefaultSubscreensItem()
                    if (defaultSubscreenName) {
                        def subscreenItem = currentScreenDef.getSubscreensItem(defaultSubscreenName)
                        if (subscreenItem?.location) {
                            try {
                                def subscreenDef = currentScreenDef.sfi.getScreenDefinition(subscreenItem.location)
                                if (subscreenDef) {
                                    ec.logger.info("MCP: Adding default subscreen '${defaultSubscreenName}' at ${subscreenItem.location} to traversal")
                                    currentScreenDef = subscreenDef
                                    depth++
                                } else {
                                    currentScreenDef = null
                                }
                            } catch (Exception e) {
                                ec.logger.warn("MCP: Could not load subscreen ${subscreenItem.location}: ${e.message}")
                                currentScreenDef = null
                            }
                        } else {
                            currentScreenDef = null
                        }
                    } else {
                        currentScreenDef = null
                    }
                }
                
                // Now collect transitions from all screens
                screensToProcess.each { screenDef ->
                    screenDef.getAllTransitions().each { trans ->
                        def transName = trans.getName()
                        if (collectedTransitionNames.contains(transName)) return // skip duplicates
                        collectedTransitionNames.add(transName)
                        
                        def service = trans.getSingleServiceName()
                        
                        // Classify action type
                        def actionType = "screen-transition"
                        def transNameLower = transName?.toString()?.toLowerCase() ?: ''
                        
                        if (service) {
                            actionType = "service-action"
                        } else if (transNameLower.contains('delete')) {
                            actionType = "delete-action"
                        } else if (transNameLower.startsWith('form') || transNameLower == 'find' || transNameLower == 'search') {
                            actionType = "form-action"
                        }
                        
                        def actionInfo = [
                            name: transName,
                            service: service,
                            type: actionType
                        ]
                        
                        semanticState.actions << actionInfo
                    }
                }
                
                // 3. Extract parameters with metadata
                semanticState.parameters = [:]
                if (finalScreenDef.parameterByName) {
                    finalScreenDef.parameterByName.each { name, param ->
                        def value = postContext.get(name) ?: parameters?.get(name)
                        
                        // Build parameter metadata
                        def paramInfo = [:]
                        
                        // Add value if exists
                        if (value != null) {
                            paramInfo.value = serializeMoquiObject(value, 0)
                        }
                        
                        // Extract parameter type - try multiple approaches
                        def type = "string"
                        try {
                            // Try to get type via reflection or known properties
                            if (param.hasProperty('type')) {
                                def typeObj = param.type
                                if (typeObj != null) type = typeObj.toString().toLowerCase()
                            } else if (param.hasProperty('parameterType')) {
                                def typeObj = param.parameterType
                                if (typeObj != null) type = typeObj.toString().toLowerCase()
                            }
                        } catch (Exception e) {
                            // Fall back to type inference from value
                        }
                        
                        // Infer type from value if type couldn't be extracted
                        if (type == "string" && value != null) {
                            if (value instanceof Number) {
                                type = (value instanceof Integer || value instanceof Long) ? "long" : "decimal"
                            } else if (value instanceof Boolean) {
                                type = "boolean"
                            } else if (value instanceof Collection || value instanceof Map) {
                                type = (value instanceof Collection) ? "list" : "map"
                            }
                        }
                        paramInfo.type = type
                        
                        // Extract required flag - defensive check
                        paramInfo.required = false
                        try {
                            if (param.hasProperty('required')) {
                                paramInfo.required = (param.required == true)
                            }
                        } catch (Exception e) {
                            // Skip if property doesn't exist
                        }
                        
                        // Extract default value - defensive check
                        try {
                            if (param.hasProperty('defaultValue') && param.defaultValue != null) {
                                paramInfo.defaultValue = param.defaultValue.toString()
                            }
                        } catch (Exception e) {
                            // Skip if property doesn't exist
                        }
                        
                        semanticState.parameters[name] = paramInfo
                    }
                }
                
                // Log semantic state size for optimization tracking
                def semanticStateJson = new groovy.json.JsonBuilder(semanticState).toString()
                def semanticStateSize = semanticStateJson.length()
                ec.logger.info("MCP Screen Execution: Semantic state size: ${semanticStateSize} bytes, data keys: ${semanticState.data.keySet()}, actions count: ${semanticState.actions.size()}")
            }
            
            ec.logger.info("MCP Screen Execution: Successfully rendered screen ${screenPath}, output length: ${output?.length() ?: 0}")

            def executionTime = (System.currentTimeMillis() - startTime) / 1000.0
            
            // Build result based on renderMode
            def content = []
            if ((renderMode == null || renderMode == "compact") && semanticState) {
                // Return compact actionable format (default)
                def compactData = convertToCompactFormat(semanticState, screenPath)
                
                // Include wiki summary if available
                if (wikiInstructions) {
                    def wikiSummary = extractSummary(wikiInstructions)
                    if (wikiSummary) compactData.help = wikiSummary
                }
                
                // Add action result if an action was executed
                if (actionResult) {
                    compactData.result = actionResult
                }
                
                content << [
                    type: "text",
                    text: new groovy.json.JsonBuilder(compactData).toString()
                ]
            } else if (renderMode == "aria" && semanticState) {
                // Return ARIA accessibility tree format
                def ariaTree = convertToAriaTree(semanticState, screenPath)
                def ariaResult = [
                    screenPath: screenPath,
                    aria: ariaTree
                ]
                
                // Include summary if available
                if (wikiInstructions) {
                    def summary = extractSummary(wikiInstructions)
                    if (summary) ariaResult.summary = summary
                }
                
                // Add action result if an action was executed
                if (actionResult) {
                    ariaResult.actionResult = actionResult
                }
                
                content << [
                    type: "text",
                    text: new groovy.json.JsonBuilder(ariaResult).toString()
                ]
            } else if ((renderMode == "mcp" || renderMode == "json") && semanticState) {
                // Return structured MCP data
                def mcpResult = [
                    screenPath: screenPath,
                    screenUrl: screenUrl,
                    executionTime: executionTime,
                    isError: isError,
                    semanticState: semanticState
                ]
                
                // Add action result if an action was executed
                if (actionResult) {
                    mcpResult.actionResult = actionResult
                }
                
                // Include text output preview (truncated for readability)
                if (output) {
                    mcpResult.textPreview = output.take(2000) + (output.length() > 2000 ? "..." : "")
                }
                if (wikiInstructions) {
                    mcpResult.wikiInstructions = wikiInstructions
                    def summary = extractSummary(wikiInstructions)
                    if (summary) mcpResult.summary = summary
                }
                
                content << [
                    type: "text",
                    text: new groovy.json.JsonBuilder(mcpResult).toString()
                ]
            } else {
                // Return raw output for other modes (text, html, etc)
                def textOutput = output
                if (wikiInstructions) {
                    textOutput = "--- Wiki Instructions ---\n\n${wikiInstructions}\n\n--- Screen Output ---\n\n${output}"
                }
                content << [
                    type: "text",
                    text: textOutput,
                    screenPath: screenPath,
                    screenUrl: screenUrl,
                    executionTime: executionTime,
                    isError: isError
                ]
            }
            
            result = [
                content: content,
                isError: false
            ]
            return // Success!

        } catch (Exception e) {
            isError = true
            ec.logger.error("MCP Screen Execution: Full exception for ${screenPath}", e)
            output = "SCREEN RENDERING ERROR: ${e.message}"
            result = [
                isError: true,
                content: [[type: "text", text: output]]
            ]
        }
    ]]></script>
</actions>
</service>

    <service verb="mcp" noun="ResourcesTemplatesList" authenticate="false" allow-remote="true" transaction-timeout="30">
        <description>Handle MCP resources/templates/list request</description>
        <in-parameters>
            <parameter name="sessionId"/>
        </in-parameters>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                
                ExecutionContext ec = context.ec
                
                // For now, return empty templates list - can be extended later
                def templates = []
                
                result = [resourceTemplates: templates]
            ]]></script>
        </actions>
    </service>
    
    <service verb="mcp" noun="ResourcesSubscribe" authenticate="false" allow-remote="true" transaction-timeout="30">
        <description>Handle MCP resources/subscribe request</description>
        <in-parameters>
            <parameter name="sessionId"/>
            <parameter name="uri" required="true"><description>Resource URI to subscribe to</description></parameter>
        </in-parameters>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                
                ExecutionContext ec = context.ec
                
                ec.logger.info("Resource subscription requested for URI: ${uri}, sessionId: ${sessionId}")
                
                // For now, just return success - actual subscription tracking could be added
                result = [subscribed: true, uri: uri]
            ]]></script>
        </actions>
    </service>
    
    <service verb="mcp" noun="ResourcesUnsubscribe" authenticate="false" allow-remote="true" transaction-timeout="30">
        <description>Handle MCP resources/unsubscribe request</description>
        <in-parameters>
            <parameter name="sessionId"/>
            <parameter name="uri" required="true"><description>Resource URI to unsubscribe from</description></parameter>
        </in-parameters>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                
                ExecutionContext ec = context.ec
                
                ec.logger.info("Resource unsubscription requested for URI: ${uri}, sessionId: ${sessionId}")
                
                // For now, just return success - actual subscription tracking could be added
                result = [unsubscribed: true, uri: uri]
            ]]></script>
        </actions>
    </service>
    
    <service verb="mcp" noun="PromptsList" authenticate="false" allow-remote="true" transaction-timeout="30">
        <description>Handle MCP prompts/list request</description>
        <in-parameters>
            <parameter name="sessionId"/>
        </in-parameters>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                import groovy.json.JsonSlurper
                
                ExecutionContext ec = context.ec
                
                ec.logger.info("MCP PromptsList: Listing prompts from wiki space MCP_PROMPTS")
                
                def prompts = []
                
                // Query all wiki pages in MCP_PROMPTS space
                def wikiPageList = ec.entity.find("moqui.resource.wiki.WikiPage")
                    .condition("wikiSpaceId", "MCP_PROMPTS")
                    .useCache(true)
                    .list()
                
                for (def wp in wikiPageList) {
                    // Try to load argument schema from attachment
                    def arguments = []
                    try {
                        def attachment = ec.entity.find("moqui.resource.wiki.WikiPageAttachment")
                            .condition("wikiPageId", wp.wikiPageId)
                            .condition("filename", "arguments.json")
                            .one()
                        if (attachment) {
                            def attachmentRef = ec.resource.getLocationReference(attachment.getLocation())
                            def jsonText = attachmentRef?.getText()
                            if (jsonText) {
                                arguments = new JsonSlurper().parseText(jsonText) ?: []
                            }
                        }
                    } catch (Exception e) {
                        ec.logger.debug("Could not parse arguments for ${wp.pagePath}: ${e.message}")
                    }
                    
                    prompts << [
                        name: wp.pagePath,
                        title: wp.pagePath.split('-').collect { it.capitalize() }.join(' '),
                        description: "MCP prompt template",
                        arguments: arguments
                    ]
                }
                
                result = [prompts: prompts]
            ]]></script>
        </actions>
    </service>
    
    <service verb="mcp" noun="PromptsGet" authenticate="false" allow-remote="true" transaction-timeout="30">
        <description>Handle MCP prompts/get request</description>
        <in-parameters>
            <parameter name="sessionId"/>
            <parameter name="name" required="true"><description>Prompt name to retrieve</description></parameter>
        </in-parameters>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                import groovy.text.GStringTemplateEngine
                import groovy.json.JsonSlurper
                import groovy.json.JsonBuilder
                
                ExecutionContext ec = context.ec
                
                ec.logger.info("MCP PromptsGet: Retrieving prompt '${name}' from wiki space MCP_PROMPTS")
                
                // Get the wiki page for this prompt
                def wikiPage = ec.entity.find("moqui.resource.wiki.WikiPage")
                    .condition("wikiSpaceId", "MCP_PROMPTS")
                    .condition("pagePath", name)
                    .one()
                
                if (!wikiPage) {
                    throw new Exception("Prompt not found: ${name}")
                }
                
                // Get the wiki space to build the page location
                def wikiSpace = ec.entity.find("moqui.resource.wiki.WikiSpace")
                    .condition("wikiSpaceId", "MCP_PROMPTS")
                    .one()
                
                if (!wikiSpace) {
                    throw new Exception("MCP Prompts wiki space not found")
                }
                
                // Build the resource location for the page (root + page path + .md)
                def pageLocation = wikiSpace.rootPageLocation
                if (!pageLocation.endsWith('/')) {
                    pageLocation += '/'
                }
                pageLocation += name + '.md'
                
                // Get the resource reference and text content
                def pageRef = ec.resource.getLocationReference(pageLocation)
                def templateText = pageRef?.getText()
                
                if (!templateText) {
                    throw new Exception("Prompt template not found: ${name}")
                }
                
                // Render template using Groovy GString engine
                def templateEngine = new GStringTemplateEngine()
                def template = templateEngine.createTemplate(templateText)
                def binding = arguments ?: [:]
                def rendered = template.make(binding).toString()
                
                ec.logger.info("MCP PromptsGet: Rendered prompt '${name}' with ${binding.size()} arguments")
                
                result = [
                    description: "MCP prompt template",
                    messages: [[
                        role: "user",
                        content: [type: "text", text: rendered]
                    ]]
                ]
            ]]></script>
        </actions>
    </service>
    
    <service verb="mcp" noun="RootsList" authenticate="false" allow-remote="true" transaction-timeout="30">
        <description>Handle MCP roots/list request</description>
        <in-parameters>
            <parameter name="sessionId"/>
        </in-parameters>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                
                ExecutionContext ec = context.ec
                
                // For now, return empty roots list - can be extended later
                def roots = []
                
                result = [roots: roots]
            ]]></script>
        </actions>
    </service>
    
    <service verb="mcp" noun="SamplingCreateMessage" authenticate="false" allow-remote="true" transaction-timeout="30">
        <description>Handle MCP sampling/createMessage request</description>
        <in-parameters>
            <parameter name="sessionId"/>
            <parameter name="messages" type="List"><description>List of messages to sample</description></parameter>
            <parameter name="maxTokens" type="Integer"><description>Maximum tokens to generate</description></parameter>
            <parameter name="temperature" type="BigDecimal"><description>Sampling temperature</description></parameter>
        </in-parameters>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                
                ExecutionContext ec = context.ec
                
                ec.logger.info("Sampling createMessage requested for sessionId: ${sessionId}")
                
                // For now, return not implemented - can be extended with actual LLM integration
                result = [error: "Sampling not implemented"]
            ]]></script>
        </actions>
    </service>
    
    <service verb="mcp" noun="ElicitationCreate" authenticate="false" allow-remote="true" transaction-timeout="30">
        <description>Handle MCP elicitation/create request</description>
        <in-parameters>
            <parameter name="sessionId"/>
            <parameter name="prompt"><description>Prompt for elicitation</description></parameter>
            <parameter name="context"><description>Context for elicitation</description></parameter>
        </in-parameters>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                
                ExecutionContext ec = context.ec
                
                ec.logger.info("Elicitation create requested for sessionId: ${sessionId}")
                
                // For now, return not implemented - can be extended later
                result = [error: "Elicitation not implemented"]
            ]]></script>
        </actions>
    </service>

    <service verb="mcp" noun="BrowseScreens" authenticate="false" allow-remote="true" transaction-timeout="60">
        <description>Browse Moqui screens hierarchically to discover functionality. Renders screen content with renderMode='mcp' by default. Supports action parameter for form submission and transitions.</description>
        <in-parameters>
            <parameter name="path" required="false"><description>Screen path to browse (e.g. 'PopCommerce'). Leave empty for root apps.</description></parameter>
            <parameter name="action"><description>Action to process before rendering: null (browse), 'submit' (form), 'create', 'update', or transition name</description></parameter>
            <parameter name="renderMode" default="compact"><description>Render mode: compact (default), aria (accessibility tree), text, html</description></parameter>
            <parameter name="parameters" type="Map"><description>Parameters to pass to screen during rendering or action</description></parameter>
            <parameter name="sessionId"/>
        </in-parameters>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext

                ExecutionContext ec = context.ec
                ec.logger.info("BrowseScreens: SERVICE STARTED")
                def subscreens = []
                def currentPath = path ?: "root"
                def userGroups = ec.user.getUserGroupIdSet().collect { it }

                // Strip query parameters from path for screen resolution
                if (currentPath.contains("?")) {
                    currentPath = currentPath.split("\\?")[0]
                }
                
                // Helper to load wiki content for a specific path (no hierarchy walk)
                def loadWikiContentForPath = { simplePath ->
                    try {
                        ec.logger.debug("BrowseScreens: Looking up wiki instructions for ${simplePath}")

                        def wikiPage = ec.entity.find("moqui.resource.wiki.WikiPage")
                            .condition("wikiSpaceId", "MCP_SCREEN_DOCS")
                            .condition("pagePath", simplePath)
                            .useCache(true)
                            .one()

                        if (wikiPage) {
                            ec.logger.debug("BrowseScreens: Found wikiPage: ${wikiPage.pagePath}")
                            def wikiSpace = ec.entity.find("moqui.resource.wiki.WikiSpace")
                                .condition("wikiSpaceId", wikiPage.wikiSpaceId)
                                .one()

                            if (wikiSpace) {
                                def dbResource = ec.entity.find("moqui.resource.DbResource")
                                    .condition("parentResourceId", "WIKI_MCP_SCREEN_DOCS")
                                    .condition("filename", wikiPage.pagePath + ".md")
                                    .one()

                                if (dbResource) {
                                    def dbResourceFile = ec.entity.find("moqui.resource.DbResourceFile")
                                        .condition("resourceId", dbResource.resourceId)
                                        .condition("versionName", wikiPage.publishedVersionName)
                                        .one()

                                    if (!dbResourceFile) {
                                        dbResourceFile = ec.entity.find("moqui.resource.DbResourceFile")
                                            .condition("resourceId", dbResource.resourceId)
                                            .one()
                                    }

                                    if (dbResourceFile && dbResourceFile.fileData) {
                                        def content = new String(dbResourceFile.fileData.getBytes(new Long(1).longValue(), new Long(dbResourceFile.fileData.length()).intValue()), "UTF-8")
                                        ec.logger.debug("BrowseScreens: Found wiki instructions for ${simplePath}, length: ${content?.length()}")
                                        return content
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        ec.logger.debug("BrowseScreens: Error getting wiki instructions for ${simplePath}: ${e.message}")
                    }
                    return null
                }
                
                // Helper function to load wiki content with path hierarchy walk
                // Walks up the path hierarchy to find the most specific wiki doc available
                // e.g., for "Catalog/Product/EditProduct/Assocs", tries in order:
                //   1. Catalog/Product/EditProduct/Assocs (most specific)
                //   2. Catalog/Product/EditProduct
                //   3. Catalog/Product
                //   4. Catalog
                def loadWikiContent = { path ->
                    ec.logger.info("BrowseScreens: loadWikiContent CALLED for ${path}")
                    
                    if (!path || path == "root") {
                        // For root, try exact match only
                        return loadWikiContentForPath("root")
                    }
                    
                    def simplePath = path
                    if (simplePath.contains("?")) {
                        simplePath = simplePath.split("\\?")[0]
                    }
                    // Normalize - remove leading/trailing slashes
                    simplePath = simplePath.replaceAll('^/+', '').replaceAll('/+$', '')
                    
                    if (!simplePath) return null
                    
                    // Build list of paths from most specific to least specific
                    def segments = simplePath.split('/')
                    for (int i = segments.length; i > 0; i--) {
                        def tryPath = segments[0..i-1].join('/')
                        def content = loadWikiContentForPath(tryPath)
                        if (content) {
                            if (tryPath != simplePath) {
                                ec.logger.info("BrowseScreens: Found inherited wiki docs at ${tryPath} for ${simplePath}")
                            }
                            return content
                        }
                    }
                    return null
                }

                // Helper to convert full component path to simple path (PopCommerce/screen/Root.xml -> PopCommerce/Root)
                def convertToSimplePath = { fullPath ->
                    if (!fullPath) return null
                    String cleanPath = fullPath
                    if (cleanPath.startsWith("component://")) cleanPath = cleanPath.substring(12)
                    if (cleanPath.endsWith(".xml")) cleanPath = cleanPath.substring(0, cleanPath.length() - 4)
                    List<String> parts = cleanPath.split('/').toList()
                    if (parts.size() > 1 && parts[1] == "screen") parts.remove(1)
                    return parts.join('/')
                }

                // Helper to extract short description from wiki content
                def getShortDescription = { wikiText ->
                    if (!wikiText) return null
                    def textString = wikiText instanceof String ? wikiText : new String(wikiText, "UTF-8")
                    def lines = textString.split('\n')
                    for (def line : lines) {
                        if (line.trim() && !line.trim().startsWith('#')) {
                            return line.trim().take(200)
                        }
                    }
                    return null
                }

                def resolvedScreenDef = null
                if (currentPath == "root") {
                    // Discover top-level applications
                    def aacvList = ec.entity.find("moqui.security.ArtifactAuthzCheckView")
                        .condition("userGroupId", userGroups)
                        .condition("artifactTypeEnumId", "AT_XML_SCREEN")
                        .useCache(true)
                        .disableAuthz()
                        .list()
                        
                    def rootScreens = new HashSet()
                    for (def aacv in aacvList) {
                        def name = aacv.artifactName
                        if (name.startsWith("component://") && name.endsWith(".xml")) {
                            def parts = name.substring(12).split('/')
                            if (parts.length >= 3 && parts[1] == "screen") {
                                def filename = parts[parts.length - 1]
                                def componentName = parts[0]
                                if (filename == componentName + ".xml" || filename == componentName + "Admin.xml" || filename == componentName + "Root.xml" || filename == "webroot.xml") {
                                    rootScreens.add(name)
                                }
                            }
                        }
                    }
                    
                    for (def screenPath in rootScreens) {
                        def simplePath = convertToSimplePath(screenPath)
                        def wikiContent = loadWikiContent(simplePath)
                        def description = wikiContent ? getShortDescription(wikiContent) : "Application: ${simplePath}"
                        subscreens << [
                            path: simplePath,
                            description: description
                        ]
                    }
                } else {
                    // Forward slash path resolution using Moqui standard with robust component-based fallback
                    def webrootSd = ec.screen.getScreenDefinition("component://webroot/screen/webroot.xml")
                    def pathSegments = []
                    currentPath.split('/').each { if (it && it.trim()) pathSegments.add(it) }
                    
                    // 1. Try literal resolution from webroot
                    def screenPathList = org.moqui.impl.screen.ScreenUrlInfo.parseSubScreenPath(
                        webrootSd, webrootSd, pathSegments, currentPath, [:], ec.screenFacade
                    )
                    
                    def currentSd = webrootSd
                    def reachedIndex = -1
                    if (screenPathList) {
                        for (int i = 0; i < screenPathList.size(); i++) {
                            def screenName = screenPathList[i]
                            def ssi = currentSd?.getSubscreensItem(screenName)
                            if (ssi && ssi.getLocation()) {
                                currentSd = ec.screen.getScreenDefinition(ssi.getLocation())
                                reachedIndex = i
                            } else {
                                break
                            }
                        }
                    }
                    
                    resolvedScreenDef = currentSd

                    // 2. If literal resolution failed, try Component-based resolution
                    if (reachedIndex == -1 && pathSegments.size() >= 2) {
                        def componentName = pathSegments[0]
                        def rootScreenName = pathSegments[1]
                        def compRootLoc = "component://${componentName}/screen/${rootScreenName}.xml"
                        
                        if (ec.resource.getLocationReference(compRootLoc).exists) {
                            ec.logger.info("BrowseScreens Path Resolution: Found component root at ${compRootLoc}")
                            resolvedScreenDef = ec.screen.getScreenDefinition(compRootLoc)
                            def subScreenPath = pathSegments.size() > 2 ? pathSegments[2..-1].join('/') : ""
                            
                            // Resolve further if there are remaining segments
                            if (subScreenPath) {
                                def remainingSegments = pathSegments[2..-1]
                                def compPathList = org.moqui.impl.screen.ScreenUrlInfo.parseSubScreenPath(
                                    resolvedScreenDef, resolvedScreenDef, remainingSegments, subScreenPath, [:], ec.screenFacade
                                )
                                if (compPathList) {
                                    for (String screenName in compPathList) {
                                        def ssi = resolvedScreenDef?.getSubscreensItem(screenName)
                                        if (ssi && ssi.getLocation()) {
                                            resolvedScreenDef = ec.screen.getScreenDefinition(ssi.getLocation())
                                        } else {
                                            break
                                        }
                                    }
                                }
                            }
                        }
                    }
                    
                    // 3. Fallback to double-slash search if still not found
                    if (reachedIndex == -1 && resolvedScreenDef == webrootSd && pathSegments.size() > 0 && !currentPath.startsWith("//")) {
                        def searchPath = "//" + pathSegments.join('/')
                        ec.logger.info("BrowseScreens Path Resolution: Fallback to search path ${searchPath}")
                        
                        def searchPathList = org.moqui.impl.screen.ScreenUrlInfo.parseSubScreenPath(
                            webrootSd, webrootSd, pathSegments, searchPath, [:], ec.screenFacade
                        )
                        
                        if (searchPathList) {
                            resolvedScreenDef = webrootSd
                            for (String screenName in searchPathList) {
                                def ssi = resolvedScreenDef?.getSubscreensItem(screenName)
                                if (ssi && ssi.getLocation()) {
                                    resolvedScreenDef = ec.screen.getScreenDefinition(ssi.getLocation())
                                } else {
                                    break
                                }
                            }
                        }
                    }

                    if (resolvedScreenDef) {
                        resolvedScreenDef.getSubscreensItemsSorted().each { subItem ->
                            def subName = subItem.getName()
                            def subPath = currentPath + "/" + subName
                            def wikiContent = loadWikiContent(subPath)
                            subscreens << [
                                path: subPath,
                                description: wikiContent ? getShortDescription(wikiContent) : "Subscreen: ${subName}"
                            ]
                        }
                    }
                }
                
                // Process action before rendering
                // Action execution is now handled by ScreenAsMcpTool via framework's transition handling
                // Just log that we're passing the action through
                if (action) {
                    ec.logger.info("BrowseScreens: Passing action '${action}' to ScreenAsMcpTool for framework execution")
                }
                
                // Try to get wiki instructions for screen
                def wikiInstructions = null

                ec.logger.info("BrowseScreens: About to check wiki instructions, currentPath='${currentPath}', isRoot=${currentPath == 'root'}")

                wikiInstructions = loadWikiContent(currentPath)

                // Render current screen if not root browsing
                def renderedContent = null
                def renderError = null
                def actualRenderMode = renderMode ?: "compact"

                def resultMap = [
                    currentPath: currentPath,
                    subscreens: subscreens,
                    renderMode: actualRenderMode
                ]
                
                // Add global navigation - these are always available regardless of current app
                // Mirrors the MyAccountNav component in the web UI
                resultMap.globalNav = [
                    [name: "My Notifications", path: "apps/my/User/Notifications", icon: "info"],
                    [name: "My Messages", path: "apps/my/User/Messages/FindMessage", icon: "message"],
                    [name: "My Calendar", path: "apps/my/User/Calendar/MyCalendar", icon: "calendar"],
                    [name: "My Tasks", path: "apps/my/User/Task/MyTasks", icon: "tasks"]
                ]

                if (currentPath != "root") {
                    try {
                        ec.logger.info("BrowseScreens: Rendering screen ${currentPath} with mode=${actualRenderMode}")

                        // Pass forward-slash path directly to ScreenAsMcpTool
                        // ScreenAsMcpTool will use Moqui's ScreenUrlInfo.parseSubScreenPath to navigate through screen hierarchy
                        // Action is passed through for framework-based transition execution
                        def browseScreenCallParams = [
                            path: path,
                            parameters: parameters ?: [:],
                            action: action,  // Let ScreenAsMcpTool handle via framework
                            renderMode: actualRenderMode,
                            sessionId: sessionId
                        ]

                        // Call ScreenAsMcpTool to render
                        def browseResult = ec.service.sync().name("McpServices.execute#ScreenAsMcpTool")
                            .parameters(browseScreenCallParams)
                            .call()

                        // Extract rendered content and semantic state from result
                        if (browseResult) {
                            def resultObj = null
                            // ScreenAsMcpTool returns {result: {content: [...]}}
                            if (browseResult.result) {
                                def contentList = browseResult.result.content
                                if (contentList && contentList.size() > 0) {
                                    def rawText = contentList[0].text
                                    if (rawText && rawText.startsWith("{")) {
                                        try { resultObj = new groovy.json.JsonSlurper().parseText(rawText) } catch(e) {}
                                    }
                                    renderedContent = rawText
                                }
                            }

                            // Handle compact mode - pass through compact data directly
                            if ((actualRenderMode == "compact" || actualRenderMode == null) && resultObj && resultObj.screen) {
                                // Compact mode returns flat structure, merge it into resultMap
                                resultObj.each { k, v -> if (k != "screen") resultMap[k] = v }
                                resultMap.screen = resultObj.screen
                                ec.logger.info("BrowseScreens: Compact mode - passing through for ${currentPath}")
                            // Handle ARIA mode - pass through the aria tree directly
                            } else if (actualRenderMode == "aria" && resultObj && resultObj.aria) {
                                resultMap.aria = resultObj.aria
                                if (resultObj.summary) resultMap.summary = resultObj.summary
                                ec.logger.info("BrowseScreens: ARIA mode - passing through aria tree for ${currentPath}")
                            } else if (resultObj && resultObj.semanticState) {
                                resultMap.semanticState = resultObj.semanticState

                                // Build UI narrative for LLM guidance
                                try {
                                    def narrativeBuilder = new org.moqui.mcp.UiNarrativeBuilder()
                                    // Use the screen definition we already resolved
                                    def screenDefForNarrative = resolvedScreenDef

                                    def uiNarrative = narrativeBuilder.buildNarrative(
                                        screenDefForNarrative,
                                        resultObj.semanticState,
                                        currentPath
                                    )
                                    resultMap.uiNarrative = uiNarrative
                                    ec.logger.info("BrowseScreens: Generated UI narrative for ${currentPath}: ${uiNarrative?.keySet()}")
                                } catch (Exception e) {
                                    ec.logger.warn("BrowseScreens: Failed to generate UI narrative: ${e.message}")
                                }
                            }
                        }

                        ec.logger.info("BrowseScreens: Successfully rendered screen ${currentPath}, content length: ${renderedContent?.length() ?: 0}")
                    } catch (Exception e) {
                        renderError = "Screen rendering failed: ${e.message}"
                        ec.logger.warn("BrowseScreens render error for ${currentPath}: ${e.message}")
                    }
                }
                
                if (actionResult) {
                    resultMap.actionResult = actionResult
                }

                // Don't include renderedContent for renderMode "mcp", "aria", or "compact" - structured data is provided instead
                // Including both duplicates data and truncation breaks JSON structure
                if (renderedContent && actualRenderMode != "mcp" && actualRenderMode != "aria" && actualRenderMode != "compact") {
                    resultMap.renderedContent = renderedContent
                }
                
                if (actionError) {
                    resultMap.actionError = actionError
                }

                if (wikiInstructions) {
                    resultMap.wikiInstructions = wikiInstructions
                    // Extract first non-header paragraph as summary
                    def summary = getShortDescription(wikiInstructions)
                    if (summary) {
                        resultMap.summary = summary
                    }
                }

                if (renderError) {
                    resultMap.renderError = renderError
                }
                
                // Return in MCP format - content array as direct child of result
                result = [
                    content: [[type: "text", text: new groovy.json.JsonBuilder(resultMap).toString()]],
                    isError: false
                ]
            ]]></script>
        </actions>
    </service>

    <service verb="mcp" noun="SearchScreens" authenticate="false" allow-remote="true" transaction-timeout="60">
        <description>Search for screens by name, path, or description. Builds an index by walking the screen tree.</description>
        <in-parameters>
            <parameter name="query" required="true"/>
            <parameter name="sessionId"/>
        </in-parameters>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                
                ExecutionContext ec = context.ec
                def matches = []
                def queryLower = query.toLowerCase()
                
                // Screen index cache key - use Moqui's cache API properly
                def cacheKey = "MCP_SCREEN_INDEX"
                def mcpCache = ec.cache.getCache("mcp.screen.index")
                def screenIndex = mcpCache.get(cacheKey)
                
                if (!screenIndex) {
                    ec.logger.info("SearchScreens: Building screen index...")
                    screenIndex = []
                    
                    // Helper to load wiki description for a path
                    def loadWikiDescription = { simplePath ->
                        try {
                            def wikiPage = ec.entity.find("moqui.resource.wiki.WikiPage")
                                .condition("wikiSpaceId", "MCP_SCREEN_DOCS")
                                .condition("pagePath", simplePath)
                                .useCache(true)
                                .one()
                            
                            if (wikiPage) {
                                def dbResource = ec.entity.find("moqui.resource.DbResource")
                                    .condition("parentResourceId", "WIKI_MCP_SCREEN_DOCS")
                                    .condition("filename", wikiPage.pagePath + ".md")
                                    .one()
                                
                                if (dbResource) {
                                    def dbResourceFile = ec.entity.find("moqui.resource.DbResourceFile")
                                        .condition("resourceId", dbResource.resourceId)
                                        .one()
                                    
                                    if (dbResourceFile && dbResourceFile.fileData) {
                                        def content = new String(dbResourceFile.fileData.getBytes(1L, dbResourceFile.fileData.length() as int), "UTF-8")
                                        // Extract first line or sentence as description
                                        def lines = content.split('\n')
                                        for (line in lines) {
                                            line = line.trim()
                                            if (line && !line.startsWith('#')) {
                                                return line.length() > 150 ? line.substring(0, 147) + "..." : line
                                            }
                                        }
                                    }
                                }
                            }
                        } catch (Exception e) {
                            ec.logger.debug("SearchScreens: Error loading wiki for ${simplePath}: ${e.message}")
                        }
                        return null
                    }
                    
                    // Recursive function to walk screen tree
                    def walkScreenTree
                    walkScreenTree = { screenDef, basePath, depth ->
                        if (depth > 6 || !screenDef) return  // Limit depth to prevent infinite loops
                        
                        try {
                            screenDef.getSubscreensItemsSorted().each { subItem ->
                                def subName = subItem.getName()
                                def subPath = basePath ? "${basePath}/${subName}" : subName
                                def subLocation = subItem.getLocation()
                                
                                if (subLocation) {
                                    // Get wiki description or generate from name
                                    def description = loadWikiDescription(subPath)
                                    if (!description) {
                                        // Generate description from screen name
                                        def humanName = subName.replaceAll(/([A-Z])/, ' $1').trim()
                                        description = "Screen: ${humanName}"
                                    }
                                    
                                    // Extract screen name for search
                                    def screenName = subName
                                    
                                    screenIndex << [
                                        path: subPath,
                                        name: screenName,
                                        description: description,
                                        depth: depth
                                    ]
                                    
                                    // Recurse into subscreen
                                    try {
                                        def subScreenDef = ec.screen.getScreenDefinition(subLocation)
                                        if (subScreenDef) {
                                            walkScreenTree(subScreenDef, subPath, depth + 1)
                                        }
                                    } catch (Exception e) {
                                        ec.logger.debug("SearchScreens: Could not load subscreen ${subPath}: ${e.message}")
                                    }
                                }
                            }
                        } catch (Exception e) {
                            ec.logger.debug("SearchScreens: Error walking ${basePath}: ${e.message}")
                        }
                    }
                    
                    // Start from webroot
                    def webrootSd = ec.screen.getScreenDefinition("component://webroot/screen/webroot.xml")
                    if (webrootSd) {
                        walkScreenTree(webrootSd, "", 0)
                    }
                    
                    // Cache the index
                    mcpCache.put(cacheKey, screenIndex)
                    ec.logger.info("SearchScreens: Built index with ${screenIndex.size()} screens")
                }
                
                // Search the index
                def scored = []
                for (screen in screenIndex) {
                    def score = 0
                    def nameLower = screen.name?.toLowerCase() ?: ""
                    def pathLower = screen.path?.toLowerCase() ?: ""
                    def descLower = screen.description?.toLowerCase() ?: ""
                    
                    // Exact name match (highest priority)
                    if (nameLower == queryLower) {
                        score += 100
                    }
                    // Name starts with query
                    else if (nameLower.startsWith(queryLower)) {
                        score += 50
                    }
                    // Name contains query
                    else if (nameLower.contains(queryLower)) {
                        score += 30
                    }
                    
                    // Path contains query
                    if (pathLower.contains(queryLower)) {
                        score += 20
                    }
                    
                    // Description contains query
                    if (descLower.contains(queryLower)) {
                        score += 10
                    }
                    
                    // Prefer shallower screens (more likely to be entry points)
                    if (score > 0) {
                        score -= (screen.depth ?: 0) * 2
                        scored << [screen: screen, score: score]
                    }
                }
                
                // Sort by score descending, take top 15
                scored.sort { -it.score }
                def topMatches = scored.take(15)
                
                for (item in topMatches) {
                    matches << [
                        path: item.screen.path,
                        name: item.screen.name,
                        description: item.screen.description
                    ]
                }
                
                // Add hint if no matches
                def hint = null
                if (matches.isEmpty()) {
                    hint = "No screens found matching '${query}'. Try broader terms like 'product', 'order', 'party', or use moqui_browse_screens to explore."
                } else if (matches.size() >= 15) {
                    hint = "Showing top 15 results. Refine your search for more specific matches."
                }
                
                def resultMap = hint ? [matches: matches, hint: hint] : [matches: matches]
                
                // Return in MCP format - content array with JSON text
                result = [
                    content: [[type: "text", text: new groovy.json.JsonBuilder(resultMap).toString()]],
                    isError: false
                ]
            ]]></script>
        </actions>
    </service>

    <service verb="list" noun="Tools" authenticate="false" allow-remote="true" transaction-timeout="60">
        <description>List discovery tools and the unified screen renderer.</description>
        <in-parameters>
            <parameter name="sessionId"/>
            <parameter name="cursor"/>
        </in-parameters>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                
                ExecutionContext ec = context.ec
                
                def tools = [
                    [
                        name: "moqui_browse_screens",
                        title: "Browse Screens",
                        description: "Browse Moqui screen hierarchy, process actions, and render screen content. Input 'path' (empty for root). Default renderMode is 'compact'.",
                        inputSchema: [
                            type: "object",
                            properties: [
                                "path": [type: "string", description: "Path to browse (e.g. 'PopCommerce')"],
                                "action": [type: "string", description: "Action to process before rendering: null (browse), 'submit' (form), 'create', 'update', or transition name"],
                                "renderMode": [type: "string", description: "Render mode: compact (default), aria (accessibility tree), text, html"],
                                "parameters": [type: "object", description: "Parameters to pass to screen during rendering or action"]
                            ]
                        ]
                    ],
                    [
                        name: "moqui_search_screens",
                        title: "Search Screens",
                        description: "Search for screens by name to find their paths.",
                        inputSchema: [
                            type: "object",
                            properties: [
                                "query": [type: "string", description: "Search query"]
                            ],
                            required: ["query"]
                        ]
                     ],
                     [
                        name: "moqui_get_screen_details",
                        title: "Get Screen Details",
                        description: "Get screen field details including dropdown options. Use this to understand available fields and their options before submitting forms.",
                        inputSchema: [
                            type: "object",
                            properties: [
                                "path": [type: "string", description: "Screen path to analyze (e.g., 'PopCommerce/PopCommerceAdmin/Party/FindParty')"],
                                "fieldName": [type: "string", description: "Optional specific field name. If not provided, returns all fields."],
                                "parameters": [type: "object", description: "Optional parameters to set in context before rendering (for autocomplete contexts)."]
                            ],
                            required: ["path"]
                        ]
                     ],
                     [
                        name: "moqui_get_help",
                        title: "Get Help",
                        description: "Fetch extended documentation for a screen or service. Use URIs from 'describedby' fields in ARIA responses.",
                        inputSchema: [
                            type: "object",
                            properties: [
                                "uri": [type: "string", description: "Help URI (e.g., 'wiki:screen:EditProduct' or 'wiki:service:ProductFeature')"]
                            ],
                            required: ["uri"]
                        ]
                     ],
                     [
                        name: "moqui_batch_operations",
                        title: "Batch Operations",
                        description: "Execute multiple screen operations in sequence. Stops on first error. Returns results for each operation.",
                        inputSchema: [
                            type: "object",
                            properties: [
                                "operations": [
                                    type: "array",
                                    description: "Array of operations to execute in sequence",
                                    items: [
                                        type: "object",
                                        properties: [
                                            "id": [type: "string", description: "Optional operation identifier for result tracking"],
                                            "path": [type: "string", description: "Screen path"],
                                            "action": [type: "string", description: "Action/transition to execute"],
                                            "parameters": [type: "object", description: "Parameters for the action"]
                                        ],
                                        required: ["path", "action"]
                                    ]
                                ],
                                "stopOnError": [type: "boolean", description: "Stop execution on first error (default: true)"],
                                "returnLastOnly": [type: "boolean", description: "Return only last operation result (default: false)"]
                            ],
                            required: ["operations"]
                        ]
                     ],
                      [
                        name: "prompts_list",
                        title: "List Prompts",
                        description: "List available MCP prompt templates.",
                        inputSchema: [
                            type: "object",
                            properties: [:]
                        ]
                    ],
                    [
                        name: "prompts_get",
                        title: "Get Prompt",
                        description: "Retrieve and render a specific MCP prompt template.",
                        inputSchema: [
                            type: "object",
                            properties: [
                                "name": [type: "string", description: "Prompt name"],
                                "arguments": [type: "object", description: "Arguments for prompt template"]
                            ],
                            required: ["name"]
                        ]
                    ]
                ]
                
                result = [tools: tools]
            ]]></script>
        </actions>
    </service>

    <service verb="mcp" noun="GetScreenDetails" authenticate="true" allow-remote="true" transaction-timeout="60">
        <description>Get screen field details including dropdown options. Use this to understand available fields and their options before submitting forms.</description>
        <in-parameters>
            <parameter name="path" required="true"><description>Screen path to analyze (e.g., '/PopCommerce/PopCommerceAdmin/Party/FindParty').</description></parameter>
            <parameter name="fieldName"><description>Optional specific field name. If not provided, returns all fields.</description></parameter>
            <parameter name="parameters" type="Map"><description>Optional parameters to set in context before rendering (for autocomplete contexts).</description></parameter>
        </in-parameters>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                import groovy.json.JsonBuilder
                import org.moqui.mcp.McpFieldOptionsService
                
                ExecutionContext ec = context.ec
                
                def serviceResult = McpFieldOptionsService.service(path, fieldName, parameters, ec)
                
                // Return in standard MCP format with content array
                def resultJson = new JsonBuilder(serviceResult).toString()
                result = [
                    content: [[type: "text", text: resultJson]],
                    isError: false
                ]
            ]]></script>
        </actions>
    </service>

    <service verb="mcp" noun="GetHelp" authenticate="true" allow-remote="true" transaction-timeout="30">
        <description>Fetch extended documentation for a screen or service. Use URIs from 'describedby' fields in ARIA responses.</description>
        <in-parameters>
            <parameter name="uri" required="true"><description>Help URI (e.g., 'wiki:screen:EditProduct' or 'wiki:service:ProductFeature')</description></parameter>
        </in-parameters>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                import groovy.json.JsonBuilder
                
                ExecutionContext ec = context.ec
                
                def content = null
                def metadata = [uri: uri]
                
                // Parse URI format: wiki:type:name
                // e.g., wiki:screen:EditProduct, wiki:service:ProductFeature
                if (uri?.startsWith("wiki:")) {
                    def parts = uri.split(":", 3)
                    if (parts.length >= 3) {
                        def wikiType = parts[1]  // screen, service
                        def pageName = parts[2]
                        
                        metadata.type = wikiType
                        metadata.name = pageName
                        
                        // Determine wiki space based on type
                        def wikiSpaceId = null
                        def pagePath = null
                        
                        switch (wikiType) {
                            case "screen":
                                wikiSpaceId = "MCP_SCREEN_DOCS"
                                // Try to find by screen name in page path
                                pagePath = pageName
                                break
                            case "service":
                                wikiSpaceId = "MCP_SERVICE_DOCS"
                                pagePath = pageName
                                break
                            default:
                                wikiSpaceId = "MCP_SCREEN_DOCS"
                                pagePath = pageName
                        }
                        
                        // Try to find wiki page by path
                        def wikiPage = ec.entity.find("moqui.resource.wiki.WikiPage")
                            .condition("wikiSpaceId", wikiSpaceId)
                            .condition("pagePath", pagePath)
                            .useCache(true)
                            .one()
                        
                        // If not found by exact path, try partial match
                        if (!wikiPage) {
                            def allPages = ec.entity.find("moqui.resource.wiki.WikiPage")
                                .condition("wikiSpaceId", wikiSpaceId)
                                .useCache(true)
                                .list()
                            wikiPage = allPages.find { it.pagePath?.endsWith(pagePath) || it.pagePath?.contains(pagePath) }
                        }
                        
                        if (wikiPage) {
                            // Use direct DbResource/DbResourceFile lookup (like BrowseScreens does)
                            def parentResourceId = (wikiType == "service") ? "WIKI_MCP_SERVICE_DOCS" : "WIKI_MCP_SCREEN_DOCS"
                            
                            def dbResource = ec.entity.find("moqui.resource.DbResource")
                                .condition("parentResourceId", parentResourceId)
                                .condition("filename", wikiPage.pagePath + ".md")
                                .one()
                            

                            
                            if (dbResource) {
                                def dbResourceFile = ec.entity.find("moqui.resource.DbResourceFile")
                                    .condition("resourceId", dbResource.resourceId)
                                    .condition("versionName", wikiPage.publishedVersionName)
                                    .one()
                                
                                if (!dbResourceFile) {
                                    dbResourceFile = ec.entity.find("moqui.resource.DbResourceFile")
                                        .condition("resourceId", dbResource.resourceId)
                                        .one()
                                }
                                
                                if (dbResourceFile && dbResourceFile.fileData) {
                                    content = new String(dbResourceFile.fileData.getBytes(new Long(1).longValue(), new Long(dbResourceFile.fileData.length()).intValue()), "UTF-8")
                                    metadata.found = true
                                    metadata.pagePath = wikiPage.pagePath
                                    metadata.resourceId = dbResource.resourceId
                                }
                            }
                        }
                        
                        if (!content) {
                            metadata.found = false
                            content = "No documentation found for ${wikiType}: ${pageName}. Available documentation can be found in the MCP_SCREEN_DOCS and MCP_SERVICE_DOCS wiki spaces."
                        }
                    }
                } else {
                    metadata.error = "Invalid URI format. Expected 'wiki:type:name' (e.g., 'wiki:service:ProductFeature')"
                    content = metadata.error
                }
                
                def resultData = [
                    content: content,
                    metadata: metadata
                ]
                
                result = [
                    content: [[type: "text", text: new JsonBuilder(resultData).toString()]],
                    isError: false
                ]
            ]]></script>
        </actions>
    </service>

    <!-- NOTE: handle#McpRequest service removed - functionality moved to screen/webapp.xml for unified handling -->

    <service verb="mcp" noun="BatchOperations" authenticate="true" allow-remote="true" transaction-timeout="120">
        <description>Execute multiple screen operations in sequence. Stops on first error by default. Returns results for each operation.</description>
        <in-parameters>
            <parameter name="operations" type="List" required="true"><description>Array of operations to execute in sequence</description></parameter>
            <parameter name="stopOnError" type="Boolean" default="true"><description>Stop execution on first error (default: true)</description></parameter>
            <parameter name="returnLastOnly" type="Boolean" default="false"><description>Return only last operation result (default: false)</description></parameter>
        </in-parameters>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                import groovy.json.JsonBuilder
                import groovy.json.JsonSlurper
                
                ExecutionContext ec = context.ec
                
                def results = []
                def hasError = false
                def lastResult = null
                def executedCount = 0
                
                ec.logger.info("BatchOperations: Starting batch with ${operations?.size()} operations, stopOnError=${stopOnError}")
                
                for (int i = 0; i < operations.size(); i++) {
                    def op = operations[i]
                    def opId = op.id ?: "op_${i + 1}"
                    
                    ec.logger.info("BatchOperations: Executing operation ${opId}: path=${op.path}, action=${op.action}")
                    
                    try {
                        // Call browse screens for each operation
                        def browseResult = ec.service.sync().name("McpServices.mcp#BrowseScreens")
                            .parameters([
                                path: op.path,
                                action: op.action,
                                parameters: op.parameters ?: [:],
                                renderMode: "compact"  // Use compact mode for efficiency
                            ])
                            .call()
                        
                        // Extract the result content
                        def opResult = [
                            id: opId,
                            path: op.path,
                            action: op.action,
                            status: "success"
                        ]
                        
                        // Parse the result to check for errors
                        if (browseResult?.result?.content) {
                            def contentList = browseResult.result.content
                            if (contentList && contentList.size() > 0) {
                                def rawText = contentList[0].text
                                if (rawText && rawText.startsWith("{")) {
                                    try {
                                        def parsed = new JsonSlurper().parseText(rawText)
                                        
                                        // Check if there's an action result with error
                                        if (parsed.result?.status == "error" || parsed.actionResult?.status == "error") {
                                            opResult.status = "error"
                                            opResult.message = parsed.result?.message ?: parsed.actionResult?.message
                                            opResult.validationErrors = parsed.result?.validationErrors ?: parsed.actionResult?.validationErrors
                                            hasError = true
                                        } else {
                                            // Success - extract relevant data
                                            opResult.result = parsed.result ?: parsed.actionResult
                                            if (parsed.result?.result) {
                                                // Copy any IDs for use in subsequent operations
                                                opResult.outputIds = parsed.result.result
                                            }
                                        }
                                    } catch (e) {
                                        // JSON parse failed, treat as success but no parsed data
                                        opResult.rawOutput = rawText
                                    }
                                }
                            }
                        }
                        
                        executedCount++
                        lastResult = opResult
                        results << opResult
                        
                        ec.logger.info("BatchOperations: Operation ${opId} completed with status=${opResult.status}")
                        
                        // Stop on error if requested
                        if (hasError && stopOnError) {
                            ec.logger.info("BatchOperations: Stopping batch due to error in operation ${opId}")
                            break
                        }
                        
                    } catch (Exception e) {
                        def opResult = [
                            id: opId,
                            path: op.path,
                            action: op.action,
                            status: "error",
                            message: "Exception: ${e.message}"
                        ]
                        results << opResult
                        lastResult = opResult
                        hasError = true
                        executedCount++
                        
                        ec.logger.error("BatchOperations: Exception in operation ${opId}: ${e.message}", e)
                        
                        if (stopOnError) {
                            break
                        }
                    }
                }
                
                def summary = [
                    totalOperations: operations.size(),
                    executedOperations: executedCount,
                    successCount: results.count { it.status == "success" },
                    errorCount: results.count { it.status == "error" },
                    hasError: hasError
                ]
                
                def resultData
                if (returnLastOnly) {
                    resultData = [
                        summary: summary,
                        result: lastResult
                    ]
                } else {
                    resultData = [
                        summary: summary,
                        results: results
                    ]
                }
                
                ec.logger.info("BatchOperations: Completed. Summary: ${summary}")
                
                result = [
                    content: [[type: "text", text: new JsonBuilder(resultData).toString()]],
                    isError: hasError
                ]
            ]]></script>
        </actions>
    </service>

</services>