McpJsonRpcServices.xml 39.1 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
<?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 JSON-RPC 2.0 Handler -->
    
    <service verb="handle" noun="JsonRpcRequest" authenticate="true" allow-remote="true" transaction-timeout="300">
        <description>Handle MCP JSON-RPC 2.0 requests with direct Moqui integration (MCP 2025-06-18 compliant)</description>
        <in-parameters>
            <parameter name="jsonrpc" required="true"/>
            <parameter name="id"/>
            <parameter name="method"/>
            <parameter name="params" type="Map"/>
        </in-parameters>
        <out-parameters>
            <parameter name="response" type="text-very-long"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                import groovy.json.JsonBuilder
                import java.util.UUID
                
                ExecutionContext ec = context.ec
                
                // Validate HTTP method - only POST allowed for JSON-RPC messages
                def httpMethod = ec.web?.request?.method
                if (httpMethod != "POST") {
                    ec.web?.response?.setStatus(405) // Method Not Allowed
                    ec.web?.response?.setHeader("Allow", "POST")
                    response = "Method Not Allowed. Use POST for JSON-RPC messages."
                    return
                }
                
                // Validate Accept header - must include both application/json and text/event-stream
                def acceptHeader = ec.web?.request?.getHeader("Accept")
                if (!acceptHeader?.contains("application/json") || !acceptHeader?.contains("text/event-stream")) {
                    ec.web?.response?.setStatus(406) // Not Acceptable
                    response = "Accept header must include both application/json and text/event-stream"
                    return
                }
                
                // Validate Origin header for DNS rebinding protection
                def originHeader = ec.web?.request?.getHeader("Origin")
                if (originHeader) {
                    def originValid = ec.service.sync("mo-mcp.McpJsonRpcServices.isValidOrigin#Helper", [origin: originHeader, ec: ec]).isValid
                    if (!originValid) {
                        ec.web?.response?.setStatus(403) // Forbidden
                        response = "Invalid Origin header"
                        return
                    }
                }
                
                // Check if client wants streaming by looking at Accept header
                def wantsStreaming = acceptHeader?.contains("text/event-stream")
                
                // Detect request type: request (has method and id), notification (has method, no id), response (no method)
                def isNotification = (method != null && (id == null || id == ""))
                def isResponse = (method == null)
                def isRequest = (method != null && id != null && id != "")
                
                // Set protocol version header on all responses
                ec.web?.response?.setHeader("MCP-Protocol-Version", "2025-06-18")
                
                // Handle session management
                def sessionId = ec.web?.request?.getHeader("Mcp-Session-Id")
                def isInitialize = (method == "initialize")
                
                if (!isInitialize && !sessionId) {
                    ec.web?.response?.setStatus(400) // Bad Request
                    response = "Mcp-Session-Id header required for non-initialization requests"
                    return
                }
                
                // Validate JSON-RPC version
                if (jsonrpc != "2.0") {
                    def errorResponse = new JsonBuilder([
                        jsonrpc: "2.0",
                        error: [
                            code: -32600,
                            message: "Invalid Request: Only JSON-RPC 2.0 supported"
                        ],
                        id: id
                    ]).toString()
                    
                    if (wantsStreaming) {
                        response = "event: error\nid: ${UUID.randomUUID().toString()}\ndata: ${errorResponse}\n\n"
                        ec.web?.response?.setContentType("text/event-stream")
                        ec.web?.response?.setHeader("Cache-Control", "no-cache")
                        ec.web?.response?.setHeader("Connection", "keep-alive")
                    } else {
                        ec.web?.response?.setStatus(400) // Bad Request
                        response = errorResponse
                    }
                    return
                }
                
                def result = null
                def error = null
                def newSessionId = null
                
                try {
                    // Route to appropriate MCP method handler
                    switch (method) {
                        case "initialize":
                            result = handleInitialize(params, ec)
                            // Generate new session ID for initialization
                            newSessionId = UUID.randomUUID().toString()
                            ec.web?.response?.setHeader("Mcp-Session-Id", newSessionId)
                            break
                        case "tools/list":
                            result = handleToolsList(params, ec)
                            break
                        case "tools/call":
                            result = handleToolsCall(params, ec, wantsStreaming)
                            break
                        case "resources/list":
                            result = handleResourcesList(params, ec)
                            break
                        case "resources/read":
                            result = handleResourcesRead(params, ec, wantsStreaming)
                            break
                        case "ping":
                            result = handlePing(params, ec)
                            break
                        default:
                            if (method) {
                                error = [
                                    code: -32601,
                                    message: "Method not found: ${method}"
                                ]
                            } else {
                                // This is a response from client, just acknowledge
                                ec.web?.response?.setStatus(202) // Accepted
                                response = ""
                                return
                            }
                    }
                } catch (Exception e) {
                    ec.logger.error("MCP JSON-RPC error for method ${method}", e)
                    error = [
                        code: -32603,
                        message: "Internal error: ${e.message}"
                    ]
                }
                
                // Handle different request types according to MCP spec
                if (isNotification || isResponse) {
                    // For notifications and responses, return 202 Accepted
                    ec.web?.response?.setStatus(202)
                    response = ""
                    return
                }
                
                // For requests, build full JSON-RPC response
                def responseObj = [
                    jsonrpc: "2.0",
                    id: id
                ]
                
                if (error) {
                    responseObj.error = error
                    ec.web?.response?.setStatus(400) // Bad Request for errors
                } else {
                    responseObj.result = result
                }
                
                def jsonResponse = new JsonBuilder(responseObj).toString()
                def eventId = UUID.randomUUID().toString()
                
                if (wantsStreaming) {
                    // Return as Server-Sent Events with proper format
                    response = "event: response\nid: ${eventId}\ndata: ${jsonResponse}\n\n"
                    ec.web?.response?.setContentType("text/event-stream")
                    ec.web?.response?.setHeader("Cache-Control", "no-cache")
                    ec.web?.response?.setHeader("Connection", "keep-alive")
                    ec.web?.response?.setHeader("Access-Control-Allow-Origin", "*")
                    ec.web?.response?.setHeader("Access-Control-Allow-Headers", "Cache-Control, Mcp-Session-Id, MCP-Protocol-Version")
                } else {
                    response = jsonResponse
                    ec.web?.response?.setContentType("application/json")
                    ec.web?.response?.setHeader("Access-Control-Allow-Origin", "*")
                    ec.web?.response?.setHeader("Access-Control-Allow-Headers", "Cache-Control, Mcp-Session-Id, MCP-Protocol-Version")
                }
                
                // Log request for audit
                ec.message.addMessage("MCP ${method} request processed${wantsStreaming ? ' (streamed)' : ''}", "info")
            ]]></script>
        </actions>
    </service>

    <!-- Helper Functions for the main service -->
    
    <service verb="isValidOrigin" noun="Helper" authenticate="false" allow-remote="false">
        <description>Helper function to validate Origin header</description>
        <in-parameters>
            <parameter name="origin" required="true"/>
            <parameter name="ec" type="org.moqui.context.ExecutionContext" required="true"/>
        </in-parameters>
        <out-parameters>
            <parameter name="isValid" type="boolean"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                // 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>

    <!-- MCP Method Implementations -->
    
    <service verb="handle" noun="Initialize" authenticate="true" allow-remote="true" transaction-timeout="30">
        <description>Handle MCP initialize request with Moqui authentication</description>
        <in-parameters>
            <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 groovy.json.JsonBuilder
                
                ExecutionContext ec = context.ec
                
                // 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
                
                // Build server capabilities
                def serverCapabilities = [
                    tools: [:],
                    resources: [:],
                    logging: [:]
                ]
                
                // Build server info
                def serverInfo = [
                    name: "Moqui MCP Server",
                    version: "2.0.0"
                ]
                
                result = [
                    protocolVersion: "2025-06-18",
                    capabilities: serverCapabilities,
                    serverInfo: serverInfo,
                    instructions: "This server provides access to Moqui ERP services and entities through MCP. Use tools/list to discover available operations."
                ]
            ]]></script>
        </actions>
    </service>

    <service verb="handle" noun="ToolsList" authenticate="true" allow-remote="true" transaction-timeout="60">
        <description>Handle MCP tools/list request with direct Moqui service discovery</description>
        <in-parameters>
            <parameter name="cursor"/>
        </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
                
                // Get all service names from Moqui service engine
                def allServiceNames = ec.service.getServiceNames()
                def availableTools = []
                
                // Convert services to MCP tools
                for (serviceName in allServiceNames) {
                    try {
                        // Check if user has permission
                        if (!ec.service.hasPermission(serviceName)) {
                            continue
                        }
                        
                        def serviceInfo = ec.service.getServiceInfo(serviceName)
                        if (!serviceInfo) continue
                        
                        // Convert service to MCP tool format
                        def tool = [
                            name: serviceName,
                            description: serviceInfo.description ?: "Moqui service: ${serviceName}",
                            inputSchema: [
                                type: "object",
                                properties: [:],
                                required: []
                            ]
                        ]
                        
                        // Convert service parameters to JSON Schema
                        def inParamNames = serviceInfo.getInParameterNames()
                        for (paramName in inParamNames) {
                            def paramInfo = serviceInfo.getInParameter(paramName)
                            tool.inputSchema.properties[paramName] = [
                                type: ec.service.sync("mo-mcp.McpServices.convert#MoquiTypeToJsonSchemaType", [moquiType: paramInfo.type])?.jsonSchemaType ?: "string",
                                description: paramInfo.description ?: ""
                            ]
                            
                            if (paramInfo.required) {
                                tool.inputSchema.required << paramName
                            }
                        }
                        
                        availableTools << tool
                        
                    } catch (Exception e) {
                        ec.logger.warn("Error processing service ${serviceName}: ${e.message}")
                    }
                }
                
                result = [
                    tools: availableTools
                ]
                
                // Add pagination if needed
                if (availableTools.size() >= 100) {
                    result.nextCursor = UUID.randomUUID().toString()
                }
            ]]></script>
        </actions>
    </service>

    <service verb="handle" 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="name" required="true"/>
            <parameter name="arguments" type="Map"/>
        </in-parameters>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                import groovy.json.JsonBuilder
                
                ExecutionContext ec = context.ec
                
                // Validate service exists
                if (!ec.service.isServiceDefined(name)) {
                    throw new Exception("Tool not found: ${name}")
                }
                
                // Check permission
                if (!ec.service.hasPermission(name)) {
                    throw new Exception("Permission denied for tool: ${name}")
                }
                
                // Create audit record
                def artifactHit = ec.entity.makeValue("moqui.server.ArtifactHit")
                artifactHit.setSequencedIdPrimary()
                artifactHit.visitId = ec.web?.visitId
                artifactHit.userId = ec.user.userId
                artifactHit.artifactType = "MCP"
                artifactHit.artifactSubType = "Tool"
                artifactHit.artifactName = name
                artifactHit.parameterString = new JsonBuilder(arguments ?: [:]).toString()
                artifactHit.startDateTime = ec.user.now
                artifactHit.create()
                
                def startTime = System.currentTimeMillis()
                try {
                    if (wantsStreaming) {
                        // Streaming response for long-running operations
                        ec.web?.response?.setContentType("text/event-stream")
                        ec.web?.response?.setHeader("Cache-Control", "no-cache")
                        ec.web?.response?.setHeader("Connection", "keep-alive")
                        ec.web?.response?.setHeader("Access-Control-Allow-Origin", "*")
                        ec.web?.response?.setHeader("Access-Control-Allow-Headers", "Cache-Control, Mcp-Session-Id, MCP-Protocol-Version")
                        
                        // Send start event with proper SSE format
                        def startEvent = new JsonBuilder([
                            type: "start",
                            tool: name,
                            timestamp: ec.user.now
                        ]).toString()
                        def startEventId = UUID.randomUUID().toString()
                        ec.web?.response?.outputStream?.print("event: start\nid: ${startEventId}\ndata: ${startEvent}\n\n")
                        ec.web?.response?.outputStream?.flush()
                        
                        // Execute service
                        def serviceResult = ec.service.sync().name(name).parameters(arguments ?: [:]).call()
                        def executionTime = (System.currentTimeMillis() - startTime) / 1000.0
                        
                        // Send progress/result event with proper SSE format
                        def content = []
                        if (serviceResult) {
                            content << [
                                type: "text",
                                text: new JsonBuilder(serviceResult).toString()
                            ]
                        }
                        
                        def resultEvent = new JsonBuilder([
                            type: "result",
                            content: content,
                            isError: false,
                            executionTime: executionTime
                        ]).toString()
                        def resultEventId = UUID.randomUUID().toString()
                        ec.web?.response?.outputStream?.print("event: result\nid: ${resultEventId}\ndata: ${resultEvent}\n\n")
                        ec.web?.response?.outputStream?.flush()
                        
                        // Send completion event with proper SSE format
                        def completeEvent = new JsonBuilder([
                            type: "complete",
                            timestamp: ec.user.now
                        ]).toString()
                        def completeEventId = UUID.randomUUID().toString()
                        ec.web?.response?.outputStream?.print("event: complete\nid: ${completeEventId}\ndata: ${completeEvent}\n\n")
                        ec.web?.response?.outputStream?.flush()
                        
                        result = [streamed: true]
                        
                        // Update audit record
                        artifactHit.runningTimeMillis = executionTime
                        artifactHit.wasError = "N"
                        artifactHit.outputSize = new JsonBuilder(result).toString().length()
                        artifactHit.update()
                        
                    } else {
                        // Standard non-streaming response
                        def serviceResult = ec.service.sync().name(name).parameters(arguments ?: [:]).call()
                        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 = [
                            content: content,
                            isError: false
                        ]
                        
                        // Update audit record
                        artifactHit.runningTimeMillis = executionTime
                        artifactHit.wasError = "N"
                        artifactHit.outputSize = new JsonBuilder(result).toString().length()
                        artifactHit.update()
                    }
                    
                } catch (Exception e) {
                    def executionTime = (System.currentTimeMillis() - startTime) / 1000.0
                    
                    if (wantsStreaming) {
                        // Send error event with proper SSE format
                        def errorEvent = new JsonBuilder([
                            type: "error",
                            message: e.message,
                            tool: name
                        ]).toString()
                        def errorEventId = UUID.randomUUID().toString()
                        ec.web?.response?.outputStream?.print("event: error\nid: ${errorEventId}\ndata: ${errorEvent}\n\n")
                        ec.web?.response?.outputStream?.flush()
                        
                        result = [streamed: true, error: true]
                    } else {
                        result = [
                            content: [
                                [
                                    type: "text",
                                    text: "Error executing tool ${name}: ${e.message}"
                                ]
                            ],
                            isError: true
                        ]
                    }
                    
                    // Update audit record with error
                    artifactHit.runningTimeMillis = executionTime
                    artifactHit.wasError = "Y"
                    artifactHit.errorMessage = e.message
                    artifactHit.update()
                    
                    ec.logger.error("MCP tool execution error", e)
                }
            ]]></script>
        </actions>
    </service>

    <service verb="handle" noun="ResourcesList" authenticate="true" allow-remote="true" transaction-timeout="60">
        <description>Handle MCP resources/list request with Moqui entity discovery</description>
        <in-parameters>
            <parameter name="cursor"/>
        </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
                
                // Get all entity names from Moqui entity engine
                def allEntityNames = ec.entity.getEntityNames()
                def availableResources = []
                
                // Convert entities to MCP resources
                for (entityName in allEntityNames) {
                    try {
                        // Check if user has permission
                        if (!ec.user.hasPermission("entity:${entityName}", "VIEW")) {
                            continue
                        }
                        
                        def entityInfo = ec.entity.getEntityInfo(entityName)
                        if (!entityInfo) continue
                        
                        // Convert entity to MCP resource format
                        def resource = [
                            uri: "entity://${entityName}",
                            name: entityName,
                            description: "Moqui entity: ${entityName}",
                            mimeType: "application/json"
                        ]
                        
                        availableResources << resource
                        
                    } catch (Exception e) {
                        ec.logger.warn("Error processing entity ${entityName}: ${e.message}")
                    }
                }
                
                result = [
                    resources: availableResources
                ]
            ]]></script>
        </actions>
    </service>

    <service verb="handle" 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="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
                
                // Check if client wants streaming by looking at Accept header
                def acceptHeader = ec.web?.request?.getHeader("Accept")
                def wantsStreaming = acceptHeader?.contains("text/event-stream")
                
                // 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}")
                }
                
                // Check permission
                if (!ec.user.hasPermission("entity:${entityName}", "VIEW")) {
                    throw new Exception("Permission denied for entity: ${entityName}")
                }
                
                // Create audit record
                def artifactHit = ec.entity.makeValue("moqui.server.ArtifactHit")
                artifactHit.setSequencedIdPrimary()
                artifactHit.visitId = ec.web?.visitId
                artifactHit.userId = ec.user.userId
                artifactHit.artifactType = "MCP"
                artifactHit.artifactSubType = "Resource"
                artifactHit.artifactName = "resources/read"
                artifactHit.parameterString = uri
                artifactHit.startDateTime = ec.user.now
                artifactHit.create()
                
                def startTime = System.currentTimeMillis()
                try {
                    // Query entity data (limited to prevent large responses)
                    def entityList = ec.entity.find(entityName)
                        .limit(100)
                        .list()
                    
                    def executionTime = (System.currentTimeMillis() - startTime) / 1000.0
                    
                    // Convert to MCP resource content
                    def contents = [
                        [
                            uri: uri,
                            mimeType: "application/json",
                            text: new JsonBuilder([
                                entityName: entityName,
                                recordCount: entityList.size(),
                                data: entityList
                            ]).toString()
                        ]
                    ]
                    
                    result = [
                        contents: contents
                    ]
                    
                    // Update audit record
                    artifactHit.runningTimeMillis = executionTime
                    artifactHit.wasError = "N"
                    artifactHit.outputSize = new JsonBuilder(result).toString().length()
                    artifactHit.update()
                    
                } catch (Exception e) {
                    def executionTime = (System.currentTimeMillis() - startTime) / 1000.0
                    
                    // Update audit record with error
                    artifactHit.runningTimeMillis = executionTime
                    artifactHit.wasError = "Y"
                    artifactHit.errorMessage = e.message
                    artifactHit.update()
                    
                    throw new Exception("Error reading resource ${uri}: ${e.message}")
                }
            ]]></script>
        </actions>
    </service>

    <service verb="handle" noun="Ping" authenticate="true" allow-remote="true" transaction-timeout="10">
        <description>Handle MCP ping request for health check</description>
        <in-parameters/>
        <out-parameters>
            <parameter name="result" type="Map"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                result = [
                    timestamp: ec.user.now,
                    status: "healthy",
                    version: "2.0.0"
                ]
            ]]></script>
        </actions>
    </service>

    <!-- GET Method Support for SSE Streams -->
    
    <service verb="handle" noun="HttpGetRequest" authenticate="true" allow-remote="true" transaction-timeout="300">
        <description>Handle MCP HTTP GET requests for SSE streams (MCP 2025-06-18 compliant)</description>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                import groovy.json.JsonBuilder
                import java.util.UUID
                
                ExecutionContext ec = context.ec
                
                // Validate Accept header - must include text/event-stream
                def acceptHeader = ec.web?.request?.getHeader("Accept")
                if (!acceptHeader?.contains("text/event-stream")) {
                    ec.web?.response?.setStatus(406) // Not Acceptable
                    response = "Accept header must include text/event-stream for GET requests"
                    return
                }
                
                // Validate Origin header for DNS rebinding protection
                def originHeader = ec.web?.request?.getHeader("Origin")
                if (originHeader) {
                    def originValid = ec.service.sync("mo-mcp.McpJsonRpcServices.isValidOrigin#Helper", [origin: originHeader, ec: ec]).isValid
                    if (!originValid) {
                        ec.web?.response?.setStatus(403) // Forbidden
                        response = "Invalid Origin header"
                        return
                    }
                }
                
                // Set protocol version header
                ec.web?.response?.setHeader("MCP-Protocol-Version", "2025-06-18")
                
                // Handle session management
                def sessionId = ec.web?.request?.getHeader("Mcp-Session-Id")
                if (!sessionId) {
                    ec.web?.response?.setStatus(400) // Bad Request
                    response = "Mcp-Session-Id header required for GET requests"
                    return
                }
                
                // Set SSE headers
                ec.web?.response?.setContentType("text/event-stream")
                ec.web?.response?.setHeader("Cache-Control", "no-cache")
                ec.web?.response?.setHeader("Connection", "keep-alive")
                ec.web?.response?.setHeader("Access-Control-Allow-Origin", "*")
                ec.web?.response?.setHeader("Access-Control-Allow-Headers", "Cache-Control, Mcp-Session-Id, MCP-Protocol-Version")
                
                // Handle Last-Event-ID for resumability
                def lastEventId = ec.web?.request?.getHeader("Last-Event-ID")
                
                // Start SSE stream with a ping event
                def pingEvent = new JsonBuilder([
                    type: "ping",
                    timestamp: ec.user.now,
                    sessionId: sessionId
                ]).toString()
                
                def eventId = UUID.randomUUID().toString()
                response = "event: ping\nid: ${eventId}\ndata: ${pingEvent}\n\n"
                
                // In a real implementation, you would keep the stream open and send events
                // For now, we'll just send the initial ping and close
                ec.message.addMessage("MCP SSE stream opened for session ${sessionId}", "info")
            ]]></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
                
                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="true" allow-remote="true">
        <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>

</services>