agents 0.0.0-9ae8ee3 → 0.0.0-9beccdd

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 (50) hide show
  1. package/README.md +31 -6
  2. package/dist/ai-chat-agent.d.ts +9 -8
  3. package/dist/ai-chat-agent.js +142 -59
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration.d.ts +152 -0
  6. package/dist/ai-chat-v5-migration.js +19 -0
  7. package/dist/ai-chat-v5-migration.js.map +1 -0
  8. package/dist/ai-react.d.ts +59 -70
  9. package/dist/ai-react.js +144 -37
  10. package/dist/ai-react.js.map +1 -1
  11. package/dist/ai-types.d.ts +36 -19
  12. package/dist/ai-types.js +6 -0
  13. package/dist/chunk-AVYJQSLW.js +17 -0
  14. package/dist/chunk-AVYJQSLW.js.map +1 -0
  15. package/dist/{chunk-PVQZBKN7.js → chunk-LL2AFX7V.js} +5 -2
  16. package/dist/chunk-LL2AFX7V.js.map +1 -0
  17. package/dist/{chunk-3IQQY2UH.js → chunk-PNF6ZMUA.js} +114 -88
  18. package/dist/chunk-PNF6ZMUA.js.map +1 -0
  19. package/dist/{chunk-KUH345EY.js → chunk-QEVM4BVL.js} +5 -5
  20. package/dist/chunk-QEVM4BVL.js.map +1 -0
  21. package/dist/chunk-UJVEAURM.js +150 -0
  22. package/dist/chunk-UJVEAURM.js.map +1 -0
  23. package/dist/{chunk-UNG3FXYX.js → chunk-VYENMKFS.js} +110 -23
  24. package/dist/chunk-VYENMKFS.js.map +1 -0
  25. package/dist/client-CcIORE73.d.ts +4607 -0
  26. package/dist/client.js +2 -1
  27. package/dist/index.d.ts +546 -32
  28. package/dist/index.js +7 -4
  29. package/dist/mcp/client.d.ts +9 -1052
  30. package/dist/mcp/client.js +1 -1
  31. package/dist/mcp/do-oauth-client-provider.d.ts +1 -0
  32. package/dist/mcp/do-oauth-client-provider.js +1 -1
  33. package/dist/mcp/index.d.ts +33 -28
  34. package/dist/mcp/index.js +172 -14
  35. package/dist/mcp/index.js.map +1 -1
  36. package/dist/observability/index.d.ts +46 -14
  37. package/dist/observability/index.js +5 -4
  38. package/dist/react.d.ts +4 -2
  39. package/dist/react.js +7 -5
  40. package/dist/react.js.map +1 -1
  41. package/dist/schedule.d.ts +83 -9
  42. package/dist/schedule.js +15 -2
  43. package/dist/schedule.js.map +1 -1
  44. package/package.json +15 -7
  45. package/src/index.ts +140 -97
  46. package/dist/chunk-3IQQY2UH.js.map +0 -1
  47. package/dist/chunk-KUH345EY.js.map +0 -1
  48. package/dist/chunk-PVQZBKN7.js.map +0 -1
  49. package/dist/chunk-UNG3FXYX.js.map +0 -1
  50. package/dist/index-CLW1aEBr.d.ts +0 -615
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  MCPClientManager,
3
3
  getNamespacedData
4
- } from "../chunk-UNG3FXYX.js";
4
+ } from "../chunk-VYENMKFS.js";
5
5
  export {
6
6
  MCPClientManager,
7
7
  getNamespacedData
@@ -15,6 +15,7 @@ declare class DurableObjectOAuthClientProvider implements AgentsOAuthProvider {
15
15
  private _clientId_;
16
16
  constructor(storage: DurableObjectStorage, clientName: string, baseRedirectUrl: string);
17
17
  get clientMetadata(): OAuthClientMetadata;
18
+ get clientUri(): string;
18
19
  get redirectUrl(): string;
19
20
  get clientId(): string;
20
21
  set clientId(clientId_: string);
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  DurableObjectOAuthClientProvider
3
- } from "../chunk-PVQZBKN7.js";
3
+ } from "../chunk-LL2AFX7V.js";
4
4
  export {
5
5
  DurableObjectOAuthClientProvider
6
6
  };
@@ -1,41 +1,21 @@
1
- import { MCPClientManager } from './client.js';
1
+ import { M as MCPClientManager } from '../client-CcIORE73.js';
2
+ export { S as SSEEdgeClientTransport, a as StreamableHTTPEdgeClientTransport } from '../client-CcIORE73.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
- import { SSEClientTransport, SSEClientTransportOptions } from '@modelcontextprotocol/sdk/client/sse.js';
7
- import { StreamableHTTPClientTransport, StreamableHTTPClientTransportOptions } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
8
9
  import 'zod';
9
10
  import '@modelcontextprotocol/sdk/client/index.js';
10
11
  import '@modelcontextprotocol/sdk/shared/protocol.js';
11
- import '@modelcontextprotocol/sdk/types.js';
12
12
  import 'ai';
13
+ import '@modelcontextprotocol/sdk/client/sse.js';
14
+ import '@modelcontextprotocol/sdk/client/streamableHttp.js';
13
15
  import './do-oauth-client-provider.js';
14
16
  import '@modelcontextprotocol/sdk/client/auth.js';
15
17
  import '@modelcontextprotocol/sdk/shared/auth.js';
16
18
 
17
- declare class SSEEdgeClientTransport extends SSEClientTransport {
18
- private authProvider;
19
- /**
20
- * Creates a new EdgeSSEClientTransport, which overrides fetch to be compatible with the CF workers environment
21
- */
22
- constructor(url: URL, options: SSEClientTransportOptions);
23
- authHeaders(): Promise<{
24
- Authorization: string;
25
- } | undefined>;
26
- }
27
-
28
- declare class StreamableHTTPEdgeClientTransport extends StreamableHTTPClientTransport {
29
- private authProvider;
30
- /**
31
- * Creates a new StreamableHTTPEdgeClientTransport, which overrides fetch to be compatible with the CF workers environment
32
- */
33
- constructor(url: URL, options: StreamableHTTPClientTransportOptions);
34
- authHeaders(): Promise<{
35
- Authorization: string;
36
- } | undefined>;
37
- }
38
-
39
19
  interface CORSOptions {
40
20
  origin?: string;
41
21
  methods?: string;
@@ -63,6 +43,13 @@ declare abstract class McpAgent<Env = unknown, State = unknown, Props extends Re
63
43
  get state(): State;
64
44
  sql<T = Record<string, string | number | boolean | null>>(strings: TemplateStringsArray, ...values: (string | number | boolean | null)[]): T[];
65
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>;
66
53
  onStateUpdate(state: State | undefined, source: Connection | "server"): void;
67
54
  onStart(): Promise<void>;
68
55
  /**
@@ -72,15 +59,33 @@ declare abstract class McpAgent<Env = unknown, State = unknown, Props extends Re
72
59
  props: Props;
73
60
  initRun: boolean;
74
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
+ };
75
72
  _init(props: Props): Promise<void>;
76
73
  setInitialized(): Promise<void>;
77
74
  isInitialized(): Promise<boolean>;
75
+ updateProps(props: Props): Promise<void>;
78
76
  private _initialize;
79
77
  fetch(request: Request): Promise<Response>;
80
78
  getWebSocket(): WebSocket | null;
81
79
  getWebSocketForResponseID(id: string): WebSocket | null;
82
80
  onMessage(connection: Connection, event: WSMessage): Promise<void>;
83
- 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>;
84
89
  webSocketMessage(ws: WebSocket, event: ArrayBuffer | string): Promise<void>;
85
90
  webSocketError(ws: WebSocket, error: unknown): Promise<void>;
86
91
  webSocketClose(ws: WebSocket, code: number, reason: string, wasClean: boolean): Promise<void>;
@@ -104,4 +109,4 @@ declare abstract class McpAgent<Env = unknown, State = unknown, Props extends Re
104
109
  };
105
110
  }
106
111
 
107
- export { McpAgent, SSEEdgeClientTransport, StreamableHTTPEdgeClientTransport };
112
+ export { McpAgent };
package/dist/mcp/index.js CHANGED
@@ -1,12 +1,13 @@
1
1
  import {
2
2
  Agent
3
- } from "../chunk-3IQQY2UH.js";
3
+ } from "../chunk-PNF6ZMUA.js";
4
4
  import {
5
5
  SSEEdgeClientTransport,
6
6
  StreamableHTTPEdgeClientTransport
7
- } from "../chunk-UNG3FXYX.js";
8
- import "../chunk-PVQZBKN7.js";
9
- import "../chunk-KUH345EY.js";
7
+ } from "../chunk-VYENMKFS.js";
8
+ import "../chunk-LL2AFX7V.js";
9
+ import "../chunk-QEVM4BVL.js";
10
+ import "../chunk-AVYJQSLW.js";
10
11
 
11
12
  // src/mcp/index.ts
12
13
  import { DurableObject } from "cloudflare:workers";
@@ -18,6 +19,9 @@ import {
18
19
  isJSONRPCRequest,
19
20
  isJSONRPCResponse
20
21
  } from "@modelcontextprotocol/sdk/types.js";
22
+ import {
23
+ ElicitRequestSchema
24
+ } from "@modelcontextprotocol/sdk/types.js";
21
25
  var MAXIMUM_MESSAGE_SIZE_BYTES = 4 * 1024 * 1024;
22
26
  function corsHeaders(_request, corsOptions = {}) {
23
27
  const origin = "*";
@@ -144,6 +148,45 @@ var McpAgent = class _McpAgent extends DurableObject {
144
148
  setState(state) {
145
149
  return this._agent.setState(state);
146
150
  }
151
+ /**
152
+ * Elicit user input with a message and schema
153
+ */
154
+ async elicitInput(params) {
155
+ const requestId = `elicit_${Math.random().toString(36).substring(2, 11)}`;
156
+ await this.ctx.storage.put(`elicitation:${requestId}`, {
157
+ message: params.message,
158
+ requestedSchema: params.requestedSchema,
159
+ timestamp: Date.now()
160
+ });
161
+ const elicitRequest = {
162
+ jsonrpc: "2.0",
163
+ id: requestId,
164
+ method: "elicitation/create",
165
+ params: {
166
+ message: params.message,
167
+ requestedSchema: params.requestedSchema
168
+ }
169
+ };
170
+ if (this._transport) {
171
+ await this._transport.send(elicitRequest);
172
+ } else {
173
+ const connections = this._agent?.getConnections();
174
+ if (!connections || Array.from(connections).length === 0) {
175
+ await this.ctx.storage.delete(`elicitation:${requestId}`);
176
+ throw new Error("No active connections available for elicitation");
177
+ }
178
+ const connectionList = Array.from(connections);
179
+ for (const connection of connectionList) {
180
+ try {
181
+ connection.send(JSON.stringify(elicitRequest));
182
+ } catch (error) {
183
+ console.error("Failed to send elicitation request:", error);
184
+ }
185
+ }
186
+ }
187
+ return this._waitForElicitationResponse(requestId);
188
+ }
189
+ // we leave the variables as unused for autocomplete purposes
147
190
  // biome-ignore lint/correctness/noUnusedFunctionParameters: overriden later
148
191
  onStateUpdate(state, source) {
149
192
  }
@@ -181,15 +224,32 @@ var McpAgent = class _McpAgent extends DurableObject {
181
224
  await server.connect(this._transport);
182
225
  }
183
226
  }
227
+ /**
228
+ * Handle errors that occur during initialization or operation.
229
+ * Override this method to provide custom error handling.
230
+ * @param error - The error that occurred
231
+ * @returns An error response object with status code and message
232
+ */
233
+ onError(error) {
234
+ console.error("McpAgent error:", error);
235
+ return {
236
+ status: 500,
237
+ message: error.message || "An unexpected error occurred during initialization"
238
+ };
239
+ }
184
240
  async _init(props) {
185
- await this.ctx.storage.put("props", props ?? {});
241
+ await this.updateProps(props);
186
242
  if (!this.ctx.storage.get("transportType")) {
187
243
  await this.ctx.storage.put("transportType", "unset");
188
244
  }
189
- this.props = props;
190
245
  if (!this.initRun) {
191
246
  this.initRun = true;
192
- await this.init();
247
+ try {
248
+ await this.init();
249
+ } catch (error) {
250
+ const errorResponse = this.onError(error);
251
+ throw new Error(`Initialization failed: ${errorResponse.message}`);
252
+ }
193
253
  }
194
254
  }
195
255
  async setInitialized() {
@@ -198,6 +258,10 @@ var McpAgent = class _McpAgent extends DurableObject {
198
258
  async isInitialized() {
199
259
  return await this.ctx.storage.get("initialized") === true;
200
260
  }
261
+ async updateProps(props) {
262
+ await this.ctx.storage.put("props", props ?? {});
263
+ this.props = props;
264
+ }
201
265
  async _initialize() {
202
266
  await this.ctx.blockConcurrencyWhile(async () => {
203
267
  this._status = "starting";
@@ -284,14 +348,78 @@ var McpAgent = class _McpAgent extends DurableObject {
284
348
  this._transport?.onerror?.(error);
285
349
  return;
286
350
  }
351
+ if (await this._handleElicitationResponse(message)) {
352
+ return;
353
+ }
287
354
  if (isJSONRPCRequest(message)) {
288
355
  this._requestIdToConnectionId.set(message.id.toString(), connection.id);
289
356
  }
290
357
  this._transport?.onmessage?.(message);
291
358
  }
359
+ /**
360
+ * Wait for elicitation response through storage polling
361
+ */
362
+ async _waitForElicitationResponse(requestId) {
363
+ const startTime = Date.now();
364
+ const timeout = 6e4;
365
+ try {
366
+ while (Date.now() - startTime < timeout) {
367
+ const response = await this.ctx.storage.get(
368
+ `elicitation:response:${requestId}`
369
+ );
370
+ if (response) {
371
+ await this.ctx.storage.delete(`elicitation:${requestId}`);
372
+ await this.ctx.storage.delete(`elicitation:response:${requestId}`);
373
+ return response;
374
+ }
375
+ await new Promise((resolve) => setTimeout(resolve, 100));
376
+ }
377
+ throw new Error("Elicitation request timed out");
378
+ } finally {
379
+ await this.ctx.storage.delete(`elicitation:${requestId}`);
380
+ await this.ctx.storage.delete(`elicitation:response:${requestId}`);
381
+ }
382
+ }
383
+ /**
384
+ * Handle elicitation responses */
385
+ async _handleElicitationResponse(message) {
386
+ if (isJSONRPCResponse(message) && message.result) {
387
+ const requestId = message.id?.toString();
388
+ if (!requestId || !requestId.startsWith("elicit_")) return false;
389
+ const pendingRequest = await this.ctx.storage.get(
390
+ `elicitation:${requestId}`
391
+ );
392
+ if (!pendingRequest) return false;
393
+ await this.ctx.storage.put(
394
+ `elicitation:response:${requestId}`,
395
+ message.result
396
+ );
397
+ return true;
398
+ }
399
+ if (isJSONRPCError(message)) {
400
+ const requestId = message.id?.toString();
401
+ if (!requestId || !requestId.startsWith("elicit_")) return false;
402
+ const pendingRequest = await this.ctx.storage.get(
403
+ `elicitation:${requestId}`
404
+ );
405
+ if (!pendingRequest) return false;
406
+ const errorResult = {
407
+ action: "cancel",
408
+ content: {
409
+ error: message.error.message || "Elicitation request failed"
410
+ }
411
+ };
412
+ await this.ctx.storage.put(
413
+ `elicitation:response:${requestId}`,
414
+ errorResult
415
+ );
416
+ return true;
417
+ }
418
+ return false;
419
+ }
292
420
  // All messages received over SSE after the initial connection has been established
293
421
  // will be passed here
294
- async onSSEMcpMessage(_sessionId, request) {
422
+ async onSSEMcpMessage(_sessionId, messageBody) {
295
423
  if (this._status !== "started") {
296
424
  await this._initialize();
297
425
  }
@@ -299,14 +427,16 @@ var McpAgent = class _McpAgent extends DurableObject {
299
427
  return new Error("Internal Server Error: Expected SSE protocol");
300
428
  }
301
429
  try {
302
- const message = await request.json();
303
430
  let parsedMessage;
304
431
  try {
305
- parsedMessage = JSONRPCMessageSchema.parse(message);
432
+ parsedMessage = JSONRPCMessageSchema.parse(messageBody);
306
433
  } catch (error) {
307
434
  this._transport?.onerror?.(error);
308
435
  throw error;
309
436
  }
437
+ if (await this._handleElicitationResponse(parsedMessage)) {
438
+ return null;
439
+ }
310
440
  this._transport?.onmessage?.(parsedMessage);
311
441
  return null;
312
442
  } catch (error) {
@@ -383,7 +513,16 @@ data: ${relativeUrlWithSession}
383
513
  writer.write(encoder.encode(endpointMessage));
384
514
  const id = namespace.idFromName(`sse:${sessionId}`);
385
515
  const doStub = namespace.get(id);
386
- await doStub._init(ctx.props);
516
+ try {
517
+ await doStub._init(ctx.props);
518
+ } catch (error) {
519
+ console.error("Failed to initialize McpAgent:", error);
520
+ await writer.close();
521
+ const errorMessage = error instanceof Error ? error.message : String(error);
522
+ return new Response(`Initialization failed: ${errorMessage}`, {
523
+ status: 500
524
+ });
525
+ }
387
526
  const upgradeUrl = new URL(request.url);
388
527
  upgradeUrl.pathname = "/sse";
389
528
  const existingHeaders = {};
@@ -484,7 +623,9 @@ data: ${JSON.stringify(result.data)}
484
623
  }
485
624
  const id = namespace.idFromName(`sse:${sessionId}`);
486
625
  const doStub = namespace.get(id);
487
- const error = await doStub.onSSEMcpMessage(sessionId, request);
626
+ const messageBody = await request.json();
627
+ await doStub.updateProps(ctx.props);
628
+ const error = await doStub.onSSEMcpMessage(sessionId, messageBody);
488
629
  if (error) {
489
630
  return new Response(error.message, {
490
631
  headers: {
@@ -654,8 +795,22 @@ data: ${JSON.stringify(result.data)}
654
795
  const doStub = namespace.get(id);
655
796
  const isInitialized = await doStub.isInitialized();
656
797
  if (isInitializationRequest) {
657
- await doStub._init(ctx.props);
658
- await doStub.setInitialized();
798
+ try {
799
+ await doStub._init(ctx.props);
800
+ await doStub.setInitialized();
801
+ } catch (error) {
802
+ console.error("Failed to initialize McpAgent:", error);
803
+ const errorMessage = error instanceof Error ? error.message : String(error);
804
+ const body2 = JSON.stringify({
805
+ error: {
806
+ code: -32001,
807
+ message: `Initialization failed: ${errorMessage}`
808
+ },
809
+ id: null,
810
+ jsonrpc: "2.0"
811
+ });
812
+ return new Response(body2, { status: 500 });
813
+ }
659
814
  } else if (!isInitialized) {
660
815
  const body2 = JSON.stringify({
661
816
  error: {
@@ -666,6 +821,8 @@ data: ${JSON.stringify(result.data)}
666
821
  jsonrpc: "2.0"
667
822
  });
668
823
  return new Response(body2, { status: 404 });
824
+ } else {
825
+ await doStub.updateProps(ctx.props);
669
826
  }
670
827
  const { readable, writable } = new TransformStream();
671
828
  const writer = writable.getWriter();
@@ -791,6 +948,7 @@ data: ${JSON.stringify(result.data)}
791
948
  }
792
949
  };
793
950
  export {
951
+ ElicitRequestSchema,
794
952
  McpAgent,
795
953
  SSEEdgeClientTransport,
796
954
  StreamableHTTPEdgeClientTransport