VisitBasedMcpSession.groovy
8.63 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
/*
* This software is in the public domain under CC0 1.0 Universal plus a
* Grant of Patent License.
*
* To the extent possible under law, 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
* <http://creativecommons.org/publicdomain/zero/1.0/>.
*/
package org.moqui.mcp
import org.moqui.context.ExecutionContext
import org.moqui.impl.context.ExecutionContextImpl
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicLong
/**
* MCP Session implementation that integrates with Moqui's Visit system
* Provides SDK-style session management while leveraging Moqui's built-in tracking
*/
class VisitBasedMcpSession implements MoquiMcpTransport {
protected final static Logger logger = LoggerFactory.getLogger(VisitBasedMcpSession.class)
private final String sessionId
private final String visitId
private final PrintWriter writer
private final ExecutionContextImpl ec
private final AtomicBoolean active = new AtomicBoolean(true)
private final AtomicBoolean closing = new AtomicBoolean(false)
private final AtomicLong messageCount = new AtomicLong(0)
private final Date createdAt
// MCP session metadata stored in Visit context
private final Map<String, Object> sessionMetadata = new ConcurrentHashMap<>()
VisitBasedMcpSession(String sessionId, String visitId, PrintWriter writer, ExecutionContextImpl ec) {
this.sessionId = sessionId
this.visitId = visitId
this.writer = writer
this.ec = ec
this.createdAt = new Date()
// Initialize session metadata in Visit context
initializeSessionMetadata()
}
private void initializeSessionMetadata() {
try {
// Store MCP session info in Visit context for persistence
if (visitId && ec) {
def visit = ec.entity.find("moqui.server.Visit").condition("visitId", visitId).one()
if (visit) {
// Store MCP session metadata as JSON in Visit's context or a separate field
sessionMetadata.put("mcpSessionId", sessionId)
sessionMetadata.put("mcpCreatedAt", createdAt.time)
sessionMetadata.put("mcpProtocolVersion", "2025-06-18")
sessionMetadata.put("mcpTransportType", "SSE")
logger.info("MCP Session ${sessionId} initialized with Visit ${visitId}")
}
}
} catch (Exception e) {
logger.warn("Failed to initialize session metadata for Visit ${visitId}: ${e.message}")
}
}
@Override
void sendMessage(JsonRpcMessage message) {
if (!active.get() || closing.get()) {
logger.warn("Attempted to send message on inactive or closing session ${sessionId}")
return
}
try {
String jsonMessage = message.toJson()
sendSseEvent("message", jsonMessage)
messageCount.incrementAndGet()
// Update session activity in Visit
updateSessionActivity()
} catch (Exception e) {
logger.error("Failed to send message on session ${sessionId}: ${e.message}")
if (e.message?.contains("disconnected") || e.message?.contains("Client disconnected")) {
close()
}
}
}
void closeGracefully() {
if (!active.compareAndSet(true, false)) {
return // Already closed
}
closing.set(true)
logger.info("Gracefully closing MCP session ${sessionId}")
try {
// Send graceful shutdown notification
def shutdownMessage = new JsonRpcNotification("shutdown", [
sessionId: sessionId,
timestamp: System.currentTimeMillis()
])
sendMessage(shutdownMessage)
// Give some time for message to be sent
Thread.sleep(100)
} catch (Exception e) {
logger.warn("Error during graceful shutdown of session ${sessionId}: ${e.message}")
} finally {
close()
}
}
void close() {
if (!active.compareAndSet(true, false)) {
return // Already closed
}
logger.info("Closing MCP session ${sessionId} (messages sent: ${messageCount.get()})")
try {
// Update Visit with session end info
updateSessionEnd()
// Send final close event if writer is still available
if (writer && !writer.checkError()) {
sendSseEvent("close", groovy.json.JsonOutput.toJson([
type: "disconnected",
sessionId: sessionId,
messageCount: messageCount.get(),
timestamp: System.currentTimeMillis()
]))
}
} catch (Exception e) {
logger.warn("Error during session close ${sessionId}: ${e.message}")
}
}
@Override
boolean isActive() {
return active.get() && !closing.get() && writer && !writer.checkError()
}
@Override
String getSessionId() {
return sessionId
}
String getVisitId() {
return visitId
}
/**
* Get session statistics
*/
Map getSessionStats() {
return [
sessionId: sessionId,
visitId: visitId,
createdAt: createdAt,
messageCount: messageCount.get(),
active: active.get(),
closing: closing.get(),
duration: System.currentTimeMillis() - createdAt.time
]
}
/**
* Send SSE event with proper formatting
*/
private void sendSseEvent(String eventType, String data) throws IOException {
if (!writer || writer.checkError()) {
throw new IOException("Writer is closed or client disconnected")
}
writer.write("event: " + eventType + "\n")
writer.write("data: " + data + "\n\n")
writer.flush()
if (writer.checkError()) {
throw new IOException("Client disconnected during write")
}
}
/**
* Update session activity in Visit record
*/
private void updateSessionActivity() {
try {
if (visitId && ec) {
// Update Visit with latest activity
ec.service.sync().name("update", "moqui.server.Visit")
.parameters([
visitId: visitId,
thruDate: ec.user.getNowTimestamp()
])
.call()
// Could also update a custom field for MCP-specific activity
sessionMetadata.put("mcpLastActivity", System.currentTimeMillis())
sessionMetadata.put("mcpMessageCount", messageCount.get())
}
} catch (Exception e) {
logger.debug("Failed to update session activity: ${e.message}")
}
}
/**
* Update Visit record with session end information
*/
private void updateSessionEnd() {
try {
if (visitId && ec) {
// Update Visit with session end info
ec.service.sync().name("update", "moqui.server.Visit")
.parameters([
visitId: visitId,
thruDate: ec.user.getNowTimestamp()
])
.call()
// Store final session metadata
sessionMetadata.put("mcpEndedAt", System.currentTimeMillis())
sessionMetadata.put("mcpFinalMessageCount", messageCount.get())
logger.info("Updated Visit ${visitId} with MCP session end info")
}
} catch (Exception e) {
logger.warn("Failed to update session end for Visit ${visitId}: ${e.message}")
}
}
/**
* Get session metadata
*/
Map getSessionMetadata() {
return new HashMap<>(sessionMetadata)
}
/**
* Add custom metadata to session
*/
void addSessionMetadata(String key, Object value) {
sessionMetadata.put(key, value)
}
}