agents 0.0.0-df41827 → 0.0.0-df52d4b

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 (38) hide show
  1. package/README.md +128 -22
  2. package/dist/ai-chat-agent.d.ts +5 -2
  3. package/dist/ai-chat-agent.js +24 -4
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-react.d.ts +6 -3
  6. package/dist/ai-react.js.map +1 -1
  7. package/dist/{chunk-ZRRXJUAA.js → chunk-DQJFYHG3.js} +595 -93
  8. package/dist/chunk-DQJFYHG3.js.map +1 -0
  9. package/dist/{chunk-E3LCYPCB.js → chunk-EM3J4KV7.js} +147 -18
  10. package/dist/chunk-EM3J4KV7.js.map +1 -0
  11. package/dist/{chunk-NKZZ66QY.js → chunk-KUH345EY.js} +1 -1
  12. package/dist/chunk-KUH345EY.js.map +1 -0
  13. package/dist/{chunk-767EASBA.js → chunk-PVQZBKN7.js} +1 -1
  14. package/dist/chunk-PVQZBKN7.js.map +1 -0
  15. package/dist/client-DgyzBU_8.d.ts +4601 -0
  16. package/dist/client.d.ts +2 -2
  17. package/dist/client.js +1 -1
  18. package/dist/index.d.ts +152 -16
  19. package/dist/index.js +10 -4
  20. package/dist/mcp/client.d.ts +9 -781
  21. package/dist/mcp/client.js +1 -1
  22. package/dist/mcp/do-oauth-client-provider.js +1 -1
  23. package/dist/mcp/index.d.ts +35 -7
  24. package/dist/mcp/index.js +190 -18
  25. package/dist/mcp/index.js.map +1 -1
  26. package/dist/observability/index.d.ts +46 -0
  27. package/dist/observability/index.js +10 -0
  28. package/dist/observability/index.js.map +1 -0
  29. package/dist/react.d.ts +8 -5
  30. package/dist/react.js.map +1 -1
  31. package/dist/schedule.d.ts +4 -4
  32. package/dist/schedule.js.map +1 -1
  33. package/package.json +34 -26
  34. package/src/index.ts +799 -134
  35. package/dist/chunk-767EASBA.js.map +0 -1
  36. package/dist/chunk-E3LCYPCB.js.map +0 -1
  37. package/dist/chunk-NKZZ66QY.js.map +0 -1
  38. package/dist/chunk-ZRRXJUAA.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  MCPClientManager,
3
3
  getNamespacedData
4
- } from "../chunk-E3LCYPCB.js";
4
+ } from "../chunk-EM3J4KV7.js";
5
5
  export {
6
6
  MCPClientManager,
7
7
  getNamespacedData
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  DurableObjectOAuthClientProvider
3
- } from "../chunk-767EASBA.js";
3
+ } from "../chunk-PVQZBKN7.js";
4
4
  export {
5
5
  DurableObjectOAuthClientProvider
6
6
  };
@@ -1,14 +1,17 @@
1
- import { MCPClientManager } from './client.js';
1
+ import { M as MCPClientManager } from '../client-DgyzBU_8.js';
2
+ export { S as SSEEdgeClientTransport, a as StreamableHTTPEdgeClientTransport } from '../client-DgyzBU_8.js';
2
3
  import { DurableObject } from 'cloudflare:workers';
3
4
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
4
5
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
6
+ import { ElicitResult } from '@modelcontextprotocol/sdk/types.js';
7
+ export { ElicitRequest, ElicitRequestSchema, ElicitResult } from '@modelcontextprotocol/sdk/types.js';
5
8
  import { Connection, WSMessage } from 'partyserver';
6
9
  import 'zod';
7
10
  import '@modelcontextprotocol/sdk/client/index.js';
8
- import '@modelcontextprotocol/sdk/client/sse.js';
9
11
  import '@modelcontextprotocol/sdk/shared/protocol.js';
10
- import '@modelcontextprotocol/sdk/types.js';
11
12
  import 'ai';
13
+ import '@modelcontextprotocol/sdk/client/sse.js';
14
+ import '@modelcontextprotocol/sdk/client/streamableHttp.js';
12
15
  import './do-oauth-client-provider.js';
13
16
  import '@modelcontextprotocol/sdk/client/auth.js';
14
17
  import '@modelcontextprotocol/sdk/shared/auth.js';
@@ -40,6 +43,13 @@ declare abstract class McpAgent<Env = unknown, State = unknown, Props extends Re
40
43
  get state(): State;
41
44
  sql<T = Record<string, string | number | boolean | null>>(strings: TemplateStringsArray, ...values: (string | number | boolean | null)[]): T[];
42
45
  setState(state: State): void;
46
+ /**
47
+ * Elicit user input with a message and schema
48
+ */
49
+ elicitInput(params: {
50
+ message: string;
51
+ requestedSchema: unknown;
52
+ }): Promise<ElicitResult>;
43
53
  onStateUpdate(state: State | undefined, source: Connection | "server"): void;
44
54
  onStart(): Promise<void>;
45
55
  /**
@@ -49,31 +59,49 @@ declare abstract class McpAgent<Env = unknown, State = unknown, Props extends Re
49
59
  props: Props;
50
60
  initRun: boolean;
51
61
  abstract init(): Promise<void>;
62
+ /**
63
+ * Handle errors that occur during initialization or operation.
64
+ * Override this method to provide custom error handling.
65
+ * @param error - The error that occurred
66
+ * @returns An error response object with status code and message
67
+ */
68
+ onError(error: Error): {
69
+ status: number;
70
+ message: string;
71
+ };
52
72
  _init(props: Props): Promise<void>;
53
73
  setInitialized(): Promise<void>;
54
74
  isInitialized(): Promise<boolean>;
75
+ updateProps(props: Props): Promise<void>;
55
76
  private _initialize;
56
77
  fetch(request: Request): Promise<Response>;
57
78
  getWebSocket(): WebSocket | null;
58
79
  getWebSocketForResponseID(id: string): WebSocket | null;
59
80
  onMessage(connection: Connection, event: WSMessage): Promise<void>;
60
- onSSEMcpMessage(_sessionId: string, request: Request): Promise<Error | null>;
81
+ /**
82
+ * Wait for elicitation response through storage polling
83
+ */
84
+ private _waitForElicitationResponse;
85
+ /**
86
+ * Handle elicitation responses */
87
+ private _handleElicitationResponse;
88
+ onSSEMcpMessage(_sessionId: string, messageBody: unknown): Promise<Error | null>;
61
89
  webSocketMessage(ws: WebSocket, event: ArrayBuffer | string): Promise<void>;
62
90
  webSocketError(ws: WebSocket, error: unknown): Promise<void>;
63
91
  webSocketClose(ws: WebSocket, code: number, reason: string, wasClean: boolean): Promise<void>;
64
- static mount(path: string, { binding, corsOptions, }?: {
92
+ static mount(path: string, { binding, corsOptions }?: {
65
93
  binding?: string;
66
94
  corsOptions?: CORSOptions;
67
95
  }): {
68
96
  fetch<Env>(this: void, request: Request, env: Env, ctx: ExecutionContext): Promise<Response>;
69
97
  };
70
- static serveSSE(path: string, { binding, corsOptions, }?: {
98
+ static serveSSE(path: string, { binding, corsOptions }?: {
71
99
  binding?: string;
72
100
  corsOptions?: CORSOptions;
73
101
  }): {
74
102
  fetch<Env>(this: void, request: Request, env: Env, ctx: ExecutionContext): Promise<Response>;
75
103
  };
76
- static serve(path: string, { binding, corsOptions, }?: {
104
+ static serve(path: string, { binding, corsOptions }?: {
77
105
  binding?: string;
78
106
  corsOptions?: CORSOptions;
79
107
  }): {
package/dist/mcp/index.js CHANGED
@@ -1,25 +1,31 @@
1
1
  import {
2
2
  Agent
3
- } from "../chunk-ZRRXJUAA.js";
4
- import "../chunk-E3LCYPCB.js";
5
- import "../chunk-767EASBA.js";
6
- import "../chunk-NKZZ66QY.js";
3
+ } from "../chunk-DQJFYHG3.js";
4
+ import {
5
+ SSEEdgeClientTransport,
6
+ StreamableHTTPEdgeClientTransport
7
+ } from "../chunk-EM3J4KV7.js";
8
+ import "../chunk-PVQZBKN7.js";
9
+ import "../chunk-KUH345EY.js";
7
10
 
8
11
  // src/mcp/index.ts
9
12
  import { DurableObject } from "cloudflare:workers";
10
13
  import {
11
14
  InitializeRequestSchema,
15
+ JSONRPCMessageSchema,
12
16
  isJSONRPCError,
13
17
  isJSONRPCNotification,
14
18
  isJSONRPCRequest,
15
- isJSONRPCResponse,
16
- JSONRPCMessageSchema
19
+ isJSONRPCResponse
20
+ } from "@modelcontextprotocol/sdk/types.js";
21
+ import {
22
+ ElicitRequestSchema
17
23
  } from "@modelcontextprotocol/sdk/types.js";
18
24
  var MAXIMUM_MESSAGE_SIZE_BYTES = 4 * 1024 * 1024;
19
25
  function corsHeaders(_request, corsOptions = {}) {
20
26
  const origin = "*";
21
27
  return {
22
- "Access-Control-Allow-Headers": corsOptions.headers || "Content-Type, mcp-session-id",
28
+ "Access-Control-Allow-Headers": corsOptions.headers || "Content-Type, mcp-session-id, mcp-protocol-version",
23
29
  "Access-Control-Allow-Methods": corsOptions.methods || "GET, POST, OPTIONS",
24
30
  "Access-Control-Allow-Origin": corsOptions.origin || origin,
25
31
  "Access-Control-Expose-Headers": corsOptions.exposeHeaders || "mcp-session-id",
@@ -141,6 +147,45 @@ var McpAgent = class _McpAgent extends DurableObject {
141
147
  setState(state) {
142
148
  return this._agent.setState(state);
143
149
  }
150
+ /**
151
+ * Elicit user input with a message and schema
152
+ */
153
+ async elicitInput(params) {
154
+ const requestId = `elicit_${Math.random().toString(36).substring(2, 11)}`;
155
+ await this.ctx.storage.put(`elicitation:${requestId}`, {
156
+ message: params.message,
157
+ requestedSchema: params.requestedSchema,
158
+ timestamp: Date.now()
159
+ });
160
+ const elicitRequest = {
161
+ jsonrpc: "2.0",
162
+ id: requestId,
163
+ method: "elicitation/create",
164
+ params: {
165
+ message: params.message,
166
+ requestedSchema: params.requestedSchema
167
+ }
168
+ };
169
+ if (this._transport) {
170
+ await this._transport.send(elicitRequest);
171
+ } else {
172
+ const connections = this._agent?.getConnections();
173
+ if (!connections || Array.from(connections).length === 0) {
174
+ await this.ctx.storage.delete(`elicitation:${requestId}`);
175
+ throw new Error("No active connections available for elicitation");
176
+ }
177
+ const connectionList = Array.from(connections);
178
+ for (const connection of connectionList) {
179
+ try {
180
+ connection.send(JSON.stringify(elicitRequest));
181
+ } catch (error) {
182
+ console.error("Failed to send elicitation request:", error);
183
+ }
184
+ }
185
+ }
186
+ return this._waitForElicitationResponse(requestId);
187
+ }
188
+ // we leave the variables as unused for autocomplete purposes
144
189
  // biome-ignore lint/correctness/noUnusedFunctionParameters: overriden later
145
190
  onStateUpdate(state, source) {
146
191
  }
@@ -178,15 +223,32 @@ var McpAgent = class _McpAgent extends DurableObject {
178
223
  await server.connect(this._transport);
179
224
  }
180
225
  }
226
+ /**
227
+ * Handle errors that occur during initialization or operation.
228
+ * Override this method to provide custom error handling.
229
+ * @param error - The error that occurred
230
+ * @returns An error response object with status code and message
231
+ */
232
+ onError(error) {
233
+ console.error("McpAgent error:", error);
234
+ return {
235
+ status: 500,
236
+ message: error.message || "An unexpected error occurred during initialization"
237
+ };
238
+ }
181
239
  async _init(props) {
182
- await this.ctx.storage.put("props", props ?? {});
240
+ await this.updateProps(props);
183
241
  if (!this.ctx.storage.get("transportType")) {
184
242
  await this.ctx.storage.put("transportType", "unset");
185
243
  }
186
- this.props = props;
187
244
  if (!this.initRun) {
188
245
  this.initRun = true;
189
- await this.init();
246
+ try {
247
+ await this.init();
248
+ } catch (error) {
249
+ const errorResponse = this.onError(error);
250
+ throw new Error(`Initialization failed: ${errorResponse.message}`);
251
+ }
190
252
  }
191
253
  }
192
254
  async setInitialized() {
@@ -195,6 +257,10 @@ var McpAgent = class _McpAgent extends DurableObject {
195
257
  async isInitialized() {
196
258
  return await this.ctx.storage.get("initialized") === true;
197
259
  }
260
+ async updateProps(props) {
261
+ await this.ctx.storage.put("props", props ?? {});
262
+ this.props = props;
263
+ }
198
264
  async _initialize() {
199
265
  await this.ctx.blockConcurrencyWhile(async () => {
200
266
  this._status = "starting";
@@ -281,14 +347,78 @@ var McpAgent = class _McpAgent extends DurableObject {
281
347
  this._transport?.onerror?.(error);
282
348
  return;
283
349
  }
350
+ if (await this._handleElicitationResponse(message)) {
351
+ return;
352
+ }
284
353
  if (isJSONRPCRequest(message)) {
285
354
  this._requestIdToConnectionId.set(message.id.toString(), connection.id);
286
355
  }
287
356
  this._transport?.onmessage?.(message);
288
357
  }
358
+ /**
359
+ * Wait for elicitation response through storage polling
360
+ */
361
+ async _waitForElicitationResponse(requestId) {
362
+ const startTime = Date.now();
363
+ const timeout = 6e4;
364
+ try {
365
+ while (Date.now() - startTime < timeout) {
366
+ const response = await this.ctx.storage.get(
367
+ `elicitation:response:${requestId}`
368
+ );
369
+ if (response) {
370
+ await this.ctx.storage.delete(`elicitation:${requestId}`);
371
+ await this.ctx.storage.delete(`elicitation:response:${requestId}`);
372
+ return response;
373
+ }
374
+ await new Promise((resolve) => setTimeout(resolve, 100));
375
+ }
376
+ throw new Error("Elicitation request timed out");
377
+ } finally {
378
+ await this.ctx.storage.delete(`elicitation:${requestId}`);
379
+ await this.ctx.storage.delete(`elicitation:response:${requestId}`);
380
+ }
381
+ }
382
+ /**
383
+ * Handle elicitation responses */
384
+ async _handleElicitationResponse(message) {
385
+ if (isJSONRPCResponse(message) && message.result) {
386
+ const requestId = message.id?.toString();
387
+ if (!requestId || !requestId.startsWith("elicit_")) return false;
388
+ const pendingRequest = await this.ctx.storage.get(
389
+ `elicitation:${requestId}`
390
+ );
391
+ if (!pendingRequest) return false;
392
+ await this.ctx.storage.put(
393
+ `elicitation:response:${requestId}`,
394
+ message.result
395
+ );
396
+ return true;
397
+ }
398
+ if (isJSONRPCError(message)) {
399
+ const requestId = message.id?.toString();
400
+ if (!requestId || !requestId.startsWith("elicit_")) return false;
401
+ const pendingRequest = await this.ctx.storage.get(
402
+ `elicitation:${requestId}`
403
+ );
404
+ if (!pendingRequest) return false;
405
+ const errorResult = {
406
+ action: "cancel",
407
+ content: {
408
+ error: message.error.message || "Elicitation request failed"
409
+ }
410
+ };
411
+ await this.ctx.storage.put(
412
+ `elicitation:response:${requestId}`,
413
+ errorResult
414
+ );
415
+ return true;
416
+ }
417
+ return false;
418
+ }
289
419
  // All messages received over SSE after the initial connection has been established
290
420
  // will be passed here
291
- async onSSEMcpMessage(_sessionId, request) {
421
+ async onSSEMcpMessage(_sessionId, messageBody) {
292
422
  if (this._status !== "started") {
293
423
  await this._initialize();
294
424
  }
@@ -296,14 +426,16 @@ var McpAgent = class _McpAgent extends DurableObject {
296
426
  return new Error("Internal Server Error: Expected SSE protocol");
297
427
  }
298
428
  try {
299
- const message = await request.json();
300
429
  let parsedMessage;
301
430
  try {
302
- parsedMessage = JSONRPCMessageSchema.parse(message);
431
+ parsedMessage = JSONRPCMessageSchema.parse(messageBody);
303
432
  } catch (error) {
304
433
  this._transport?.onerror?.(error);
305
434
  throw error;
306
435
  }
436
+ if (await this._handleElicitationResponse(parsedMessage)) {
437
+ return null;
438
+ }
307
439
  this._transport?.onmessage?.(parsedMessage);
308
440
  return null;
309
441
  } catch (error) {
@@ -380,12 +512,26 @@ data: ${relativeUrlWithSession}
380
512
  writer.write(encoder.encode(endpointMessage));
381
513
  const id = namespace.idFromName(`sse:${sessionId}`);
382
514
  const doStub = namespace.get(id);
383
- await doStub._init(ctx.props);
515
+ try {
516
+ await doStub._init(ctx.props);
517
+ } catch (error) {
518
+ console.error("Failed to initialize McpAgent:", error);
519
+ await writer.close();
520
+ const errorMessage = error instanceof Error ? error.message : String(error);
521
+ return new Response(`Initialization failed: ${errorMessage}`, {
522
+ status: 500
523
+ });
524
+ }
384
525
  const upgradeUrl = new URL(request.url);
385
526
  upgradeUrl.pathname = "/sse";
527
+ const existingHeaders = {};
528
+ request.headers.forEach((value, key) => {
529
+ existingHeaders[key] = value;
530
+ });
386
531
  const response = await doStub.fetch(
387
532
  new Request(upgradeUrl, {
388
533
  headers: {
534
+ ...existingHeaders,
389
535
  Upgrade: "websocket",
390
536
  // Required by PartyServer
391
537
  "x-partykit-room": sessionId
@@ -476,7 +622,9 @@ data: ${JSON.stringify(result.data)}
476
622
  }
477
623
  const id = namespace.idFromName(`sse:${sessionId}`);
478
624
  const doStub = namespace.get(id);
479
- const error = await doStub.onSSEMcpMessage(sessionId, request);
625
+ const messageBody = await request.json();
626
+ await doStub.updateProps(ctx.props);
627
+ const error = await doStub.onSSEMcpMessage(sessionId, messageBody);
480
628
  if (error) {
481
629
  return new Response(error.message, {
482
630
  headers: {
@@ -646,8 +794,22 @@ data: ${JSON.stringify(result.data)}
646
794
  const doStub = namespace.get(id);
647
795
  const isInitialized = await doStub.isInitialized();
648
796
  if (isInitializationRequest) {
649
- await doStub._init(ctx.props);
650
- await doStub.setInitialized();
797
+ try {
798
+ await doStub._init(ctx.props);
799
+ await doStub.setInitialized();
800
+ } catch (error) {
801
+ console.error("Failed to initialize McpAgent:", error);
802
+ const errorMessage = error instanceof Error ? error.message : String(error);
803
+ const body2 = JSON.stringify({
804
+ error: {
805
+ code: -32001,
806
+ message: `Initialization failed: ${errorMessage}`
807
+ },
808
+ id: null,
809
+ jsonrpc: "2.0"
810
+ });
811
+ return new Response(body2, { status: 500 });
812
+ }
651
813
  } else if (!isInitialized) {
652
814
  const body2 = JSON.stringify({
653
815
  error: {
@@ -658,15 +820,22 @@ data: ${JSON.stringify(result.data)}
658
820
  jsonrpc: "2.0"
659
821
  });
660
822
  return new Response(body2, { status: 404 });
823
+ } else {
824
+ await doStub.updateProps(ctx.props);
661
825
  }
662
826
  const { readable, writable } = new TransformStream();
663
827
  const writer = writable.getWriter();
664
828
  const encoder = new TextEncoder();
665
829
  const upgradeUrl = new URL(request.url);
666
830
  upgradeUrl.pathname = "/streamable-http";
831
+ const existingHeaders = {};
832
+ request.headers.forEach((value, key) => {
833
+ existingHeaders[key] = value;
834
+ });
667
835
  const response = await doStub.fetch(
668
836
  new Request(upgradeUrl, {
669
837
  headers: {
838
+ ...existingHeaders,
670
839
  Upgrade: "websocket",
671
840
  // Required by PartyServer
672
841
  "x-partykit-room": sessionId
@@ -778,6 +947,9 @@ data: ${JSON.stringify(result.data)}
778
947
  }
779
948
  };
780
949
  export {
781
- McpAgent
950
+ ElicitRequestSchema,
951
+ McpAgent,
952
+ SSEEdgeClientTransport,
953
+ StreamableHTTPEdgeClientTransport
782
954
  };
783
955
  //# sourceMappingURL=index.js.map