agents 0.0.0-1232c19 → 0.0.0-14616d3

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 (51) hide show
  1. package/README.md +131 -25
  2. package/dist/ai-chat-agent.d.ts +11 -7
  3. package/dist/ai-chat-agent.js +146 -47
  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 +61 -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-767EASBA.js → chunk-LL2AFX7V.js} +5 -2
  16. package/dist/chunk-LL2AFX7V.js.map +1 -0
  17. package/dist/{chunk-ZRRXJUAA.js → chunk-O4KIASSE.js} +632 -118
  18. package/dist/chunk-O4KIASSE.js.map +1 -0
  19. package/dist/{chunk-NKZZ66QY.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-E3LCYPCB.js → chunk-VYENMKFS.js} +163 -20
  24. package/dist/chunk-VYENMKFS.js.map +1 -0
  25. package/dist/client-CpU7236R.d.ts +4607 -0
  26. package/dist/client.d.ts +2 -2
  27. package/dist/client.js +2 -1
  28. package/dist/index.d.ts +164 -20
  29. package/dist/index.js +13 -4
  30. package/dist/mcp/client.d.ts +9 -781
  31. package/dist/mcp/client.js +1 -1
  32. package/dist/mcp/do-oauth-client-provider.d.ts +1 -0
  33. package/dist/mcp/do-oauth-client-provider.js +1 -1
  34. package/dist/mcp/index.d.ts +35 -7
  35. package/dist/mcp/index.js +191 -18
  36. package/dist/mcp/index.js.map +1 -1
  37. package/dist/observability/index.d.ts +46 -0
  38. package/dist/observability/index.js +11 -0
  39. package/dist/observability/index.js.map +1 -0
  40. package/dist/react.d.ts +9 -5
  41. package/dist/react.js +7 -5
  42. package/dist/react.js.map +1 -1
  43. package/dist/schedule.d.ts +79 -5
  44. package/dist/schedule.js +15 -2
  45. package/dist/schedule.js.map +1 -1
  46. package/package.json +41 -28
  47. package/src/index.ts +841 -153
  48. package/dist/chunk-767EASBA.js.map +0 -1
  49. package/dist/chunk-E3LCYPCB.js.map +0 -1
  50. package/dist/chunk-NKZZ66QY.js.map +0 -1
  51. 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-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-767EASBA.js";
3
+ } from "../chunk-LL2AFX7V.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-CpU7236R.js';
2
+ export { S as SSEEdgeClientTransport, a as StreamableHTTPEdgeClientTransport } from '../client-CpU7236R.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,32 @@
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-O4KIASSE.js";
4
+ import {
5
+ SSEEdgeClientTransport,
6
+ StreamableHTTPEdgeClientTransport
7
+ } from "../chunk-VYENMKFS.js";
8
+ import "../chunk-LL2AFX7V.js";
9
+ import "../chunk-QEVM4BVL.js";
10
+ import "../chunk-AVYJQSLW.js";
7
11
 
8
12
  // src/mcp/index.ts
9
13
  import { DurableObject } from "cloudflare:workers";
10
14
  import {
11
15
  InitializeRequestSchema,
16
+ JSONRPCMessageSchema,
12
17
  isJSONRPCError,
13
18
  isJSONRPCNotification,
14
19
  isJSONRPCRequest,
15
- isJSONRPCResponse,
16
- JSONRPCMessageSchema
20
+ isJSONRPCResponse
21
+ } from "@modelcontextprotocol/sdk/types.js";
22
+ import {
23
+ ElicitRequestSchema
17
24
  } from "@modelcontextprotocol/sdk/types.js";
18
25
  var MAXIMUM_MESSAGE_SIZE_BYTES = 4 * 1024 * 1024;
19
26
  function corsHeaders(_request, corsOptions = {}) {
20
27
  const origin = "*";
21
28
  return {
22
- "Access-Control-Allow-Headers": corsOptions.headers || "Content-Type, mcp-session-id",
29
+ "Access-Control-Allow-Headers": corsOptions.headers || "Content-Type, mcp-session-id, mcp-protocol-version",
23
30
  "Access-Control-Allow-Methods": corsOptions.methods || "GET, POST, OPTIONS",
24
31
  "Access-Control-Allow-Origin": corsOptions.origin || origin,
25
32
  "Access-Control-Expose-Headers": corsOptions.exposeHeaders || "mcp-session-id",
@@ -141,6 +148,45 @@ var McpAgent = class _McpAgent extends DurableObject {
141
148
  setState(state) {
142
149
  return this._agent.setState(state);
143
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
144
190
  // biome-ignore lint/correctness/noUnusedFunctionParameters: overriden later
145
191
  onStateUpdate(state, source) {
146
192
  }
@@ -178,15 +224,32 @@ var McpAgent = class _McpAgent extends DurableObject {
178
224
  await server.connect(this._transport);
179
225
  }
180
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
+ }
181
240
  async _init(props) {
182
- await this.ctx.storage.put("props", props ?? {});
241
+ await this.updateProps(props);
183
242
  if (!this.ctx.storage.get("transportType")) {
184
243
  await this.ctx.storage.put("transportType", "unset");
185
244
  }
186
- this.props = props;
187
245
  if (!this.initRun) {
188
246
  this.initRun = true;
189
- 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
+ }
190
253
  }
191
254
  }
192
255
  async setInitialized() {
@@ -195,6 +258,10 @@ var McpAgent = class _McpAgent extends DurableObject {
195
258
  async isInitialized() {
196
259
  return await this.ctx.storage.get("initialized") === true;
197
260
  }
261
+ async updateProps(props) {
262
+ await this.ctx.storage.put("props", props ?? {});
263
+ this.props = props;
264
+ }
198
265
  async _initialize() {
199
266
  await this.ctx.blockConcurrencyWhile(async () => {
200
267
  this._status = "starting";
@@ -281,14 +348,78 @@ var McpAgent = class _McpAgent extends DurableObject {
281
348
  this._transport?.onerror?.(error);
282
349
  return;
283
350
  }
351
+ if (await this._handleElicitationResponse(message)) {
352
+ return;
353
+ }
284
354
  if (isJSONRPCRequest(message)) {
285
355
  this._requestIdToConnectionId.set(message.id.toString(), connection.id);
286
356
  }
287
357
  this._transport?.onmessage?.(message);
288
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
+ }
289
420
  // All messages received over SSE after the initial connection has been established
290
421
  // will be passed here
291
- async onSSEMcpMessage(_sessionId, request) {
422
+ async onSSEMcpMessage(_sessionId, messageBody) {
292
423
  if (this._status !== "started") {
293
424
  await this._initialize();
294
425
  }
@@ -296,14 +427,16 @@ var McpAgent = class _McpAgent extends DurableObject {
296
427
  return new Error("Internal Server Error: Expected SSE protocol");
297
428
  }
298
429
  try {
299
- const message = await request.json();
300
430
  let parsedMessage;
301
431
  try {
302
- parsedMessage = JSONRPCMessageSchema.parse(message);
432
+ parsedMessage = JSONRPCMessageSchema.parse(messageBody);
303
433
  } catch (error) {
304
434
  this._transport?.onerror?.(error);
305
435
  throw error;
306
436
  }
437
+ if (await this._handleElicitationResponse(parsedMessage)) {
438
+ return null;
439
+ }
307
440
  this._transport?.onmessage?.(parsedMessage);
308
441
  return null;
309
442
  } catch (error) {
@@ -380,12 +513,26 @@ data: ${relativeUrlWithSession}
380
513
  writer.write(encoder.encode(endpointMessage));
381
514
  const id = namespace.idFromName(`sse:${sessionId}`);
382
515
  const doStub = namespace.get(id);
383
- 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
+ }
384
526
  const upgradeUrl = new URL(request.url);
385
527
  upgradeUrl.pathname = "/sse";
528
+ const existingHeaders = {};
529
+ request.headers.forEach((value, key) => {
530
+ existingHeaders[key] = value;
531
+ });
386
532
  const response = await doStub.fetch(
387
533
  new Request(upgradeUrl, {
388
534
  headers: {
535
+ ...existingHeaders,
389
536
  Upgrade: "websocket",
390
537
  // Required by PartyServer
391
538
  "x-partykit-room": sessionId
@@ -476,7 +623,9 @@ data: ${JSON.stringify(result.data)}
476
623
  }
477
624
  const id = namespace.idFromName(`sse:${sessionId}`);
478
625
  const doStub = namespace.get(id);
479
- 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);
480
629
  if (error) {
481
630
  return new Response(error.message, {
482
631
  headers: {
@@ -646,8 +795,22 @@ data: ${JSON.stringify(result.data)}
646
795
  const doStub = namespace.get(id);
647
796
  const isInitialized = await doStub.isInitialized();
648
797
  if (isInitializationRequest) {
649
- await doStub._init(ctx.props);
650
- 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
+ }
651
814
  } else if (!isInitialized) {
652
815
  const body2 = JSON.stringify({
653
816
  error: {
@@ -658,15 +821,22 @@ data: ${JSON.stringify(result.data)}
658
821
  jsonrpc: "2.0"
659
822
  });
660
823
  return new Response(body2, { status: 404 });
824
+ } else {
825
+ await doStub.updateProps(ctx.props);
661
826
  }
662
827
  const { readable, writable } = new TransformStream();
663
828
  const writer = writable.getWriter();
664
829
  const encoder = new TextEncoder();
665
830
  const upgradeUrl = new URL(request.url);
666
831
  upgradeUrl.pathname = "/streamable-http";
832
+ const existingHeaders = {};
833
+ request.headers.forEach((value, key) => {
834
+ existingHeaders[key] = value;
835
+ });
667
836
  const response = await doStub.fetch(
668
837
  new Request(upgradeUrl, {
669
838
  headers: {
839
+ ...existingHeaders,
670
840
  Upgrade: "websocket",
671
841
  // Required by PartyServer
672
842
  "x-partykit-room": sessionId
@@ -778,6 +948,9 @@ data: ${JSON.stringify(result.data)}
778
948
  }
779
949
  };
780
950
  export {
781
- McpAgent
951
+ ElicitRequestSchema,
952
+ McpAgent,
953
+ SSEEdgeClientTransport,
954
+ StreamableHTTPEdgeClientTransport
782
955
  };
783
956
  //# sourceMappingURL=index.js.map