AgentServices.xml
14.3 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
<?xml version="1.0" encoding="UTF-8"?>
<services xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://moqui.org/xsd/service-definition-3.xsd">
<!-- ========================================================= -->
<!-- Agent Tool Bridge (The Secure Gateway) -->
<!-- ========================================================= -->
<service verb="call" noun="McpToolWithDelegation" authenticate="false">
<description>
Securely executes an MCP tool by impersonating target user (runAsUserId).
The calling agent must have permission to use this service, but
tool execution itself is subject to target user's permissions.
</description>
<in-parameters>
<parameter name="toolName" required="true"/>
<parameter name="arguments" type="Map"/>
<parameter name="runAsUserId" required="true">
<description>The UserAccount ID to impersonate.</description>
</parameter>
</in-parameters>
<out-parameters>
<parameter name="result" type="Map"/>
</out-parameters>
<actions>
<script><![CDATA[
import org.moqui.mcp.adapter.McpToolAdapter
import org.moqui.context.ArtifactAuthorizationException
// 1. Capture current agent identity
String agentUsername = ec.user.username
try {
// 2. Switch identity to target user
boolean loggedIn = ec.user.internalLoginUser(runAsUserId, false)
if (!loggedIn) throw new Exception("Could not switch to user ${runAsUserId}")
ec.logger.info("Agent ${agentUsername} executing ${toolName} AS ${ec.user.username} (${runAsUserId})")
// 3. Execute Tool
McpToolAdapter adapter = new McpToolAdapter()
result = adapter.callTool(ec, toolName, arguments)
} finally {
// 4. Restore Agent Identity
if (agentUsername) {
ec.user.internalLoginUser(agentUsername, false)
}
}
]]></script>
</actions>
</service>
<!-- ========================================================= -->
<!-- Agent Client (OpenAI-Compatible API Wrapper) -->
<!-- ========================================================= -->
<service verb="call" noun="OpenAiChatCompletion">
<description>Generic wrapper for OpenAI-compatible chat completions (VLLM, OpenAI, etc.)</description>
<in-parameters>
<parameter name="endpointUrl" required="true"/>
<parameter name="apiKey"/>
<parameter name="model" required="true"/>
<parameter name="messages" type="List" required="true"/>
<parameter name="tools" type="List"/>
<parameter name="temperature" type="BigDecimal" default="0.7"/>
<parameter name="maxTokens" type="Integer"/>
</in-parameters>
<out-parameters>
<parameter name="response" type="Map"/>
<parameter name="httpStatus" type="Integer"/>
<parameter name="error" type="String"/>
</out-parameters>
<actions>
<script><![CDATA[
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
def payloadMap = [
model: model,
messages: messages,
temperature: temperature,
stream: false
]
if (maxTokens) payloadMap.max_tokens = maxTokens
if (tools) payloadMap.tools = tools
String jsonPayload = new JsonBuilder(payloadMap).toString()
URL url = new URL(endpointUrl + "/chat/completions")
HttpURLConnection conn = (HttpURLConnection) url.openConnection()
conn.setRequestMethod("POST")
conn.setRequestProperty("Content-Type", "application/json")
if (apiKey) conn.setRequestProperty("Authorization", "Bearer " + apiKey)
conn.setDoOutput(true)
conn.setConnectTimeout(10000)
conn.setReadTimeout(60000)
try {
conn.outputStream.write(jsonPayload.getBytes("UTF-8"))
httpStatus = conn.responseCode
InputStream is = (httpStatus >= 200 && httpStatus < 300) ? conn.inputStream : conn.errorStream
String responseText = is?.text
if (responseText) response = new JsonSlurper().parseText(responseText)
if (httpStatus >= 300) error = "HTTP ${httpStatus}: ${responseText}"
} catch (Exception e) {
error = e.message
httpStatus = 500
ec.logger.error("OpenAI Client Exception", e)
}
]]></script>
</actions>
</service>
<!-- ========================================================= -->
<!-- Agent Runner (Single Turn State Machine) -->
<!-- ========================================================= -->
<service verb="run" noun="AgentTaskTurn" authenticate="false">
<description>
Processes ONE turn of an Agent Task.
Loads thread history, calls LLM, executes ONE set of tools, saves state, and re-queues if needed.
</description>
<in-parameters>
<parameter name="systemMessageId" required="true"/>
</in-parameters>
<actions>
<script><![CDATA[
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import org.moqui.mcp.adapter.McpToolAdapter
// 1. Load SystemMessage Task
def taskMsg = ec.entity.find("moqui.service.message.SystemMessage")
.condition("systemMessageId", systemMessageId).one()
if (!taskMsg || taskMsg.statusId != "SmsgReceived") return
// Get AI Config
def aiConfig = ec.entity.find("moqui.mcp.agent.ProductStoreAiConfig")
.condition("productStoreId", taskMsg.productStoreId)
.condition("aiConfigId", taskMsg.aiConfigId).one()
if (!aiConfig?.endpointUrl || !aiConfig?.modelName) {
taskMsg.statusId = "SmsgError"; taskMsg.update()
return
}
// 2. Reconstruct Conversation History from CommunicationEvents
def messages = []
messages.add([role: "system", content: "You are a helpful Moqui ERP assistant. You act as user ${taskMsg.effectiveUserId}."])
if (taskMsg.rootCommEventId) {
def threadEvents = ec.entity.find("mantle.party.communication.CommunicationEvent")
.condition("rootCommEventId", taskMsg.rootCommEventId)
.orderBy("entryDate").list()
threadEvents.each { ev ->
// Distinguish roles based on fromPartyId
String role = (ev.fromPartyId == "AGENT_CLAUDE_PARTY") ? "assistant" : "user"
// Check if it's a tool result (stored in contentType application/json)
if (ev.contentType == "application/json") {
def json = new JsonSlurper().parseText(ev.body)
if (json.tool_call_id) {
messages.add([role: "tool", tool_call_id: json.tool_call_id, content: json.content])
} else if (json.tool_calls) {
messages.add([role: "assistant", tool_calls: json.tool_calls])
}
} else {
messages.add([role: role, content: ev.body])
}
}
} else {
// Initial task message
messages.add([role: "user", content: taskMsg.messageText])
}
// 3. Prepare Tools
def mcpToolAdapter = new org.moqui.mcp.adapter.McpToolAdapter()
def moquiTools = mcpToolAdapter.listTools()
def openAiTools = moquiTools.collect { tool ->
[type: "function", function: [
name: tool.name, description: tool.description,
parameters: [type: "object", properties: [
path: [type: "string"], action: [type: "string"], parameters: [type: "object"]
]]
]]
}
// 4. Call LLM
def llmResult = ec.service.sync().name("AgentServices.call#OpenAiChatCompletion").parameters([
endpointUrl: aiConfig.endpointUrl, apiKey: aiConfig.apiKey,
model: aiConfig.modelName, messages: messages, tools: openAiTools,
temperature: aiConfig.temperature
]).call()
if (llmResult.error) {
taskMsg.statusId = "SmsgError"; taskMsg.update()
return
}
def responseMsg = llmResult.response.choices[0].message
// 5. Handle Response
if (responseMsg.tool_calls) {
// SAVE Assistant "Thought" (Tool Calls)
def assistantComm = ec.service.sync().name("create#mantle.party.communication.CommunicationEvent").parameters([
fromPartyId: "AGENT_CLAUDE_PARTY", toPartyId: taskMsg.requestedByPartyId,
rootCommEventId: taskMsg.rootCommEventId, parentCommEventId: taskMsg.rootCommEventId,
communicationEventTypeId: "Message", contentType: "application/json",
body: JsonOutput.toJson([tool_calls: responseMsg.tool_calls]),
entryDate: ec.user.nowTimestamp, statusId: "CeReceived"
]).call()
// EXECUTE Tools and Save Results
responseMsg.tool_calls.each { toolCall ->
def result = [:]
try {
def runResult = ec.service.sync().name("AgentServices.call#McpToolWithDelegation").parameters([
toolName: toolCall.function.name, arguments: new JsonSlurper().parseText(toolCall.function.arguments),
runAsUserId: taskMsg.effectiveUserId
]).call()
result = runResult.result
} catch (Exception e) { result = [error: e.message] }
// Save Tool Result as CommEvent
ec.service.sync().name("create#mantle.party.communication.CommunicationEvent").parameters([
fromPartyId: taskMsg.requestedByPartyId, toPartyId: "AGENT_CLAUDE_PARTY",
rootCommEventId: taskMsg.rootCommEventId, parentCommEventId: assistantComm.communicationEventId,
communicationEventTypeId: "Message", contentType: "application/json",
body: JsonOutput.toJson([tool_call_id: toolCall.id, content: JsonOutput.toJson(result)]),
entryDate: ec.user.nowTimestamp, statusId: "CeReceived"
]).call()
}
// 6. RE-QUEUE: Create next turn message
ec.service.sync().name("create#moqui.service.message.SystemMessage").parameters([
systemMessageTypeId: "SmtyAgentTask", statusId: "SmsgReceived",
productStoreId: taskMsg.productStoreId, aiConfigId: taskMsg.aiConfigId,
requestedByPartyId: taskMsg.requestedByPartyId, effectiveUserId: taskMsg.effectiveUserId,
rootCommEventId: taskMsg.rootCommEventId, isOutgoing: "N"
]).call()
taskMsg.statusId = "SmsgConsumed"; taskMsg.update()
} else {
// FINAL Response
ec.service.sync().name("create#mantle.party.communication.CommunicationEvent").parameters([
fromPartyId: "AGENT_CLAUDE_PARTY", toPartyId: taskMsg.requestedByPartyId,
rootCommEventId: taskMsg.rootCommEventId, parentCommEventId: taskMsg.rootCommEventId,
communicationEventTypeId: "Message", contentType: "text/plain",
body: responseMsg.content, entryDate: ec.user.nowTimestamp, statusId: "CeReceived"
]).call()
taskMsg.statusId = "SmsgConfirmed"; taskMsg.update()
}
]]></script>
</actions>
</service>
<!-- ========================================================= -->
<!-- Task Scheduler (Polls Queue) -->
<!-- ========================================================= -->
<service verb="poll" noun="AgentQueue" authenticate="false">
<description>Scheduled service to pick up pending tasks and process them.</description>
<actions>
<script><![CDATA[
// Find pending tasks
def pendingTasks = ec.entity.find("moqui.service.message.SystemMessage")
.condition("statusId", "SmsgReceived")
.condition("systemMessageTypeId", "SmtyAgentTask")
.limit(5)
.disableAuthz()
.list()
pendingTasks.each { task ->
// Run Agent Task Turn
ec.service.sync().name("AgentServices.run#AgentTaskTurn")
.parameters([systemMessageId: task.systemMessageId])
.call()
}
]]></script>
</actions>
</service>
</services>