McpServices.xml 84 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
<?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
                
                // 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
                def serverInfo = [
                    name: "Moqui MCP Server",
                    version: "2.0.1"
                ]
                
                result = [
                    protocolVersion: "2025-06-18",
                    capabilities: serverCapabilities,
                    serverInfo: serverInfo,
                    sessionId: sessionId,
                    instructions: "This server provides access to Moqui ERP through MCP. For common business queries: Use screen_PopCommerce_screen_PopCommerceAdmin_Catalog.Feature_FindFeature to search by features like color or size. Use screen_PopCommerce_screen_PopCommerceAdmin_Catalog.Product_FindProduct for product catalog, screen_PopCommerce_screen_PopCommerceAdmin_Order.FindOrder for order status, screen_PopCommerce_screen_PopCommerceRoot.Customer for customer management, screen_PopCommerce_screen_PopCommerceAdmin_Catalog.Product_EditPrices to check prices and screen_PopCommerce_screen_PopCommerceAdmin.QuickSearch for general searches. All screens support parameterized queries for filtering results."
                ]
                
                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 org.moqui.impl.context.UserFacadeImpl.UserInfo
                import groovy.json.JsonBuilder
                
                ExecutionContext ec = context.ec
                
                // Start timing for execution metrics
                def startTime = System.currentTimeMillis()
                
                // Handle stubbed MCP protocol methods by routing to actual Moqui services
                // Map contains MCP protocol method names to their actual service implementations
                def protocolMethodMappings = [
                    "tools/list": "McpServices.list#Tools",
                    "tools/call": "McpServices.mcp#ToolsCall", 
                    "resources/list": "McpServices.mcp#ResourcesList",
                    "resources/read": "McpServices.mcp#ResourcesRead",
                    "resources/subscribe": "McpServices.mcp#ResourcesSubscribe",
                    "resources/unsubscribe": "McpServices.mcp#ResourcesUnsubscribe",
                    "prompts/list": "McpServices.mcp#PromptsList",
                    "prompts/get": "McpServices.mcp#PromptsGet",
                    "ping": "McpServices.mcp#Ping",
                    "moqui_browse_screens": "McpServices.mcp#BrowseScreens",
                    "moqui_search_screens": "McpServices.mcp#SearchScreens",
                    "moqui_get_screen_details": "McpServices.mcp#GetScreenDetails"
                ]
                
                if (protocolMethodMappings.containsKey(name)) {
                    ec.logger.info("MCP ToolsCall: Routing protocol method ${name} to ${protocolMethodMappings[name]}")
                    def targetServiceName = protocolMethodMappings[name]
                    
                    // Special handling for tools/call to avoid infinite recursion
                    if (name == "tools/call") {
                        // Extract the actual tool name and arguments from arguments
                        def actualToolName = arguments?.name
                        def actualArguments = arguments?.arguments
                        
                        if (!actualToolName) {
                            throw new Exception("tools/call requires 'name' parameter in arguments")
                        }
                        
                        // Ensure sessionId is always passed through in arguments
                        if (actualArguments instanceof Map) {
                            actualArguments.sessionId = sessionId
                        } else {
                            actualArguments = [sessionId: sessionId]
                        }
                        
                        // Check if this is a screen tool (starts with screen_ or moqui_) - route to screen execution service
                        def screenPath = org.moqui.mcp.McpUtils.getScreenPath(actualToolName)
                        def isLegacyScreen = actualToolName.startsWith("screen_")
                        
                        if (screenPath || isLegacyScreen) {
                            ec.logger.info("MCP ToolsCall: Routing screen tool '${actualToolName}' to executeScreenAsMcpTool")
                            
                            def subscreenName = null
                            
                            if (isLegacyScreen) {
                                // Decode legacy screen path from tool name
                                def toolNameSuffix = actualToolName.substring(7)  // Remove "screen_" prefix
                                
                                // Check if this is a subscreen (contains dot after initial prefix)
                                if (toolNameSuffix.contains('.')) {
                                    def lastDotIndex = toolNameSuffix.lastIndexOf('.')
                                    def parentPath = toolNameSuffix.substring(0, lastDotIndex)
                                    subscreenName = toolNameSuffix.substring(lastDotIndex + 1)
                                    screenPath = "component://" + parentPath.replace('_', '/') + ".xml"
                                } else {
                                    screenPath = "component://" + toolNameSuffix.replace('_', '/') + ".xml"
                                }
                            } else {
                                // For moqui_ tools, check existence and fallback to subscreen
                                // Walk down from component root to find the actual screen file and the subscreen path below it
                                def cleanName = actualToolName.substring(6) // Remove moqui_
                                def parts = cleanName.split('_').toList()
                                def component = parts[0]
                                def currentPath = "component://${component}/screen"
                                def subNameParts = []
                                
                                // Parts start from index 1 (after component)
                                for (int i = 1; i < parts.size(); i++) {
                                    def part = parts[i]
                                    def nextPath = "${currentPath}/${part}"
                                    if (ec.resource.getLocationReference(nextPath + ".xml").getExists()) {
                                        currentPath = nextPath
                                        // Reset subNameParts when we find a deeper screen file
                                        subNameParts = []
                                    } else {
                                        subNameParts << part
                                    }
                                }
                                
                                screenPath = currentPath + ".xml"
                                if (subNameParts) subscreenName = subNameParts.join("_")
                            }
                            
                            ec.logger.info("MCP ToolsCall: Decoded screen tool - screenPath=${screenPath}, subscreen=${subscreenName}")
                            
                            // Call screen execution service with decoded parameters
                            def screenCallParams = [
                                screenPath: screenPath,
                                parameters: actualArguments, //actualArguments?.arguments ?: [:],
                                renderMode: actualArguments?.renderMode ?: "html",
                                sessionId: sessionId
                            ]
                            if (subscreenName) {
                                screenCallParams.subscreenName = subscreenName
                            }
                            

                            ec.logger.info("EXECUTESCREEN ${screenCallParams}")
                            return ec.service.sync().name("McpServices.execute#ScreenAsMcpTool")
                                .parameters(screenCallParams)
                                .call()
                        } else {
                            // For non-screen tools, check if it's another protocol method
                            def actualTargetServiceName = protocolMethodMappings[actualToolName]
                            if (actualTargetServiceName) {
                                ec.logger.info("MCP ToolsCall: Routing tools/call with name '${actualToolName}' to ${actualTargetServiceName}")
                                return ec.service.sync().name(actualTargetServiceName)
                                    .parameters(actualArguments ?: [:])
                                    .call()
                            } else {
                                throw new Exception("Unknown tool name: ${actualToolName}")
                            }
                        }
                    } else {
                        // For other protocol methods, call the target service with provided arguments
                        ec.logger.info("MCP ToolsCall: ${targetServiceName} ${arguments}")
                        def serviceResult = ec.service.sync().name(targetServiceName)
                            .parameters(arguments ?: [:])
                            .call()
                        
                        def executionTime = (System.currentTimeMillis() - startTime) / 1000.0
                        
                        // Convert result to MCP format
                        def content = []
                        if (serviceResult?.result) {
                            content << [
                                type: "text",
                                text: new groovy.json.JsonBuilder(serviceResult.result).toString()
                            ]
                        }
                        
                        result = [
                            content: content,
                            isError: false
                        ]
                        return
                    }
                }
                
                // Check if this is a screen-based tool using McpUtils
                def screenPath = null
                def subscreenName = null
                if (name.startsWith("moqui_")) {
                    def cleanName = name.substring(6)
                    def parts = cleanName.split('_').toList()
                    def component = parts[0]
                    def currentPath = "component://${component}/screen"
                    def subNameParts = []
                    
                    for (int i = 1; i < parts.size(); i++) {
                        def part = parts[i]
                        def nextPath = "${currentPath}/${part}"
                        if (ec.resource.getLocationReference(nextPath + ".xml").getExists()) {
                            currentPath = nextPath
                            subNameParts = []
                        } else {
                            subNameParts << part
                        }
                    }
                    screenPath = currentPath + ".xml"
                    if (subNameParts) subscreenName = subNameParts.join("_")
                } else {
                    screenPath = org.moqui.mcp.McpUtils.getScreenPath(name)
                }
                
                if (screenPath) {
                    ec.logger.info("Decoded screen path for tool ${name}: ${screenPath}, subscreen: ${subscreenName}")
                    
                    // Now call the screen tool with proper user context
                    def screenParams = arguments ?: [:]
                    // Use requested render mode from arguments, default to text for LLM-friendly output
                    def renderMode = screenParams.remove('renderMode') ?: "html"
                    def serviceCallParams = [screenPath: screenPath, parameters: screenParams, renderMode: renderMode, sessionId: sessionId]
                    if (subscreenName) {
                        serviceCallParams.subscreenName = subscreenName
                    }

                    ec.logger.info("SCREENASTOOL ${serviceCallParams}")
                    serviceResult = ec.service.sync().name("McpServices.execute#ScreenAsMcpTool")
                        .parameters(serviceCallParams)
                        .call()
                        
                    def executionTime = (System.currentTimeMillis() - startTime) / 1000.0
                    
                    // Convert result to MCP format
                    def content = []
                    
                    if (serviceResult?.result) {
                        // Handle screen execution result which has content array
                        if (serviceResult.result.content && serviceResult.result.content instanceof List) {
                            // Use the content array directly from the screen execution result
                            content.addAll(serviceResult.result.content)
                        } else if (serviceResult.result.type == "text" && serviceResult.result.text) {
                            content << [
                                type: "text", 
                                text: serviceResult.result.text
                            ]
                        } else {
                            content << [
                                type: "text", 
                                text: serviceResult.result.text ?: serviceResult.result.toString() ?: "Screen executed successfully"
                            ]
                        }
                    }
                    
                    result = [
                        content: content,
                        isError: false
                    ]
                    return
                }
                
                // For service tools, validate service exists
                if (!ec.service.isServiceDefined(name)) {
                    throw new Exception("Tool not found: ${name}")
                }
                
                // Capture original user for permission context
                def originalUsername = ec.user.username
                UserInfo adminUserInfo = null
                
                try {
                    // Execute service with elevated privileges for system access
                    // but maintain audit context with actual user
                    def serviceResult
                    adminUserInfo = null
                    try {
                        serviceResult = ec.service.sync().name(name).parameters(arguments ?: [:]).call()
                } finally {
                    if (adminUserInfo != null) {
                        ec.user.popUser()
                    }
                    ec.artifactExecution.enableAuthz()
                }
                    executionTime = (System.currentTimeMillis() - startTime) / 1000.0
                    
                    // Convert result to MCP format
                    content = []
                    if (serviceResult) {
                        content << [
                            type: "text",
                            text: new JsonBuilder(serviceResult).toString()
                        ]
                    }
                    
                    result = [
                        content: content,
                        isError: serviceResult?.result?.isError ?: false
                    ]
                } catch (Exception e2) {
                    executionTime = (System.currentTimeMillis() - startTime) / 1000.0
                    
                    result = [
                        content: [
                            [
                                type: "text",
                                text: "Error executing tool ${name}: ${e.message}"
                            ]
                        ],
                        isError: true
                    ]
                    
                    ec.logger.error("MCP tool execution error", e)
                } finally {
                    // Always restore original user context
                    if (adminUserInfo != null) {
                        ec.user.popUser()
                    }
                    
                    // Send a simple notification about tool execution
                    try {
                        def servlet = ec.web.getServletContext().getAttribute("enhancedMcpServlet")
                        ec.logger.info("TOOLS CALL: Got servlet reference: ${servlet != null}, sessionId: ${sessionId}")
                        if (servlet && sessionId) {
                            def notification = [
                                method: "notifications/tool_execution",
                                params: [
                                    toolName: name,
                                    executionTime: (System.currentTimeMillis() - startTime) / 1000.0,
                                    success: !result?.result?.isError,
                                    timestamp: System.currentTimeMillis()
                                ]
                            ]
                            servlet.queueNotification(sessionId, notification)
                            ec.logger.info("Queued tool execution notification for session ${sessionId}")
                        }
                    } 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</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
                import org.moqui.impl.context.UserFacadeImpl.UserInfo
                
                ExecutionContext ec = context.ec
                
                // Build list of available entities as resources
                def resources = []
                
                UserInfo adminUserInfo = null
                    
                // Store original user context before switching to ADMIN
                def originalUsername = ec.user.username
                def originalUserId = ec.user.userId
                def userGroups = ec.user.getUserGroupIdSet().collect { it }
                
                // Use curated list of commonly used entities instead of discovering all entities
                def availableResources = []
                
                ec.logger.debug("MCP ResourcesList: Starting permissions-based entity discovery ${userGroups}")
                
                // Get user's accessible entities using Moqui's optimized ArtifactAuthzCheckView
                def userAccessibleEntities = null as Set<String>
                adminUserInfo = null
                try {
                    adminUserInfo = ec.user.pushUser("ADMIN")
                    def aacvList = ec.entity.find("moqui.security.ArtifactAuthzCheckView")
                        .condition("userGroupId", userGroups)
                        .condition("artifactTypeEnumId", "AT_ENTITY")
                        .useCache(true)
                        .disableAuthz()
                        .list()
                    userAccessibleEntities = aacvList.collect { it.artifactName } as Set<String>
                } finally {
                    if (adminUserInfo != null) {
                        ec.user.popUser()
                    }
                }
                
                // Helper function to check if user has permission to an entity
                def userHasEntityPermission = { entityName ->
                    // Use pre-computed accessible entities set for O(1) lookup
                    return userAccessibleEntities != null && userAccessibleEntities.contains(entityName.toString())
                }
                
                // Add all permitted entities including ViewEntities for LLM convenience
                def allEntityNames = ec.entity.getAllEntityNames()
                def allViewNames = [] as Set<String>
                
                // Get ViewEntities by checking entity definitions for view entities
                def entityInfoList = ec.entity.getAllEntityInfo(0, true) // includeViewEntities=true
                for (entityInfo in entityInfoList) {
                    if (entityInfo.isViewEntity) {
                        allViewNames.add(entityInfo.entityName)
                    }
                }
                
                // Combine real entities and ViewEntities
                def allAccessibleEntities = allEntityNames + allViewNames
                
                for (entityName in allAccessibleEntities) {
                    if (userHasEntityPermission(entityName)) {
                        def description = "Moqui entity: ${entityName}"
                        if (entityName.contains("View")) {
                            description = "Moqui ViewEntity: ${entityName} (pre-joined data for LLM convenience)"
                        }
                        
                        ec.logger.debug("MCP ResourcesList: Adding entity: ${entityName}")
                        availableResources << [
                            uri: "entity://${entityName}",
                            name: entityName,
                            description: description,
                            mimeType: "application/json"
                        ]
                    }
                }
                
                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()
                
                // 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
                    def responseMap = [
                        entityName: entityName,
                        description: entityDef.description,
                        packageName: entityDef.packageName,
                        recordCount: entityList.size(),
                        data: entityList
                    ]
                    
                    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>

    <!-- Helper Functions -->
    
    <service verb="validate" noun="Origin" authenticate="false" allow-remote="false">
        <description>Validate Origin header for DNS rebinding protection</description>
        <in-parameters>
            <parameter name="origin" required="true"/>
        </in-parameters>
        <out-parameters>
            <parameter name="isValid" type="boolean"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                import org.moqui.impl.context.UserFacadeImpl.UserInfo
                
                ExecutionContext ec = context.ec
                
                // Allow localhost origins
                if (origin?.startsWith("http://localhost:") || origin?.startsWith("https://localhost:")) {
                    isValid = true
                    return
                }
                
                // Allow 127.0.0.1 origins
                if (origin?.startsWith("http://127.0.0.1:") || origin?.startsWith("https://127.0.0.1:")) {
                    isValid = true
                    return
                }
                
                // Allow same-origin requests (check against current host)
                def currentHost = ec.web?.request?.getServerName()
                def currentScheme = ec.web?.request?.getScheme()
                def currentPort = ec.web?.request?.getServerPort()
                
                def expectedOrigin = "${currentScheme}://${currentHost}"
                if ((currentScheme == "http" && currentPort != 80) || (currentScheme == "https" && currentPort != 443)) {
                    expectedOrigin += ":${currentPort}"
                }
                
                if (origin == expectedOrigin) {
                    isValid = true
                    return
                }
                
                // Check for configured allowed origins (could be from system properties)
                def allowedOrigins = ec.getFactory().getConfiguration().getStringList("moqui.mcp.allowed_origins", [])
                if (allowedOrigins.contains(origin)) {
                    isValid = true
                    return
                }
                
                isValid = false
            ]]></script>
        </actions>
    </service>
    
    <service verb="convert" noun="MoquiTypeToJsonSchemaType" authenticate="false">
        <description>Convert Moqui data types to JSON Schema types</description>
        <in-parameters>
            <parameter name="moquiType" required="true"/>
        </in-parameters>
        <out-parameters>
            <parameter name="jsonSchemaType"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                // Simple type mapping - can be expanded as needed
                def typeMap = [
                    "text-short": "string",
                    "text-medium": "string", 
                    "text-long": "string",
                    "text-very-long": "string",
                    "id": "string",
                    "id-long": "string",
                    "number-integer": "integer",
                    "number-decimal": "number",
                    "number-float": "number",
                    "date": "string",
                    "date-time": "string",
                    "date-time-nano": "string",
                    "boolean": "boolean",
                    "text-indicator": "boolean"
                ]
                
                jsonSchemaType = typeMap[moquiType] ?: "string"
            ]]></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="screenPath" required="true"/>
            <parameter name="parameters" type="Map"><description>Parameters to pass to the screen</description></parameter>
            <parameter name="renderMode" default="html"><description>Render mode: text, html, xml, vuet, qvt</description></parameter>
            <parameter name="sessionId"><description>Session ID for user context restoration</description></parameter>
            <parameter name="subscreenName"><description>Optional subscreen name for dot notation paths</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()
    // Note: Screen validation will happen during render
    // if (!ec.screen.isScreenDefined(screenPath)) {
    //     throw new Exception("Screen not found: ${screenPath}")
    // }
    
    // Set parameters in context
    if (parameters) {
        ec.context.putAll(parameters)
    }
    
    // Try to render screen content for LLM consumption
    def output = null
    def screenUrl = "http://localhost:8080/${screenPath}"
    def isError = false
    
    try {
        ec.logger.info("MCP Screen Execution: Attempting to render screen ${screenPath} using ScreenTest with proper root screen")
        
        // For ScreenTest to work properly, we need to use the correct root screen
        // The screenPath should be relative to the appropriate root screen
        def testScreenPath = screenPath
        def rootScreen = "component://webroot/screen/webroot.xml"
        
        // Initialize standalone flag outside the if block
        def targetScreenDef = null
        def isStandalone = false
        
            def pathAfterComponent = screenPath.substring(12).replace('.xml','') // Remove "component://"
            def pathParts = pathAfterComponent.split("/")
                // If the screen path is already a full component:// path, we need to handle it differently
        if (screenPath.startsWith("component://")) {
            // For component:// paths, we need to use the component's root screen, not webroot
            // Extract the component name and use its root screen
            if (pathParts.length >= 2) {
                def componentName = pathParts[0]
                def remainingPath = pathParts[1..-1].join("/")
                
                // Check if the target screen itself is standalone FIRST
                try {
                    targetScreenDef = ec.screen.getScreenDefinition(screenPath)
                    ec.logger.info("MCP Screen Execution: Target screen def for ${screenPath}: ${targetScreenDef?.getClass()?.getSimpleName()}")
                    if (targetScreenDef?.screenNode) {
                        def standaloneAttr = targetScreenDef.screenNode.attribute('standalone')
                        ec.logger.info("MCP Screen Execution: Target screen ${screenPath} standalone attribute: '${standaloneAttr}'")
                        isStandalone = standaloneAttr == "true"
                    } else {
                        ec.logger.warn("MCP Screen Execution: Target screen ${screenPath} has no screenNode")
                    }
                    ec.logger.info("MCP Screen Execution: Target screen ${screenPath} standalone=${isStandalone}")
                    
                    if (isStandalone) {
                        // For standalone screens, try to render with minimal context or fall back to URL
                        ec.logger.info("MCP Screen Execution: Standalone screen detected, will try direct rendering")
                        rootScreen = screenPath
                        testScreenPath = ""  // Empty path for standalone screens
                        // We'll handle standalone screens specially below
                    }
                } catch (Exception e) {
                    ec.logger.warn("MCP Screen Execution: Error checking target screen ${screenPath}: ${e.message}")
                    ec.logger.error("MCP Screen Execution: Full exception", e)
                }
                
                // Only look for component root if target is not standalone
                if (!isStandalone) {
                    // For component://webroot/screen/... paths, always use webroot as root
                    if (pathAfterComponent.startsWith("webroot/screen/")) {
                        // This is a webroot screen, use webroot as root and the rest as path
                        rootScreen = "component://webroot/screen/webroot.xml"
                        testScreenPath = pathAfterComponent.substring("webroot/screen/".length())
                        // Remove any leading "webroot/" from the path since we're already using webroot as root
                        if (testScreenPath.startsWith("webroot/")) {
                            testScreenPath = testScreenPath.substring("webroot/".length())
                        }
                        ec.logger.info("MCP Screen Execution: Using webroot root for webroot screen: ${rootScreen} with path: ${testScreenPath}")
                    } else {
                        // For other component screens, check if this is a direct screen path (not a subscreen path)
                        def pathSegments = remainingPath.split("/")
                        def isDirectScreenPath = false
                        
                        // Try to check if the full path is a valid screen
                        try {
                            def directScreenDef = ec.screen.getScreenDefinition(screenPath)
                            if (directScreenDef) {
                                isDirectScreenPath = true
                                ec.logger.info("MCP Screen Execution: Found direct screen path: ${screenPath}")
                            }
                        } catch (Exception e) {
                            ec.logger.debug("MCP Screen Execution: Direct screen check failed for ${screenPath}: ${e.message}")
                        }
                        
                        if (isDirectScreenPath) {
                            // For direct screen paths, use the screen itself as root
                            rootScreen = screenPath
                            testScreenPath = ""
                            ec.logger.info("MCP Screen Execution: Using direct screen as root: ${rootScreen}")
                        } else {
                            // Try to find the actual root screen for this component
                            def componentRootScreen = null
                            def possibleRootScreens = [
                                "${componentName}.xml",
                                "${componentName}Admin.xml",
                                "${componentName}Root.xml"
                            ]
                            
                            for (rootScreenName in possibleRootScreens) {
                                def candidateRoot = "component://${componentName}/screen/${rootScreenName}"
                                try {
                                    def testDef = ec.screen.getScreenDefinition(candidateRoot)
                                    if (testDef) {
                                        componentRootScreen = candidateRoot
                                        ec.logger.info("MCP Screen Execution: Found component root screen: ${componentRootScreen}")
                                        break
                                    }
                                } catch (Exception e) {
                                    ec.logger.debug("MCP Screen Execution: Root screen ${candidateRoot} not found: ${e.message}")
                                }
                            }
                            
                            if (componentRootScreen) {
                                rootScreen = componentRootScreen
                                testScreenPath = remainingPath
                                ec.logger.info("MCP Screen Execution: Using component root ${rootScreen} for path ${testScreenPath}")
                            } else {
                                // For mantle and other components, try using the component's screen directory as root
                                // This is a better fallback than webroot
                                def componentScreenRoot = "component://${componentName}/screen/"
                                if (pathAfterComponent.startsWith("${componentName}/screen/")) {
                                    // Extract the screen file name from the path
                                    def screenFileName = pathAfterComponent.substring("${componentName}/screen/".length())
                                    rootScreen = screenPath  // Use the full path as root
                                    testScreenPath = ""     // Empty path for direct screen access
                                    ec.logger.info("MCP Screen Execution: Using component screen as direct root: ${rootScreen}")
                                } else {
                                    // Final fallback: try webroot
                                    rootScreen = "component://webroot/screen/webroot.xml"
                                    testScreenPath = pathAfterComponent
                                    ec.logger.warn("MCP Screen Execution: Could not find component root for ${componentName}, using webroot fallback: ${testScreenPath}")
                                }
                            }
                        }
                    }
                }
            } else {
                // Fallback for malformed component paths
                testScreenPath = pathAfterComponent
                ec.logger.warn("MCP Screen Execution: Malformed component path, using fallback: ${testScreenPath}")
            }
        }
        
        // Handle subscreen if specified
        if (subscreenName) {
            ec.logger.info("MCP Screen Execution: Handling subscreen ${subscreenName} for parent ${screenPath}")
            
            // For subscreens, we need to modify the render path to include the subscreen
            // The pathParts array already contains the full path, so we need to add the subscreen name
            def subscreenPathParts = pathParts + subscreenName.split('_')
            ec.logger.info("MCP Screen Execution: Full subscreen path parts: ${subscreenPathParts}")
            
            // User context should already be correct from MCP servlet restoration
            // CustomScreenTestImpl will capture current user context automatically
            ec.logger.info("MCP Screen Execution: Current user context - userId: ${ec.user.userId}, username: ${ec.user.username}")
            
            // Regular screen rendering with current user context - use our custom ScreenTestImpl
            def screenTest = new org.moqui.mcp.CustomScreenTestImpl(ec.ecfi)
                .rootScreen(rootScreen)
                .renderMode(renderMode ? renderMode : "html")
                .auth(ec.user.username) // Propagate current user to the test renderer
            
            ec.logger.info("MCP Screen Execution: ScreenTest object created for subscreen: ${screenTest?.getClass()?.getSimpleName()}")
                
            if (screenTest) {
                def renderParams = parameters ?: [:]
                
                // Add current user info to render context to maintain authentication
                renderParams.userId = ec.user.userId
                renderParams.username = ec.user.username
                
                // Set user context in ScreenTest to maintain authentication
                // Note: ScreenTestImpl may not have direct userAccountId property, 
                // the user context should be inherited from the current ExecutionContext
                ec.logger.info("MCP Screen Execution: Current user context - userId: ${ec.user.userId}, username: ${ec.user.username}")
                ec.logger.info("SUBSCREEN PATH PARTS ${subscreenPathParts}")
                
                // Regular screen rendering with timeout for subscreen
                try {
                    // Construct the proper relative path from parent screen to target subscreen
                    // The subscreenName contains the full path from parent with underscores, convert to proper path
                    def relativePath = subscreenName.replaceAll('_','/')
                    ec.logger.info("TESTRENDER ${relativePath} ${renderParams}")
                    // For subscreens, use the full relative path from parent screen to target subscreen
                    def testRender = screenTest.render(relativePath, renderParams, "POST")
                    output = testRender.getOutput()
                    def outputLength = output?.length() ?: 0
                    ec.logger.info("MCP Screen Execution: Successfully rendered screen ${screenPath}, output length: ${output?.length() ?: 0}")
                } catch (java.util.concurrent.TimeoutException e) {
                    throw new Exception("Screen rendering timed out after 30 seconds for ${screenPath}")
                }
            } else {
                throw new Exception("ScreenTest object is null")
            }
        } else {
            // Direct screen execution (no subscreen)
            ec.logger.info("MCP Screen Execution: Rendering direct screen ${screenPath} (root: ${rootScreen}, path: ${testScreenPath})")
            
            def screenTest = new org.moqui.mcp.CustomScreenTestImpl(ec.ecfi)
                .rootScreen(rootScreen)
                .renderMode(renderMode ? renderMode : "html")
                .auth(ec.user.username)
            
            if (screenTest) {
                def renderParams = parameters ?: [:]
                renderParams.userId = ec.user.userId
                renderParams.username = ec.user.username
                
                try {
                    ec.logger.info("TESTRENDER ${testScreenPath} ${renderParams}")
                    def testRender = screenTest.render(testScreenPath, renderParams, "POST")
                    output = testRender.getOutput()
                    ec.logger.info("MCP Screen Execution: Successfully rendered screen ${screenPath}, output length: ${output?.length() ?: 0}")
                } catch (java.util.concurrent.TimeoutException e) {
                    throw new Exception("Screen rendering timed out after 30 seconds for ${screenPath}")
                }
            }
        }
    } catch (Exception e) {
        isError = true
        ec.logger.warn("MCP Screen Execution: Could not render screen ${screenPath}, exposing error details: ${e.message}")
        ec.logger.warn("MCP Screen Execution: Exception details: ${e.getClass()?.getSimpleName()}: ${e.getMessage()}")
        ec.logger.error("MCP Screen Execution: Full exception for ${screenPath}", e)
        
        // Expose detailed error information instead of URL fallback
        def errorDetails = []
        errorDetails << "SCREEN RENDERING ERROR"
        errorDetails << "======================"
        errorDetails << "Screen Path: ${screenPath}"
        errorDetails << "Error Type: ${e.getClass()?.getSimpleName()}"
        errorDetails << "Error Message: ${e.getMessage()}"
        errorDetails << ""
        
        // Add stack trace for debugging (limited depth for readability)
        if (e.getStackTrace()) {
            errorDetails << "Stack Trace (top 10 frames):"
            e.getStackTrace().take(10).eachWithIndex { stackTrace, index ->
                errorDetails << "  ${index + 1}. ${stackTrace.toString()}"
            }
            if (e.getStackTrace().size() > 10) {
                errorDetails << "  ... and ${e.getStackTrace().size() - 10} more frames"
            }
        }
        
        // Add cause information if available
        def cause = e.getCause()
        if (cause) {
            errorDetails << ""
            errorDetails << "Root Cause: ${cause.getClass()?.getSimpleName()}: ${cause.getMessage()}"
        }
        
        // Add context information
        errorDetails << ""
        errorDetails << "Context Information:"
        errorDetails << "- User: ${ec.user.username} (${ec.user.userId})"
        errorDetails << "- Render Mode: ${renderMode}"
        errorDetails << "- Parameters: ${parameters ?: 'none'}"
        errorDetails << "- Execution Time: ${((System.currentTimeMillis() - startTime) / 1000.0)}s"
        
        // Add troubleshooting suggestions
        errorDetails << ""
        errorDetails << "Troubleshooting Suggestions:"
        errorDetails << "1. Check if the screen path is correct and the screen exists"
        errorDetails << "2. Verify user has permission to access this screen"
        errorDetails << "3. Check if all required parameters are provided"
        errorDetails << "4. Verify screen dependencies and data access"
        errorDetails << "5. Check server logs for more detailed error information"
        
        output = errorDetails.join("\n")
    }
    
    // Helper function to convert web paths to MCP tool names
    def convertWebPathToMcpTool = { path ->
        try {
            ec.logger.info("Converting web path to MCP tool: ${path}")
            // Handle simple catalog paths (dropdown menu items)
            if (path == "Category" || path.startsWith("Category/") || path == "Product/FindProduct/getCategoryList") {
                return "moqui_SimpleScreens_SimpleScreens_Catalog_Category"
            } else if (path == "Feature" || path.startsWith("Feature/")) {
                return "moqui_SimpleScreens_SimpleScreens_Catalog_Feature"
            } else if (path == "FeatureGroup" || path.startsWith("FeatureGroup/")) {
                return "moqui_SimpleScreens_SimpleScreens_Catalog_FeatureGroup"
            } else if (path == "Product" || path.startsWith("Product/")) {
                return "moqui_SimpleScreens_SimpleScreens_Catalog_Product"
            } else if (path.startsWith("Search")) {
                return "moqui_SimpleScreens_SimpleScreens_Search"
            }
            
            // Handle full catalog paths
            if (path.startsWith("Product/FindProduct")) {
                return "screen_SimpleScreens_screen_SimpleScreens_Catalog_Product"
            } else if (path.startsWith("Category/FindCategory")) {
                return "screen_SimpleScreens_screen_SimpleScreens_Catalog_Category"  
            } else if (path.startsWith("Feature/FindFeature")) {
                return "screen_SimpleScreens_screen_SimpleScreens_Catalog_Feature"
            } else if (path.startsWith("FeatureGroup/FindFeatureGroup")) {
                return "screen_SimpleScreens_screen_SimpleScreens_Catalog_FeatureGroup"
            }
            
            // Handle PopCommerce Admin paths
            if (path.startsWith("PopcAdmin/")) {
                def cleanPath = path.replace("PopcAdmin/", "PopCommerceAdmin/")
                def toolName = "screen_PopCommerce_screen_" + cleanPath.replace("/", "_")
                return toolName
            }
            
            // Handle SimpleScreens paths
            if (path.startsWith("apps/")) {
                def cleanPath = path.replace("apps/", "")
                def toolName = "screen_SimpleScreens_screen_SimpleScreens_" + cleanPath.replace("/", "_")
                return toolName
            }
            
            return null
        } catch (Exception e) {
            ec.logger.debug("Error converting web path ${path} to MCP tool: ${e.message}")
            return null
        }
    }
    
    def executionTime = (System.currentTimeMillis() - startTime) / 1000.0
    
    // Convert web URLs to MCP tool suggestions to keep users in MCP ecosystem
    def processedOutput = output
    if (output && !isError) {
        try {
            // Convert common web URLs to MCP tool suggestions
            processedOutput = output.replaceAll(/http:\/\/localhost:8080\/([^\s"'>]+)/) { match ->
                def path = match[1]
                def toolName = convertWebPathToMcpTool(path)
                if (toolName) {
                    return "MCP_TOOL:${toolName}"
                } else {
                    return match[0] // Keep original if no MCP tool found
                }
            }
            
            ec.logger.info("MCP Screen Execution: Converted web URLs to MCP tool suggestions for ${screenPath}")
        } catch (Exception e) {
            ec.logger.warn("MCP Screen Execution: Error converting URLs to MCP tools: ${e.message}")
            // Keep original output if conversion fails
        }
    }
    
    // Return screen result directly as content array (standard MCP flow)
    def content = []
    
    // Add execution status as first content item
    /*
    content << [
        type: "text",
        text: "Screen execution completed for ${screenPath} in ${executionTime}s"
    ]
    */
    
    // Add screen HTML as main content
    content << [
        type: "text",
        text: processedOutput,
        screenPath: screenPath,
        screenUrl: screenUrl,
        executionTime: executionTime,
        isError: isError
    ]
    
    result = [
        content: content,
        isError: false
    ]
    
    ec.logger.info("MCP Screen Execution: Returned result directly for screen ${screenPath} in ${executionTime}s")
            ]]></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
                
                ExecutionContext ec = context.ec
                
                // For now, return empty prompts list - can be extended later
                def prompts = []
                
                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
                
                ExecutionContext ec = context.ec
                
                ec.logger.info("Prompt requested: ${name}, sessionId: ${sessionId}")
                
                // For now, return not found - can be extended later
                result = [error: "Prompt not found: ${name}"]
            ]]></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="30">
        <description>Browse Moqui screens hierarchically to discover functionality.</description>
        <in-parameters>
            <parameter name="path" required="false"><description>Screen path or tool name to browse. Leave empty for root apps.</description></parameter>
            <parameter name="sessionId"/>
        </in-parameters>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                import org.moqui.mcp.McpUtils
                
                ExecutionContext ec = context.ec
                def subscreens = []
                def tools = []
                def currentPath = path
                
                // Logic to find screens
                if (!path || path == "/" || path == "root") {
                    currentPath = "root"
                    // Return known root apps
                    // In a real implementation, we'd discover these from components
                    def roots = ["PopCommerce", "SimpleScreens", "HiveMind", "Mantle"]
                    
                    for (root in roots) {
                        def toolName = "moqui_${root}"
                        subscreens << [
                            name: toolName,
                            path: toolName, 
                            description: "Application: ${root}"
                        ]
                    }
                } else {
                    // Resolve path
                    def screenPath = path.startsWith("moqui_") ? McpUtils.getScreenPath(path) : null
                    // Keep track of the tool name used to reach here, to maintain context
                    def baseToolName = path.startsWith("moqui_") ? path : null

                    if (!screenPath && !path.startsWith("component://")) {
                        // Try to handle "popcommerce/admin" style by guessing
                        def toolName = "moqui_" + path.replace('/', '_')
                        screenPath = McpUtils.getScreenPath(toolName)
                        if (!baseToolName) baseToolName = toolName
                    } else if (path.startsWith("component://")) {
                        screenPath = path
                        // If starting with component path, we can't easily establish a base tool name 
                        // that preserves context if it's not a standard path. 
                        // But McpUtils.getToolName will try.
                        if (!baseToolName) baseToolName = McpUtils.getToolName(path)
                    }
                    
                    if (screenPath) {
                        // Check if screen exists, if not try to resolve as subscreen
                        if (!ec.resource.getLocationReference(screenPath).getExists()) {
                            def lastSlash = screenPath.lastIndexOf('/')
                            if (lastSlash > 0) {
                                def parentPath = screenPath.substring(0, lastSlash) + ".xml"
                                def subscreenName = screenPath.substring(lastSlash + 1).replace('.xml', '')
                                
                                if (ec.resource.getLocationReference(parentPath).getExists()) {
                                    // Found parent, now find the subscreen location
                                    try {
                                        def parentDef = ec.screen.getScreenDefinition(parentPath)
                                        def subscreenItem = parentDef?.getSubscreensItem(subscreenName)
                                        if (subscreenItem && subscreenItem.getLocation()) {
                                            ec.logger.info("Redirecting browse from ${screenPath} to ${subscreenItem.getLocation()}")
                                            screenPath = subscreenItem.getLocation()
                                        }
                                    } catch (Exception e) {
                                        ec.logger.warn("Error resolving subscreen location: ${e.message}")
                                    }
                                }
                            }
                        }

                        try {
                            // First, add the current screen itself as a tool if it's executable
                            // Use baseToolName if available to preserve context (e.g. moqui_PopCommerce_...)
                            // even if the implementation is in another component (e.g. SimpleScreens)
                            def currentToolName = baseToolName ?: McpUtils.getToolName(screenPath)
                            tools << [
                                name: currentToolName,
                                description: "Execute screen: ${currentToolName}",
                                type: "screen"
                            ]

                            // Then look for subscreens
                            // Use getScreenInfoList with depth/mode? to ensure implicit subscreens are loaded
                            // The original list#Tools used getScreenInfoList(path, 1)
                            def screenInfoList = null
                            try {
                                screenInfoList = ec.screen.getScreenInfoList(screenPath, 1)
                            } catch (Exception e) {
                                ec.logger.debug("getScreenInfoList failed, trying getScreenInfo: ${e.message}")
                            }
                            
                            def screenInfo = screenInfoList ? screenInfoList.first() : ec.screen.getScreenInfo(screenPath)
                            
                            if (screenInfo?.subscreenInfoByName) {
                                for (entry in screenInfo.subscreenInfoByName) {
                                    def subName = entry.key
                                    def subInfo = entry.value
                                    
                                    // Construct sub-tool name by extending the parent path
                                    // This assumes subscreens are structurally nested in the tool name
                                    // e.g. moqui_PopCommerce_Admin -> moqui_PopCommerce_Admin_Catalog
                                    def parentToolName = baseToolName ?: McpUtils.getToolName(screenPath)
                                    def subToolName = parentToolName + "_" + subName
                                    
                                    subscreens << [
                                        name: subToolName,
                                        path: subToolName,
                                        description: "Subscreen: ${subName}"
                                    ]
                                }
                            }
                        } catch (Exception e) {
                            ec.logger.warn("Browse error for ${screenPath}: ${e.message}")
                        }
                    }
                }
                
                result = [
                    currentPath: currentPath,
                    subscreens: subscreens,
                    availableTools: tools,
                    message: "Found ${subscreens.size()} subscreens and ${tools.size()} tools."
                ]
            ]]></script>
        </actions>
    </service>

    <service verb="mcp" noun="SearchScreens" authenticate="false" allow-remote="true" transaction-timeout="60">
        <description>Search for screens by name or path.</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
                import org.moqui.mcp.McpUtils
                
                ExecutionContext ec = context.ec
                def matches = []
                
                // Search all screens known to the system (via authz rules)
                // Use disableAuthz() to bypass permission check on the system view itself
                def aacvList = ec.entity.find("moqui.security.ArtifactAuthzCheckView")
                    .condition("artifactTypeEnumId", "AT_XML_SCREEN")
                    .condition("artifactName", "like", "%${query}%")
                    .selectField("artifactName")
                    .distinct(true)
                    .disableAuthz()
                    .limit(20)
                    .list()
                
                for (hit in aacvList) {
                    def toolName = McpUtils.getToolName(hit.artifactName)
                    if (toolName) {
                        matches << [
                            name: toolName,
                            description: "Screen: ${hit.artifactName}"
                        ]
                    }
                }
                
                result = [matches: matches]
            ]]></script>
        </actions>
    </service>

    <service verb="mcp" noun="GetScreenDetails" authenticate="false" allow-remote="true" transaction-timeout="30">
        <description>Get detailed schema and usage info for a specific screen tool.</description>
        <in-parameters>
            <parameter name="name" required="true"><description>Tool name (e.g. moqui_PopCommerce_...)</description></parameter>
            <parameter name="sessionId"/>
        </in-parameters>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                import org.moqui.mcp.McpUtils
                
                ExecutionContext ec = context.ec
                def screenPath = McpUtils.getScreenPath(name)
                ec.logger.info("GetScreenDetails: name=${name} -> screenPath=${screenPath}")
                def toolDef = null
                
                if (screenPath) {
                    try {
                        def parameters = [:]
                        // Use getScreenDefinition for stable access to parameters
                        def screenDef = ec.screen.getScreenDefinition(screenPath)
                        
                        if (screenDef && screenDef.screenNode) {
                            // Extract parameters from XML node
                            def parameterNodes = screenDef.screenNode.children("parameter")
                            for (node in parameterNodes) {
                                def paramName = node.attribute("name")
                                parameters[paramName] = [
                                    type: "string", 
                                    description: "Screen Parameter"
                                ]
                            }
                            
                            // Also extract transition parameters if possible
                            def transitionNodes = screenDef.screenNode.children("transition")
                            for (node in transitionNodes) {
                                // Transition parameters
                                def tParams = node.children("parameter")
                                for (tp in tParams) {
                                    def tpName = tp.attribute("name")
                                    if (!parameters[tpName]) {
                                        parameters[tpName] = [
                                            type: "string",
                                            description: "Transition Parameter for ${node.attribute('name')}"
                                        ]
                                    }
                                }
                            }
                        }
                        
                        toolDef = [
                            name: name,
                            description: "Full details for ${name} (${screenPath})",
                            inputSchema: [
                                type: "object",
                                properties: parameters
                            ]
                        ]
                    } catch (Exception e) {
                        ec.logger.warn("Error getting screen details for ${name}: ${e.message}")
                    }
                }
                
                result = [tool: toolDef]
            ]]></script>
        </actions>
    </service>

    <service verb="list" noun="Tools" authenticate="false" allow-remote="true" transaction-timeout="60">
        <description>List discovery tools and root apps.</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
                
                // Static list of Discovery Tools
                def tools = [
                    [
                        name: "moqui_browse_screens",
                        title: "Browse Screens",
                        description: "Browse the Moqui screen hierarchy. Use this to discover capabilities. Input 'path' (empty for root).",
                        inputSchema: [
                            type: "object",
                            properties: [
                                path: [type: "string", description: "Path to browse (e.g. 'moqui_PopCommerce')"]
                            ]
                        ]
                    ],
                    [
                        name: "moqui_search_screens",
                        title: "Search Screens",
                        description: "Search for screens/functionality by name.",
                        inputSchema: [
                            type: "object",
                            properties: [
                                query: [type: "string", description: "Search query"]
                            ],
                            required: ["query"]
                        ]
                    ],
                    [
                        name: "moqui_get_screen_details",
                        title: "Get Screen Details",
                        description: "Get input schema and details for a specific tool/screen.",
                        inputSchema: [
                            type: "object",
                            properties: [
                                name: [type: "string", description: "Tool name"]
                            ],
                            required: ["name"]
                        ]
                    ]
                ]
                
                // Add standard MCP methods
                def standardMcpMethods = [
                    [
                        name: "tools/list",
                        title: "List Available Tools",
                        description: "Get a list of all available MCP tools",
                        inputSchema: [type: "object", properties: [:], required: []]
                    ],
                    [
                        name: "tools/call",
                        title: "Execute Tool",
                        description: "Execute a specific MCP tool",
                        inputSchema: [
                            type: "object",
                            properties: [
                                name: [type: "string"],
                                arguments: [type: "object"]
                            ],
                            required: ["name"]
                        ]
                    ]
                ]
                
                tools.addAll(standardMcpMethods)
                
                result = [tools: tools]
            ]]></script>
        </actions>
    </service>

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

</services>