McpServices.xml 17.5 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
<?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="protocolVersion" type="text-medium" required="true"/>
            <parameter name="capabilities" type="Map"/>
            <parameter name="clientInfo" type="Map"/>
        </in-parameters>
        <out-parameters>
            <parameter name="protocolVersion" type="text-medium"/>
            <parameter name="capabilities" type="Map"/>
            <parameter name="serverInfo" type="Map"/>
            <parameter name="instructions" type="text-long"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                import groovy.json.JsonBuilder
                
                ExecutionContext ec = context.ec
                
                // Validate protocol version
                if (protocolVersion != "2025-06-18") {
                    throw new Exception("Unsupported protocol version: ${protocolVersion}")
                }
                
                // Build server capabilities
                def serverCapabilities = [
                    tools: [:],
                    resources: [:],
                    logging: [:]
                ]
                
                // Build server info
                def serverInfo = [
                    name: "Moqui MCP Server",
                    version: "2.0.0"
                ]
                
                protocolVersion = "2025-06-18"
                capabilities = serverCapabilities
                instructions = "This server provides access to Moqui ERP services and entities through MCP. Use mcp#ToolsList to discover available operations."
            ]]></script>
        </actions>
    </service>

    <service verb="mcp" 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" type="text-medium"/>
        </in-parameters>
        <out-parameters>
            <parameter name="tools" type="List"/>
            <parameter name="nextCursor" type="text-medium"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                import org.moqui.context.ExecutionContext
                import groovy.json.JsonBuilder
                import java.util.UUID
                
                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: convertMoquiTypeToJsonSchemaType(paramInfo.type),
                                description: paramInfo.description ?: ""
                            ]
                            
                            if (paramInfo.required) {
                                tool.inputSchema.required << paramName
                            }
                        }
                        
                        availableTools << tool
                        
                    } catch (Exception e) {
                        ec.logger.warn("Error processing service ${serviceName}: ${e.message}")
                    }
                }
                
                tools = availableTools
                
                // Add pagination if needed
                if (availableTools.size() >= 100) {
                    nextCursor = UUID.randomUUID().toString()
                }
            ]]></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="name" type="text-medium" required="true"/>
            <parameter name="arguments" type="Map"/>
        </in-parameters>
        <out-parameters>
            <parameter name="content" type="List"/>
            <parameter name="isError" type="text-indicator"/>
        </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 {
                    // Execute service directly
                    def serviceResult = ec.service.sync(name, arguments ?: [:])
                    def executionTime = (System.currentTimeMillis() - startTime) / 1000.0
                    
                    // Convert result to MCP format
                    content = []
                    if (serviceResult) {
                        content << [
                            type: "text",
                            text: new JsonBuilder(serviceResult).toString()
                        ]
                    }
                    
                    isError = "N"
                    
                    // Update audit record
                    artifactHit.runningTimeMillis = executionTime
                    artifactHit.wasError = "N"
                    artifactHit.outputSize = new JsonBuilder([content: content, isError: isError]).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()
                    
                    content = [
                        [
                            type: "text",
                            text: "Error executing tool ${name}: ${e.message}"
                        ]
                    ]
                    
                    isError = "Y"
                    ec.logger.error("MCP tool execution error", e)
                }
            ]]></script>
        </actions>
    </service>

    <service verb="mcp" 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" type="text-medium"/>
        </in-parameters>
        <out-parameters>
            <parameter name="resources" type="List"/>
        </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}")
                    }
                }
                
                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="uri" type="text-medium" required="true"/>
        </in-parameters>
        <out-parameters>
            <parameter name="contents" type="List"/>
        </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}")
                }
                
                // 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
                    contents = [
                        [
                            uri: uri,
                            mimeType: "application/json",
                            text: new JsonBuilder([
                                entityName: entityName,
                                recordCount: entityList.size(),
                                data: entityList
                            ]).toString()
                        ]
                    ]
                    
                    // Update audit record
                    artifactHit.runningTimeMillis = executionTime
                    artifactHit.wasError = "N"
                    artifactHit.outputSize = new JsonBuilder(contents).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="mcp" 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="timestamp" type="date-time"/>
            <parameter name="status" type="text-short"/>
            <parameter name="version" type="text-medium"/>
        </out-parameters>
        <actions>
            <script><![CDATA[
                timestamp = ec.user.now
                status = "healthy"
                version = "2.0.0"
            ]]></script>
        </actions>
    </service>

    <!-- Helper Functions -->
    
    <service verb="convert" noun="MoquiTypeToJsonSchemaType" authenticate="false">
        <description>Convert Moqui data types to JSON Schema types</description>
        <in-parameters>
            <parameter name="moquiType" type="text-medium" required="true"/>
        </in-parameters>
        <out-parameters>
            <parameter name="jsonSchemaType" type="text-medium"/>
        </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>