McpServices.xml 69.9 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
<?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
                
                // Get Visit (session) created by servlet and validate access
                def visit = ec.entity.find("moqui.server.Visit")
                    .condition("visitId", sessionId)
                    .disableAuthz()
                    .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()
                    
                    visit.initialRequest = groovy.json.JsonOutput.toJson(metadata)
                    ec.artifactExecution.disableAuthz()
                    ec.logger.info("SESSIONID: ${sessionId}")
                    sessionId ? visit.update() : visit.store()
                    ec.artifactExecution.enableAuthz()
                } finally {
                    if (adminUserInfo != null) {
                        ec.user.popUser()
                    }
                }
                
                // Validate protocol version - support common MCP versions
                def supportedVersions = ["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
                
                // Get user-specific tools and resources in SAME transaction context
                def toolsResult = ec.service.sync().name("McpServices.mcp#ToolsList")
                    .parameters([sessionId: visit.visitId])
                    .requireNewTransaction(false)  // Use current transaction
                    .disableAuthz()  // Disable authz for internal call
                    .call()
                def resourcesResult = ec.service.sync().name("McpServices.mcp#ResourcesList")
                    .parameters([sessionId: visit.visitId])
                    .requireNewTransaction(false)  // Use current transaction
                    .disableAuthz()  // Disable authz for internal call
                    .call()
                
                // Build server capabilities based on what user can access
                def serverCapabilities = [
                    tools: toolsResult?.result?.tools ? [listChanged: true] : [:],
                    resources: resourcesResult?.result?.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,
                    instructions: "This server provides access to Moqui ERP services and entities through MCP. Tools and resources are filtered based on your permissions.",
                    sessionId: visit.visitId
                ]
                
                ec.logger.info("MCP Initialize for user ${userId} (session ${sessionId}): ${toolsResult?.result?.tools?.size() ?: 0} tools, ${resourcesResult?.result?.resources?.size() ?: 0} resources")
            ]]></script>
        </actions>
    </service>

    <service verb="mcp" noun="ToolsList" authenticate="false" allow-remote="true" transaction-timeout="60">
        <description>Handle MCP tools/list request with admin discovery but user permission filtering</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 java.util.UUID
                
                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
                
                // Validate session if provided
                /*
                if (sessionId) {
                    def visit = ec.entity.find("moqui.server.Visit")
                        .condition("visitId", sessionId)
                        .disableAuthz()
                        .one()
                    
                    if (!visit || visit.userId != ec.user.userId) {
                        //throw new Exception("Invalid session: ${sessionId}")
                    }
                }
                
                // Update session activity
                if (sessionId) {
                    def visitObj = ec.entity.find("moqui.server.Visit")
                        .condition("visitId", sessionId)
                        .disableAuthz()
                        .one()
                    
                    if (visitObj) {
                        def metadata = [:]
                        try {
                            metadata = groovy.json.JsonSlurper().parseText(visitObj.initialRequest ?: "{}") as Map
                        } catch (Exception e) {
                            ec.logger.debug("Failed to parse Visit metadata: ${e.message}")
                        }
                        
                        metadata.mcpLastActivity = System.currentTimeMillis()
                        metadata.mcpLastOperation = "tools/list"
                        
                        // Update Visit - need admin context for Visit updates
                        adminUserInfo = null
                        try {
                            adminUserInfo = ec.user.pushUser("ADMIN")
                            visitObj.initialRequest = groovy.json.JsonOutput.toJson(metadata)
                            ec.artifactExecution.disableAuthz()
                            visitObj.update()
                            ec.artifactExecution.enableAuthz()
                        } finally {
                            if (adminUserInfo != null) {
                                ec.user.popUser()
                            }
                        }
                    }
                }
                */
                
                // 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 }
                
                // Get user's accessible services using Moqui's optimized ArtifactAuthzCheckView
                def userAccessibleServices = 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_SERVICE")
                        .useCache(true)
                        .disableAuthz()
                        .list()
                    userAccessibleServices = aacvList.collect { it.artifactName } as Set<String>
                } finally {
                    if (adminUserInfo != null) {
                        ec.user.popUser()
                    }
                }
                
                // Helper function to check if user has permission to a service
                def userHasPermission = { serviceName ->
                    // Use pre-computed accessible services set for O(1) lookup
                    return userAccessibleServices != null && userAccessibleServices.contains(serviceName.toString())
                }
                
                try {
                    def availableTools = []
                    
                    // Get only services user has access to via artifact groups
                    def accessibleServiceNames = []
                    for (serviceName in userAccessibleServices) {
                        // Handle wildcard patterns like "McpServices.*"
                        if (serviceName.contains("*")) {
                            def pattern = serviceName.replace("*", ".*")
                            def allServiceNames = ec.service.getKnownServiceNames()
                            def matchingServices = allServiceNames.findAll { it.matches(pattern) }
                            // Only add services that actually exist
                            accessibleServiceNames.addAll(matchingServices.findAll { ec.service.isServiceDefined(it) })
                        } else {
                            // Only add if service actually exists
                            if (ec.service.isServiceDefined(serviceName)) {
                                accessibleServiceNames << serviceName
                            }
                        }
                    }
                    accessibleServiceNames = accessibleServiceNames.unique()
                    
                    ec.logger.info("MCP ToolsList: Found ${accessibleServiceNames.size()} accessible services for user ${originalUsername} (${originalUserId})${sessionId ? ' (session: ' + sessionId + ')' : ''}")
                    
                    // Helper function to convert service to MCP tool
                    def convertServiceToTool = { serviceName ->
                        try {
                            def serviceDefinition = ec.service.getServiceDefinition(serviceName)
                            if (!serviceDefinition) return null
                            
                            def serviceNode = serviceDefinition.serviceNode
                            
                            // Convert service to MCP tool format
                            def tool = [
                                name: serviceName,
                                title: serviceNode.first("description")?.text ?: serviceName,
                                description: serviceNode.first("description")?.text ?: "Moqui service: ${serviceName}",
                                inputSchema: [
                                    type: "object",
                                    properties: [:],
                                    required: []
                                ]
                            ]
                            
                            // Add service metadata to help LLM
                            if (serviceDefinition.verb && serviceDefinition.noun) {
                                tool.description += " (${serviceDefinition.verb}:${serviceDefinition.noun})"
                            }
                            
                            // Convert service parameters to JSON Schema
                            def inParamNames = serviceDefinition.getInParameterNames()
                            for (paramName in inParamNames) {
                                def paramNode = serviceDefinition.getInParameter(paramName)
                                def paramDesc = paramNode.first("description")?.text ?: ""
                                
                                // Add type information to description for LLM
                                def paramType = paramNode?.attribute('type') ?: 'String'
                                if (!paramDesc) {
                                    paramDesc = "Parameter of type ${paramType}"
                                } else {
                                    paramDesc += " (type: ${paramType})"
                                }
                                
                                // Convert Moqui type to JSON Schema type
                                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"
                                ]
                                def jsonSchemaType = typeMap[paramType] ?: "string"
                                
                                tool.inputSchema.properties[paramName] = [
                                    type: jsonSchemaType,
                                    description: paramDesc
                                ]
                                
                                if (paramNode?.attribute('required') == "true") {
                                    tool.inputSchema.required << paramName
                                }
                            }
                            
                            return tool
                        } catch (Exception e) {
                            ec.logger.warn("Error converting service ${serviceName} to tool: ${e.message}")
                            return null
                        }
                    }
                    
                    // Add all accessible services as tools
                    for (serviceName in accessibleServiceNames) {
                        def tool = convertServiceToTool(serviceName)
                        if (tool) {
                            availableTools << tool
                        }
                    }
                    
                    // Add screen-based tools
                    try {
                        def screenToolsResult = ec.service.sync().name("McpServices.discover#ScreensAsMcpTools")
                            .parameters([sessionId: sessionId])
                            .requireNewTransaction(false)  // Use current transaction
                            .call()
                        
                        if (screenToolsResult?.tools) {
                            availableTools.addAll(screenToolsResult.tools)
                            ec.logger.info("MCP ToolsList: Added ${screenToolsResult.tools.size()} screen-based tools")
                        }
                    } catch (Exception e) {
                        ec.logger.warn("Error discovering screen tools: ${e.message}")
                    }
                    
                // Implement pagination according to MCP spec
                def pageSize = 50  // Reasonable page size for tool lists
                def startIndex = 0
                
                if (cursor) {
                    try {
                        // Parse cursor to get start index (simple approach: cursor is the start index)
                        startIndex = Integer.parseInt(cursor)
                    } catch (Exception e) {
                        ec.logger.warn("Invalid cursor format: ${cursor}, starting from beginning")
                        startIndex = 0
                    }
                }
                
                // Get paginated subset of tools
                def endIndex = Math.min(startIndex + pageSize, availableTools.size())
                def paginatedTools = availableTools.subList(startIndex, endIndex)
                
                result = [tools: paginatedTools]
                
                // Add nextCursor if there are more tools
                if (endIndex < availableTools.size()) {
                    result.nextCursor = String.valueOf(endIndex)
                }
                    
                    ec.logger.info("MCP ToolsList: Returning ${availableTools.size()} tools for user ${originalUsername}")
                    
                } finally {
                    // Always restore original user context
                    if (adminUserInfo != null) {
                        ec.user.popUser()
                    }
                }
            ]]></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()
                
                // Check if this is a screen-based tool or a service-based tool
                def isScreenTool = name.startsWith("screen_")
                
                if (isScreenTool) {
                    // For screen tools, we need to extract the original screen path from the tool description
                    // The tool name is encoded but the description contains the original path
                    def toolName = name.substring(7)  // Remove "screen_" prefix
                    
                    // Find the tool in our available tools to get the original screen path from description
                    def originalScreenPath = null
                    def toolsResult = ec.service.sync().name("McpServices.mcp#ToolsList")
                        .parameters([sessionId: sessionId])
                        .disableAuthz()
                        .call()
                    
                    // The internal service call returns tools list directly, not wrapped in MCP format
                    if (toolsResult?.result?.tools) {
                        def matchingTool = toolsResult.result.tools.find { it.name == name }
                        if (matchingTool?.description?.startsWith("Moqui screen: ")) {
                            originalScreenPath = matchingTool.description.substring("Moqui screen: ".length())
                        }
                    }
                    
                    def screenPath = originalScreenPath
                    
                    // If we couldn't find the original path, try the old method as fallback
                    if (!screenPath) {
                        screenPath = toolName.replace('_', '/').replace('component///', 'component://').replace('/xml','.xml')
                        ec.logger.warn("Could not find original screen path for tool ${name}, using fallback reconstruction: ${screenPath}")
                    } else {
                        ec.logger.info("Found original screen path for tool ${name}: ${screenPath}")
                    }
                    
                    /*
                    // Map common screen patterns to actual screen locations
                    if (screenPath.startsWith("OrderFind") || screenPath.startsWith("ProductFind") || screenPath.startsWith("PartyFind")) {
                        // For find screens, try to use appropriate component screens
                        if (screenPath.startsWith("Order")) {
                            screenPath = "webroot/apps/order"  // Try to map to order app
                        } else if (screenPath.startsWith("Product")) {
                            screenPath = "webroot/apps/product"  // Try to map to product app  
                        } else if (screenPath.startsWith("Party")) {
                            screenPath = "webroot/apps/party"  // Try to map to party app
                        }
                    } else if (screenPath == "apps") {
                        screenPath = "component://webroot/screen/webroot.xml"  // Use full component path to webroot screen
                    }
                    */

                    // Restore user context from sessionId before calling screen tool
                    def serviceResult = null
                    def visit = null
                    UserInfo restoredUserInfo = null
                    try {
                        // Get Visit to find the actual user who created this session
                        visit = ec.entity.find("moqui.server.Visit")
                            .condition("visitId", sessionId)
                            .disableAuthz()
                            .one()
                        
                        if (!visit) {
                            throw new Exception("Invalid session for screen tool execution: ${sessionId}")
                        }
                        
                        // Restore user context - handle special MCP case where Visit was created with ADMIN
                        if (visit.userId && visit.userId != ec.user.userId) {
                            // Restore the actual user who created the session
                            def userAccount = ec.entity.find("moqui.security.UserAccount")
                                .condition("userId", visit.userId)
                                .disableAuthz()
                                .one()
                            if (userAccount) {
                                restoredUserInfo = ec.user.pushUser(userAccount.username)
                                ec.logger.info("Screen tool execution: Restored user context for ${userAccount.username}")
                            }
                        }
                        
                        // Now call the screen tool with proper user context
                        serviceResult = ec.service.sync().name("McpServices.execute#ScreenAsMcpTool")
                            .parameters([screenPath: screenPath, parameters: arguments ?: [:], renderMode: "json"])
                            .call()
                            
                    } finally {
                        // Always restore original user context
                        if (restoredUserInfo != null) {
                            ec.user.popUser()
                            ec.logger.info("Screen tool execution: Restored original user context ${ec.user.username}")
                        }
                    }
                    
                    def executionTime = (System.currentTimeMillis() - startTime) / 1000.0
                    
                    // Convert result to MCP format
                    def content = []
                    
                    if (serviceResult?.result) {
                        // Handle screen execution result which has type, text, screenPath, screenUrl, executionTime
                        if (serviceResult.result.type == "text" && serviceResult.result.text) {
                            content << [
                                type: "text", 
                                text: serviceResult.result.text
                            ]
                        } else {
                            content << [
                                type: "text", 
                                text: serviceResult.result.toString() ?: "Screen executed successfully"
                            ]
                        }
                    }
                    
                    result.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
                
                // Timing already started above
                
                // Validate session if provided
                /*
                if (sessionId) {
                    def visit = null
                    adminUserInfo = null
                    try {
                        adminUserInfo = ec.user.pushUser("ADMIN")
                        visit = ec.entity.find("moqui.server.Visit")
                            .condition("visitId", sessionId)
                            .one()
                    } finally {
                        if (adminUserInfo != null) {
                                ec.user.popUser()
                            }
                    }
                    
                    // Validate session - allow special MCP case where Visit was created with ADMIN but accessed by MCP_USER or MCP_BUSINESS
                    boolean sessionValid = false
                    if (visit) {
                        if (visit.userId == ec.user.userId) {
                            sessionValid = true
                        } else if (visit.userId == "ADMIN" && (ec.user.username == "mcp-user" || ec.user.username == "mcp-business")) {
                            // Special MCP case: Visit created with ADMIN for privileged access but accessed by MCP users
                            sessionValid = true
                        }
                    }
                    
                    if (!sessionValid) {
                        //throw new Exception("Invalid session: ${sessionId}")
                    }
                }
                */
                
                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()
                            }
                    }
                    def executionTime = (System.currentTimeMillis() - startTime) / 1000.0
                    
                    // Convert result to MCP format
                    def content = []
                    if (serviceResult) {
                        content << [
                            type: "text",
                            text: new JsonBuilder(serviceResult).toString()
                        ]
                    }
                    
                    result.result = [
                        content: content,
                        isError: false
                    ]
                } catch (Exception e) {
                    def 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()
                    }
                }
            ]]></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
                
                // Update session activity
                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}")
                }
                    
                // 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.info("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.info("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
                
                // Parse entity URI (format: entity://EntityName)
                if (!uri.startsWith("entity://")) {
                    throw new Exception("Invalid resource URI: ${uri}")
                }
                
                def entityName = uri.substring(9) // Remove "entity://" prefix
                
                // Validate entity exists
                if (!ec.entity.isEntityDefined(entityName)) {
                    throw new Exception("Entity not found: ${entityName}")
                }
                
                // Permission checking is handled by Moqui's artifact authorization system through artifact groups
                
try {
                 // Try to get entity definition - handle both real entities and view entities
                      def entityDef = null
                      try {
                          // First try getAllEntityInfo for detailed info
                          def entityInfoList = ec.entity.getAllEntityInfo(-1, true) // all entities, include view entities
                          entityDef = entityInfoList.find { it.entityName == entityName }
                          
                          if (!entityDef) {
                              // If not found in detailed list, try basic entity check
                              if (ec.entity.isEntityDefined(entityName)) {
                                  // Create minimal entity definition for basic query
                                  entityDef = [
                                      entityName: entityName,
                                      packageName: entityName.split('\\.')[0],
                                      description: "Entity: ${entityName}",
                                      isViewEntity: entityName.contains('View'),
                                      allFieldInfoList: []
                                  ]
                              }
                          }
                      } catch (Exception e) {
                          ec.logger.warn("ResourcesRead: Error getting entity info for ${entityName}: ${e.message}")
                          // Fallback: try basic entity check
                          if (ec.entity.isEntityDefined(entityName)) {
                              entityDef = [
                                  entityName: entityName,
                                  packageName: entityName.split('\\.')[0],
                                  description: "Entity: ${entityName}",
                                  isViewEntity: entityName.contains('View'),
                                  allFieldInfoList: []
                              ]
                          }
                      }
                      
                      if (!entityDef) {
                          throw new Exception("Entity not found: ${entityName}")
                      }
                      
                      ec.logger.info("ResourcesRead: Found entity ${entityName}, isViewEntity=${entityDef.isViewEntity}")
                     
                     // Query entity data (limited to prevent large responses)
                     def entityList = ec.entity.find(entityName)
                         .limit(100)
                         .list()
                     
                     def executionTime = (System.currentTimeMillis() - startTime) / 1000.0
                     
                     // Build field info for LLM
                     def fieldInfo = []
                     entityDef.allFieldInfoList.each { field ->
                         fieldInfo << [
                             name: field.name,
                             type: field.type,
                             description: field.description ?: "",
                             isPk: field.isPk,
                             required: field.notNull
                         ]
                     }
                     
                     // Convert to MCP resource content
                     def contents = [
                         [
                             uri: uri,
                             mimeType: "application/json",
                             text: new JsonBuilder([
                                 entityName: entityName,
                                 description: entityDef.description ?: "",
                                 packageName: entityDef.packageName,
                                 recordCount: entityList.size(),
                                 fields: fieldInfo,
                                 data: entityList
                             ]).toString()
                         ]
                     ]
                     
                     result = [contents: contents]
                     
                 } catch (Exception e) {
                      def executionTime = (System.currentTimeMillis() - startTime) / 1000.0
                      ec.logger.warn("Error reading resource ${uri}: ${e.message}")
                      result = [error: "Error reading resource ${uri}: ${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[
                result = [
                    timestamp: ec.user.getNowTimestamp(),
                    status: "healthy",
                    version: "2.0.2",
                    sessionId: sessionId,
                    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="list" noun="Products" authenticate="true" allow-remote="true" transaction-timeout="30">
        <description>List products with basic information for MCP business toolkit</description>
        <in-parameters>
            <parameter name="productCategoryId" required="false"/>
            <parameter name="ownerPartyId" required="false"/>
            <parameter name="pageSize" type="Integer" default="20"/>
            <parameter name="pageIndex" type="Integer" default="0"/>
        </in-parameters>
        <out-parameters>
            <parameter name="products" type="List"/>
            <parameter name="totalCount" type="Integer"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                import org.moqui.impl.context.UserFacadeImpl.UserInfo
                
                ExecutionContext ec = context.ec
                
                def entityFind = ec.entity.find("mantle.product.Product")
                
                // Apply filters if provided
                if (productCategoryId) {
                    entityFind.condition("productCategoryId", productCategoryId)
                }
                if (ownerPartyId) {
                    entityFind.condition("ownerPartyId", ownerPartyId)
                }
                
                // Get total count
                totalCount = entityFind.count()
                
                // Apply pagination
                entityFind.orderBy("productName").limit(pageSize).offset(pageIndex * pageSize)
                
                // Get product list with basic fields
                products = entityFind.selectFields(["productId", "productName", "description", "productTypeId", 
                                                   "productCategoryId", "ownerPartyId", "internalName"]).list()
                
            ]]></script>
        </actions>
    </service>

    <!-- Screen-based MCP Services -->
    
    <service verb="discover" noun="ScreensAsMcpTools" authenticate="false" allow-remote="true" transaction-timeout="60">
        <description>Discover screens accessible to user and convert them to MCP tools</description>
        <in-parameters>
            <parameter name="sessionId"/>
            <parameter name="screenPathPattern" required="false"><description>Optional pattern to filter screen paths (supports wildcards)</description></parameter>
        </in-parameters>
        <out-parameters>
            <parameter name="tools" type="List"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                import org.moqui.impl.context.UserFacadeImpl.UserInfo
                import org.moqui.impl.screen.ScreenDefinition
                
                ExecutionContext ec = context.ec
                
                ec.logger.info("=== SCREEN DISCOVERY SERVICE CALLED ===")
                
                def originalUsername = ec.user.username
                def originalUserId = ec.user.userId
                def userGroups = ec.user.getUserGroupIdSet().collect { it }
                
                ec.logger.info("MCP Screen Discovery: Starting for user ${originalUsername} (${originalUserId}) with groups ${userGroups}")
                
                def tools = []
                
// Discover screens that user can actually access
                def accessibleScreens = [] as Set<String>
                adminUserInfo = null
                try {
                    adminUserInfo = ec.user.pushUser("ADMIN")
                    
                    // Get all user's accessible screens using ArtifactAuthzCheckView
                    def aacvList = ec.entity.find("moqui.security.ArtifactAuthzCheckView")
                        .condition("userGroupId", userGroups)
                        .condition("artifactTypeEnumId", "AT_XML_SCREEN")
                        .useCache(true)
                        .disableAuthz()
                        .list()
                    accessibleScreens = aacvList.collect { it.artifactName } as Set<String>
                    
                    ec.logger.info("MCP Screen Discovery: Found ${accessibleScreens.size()} accessible screens for user ${originalUsername}")
                    
                } finally {
                    if (adminUserInfo != null) {
                        ec.user.popUser()
                    }
                }
                
                // Helper function to check if user has permission to a screen
                def userHasScreenPermission = { screenName ->
                    return accessibleScreens.contains(screenName.toString())
                }
                
                // Helper function to convert screen path to MCP tool name
                def screenPathToToolName = { screenPath ->
                    // Create a safe tool name but we'll store the original path in description
                    return "screen_" + screenPath.replaceAll("[^a-zA-Z0-9]", "_")
                }
                
                // Helper function to create MCP tool from screen
                def createScreenTool = { screenPath, title, description, parameters = [:] ->
                    def toolName = screenPathToToolName(screenPath)
                    return [
                        name: toolName,
                        title: title,
                        description: "Moqui screen: ${screenPath}",  // Store original path in description
                        inputSchema: [
                            type: "object",
                            properties: parameters,
                            required: []
                        ]
                    ]
                }
                
                // Use discovered screens instead of hardcoded list
                for (screenPath in accessibleScreens) {
                    try {
                        ec.logger.info("MCP Screen Discovery: Processing screen ${screenPath}")
                        
                        // For MCP, include all accessible screens - LLMs can decide what's useful
                        // Skip only obviously problematic patterns
                        if (screenPath.contains("/error/") || screenPath.contains("/system/")) {
                            ec.logger.info("MCP Screen Discovery: Skipping system screen ${screenPath}")
                            continue
                        }
                        
                        // Try to get screen definition, but don't require it for MCP
                        def screenDefinition = null
                        def title = screenPath.split("/")[-1]
                        def description = "Moqui screen: ${screenPath}"
                        
                        try {
                            screenDefinition = ec.screen.getScreenDefinition(screenPath)
                            if (screenDefinition?.screenNode?.first("description")?.text) {
                                title = screenDefinition.screenNode.first("description").text
                                description = screenDefinition.screenNode.first("description").text
                            }
                        } catch (Exception e) {
                            ec.logger.info("MCP Screen Discovery: No screen definition for ${screenPath}, using basic info")
                            // Continue anyway - the screen might still be useful for MCP
                        }
                        
                        // Get screen parameters from transitions
                        def parameters = [:]
                        try {
                            def screenInfo = ec.screen.getScreenInfo(screenPath)
                            if (screenInfo?.transitionInfoByName) {
                                for (transitionEntry in screenInfo.transitionInfoByName) {
                                    def transitionInfo = transitionEntry.value
                                    // Add path parameters
                                    transitionInfo.ti?.getPathParameterList()?.each { param ->
                                        parameters[param] = [
                                            type: "string",
                                            description: "Path parameter for transition: ${param}"
                                        ]
                                    }
                                    // Add request parameters
                                    transitionInfo.ti?.getRequestParameterList()?.each { param ->
                                        parameters[param.name] = [
                                            type: "string",
                                            description: "Request parameter: ${param.name}"
                                        ]
                                    }
                                }
                            }
                        } catch (Exception e) {
                            ec.logger.debug("Could not extract parameters from screen ${screenPath}: ${e.message}")
                        }
                        
                        ec.logger.info("MCP Screen Discovery: Adding accessible screen ${screenPath}")
                        tools << createScreenTool(screenPath, title, description, parameters)
                        
                    } catch (Exception e) {
                        ec.logger.warn("Error processing screen ${screenPath}: ${e.message}")
                    }
                }
                
                ec.logger.info("MCP Screen Discovery: Created ${tools.size()} hardcoded screen tools for user ${originalUsername}")
                
                result.tools = tools
                
            ]]></script>
        </actions>
    </service>
    

    
    <service verb="convert" noun="ScreenToMcpTool" authenticate="false">
        <description>Convert a screen path to MCP tool format</description>
        <in-parameters>
            <parameter name="screenPath" required="true"/>
        </in-parameters>
        <out-parameters>
            <parameter name="tool" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                
                ExecutionContext ec = context.ec
                
                ec.logger.info("=== SCREEN TO MCP TOOL: ${screenPath} ===")
                
                tool = null
                try {
                    // Try to get screen definition
                    def screenDef = null
                    try {
                        ec.logger.info("SCREEN TO MCP: Getting screen definition for ${screenPath}")
                        screenDef = ec.screen.getScreenDefinition(screenPath)
                        ec.logger.info("SCREEN TO MCP: Got screen definition: ${screenDef ? 'YES' : 'NO'}")
                    } catch (Exception e) {
                        ec.logger.warn("SCREEN TO MCP: Error getting screen definition: ${e.message}")
                        // Screen might not exist or be accessible
                        return
                    }
                    
                    if (!screenDef) {
                        return
                    }
                    
                    // Extract screen information
                    def screenName = screenPath.replaceAll("[^a-zA-Z0-9]", "_")
                    def title = screenDef.getScreenName() ?: screenPath.split("/")[-1]
                    def description = screenDef.getDescription() ?: "Moqui screen: ${screenPath}"
                    
                    // Get screen parameters from transitions and forms
                    def parameters = [:]
                    def required = []
                    
                    try {
                        // Get transitions for parameter discovery
                        def transitions = screenDef.getTransitionMap()
                        transitions.each { transitionName, transition ->
                            transition.getPathParameterList().each { param ->
                                parameters[param] = [
                                    type: "string",
                                    description: "Path parameter: ${param}"
                                ]
                                required << param
                            }
                            
                            // Get single service parameters if transition calls a service
                            def serviceName = transition.getSingleServiceName()
                            if (serviceName) {
                                try {
                                    def serviceDef = ec.service.getServiceDefinition(serviceName)
                                    if (serviceDef) {
                                        def inParamNames = serviceDef.getInParameterNames()
                                        for (paramName in inParamNames) {
                                            def paramNode = serviceDef.getInParameter(paramName)
                                            def paramType = paramNode?.attribute('type') ?: 'String'
                                            def paramDesc = paramNode.first("description")?.text ?: "Parameter from service ${serviceName}"
                                            
                                            // Convert Moqui type to JSON Schema type
                                            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"
                                            ]
                                            def jsonSchemaType = typeMap[paramType] ?: "string"
                                            
                                            parameters[paramName] = [
                                                type: jsonSchemaType,
                                                description: paramDesc
                                            ]
                                            
                                            if (paramNode?.attribute('required') == "true") {
                                                required << paramName
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    ec.logger.debug("Error getting service definition for ${serviceName}: ${e.message}")
                                }
                            }
                        }
                    } catch (Exception e) {
                        ec.logger.debug("Error getting transitions for screen ${screenPath}: ${e.message}")
                    }
                    
                    // Build MCP tool
                    tool = [
                        name: "screen_${screenName}",
                        title: title,
                        description: "${description}. This tool renders the Moqui screen '${screenPath}' and returns the output.",
                        inputSchema: [
                            type: "object",
                            properties: parameters,
                            required: required.unique()
                        ]
                    ]
                    
                    // Add screen metadata
                    tool.screenPath = screenPath
                    tool.toolType = "screen"
                    
                    // Add screen structure metadata
                    try {
                        def screenInfo = ec.screen.getScreenInfo(screenPath)
                        if (screenInfo) {
                            tool.screenInfo = [
                                name: screenInfo.name,
                                level: screenInfo.level,
                                hasTransitions: screenInfo.transitions > 0,
                                hasForms: screenInfo.forms > 0,
                                subscreens: screenInfo.subscreens
                            ]
                        }
                    } catch (Exception e) {
                        ec.logger.debug("Could not get screen info for metadata: ${e.message}")
                    }
                    
                } catch (Exception e) {
                    ec.logger.warn("Error converting screen ${screenPath} to MCP tool: ${e.message}")
                }
            ]]></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="json"><description>Render mode: json, text, csv, xml</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()
                try {
                    // 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}"
                    
                    try {
                        ec.logger.info("MCP Screen Execution: Attempting to render screen ${screenPath}")
                        
                        // Try to render screen with specified render mode for LLM to read
                        def screenRender = ec.screen.makeRender()
                            .rootScreen(screenPath)  // Set root screen location
                            .renderMode(renderMode)  // Set render mode from parameter, but don't set additional path for root screen
                        
                        // Mock sri.sendRedirectAndStopRender() to prevent redirects in MCP context
                        // We want screen content, not redirects to other pages
                        def mockSri = [
                            sendRedirectAndStopRender: { String redirectUrl ->
                                ec.logger.info("MCP Screen Execution: Ignoring redirect to ${redirectUrl} - continuing screen render for MCP")
                                // Don't actually redirect, just log and continue
                            }
                        ]
                        ec.context.put("sri", mockSri)
                        
                        ec.logger.info("MCP Screen Execution: ScreenRender object created: ${screenRender?.getClass()?.getSimpleName()}")
                        
                        if (screenRender) {
                            output = screenRender.render()
                            ec.logger.info("MCP Screen Execution: Successfully rendered screen ${screenPath}, output length: ${output?.length() ?: 0}")
                        } else {
                            throw new Exception("ScreenRender object is null")
                        }
                        
                    } catch (Exception e) {
                        ec.logger.warn("MCP Screen Execution: Could not render screen ${screenPath}, falling back to URL: ${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)
                        
                        // Fallback to URL if rendering fails
                        output = "Screen '${screenPath}' is accessible at: ${screenUrl}\n\nNote: Screen content could not be rendered. You can visit this URL in a web browser to interact with the screen directly."
                    }
                    
                    def executionTime = (System.currentTimeMillis() - startTime) / 1000.0
                    
                    // Return just the rendered screen content for MCP wrapper to handle
                    result = [
                        type: "text",
                        text: output,
                        screenPath: screenPath,
                        screenUrl: screenUrl,
                        executionTime: executionTime
                    ]
                    
                    ec.logger.info("MCP Screen Execution: Generated URL for screen ${screenPath} in ${executionTime}s")
                    
                } catch (Exception e) {
                    def executionTime = (System.currentTimeMillis() - startTime) / 1000.0
                    
                    result = [
                        content: [
                            [
                                type: "text", 
                                text: "Error executing screen ${screenPath}: ${e.message}"
                            ]
                        ],
                        isError: true,
                        metadata: [
                            screenPath: screenPath,
                            renderMode: renderMode,
                            executionTime: executionTime
                        ]
                    ]
                    
                    ec.logger.error("MCP Screen Execution error for ${screenPath}", e)
                }
            ]]></script>
        </actions>
    </service>

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

</services>