agents 0.0.109 → 0.0.111

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.
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  MCPClientManager,
3
3
  getNamespacedData
4
- } from "../chunk-UNG3FXYX.js";
4
+ } from "../chunk-HY7ZLHJB.js";
5
5
  export {
6
6
  MCPClientManager,
7
7
  getNamespacedData
@@ -1,41 +1,21 @@
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
- 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,10 +1,10 @@
1
1
  import {
2
2
  Agent
3
- } from "../chunk-3IQQY2UH.js";
3
+ } from "../chunk-JXN5WZFQ.js";
4
4
  import {
5
5
  SSEEdgeClientTransport,
6
6
  StreamableHTTPEdgeClientTransport
7
- } from "../chunk-UNG3FXYX.js";
7
+ } from "../chunk-HY7ZLHJB.js";
8
8
  import "../chunk-PVQZBKN7.js";
9
9
  import "../chunk-KUH345EY.js";
10
10
 
@@ -18,6 +18,9 @@ import {
18
18
  isJSONRPCRequest,
19
19
  isJSONRPCResponse
20
20
  } from "@modelcontextprotocol/sdk/types.js";
21
+ import {
22
+ ElicitRequestSchema
23
+ } from "@modelcontextprotocol/sdk/types.js";
21
24
  var MAXIMUM_MESSAGE_SIZE_BYTES = 4 * 1024 * 1024;
22
25
  function corsHeaders(_request, corsOptions = {}) {
23
26
  const origin = "*";
@@ -144,6 +147,45 @@ var McpAgent = class _McpAgent extends DurableObject {
144
147
  setState(state) {
145
148
  return this._agent.setState(state);
146
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
147
189
  // biome-ignore lint/correctness/noUnusedFunctionParameters: overriden later
148
190
  onStateUpdate(state, source) {
149
191
  }
@@ -181,15 +223,32 @@ var McpAgent = class _McpAgent extends DurableObject {
181
223
  await server.connect(this._transport);
182
224
  }
183
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
+ }
184
239
  async _init(props) {
185
- await this.ctx.storage.put("props", props ?? {});
240
+ await this.updateProps(props);
186
241
  if (!this.ctx.storage.get("transportType")) {
187
242
  await this.ctx.storage.put("transportType", "unset");
188
243
  }
189
- this.props = props;
190
244
  if (!this.initRun) {
191
245
  this.initRun = true;
192
- 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
+ }
193
252
  }
194
253
  }
195
254
  async setInitialized() {
@@ -198,6 +257,10 @@ var McpAgent = class _McpAgent extends DurableObject {
198
257
  async isInitialized() {
199
258
  return await this.ctx.storage.get("initialized") === true;
200
259
  }
260
+ async updateProps(props) {
261
+ await this.ctx.storage.put("props", props ?? {});
262
+ this.props = props;
263
+ }
201
264
  async _initialize() {
202
265
  await this.ctx.blockConcurrencyWhile(async () => {
203
266
  this._status = "starting";
@@ -284,14 +347,78 @@ var McpAgent = class _McpAgent extends DurableObject {
284
347
  this._transport?.onerror?.(error);
285
348
  return;
286
349
  }
350
+ if (await this._handleElicitationResponse(message)) {
351
+ return;
352
+ }
287
353
  if (isJSONRPCRequest(message)) {
288
354
  this._requestIdToConnectionId.set(message.id.toString(), connection.id);
289
355
  }
290
356
  this._transport?.onmessage?.(message);
291
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
+ }
292
419
  // All messages received over SSE after the initial connection has been established
293
420
  // will be passed here
294
- async onSSEMcpMessage(_sessionId, request) {
421
+ async onSSEMcpMessage(_sessionId, messageBody) {
295
422
  if (this._status !== "started") {
296
423
  await this._initialize();
297
424
  }
@@ -299,14 +426,16 @@ var McpAgent = class _McpAgent extends DurableObject {
299
426
  return new Error("Internal Server Error: Expected SSE protocol");
300
427
  }
301
428
  try {
302
- const message = await request.json();
303
429
  let parsedMessage;
304
430
  try {
305
- parsedMessage = JSONRPCMessageSchema.parse(message);
431
+ parsedMessage = JSONRPCMessageSchema.parse(messageBody);
306
432
  } catch (error) {
307
433
  this._transport?.onerror?.(error);
308
434
  throw error;
309
435
  }
436
+ if (await this._handleElicitationResponse(parsedMessage)) {
437
+ return null;
438
+ }
310
439
  this._transport?.onmessage?.(parsedMessage);
311
440
  return null;
312
441
  } catch (error) {
@@ -383,7 +512,16 @@ data: ${relativeUrlWithSession}
383
512
  writer.write(encoder.encode(endpointMessage));
384
513
  const id = namespace.idFromName(`sse:${sessionId}`);
385
514
  const doStub = namespace.get(id);
386
- 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
+ }
387
525
  const upgradeUrl = new URL(request.url);
388
526
  upgradeUrl.pathname = "/sse";
389
527
  const existingHeaders = {};
@@ -484,7 +622,9 @@ data: ${JSON.stringify(result.data)}
484
622
  }
485
623
  const id = namespace.idFromName(`sse:${sessionId}`);
486
624
  const doStub = namespace.get(id);
487
- 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);
488
628
  if (error) {
489
629
  return new Response(error.message, {
490
630
  headers: {
@@ -654,8 +794,22 @@ data: ${JSON.stringify(result.data)}
654
794
  const doStub = namespace.get(id);
655
795
  const isInitialized = await doStub.isInitialized();
656
796
  if (isInitializationRequest) {
657
- await doStub._init(ctx.props);
658
- 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
+ }
659
813
  } else if (!isInitialized) {
660
814
  const body2 = JSON.stringify({
661
815
  error: {
@@ -666,6 +820,8 @@ data: ${JSON.stringify(result.data)}
666
820
  jsonrpc: "2.0"
667
821
  });
668
822
  return new Response(body2, { status: 404 });
823
+ } else {
824
+ await doStub.updateProps(ctx.props);
669
825
  }
670
826
  const { readable, writable } = new TransformStream();
671
827
  const writer = writable.getWriter();
@@ -791,6 +947,7 @@ data: ${JSON.stringify(result.data)}
791
947
  }
792
948
  };
793
949
  export {
950
+ ElicitRequestSchema,
794
951
  McpAgent,
795
952
  SSEEdgeClientTransport,
796
953
  StreamableHTTPEdgeClientTransport