agents 0.0.0-ed3f94d → 0.0.0-edd3357

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.
Files changed (60) hide show
  1. package/dist/ai-chat-agent.d.ts +1 -2
  2. package/dist/ai-chat-agent.js +57 -350
  3. package/dist/ai-chat-agent.js.map +1 -1
  4. package/dist/ai-chat-v5-migration.js +0 -1
  5. package/dist/ai-react.d.ts +1 -8
  6. package/dist/ai-react.js +111 -157
  7. package/dist/ai-react.js.map +1 -1
  8. package/dist/ai-types.d.ts +0 -1
  9. package/dist/ai-types.js +1 -2
  10. package/dist/{chunk-BER7KXUJ.js → chunk-AVYJQSLW.js} +1 -2
  11. package/dist/chunk-AVYJQSLW.js.map +1 -0
  12. package/dist/{chunk-Z44WASMA.js → chunk-LL2AFX7V.js} +2 -7
  13. package/dist/{chunk-Z44WASMA.js.map → chunk-LL2AFX7V.js.map} +1 -1
  14. package/dist/{chunk-3OT2NNEW.js → chunk-MH46VMM4.js} +67 -396
  15. package/dist/chunk-MH46VMM4.js.map +1 -0
  16. package/dist/{chunk-254F4GDT.js → chunk-YDUDMOL6.js} +50 -97
  17. package/dist/chunk-YDUDMOL6.js.map +1 -0
  18. package/dist/{client-DVoPb3-C.d.ts → client-CvaJdLQA.d.ts} +26 -131
  19. package/dist/client.js +1 -2
  20. package/dist/index.d.ts +32 -25
  21. package/dist/index.js +4 -5
  22. package/dist/mcp/client.d.ts +1 -2
  23. package/dist/mcp/client.js +1 -2
  24. package/dist/mcp/do-oauth-client-provider.js +1 -2
  25. package/dist/mcp/index.d.ts +31 -13
  26. package/dist/mcp/index.js +163 -233
  27. package/dist/mcp/index.js.map +1 -1
  28. package/dist/observability/index.d.ts +24 -12
  29. package/dist/observability/index.js +4 -5
  30. package/dist/react.d.ts +6 -10
  31. package/dist/react.js +3 -101
  32. package/dist/react.js.map +1 -1
  33. package/dist/schedule.js +0 -2
  34. package/dist/schedule.js.map +1 -1
  35. package/package.json +6 -19
  36. package/src/index.ts +57 -141
  37. package/dist/_esm-LV5FJ3HK.js +0 -3922
  38. package/dist/_esm-LV5FJ3HK.js.map +0 -1
  39. package/dist/ccip-CMBYN64O.js +0 -15
  40. package/dist/ccip-CMBYN64O.js.map +0 -1
  41. package/dist/chunk-254F4GDT.js.map +0 -1
  42. package/dist/chunk-3OT2NNEW.js.map +0 -1
  43. package/dist/chunk-5Y6BEZDY.js +0 -276
  44. package/dist/chunk-5Y6BEZDY.js.map +0 -1
  45. package/dist/chunk-BER7KXUJ.js.map +0 -1
  46. package/dist/chunk-JJBFIGUC.js +0 -5202
  47. package/dist/chunk-JJBFIGUC.js.map +0 -1
  48. package/dist/chunk-PR4QN5HX.js +0 -43
  49. package/dist/chunk-PR4QN5HX.js.map +0 -1
  50. package/dist/chunk-TYAY6AU6.js +0 -159
  51. package/dist/chunk-TYAY6AU6.js.map +0 -1
  52. package/dist/codemode/ai.d.ts +0 -25
  53. package/dist/codemode/ai.js +0 -5112
  54. package/dist/codemode/ai.js.map +0 -1
  55. package/dist/mcp/x402.d.ts +0 -39
  56. package/dist/mcp/x402.js +0 -3195
  57. package/dist/mcp/x402.js.map +0 -1
  58. package/dist/mcp-BH1fJeiU.d.ts +0 -58
  59. package/dist/secp256k1-M22GZP2U.js +0 -2193
  60. package/dist/secp256k1-M22GZP2U.js.map +0 -1
package/dist/mcp/index.js CHANGED
@@ -1,21 +1,21 @@
1
1
  import {
2
2
  Agent,
3
- getAgentByName,
4
- getCurrentAgent
5
- } from "../chunk-254F4GDT.js";
3
+ getAgentByName
4
+ } from "../chunk-YDUDMOL6.js";
6
5
  import {
7
6
  SSEEdgeClientTransport,
8
7
  StreamableHTTPEdgeClientTransport
9
- } from "../chunk-3OT2NNEW.js";
10
- import "../chunk-Z44WASMA.js";
8
+ } from "../chunk-MH46VMM4.js";
9
+ import "../chunk-LL2AFX7V.js";
11
10
  import "../chunk-QEVM4BVL.js";
12
- import "../chunk-BER7KXUJ.js";
13
- import "../chunk-PR4QN5HX.js";
11
+ import "../chunk-AVYJQSLW.js";
14
12
 
15
13
  // src/mcp/index.ts
16
14
  import {
17
- JSONRPCMessageSchema as JSONRPCMessageSchema3,
18
- isJSONRPCError as isJSONRPCError2,
15
+ JSONRPCMessageSchema as JSONRPCMessageSchema2,
16
+ isJSONRPCError as isJSONRPCError3,
17
+ isJSONRPCNotification as isJSONRPCNotification2,
18
+ isJSONRPCRequest as isJSONRPCRequest2,
19
19
  isJSONRPCResponse as isJSONRPCResponse3
20
20
  } from "@modelcontextprotocol/sdk/types.js";
21
21
 
@@ -24,10 +24,12 @@ import {
24
24
  JSONRPCMessageSchema,
25
25
  InitializeRequestSchema,
26
26
  isJSONRPCResponse,
27
- isJSONRPCNotification
27
+ isJSONRPCError,
28
+ isJSONRPCNotification,
29
+ isJSONRPCRequest
28
30
  } from "@modelcontextprotocol/sdk/types.js";
29
- var MCP_HTTP_METHOD_HEADER = "cf-mcp-method";
30
- var MCP_MESSAGE_HEADER = "cf-mcp-message";
31
+ var STANDALONE_SSE_MARKER = "standalone-sse";
32
+ var STANDALONE_SSE_METHOD = "cf/standalone_sse/attach";
31
33
  var MAXIMUM_MESSAGE_SIZE_BYTES = 4 * 1024 * 1024;
32
34
  var createStreamingHttpHandler = (basePath, namespace, corsOptions) => {
33
35
  let pathname = basePath;
@@ -178,8 +180,6 @@ var createStreamingHttpHandler = (basePath, namespace, corsOptions) => {
178
180
  const req = new Request(request.url, {
179
181
  headers: {
180
182
  ...existingHeaders,
181
- [MCP_HTTP_METHOD_HEADER]: "POST",
182
- [MCP_MESSAGE_HEADER]: JSON.stringify(messages),
183
183
  Upgrade: "websocket"
184
184
  }
185
185
  });
@@ -199,17 +199,26 @@ var createStreamingHttpHandler = (basePath, namespace, corsOptions) => {
199
199
  });
200
200
  return new Response(body2, { status: 500 });
201
201
  }
202
+ const requestIds = /* @__PURE__ */ new Set();
202
203
  ws.accept();
203
204
  ws.addEventListener("message", (event) => {
204
205
  async function onMessage(event2) {
205
206
  try {
206
207
  const data = typeof event2.data === "string" ? event2.data : new TextDecoder().decode(event2.data);
207
208
  const message = JSON.parse(data);
208
- if (message.type !== "cf_mcp_agent_event" /* CF_MCP_AGENT_EVENT */) {
209
+ const result = JSONRPCMessageSchema.safeParse(message);
210
+ if (!result.success) {
209
211
  return;
210
212
  }
211
- await writer.write(encoder.encode(message.event));
212
- if (message.close) {
213
+ if (isJSONRPCResponse(result.data) || isJSONRPCError(result.data)) {
214
+ requestIds.delete(result.data.id);
215
+ }
216
+ const messageText = `event: message
217
+ data: ${JSON.stringify(result.data)}
218
+
219
+ `;
220
+ await writer.write(encoder.encode(messageText));
221
+ if (requestIds.size === 0) {
213
222
  ws?.close();
214
223
  await writer.close().catch(() => {
215
224
  });
@@ -238,12 +247,21 @@ var createStreamingHttpHandler = (basePath, namespace, corsOptions) => {
238
247
  (msg) => isJSONRPCNotification(msg) || isJSONRPCResponse(msg)
239
248
  );
240
249
  if (hasOnlyNotificationsOrResponses) {
250
+ for (const message of messages) {
251
+ ws.send(JSON.stringify(message));
252
+ }
241
253
  ws.close();
242
254
  return new Response(null, {
243
255
  headers: corsHeaders(request, corsOptions),
244
256
  status: 202
245
257
  });
246
258
  }
259
+ for (const message of messages) {
260
+ if (isJSONRPCRequest(message)) {
261
+ requestIds.add(message.id);
262
+ }
263
+ ws.send(JSON.stringify(message));
264
+ }
247
265
  return new Response(readable, {
248
266
  headers: {
249
267
  "Cache-Control": "no-cache",
@@ -269,17 +287,7 @@ var createStreamingHttpHandler = (basePath, namespace, corsOptions) => {
269
287
  }
270
288
  const sessionId = request.headers.get("mcp-session-id");
271
289
  if (!sessionId)
272
- return new Response(
273
- JSON.stringify({
274
- error: {
275
- code: -32e3,
276
- message: "Bad Request: Mcp-Session-Id header is required"
277
- },
278
- id: null,
279
- jsonrpc: "2.0"
280
- }),
281
- { status: 400 }
282
- );
290
+ return new Response("Missing sessionId", { status: 400 });
283
291
  const { readable, writable } = new TransformStream();
284
292
  const writer = writable.getWriter();
285
293
  const encoder = new TextEncoder();
@@ -308,7 +316,6 @@ var createStreamingHttpHandler = (basePath, namespace, corsOptions) => {
308
316
  new Request(request.url, {
309
317
  headers: {
310
318
  ...existingHeaders,
311
- [MCP_HTTP_METHOD_HEADER]: "GET",
312
319
  Upgrade: "websocket"
313
320
  }
314
321
  })
@@ -321,15 +328,24 @@ var createStreamingHttpHandler = (basePath, namespace, corsOptions) => {
321
328
  });
322
329
  }
323
330
  ws.accept();
331
+ ws.send(
332
+ JSON.stringify({
333
+ jsonrpc: "2.0",
334
+ method: STANDALONE_SSE_METHOD,
335
+ params: {}
336
+ })
337
+ );
324
338
  ws.addEventListener("message", (event) => {
325
339
  try {
326
340
  async function onMessage(ev) {
327
341
  const data = typeof ev.data === "string" ? ev.data : new TextDecoder().decode(ev.data);
328
- const message = JSON.parse(data);
329
- if (message.type !== "cf_mcp_agent_event" /* CF_MCP_AGENT_EVENT */) {
330
- return;
331
- }
332
- await writer.write(encoder.encode(message.event));
342
+ const parsed = JSONRPCMessageSchema.safeParse(JSON.parse(data));
343
+ if (!parsed.success) return;
344
+ const frame = `event: message
345
+ data: ${JSON.stringify(parsed.data)}
346
+
347
+ `;
348
+ await writer.write(encoder.encode(frame));
333
349
  }
334
350
  onMessage(event).catch(console.error);
335
351
  } catch (e) {
@@ -572,10 +588,8 @@ function isDurableObjectNamespace(namespace) {
572
588
 
573
589
  // src/mcp/transport.ts
574
590
  import {
575
- isJSONRPCError,
576
- isJSONRPCRequest,
577
- isJSONRPCResponse as isJSONRPCResponse2,
578
- JSONRPCMessageSchema as JSONRPCMessageSchema2
591
+ isJSONRPCError as isJSONRPCError2,
592
+ isJSONRPCResponse as isJSONRPCResponse2
579
593
  } from "@modelcontextprotocol/sdk/types.js";
580
594
  var McpSSETransport = class {
581
595
  constructor(getWebSocket) {
@@ -606,190 +620,59 @@ var McpSSETransport = class {
606
620
  this.onclose?.();
607
621
  }
608
622
  };
609
- var StreamableHTTPServerTransport = class {
610
- constructor(options) {
623
+ var McpStreamableHttpTransport = class {
624
+ constructor(getWebSocketForMessageID, notifyResponseIdSent, getWebSocketForStandaloneSse) {
611
625
  this._started = false;
612
- // This is to keep track whether all messages from a single POST request have been answered.
613
- // I's fine that we don't persist this since it's only for backwards compatibility as clients
614
- // should no longer batch requests, per the spec.
615
- this._requestResponseMap = /* @__PURE__ */ new Map();
616
- const { agent } = getCurrentAgent();
617
- if (!agent)
618
- throw new Error("McpAgent was not found in Transport constructor");
619
- this.sessionId = agent.getSessionId();
620
- this._eventStore = options.eventStore;
626
+ this._getWebSocketForMessageID = getWebSocketForMessageID;
627
+ this._notifyResponseIdSent = notifyResponseIdSent;
628
+ this._getWebSocketForStandaloneSse = getWebSocketForStandaloneSse;
621
629
  }
622
- /**
623
- * Starts the transport. This is required by the Transport interface but is a no-op
624
- * for the Streamable HTTP transport as connections are managed per-request.
625
- */
626
630
  async start() {
627
631
  if (this._started) {
628
632
  throw new Error("Transport already started");
629
633
  }
630
634
  this._started = true;
631
635
  }
632
- /**
633
- * Handles GET requests for SSE stream
634
- */
635
- async handleGetRequest(req) {
636
- const { connection } = getCurrentAgent();
637
- if (!connection)
638
- throw new Error("Connection was not found in handleGetRequest");
639
- if (this._eventStore) {
640
- const lastEventId = req.headers.get("last-event-id");
641
- if (lastEventId) {
642
- await this.replayEvents(lastEventId);
643
- return;
644
- }
645
- }
646
- connection.setState({
647
- _standaloneSse: true
648
- });
649
- }
650
- /**
651
- * Replays events that would have been sent after the specified event ID
652
- * Only used when resumability is enabled
653
- */
654
- async replayEvents(lastEventId) {
655
- if (!this._eventStore) {
656
- return;
657
- }
658
- const { connection } = getCurrentAgent();
659
- if (!connection)
660
- throw new Error("Connection was not available in replayEvents");
661
- try {
662
- await this._eventStore?.replayEventsAfter(lastEventId, {
663
- send: async (eventId, message) => {
664
- try {
665
- this.writeSSEEvent(connection, message, eventId);
666
- } catch (error) {
667
- this.onerror?.(error);
668
- }
669
- }
670
- });
671
- } catch (error) {
672
- this.onerror?.(error);
673
- }
674
- }
675
- /**
676
- * Writes an event to the SSE stream with proper formatting
677
- */
678
- writeSSEEvent(connection, message, eventId, close) {
679
- let eventData = "event: message\n";
680
- if (eventId) {
681
- eventData += `id: ${eventId}
682
- `;
683
- }
684
- eventData += `data: ${JSON.stringify(message)}
685
-
686
- `;
687
- return connection.send(
688
- JSON.stringify({
689
- type: "cf_mcp_agent_event" /* CF_MCP_AGENT_EVENT */,
690
- event: eventData,
691
- close
692
- })
693
- );
694
- }
695
- /**
696
- * Handles POST requests containing JSON-RPC messages
697
- */
698
- async handlePostRequest(req, parsedBody) {
699
- const authInfo = req.auth;
700
- const requestInfo = {
701
- headers: Object.fromEntries(req.headers.entries())
702
- };
703
- delete requestInfo.headers[MCP_HTTP_METHOD_HEADER];
704
- delete requestInfo.headers[MCP_MESSAGE_HEADER];
705
- delete requestInfo.headers.upgrade;
706
- const rawMessage = parsedBody;
707
- let messages;
708
- if (Array.isArray(rawMessage)) {
709
- messages = rawMessage.map((msg) => JSONRPCMessageSchema2.parse(msg));
710
- } else {
711
- messages = [JSONRPCMessageSchema2.parse(rawMessage)];
712
- }
713
- const hasRequests = messages.some(isJSONRPCRequest);
714
- if (!hasRequests) {
715
- for (const message of messages) {
716
- this.onmessage?.(message, { authInfo, requestInfo });
717
- }
718
- } else if (hasRequests) {
719
- const { connection } = getCurrentAgent();
720
- if (!connection)
721
- throw new Error("Connection was not found in handlePostRequest");
722
- const requestIds = messages.filter(isJSONRPCRequest).map((message) => message.id);
723
- connection.setState({
724
- requestIds
725
- });
726
- for (const message of messages) {
727
- this.onmessage?.(message, { authInfo, requestInfo });
728
- }
729
- }
730
- }
731
- async close() {
732
- const { agent } = getCurrentAgent();
733
- if (!agent) throw new Error("Agent was not found in close");
734
- for (const conn of agent.getConnections()) {
735
- conn.close(1e3, "Session closed");
736
- }
737
- this.onclose?.();
738
- }
739
636
  async send(message, options) {
740
- const { agent } = getCurrentAgent();
741
- if (!agent) throw new Error("Agent was not found in send");
637
+ if (!this._started) {
638
+ throw new Error("Transport not started");
639
+ }
742
640
  let requestId = options?.relatedRequestId;
743
- if (isJSONRPCResponse2(message) || isJSONRPCError(message)) {
641
+ if (isJSONRPCResponse2(message) || isJSONRPCError2(message)) {
744
642
  requestId = message.id;
745
643
  }
746
644
  if (requestId === void 0) {
747
- if (isJSONRPCResponse2(message) || isJSONRPCError(message)) {
645
+ if (isJSONRPCResponse2(message) || isJSONRPCError2(message)) {
748
646
  throw new Error(
749
647
  "Cannot send a response on a standalone SSE stream unless resuming a previous client request"
750
648
  );
751
649
  }
752
- let standaloneConnection;
753
- for (const conn of agent.getConnections()) {
754
- if (conn.state?._standaloneSse) standaloneConnection = conn;
755
- }
756
- if (standaloneConnection === void 0) {
650
+ const standaloneSseSocket = this._getWebSocketForStandaloneSse();
651
+ if (!standaloneSseSocket) {
757
652
  return;
758
653
  }
759
- let eventId2;
760
- if (this._eventStore) {
761
- eventId2 = await this._eventStore.storeEvent(
762
- standaloneConnection.id,
763
- message
764
- );
654
+ try {
655
+ standaloneSseSocket?.send(JSON.stringify(message));
656
+ } catch (error) {
657
+ this.onerror?.(error);
765
658
  }
766
- this.writeSSEEvent(standaloneConnection, message, eventId2);
767
659
  return;
768
660
  }
769
- const connection = Array.from(
770
- agent.getConnections()
771
- ).find((conn) => conn.state?.requestIds?.includes(requestId));
772
- if (!connection) {
773
- throw new Error(
774
- `No connection established for request ID: ${String(requestId)}`
775
- );
776
- }
777
- let eventId;
778
- if (this._eventStore) {
779
- eventId = await this._eventStore.storeEvent(connection.id, message);
661
+ const websocket = this._getWebSocketForMessageID(requestId.toString());
662
+ if (!websocket) {
663
+ throw new Error(`Could not find WebSocket for message id: ${requestId}`);
780
664
  }
781
- let shouldClose = false;
782
- if (isJSONRPCResponse2(message) || isJSONRPCError(message)) {
783
- this._requestResponseMap.set(requestId, message);
784
- const relatedIds = connection.state?.requestIds ?? [];
785
- shouldClose = relatedIds.every((id) => this._requestResponseMap.has(id));
786
- if (shouldClose) {
787
- for (const id of relatedIds) {
788
- this._requestResponseMap.delete(id);
789
- }
665
+ try {
666
+ websocket?.send(JSON.stringify(message));
667
+ if (isJSONRPCResponse2(message) || isJSONRPCError2(message)) {
668
+ this._notifyResponseIdSent(message.id.toString());
790
669
  }
670
+ } catch (error) {
671
+ this.onerror?.(error);
791
672
  }
792
- this.writeSSEEvent(connection, message, eventId, shouldClose);
673
+ }
674
+ async close() {
675
+ this.onclose?.();
793
676
  }
794
677
  };
795
678
 
@@ -798,6 +681,17 @@ import {
798
681
  ElicitRequestSchema
799
682
  } from "@modelcontextprotocol/sdk/types.js";
800
683
  var McpAgent = class _McpAgent extends Agent {
684
+ constructor(ctx, env) {
685
+ super(ctx, env);
686
+ this._requestIdToConnectionId = /* @__PURE__ */ new Map();
687
+ for (const connection of this.getConnections()) {
688
+ const meta = connection.state;
689
+ if (meta?.role === STANDALONE_SSE_MARKER) {
690
+ this._standaloneSseConnectionId = connection.id;
691
+ return;
692
+ }
693
+ }
694
+ }
801
695
  /*
802
696
  * Helpers
803
697
  */
@@ -824,18 +718,10 @@ var McpAgent = class _McpAgent extends Agent {
824
718
  );
825
719
  }
826
720
  }
827
- /** Read the sessionId for this agent.
828
- * This relies on the naming scheme being `sse:${sessionId}`
829
- * or `streamable-http:${sessionId}`.
830
- */
831
- getSessionId() {
832
- const [_, sessionId] = this.name.split(":");
833
- if (!sessionId) {
834
- throw new Error(
835
- "Invalid session id. McpAgent must be addressed with a valid session id."
836
- );
837
- }
838
- return sessionId;
721
+ /** Get the WebSocket for the standalone SSE if any. Streamable HTTP only. */
722
+ getWebSocketForStandaloneSse() {
723
+ if (!this._standaloneSseConnectionId) return null;
724
+ return this.getConnection(this._standaloneSseConnectionId) ?? null;
839
725
  }
840
726
  /** Get the unique WebSocket. SSE transport only. */
841
727
  getWebSocket() {
@@ -845,6 +731,14 @@ var McpAgent = class _McpAgent extends Agent {
845
731
  }
846
732
  return websockets[0];
847
733
  }
734
+ /** Get the corresponding WebSocket for a responseId. Streamable HTTP only. */
735
+ getWebSocketForResponseID(id) {
736
+ const connectionId = this._requestIdToConnectionId.get(id);
737
+ if (connectionId === void 0) {
738
+ return null;
739
+ }
740
+ return this.getConnection(connectionId) ?? null;
741
+ }
848
742
  /** Returns a new transport matching the type of the Agent. */
849
743
  initTransport() {
850
744
  switch (this.getTransportType()) {
@@ -852,7 +746,11 @@ var McpAgent = class _McpAgent extends Agent {
852
746
  return new McpSSETransport(() => this.getWebSocket());
853
747
  }
854
748
  case "streamable-http": {
855
- return new StreamableHTTPServerTransport({});
749
+ return new McpStreamableHttpTransport(
750
+ (id) => this.getWebSocketForResponseID(id),
751
+ (id) => this._requestIdToConnectionId.delete(id),
752
+ () => this.getWebSocketForStandaloneSse()
753
+ );
856
754
  }
857
755
  }
858
756
  }
@@ -861,12 +759,6 @@ var McpAgent = class _McpAgent extends Agent {
861
759
  await this.ctx.storage.put("props", props ?? {});
862
760
  this.props = props;
863
761
  }
864
- async reinitializeServer() {
865
- const initializeRequest = await this.getInitializeRequest();
866
- if (initializeRequest) {
867
- this._transport?.onmessage?.(initializeRequest);
868
- }
869
- }
870
762
  /*
871
763
  * Base Agent / Parykit Server overrides
872
764
  */
@@ -878,10 +770,13 @@ var McpAgent = class _McpAgent extends Agent {
878
770
  const server = await this.server;
879
771
  this._transport = this.initTransport();
880
772
  await server.connect(this._transport);
881
- await this.reinitializeServer();
773
+ const initializeRequest = await this.getInitializeRequest();
774
+ if (initializeRequest) {
775
+ this._transport.onmessage?.(initializeRequest);
776
+ }
882
777
  }
883
778
  /** Validates new WebSocket connections. */
884
- async onConnect(conn, { request: req }) {
779
+ async onConnect(conn, _) {
885
780
  switch (this.getTransportType()) {
886
781
  case "sse": {
887
782
  const websockets = Array.from(this.getConnections());
@@ -892,19 +787,54 @@ var McpAgent = class _McpAgent extends Agent {
892
787
  break;
893
788
  }
894
789
  case "streamable-http":
895
- if (this._transport instanceof StreamableHTTPServerTransport) {
896
- switch (req.headers.get(MCP_HTTP_METHOD_HEADER)) {
897
- case "POST": {
898
- const payloadHeader = req.headers.get(MCP_MESSAGE_HEADER);
899
- const parsedBody = await JSON.parse(payloadHeader ?? "{}");
900
- this._transport?.handlePostRequest(req, parsedBody);
901
- break;
902
- }
903
- case "GET":
904
- this._transport?.handleGetRequest(req);
905
- break;
906
- }
907
- }
790
+ break;
791
+ }
792
+ }
793
+ /** Handles MCP Messages for Streamable HTTP. */
794
+ async onMessage(connection, event) {
795
+ if (this.getTransportType() !== "streamable-http") {
796
+ const err = new Error(
797
+ "Internal Server Error: Expected streamable-http protocol"
798
+ );
799
+ this._transport?.onerror?.(err);
800
+ return;
801
+ }
802
+ let message;
803
+ try {
804
+ const data = typeof event === "string" ? event : new TextDecoder().decode(event);
805
+ message = JSONRPCMessageSchema2.parse(JSON.parse(data));
806
+ } catch (error) {
807
+ this._transport?.onerror?.(error);
808
+ return;
809
+ }
810
+ if (isJSONRPCNotification2(message) && message.method === STANDALONE_SSE_METHOD) {
811
+ if (this._standaloneSseConnectionId && this._standaloneSseConnectionId !== connection.id) {
812
+ const standaloneSseSocket = this.getConnection(
813
+ this._standaloneSseConnectionId
814
+ );
815
+ standaloneSseSocket?.close(1e3, "replaced");
816
+ }
817
+ connection.setState({
818
+ role: STANDALONE_SSE_MARKER
819
+ });
820
+ this._standaloneSseConnectionId = connection.id;
821
+ return;
822
+ }
823
+ if (await this._handleElicitationResponse(message)) {
824
+ return;
825
+ }
826
+ if (isJSONRPCRequest2(message)) {
827
+ this._requestIdToConnectionId.set(message.id.toString(), connection.id);
828
+ }
829
+ this._transport?.onmessage?.(message);
830
+ }
831
+ /** Remove clients from our cache when they disconnect */
832
+ async onClose(conn, _code, _reason, _wasClean) {
833
+ for (const [reqId, connId] of this._requestIdToConnectionId) {
834
+ if (connId === conn.id) this._requestIdToConnectionId.delete(reqId);
835
+ }
836
+ if (this._standaloneSseConnectionId === conn.id) {
837
+ this._standaloneSseConnectionId = void 0;
908
838
  }
909
839
  }
910
840
  /*
@@ -918,7 +848,7 @@ var McpAgent = class _McpAgent extends Agent {
918
848
  try {
919
849
  let parsedMessage;
920
850
  try {
921
- parsedMessage = JSONRPCMessageSchema3.parse(messageBody);
851
+ parsedMessage = JSONRPCMessageSchema2.parse(messageBody);
922
852
  } catch (error) {
923
853
  this._transport?.onerror?.(error);
924
854
  throw error;
@@ -1007,7 +937,7 @@ var McpAgent = class _McpAgent extends Agent {
1007
937
  );
1008
938
  return true;
1009
939
  }
1010
- if (isJSONRPCError2(message)) {
940
+ if (isJSONRPCError3(message)) {
1011
941
  const requestId = message.id?.toString();
1012
942
  if (!requestId || !requestId.startsWith("elicit_")) return false;
1013
943
  const pendingRequest = await this.ctx.storage.get(