agents 0.0.0-9069759 → 0.0.0-90db5ba

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,755 @@
1
+ import {
2
+ Agent
3
+ } from "../chunk-XG52S6YY.js";
4
+ import {
5
+ __privateAdd,
6
+ __privateGet,
7
+ __privateMethod,
8
+ __privateSet
9
+ } from "../chunk-HMLY7DHA.js";
10
+
11
+ // src/mcp/index.ts
12
+ import { DurableObject } from "cloudflare:workers";
13
+ import {
14
+ InitializeRequestSchema,
15
+ isJSONRPCError,
16
+ isJSONRPCNotification,
17
+ isJSONRPCRequest,
18
+ isJSONRPCResponse,
19
+ JSONRPCMessageSchema
20
+ } from "@modelcontextprotocol/sdk/types.js";
21
+ var MAXIMUM_MESSAGE_SIZE_BYTES = 4 * 1024 * 1024;
22
+ function handleCORS(request, corsOptions) {
23
+ const origin = request.headers.get("Origin") || "*";
24
+ const corsHeaders = {
25
+ "Access-Control-Allow-Origin": corsOptions?.origin || origin,
26
+ "Access-Control-Allow-Methods": corsOptions?.methods || "GET, POST, OPTIONS",
27
+ "Access-Control-Allow-Headers": corsOptions?.headers || "Content-Type",
28
+ "Access-Control-Max-Age": (corsOptions?.maxAge || 86400).toString()
29
+ };
30
+ if (request.method === "OPTIONS") {
31
+ return new Response(null, { headers: corsHeaders });
32
+ }
33
+ return null;
34
+ }
35
+ var _getWebSocket, _started;
36
+ var McpSSETransport = class {
37
+ constructor(getWebSocket) {
38
+ __privateAdd(this, _getWebSocket);
39
+ __privateAdd(this, _started, false);
40
+ __privateSet(this, _getWebSocket, getWebSocket);
41
+ }
42
+ async start() {
43
+ if (__privateGet(this, _started)) {
44
+ throw new Error("Transport already started");
45
+ }
46
+ __privateSet(this, _started, true);
47
+ }
48
+ async send(message) {
49
+ if (!__privateGet(this, _started)) {
50
+ throw new Error("Transport not started");
51
+ }
52
+ const websocket = __privateGet(this, _getWebSocket).call(this);
53
+ if (!websocket) {
54
+ throw new Error("WebSocket not connected");
55
+ }
56
+ try {
57
+ websocket.send(JSON.stringify(message));
58
+ } catch (error) {
59
+ this.onerror?.(error);
60
+ throw error;
61
+ }
62
+ }
63
+ async close() {
64
+ this.onclose?.();
65
+ }
66
+ };
67
+ _getWebSocket = new WeakMap();
68
+ _started = new WeakMap();
69
+ var _getWebSocketForGetRequest, _getWebSocketForMessageID, _notifyResponseIdSent, _started2;
70
+ var McpStreamableHttpTransport = class {
71
+ constructor(getWebSocketForMessageID, notifyResponseIdSent) {
72
+ // TODO: If there is an open connection to send server-initiated messages
73
+ // back, we should use that connection
74
+ __privateAdd(this, _getWebSocketForGetRequest);
75
+ // Get the appropriate websocket connection for a given message id
76
+ __privateAdd(this, _getWebSocketForMessageID);
77
+ // Notify the server that a response has been sent for a given message id
78
+ // so that it may clean up it's mapping of message ids to connections
79
+ // once they are no longer needed
80
+ __privateAdd(this, _notifyResponseIdSent);
81
+ __privateAdd(this, _started2, false);
82
+ __privateSet(this, _getWebSocketForMessageID, getWebSocketForMessageID);
83
+ __privateSet(this, _notifyResponseIdSent, notifyResponseIdSent);
84
+ __privateSet(this, _getWebSocketForGetRequest, () => null);
85
+ }
86
+ async start() {
87
+ if (__privateGet(this, _started2)) {
88
+ throw new Error("Transport already started");
89
+ }
90
+ __privateSet(this, _started2, true);
91
+ }
92
+ async send(message) {
93
+ if (!__privateGet(this, _started2)) {
94
+ throw new Error("Transport not started");
95
+ }
96
+ let websocket = null;
97
+ if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
98
+ websocket = __privateGet(this, _getWebSocketForMessageID).call(this, message.id.toString());
99
+ if (!websocket) {
100
+ throw new Error(
101
+ `Could not find WebSocket for message id: ${message.id}`
102
+ );
103
+ }
104
+ } else if (isJSONRPCRequest(message)) {
105
+ websocket = __privateGet(this, _getWebSocketForGetRequest).call(this);
106
+ } else if (isJSONRPCNotification(message)) {
107
+ websocket = null;
108
+ }
109
+ try {
110
+ websocket?.send(JSON.stringify(message));
111
+ if (isJSONRPCResponse(message)) {
112
+ __privateGet(this, _notifyResponseIdSent).call(this, message.id.toString());
113
+ }
114
+ } catch (error) {
115
+ this.onerror?.(error);
116
+ throw error;
117
+ }
118
+ }
119
+ async close() {
120
+ this.onclose?.();
121
+ }
122
+ };
123
+ _getWebSocketForGetRequest = new WeakMap();
124
+ _getWebSocketForMessageID = new WeakMap();
125
+ _notifyResponseIdSent = new WeakMap();
126
+ _started2 = new WeakMap();
127
+ var _status, _transport, _transportType, _requestIdToConnectionId, _agent, _McpAgent_instances, initialize_fn;
128
+ var _McpAgent = class _McpAgent extends DurableObject {
129
+ constructor(ctx, env) {
130
+ var _a;
131
+ super(ctx, env);
132
+ __privateAdd(this, _McpAgent_instances);
133
+ __privateAdd(this, _status, "zero");
134
+ __privateAdd(this, _transport);
135
+ __privateAdd(this, _transportType, "unset");
136
+ __privateAdd(this, _requestIdToConnectionId, /* @__PURE__ */ new Map());
137
+ /**
138
+ * Since McpAgent's _aren't_ yet real "Agents", let's only expose a couple of the methods
139
+ * to the outer class: initialState/state/setState/onStateUpdate/sql
140
+ */
141
+ __privateAdd(this, _agent);
142
+ this.initRun = false;
143
+ const self = this;
144
+ __privateSet(this, _agent, new (_a = class extends Agent {
145
+ onStateUpdate(state, source) {
146
+ return self.onStateUpdate(state, source);
147
+ }
148
+ async onMessage(connection, message) {
149
+ return self.onMessage(connection, message);
150
+ }
151
+ }, _a.options = {
152
+ hibernate: true
153
+ }, _a)(ctx, env));
154
+ }
155
+ get state() {
156
+ return __privateGet(this, _agent).state;
157
+ }
158
+ sql(strings, ...values) {
159
+ return __privateGet(this, _agent).sql(strings, ...values);
160
+ }
161
+ setState(state) {
162
+ return __privateGet(this, _agent).setState(state);
163
+ }
164
+ onStateUpdate(state, source) {
165
+ }
166
+ async onStart() {
167
+ var _a;
168
+ const self = this;
169
+ __privateSet(this, _agent, new (_a = class extends Agent {
170
+ constructor() {
171
+ super(...arguments);
172
+ this.initialState = self.initialState;
173
+ }
174
+ onStateUpdate(state, source) {
175
+ return self.onStateUpdate(state, source);
176
+ }
177
+ async onMessage(connection, event) {
178
+ return self.onMessage(connection, event);
179
+ }
180
+ }, _a.options = {
181
+ hibernate: true
182
+ }, _a)(this.ctx, this.env));
183
+ this.props = await this.ctx.storage.get("props");
184
+ __privateSet(this, _transportType, await this.ctx.storage.get(
185
+ "transportType"
186
+ ));
187
+ this.init?.();
188
+ if (__privateGet(this, _transportType) === "sse") {
189
+ __privateSet(this, _transport, new McpSSETransport(() => this.getWebSocket()));
190
+ await this.server.connect(__privateGet(this, _transport));
191
+ } else if (__privateGet(this, _transportType) === "streamable-http") {
192
+ __privateSet(this, _transport, new McpStreamableHttpTransport(
193
+ (id) => this.getWebSocketForResponseID(id),
194
+ (id) => __privateGet(this, _requestIdToConnectionId).delete(id)
195
+ ));
196
+ await this.server.connect(__privateGet(this, _transport));
197
+ }
198
+ }
199
+ async _init(props) {
200
+ await this.ctx.storage.put("props", props ?? {});
201
+ await this.ctx.storage.put("transportType", "unset");
202
+ this.props = props;
203
+ if (!this.initRun) {
204
+ this.initRun = true;
205
+ await this.init();
206
+ }
207
+ }
208
+ isInitialized() {
209
+ return this.initRun;
210
+ }
211
+ // Allow the worker to fetch a websocket connection to the agent
212
+ async fetch(request) {
213
+ if (__privateGet(this, _status) !== "started") {
214
+ await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
215
+ }
216
+ if (request.headers.get("Upgrade") !== "websocket") {
217
+ return new Response("Expected WebSocket Upgrade request", {
218
+ status: 400
219
+ });
220
+ }
221
+ const url = new URL(request.url);
222
+ const path = url.pathname;
223
+ switch (path) {
224
+ case "/sse": {
225
+ const websockets = this.ctx.getWebSockets();
226
+ if (websockets.length > 0) {
227
+ return new Response("Websocket already connected", { status: 400 });
228
+ }
229
+ await this.ctx.storage.put("transportType", "sse");
230
+ __privateSet(this, _transportType, "sse");
231
+ if (!__privateGet(this, _transport)) {
232
+ __privateSet(this, _transport, new McpSSETransport(() => this.getWebSocket()));
233
+ await this.server.connect(__privateGet(this, _transport));
234
+ }
235
+ return __privateGet(this, _agent).fetch(request);
236
+ }
237
+ case "/streamable-http": {
238
+ if (!__privateGet(this, _transport)) {
239
+ __privateSet(this, _transport, new McpStreamableHttpTransport(
240
+ (id) => this.getWebSocketForResponseID(id),
241
+ (id) => __privateGet(this, _requestIdToConnectionId).delete(id)
242
+ ));
243
+ await this.server.connect(__privateGet(this, _transport));
244
+ }
245
+ await this.ctx.storage.put("transportType", "streamable-http");
246
+ __privateSet(this, _transportType, "streamable-http");
247
+ return __privateGet(this, _agent).fetch(request);
248
+ }
249
+ default:
250
+ return new Response(
251
+ "Internal Server Error: Expected /sse or /streamable-http path",
252
+ {
253
+ status: 500
254
+ }
255
+ );
256
+ }
257
+ }
258
+ getWebSocket() {
259
+ const websockets = this.ctx.getWebSockets();
260
+ if (websockets.length === 0) {
261
+ return null;
262
+ }
263
+ return websockets[0];
264
+ }
265
+ getWebSocketForResponseID(id) {
266
+ const connectionId = __privateGet(this, _requestIdToConnectionId).get(id);
267
+ if (connectionId === void 0) {
268
+ return null;
269
+ }
270
+ return __privateGet(this, _agent).getConnection(connectionId) ?? null;
271
+ }
272
+ // All messages received here. This is currently never called
273
+ async onMessage(connection, event) {
274
+ if (__privateGet(this, _transportType) !== "streamable-http") {
275
+ const err = new Error(
276
+ "Internal Server Error: Expected streamable-http protocol"
277
+ );
278
+ __privateGet(this, _transport)?.onerror?.(err);
279
+ return;
280
+ }
281
+ let message;
282
+ try {
283
+ const data = typeof event === "string" ? event : new TextDecoder().decode(event);
284
+ message = JSONRPCMessageSchema.parse(JSON.parse(data));
285
+ } catch (error) {
286
+ __privateGet(this, _transport)?.onerror?.(error);
287
+ return;
288
+ }
289
+ if (isJSONRPCRequest(message)) {
290
+ __privateGet(this, _requestIdToConnectionId).set(message.id.toString(), connection.id);
291
+ }
292
+ __privateGet(this, _transport)?.onmessage?.(message);
293
+ }
294
+ // All messages received over SSE after the initial connection has been established
295
+ // will be passed here
296
+ async onSSEMcpMessage(sessionId, request) {
297
+ if (__privateGet(this, _status) !== "started") {
298
+ await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
299
+ }
300
+ if (__privateGet(this, _transportType) !== "sse") {
301
+ return new Error("Internal Server Error: Expected SSE protocol");
302
+ }
303
+ try {
304
+ const message = await request.json();
305
+ let parsedMessage;
306
+ try {
307
+ parsedMessage = JSONRPCMessageSchema.parse(message);
308
+ } catch (error) {
309
+ __privateGet(this, _transport)?.onerror?.(error);
310
+ throw error;
311
+ }
312
+ __privateGet(this, _transport)?.onmessage?.(parsedMessage);
313
+ return null;
314
+ } catch (error) {
315
+ __privateGet(this, _transport)?.onerror?.(error);
316
+ return error;
317
+ }
318
+ }
319
+ // Delegate all websocket events to the underlying agent
320
+ async webSocketMessage(ws, event) {
321
+ if (__privateGet(this, _status) !== "started") {
322
+ await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
323
+ }
324
+ return await __privateGet(this, _agent).webSocketMessage(ws, event);
325
+ }
326
+ // WebSocket event handlers for hibernation support
327
+ async webSocketError(ws, error) {
328
+ if (__privateGet(this, _status) !== "started") {
329
+ await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
330
+ }
331
+ return await __privateGet(this, _agent).webSocketError(ws, error);
332
+ }
333
+ async webSocketClose(ws, code, reason, wasClean) {
334
+ if (__privateGet(this, _status) !== "started") {
335
+ await __privateMethod(this, _McpAgent_instances, initialize_fn).call(this);
336
+ }
337
+ return await __privateGet(this, _agent).webSocketClose(ws, code, reason, wasClean);
338
+ }
339
+ static mount(path, {
340
+ binding = "MCP_OBJECT",
341
+ corsOptions
342
+ } = {}) {
343
+ return _McpAgent.serveSSE(path, { binding, corsOptions });
344
+ }
345
+ static serveSSE(path, {
346
+ binding = "MCP_OBJECT",
347
+ corsOptions
348
+ } = {}) {
349
+ let pathname = path;
350
+ if (path === "/") {
351
+ pathname = "/*";
352
+ }
353
+ const basePattern = new URLPattern({ pathname });
354
+ const messagePattern = new URLPattern({ pathname: `${pathname}/message` });
355
+ return {
356
+ fetch: async (request, env, ctx) => {
357
+ const corsResponse = handleCORS(request, corsOptions);
358
+ if (corsResponse) return corsResponse;
359
+ const url = new URL(request.url);
360
+ const namespace = env[binding];
361
+ if (request.method === "GET" && basePattern.test(url)) {
362
+ const sessionId = url.searchParams.get("sessionId") || namespace.newUniqueId().toString();
363
+ const { readable, writable } = new TransformStream();
364
+ const writer = writable.getWriter();
365
+ const encoder = new TextEncoder();
366
+ const endpointMessage = `event: endpoint
367
+ data: ${encodeURI(`${pathname}/message`)}?sessionId=${sessionId}
368
+
369
+ `;
370
+ writer.write(encoder.encode(endpointMessage));
371
+ const id = namespace.idFromName(`sse:${sessionId}`);
372
+ const doStub = namespace.get(id);
373
+ await doStub._init(ctx.props);
374
+ const upgradeUrl = new URL(request.url);
375
+ upgradeUrl.pathname = "/sse";
376
+ const response = await doStub.fetch(
377
+ new Request(upgradeUrl, {
378
+ headers: {
379
+ Upgrade: "websocket",
380
+ // Required by PartyServer
381
+ "x-partykit-room": sessionId
382
+ }
383
+ })
384
+ );
385
+ const ws = response.webSocket;
386
+ if (!ws) {
387
+ console.error("Failed to establish WebSocket connection");
388
+ await writer.close();
389
+ return new Response("Failed to establish WebSocket connection", {
390
+ status: 500
391
+ });
392
+ }
393
+ ws.accept();
394
+ ws.addEventListener("message", (event) => {
395
+ try {
396
+ const message = JSON.parse(event.data);
397
+ const result = JSONRPCMessageSchema.safeParse(message);
398
+ if (!result.success) {
399
+ return;
400
+ }
401
+ const messageText = `event: message
402
+ data: ${JSON.stringify(result.data)}
403
+
404
+ `;
405
+ Promise.resolve(writer.write(encoder.encode(messageText)));
406
+ } catch (error) {
407
+ console.error("Error forwarding message to SSE:", error);
408
+ }
409
+ });
410
+ ws.addEventListener("error", (error) => {
411
+ try {
412
+ Promise.resolve(writer.close());
413
+ } catch (e) {
414
+ }
415
+ });
416
+ ws.addEventListener("close", () => {
417
+ try {
418
+ Promise.resolve(writer.close());
419
+ } catch (error) {
420
+ console.error("Error closing SSE connection:", error);
421
+ }
422
+ });
423
+ return new Response(readable, {
424
+ headers: {
425
+ "Content-Type": "text/event-stream",
426
+ "Cache-Control": "no-cache",
427
+ Connection: "keep-alive",
428
+ "Access-Control-Allow-Origin": corsOptions?.origin || "*"
429
+ }
430
+ });
431
+ }
432
+ if (request.method === "POST" && messagePattern.test(url)) {
433
+ const sessionId = url.searchParams.get("sessionId");
434
+ if (!sessionId) {
435
+ return new Response(
436
+ `Missing sessionId. Expected POST to ${pathname} to initiate new one`,
437
+ { status: 400 }
438
+ );
439
+ }
440
+ const contentType = request.headers.get("content-type") || "";
441
+ if (!contentType.includes("application/json")) {
442
+ return new Response(`Unsupported content-type: ${contentType}`, {
443
+ status: 400
444
+ });
445
+ }
446
+ const contentLength = Number.parseInt(
447
+ request.headers.get("content-length") || "0",
448
+ 10
449
+ );
450
+ if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
451
+ return new Response(
452
+ `Request body too large: ${contentLength} bytes`,
453
+ {
454
+ status: 400
455
+ }
456
+ );
457
+ }
458
+ const id = namespace.idFromName(`sse:${sessionId}`);
459
+ const doStub = namespace.get(id);
460
+ const error = await doStub.onSSEMcpMessage(sessionId, request);
461
+ if (error) {
462
+ return new Response(error.message, {
463
+ status: 400,
464
+ headers: {
465
+ "Content-Type": "text/event-stream",
466
+ "Cache-Control": "no-cache",
467
+ Connection: "keep-alive",
468
+ "Access-Control-Allow-Origin": corsOptions?.origin || "*"
469
+ }
470
+ });
471
+ }
472
+ return new Response("Accepted", {
473
+ status: 202,
474
+ headers: {
475
+ "Content-Type": "text/event-stream",
476
+ "Cache-Control": "no-cache",
477
+ Connection: "keep-alive",
478
+ "Access-Control-Allow-Origin": corsOptions?.origin || "*"
479
+ }
480
+ });
481
+ }
482
+ return new Response("Not Found", { status: 404 });
483
+ }
484
+ };
485
+ }
486
+ static serve(path, {
487
+ binding = "MCP_OBJECT",
488
+ corsOptions
489
+ } = {}) {
490
+ let pathname = path;
491
+ if (path === "/") {
492
+ pathname = "/*";
493
+ }
494
+ const basePattern = new URLPattern({ pathname });
495
+ return {
496
+ fetch: async (request, env, ctx) => {
497
+ const corsResponse = handleCORS(request, corsOptions);
498
+ if (corsResponse) {
499
+ return corsResponse;
500
+ }
501
+ const url = new URL(request.url);
502
+ const namespace = env[binding];
503
+ if (request.method === "POST" && basePattern.test(url)) {
504
+ const acceptHeader = request.headers.get("accept");
505
+ if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) {
506
+ const body2 = JSON.stringify({
507
+ jsonrpc: "2.0",
508
+ error: {
509
+ code: -32e3,
510
+ message: "Not Acceptable: Client must accept both application/json and text/event-stream"
511
+ },
512
+ id: null
513
+ });
514
+ return new Response(body2, { status: 406 });
515
+ }
516
+ const ct = request.headers.get("content-type");
517
+ if (!ct || !ct.includes("application/json")) {
518
+ const body2 = JSON.stringify({
519
+ jsonrpc: "2.0",
520
+ error: {
521
+ code: -32e3,
522
+ message: "Unsupported Media Type: Content-Type must be application/json"
523
+ },
524
+ id: null
525
+ });
526
+ return new Response(body2, { status: 415 });
527
+ }
528
+ const contentLength = Number.parseInt(
529
+ request.headers.get("content-length") ?? "0",
530
+ 10
531
+ );
532
+ if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) {
533
+ const body2 = JSON.stringify({
534
+ jsonrpc: "2.0",
535
+ error: {
536
+ code: -32e3,
537
+ message: `Request body too large. Maximum size is ${MAXIMUM_MESSAGE_SIZE_BYTES} bytes`
538
+ },
539
+ id: null
540
+ });
541
+ return new Response(body2, { status: 413 });
542
+ }
543
+ let sessionId = request.headers.get("mcp-session-id");
544
+ let rawMessage;
545
+ try {
546
+ rawMessage = await request.json();
547
+ } catch (error) {
548
+ const body2 = JSON.stringify({
549
+ jsonrpc: "2.0",
550
+ error: {
551
+ code: -32700,
552
+ message: "Parse error: Invalid JSON"
553
+ },
554
+ id: null
555
+ });
556
+ return new Response(body2, { status: 400 });
557
+ }
558
+ let arrayMessage;
559
+ if (Array.isArray(rawMessage)) {
560
+ arrayMessage = rawMessage;
561
+ } else {
562
+ arrayMessage = [rawMessage];
563
+ }
564
+ let messages = [];
565
+ for (const msg of arrayMessage) {
566
+ if (!JSONRPCMessageSchema.safeParse(msg).success) {
567
+ const body2 = JSON.stringify({
568
+ jsonrpc: "2.0",
569
+ error: {
570
+ code: -32700,
571
+ message: "Parse error: Invalid JSON-RPC message"
572
+ },
573
+ id: null
574
+ });
575
+ return new Response(body2, { status: 400 });
576
+ }
577
+ }
578
+ messages = arrayMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
579
+ const isInitializationRequest = messages.some(
580
+ (msg) => InitializeRequestSchema.safeParse(msg).success
581
+ );
582
+ if (isInitializationRequest && sessionId) {
583
+ const body2 = JSON.stringify({
584
+ jsonrpc: "2.0",
585
+ error: {
586
+ code: -32600,
587
+ message: "Invalid Request: Initialization requests must not include a sessionId"
588
+ },
589
+ id: null
590
+ });
591
+ return new Response(body2, { status: 400 });
592
+ }
593
+ if (isInitializationRequest && messages.length > 1) {
594
+ const body2 = JSON.stringify({
595
+ jsonrpc: "2.0",
596
+ error: {
597
+ code: -32600,
598
+ message: "Invalid Request: Only one initialization request is allowed"
599
+ },
600
+ id: null
601
+ });
602
+ return new Response(body2, { status: 400 });
603
+ }
604
+ if (!isInitializationRequest && !sessionId) {
605
+ const body2 = JSON.stringify({
606
+ jsonrpc: "2.0",
607
+ error: {
608
+ code: -32e3,
609
+ message: "Bad Request: Mcp-Session-Id header is required"
610
+ },
611
+ id: null
612
+ });
613
+ return new Response(body2, { status: 400 });
614
+ }
615
+ sessionId = sessionId ?? namespace.newUniqueId().toString();
616
+ const id = namespace.idFromName(`streamable-http:${sessionId}`);
617
+ const doStub = namespace.get(id);
618
+ const isInitialized = await doStub.isInitialized();
619
+ if (isInitializationRequest) {
620
+ await doStub._init(ctx.props);
621
+ } else if (!isInitialized) {
622
+ const body2 = JSON.stringify({
623
+ jsonrpc: "2.0",
624
+ error: {
625
+ code: -32001,
626
+ message: "Session not found"
627
+ },
628
+ id: null
629
+ });
630
+ return new Response(body2, { status: 404 });
631
+ }
632
+ const { readable, writable } = new TransformStream();
633
+ const writer = writable.getWriter();
634
+ const encoder = new TextEncoder();
635
+ const upgradeUrl = new URL(request.url);
636
+ upgradeUrl.pathname = "/streamable-http";
637
+ const response = await doStub.fetch(
638
+ new Request(upgradeUrl, {
639
+ headers: {
640
+ Upgrade: "websocket",
641
+ // Required by PartyServer
642
+ "x-partykit-room": sessionId
643
+ }
644
+ })
645
+ );
646
+ const ws = response.webSocket;
647
+ if (!ws) {
648
+ console.error("Failed to establish WebSocket connection");
649
+ await writer.close();
650
+ const body2 = JSON.stringify({
651
+ jsonrpc: "2.0",
652
+ error: {
653
+ code: -32001,
654
+ message: "Failed to establish WebSocket connection"
655
+ },
656
+ id: null
657
+ });
658
+ return new Response(body2, { status: 500 });
659
+ }
660
+ const requestIds = /* @__PURE__ */ new Set();
661
+ ws.accept();
662
+ ws.addEventListener("message", (event) => {
663
+ try {
664
+ const data = typeof event.data === "string" ? event.data : new TextDecoder().decode(event.data);
665
+ const message = JSON.parse(data);
666
+ const result = JSONRPCMessageSchema.safeParse(message);
667
+ if (!result.success) {
668
+ return;
669
+ }
670
+ if (isJSONRPCResponse(result.data) || isJSONRPCError(result.data)) {
671
+ requestIds.delete(result.data.id);
672
+ }
673
+ const messageText = `event: message
674
+ data: ${JSON.stringify(result.data)}
675
+
676
+ `;
677
+ Promise.resolve(writer.write(encoder.encode(messageText)));
678
+ if (requestIds.size === 0) {
679
+ ws.close();
680
+ }
681
+ } catch (error) {
682
+ console.error("Error forwarding message to SSE:", error);
683
+ }
684
+ });
685
+ ws.addEventListener("error", (error) => {
686
+ try {
687
+ Promise.resolve(writer.close());
688
+ } catch (e) {
689
+ }
690
+ });
691
+ ws.addEventListener("close", () => {
692
+ try {
693
+ Promise.resolve(writer.close());
694
+ } catch (error) {
695
+ console.error("Error closing SSE connection:", error);
696
+ }
697
+ });
698
+ const hasOnlyNotificationsOrResponses = messages.every(
699
+ (msg) => isJSONRPCNotification(msg) || isJSONRPCResponse(msg)
700
+ );
701
+ if (hasOnlyNotificationsOrResponses) {
702
+ for (const message of messages) {
703
+ ws.send(JSON.stringify(message));
704
+ }
705
+ ws.close();
706
+ return new Response(null, { status: 202 });
707
+ }
708
+ for (const message of messages) {
709
+ if (isJSONRPCRequest(message)) {
710
+ requestIds.add(message.id);
711
+ }
712
+ ws.send(JSON.stringify(message));
713
+ }
714
+ return new Response(readable, {
715
+ headers: {
716
+ "Content-Type": "text/event-stream",
717
+ "Cache-Control": "no-cache",
718
+ Connection: "keep-alive",
719
+ "mcp-session-id": sessionId,
720
+ "Access-Control-Allow-Origin": corsOptions?.origin || "*"
721
+ },
722
+ status: 200
723
+ });
724
+ }
725
+ const body = JSON.stringify({
726
+ jsonrpc: "2.0",
727
+ error: {
728
+ code: -32e3,
729
+ message: "Method not allowed"
730
+ },
731
+ id: null
732
+ });
733
+ return new Response(body, { status: 405 });
734
+ }
735
+ };
736
+ }
737
+ };
738
+ _status = new WeakMap();
739
+ _transport = new WeakMap();
740
+ _transportType = new WeakMap();
741
+ _requestIdToConnectionId = new WeakMap();
742
+ _agent = new WeakMap();
743
+ _McpAgent_instances = new WeakSet();
744
+ initialize_fn = async function() {
745
+ await this.ctx.blockConcurrencyWhile(async () => {
746
+ __privateSet(this, _status, "starting");
747
+ await this.onStart();
748
+ __privateSet(this, _status, "started");
749
+ });
750
+ };
751
+ var McpAgent = _McpAgent;
752
+ export {
753
+ McpAgent
754
+ };
755
+ //# sourceMappingURL=index.js.map