McpFieldOptionsService.groovy
11.2 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
package org.moqui.mcp
import org.moqui.context.ExecutionContext
import org.moqui.impl.context.ExecutionContextFactoryImpl
import groovy.json.JsonSlurper
/**
* Service for getting screen field details including dropdown options via dynamic-options.
*
* This implementation mirrors how the Moqui web UI handles autocomplete:
* - Uses CustomScreenTestImpl with skipJsonSerialize(true) to call transitions
* - Captures the raw JSON response via getJsonObject()
* - Processes the response to extract options
*
* See ScreenRenderImpl.getFieldOptions() in moqui-framework for the reference implementation.
*/
class McpFieldOptionsService {
static service(String path, String fieldName, Map parameters, ExecutionContext ec) {
if (!path) throw new IllegalArgumentException("path is required")
def result = [screenPath: path, fields: [:]]
try {
// Pass mcpFullOptions through parameters to get full dropdown options without truncation
def mergedParams = (parameters ?: [:]) + [mcpFullOptions: true]
def browseResult = ec.service.sync().name("McpServices.execute#ScreenAsMcpTool")
.parameters([path: path, parameters: mergedParams, renderMode: "mcp", sessionId: null])
.call()
if (!browseResult?.result?.content) {
ec.logger.warn("GetScreenDetails: No content from ScreenAsMcpTool for path ${path}")
return result + [error: "No content from ScreenAsMcpTool"]
}
def rawText = browseResult.result.content[0].text
if (!rawText || !rawText.startsWith("{")) {
ec.logger.warn("GetScreenDetails: Invalid JSON from ScreenAsMcpTool for path ${path}")
return result + [error: "Invalid JSON from ScreenAsMcpTool"]
}
def resultObj = new JsonSlurper().parseText(rawText)
def semanticState = resultObj?.semanticState
def formMetadata = semanticState?.data?.formMetadata
if (!(formMetadata instanceof Map)) {
ec.logger.warn("GetScreenDetails: formMetadata is not a Map for path ${path}")
return result + [error: "No form metadata found"]
}
def allFields = [:]
formMetadata.each { formName, formItem ->
if (!(formItem instanceof Map) || !formItem.fields) return
formItem.fields.each { field ->
if (!(field instanceof Map) || !field.name) return
def fieldInfo = [
name: field.name,
title: field.title,
type: field.type,
required: field.required ?: false
]
if (field.type == "dropdown" && field.options) fieldInfo.options = field.options
def dynamicOptions = field.dynamicOptions
if (dynamicOptions instanceof Map) {
fieldInfo.dynamicOptions = dynamicOptions
try {
fetchOptions(fieldInfo, path, parameters, dynamicOptions, ec)
} catch (Exception e) {
ec.logger.warn("GetScreenDetails: Failed to fetch options for ${field.name}: ${e.message}")
fieldInfo.optionsError = e.message
}
}
// Merge fields with same name - prefer version with options
// This handles cases where a field appears in both search and edit forms
def existingField = allFields[field.name]
if (existingField) {
// Keep existing options if new field has none
if (existingField.options && !fieldInfo.options) {
fieldInfo.options = existingField.options
}
// Merge dynamicOptions if existing has them
if (existingField.dynamicOptions && !fieldInfo.dynamicOptions) {
fieldInfo.dynamicOptions = existingField.dynamicOptions
}
}
allFields[field.name] = fieldInfo
}
}
if (fieldName) {
if (allFields[fieldName]) result.fields[fieldName] = allFields[fieldName]
else result.error = "Field not found: ${fieldName}"
} else {
result.fields = allFields.collectEntries { k, v -> [k, v] }
}
} catch (Exception e) {
ec.logger.error("MCP GetScreenDetails error: ${e.message}", e)
result.error = e.message
}
return result
}
/**
* Fetch options for a field with dynamic-options by calling the transition.
*
* This uses CustomScreenTestImpl with skipJsonSerialize(true) to call the transition
* and capture the raw JSON response - exactly how ScreenRenderImpl.getFieldOptions() works.
*/
private static void fetchOptions(Map fieldInfo, String path, Map parameters, Map dynamicOptions, ExecutionContext ec) {
def transitionName = dynamicOptions.transition
if (!transitionName) return
def optionParams = [:]
// 1. Handle dependsOn (from form XML) - maps field values to service parameters
if (dynamicOptions.dependsOn) {
def depList = dynamicOptions.dependsOn instanceof String ?
new JsonSlurper().parseText(dynamicOptions.dependsOn) : dynamicOptions.dependsOn
depList.each { dep ->
def parts = dep.split('\\|')
def fld = parts[0], prm = parts.size() > 1 ? parts[1] : fld
def val = parameters?.get(fld)
// Try common form map names if not found at top level
if (val == null) {
['fieldValues', 'fieldValuesMap', 'formValues', 'formValuesMap', 'formMap'].each { mapName ->
def mapVal = parameters?.get(mapName as String)
if (mapVal instanceof Map) {
val = mapVal.get(fld)
if (val != null) return
}
}
}
if (val != null) optionParams[prm] = val
}
}
// 2. Handle serverSearch fields - skip if no search term provided (matches framework behavior)
def isServerSearch = dynamicOptions.serverSearch == true || dynamicOptions.serverSearch == "true"
if (isServerSearch) {
if (parameters?.term != null && parameters.term.toString().length() > 0) {
optionParams.term = parameters.term
} else {
return // Skip server-search fields without a term
}
}
// 3. Use CustomScreenTestImpl with skipJsonSerialize to call the transition
try {
def ecfi = (ExecutionContextFactoryImpl) ec.factory
// Build transition path by appending transition name to screen path
def fullPath = path
if (!fullPath.endsWith('/')) fullPath += '/'
fullPath += transitionName
// Parse path segments for component-based resolution
def pathSegments = []
fullPath.split('/').each { if (it && it.trim()) pathSegments.add(it) }
// Component-based resolution (same as ScreenAsMcpTool)
def rootScreen = "component://webroot/screen/webroot.xml"
def testScreenPath = fullPath
if (pathSegments.size() >= 2) {
def componentName = pathSegments[0]
def rootScreenName = pathSegments[1]
def compRootLoc = "component://${componentName}/screen/${rootScreenName}.xml"
if (ec.resource.getLocationReference(compRootLoc).exists) {
rootScreen = compRootLoc
testScreenPath = pathSegments.size() > 2 ? pathSegments[2..-1].join('/') : ""
}
}
// Use CustomScreenTestImpl with skipJsonSerialize - like ScreenRenderImpl.getFieldOptions()
def screenTest = new CustomScreenTestImpl(ecfi)
.rootScreen(rootScreen)
.skipJsonSerialize(true)
.auth(ec.user.username)
def str = screenTest.render(testScreenPath, optionParams, "GET")
// Get JSON object directly (like web UI does)
def jsonObj = str.getJsonObject()
// Extract value-field and label-field from dynamic-options config
def valueField = dynamicOptions.valueField ?: dynamicOptions.'value-field' ?: 'value'
def labelField = dynamicOptions.labelField ?: dynamicOptions.'label-field' ?: 'label'
// Process the JSON response - same logic as ScreenRenderImpl.getFieldOptions()
List optsList = null
if (jsonObj instanceof List) {
optsList = (List) jsonObj
} else if (jsonObj instanceof Map) {
Map jsonMap = (Map) jsonObj
// Try 'options' key first (standard pattern)
def optionsObj = jsonMap.get("options")
if (optionsObj instanceof List) {
optsList = (List) optionsObj
} else if (jsonMap.get("resultList") instanceof List) {
// Some services return resultList
optsList = (List) jsonMap.get("resultList")
}
}
if (optsList != null && optsList.size() > 0) {
fieldInfo.options = optsList.collect { entryObj ->
if (entryObj instanceof Map) {
Map entryMap = (Map) entryObj
// Try configured fields first, then common fallbacks
def value = entryMap.get(valueField) ?:
entryMap.get('value') ?:
entryMap.get('geoId') ?:
entryMap.get('enumId') ?:
entryMap.get('id') ?:
entryMap.get('key')
def label = entryMap.get(labelField) ?:
entryMap.get('label') ?:
entryMap.get('description') ?:
entryMap.get('name') ?:
entryMap.get('text') ?:
value?.toString()
[value: value, label: label]
} else {
[value: entryObj, label: entryObj?.toString()]
}
}.findAll { it.value != null }
}
} catch (Exception e) {
ec.logger.warn("GetScreenDetails: Error calling transition ${transitionName}: ${e.message}")
fieldInfo.optionsError = "Transition call failed: ${e.message}"
}
}
}