agents 0.0.0-5908188 → 0.0.0-59ac254

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 (68) hide show
  1. package/README.md +5 -3
  2. package/dist/ai-chat-agent.d.ts +95 -13
  3. package/dist/ai-chat-agent.js +354 -74
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/{ai-chat-v5-migration-DBHGW4Hv.js → ai-chat-v5-migration-DguhuLKF.js} +1 -1
  6. package/dist/{ai-chat-v5-migration-DBHGW4Hv.js.map → ai-chat-v5-migration-DguhuLKF.js.map} +1 -1
  7. package/dist/ai-chat-v5-migration.js +1 -1
  8. package/dist/ai-react.d.ts +15 -9
  9. package/dist/ai-react.js +179 -29
  10. package/dist/ai-react.js.map +1 -1
  11. package/dist/{ai-types-B3aQaFv3.js → ai-types-CwgHzwUb.js} +5 -1
  12. package/dist/ai-types-CwgHzwUb.js.map +1 -0
  13. package/dist/{ai-types-D5YoPrBZ.d.ts → ai-types-D_hTbf25.d.ts} +15 -7
  14. package/dist/ai-types.d.ts +1 -1
  15. package/dist/ai-types.js +1 -1
  16. package/dist/cli/index.d.ts +1 -0
  17. package/dist/cli/index.js +28 -0
  18. package/dist/cli/index.js.map +1 -0
  19. package/dist/client-C_M5uPrn.d.ts +834 -0
  20. package/dist/{client-BfiZ3HQd.js → client-CcyhkGfN.js} +2 -2
  21. package/dist/{client-BfiZ3HQd.js.map → client-CcyhkGfN.js.map} +1 -1
  22. package/dist/{client-CbWe9FBd.d.ts → client-ClORm6f0.d.ts} +2 -2
  23. package/dist/client-QZa2Rq0l.js +1105 -0
  24. package/dist/client-QZa2Rq0l.js.map +1 -0
  25. package/dist/client.d.ts +2 -2
  26. package/dist/client.js +2 -2
  27. package/dist/codemode/ai.js +6 -5
  28. package/dist/codemode/ai.js.map +1 -1
  29. package/dist/context-BkKbAa1R.js +8 -0
  30. package/dist/context-BkKbAa1R.js.map +1 -0
  31. package/dist/context-_sPQqJWv.d.ts +24 -0
  32. package/dist/context.d.ts +6 -0
  33. package/dist/context.js +3 -0
  34. package/dist/{do-oauth-client-provider-DGc5pP0l.d.ts → do-oauth-client-provider-B-ryFIPr.d.ts} +20 -5
  35. package/dist/{do-oauth-client-provider-CswoD5Lu.js → do-oauth-client-provider-B1fVIshX.js} +70 -8
  36. package/dist/do-oauth-client-provider-B1fVIshX.js.map +1 -0
  37. package/dist/{index-DhJCaDWd.d.ts → index-CyDpAVHZ.d.ts} +2 -2
  38. package/dist/{index-BJOkI2Mo.d.ts → index-DUnsVDnf.d.ts} +83 -74
  39. package/dist/index.d.ts +34 -34
  40. package/dist/index.js +6 -5
  41. package/dist/mcp/client.d.ts +4 -4
  42. package/dist/mcp/client.js +2 -1
  43. package/dist/mcp/do-oauth-client-provider.d.ts +1 -1
  44. package/dist/mcp/do-oauth-client-provider.js +1 -1
  45. package/dist/mcp/index.d.ts +98 -24
  46. package/dist/mcp/index.js +298 -91
  47. package/dist/mcp/index.js.map +1 -1
  48. package/dist/mcp/x402.js +10 -6
  49. package/dist/mcp/x402.js.map +1 -1
  50. package/dist/{mcp-Dw5vDrY8.d.ts → mcp-CzbSsLfc.d.ts} +1 -1
  51. package/dist/observability/index.d.ts +2 -2
  52. package/dist/observability/index.js +6 -5
  53. package/dist/react-DbzUBop3.d.ts +131 -0
  54. package/dist/react.d.ts +15 -10
  55. package/dist/react.js +57 -57
  56. package/dist/react.js.map +1 -1
  57. package/dist/{serializable-CymX8ovI.d.ts → serializable-C4GLimgv.d.ts} +1 -1
  58. package/dist/serializable.d.ts +1 -1
  59. package/dist/{src-CTtjSFyX.js → src-BmbDclOA.js} +129 -179
  60. package/dist/src-BmbDclOA.js.map +1 -0
  61. package/package.json +53 -38
  62. package/dist/ai-types-B3aQaFv3.js.map +0 -1
  63. package/dist/client-BmMRlvlM.d.ts +0 -5313
  64. package/dist/client-CIvp_OWw.js +0 -786
  65. package/dist/client-CIvp_OWw.js.map +0 -1
  66. package/dist/do-oauth-client-provider-CswoD5Lu.js.map +0 -1
  67. package/dist/react-7YOau7tS.d.ts +0 -115
  68. package/dist/src-CTtjSFyX.js.map +0 -1
package/dist/mcp/index.js CHANGED
@@ -1,10 +1,13 @@
1
- import { t as MessageType } from "../ai-types-B3aQaFv3.js";
2
- import "../client-BfiZ3HQd.js";
3
- import { i as SSEEdgeClientTransport, r as StreamableHTTPEdgeClientTransport } from "../client-CIvp_OWw.js";
4
- import "../do-oauth-client-provider-CswoD5Lu.js";
5
- import { c as getCurrentAgent, s as getAgentByName, t as Agent } from "../src-CTtjSFyX.js";
1
+ import "../context-BkKbAa1R.js";
2
+ import { t as MessageType } from "../ai-types-CwgHzwUb.js";
3
+ import "../client-CcyhkGfN.js";
4
+ import "../client-QZa2Rq0l.js";
5
+ import "../do-oauth-client-provider-B1fVIshX.js";
6
+ import { c as getCurrentAgent, s as getAgentByName, t as Agent } from "../src-BmbDclOA.js";
6
7
  import { AsyncLocalStorage } from "node:async_hooks";
7
- import { ElicitRequestSchema, InitializeRequestSchema, JSONRPCMessageSchema, isInitializeRequest, isJSONRPCError, isJSONRPCNotification, isJSONRPCRequest, isJSONRPCResponse } from "@modelcontextprotocol/sdk/types.js";
8
+ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
9
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
10
+ import { ElicitRequestSchema, InitializeRequestSchema, JSONRPCMessageSchema, SUPPORTED_PROTOCOL_VERSIONS, isInitializeRequest, isJSONRPCError, isJSONRPCNotification, isJSONRPCRequest, isJSONRPCResponse } from "@modelcontextprotocol/sdk/types.js";
8
11
 
9
12
  //#region src/mcp/utils.ts
10
13
  /**
@@ -21,7 +24,7 @@ const MCP_HTTP_METHOD_HEADER = "cf-mcp-method";
21
24
  */
22
25
  const MCP_MESSAGE_HEADER = "cf-mcp-message";
23
26
  const MAXIMUM_MESSAGE_SIZE_BYTES = 4 * 1024 * 1024;
24
- const createStreamingHttpHandler = (basePath, namespace, corsOptions) => {
27
+ const createStreamingHttpHandler = (basePath, namespace, options = {}) => {
25
28
  let pathname = basePath;
26
29
  if (basePath === "/") pathname = "/*";
27
30
  const basePattern = new URLPattern({ pathname });
@@ -130,7 +133,10 @@ const createStreamingHttpHandler = (basePath, namespace, corsOptions) => {
130
133
  return new Response(body$1, { status: 400 });
131
134
  }
132
135
  sessionId = sessionId ?? namespace.newUniqueId().toString();
133
- const agent = await getAgentByName(namespace, `streamable-http:${sessionId}`, { props: ctx.props });
136
+ const agent = await getAgentByName(namespace, `streamable-http:${sessionId}`, {
137
+ props: ctx.props,
138
+ jurisdiction: options.jurisdiction
139
+ });
134
140
  const isInitialized = await agent.getInitializeRequest();
135
141
  if (maybeInitializeRequest) await agent.setInitializeRequest(maybeInitializeRequest);
136
142
  else if (!isInitialized) {
@@ -205,7 +211,7 @@ const createStreamingHttpHandler = (basePath, namespace, corsOptions) => {
205
211
  if (messages.every((msg) => isJSONRPCNotification(msg) || isJSONRPCResponse(msg))) {
206
212
  ws.close();
207
213
  return new Response(null, {
208
- headers: corsHeaders(request, corsOptions),
214
+ headers: corsHeaders(request, options.corsOptions),
209
215
  status: 202
210
216
  });
211
217
  }
@@ -215,7 +221,7 @@ const createStreamingHttpHandler = (basePath, namespace, corsOptions) => {
215
221
  Connection: "keep-alive",
216
222
  "Content-Type": "text/event-stream",
217
223
  "mcp-session-id": sessionId,
218
- ...corsHeaders(request, corsOptions)
224
+ ...corsHeaders(request, options.corsOptions)
219
225
  },
220
226
  status: 200
221
227
  });
@@ -243,7 +249,10 @@ const createStreamingHttpHandler = (basePath, namespace, corsOptions) => {
243
249
  const { readable, writable } = new TransformStream();
244
250
  const writer = writable.getWriter();
245
251
  const encoder = new TextEncoder();
246
- const agent = await getAgentByName(namespace, `streamable-http:${sessionId}`, { props: ctx.props });
252
+ const agent = await getAgentByName(namespace, `streamable-http:${sessionId}`, {
253
+ props: ctx.props,
254
+ jurisdiction: options.jurisdiction
255
+ });
247
256
  if (!await agent.getInitializeRequest()) return new Response(JSON.stringify({
248
257
  jsonrpc: "2.0",
249
258
  error: {
@@ -292,7 +301,7 @@ const createStreamingHttpHandler = (basePath, namespace, corsOptions) => {
292
301
  Connection: "keep-alive",
293
302
  "Content-Type": "text/event-stream",
294
303
  "mcp-session-id": sessionId,
295
- ...corsHeaders(request, corsOptions)
304
+ ...corsHeaders(request, options.corsOptions)
296
305
  },
297
306
  status: 200
298
307
  });
@@ -307,9 +316,9 @@ const createStreamingHttpHandler = (basePath, namespace, corsOptions) => {
307
316
  id: null
308
317
  }), {
309
318
  status: 400,
310
- headers: corsHeaders(request, corsOptions)
319
+ headers: corsHeaders(request, options.corsOptions)
311
320
  });
312
- const agent = await getAgentByName(namespace, `streamable-http:${sessionId}`);
321
+ const agent = await getAgentByName(namespace, `streamable-http:${sessionId}`, { jurisdiction: options.jurisdiction });
313
322
  if (!await agent.getInitializeRequest()) return new Response(JSON.stringify({
314
323
  jsonrpc: "2.0",
315
324
  error: {
@@ -319,12 +328,12 @@ const createStreamingHttpHandler = (basePath, namespace, corsOptions) => {
319
328
  id: null
320
329
  }), {
321
330
  status: 404,
322
- headers: corsHeaders(request, corsOptions)
331
+ headers: corsHeaders(request, options.corsOptions)
323
332
  });
324
333
  ctx.waitUntil(agent.destroy().catch(() => {}));
325
334
  return new Response(null, {
326
335
  status: 204,
327
- headers: corsHeaders(request, corsOptions)
336
+ headers: corsHeaders(request, options.corsOptions)
328
337
  });
329
338
  }
330
339
  }
@@ -339,7 +348,7 @@ const createStreamingHttpHandler = (basePath, namespace, corsOptions) => {
339
348
  return new Response(body, { status: 404 });
340
349
  };
341
350
  };
342
- const createLegacySseHandler = (basePath, namespace, corsOptions) => {
351
+ const createLegacySseHandler = (basePath, namespace, options = {}) => {
343
352
  let pathname = basePath;
344
353
  if (basePath === "/") pathname = "/*";
345
354
  const basePattern = new URLPattern({ pathname });
@@ -356,7 +365,10 @@ const createLegacySseHandler = (basePath, namespace, corsOptions) => {
356
365
  endpointUrl.searchParams.set("sessionId", sessionId);
357
366
  const endpointMessage = `event: endpoint\ndata: ${endpointUrl.pathname + endpointUrl.search + endpointUrl.hash}\n\n`;
358
367
  writer.write(encoder.encode(endpointMessage));
359
- const agent = await getAgentByName(namespace, `sse:${sessionId}`, { props: ctx.props });
368
+ const agent = await getAgentByName(namespace, `sse:${sessionId}`, {
369
+ props: ctx.props,
370
+ jurisdiction: options.jurisdiction
371
+ });
360
372
  const existingHeaders = {};
361
373
  request.headers.forEach((value, key) => {
362
374
  existingHeaders[key] = value;
@@ -408,7 +420,7 @@ const createLegacySseHandler = (basePath, namespace, corsOptions) => {
408
420
  "Cache-Control": "no-cache",
409
421
  Connection: "keep-alive",
410
422
  "Content-Type": "text/event-stream",
411
- ...corsHeaders(request, corsOptions)
423
+ ...corsHeaders(request, options.corsOptions)
412
424
  } });
413
425
  }
414
426
  if (request.method === "POST" && messagePattern.test(url)) {
@@ -418,15 +430,19 @@ const createLegacySseHandler = (basePath, namespace, corsOptions) => {
418
430
  if (!contentType.includes("application/json")) return new Response(`Unsupported content-type: ${contentType}`, { status: 400 });
419
431
  const contentLength = Number.parseInt(request.headers.get("content-length") || "0", 10);
420
432
  if (contentLength > MAXIMUM_MESSAGE_SIZE_BYTES) return new Response(`Request body too large: ${contentLength} bytes`, { status: 400 });
421
- const agent = await getAgentByName(namespace, `sse:${sessionId}`, { props: ctx.props });
433
+ const agent = await getAgentByName(namespace, `sse:${sessionId}`, {
434
+ props: ctx.props,
435
+ jurisdiction: options.jurisdiction
436
+ });
422
437
  const messageBody = await request.json();
423
- const error = await agent.onSSEMcpMessage(sessionId, messageBody);
438
+ const extraInfo = { requestInfo: { headers: Object.fromEntries(request.headers.entries()) } };
439
+ const error = await agent.onSSEMcpMessage(sessionId, messageBody, extraInfo);
424
440
  if (error) return new Response(error.message, {
425
441
  headers: {
426
442
  "Cache-Control": "no-cache",
427
443
  Connection: "keep-alive",
428
444
  "Content-Type": "text/event-stream",
429
- ...corsHeaders(request, corsOptions)
445
+ ...corsHeaders(request, options.corsOptions)
430
446
  },
431
447
  status: 400
432
448
  });
@@ -435,7 +451,7 @@ const createLegacySseHandler = (basePath, namespace, corsOptions) => {
435
451
  "Cache-Control": "no-cache",
436
452
  Connection: "keep-alive",
437
453
  "Content-Type": "text/event-stream",
438
- ...corsHeaders(request, corsOptions)
454
+ ...corsHeaders(request, options.corsOptions)
439
455
  },
440
456
  status: 202
441
457
  });
@@ -464,9 +480,12 @@ function isDurableObjectNamespace(namespace) {
464
480
  //#endregion
465
481
  //#region src/mcp/transport.ts
466
482
  var McpSSETransport = class {
467
- constructor(getWebSocket) {
483
+ constructor() {
468
484
  this._started = false;
469
- this._getWebSocket = getWebSocket;
485
+ const { agent } = getCurrentAgent();
486
+ if (!agent) throw new Error("McpAgent was not found in Transport constructor");
487
+ this.sessionId = agent.getSessionId();
488
+ this._getWebSocket = () => agent.getWebSocket();
470
489
  }
471
490
  async start() {
472
491
  if (this._started) throw new Error("Transport already started");
@@ -574,19 +593,35 @@ var StreamableHTTPServerTransport = class {
574
593
  if (Array.isArray(rawMessage)) messages = rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
575
594
  else messages = [JSONRPCMessageSchema.parse(rawMessage)];
576
595
  const hasRequests = messages.some(isJSONRPCRequest);
577
- if (!hasRequests) for (const message of messages) this.onmessage?.(message, {
578
- authInfo,
579
- requestInfo
580
- });
596
+ if (!hasRequests) for (const message of messages) {
597
+ if (this.messageInterceptor) {
598
+ if (await this.messageInterceptor(message, {
599
+ authInfo,
600
+ requestInfo
601
+ })) continue;
602
+ }
603
+ this.onmessage?.(message, {
604
+ authInfo,
605
+ requestInfo
606
+ });
607
+ }
581
608
  else if (hasRequests) {
582
609
  const { connection } = getCurrentAgent();
583
610
  if (!connection) throw new Error("Connection was not found in handlePostRequest");
584
611
  const requestIds = messages.filter(isJSONRPCRequest).map((message) => message.id);
585
612
  connection.setState({ requestIds });
586
- for (const message of messages) this.onmessage?.(message, {
587
- authInfo,
588
- requestInfo
589
- });
613
+ for (const message of messages) {
614
+ if (this.messageInterceptor) {
615
+ if (await this.messageInterceptor(message, {
616
+ authInfo,
617
+ requestInfo
618
+ })) continue;
619
+ }
620
+ this.onmessage?.(message, {
621
+ authInfo,
622
+ requestInfo
623
+ });
624
+ }
590
625
  }
591
626
  }
592
627
  async close() {
@@ -625,8 +660,41 @@ var StreamableHTTPServerTransport = class {
625
660
  }
626
661
  };
627
662
 
663
+ //#endregion
664
+ //#region src/mcp/client-transports.ts
665
+ /**
666
+ * Deprecated transport wrappers
667
+ */
668
+ let didWarnAboutSSEEdgeClientTransport = false;
669
+ /**
670
+ * @deprecated Use SSEClientTransport from @modelcontextprotocol/sdk/client/sse.js instead. This alias will be removed in the next major version.
671
+ */
672
+ var SSEEdgeClientTransport = class extends SSEClientTransport {
673
+ constructor(url, options) {
674
+ super(url, options);
675
+ if (!didWarnAboutSSEEdgeClientTransport) {
676
+ didWarnAboutSSEEdgeClientTransport = true;
677
+ console.warn("SSEEdgeClientTransport is deprecated. Use SSEClientTransport from @modelcontextprotocol/sdk/client/sse.js instead. SSEEdgeClientTransport will be removed in the next major version.");
678
+ }
679
+ }
680
+ };
681
+ let didWarnAboutStreamableHTTPEdgeClientTransport = false;
682
+ /**
683
+ * @deprecated Use StreamableHTTPClientTransport from @modelcontextprotocol/sdk/client/streamableHttp.js instead. This alias will be removed in the next major version.
684
+ */
685
+ var StreamableHTTPEdgeClientTransport = class extends StreamableHTTPClientTransport {
686
+ constructor(url, options) {
687
+ super(url, options);
688
+ if (!didWarnAboutStreamableHTTPEdgeClientTransport) {
689
+ didWarnAboutStreamableHTTPEdgeClientTransport = true;
690
+ console.warn("StreamableHTTPEdgeClientTransport is deprecated. Use StreamableHTTPClientTransport from @modelcontextprotocol/sdk/client/streamableHttp.js instead. StreamableHTTPEdgeClientTransport will be removed in the next major version.");
691
+ }
692
+ }
693
+ };
694
+
628
695
  //#endregion
629
696
  //#region src/mcp/worker-transport.ts
697
+ const MCP_PROTOCOL_VERSION_HEADER = "MCP-Protocol-Version";
630
698
  var WorkerTransport = class {
631
699
  constructor(options) {
632
700
  this.started = false;
@@ -636,15 +704,93 @@ var WorkerTransport = class {
636
704
  this.streamMapping = /* @__PURE__ */ new Map();
637
705
  this.requestToStreamMapping = /* @__PURE__ */ new Map();
638
706
  this.requestResponseMap = /* @__PURE__ */ new Map();
707
+ this.stateRestored = false;
639
708
  this.sessionIdGenerator = options?.sessionIdGenerator;
640
709
  this.enableJsonResponse = options?.enableJsonResponse ?? false;
641
710
  this.onsessioninitialized = options?.onsessioninitialized;
711
+ this.corsOptions = options?.corsOptions;
712
+ this.storage = options?.storage;
713
+ }
714
+ /**
715
+ * Restore transport state from persistent storage.
716
+ * This is automatically called on start.
717
+ */
718
+ async restoreState() {
719
+ if (!this.storage || this.stateRestored) return;
720
+ const state = await Promise.resolve(this.storage.get());
721
+ if (state) {
722
+ this.sessionId = state.sessionId;
723
+ this.initialized = state.initialized;
724
+ }
725
+ this.stateRestored = true;
726
+ }
727
+ /**
728
+ * Persist current transport state to storage.
729
+ */
730
+ async saveState() {
731
+ if (!this.storage) return;
732
+ const state = {
733
+ sessionId: this.sessionId,
734
+ initialized: this.initialized
735
+ };
736
+ await Promise.resolve(this.storage.set(state));
642
737
  }
643
738
  async start() {
644
739
  if (this.started) throw new Error("Transport already started");
645
740
  this.started = true;
646
741
  }
742
+ /**
743
+ * Validates the MCP-Protocol-Version header on incoming requests.
744
+ *
745
+ * This performs a simple check: if a version header is present, it must be
746
+ * in the SUPPORTED_PROTOCOL_VERSIONS list. We do not track the negotiated
747
+ * version or enforce version consistency across requests - the SDK handles
748
+ * version negotiation during initialization, and we simply reject any
749
+ * explicitly unsupported versions.
750
+ *
751
+ * - Header present and supported: Accept
752
+ * - Header present and unsupported: 400 Bad Request
753
+ * - Header missing: Accept (version validation is optional)
754
+ */
755
+ validateProtocolVersion(request) {
756
+ const protocolVersion = request.headers.get(MCP_PROTOCOL_VERSION_HEADER);
757
+ if (protocolVersion !== null && !SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)) return new Response(JSON.stringify({
758
+ jsonrpc: "2.0",
759
+ error: {
760
+ code: -32e3,
761
+ message: `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(", ")})`
762
+ },
763
+ id: null
764
+ }), {
765
+ status: 400,
766
+ headers: {
767
+ "Content-Type": "application/json",
768
+ ...this.getHeaders()
769
+ }
770
+ });
771
+ }
772
+ getHeaders({ forPreflight } = {}) {
773
+ const options = {
774
+ origin: "*",
775
+ headers: "Content-Type, Accept, Authorization, mcp-session-id, MCP-Protocol-Version",
776
+ methods: "GET, POST, DELETE, OPTIONS",
777
+ exposeHeaders: "mcp-session-id",
778
+ maxAge: 86400,
779
+ ...this.corsOptions
780
+ };
781
+ if (forPreflight) return {
782
+ "Access-Control-Allow-Origin": options.origin,
783
+ "Access-Control-Allow-Headers": options.headers,
784
+ "Access-Control-Allow-Methods": options.methods,
785
+ "Access-Control-Max-Age": options.maxAge.toString()
786
+ };
787
+ return {
788
+ "Access-Control-Allow-Origin": options.origin,
789
+ "Access-Control-Expose-Headers": options.exposeHeaders
790
+ };
791
+ }
647
792
  async handleRequest(request, parsedBody) {
793
+ await this.restoreState();
648
794
  switch (request.method) {
649
795
  case "OPTIONS": return this.handleOptionsRequest(request);
650
796
  case "GET": return this.handleGetRequest(request);
@@ -663,10 +809,15 @@ var WorkerTransport = class {
663
809
  id: null
664
810
  }), {
665
811
  status: 406,
666
- headers: { "Content-Type": "application/json" }
812
+ headers: {
813
+ "Content-Type": "application/json",
814
+ ...this.getHeaders()
815
+ }
667
816
  });
668
- const sessionValid = this.validateSession(request);
669
- if (sessionValid !== true) return sessionValid;
817
+ const sessionError = this.validateSession(request);
818
+ if (sessionError) return sessionError;
819
+ const versionError = this.validateProtocolVersion(request);
820
+ if (versionError) return versionError;
670
821
  const streamId = this.standaloneSseStreamId;
671
822
  if (this.streamMapping.get(streamId) !== void 0) return new Response(JSON.stringify({
672
823
  jsonrpc: "2.0",
@@ -677,7 +828,10 @@ var WorkerTransport = class {
677
828
  id: null
678
829
  }), {
679
830
  status: 409,
680
- headers: { "Content-Type": "application/json" }
831
+ headers: {
832
+ "Content-Type": "application/json",
833
+ ...this.getHeaders()
834
+ }
681
835
  });
682
836
  const { readable, writable } = new TransformStream();
683
837
  const writer = writable.getWriter();
@@ -686,8 +840,7 @@ var WorkerTransport = class {
686
840
  "Content-Type": "text/event-stream",
687
841
  "Cache-Control": "no-cache",
688
842
  Connection: "keep-alive",
689
- "Access-Control-Allow-Origin": "*",
690
- "Access-Control-Expose-Headers": "mcp-session-id"
843
+ ...this.getHeaders()
691
844
  });
692
845
  if (this.sessionId !== void 0) headers.set("mcp-session-id", this.sessionId);
693
846
  const keepAlive = setInterval(() => {
@@ -710,7 +863,7 @@ var WorkerTransport = class {
710
863
  }
711
864
  async handlePostRequest(request, parsedBody) {
712
865
  const acceptHeader = request.headers.get("Accept");
713
- if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) return new Response(JSON.stringify({
866
+ if (!acceptHeader?.includes("application/json") || !acceptHeader?.includes("text/event-stream")) return new Response(JSON.stringify({
714
867
  jsonrpc: "2.0",
715
868
  error: {
716
869
  code: -32e3,
@@ -719,7 +872,10 @@ var WorkerTransport = class {
719
872
  id: null
720
873
  }), {
721
874
  status: 406,
722
- headers: { "Content-Type": "application/json" }
875
+ headers: {
876
+ "Content-Type": "application/json",
877
+ ...this.getHeaders()
878
+ }
723
879
  });
724
880
  if (!request.headers.get("Content-Type")?.includes("application/json")) return new Response(JSON.stringify({
725
881
  jsonrpc: "2.0",
@@ -730,7 +886,10 @@ var WorkerTransport = class {
730
886
  id: null
731
887
  }), {
732
888
  status: 415,
733
- headers: { "Content-Type": "application/json" }
889
+ headers: {
890
+ "Content-Type": "application/json",
891
+ ...this.getHeaders()
892
+ }
734
893
  });
735
894
  let rawMessage = parsedBody;
736
895
  if (rawMessage === void 0) try {
@@ -745,7 +904,10 @@ var WorkerTransport = class {
745
904
  id: null
746
905
  }), {
747
906
  status: 400,
748
- headers: { "Content-Type": "application/json" }
907
+ headers: {
908
+ "Content-Type": "application/json",
909
+ ...this.getHeaders()
910
+ }
749
911
  });
750
912
  }
751
913
  let messages;
@@ -762,9 +924,13 @@ var WorkerTransport = class {
762
924
  id: null
763
925
  }), {
764
926
  status: 400,
765
- headers: { "Content-Type": "application/json" }
927
+ headers: {
928
+ "Content-Type": "application/json",
929
+ ...this.getHeaders()
930
+ }
766
931
  });
767
932
  }
933
+ const requestInfo = { headers: Object.fromEntries(request.headers.entries()) };
768
934
  const isInitializationRequest = messages.some(isInitializeRequest);
769
935
  if (isInitializationRequest) {
770
936
  if (this.initialized && this.sessionId !== void 0) return new Response(JSON.stringify({
@@ -776,7 +942,10 @@ var WorkerTransport = class {
776
942
  id: null
777
943
  }), {
778
944
  status: 400,
779
- headers: { "Content-Type": "application/json" }
945
+ headers: {
946
+ "Content-Type": "application/json",
947
+ ...this.getHeaders()
948
+ }
780
949
  });
781
950
  if (messages.length > 1) return new Response(JSON.stringify({
782
951
  jsonrpc: "2.0",
@@ -787,21 +956,27 @@ var WorkerTransport = class {
787
956
  id: null
788
957
  }), {
789
958
  status: 400,
790
- headers: { "Content-Type": "application/json" }
959
+ headers: {
960
+ "Content-Type": "application/json",
961
+ ...this.getHeaders()
962
+ }
791
963
  });
792
964
  this.sessionId = this.sessionIdGenerator?.();
793
965
  this.initialized = true;
966
+ await this.saveState();
794
967
  if (this.sessionId && this.onsessioninitialized) this.onsessioninitialized(this.sessionId);
795
968
  }
796
969
  if (!isInitializationRequest) {
797
- const sessionValid = this.validateSession(request);
798
- if (sessionValid !== true) return sessionValid;
970
+ const sessionError = this.validateSession(request);
971
+ if (sessionError) return sessionError;
972
+ const versionError = this.validateProtocolVersion(request);
973
+ if (versionError) return versionError;
799
974
  }
800
975
  if (!messages.some(isJSONRPCRequest)) {
801
- for (const message of messages) this.onmessage?.(message);
976
+ for (const message of messages) this.onmessage?.(message, { requestInfo });
802
977
  return new Response(null, {
803
978
  status: 202,
804
- headers: { "Access-Control-Allow-Origin": "*" }
979
+ headers: { ...this.getHeaders() }
805
980
  });
806
981
  }
807
982
  const streamId = crypto.randomUUID();
@@ -813,7 +988,7 @@ var WorkerTransport = class {
813
988
  }
814
989
  });
815
990
  for (const message of messages) if (isJSONRPCRequest(message)) this.requestToStreamMapping.set(message.id, streamId);
816
- for (const message of messages) this.onmessage?.(message);
991
+ for (const message of messages) this.onmessage?.(message, { requestInfo });
817
992
  });
818
993
  const { readable, writable } = new TransformStream();
819
994
  const writer = writable.getWriter();
@@ -822,8 +997,7 @@ var WorkerTransport = class {
822
997
  "Content-Type": "text/event-stream",
823
998
  "Cache-Control": "no-cache",
824
999
  Connection: "keep-alive",
825
- "Access-Control-Allow-Origin": "*",
826
- "Access-Control-Expose-Headers": "mcp-session-id"
1000
+ ...this.getHeaders()
827
1001
  });
828
1002
  if (this.sessionId !== void 0) headers.set("mcp-session-id", this.sessionId);
829
1003
  this.streamMapping.set(streamId, {
@@ -835,28 +1009,24 @@ var WorkerTransport = class {
835
1009
  }
836
1010
  });
837
1011
  for (const message of messages) if (isJSONRPCRequest(message)) this.requestToStreamMapping.set(message.id, streamId);
838
- for (const message of messages) this.onmessage?.(message);
1012
+ for (const message of messages) this.onmessage?.(message, { requestInfo });
839
1013
  return new Response(readable, { headers });
840
1014
  }
841
1015
  async handleDeleteRequest(request) {
842
- const sessionValid = this.validateSession(request);
843
- if (sessionValid !== true) return sessionValid;
1016
+ const sessionError = this.validateSession(request);
1017
+ if (sessionError) return sessionError;
1018
+ const versionError = this.validateProtocolVersion(request);
1019
+ if (versionError) return versionError;
844
1020
  await this.close();
845
1021
  return new Response(null, {
846
1022
  status: 200,
847
- headers: { "Access-Control-Allow-Origin": "*" }
1023
+ headers: { ...this.getHeaders() }
848
1024
  });
849
1025
  }
850
1026
  handleOptionsRequest(_request) {
851
- const headers = new Headers({
852
- "Access-Control-Allow-Origin": "*",
853
- "Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS",
854
- "Access-Control-Allow-Headers": "Content-Type, Accept, Authorization, mcp-session-id",
855
- "Access-Control-Max-Age": "86400"
856
- });
857
1027
  return new Response(null, {
858
- status: 204,
859
- headers
1028
+ status: 200,
1029
+ headers: { ...this.getHeaders({ forPreflight: true }) }
860
1030
  });
861
1031
  }
862
1032
  handleUnsupportedRequest() {
@@ -876,7 +1046,7 @@ var WorkerTransport = class {
876
1046
  });
877
1047
  }
878
1048
  validateSession(request) {
879
- if (this.sessionIdGenerator === void 0) return true;
1049
+ if (this.sessionIdGenerator === void 0) return;
880
1050
  if (!this.initialized) return new Response(JSON.stringify({
881
1051
  jsonrpc: "2.0",
882
1052
  error: {
@@ -886,7 +1056,10 @@ var WorkerTransport = class {
886
1056
  id: null
887
1057
  }), {
888
1058
  status: 400,
889
- headers: { "Content-Type": "application/json" }
1059
+ headers: {
1060
+ "Content-Type": "application/json",
1061
+ ...this.getHeaders()
1062
+ }
890
1063
  });
891
1064
  const sessionId = request.headers.get("mcp-session-id");
892
1065
  if (!sessionId) return new Response(JSON.stringify({
@@ -898,7 +1071,10 @@ var WorkerTransport = class {
898
1071
  id: null
899
1072
  }), {
900
1073
  status: 400,
901
- headers: { "Content-Type": "application/json" }
1074
+ headers: {
1075
+ "Content-Type": "application/json",
1076
+ ...this.getHeaders()
1077
+ }
902
1078
  });
903
1079
  if (sessionId !== this.sessionId) return new Response(JSON.stringify({
904
1080
  jsonrpc: "2.0",
@@ -909,9 +1085,11 @@ var WorkerTransport = class {
909
1085
  id: null
910
1086
  }), {
911
1087
  status: 404,
912
- headers: { "Content-Type": "application/json" }
1088
+ headers: {
1089
+ "Content-Type": "application/json",
1090
+ ...this.getHeaders()
1091
+ }
913
1092
  });
914
- return true;
915
1093
  }
916
1094
  async close() {
917
1095
  for (const { cleanup } of this.streamMapping.values()) cleanup();
@@ -919,8 +1097,8 @@ var WorkerTransport = class {
919
1097
  this.requestResponseMap.clear();
920
1098
  this.onclose?.();
921
1099
  }
922
- async send(message) {
923
- let requestId;
1100
+ async send(message, options) {
1101
+ let requestId = options?.relatedRequestId;
924
1102
  if (isJSONRPCResponse(message) || isJSONRPCError(message)) requestId = message.id;
925
1103
  if (requestId === void 0) {
926
1104
  if (isJSONRPCResponse(message) || isJSONRPCError(message)) throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");
@@ -950,8 +1128,7 @@ var WorkerTransport = class {
950
1128
  const responses = relatedIds.map((id) => this.requestResponseMap.get(id));
951
1129
  const headers = new Headers({
952
1130
  "Content-Type": "application/json",
953
- "Access-Control-Allow-Origin": "*",
954
- "Access-Control-Expose-Headers": "mcp-session-id"
1131
+ ...this.getHeaders()
955
1132
  });
956
1133
  if (this.sessionId !== void 0) headers.set("mcp-session-id", this.sessionId);
957
1134
  const body = responses.length === 1 ? responses[0] : responses;
@@ -978,23 +1155,30 @@ function runWithAuthContext(context, fn) {
978
1155
 
979
1156
  //#endregion
980
1157
  //#region src/mcp/handler.ts
981
- function experimental_createMcpHandler(server, options = {}) {
1158
+ function createMcpHandler(server, options = {}) {
982
1159
  const route = options.route ?? "/mcp";
983
1160
  return async (request, _env, ctx) => {
984
1161
  const url = new URL(request.url);
985
1162
  if (route && url.pathname !== route) return new Response("Not Found", { status: 404 });
986
- const oauthCtx = ctx;
987
- const authContext = oauthCtx.props ? { props: oauthCtx.props } : void 0;
988
- const transport = new WorkerTransport(options);
989
- await server.connect(transport);
1163
+ const transport = options.transport ?? new WorkerTransport({
1164
+ sessionIdGenerator: options.sessionIdGenerator,
1165
+ enableJsonResponse: options.enableJsonResponse,
1166
+ onsessioninitialized: options.onsessioninitialized,
1167
+ corsOptions: options.corsOptions,
1168
+ storage: options.storage
1169
+ });
1170
+ const buildAuthContext = () => {
1171
+ if (options.authContext) return options.authContext;
1172
+ if (ctx.props && Object.keys(ctx.props).length > 0) return { props: ctx.props };
1173
+ };
990
1174
  const handleRequest = async () => {
991
1175
  return await transport.handleRequest(request);
992
1176
  };
1177
+ const authContext = buildAuthContext();
1178
+ if (!transport.started) await server.connect(transport);
993
1179
  try {
994
- let response;
995
- if (authContext) response = await runWithAuthContext(authContext, handleRequest);
996
- else response = await handleRequest();
997
- return response;
1180
+ if (authContext) return await runWithAuthContext(authContext, handleRequest);
1181
+ else return await handleRequest();
998
1182
  } catch (error) {
999
1183
  console.error("MCP handler error:", error);
1000
1184
  return new Response(JSON.stringify({
@@ -1011,6 +1195,17 @@ function experimental_createMcpHandler(server, options = {}) {
1011
1195
  }
1012
1196
  };
1013
1197
  }
1198
+ let didWarnAboutExperimentalCreateMcpHandler = false;
1199
+ /**
1200
+ * @deprecated This has been renamed to createMcpHandler, and experimental_createMcpHandler will be removed in the next major version
1201
+ */
1202
+ function experimental_createMcpHandler(server, options = {}) {
1203
+ if (!didWarnAboutExperimentalCreateMcpHandler) {
1204
+ didWarnAboutExperimentalCreateMcpHandler = true;
1205
+ console.warn("experimental_createMcpHandler is deprecated, use createMcpHandler instead. experimental_createMcpHandler will be removed in the next major version.");
1206
+ }
1207
+ return createMcpHandler(server, options);
1208
+ }
1014
1209
 
1015
1210
  //#endregion
1016
1211
  //#region src/mcp/index.ts
@@ -1051,8 +1246,14 @@ var McpAgent = class McpAgent extends Agent {
1051
1246
  /** Returns a new transport matching the type of the Agent. */
1052
1247
  initTransport() {
1053
1248
  switch (this.getTransportType()) {
1054
- case "sse": return new McpSSETransport(() => this.getWebSocket());
1055
- case "streamable-http": return new StreamableHTTPServerTransport({});
1249
+ case "sse": return new McpSSETransport();
1250
+ case "streamable-http": {
1251
+ const transport = new StreamableHTTPServerTransport({});
1252
+ transport.messageInterceptor = async (message) => {
1253
+ return this._handleElicitationResponse(message);
1254
+ };
1255
+ return transport;
1256
+ }
1056
1257
  }
1057
1258
  }
1058
1259
  /** Update and store the props */
@@ -1104,7 +1305,7 @@ var McpAgent = class McpAgent extends Agent {
1104
1305
  }
1105
1306
  }
1106
1307
  /** Handles MCP Messages for the legacy SSE transport. */
1107
- async onSSEMcpMessage(_sessionId, messageBody) {
1308
+ async onSSEMcpMessage(_sessionId, messageBody, extraInfo) {
1108
1309
  if (this.getTransportType() !== "sse") return /* @__PURE__ */ new Error("Internal Server Error: Expected SSE transport");
1109
1310
  try {
1110
1311
  let parsedMessage;
@@ -1115,7 +1316,7 @@ var McpAgent = class McpAgent extends Agent {
1115
1316
  throw error;
1116
1317
  }
1117
1318
  if (await this._handleElicitationResponse(parsedMessage)) return null;
1118
- this._transport?.onmessage?.(parsedMessage);
1319
+ this._transport?.onmessage?.(parsedMessage, extraInfo);
1119
1320
  return null;
1120
1321
  } catch (error) {
1121
1322
  console.error("Error forwarding message to SSE:", error);
@@ -1201,7 +1402,7 @@ var McpAgent = class McpAgent extends Agent {
1201
1402
  /** Return a handler for the given path for this MCP.
1202
1403
  * Defaults to Streamable HTTP transport.
1203
1404
  */
1204
- static serve(path, { binding = "MCP_OBJECT", corsOptions, transport = "streamable-http" } = {}) {
1405
+ static serve(path, { binding = "MCP_OBJECT", corsOptions, transport = "streamable-http", jurisdiction } = {}) {
1205
1406
  return { async fetch(request, env, ctx) {
1206
1407
  const corsResponse = handleCORS(request, corsOptions);
1207
1408
  if (corsResponse) return corsResponse;
@@ -1210,8 +1411,14 @@ var McpAgent = class McpAgent extends Agent {
1210
1411
  if (!isDurableObjectNamespace(bindingValue)) throw new Error(`Invalid McpAgent binding for ${binding}. Make sure it's a Durable Object binding.`);
1211
1412
  const namespace = bindingValue;
1212
1413
  switch (transport) {
1213
- case "streamable-http": return createStreamingHttpHandler(path, namespace, corsOptions)(request, ctx);
1214
- case "sse": return createLegacySseHandler(path, namespace, corsOptions)(request, ctx);
1414
+ case "streamable-http": return createStreamingHttpHandler(path, namespace, {
1415
+ corsOptions,
1416
+ jurisdiction
1417
+ })(request, ctx);
1418
+ case "sse": return createLegacySseHandler(path, namespace, {
1419
+ corsOptions,
1420
+ jurisdiction
1421
+ })(request, ctx);
1215
1422
  default: return new Response("Invalid MCP transport mode. Only `streamable-http` or `sse` are allowed.", { status: 500 });
1216
1423
  }
1217
1424
  } };
@@ -1231,5 +1438,5 @@ var McpAgent = class McpAgent extends Agent {
1231
1438
  };
1232
1439
 
1233
1440
  //#endregion
1234
- export { ElicitRequestSchema, McpAgent, SSEEdgeClientTransport, StreamableHTTPEdgeClientTransport, WorkerTransport, experimental_createMcpHandler, getMcpAuthContext };
1441
+ export { ElicitRequestSchema, McpAgent, SSEEdgeClientTransport, StreamableHTTPEdgeClientTransport, WorkerTransport, createMcpHandler, experimental_createMcpHandler, getMcpAuthContext };
1235
1442
  //# sourceMappingURL=index.js.map