-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathredisTransport.ts
More file actions
379 lines (324 loc) · 13.1 KB
/
Copy pathredisTransport.ts
File metadata and controls
379 lines (324 loc) · 13.1 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
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { redisClient } from "../../shared/redis.js";
import { Transport, TransportSendOptions } from "@modelcontextprotocol/sdk/shared/transport.js";
import { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js";
import { JSONRPCMessage, MessageExtraInfo } from "@modelcontextprotocol/sdk/types.js";
import { logger } from "../../shared/logger.js";
let redisTransportCounter = 0;
const notificationStreamId = "__GET_stream";
// Safety-net TTL for session ownership keys. Live sessions refresh it on every
// authorized request, and ServerRedisTransport.close() deletes the key, so the
// TTL only ever fires for keys orphaned by a crashed process.
const SESSION_OWNER_TTL_SECONDS = 30 * 60;
// Message types for Redis transport
type RedisMessage =
| {
type: 'mcp';
message: JSONRPCMessage;
extra?: MessageExtraInfo;
options?: TransportSendOptions;
}
| {
type: 'control';
action: 'SHUTDOWN' | 'PING' | 'STATUS';
timestamp?: number;
};
function sendToMcpServer(sessionId: string, message: JSONRPCMessage, extra?: { authInfo?: AuthInfo; }, options?: TransportSendOptions): Promise<void> {
const toServerChannel = getToServerChannel(sessionId);
logger.debug('Sending message to MCP server via Redis', {
sessionId,
channel: toServerChannel,
method: ('method' in message ? message.method : undefined),
id: ('id' in message ? message.id : undefined)
});
const redisMessage: RedisMessage = { type: 'mcp', message, extra, options };
return redisClient.publish(toServerChannel, JSON.stringify(redisMessage));
}
function getToServerChannel(sessionId: string): string {
return `mcp:shttp:toserver:${sessionId}`;
}
function getToClientChannel(sessionId: string, relatedRequestId: string): string {
return `mcp:shttp:toclient:${sessionId}:${relatedRequestId}`;
}
function getControlChannel(sessionId: string): string {
return `mcp:control:${sessionId}`;
}
function sendControlMessage(sessionId: string, action: 'SHUTDOWN' | 'PING' | 'STATUS'): Promise<void> {
const controlChannel = getControlChannel(sessionId);
const redisMessage: RedisMessage = {
type: 'control',
action,
timestamp: Date.now()
};
return redisClient.publish(controlChannel, JSON.stringify(redisMessage));
}
export async function shutdownSession(sessionId: string): Promise<void> {
logger.info('Sending shutdown control message', { sessionId });
return sendControlMessage(sessionId, 'SHUTDOWN');
}
export async function isLive(sessionId: string): Promise<boolean> {
// Check if the session is live by checking if the key exists in Redis
const numSubs = await redisClient.numsub(getToServerChannel(sessionId));
return numSubs > 0;
}
function getSessionOwnerKey(sessionId: string): string {
return `session:${sessionId}:owner`;
}
export async function setSessionOwner(sessionId: string, userId: string): Promise<void> {
logger.debug('Setting session owner', { sessionId, userId });
await redisClient.set(getSessionOwnerKey(sessionId), userId, { EX: SESSION_OWNER_TTL_SECONDS });
}
export async function getSessionOwner(sessionId: string): Promise<string | null> {
return await redisClient.get(getSessionOwnerKey(sessionId));
}
export async function deleteSessionOwner(sessionId: string): Promise<void> {
logger.debug('Deleting session owner', { sessionId });
await redisClient.del(getSessionOwnerKey(sessionId));
}
export async function validateSessionOwnership(sessionId: string, userId: string): Promise<boolean> {
const owner = await getSessionOwner(sessionId);
if (owner !== userId) {
return false;
}
// Sliding expiration: each authorized request keeps the ownership key alive,
// so the TTL only reaps keys whose session never got cleaned up.
await redisClient.expire(getSessionOwnerKey(sessionId), SESSION_OWNER_TTL_SECONDS);
return true;
}
export async function isSessionOwnedBy(sessionId: string, userId: string): Promise<boolean> {
const isLiveSession = await isLive(sessionId);
if (!isLiveSession) {
logger.debug('Session not live', { sessionId });
return false;
}
const isOwned = await validateSessionOwnership(sessionId, userId);
logger.debug('Session ownership check', { sessionId, userId, isOwned });
return isOwned;
}
export async function redisRelayToMcpServer(sessionId: string, transport: Transport, isGetRequest: boolean = false): Promise<() => Promise<void>> {
logger.debug('Setting up Redis relay to MCP server', {
sessionId,
isGetRequest
});
let redisCleanup: (() => Promise<void>) | undefined = undefined;
const cleanup = async () => {
// TODO: solve race conditions where we call cleanup while the subscription is being created / before it is created
if (redisCleanup) {
logger.debug('Cleaning up Redis relay', { sessionId });
await redisCleanup();
}
}
const subscribe = async (requestId: string) => {
const toClientChannel = getToClientChannel(sessionId, requestId);
logger.debug('Subscribing to client channel', {
sessionId,
requestId,
channel: toClientChannel
});
redisCleanup = await redisClient.createSubscription(toClientChannel, async (redisMessageJson) => {
const redisMessage = JSON.parse(redisMessageJson) as RedisMessage;
if (redisMessage.type === 'mcp') {
logger.debug('Relaying message from Redis to client', {
sessionId,
requestId,
method: ('method' in redisMessage.message ? redisMessage.message.method : undefined)
});
await transport.send(redisMessage.message, redisMessage.options);
}
}, (error) => {
logger.error('Error in Redis relay subscription', error, {
sessionId,
channel: toClientChannel
});
transport.onerror?.(error);
});
}
if (isGetRequest) {
await subscribe(notificationStreamId);
} else {
const messagePromise = new Promise<JSONRPCMessage>((resolve) => {
transport.onmessage = async (message, extra) => {
// First, set up response subscription if needed
if ("id" in message && message.id !== undefined) {
logger.debug('Setting up response subscription', {
sessionId,
messageId: message.id,
method: ('method' in message ? message.method : undefined)
});
await subscribe(message.id.toString());
}
// Now send the message to the MCP server
await sendToMcpServer(sessionId, message, extra);
resolve(message);
}
});
messagePromise.catch((error) => {
transport.onerror?.(error);
cleanup();
});
}
return cleanup;
}
// New Redis transport for server->client messages using request-id based channels
export class ServerRedisTransport implements Transport {
private counter: number;
private _sessionId: string;
private controlCleanup?: (() => Promise<void>);
private serverCleanup?: (() => Promise<void>);
private shouldShutdown = false;
private inactivityTimeout?: NodeJS.Timeout;
private readonly INACTIVITY_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
onclose?: (() => void) | undefined;
onerror?: ((error: Error) => void) | undefined;
onmessage?: ((message: JSONRPCMessage, extra?: { authInfo?: AuthInfo; }) => void) | undefined;
constructor(sessionId: string) {
this.counter = redisTransportCounter++;
this._sessionId = sessionId;
}
private resetInactivityTimer(): void {
// Clear existing timeout if any
if (this.inactivityTimeout) {
clearTimeout(this.inactivityTimeout);
}
// Set new timeout
this.inactivityTimeout = setTimeout(() => {
logger.info('Session timed out due to inactivity', {
sessionId: this._sessionId,
timeoutMs: this.INACTIVITY_TIMEOUT_MS
});
void shutdownSession(this._sessionId);
}, this.INACTIVITY_TIMEOUT_MS);
}
private clearInactivityTimer(): void {
if (this.inactivityTimeout) {
clearTimeout(this.inactivityTimeout);
this.inactivityTimeout = undefined;
}
}
async start(): Promise<void> {
logger.info('Starting ServerRedisTransport', {
sessionId: this._sessionId,
inactivityTimeoutMs: this.INACTIVITY_TIMEOUT_MS
});
// Start inactivity timer
this.resetInactivityTimer();
// Subscribe to MCP messages from clients
const serverChannel = getToServerChannel(this._sessionId);
logger.debug('Subscribing to server channel', {
sessionId: this._sessionId,
channel: serverChannel
});
this.serverCleanup = await redisClient.createSubscription(
serverChannel,
(messageJson) => {
const redisMessage = JSON.parse(messageJson) as RedisMessage;
if (redisMessage.type === 'mcp') {
// Reset inactivity timer on each message from client
this.resetInactivityTimer();
logger.debug('Received MCP message from client', {
sessionId: this._sessionId,
method: ('method' in redisMessage.message ? redisMessage.message.method : undefined),
id: ('id' in redisMessage.message ? redisMessage.message.id : undefined)
});
this.onmessage?.(redisMessage.message, redisMessage.extra);
}
},
(error) => {
logger.error('Error in server channel subscription', error, {
sessionId: this._sessionId,
channel: serverChannel
});
this.onerror?.(error);
}
);
// Subscribe to control messages for shutdown
const controlChannel = getControlChannel(this._sessionId);
logger.debug('Subscribing to control channel', {
sessionId: this._sessionId,
channel: controlChannel
});
this.controlCleanup = await redisClient.createSubscription(
controlChannel,
(messageJson) => {
const redisMessage = JSON.parse(messageJson) as RedisMessage;
if (redisMessage.type === 'control') {
logger.info('Received control message', {
sessionId: this._sessionId,
action: redisMessage.action
});
if (redisMessage.action === 'SHUTDOWN') {
logger.info('Shutting down transport due to control message', {
sessionId: this._sessionId
});
this.shouldShutdown = true;
this.close();
}
}
},
(error) => {
logger.error('Error in control channel subscription', error, {
sessionId: this._sessionId,
channel: controlChannel
});
this.onerror?.(error);
}
);
}
async send(message: JSONRPCMessage, options?: TransportSendOptions): Promise<void> {
const relatedRequestId = options?.relatedRequestId?.toString() ?? ("id" in message && message.id !== undefined ? message.id.toString() : notificationStreamId);
const channel = getToClientChannel(this._sessionId, relatedRequestId)
logger.debug('Sending message to client', {
sessionId: this._sessionId,
channel,
method: ('method' in message ? message.method : undefined),
id: ('id' in message ? message.id : undefined),
relatedRequestId
});
const redisMessage: RedisMessage = { type: 'mcp', message, options };
const messageStr = JSON.stringify(redisMessage);
await redisClient.publish(channel, messageStr);
}
async close(): Promise<void> {
logger.info('Closing ServerRedisTransport', {
sessionId: this._sessionId,
wasShutdown: this.shouldShutdown
});
// Clear inactivity timer
this.clearInactivityTimer();
// Clean up server message subscription
if (this.serverCleanup) {
await this.serverCleanup();
this.serverCleanup = undefined;
}
// Clean up control message subscription
if (this.controlCleanup) {
await this.controlCleanup();
this.controlCleanup = undefined;
}
// The session is finished — remove its ownership key (#21)
await deleteSessionOwner(this._sessionId);
this.onclose?.();
}
}
export async function getShttpTransport(sessionId: string, onsessionclosed: (sessionId: string) => void | Promise<void>, isGetRequest: boolean = false): Promise<StreamableHTTPServerTransport> {
logger.debug('Getting StreamableHTTPServerTransport for existing session', {
sessionId,
isGetRequest
});
// Inject the existing session ID so the transport resumes it instead of
// creating a new one. SDK 1.29 made sessionId readonly on the wrapper, but
// the underlying web-standard transport still exposes it as a writable field;
// _initialized must also be set so validateSession accepts non-init requests.
const shttpTransport = new StreamableHTTPServerTransport({
sessionIdGenerator: () => sessionId,
onsessionclosed,
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const inner = (shttpTransport as any)['_webStandardTransport'];
inner.sessionId = sessionId;
inner._initialized = true;
// Use the new request-id based relay approach
const cleanup = await redisRelayToMcpServer(sessionId, shttpTransport, isGetRequest);
shttpTransport.onclose = cleanup;
return shttpTransport;
}