McpServices.xml
33.7 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
<?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="discover" noun="McpTools" authenticate="false" allow-remote="true" transaction-timeout="30">
<description>Discover available MCP tools (services) with admin permissions</description>
<out-parameters>
<parameter name="tools" type="List"/>
</out-parameters>
<actions>
<script><![CDATA[
import org.moqui.context.ExecutionContext
import groovy.json.JsonBuilder
ExecutionContext ec = context.ec
// Run as admin to discover all available services
def originalUser = ec.user.username
try {
ec.user.internalLoginUser("admin", null)
def tools = []
// Get commonly used entity services
def entityServices = [
"org.moqui.entity.EntityServices.find#List",
"org.moqui.entity.EntityServices.find#One",
"org.moqui.entity.EntityServices.count",
"org.moqui.entity.EntityServices.create",
"org.moqui.entity.EntityServices.update",
"org.moqui.entity.EntityServices.delete"
]
for (serviceName in entityServices) {
try {
def serviceDef = ec.service.getServiceDefinition(serviceName)
if (serviceDef) {
tools << [
name: serviceName,
description: "Entity operation: ${serviceName}",
inputSchema: [
type: "object",
properties: [
entityName: [type: "string", description: "Name of the entity"],
conditions: [type: "object", description: "Query conditions (for find operations)"],
fields: [type: "array", description: "Fields to return (optional)"]
],
required: ["entityName"]
]
]
}
} catch (Exception e) {
// Skip services that don't exist or aren't accessible
}
}
// Add some basic services
def basicServices = [
"org.moqui.impl.ServiceServices.ping#Service"
]
for (serviceName in basicServices) {
try {
def serviceDef = ec.service.getServiceDefinition(serviceName)
if (serviceDef) {
tools << [
name: serviceName,
description: "System service: ${serviceName}",
inputSchema: [type: "object", properties: [:], required: []]
]
}
} catch (Exception e) {
// Skip services that don't exist
}
}
result.tools = tools
} finally {
// Restore original user context
if (originalUser) {
ec.user.internalLoginUser(originalUser, null)
}
}
]]></script>
</actions>
</service>
<service verb="discover" noun="McpResources" authenticate="false" allow-remote="true" transaction-timeout="30">
<description>Discover available MCP resources (entities) with admin permissions</description>
<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
// Run as admin to discover all available entities
def originalUser = ec.user.username
try {
ec.user.internalLoginUser("admin", null)
def resources = []
def entityNames = []
// Get all entity names
def allEntityNames = ec.entity.getAllEntityNames()
// Filter to commonly used entities for demonstration
def commonEntities = [
"moqui.basic.Enumeration",
"moqui.basic.Geo",
"moqui.security.UserAccount",
"moqui.security.UserGroup",
"moqui.security.ArtifactAuthz",
"moqui.example.Example",
"moqui.example.ExampleItem",
"mantle.account.Customer",
"mantle.product.Product",
"mantle.product.Category",
"mantle.ledger.transaction.AcctgTransaction",
"mantle.ledger.transaction.AcctgTransEntry"
]
for (entityName in commonEntities) {
if (allEntityNames.contains(entityName)) {
resources << [
uri: "entity://${entityName}",
name: entityName,
description: "Moqui entity: ${entityName}",
mimeType: "application/json"
]
}
}
result.resources = resources
} finally {
// Restore original user context
if (originalUser) {
ec.user.internalLoginUser(originalUser, null)
}
}
]]></script>
</actions>
</service>
<service verb="execute" noun="McpTool" authenticate="false" allow-remote="true" transaction-timeout="30">
<description>Execute an MCP tool (service) with elevated permissions</description>
<in-parameters>
<parameter name="toolName" type="text-long" 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
ExecutionContext ec = context.ec
// Run as admin to execute services that may require elevated permissions
def originalUser = ec.user.username
try {
ec.user.internalLoginUser("admin", null)
def serviceResult = null
// Handle common entity operations
if (toolName == "org.moqui.entity.EntityServices.count") {
def entityName = arguments?.entityName
def conditions = arguments?.conditions ?: [:]
if (!entityName) {
throw new Exception("entityName is required for count operation")
}
def count = ec.entity.find(entityName).condition(conditions).count()
serviceResult = [count: count]
} else if (toolName == "org.moqui.entity.EntityServices.find#List") {
def entityName = arguments?.entityName
def conditions = arguments?.conditions ?: [:]
def fields = arguments?.fields
def limit = arguments?.limit
def offset = arguments?.offset
if (!entityName) {
throw new Exception("entityName is required for find operation")
}
def entityFind = ec.entity.find(entityName).condition(conditions)
if (fields) entityFind.selectFields(fields)
if (limit) entityFind.limit(limit)
if (offset) entityFind.offset(offset)
def list = entityFind.list()
serviceResult = [list: list, count: list.size()]
} else {
// Try to call the service directly
serviceResult = ec.service.sync().name(toolName).parameters(arguments).call()
}
result.result = [content: [type: "text", text: serviceResult?.toString()]]
} finally {
// Restore original user context
if (originalUser) {
ec.user.internalLoginUser(originalUser, null)
}
}
]]></script>
</actions>
</service>
<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" 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
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
// Get user-specific tools and resources
def toolsResult = ec.service.sync().name("McpServices.mcp#ToolsList").parameters([:]).call()
def resourcesResult = ec.service.sync().name("McpServices.mcp#ResourcesList").parameters([:]).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.0"
]
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."
]
ec.logger.info("MCP Initialize for user ${userId}: ${toolsResult?.result?.tools?.size() ?: 0} tools, ${resourcesResult?.result?.resources?.size() ?: 0} resources")
]]></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"/>
</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
// Get all service names from Moqui service engine
def allServiceNames = ec.service.getKnownServiceNames()
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: []
]
]
// Add service metadata to help LLM
if (serviceInfo.verb && serviceInfo.noun) {
tool.description += " (${serviceInfo.verb}:${serviceInfo.noun})"
}
// Convert service parameters to JSON Schema
def inParamNames = serviceInfo.getInParameterNames()
for (paramName in inParamNames) {
def paramInfo = serviceInfo.getInParameter(paramName)
def paramDesc = paramInfo.description ?: ""
// Add type information to description for LLM
if (!paramDesc) {
paramDesc = "Parameter of type ${paramInfo.type}"
} else {
paramDesc += " (type: ${paramInfo.type})"
}
tool.inputSchema.properties[paramName] = [
type: convertMoquiTypeToJsonSchemaType(paramInfo.type),
description: paramDesc
]
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="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" 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.getNowTimestamp()
artifactHit.create()
def startTime = System.currentTimeMillis()
try {
// Execute service
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
// Update audit record with error
artifactHit.runningTimeMillis = executionTime
artifactHit.wasError = "Y"
artifactHit.errorMessage = e.message
artifactHit.update()
result = [
content: [
[
type: "text",
text: "Error executing tool ${name}: ${e.message}"
]
],
isError: true
]
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"/>
</in-parameters>
<out-parameters>
<parameter name="result" type="Map"/>
</out-parameters>
<actions>
<script><![CDATA[
import org.moqui.context.ExecutionContext
ExecutionContext ec = context.ec
// Get all entity names from Moqui entity engine
def allEntityNames = ec.entity.getAllEntityNames()
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: entityInfo.description ?: "Moqui entity: ${entityName}",
mimeType: "application/json"
]
// Add entity metadata to help LLM
if (entityInfo.packageName) {
resource.description += " (package: ${entityInfo.packageName})"
}
availableResources << resource
} catch (Exception e) {
ec.logger.warn("Error processing entity ${entityName}: ${e.message}")
}
}
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="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}")
}
// 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.getNowTimestamp()
artifactHit.create()
def startTime = System.currentTimeMillis()
try {
// Get entity definition for field descriptions
def entityDef = ec.entity.getEntityDefinition(entityName)
// 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]
// 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="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="result" type="Map"/>
</out-parameters>
<actions>
<script><![CDATA[
result = [
timestamp: ec.user.getNowTimestamp(),
status: "healthy",
version: "2.0.0"
]
]]></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
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
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>
<!-- NOTE: handle#McpRequest service removed - functionality moved to screen/webapp.xml for unified handling -->
</services>