agents 0.0.52 → 0.0.54

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,32 +1,40 @@
1
1
  import * as zod from 'zod';
2
- import { Tool, Prompt as Prompt$1, Resource, ResourceTemplate, ServerCapabilities, ClientCapabilities, CallToolRequest, CallToolResultSchema, CompatibilityCallToolResultSchema, ReadResourceRequest, GetPromptRequest } from '@modelcontextprotocol/sdk/types.js';
2
+ import { Tool, Prompt, Resource, ResourceTemplate, ServerCapabilities, ClientCapabilities, CallToolRequest, CallToolResultSchema, CompatibilityCallToolResultSchema, ReadResourceRequest, GetPromptRequest } from '@modelcontextprotocol/sdk/types.js';
3
3
  import { Client } from '@modelcontextprotocol/sdk/client/index.js';
4
- import { SSEClientTransport, SSEClientTransportOptions } from '@modelcontextprotocol/sdk/client/sse.js';
4
+ import { SSEClientTransportOptions } from '@modelcontextprotocol/sdk/client/sse.js';
5
5
  import { RequestOptions } from '@modelcontextprotocol/sdk/shared/protocol.js';
6
+ import { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js';
6
7
 
7
8
  declare class MCPClientConnection {
9
+ url: URL;
8
10
  private info;
11
+ private options;
9
12
  client: Client;
10
- transport: SSEClientTransport;
11
- connected: boolean;
13
+ connectionState: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
12
14
  instructions?: string;
13
15
  tools: Tool[];
14
- prompts: Prompt$1[];
16
+ prompts: Prompt[];
15
17
  resources: Resource[];
16
18
  resourceTemplates: ResourceTemplate[];
17
19
  serverCapabilities: ServerCapabilities | undefined;
18
- constructor(url: URL, info: ConstructorParameters<typeof Client>[0], opts?: {
20
+ constructor(url: URL, info: ConstructorParameters<typeof Client>[0], options?: {
19
21
  transport: SSEClientTransportOptions;
20
22
  client: ConstructorParameters<typeof Client>[1];
21
23
  capabilities: ClientCapabilities;
22
24
  });
23
- init(): Promise<void>;
25
+ /**
26
+ * Initialize a client connection
27
+ *
28
+ * @param code Optional OAuth code to initialize the connection with if auth hasn't been initialized
29
+ * @returns
30
+ */
31
+ init(code?: string, clientId?: string): Promise<void>;
24
32
  /**
25
33
  * Notification handler registration
26
34
  */
27
35
  registerTools(): Promise<Tool[]>;
28
36
  registerResources(): Promise<Resource[]>;
29
- registerPrompts(): Promise<Prompt$1[]>;
37
+ registerPrompts(): Promise<Prompt[]>;
30
38
  registerResourceTemplates(): Promise<ResourceTemplate[]>;
31
39
  fetchTools(): Promise<{
32
40
  [x: string]: unknown;
@@ -44,8 +52,8 @@ declare class MCPClientConnection {
44
52
  [x: string]: unknown;
45
53
  name: string;
46
54
  uri: string;
47
- mimeType?: string | undefined;
48
55
  description?: string | undefined;
56
+ mimeType?: string | undefined;
49
57
  }[]>;
50
58
  fetchPrompts(): Promise<{
51
59
  [x: string]: unknown;
@@ -62,16 +70,33 @@ declare class MCPClientConnection {
62
70
  [x: string]: unknown;
63
71
  name: string;
64
72
  uriTemplate: string;
65
- mimeType?: string | undefined;
66
73
  description?: string | undefined;
74
+ mimeType?: string | undefined;
67
75
  }[]>;
68
76
  }
69
77
 
78
+ interface AgentsOAuthProvider extends OAuthClientProvider {
79
+ authUrl: string | undefined;
80
+ clientId: string | undefined;
81
+ }
82
+
70
83
  /**
71
84
  * Utility class that aggregates multiple MCP clients into one
72
85
  */
73
86
  declare class MCPClientManager {
87
+ private name;
88
+ private version;
89
+ private auth?;
74
90
  mcpConnections: Record<string, MCPClientConnection>;
91
+ /**
92
+ * @param name Name of the MCP client
93
+ * @param version Version of the MCP Client
94
+ * @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider
95
+ */
96
+ constructor(name: string, version: string, auth?: {
97
+ baseCallbackUri: string;
98
+ storage: DurableObjectStorage;
99
+ } | undefined);
75
100
  /**
76
101
  * Connect to and register an MCP server
77
102
  *
@@ -79,11 +104,25 @@ declare class MCPClientManager {
79
104
  * @param clientConfig Client config
80
105
  * @param capabilities Client capabilities (i.e. if the client supports roots/sampling)
81
106
  */
82
- connectToServer(url: URL, info: ConstructorParameters<typeof Client>[0], opts?: {
83
- transport: SSEClientTransportOptions;
84
- client: ConstructorParameters<typeof Client>[1];
85
- capabilities: ClientCapabilities;
86
- }): Promise<void>;
107
+ connect(url: string, opts?: {
108
+ reconnect?: {
109
+ id: string;
110
+ oauthClientId?: string;
111
+ oauthCode?: string;
112
+ };
113
+ transport?: SSEClientTransportOptions & {
114
+ authProvider: AgentsOAuthProvider;
115
+ };
116
+ client?: ConstructorParameters<typeof Client>[1];
117
+ capabilities?: ClientCapabilities;
118
+ }): Promise<{
119
+ id: string;
120
+ authUrl: string | undefined;
121
+ }>;
122
+ isCallbackRequest(req: Request): boolean;
123
+ handleCallbackRequest(req: Request): Promise<{
124
+ serverId: string;
125
+ }>;
87
126
  /**
88
127
  * @returns namespaced list of tools
89
128
  */
@@ -104,7 +143,7 @@ declare class MCPClientManager {
104
143
  * Namespaced version of callTool
105
144
  */
106
145
  callTool(params: CallToolRequest["params"] & {
107
- serverName: string;
146
+ serverId: string;
108
147
  }, resultSchema: typeof CallToolResultSchema | typeof CompatibilityCallToolResultSchema, options: RequestOptions): Promise<zod.objectOutputType<zod.objectUtil.extendShape<{
109
148
  _meta: zod.ZodOptional<zod.ZodObject<{}, "passthrough", zod.ZodTypeAny, zod.objectOutputType<{}, zod.ZodTypeAny, "passthrough">, zod.objectInputType<{}, zod.ZodTypeAny, "passthrough">>>;
110
149
  }, {
@@ -239,7 +278,7 @@ declare class MCPClientManager {
239
278
  * Namespaced version of readResource
240
279
  */
241
280
  readResource(params: ReadResourceRequest["params"] & {
242
- serverName: string;
281
+ serverId: string;
243
282
  }, options: RequestOptions): Promise<zod.objectOutputType<zod.objectUtil.extendShape<{
244
283
  _meta: zod.ZodOptional<zod.ZodObject<{}, "passthrough", zod.ZodTypeAny, zod.objectOutputType<{}, zod.ZodTypeAny, "passthrough">, zod.objectInputType<{}, zod.ZodTypeAny, "passthrough">>>;
245
284
  }, {
@@ -279,7 +318,7 @@ declare class MCPClientManager {
279
318
  * Namespaced version of getPrompt
280
319
  */
281
320
  getPrompt(params: GetPromptRequest["params"] & {
282
- serverName: string;
321
+ serverId: string;
283
322
  }, options: RequestOptions): Promise<zod.objectOutputType<zod.objectUtil.extendShape<{
284
323
  _meta: zod.ZodOptional<zod.ZodObject<{}, "passthrough", zod.ZodTypeAny, zod.objectOutputType<{}, zod.ZodTypeAny, "passthrough">, zod.objectInputType<{}, zod.ZodTypeAny, "passthrough">>>;
285
324
  }, {
@@ -658,16 +697,16 @@ declare class MCPClientManager {
658
697
  }
659
698
  type NamespacedData = {
660
699
  tools: (Tool & {
661
- serverName: string;
700
+ serverId: string;
662
701
  })[];
663
702
  prompts: (Prompt & {
664
- serverName: string;
703
+ serverId: string;
665
704
  })[];
666
705
  resources: (Resource & {
667
- serverName: string;
706
+ serverId: string;
668
707
  })[];
669
708
  resourceTemplates: (ResourceTemplate & {
670
- serverName: string;
709
+ serverId: string;
671
710
  })[];
672
711
  };
673
712
  declare function getNamespacedData<T extends keyof NamespacedData>(mcpClients: Record<string, MCPClientConnection>, type: T): NamespacedData[T];
@@ -9,12 +9,17 @@ var SSEEdgeClientTransport = class extends SSEClientTransport {
9
9
  * Creates a new EdgeSSEClientTransport, which overrides fetch to be compatible with the CF workers environment
10
10
  */
11
11
  constructor(url, options) {
12
- const fetchOverride = (url2, options2 = {}) => {
12
+ const fetchOverride = async (fetchUrl, fetchInit = {}) => {
13
+ const headers = await this.authHeaders();
13
14
  const workerOptions = {
14
- ...options2
15
+ ...fetchInit,
16
+ headers: {
17
+ ...fetchInit?.headers,
18
+ ...headers
19
+ }
15
20
  };
16
21
  delete workerOptions.mode;
17
- return global.fetch(url2, workerOptions);
22
+ return fetch(fetchUrl, workerOptions);
18
23
  };
19
24
  super(url, {
20
25
  ...options,
@@ -22,7 +27,17 @@ var SSEEdgeClientTransport = class extends SSEClientTransport {
22
27
  fetch: fetchOverride
23
28
  }
24
29
  });
25
- this.url = url;
30
+ this.authProvider = options.authProvider;
31
+ }
32
+ async authHeaders() {
33
+ if (this.authProvider) {
34
+ const tokens = await this.authProvider.tokens();
35
+ if (tokens) {
36
+ return {
37
+ Authorization: `Bearer ${tokens.access_token}`
38
+ };
39
+ }
40
+ }
26
41
  }
27
42
  };
28
43
 
@@ -34,24 +49,46 @@ import {
34
49
  } from "@modelcontextprotocol/sdk/types.js";
35
50
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
36
51
  var MCPClientConnection = class {
37
- constructor(url, info, opts = { transport: {}, client: {}, capabilities: {} }) {
52
+ constructor(url, info, options = { transport: {}, client: {}, capabilities: {} }) {
53
+ this.url = url;
38
54
  this.info = info;
39
- this.transport = new SSEEdgeClientTransport(url, opts.transport);
40
- this.client = new Client(info, opts.client);
41
- this.client.registerCapabilities(opts.capabilities);
42
- this.connected = false;
55
+ this.options = options;
56
+ this.connectionState = "connecting";
43
57
  this.tools = [];
44
58
  this.prompts = [];
45
59
  this.resources = [];
46
60
  this.resourceTemplates = [];
61
+ this.client = new Client(info, options.client);
62
+ this.client.registerCapabilities(options.capabilities);
47
63
  }
48
- async init() {
49
- await this.client.connect(this.transport);
64
+ /**
65
+ * Initialize a client connection
66
+ *
67
+ * @param code Optional OAuth code to initialize the connection with if auth hasn't been initialized
68
+ * @returns
69
+ */
70
+ async init(code, clientId) {
71
+ try {
72
+ const transport = new SSEEdgeClientTransport(
73
+ this.url,
74
+ this.options.transport
75
+ );
76
+ if (code) {
77
+ await transport.finishAuth(code);
78
+ }
79
+ await this.client.connect(transport);
80
+ } catch (e) {
81
+ if (e.toString().includes("Unauthorized")) {
82
+ this.connectionState = "authenticating";
83
+ return;
84
+ }
85
+ this.connectionState = "failed";
86
+ throw e;
87
+ }
88
+ this.connectionState = "discovering";
50
89
  this.serverCapabilities = await this.client.getServerCapabilities();
51
90
  if (!this.serverCapabilities) {
52
- throw new Error(
53
- `The MCP Server ${this.info.name} failed to return server capabilities`
54
- );
91
+ throw new Error("The MCP Server failed to return server capabilities");
55
92
  }
56
93
  const [instructions, tools, resources, prompts, resourceTemplates] = await Promise.all([
57
94
  this.client.getInstructions(),
@@ -65,6 +102,7 @@ var MCPClientConnection = class {
65
102
  this.resources = resources;
66
103
  this.prompts = prompts;
67
104
  this.resourceTemplates = resourceTemplates;
105
+ this.connectionState = "ready";
68
106
  }
69
107
  /**
70
108
  * Notification handler registration
@@ -165,9 +203,109 @@ var MCPClientConnection = class {
165
203
  }
166
204
  };
167
205
 
206
+ // src/mcp/do-oauth-client-provider.ts
207
+ var DurableObjectOAuthClientProvider = class {
208
+ constructor(storage, clientName, sessionId, redirectUrl, clientId_) {
209
+ this.storage = storage;
210
+ this.clientName = clientName;
211
+ this.sessionId = sessionId;
212
+ this.redirectUrl = redirectUrl;
213
+ this.clientId_ = clientId_;
214
+ }
215
+ get clientMetadata() {
216
+ return {
217
+ redirect_uris: [this.redirectUrl],
218
+ token_endpoint_auth_method: "none",
219
+ grant_types: ["authorization_code", "refresh_token"],
220
+ response_types: ["code"],
221
+ client_name: this.clientName,
222
+ client_uri: "example.com"
223
+ };
224
+ }
225
+ get clientId() {
226
+ if (!this.clientId_) {
227
+ throw new Error("no clientId");
228
+ }
229
+ return this.clientId_;
230
+ }
231
+ set clientId(clientId_) {
232
+ this.clientId_ = clientId_;
233
+ }
234
+ keyPrefix(clientId) {
235
+ return `/${this.clientName}/${this.sessionId}/${clientId}`;
236
+ }
237
+ clientInfoKey(clientId) {
238
+ return `${this.keyPrefix(clientId)}/client_info/`;
239
+ }
240
+ async clientInformation() {
241
+ if (!this.clientId_) {
242
+ return void 0;
243
+ }
244
+ return await this.storage.get(
245
+ this.clientInfoKey(this.clientId)
246
+ ) ?? void 0;
247
+ }
248
+ async saveClientInformation(clientInformation) {
249
+ await this.storage.put(
250
+ this.clientInfoKey(clientInformation.client_id),
251
+ clientInformation
252
+ );
253
+ this.clientId = clientInformation.client_id;
254
+ }
255
+ tokenKey(clientId) {
256
+ return `${this.keyPrefix(clientId)}/token`;
257
+ }
258
+ async tokens() {
259
+ if (!this.clientId_) {
260
+ return void 0;
261
+ }
262
+ return await this.storage.get(this.tokenKey(this.clientId)) ?? void 0;
263
+ }
264
+ async saveTokens(tokens) {
265
+ await this.storage.put(this.tokenKey(this.clientId), tokens);
266
+ }
267
+ get authUrl() {
268
+ return this.authUrl_;
269
+ }
270
+ /**
271
+ * Because this operates on the server side (but we need browser auth), we send this url back to the user
272
+ * and require user interact to initiate the redirect flow
273
+ */
274
+ async redirectToAuthorization(authUrl) {
275
+ const client_id = authUrl.searchParams.get("client_id");
276
+ if (client_id) {
277
+ authUrl.searchParams.append("state", client_id);
278
+ }
279
+ this.authUrl_ = authUrl.toString();
280
+ }
281
+ codeVerifierKey(clientId) {
282
+ return `${this.keyPrefix(clientId)}/code_verifier`;
283
+ }
284
+ async saveCodeVerifier(verifier) {
285
+ await this.storage.put(this.codeVerifierKey(this.clientId), verifier);
286
+ }
287
+ async codeVerifier() {
288
+ const codeVerifier = await this.storage.get(
289
+ this.codeVerifierKey(this.clientId)
290
+ );
291
+ if (!codeVerifier) {
292
+ throw new Error("No code verifier found");
293
+ }
294
+ return codeVerifier;
295
+ }
296
+ };
297
+
168
298
  // src/mcp/client.ts
169
299
  var MCPClientManager = class {
170
- constructor() {
300
+ /**
301
+ * @param name Name of the MCP client
302
+ * @param version Version of the MCP Client
303
+ * @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider
304
+ */
305
+ constructor(name, version, auth) {
306
+ this.name = name;
307
+ this.version = version;
308
+ this.auth = auth;
171
309
  this.mcpConnections = {};
172
310
  }
173
311
  /**
@@ -177,14 +315,82 @@ var MCPClientManager = class {
177
315
  * @param clientConfig Client config
178
316
  * @param capabilities Client capabilities (i.e. if the client supports roots/sampling)
179
317
  */
180
- async connectToServer(url, info, opts = { transport: {}, client: {}, capabilities: {} }) {
181
- if (info.name in this.mcpConnections) {
318
+ async connect(url, opts = {}) {
319
+ const id = opts.reconnect?.id ?? crypto.randomUUID();
320
+ if (this.auth) {
321
+ console.warn(
322
+ "Using .auth configuration to generate an oauth provider, this is temporary and will be removed in the next version. Instead use transport.authProvider to provide an auth provider"
323
+ );
324
+ }
325
+ const authProvider = this.auth ? new DurableObjectOAuthClientProvider(
326
+ this.auth.storage,
327
+ this.name,
328
+ id,
329
+ `${this.auth.baseCallbackUri}/${id}`,
330
+ opts.reconnect?.oauthClientId
331
+ ) : opts.transport?.authProvider;
332
+ this.mcpConnections[id] = new MCPClientConnection(
333
+ new URL(url),
334
+ {
335
+ name: this.name,
336
+ version: this.version
337
+ },
338
+ {
339
+ transport: {
340
+ ...opts.transport,
341
+ authProvider
342
+ },
343
+ client: opts.client ?? {},
344
+ capabilities: opts.client ?? {}
345
+ }
346
+ );
347
+ await this.mcpConnections[id].init(
348
+ opts.reconnect?.oauthCode,
349
+ opts.reconnect?.oauthClientId
350
+ );
351
+ return {
352
+ id,
353
+ authUrl: authProvider?.authUrl
354
+ };
355
+ }
356
+ isCallbackRequest(req) {
357
+ if (this.auth?.baseCallbackUri) {
358
+ return req.url.startsWith(this.auth.baseCallbackUri) && req.method === "GET";
359
+ }
360
+ return false;
361
+ }
362
+ async handleCallbackRequest(req) {
363
+ const url = new URL(req.url);
364
+ const code = url.searchParams.get("code");
365
+ const clientId = url.searchParams.get("state");
366
+ let serverId = req.url.replace(this.auth.baseCallbackUri, "").split("?")[0];
367
+ serverId = serverId.replaceAll("/", "");
368
+ if (!code) {
369
+ throw new Error("Unauthorized: no code provided");
370
+ }
371
+ if (!clientId) {
372
+ throw new Error("Unauthorized: no state provided");
373
+ }
374
+ if (this.mcpConnections[serverId] === void 0) {
375
+ throw new Error(`Could not find serverId: ${serverId}`);
376
+ }
377
+ if (this.mcpConnections[serverId].connectionState !== "authenticating") {
182
378
  throw new Error(
183
- `An existing MCP client has already been registered under the name "${info.name}". The MCP client name must be unique.`
379
+ "Failed to authenticate: the client isn't in the `authenticating` state"
184
380
  );
185
381
  }
186
- this.mcpConnections[info.name] = new MCPClientConnection(url, info, opts);
187
- await this.mcpConnections[info.name].init();
382
+ const serverUrl = this.mcpConnections[serverId].url.toString();
383
+ await this.connect(serverUrl, {
384
+ reconnect: {
385
+ id: serverId,
386
+ oauthClientId: clientId,
387
+ oauthCode: code
388
+ }
389
+ });
390
+ if (this.mcpConnections[serverId].connectionState === "authenticating") {
391
+ throw new Error("Failed to authenticate: client failed to initialize");
392
+ }
393
+ return { serverId };
188
394
  }
189
395
  /**
190
396
  * @returns namespaced list of tools
@@ -214,8 +420,8 @@ var MCPClientManager = class {
214
420
  * Namespaced version of callTool
215
421
  */
216
422
  callTool(params, resultSchema, options) {
217
- const unqualifiedName = params.name.replace(`${params.serverName}.`, "");
218
- return this.mcpConnections[params.serverName].client.callTool(
423
+ const unqualifiedName = params.name.replace(`${params.serverId}.`, "");
424
+ return this.mcpConnections[params.serverId].client.callTool(
219
425
  {
220
426
  ...params,
221
427
  name: unqualifiedName
@@ -228,7 +434,7 @@ var MCPClientManager = class {
228
434
  * Namespaced version of readResource
229
435
  */
230
436
  readResource(params, options) {
231
- return this.mcpConnections[params.serverName].client.readResource(
437
+ return this.mcpConnections[params.serverId].client.readResource(
232
438
  params,
233
439
  options
234
440
  );
@@ -237,7 +443,7 @@ var MCPClientManager = class {
237
443
  * Namespaced version of getPrompt
238
444
  */
239
445
  getPrompt(params, options) {
240
- return this.mcpConnections[params.serverName].client.getPrompt(
446
+ return this.mcpConnections[params.serverId].client.getPrompt(
241
447
  params,
242
448
  options
243
449
  );
@@ -247,15 +453,12 @@ function getNamespacedData(mcpClients, type) {
247
453
  const sets = Object.entries(mcpClients).map(([name, conn]) => {
248
454
  return { name, data: conn[type] };
249
455
  });
250
- const namespacedData = sets.flatMap(({ name: serverName, data }) => {
456
+ const namespacedData = sets.flatMap(({ name: serverId, data }) => {
251
457
  return data.map((item) => {
252
458
  return {
253
459
  ...item,
254
- // we add a servername so we can easily pull it out and convert between qualified<->unqualified name
255
- // just in case the server name or item name includes a "."
256
- serverName: `${serverName}`,
257
- // qualified name
258
- name: `${serverName}.${item.name}`
460
+ // we add a serverId so we can easily pull it out and send the tool call to the right server
461
+ serverId
259
462
  };
260
463
  });
261
464
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/mcp/sse-edge.ts","../../src/mcp/client-connection.ts","../../src/mcp/client.ts"],"sourcesContent":["import {\n SSEClientTransport,\n type SSEClientTransportOptions,\n} from \"@modelcontextprotocol/sdk/client/sse.js\";\n\nexport class SSEEdgeClientTransport extends SSEClientTransport {\n /**\n * Creates a new EdgeSSEClientTransport, which overrides fetch to be compatible with the CF workers environment\n */\n constructor(\n private url: URL,\n options: SSEClientTransportOptions\n ) {\n // biome-ignore lint/suspicious/noExplicitAny: Overriding fetch, type doesn't matter here\n const fetchOverride = (url: any, options = {}) => {\n const workerOptions = {\n ...options,\n };\n // Remove unsupported properties\n // @ts-ignore\n // biome-ignore lint/performance/noDelete: workaround for workers environment\n delete workerOptions.mode;\n\n // Call the original fetch with fixed options\n return global.fetch(url, workerOptions);\n };\n\n super(url, {\n ...options,\n eventSourceInit: {\n fetch: fetchOverride,\n },\n });\n }\n}\n","import { SSEEdgeClientTransport } from \"./sse-edge\";\n\nimport {\n ToolListChangedNotificationSchema,\n type ClientCapabilities,\n type Resource,\n type Tool,\n type Prompt,\n ResourceListChangedNotificationSchema,\n PromptListChangedNotificationSchema,\n type ListToolsResult,\n type ListResourcesResult,\n type ListPromptsResult,\n type ServerCapabilities,\n type ResourceTemplate,\n type ListResourceTemplatesResult,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type {\n SSEClientTransport,\n SSEClientTransportOptions,\n} from \"@modelcontextprotocol/sdk/client/sse.js\";\n\nexport class MCPClientConnection {\n client: Client;\n transport: SSEClientTransport;\n connected: boolean;\n instructions?: string;\n tools: Tool[];\n prompts: Prompt[];\n resources: Resource[];\n resourceTemplates: ResourceTemplate[];\n serverCapabilities: ServerCapabilities | undefined;\n\n constructor(\n url: URL,\n private info: ConstructorParameters<typeof Client>[0],\n opts: {\n transport: SSEClientTransportOptions;\n client: ConstructorParameters<typeof Client>[1];\n capabilities: ClientCapabilities;\n } = { transport: {}, client: {}, capabilities: {} }\n ) {\n this.transport = new SSEEdgeClientTransport(url, opts.transport);\n this.client = new Client(info, opts.client);\n this.client.registerCapabilities(opts.capabilities);\n this.connected = false;\n this.tools = [];\n this.prompts = [];\n this.resources = [];\n this.resourceTemplates = [];\n }\n\n async init() {\n await this.client.connect(this.transport);\n\n this.serverCapabilities = await this.client.getServerCapabilities();\n if (!this.serverCapabilities) {\n throw new Error(\n `The MCP Server ${this.info.name} failed to return server capabilities`\n );\n }\n\n const [instructions, tools, resources, prompts, resourceTemplates] =\n await Promise.all([\n this.client.getInstructions(),\n this.registerTools(),\n this.registerResources(),\n this.registerPrompts(),\n this.registerResourceTemplates(),\n ]);\n\n this.instructions = instructions;\n this.tools = tools;\n this.resources = resources;\n this.prompts = prompts;\n this.resourceTemplates = resourceTemplates;\n }\n\n /**\n * Notification handler registration\n */\n async registerTools(): Promise<Tool[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.tools) {\n return [];\n }\n\n if (this.serverCapabilities.tools.listChanged) {\n this.client.setNotificationHandler(\n ToolListChangedNotificationSchema,\n async (_notification) => {\n this.tools = await this.fetchTools();\n }\n );\n }\n\n return this.fetchTools();\n }\n\n async registerResources(): Promise<Resource[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.resources) {\n return [];\n }\n\n if (this.serverCapabilities.resources.listChanged) {\n this.client.setNotificationHandler(\n ResourceListChangedNotificationSchema,\n async (_notification) => {\n this.resources = await this.fetchResources();\n }\n );\n }\n\n return this.fetchResources();\n }\n\n async registerPrompts(): Promise<Prompt[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.prompts) {\n return [];\n }\n\n if (this.serverCapabilities.prompts.listChanged) {\n this.client.setNotificationHandler(\n PromptListChangedNotificationSchema,\n async (_notification) => {\n this.prompts = await this.fetchPrompts();\n }\n );\n }\n\n return this.fetchPrompts();\n }\n\n async registerResourceTemplates(): Promise<ResourceTemplate[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.resources) {\n return [];\n }\n\n return this.fetchResourceTemplates();\n }\n\n async fetchTools() {\n let toolsAgg: Tool[] = [];\n let toolsResult: ListToolsResult = { tools: [] };\n do {\n toolsResult = await this.client.listTools({\n cursor: toolsResult.nextCursor,\n });\n toolsAgg = toolsAgg.concat(toolsResult.tools);\n } while (toolsResult.nextCursor);\n return toolsAgg;\n }\n\n async fetchResources() {\n let resourcesAgg: Resource[] = [];\n let resourcesResult: ListResourcesResult = { resources: [] };\n do {\n resourcesResult = await this.client.listResources({\n cursor: resourcesResult.nextCursor,\n });\n resourcesAgg = resourcesAgg.concat(resourcesResult.resources);\n } while (resourcesResult.nextCursor);\n return resourcesAgg;\n }\n\n async fetchPrompts() {\n let promptsAgg: Prompt[] = [];\n let promptsResult: ListPromptsResult = { prompts: [] };\n do {\n promptsResult = await this.client.listPrompts({\n cursor: promptsResult.nextCursor,\n });\n promptsAgg = promptsAgg.concat(promptsResult.prompts);\n } while (promptsResult.nextCursor);\n return promptsAgg;\n }\n\n async fetchResourceTemplates() {\n let templatesAgg: ResourceTemplate[] = [];\n let templatesResult: ListResourceTemplatesResult = {\n resourceTemplates: [],\n };\n do {\n templatesResult = await this.client.listResourceTemplates({\n cursor: templatesResult.nextCursor,\n });\n templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);\n } while (templatesResult.nextCursor);\n return templatesAgg;\n }\n}\n","import { MCPClientConnection } from \"./client-connection\";\n\nimport type {\n ClientCapabilities,\n CallToolRequest,\n CallToolResultSchema,\n CompatibilityCallToolResultSchema,\n ReadResourceRequest,\n GetPromptRequest,\n Tool,\n Resource,\n ResourceTemplate,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { RequestOptions } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\n\n/**\n * Utility class that aggregates multiple MCP clients into one\n */\nexport class MCPClientManager {\n public mcpConnections: Record<string, MCPClientConnection> = {};\n\n /**\n * Connect to and register an MCP server\n *\n * @param transportConfig Transport config\n * @param clientConfig Client config\n * @param capabilities Client capabilities (i.e. if the client supports roots/sampling)\n */\n async connectToServer(\n url: URL,\n info: ConstructorParameters<typeof Client>[0],\n opts: {\n transport: SSEClientTransportOptions;\n client: ConstructorParameters<typeof Client>[1];\n capabilities: ClientCapabilities;\n } = { transport: {}, client: {}, capabilities: {} }\n ) {\n if (info.name in this.mcpConnections) {\n throw new Error(\n `An existing MCP client has already been registered under the name \"${info.name}\". The MCP client name must be unique.`\n );\n }\n\n this.mcpConnections[info.name] = new MCPClientConnection(url, info, opts);\n await this.mcpConnections[info.name].init();\n }\n\n /**\n * @returns namespaced list of tools\n */\n listTools(): NamespacedData[\"tools\"] {\n return getNamespacedData(this.mcpConnections, \"tools\");\n }\n\n /**\n * @returns namespaced list of prompts\n */\n listPrompts(): NamespacedData[\"prompts\"] {\n return getNamespacedData(this.mcpConnections, \"prompts\");\n }\n\n /**\n * @returns namespaced list of tools\n */\n listResources(): NamespacedData[\"resources\"] {\n return getNamespacedData(this.mcpConnections, \"resources\");\n }\n\n /**\n * @returns namespaced list of resource templates\n */\n listResourceTemplates(): NamespacedData[\"resourceTemplates\"] {\n return getNamespacedData(this.mcpConnections, \"resourceTemplates\");\n }\n\n /**\n * Namespaced version of callTool\n */\n callTool(\n params: CallToolRequest[\"params\"] & { serverName: string },\n resultSchema:\n | typeof CallToolResultSchema\n | typeof CompatibilityCallToolResultSchema,\n options: RequestOptions\n ) {\n const unqualifiedName = params.name.replace(`${params.serverName}.`, \"\");\n return this.mcpConnections[params.serverName].client.callTool(\n {\n ...params,\n name: unqualifiedName,\n },\n resultSchema,\n options\n );\n }\n\n /**\n * Namespaced version of readResource\n */\n readResource(\n params: ReadResourceRequest[\"params\"] & { serverName: string },\n options: RequestOptions\n ) {\n return this.mcpConnections[params.serverName].client.readResource(\n params,\n options\n );\n }\n\n /**\n * Namespaced version of getPrompt\n */\n getPrompt(\n params: GetPromptRequest[\"params\"] & { serverName: string },\n options: RequestOptions\n ) {\n return this.mcpConnections[params.serverName].client.getPrompt(\n params,\n options\n );\n }\n}\n\ntype NamespacedData = {\n tools: (Tool & { serverName: string })[];\n prompts: (Prompt & { serverName: string })[];\n resources: (Resource & { serverName: string })[];\n resourceTemplates: (ResourceTemplate & { serverName: string })[];\n};\n\nexport function getNamespacedData<T extends keyof NamespacedData>(\n mcpClients: Record<string, MCPClientConnection>,\n type: T\n): NamespacedData[T] {\n const sets = Object.entries(mcpClients).map(([name, conn]) => {\n return { name, data: conn[type] };\n });\n\n const namespacedData = sets.flatMap(({ name: serverName, data }) => {\n return data.map((item) => {\n return {\n ...item,\n // we add a servername so we can easily pull it out and convert between qualified<->unqualified name\n // just in case the server name or item name includes a \".\"\n serverName: `${serverName}`,\n // qualified name\n name: `${serverName}.${item.name}`,\n };\n });\n });\n\n return namespacedData as NamespacedData[T]; // Type assertion needed due to TS limitations with conditional return types\n}\n"],"mappings":";;;AAAA;AAAA,EACE;AAAA,OAEK;AAEA,IAAM,yBAAN,cAAqC,mBAAmB;AAAA;AAAA;AAAA;AAAA,EAI7D,YACU,KACR,SACA;AAEA,UAAM,gBAAgB,CAACA,MAAUC,WAAU,CAAC,MAAM;AAChD,YAAM,gBAAgB;AAAA,QACpB,GAAGA;AAAA,MACL;AAIA,aAAO,cAAc;AAGrB,aAAO,OAAO,MAAMD,MAAK,aAAa;AAAA,IACxC;AAEA,UAAM,KAAK;AAAA,MACT,GAAG;AAAA,MACH,iBAAiB;AAAA,QACf,OAAO;AAAA,MACT;AAAA,IACF,CAAC;AAtBO;AAAA,EAuBV;AACF;;;AChCA;AAAA,EACE;AAAA,EAKA;AAAA,EACA;AAAA,OAOK;AACP,SAAS,cAAc;AAMhB,IAAM,sBAAN,MAA0B;AAAA,EAW/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AM,GAAG,UAAU,IAAI,KAAK,IAAI;AAAA,MAClC;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AAED,SAAO;AACT;","names":["url","options"]}
1
+ {"version":3,"sources":["../../src/mcp/sse-edge.ts","../../src/mcp/client-connection.ts","../../src/mcp/do-oauth-client-provider.ts","../../src/mcp/client.ts"],"sourcesContent":["import {\n SSEClientTransport,\n type SSEClientTransportOptions,\n} from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\n\nexport class SSEEdgeClientTransport extends SSEClientTransport {\n private authProvider: OAuthClientProvider | undefined;\n /**\n * Creates a new EdgeSSEClientTransport, which overrides fetch to be compatible with the CF workers environment\n */\n constructor(url: URL, options: SSEClientTransportOptions) {\n const fetchOverride: typeof fetch = async (\n fetchUrl: RequestInfo | URL,\n fetchInit: RequestInit = {}\n ) => {\n // add auth headers\n const headers = await this.authHeaders();\n const workerOptions = {\n ...fetchInit,\n headers: {\n ...fetchInit?.headers,\n ...headers,\n },\n };\n\n // Remove unsupported properties\n // biome-ignore lint/performance/noDelete: workaround for workers environment\n delete workerOptions.mode;\n\n // Call the original fetch with fixed options\n return fetch(fetchUrl, workerOptions);\n };\n\n super(url, {\n ...options,\n eventSourceInit: {\n fetch: fetchOverride,\n },\n });\n this.authProvider = options.authProvider;\n }\n\n async authHeaders() {\n if (this.authProvider) {\n const tokens = await this.authProvider.tokens();\n if (tokens) {\n return {\n Authorization: `Bearer ${tokens.access_token}`,\n };\n }\n }\n }\n}\n","import { SSEEdgeClientTransport } from \"./sse-edge\";\n\nimport {\n ToolListChangedNotificationSchema,\n type ClientCapabilities,\n type Resource,\n type Tool,\n type Prompt,\n ResourceListChangedNotificationSchema,\n PromptListChangedNotificationSchema,\n type ListToolsResult,\n type ListResourcesResult,\n type ListPromptsResult,\n type ServerCapabilities,\n type ResourceTemplate,\n type ListResourceTemplatesResult,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\n\nexport class MCPClientConnection {\n client: Client;\n connectionState:\n | \"authenticating\"\n | \"connecting\"\n | \"ready\"\n | \"discovering\"\n | \"failed\" = \"connecting\";\n instructions?: string;\n tools: Tool[] = [];\n prompts: Prompt[] = [];\n resources: Resource[] = [];\n resourceTemplates: ResourceTemplate[] = [];\n serverCapabilities: ServerCapabilities | undefined;\n\n constructor(\n public url: URL,\n private info: ConstructorParameters<typeof Client>[0],\n private options: {\n transport: SSEClientTransportOptions;\n client: ConstructorParameters<typeof Client>[1];\n capabilities: ClientCapabilities;\n } = { transport: {}, client: {}, capabilities: {} }\n ) {\n this.client = new Client(info, options.client);\n this.client.registerCapabilities(options.capabilities);\n }\n\n /**\n * Initialize a client connection\n *\n * @param code Optional OAuth code to initialize the connection with if auth hasn't been initialized\n * @returns\n */\n async init(code?: string, clientId?: string) {\n try {\n const transport = new SSEEdgeClientTransport(\n this.url,\n this.options.transport\n );\n if (code) {\n await transport.finishAuth(code);\n }\n await this.client.connect(transport);\n // biome-ignore lint/suspicious/noExplicitAny: allow for the error check here\n } catch (e: any) {\n if (e.toString().includes(\"Unauthorized\")) {\n // unauthorized, we should wait for the user to authenticate\n this.connectionState = \"authenticating\";\n return;\n }\n this.connectionState = \"failed\";\n throw e;\n }\n\n this.connectionState = \"discovering\";\n\n this.serverCapabilities = await this.client.getServerCapabilities();\n if (!this.serverCapabilities) {\n throw new Error(\"The MCP Server failed to return server capabilities\");\n }\n\n const [instructions, tools, resources, prompts, resourceTemplates] =\n await Promise.all([\n this.client.getInstructions(),\n this.registerTools(),\n this.registerResources(),\n this.registerPrompts(),\n this.registerResourceTemplates(),\n ]);\n\n this.instructions = instructions;\n this.tools = tools;\n this.resources = resources;\n this.prompts = prompts;\n this.resourceTemplates = resourceTemplates;\n\n this.connectionState = \"ready\";\n }\n\n /**\n * Notification handler registration\n */\n async registerTools(): Promise<Tool[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.tools) {\n return [];\n }\n\n if (this.serverCapabilities.tools.listChanged) {\n this.client.setNotificationHandler(\n ToolListChangedNotificationSchema,\n async (_notification) => {\n this.tools = await this.fetchTools();\n }\n );\n }\n\n return this.fetchTools();\n }\n\n async registerResources(): Promise<Resource[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.resources) {\n return [];\n }\n\n if (this.serverCapabilities.resources.listChanged) {\n this.client.setNotificationHandler(\n ResourceListChangedNotificationSchema,\n async (_notification) => {\n this.resources = await this.fetchResources();\n }\n );\n }\n\n return this.fetchResources();\n }\n\n async registerPrompts(): Promise<Prompt[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.prompts) {\n return [];\n }\n\n if (this.serverCapabilities.prompts.listChanged) {\n this.client.setNotificationHandler(\n PromptListChangedNotificationSchema,\n async (_notification) => {\n this.prompts = await this.fetchPrompts();\n }\n );\n }\n\n return this.fetchPrompts();\n }\n\n async registerResourceTemplates(): Promise<ResourceTemplate[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.resources) {\n return [];\n }\n\n return this.fetchResourceTemplates();\n }\n\n async fetchTools() {\n let toolsAgg: Tool[] = [];\n let toolsResult: ListToolsResult = { tools: [] };\n do {\n toolsResult = await this.client.listTools({\n cursor: toolsResult.nextCursor,\n });\n toolsAgg = toolsAgg.concat(toolsResult.tools);\n } while (toolsResult.nextCursor);\n return toolsAgg;\n }\n\n async fetchResources() {\n let resourcesAgg: Resource[] = [];\n let resourcesResult: ListResourcesResult = { resources: [] };\n do {\n resourcesResult = await this.client.listResources({\n cursor: resourcesResult.nextCursor,\n });\n resourcesAgg = resourcesAgg.concat(resourcesResult.resources);\n } while (resourcesResult.nextCursor);\n return resourcesAgg;\n }\n\n async fetchPrompts() {\n let promptsAgg: Prompt[] = [];\n let promptsResult: ListPromptsResult = { prompts: [] };\n do {\n promptsResult = await this.client.listPrompts({\n cursor: promptsResult.nextCursor,\n });\n promptsAgg = promptsAgg.concat(promptsResult.prompts);\n } while (promptsResult.nextCursor);\n return promptsAgg;\n }\n\n async fetchResourceTemplates() {\n let templatesAgg: ResourceTemplate[] = [];\n let templatesResult: ListResourceTemplatesResult = {\n resourceTemplates: [],\n };\n do {\n templatesResult = await this.client.listResourceTemplates({\n cursor: templatesResult.nextCursor,\n });\n templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);\n } while (templatesResult.nextCursor);\n return templatesAgg;\n }\n}\n","import type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport type {\n OAuthTokens,\n OAuthClientMetadata,\n OAuthClientInformation,\n OAuthClientInformationFull,\n} from \"@modelcontextprotocol/sdk/shared/auth.js\";\n\n// A slight extension to the standard OAuthClientProvider interface because `redirectToAuthorization` doesn't give us the interface we need\nexport interface AgentsOAuthProvider extends OAuthClientProvider {\n authUrl: string | undefined;\n clientId: string | undefined;\n}\n\nexport class DurableObjectOAuthClientProvider implements AgentsOAuthProvider {\n private authUrl_: string | undefined;\n\n constructor(\n public storage: DurableObjectStorage,\n public clientName: string,\n public sessionId: string,\n public redirectUrl: string,\n private clientId_?: string\n ) {}\n\n get clientMetadata(): OAuthClientMetadata {\n return {\n redirect_uris: [this.redirectUrl],\n token_endpoint_auth_method: \"none\",\n grant_types: [\"authorization_code\", \"refresh_token\"],\n response_types: [\"code\"],\n client_name: this.clientName,\n client_uri: \"example.com\",\n };\n }\n\n get clientId() {\n if (!this.clientId_) {\n throw new Error(\"no clientId\");\n }\n return this.clientId_;\n }\n\n set clientId(clientId_: string) {\n this.clientId_ = clientId_;\n }\n\n keyPrefix(clientId: string) {\n return `/${this.clientName}/${this.sessionId}/${clientId}`;\n }\n\n clientInfoKey(clientId: string) {\n return `${this.keyPrefix(clientId)}/client_info/`;\n }\n\n async clientInformation(): Promise<OAuthClientInformation | undefined> {\n if (!this.clientId_) {\n return undefined;\n }\n return (\n (await this.storage.get<OAuthClientInformation>(\n this.clientInfoKey(this.clientId)\n )) ?? undefined\n );\n }\n\n async saveClientInformation(\n clientInformation: OAuthClientInformationFull\n ): Promise<void> {\n await this.storage.put(\n this.clientInfoKey(clientInformation.client_id),\n clientInformation\n );\n this.clientId = clientInformation.client_id;\n }\n\n tokenKey(clientId: string) {\n return `${this.keyPrefix(clientId)}/token`;\n }\n\n async tokens(): Promise<OAuthTokens | undefined> {\n if (!this.clientId_) {\n return undefined;\n }\n return (\n (await this.storage.get<OAuthTokens>(this.tokenKey(this.clientId))) ??\n undefined\n );\n }\n\n async saveTokens(tokens: OAuthTokens): Promise<void> {\n await this.storage.put(this.tokenKey(this.clientId), tokens);\n }\n\n get authUrl() {\n return this.authUrl_;\n }\n\n /**\n * Because this operates on the server side (but we need browser auth), we send this url back to the user\n * and require user interact to initiate the redirect flow\n */\n async redirectToAuthorization(authUrl: URL): Promise<void> {\n // We want to track the client ID in state here because the typescript SSE client sometimes does\n // a dynamic client registration AFTER generating this redirect URL.\n const client_id = authUrl.searchParams.get(\"client_id\");\n if (client_id) {\n authUrl.searchParams.append(\"state\", client_id);\n }\n this.authUrl_ = authUrl.toString();\n }\n\n codeVerifierKey(clientId: string) {\n return `${this.keyPrefix(clientId)}/code_verifier`;\n }\n\n async saveCodeVerifier(verifier: string): Promise<void> {\n await this.storage.put(this.codeVerifierKey(this.clientId), verifier);\n }\n\n async codeVerifier(): Promise<string> {\n const codeVerifier = await this.storage.get<string>(\n this.codeVerifierKey(this.clientId)\n );\n if (!codeVerifier) {\n throw new Error(\"No code verifier found\");\n }\n return codeVerifier;\n }\n}\n","import { MCPClientConnection } from \"./client-connection\";\n\nimport type {\n ClientCapabilities,\n CallToolRequest,\n CallToolResultSchema,\n CompatibilityCallToolResultSchema,\n ReadResourceRequest,\n GetPromptRequest,\n Tool,\n Resource,\n Prompt,\n ResourceTemplate,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { RequestOptions } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport {\n DurableObjectOAuthClientProvider,\n type AgentsOAuthProvider,\n} from \"./do-oauth-client-provider\";\n\n/**\n * Utility class that aggregates multiple MCP clients into one\n */\nexport class MCPClientManager {\n public mcpConnections: Record<string, MCPClientConnection> = {};\n\n /**\n * @param name Name of the MCP client\n * @param version Version of the MCP Client\n * @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider\n */\n constructor(\n private name: string,\n private version: string,\n private auth?: { baseCallbackUri: string; storage: DurableObjectStorage }\n ) {}\n\n /**\n * Connect to and register an MCP server\n *\n * @param transportConfig Transport config\n * @param clientConfig Client config\n * @param capabilities Client capabilities (i.e. if the client supports roots/sampling)\n */\n async connect(\n url: string,\n opts: {\n // Allows you to reconnect to a server (in the case of a auth reconnect)\n // Doesn't handle session reconnection\n reconnect?: {\n id: string;\n oauthClientId?: string;\n oauthCode?: string;\n };\n // we're overriding authProvider here because we want to be able to access the auth URL\n transport?: SSEClientTransportOptions & {\n authProvider: AgentsOAuthProvider;\n };\n client?: ConstructorParameters<typeof Client>[1];\n capabilities?: ClientCapabilities;\n } = {}\n ): Promise<{ id: string; authUrl: string | undefined }> {\n const id = opts.reconnect?.id ?? crypto.randomUUID();\n\n // if we have global auth for the manager AND there's no authProvider override\n // then let's setup an auth provider\n\n if (this.auth) {\n console.warn(\n \"Using .auth configuration to generate an oauth provider, this is temporary and will be removed in the next version. Instead use transport.authProvider to provide an auth provider\"\n );\n }\n\n const authProvider: AgentsOAuthProvider | undefined = this.auth\n ? new DurableObjectOAuthClientProvider(\n this.auth.storage,\n this.name,\n id,\n `${this.auth.baseCallbackUri}/${id}`,\n opts.reconnect?.oauthClientId\n )\n : opts.transport?.authProvider;\n\n this.mcpConnections[id] = new MCPClientConnection(\n new URL(url),\n {\n name: this.name,\n version: this.version,\n },\n {\n transport: {\n ...opts.transport,\n authProvider,\n },\n client: opts.client ?? {},\n capabilities: opts.client ?? {},\n }\n );\n\n await this.mcpConnections[id].init(\n opts.reconnect?.oauthCode,\n opts.reconnect?.oauthClientId\n );\n\n return {\n id,\n authUrl: authProvider?.authUrl,\n };\n }\n\n isCallbackRequest(req: Request): boolean {\n if (this.auth?.baseCallbackUri) {\n return (\n req.url.startsWith(this.auth.baseCallbackUri) && req.method === \"GET\"\n );\n }\n return false;\n }\n\n async handleCallbackRequest(req: Request) {\n const url = new URL(req.url);\n const code = url.searchParams.get(\"code\");\n const clientId = url.searchParams.get(\"state\");\n let serverId = req.url\n .replace(this.auth!.baseCallbackUri, \"\")\n .split(\"?\")[0];\n serverId = serverId.replaceAll(\"/\", \"\");\n if (!code) {\n throw new Error(\"Unauthorized: no code provided\");\n }\n if (!clientId) {\n throw new Error(\"Unauthorized: no state provided\");\n }\n\n if (this.mcpConnections[serverId] === undefined) {\n throw new Error(`Could not find serverId: ${serverId}`);\n }\n\n if (this.mcpConnections[serverId].connectionState !== \"authenticating\") {\n throw new Error(\n \"Failed to authenticate: the client isn't in the `authenticating` state\"\n );\n }\n\n // reconnect to server with authorization\n const serverUrl = this.mcpConnections[serverId].url.toString();\n await this.connect(serverUrl, {\n reconnect: {\n id: serverId,\n oauthClientId: clientId,\n oauthCode: code,\n },\n });\n\n if (this.mcpConnections[serverId].connectionState === \"authenticating\") {\n throw new Error(\"Failed to authenticate: client failed to initialize\");\n }\n\n return { serverId };\n }\n\n /**\n * @returns namespaced list of tools\n */\n listTools(): NamespacedData[\"tools\"] {\n return getNamespacedData(this.mcpConnections, \"tools\");\n }\n\n /**\n * @returns namespaced list of prompts\n */\n listPrompts(): NamespacedData[\"prompts\"] {\n return getNamespacedData(this.mcpConnections, \"prompts\");\n }\n\n /**\n * @returns namespaced list of tools\n */\n listResources(): NamespacedData[\"resources\"] {\n return getNamespacedData(this.mcpConnections, \"resources\");\n }\n\n /**\n * @returns namespaced list of resource templates\n */\n listResourceTemplates(): NamespacedData[\"resourceTemplates\"] {\n return getNamespacedData(this.mcpConnections, \"resourceTemplates\");\n }\n\n /**\n * Namespaced version of callTool\n */\n callTool(\n params: CallToolRequest[\"params\"] & { serverId: string },\n resultSchema:\n | typeof CallToolResultSchema\n | typeof CompatibilityCallToolResultSchema,\n options: RequestOptions\n ) {\n const unqualifiedName = params.name.replace(`${params.serverId}.`, \"\");\n return this.mcpConnections[params.serverId].client.callTool(\n {\n ...params,\n name: unqualifiedName,\n },\n resultSchema,\n options\n );\n }\n\n /**\n * Namespaced version of readResource\n */\n readResource(\n params: ReadResourceRequest[\"params\"] & { serverId: string },\n options: RequestOptions\n ) {\n return this.mcpConnections[params.serverId].client.readResource(\n params,\n options\n );\n }\n\n /**\n * Namespaced version of getPrompt\n */\n getPrompt(\n params: GetPromptRequest[\"params\"] & { serverId: string },\n options: RequestOptions\n ) {\n return this.mcpConnections[params.serverId].client.getPrompt(\n params,\n options\n );\n }\n}\n\ntype NamespacedData = {\n tools: (Tool & { serverId: string })[];\n prompts: (Prompt & { serverId: string })[];\n resources: (Resource & { serverId: string })[];\n resourceTemplates: (ResourceTemplate & { serverId: string })[];\n};\n\nexport function getNamespacedData<T extends keyof NamespacedData>(\n mcpClients: Record<string, MCPClientConnection>,\n type: T\n): NamespacedData[T] {\n const sets = Object.entries(mcpClients).map(([name, conn]) => {\n return { name, data: conn[type] };\n });\n\n const namespacedData = sets.flatMap(({ name: serverId, data }) => {\n return data.map((item) => {\n return {\n ...item,\n // we add a serverId so we can easily pull it out and send the tool call to the right server\n serverId,\n };\n });\n });\n\n return namespacedData as NamespacedData[T]; // Type assertion needed due to TS limitations with conditional return types\n}\n"],"mappings":";;;AAAA;AAAA,EACE;AAAA,OAEK;AAGA,IAAM,yBAAN,cAAqC,mBAAmB;AAAA;AAAA;AAAA;AAAA,EAK7D,YAAY,KAAU,SAAoC;AACxD,UAAM,gBAA8B,OAClC,UACA,YAAyB,CAAC,MACvB;AAEH,YAAM,UAAU,MAAM,KAAK,YAAY;AACvC,YAAM,gBAAgB;AAAA,QACpB,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AAA,EACnE;AAAA;AAAA;AAAA;AAAA,EAKA,SACE,QACA,cAGA,SACA;AACA,UAAM,kBAAkB,OAAO,KAAK,QAAQ,GAAG,OAAO,QAAQ,KAAK,EAAE;AACrE,WAAO,KAAK,eAAe,OAAO,QAAQ,EAAE,OAAO;AAAA,MACjD;AAAA,QACE,GAAG;AAAA,QACH,MAAM;AAAA,MACR;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,aACE,QACA,SACA;AACA,WAAO,KAAK,eAAe,OAAO,QAAQ,EAAE,OAAO;AAAA,MACjD;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,UACE,QACA,SACA;AACA,WAAO,KAAK,eAAe,OAAO,QAAQ,EAAE,OAAO;AAAA,MACjD;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AASO,SAAS,kBACd,YACA,MACmB;AACnB,QAAM,OAAO,OAAO,QAAQ,UAAU,EAAE,IAAI,CAAC,CAAC,MAAM,IAAI,MAAM;AAC5D,WAAO,EAAE,MAAM,MAAM,KAAK,IAAI,EAAE;AAAA,EAClC,CAAC;AAED,QAAM,iBAAiB,KAAK,QAAQ,CAAC,EAAE,MAAM,UAAU,KAAK,MAAM;AAChE,WAAO,KAAK,IAAI,CAAC,SAAS;AACxB,aAAO;AAAA,QACL,GAAG;AAAA;AAAA,QAEH;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AAED,SAAO;AACT;","names":[]}
package/dist/mcp/index.js CHANGED
@@ -214,8 +214,12 @@ var McpAgent = class extends DurableObject {
214
214
  binding = "MCP_OBJECT",
215
215
  corsOptions
216
216
  } = {}) {
217
- const basePattern = new URLPattern({ pathname: path });
218
- const messagePattern = new URLPattern({ pathname: `${path}/message` });
217
+ let pathname = path;
218
+ if (path === "/") {
219
+ pathname = "/*";
220
+ }
221
+ const basePattern = new URLPattern({ pathname });
222
+ const messagePattern = new URLPattern({ pathname: `${pathname}/message` });
219
223
  return {
220
224
  fetch: async (request, env, ctx) => {
221
225
  const corsResponse = handleCORS(request, corsOptions);
@@ -228,7 +232,7 @@ var McpAgent = class extends DurableObject {
228
232
  const writer = writable.getWriter();
229
233
  const encoder = new TextEncoder();
230
234
  const endpointMessage = `event: endpoint
231
- data: ${encodeURI(`${path}/message`)}?sessionId=${sessionId}
235
+ data: ${encodeURI(`${pathname}/message`)}?sessionId=${sessionId}
232
236
 
233
237
  `;
234
238
  writer.write(encoder.encode(endpointMessage));
@@ -300,7 +304,7 @@ data: ${event.data}
300
304
  const sessionId = url.searchParams.get("sessionId");
301
305
  if (!sessionId) {
302
306
  return new Response(
303
- `Missing sessionId. Expected POST to ${path} to initiate new one`,
307
+ `Missing sessionId. Expected POST to ${pathname} to initiate new one`,
304
308
  { status: 400 }
305
309
  );
306
310
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/mcp/index.ts"],"sourcesContent":["import { DurableObject } from \"cloudflare:workers\";\nimport { Agent } from \"../\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { Connection } from \"../\";\nimport type { JSONRPCMessage } from \"@modelcontextprotocol/sdk/types.js\";\nimport { JSONRPCMessageSchema } from \"@modelcontextprotocol/sdk/types.js\";\nimport type { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\n\nconst MAXIMUM_MESSAGE_SIZE = 4 * 1024 * 1024; // 4MB\n\n// CORS helper function\nfunction handleCORS(\n request: Request,\n corsOptions?: CORSOptions\n): Response | null {\n const origin = request.headers.get(\"Origin\") || \"*\";\n const corsHeaders = {\n \"Access-Control-Allow-Origin\": corsOptions?.origin || origin,\n \"Access-Control-Allow-Methods\":\n corsOptions?.methods || \"GET, POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": corsOptions?.headers || \"Content-Type\",\n \"Access-Control-Max-Age\": (corsOptions?.maxAge || 86400).toString(),\n };\n\n if (request.method === \"OPTIONS\") {\n return new Response(null, { headers: corsHeaders });\n }\n\n return null;\n}\n\ninterface CORSOptions {\n origin?: string;\n methods?: string;\n headers?: string;\n maxAge?: number;\n}\n\nclass McpTransport implements Transport {\n onclose?: () => void;\n onerror?: (error: Error) => void;\n onmessage?: (message: JSONRPCMessage) => void;\n sessionId?: string;\n\n #getWebSocket: () => WebSocket | null;\n #started = false;\n constructor(getWebSocket: () => WebSocket | null) {\n this.#getWebSocket = getWebSocket;\n }\n\n async start() {\n // The transport does not manage the WebSocket connection since it's terminated\n // by the Durable Object in order to allow hibernation. There's nothing to initialize.\n if (this.#started) {\n throw new Error(\"Transport already started\");\n }\n this.#started = true;\n }\n\n async send(message: JSONRPCMessage) {\n if (!this.#started) {\n throw new Error(\"Transport not started\");\n }\n const websocket = this.#getWebSocket();\n if (!websocket) {\n throw new Error(\"WebSocket not connected\");\n }\n try {\n websocket.send(JSON.stringify(message));\n } catch (error) {\n this.onerror?.(error as Error);\n throw error;\n }\n }\n\n async close() {\n // Similar to start, the only thing to do is to pass the event on to the server\n this.onclose?.();\n }\n}\n\nexport abstract class McpAgent<\n Env = unknown,\n State = unknown,\n Props extends Record<string, unknown> = Record<string, unknown>,\n> extends DurableObject<Env> {\n #status: \"zero\" | \"starting\" | \"started\" = \"zero\";\n #transport?: McpTransport;\n #connected = false;\n\n /**\n * Since McpAgent's _aren't_ yet real \"Agents\" (they route differently, don't support\n * websockets, don't support hibernation), let's only expose a couple of the methods\n * to the outer class: initialState/state/setState/onStateUpdate/sql\n */\n readonly #agent: Agent<Env, State>;\n\n protected constructor(ctx: DurableObjectState, env: Env) {\n super(ctx, env);\n const self = this;\n\n // Since McpAgent's _aren't_ yet real \"Agents\" (they route differently, they don't support\n // scheduling etc, let's only expose a couple of the methods\n // to the outer class for now.\n this.#agent = new (class extends Agent<Env, State> {\n static options = {\n hibernate: true,\n };\n\n onStateUpdate(state: State | undefined, source: Connection | \"server\") {\n return self.onStateUpdate(state, source);\n }\n })(ctx, env);\n }\n\n /**\n * Agents API allowlist\n */\n initialState!: State;\n get state() {\n if (this.initialState) this.#agent.initialState = this.initialState;\n return this.#agent.state;\n }\n sql<T = Record<string, string | number | boolean | null>>(\n strings: TemplateStringsArray,\n ...values: (string | number | boolean | null)[]\n ) {\n return this.#agent.sql<T>(strings, ...values);\n }\n\n setState(state: State) {\n return this.#agent.setState(state);\n }\n onStateUpdate(state: State | undefined, source: Connection | \"server\") {\n // override this to handle state updates\n }\n async onStart() {\n this.props = (await this.ctx.storage.get(\"props\")) as Props;\n this.init?.();\n\n // Connect to the MCP server\n this.#transport = new McpTransport(() => this.getWebSocket());\n await this.server.connect(this.#transport);\n }\n\n /**\n * McpAgent API\n */\n abstract server: McpServer;\n props!: Props;\n initRun = false;\n\n abstract init(): Promise<void>;\n\n async _init(props: Props) {\n await this.ctx.storage.put(\"props\", props);\n this.props = props;\n if (!this.initRun) {\n this.initRun = true;\n await this.init();\n }\n }\n\n async #initialize(): Promise<void> {\n await this.ctx.blockConcurrencyWhile(async () => {\n this.#status = \"starting\";\n await this.onStart();\n this.#status = \"started\";\n });\n }\n\n // Allow the worker to fetch a websocket connection to the agent\n async fetch(request: Request): Promise<Response> {\n if (this.#status !== \"started\") {\n // This means the server \"woke up\" after hibernation\n // so we need to hydrate it again\n await this.#initialize();\n }\n\n // Only handle WebSocket upgrade requests\n if (request.headers.get(\"Upgrade\") !== \"websocket\") {\n return new Response(\"Expected WebSocket Upgrade request\", {\n status: 400,\n });\n }\n\n const url = new URL(request.url);\n const sessionId = url.searchParams.get(\"sessionId\");\n if (!sessionId) {\n return new Response(\"Missing sessionId\", { status: 400 });\n }\n\n // Create a WebSocket pair\n const webSocketPair = new WebSocketPair();\n const [client, server] = Object.values(webSocketPair);\n\n // For now, each agent can only have one connection\n // If we get an upgrade while already connected, we should error\n if (this.#connected) {\n return new Response(\"WebSocket already connected\", { status: 400 });\n }\n this.ctx.acceptWebSocket(server);\n this.#connected = true;\n\n // Connect to the MCP server\n this.#transport = new McpTransport(() => this.getWebSocket());\n await this.server.connect(this.#transport);\n\n return new Response(null, {\n status: 101,\n webSocket: client,\n });\n }\n\n getWebSocket() {\n const websockets = this.ctx.getWebSockets();\n if (websockets.length === 0) {\n return null;\n }\n return websockets[0];\n }\n\n async onMCPMessage(sessionId: string, request: Request): Promise<Response> {\n if (this.#status !== \"started\") {\n // This means the server \"woke up\" after hibernation\n // so we need to hydrate it again\n await this.#initialize();\n }\n try {\n const contentType = request.headers.get(\"content-type\") || \"\";\n if (!contentType.includes(\"application/json\")) {\n return new Response(`Unsupported content-type: ${contentType}`, {\n status: 400,\n });\n }\n\n // check if the request body is too large\n const contentLength = Number.parseInt(\n request.headers.get(\"content-length\") || \"0\",\n 10\n );\n if (contentLength > MAXIMUM_MESSAGE_SIZE) {\n return new Response(`Request body too large: ${contentLength} bytes`, {\n status: 400,\n });\n }\n\n // Clone the request before reading the body to avoid stream issues\n const message = await request.json();\n let parsedMessage: JSONRPCMessage;\n try {\n parsedMessage = JSONRPCMessageSchema.parse(message);\n } catch (error) {\n this.#transport?.onerror?.(error as Error);\n throw error;\n }\n\n this.#transport?.onmessage?.(parsedMessage);\n return new Response(\"Accepted\", { status: 202 });\n } catch (error) {\n this.#transport?.onerror?.(error as Error);\n return new Response(String(error), { status: 400 });\n }\n }\n\n // This is unused since there are no incoming websocket messages\n async webSocketMessage(ws: WebSocket, event: ArrayBuffer | string) {\n let message: JSONRPCMessage;\n try {\n // Ensure event is a string\n const data =\n typeof event === \"string\" ? event : new TextDecoder().decode(event);\n message = JSONRPCMessageSchema.parse(JSON.parse(data));\n } catch (error) {\n this.#transport?.onerror?.(error as Error);\n return;\n }\n\n if (this.#status !== \"started\") {\n // This means the server \"woke up\" after hibernation\n // so we need to hydrate it again\n await this.#initialize();\n }\n\n this.#transport?.onmessage?.(message);\n }\n\n // WebSocket event handlers for hibernation support\n async webSocketError(ws: WebSocket, error: unknown): Promise<void> {\n if (this.#status !== \"started\") {\n // This means the server \"woke up\" after hibernation\n // so we need to hydrate it again\n await this.#initialize();\n }\n this.#transport?.onerror?.(error as Error);\n }\n\n async webSocketClose(\n ws: WebSocket,\n code: number,\n reason: string,\n wasClean: boolean\n ): Promise<void> {\n if (this.#status !== \"started\") {\n // This means the server \"woke up\" after hibernation\n // so we need to hydrate it again\n await this.#initialize();\n }\n this.#transport?.onclose?.();\n this.#connected = false;\n }\n\n static mount(\n path: string,\n {\n binding = \"MCP_OBJECT\",\n corsOptions,\n }: {\n binding?: string;\n corsOptions?: CORSOptions;\n } = {}\n ) {\n const basePattern = new URLPattern({ pathname: path });\n const messagePattern = new URLPattern({ pathname: `${path}/message` });\n\n return {\n fetch: async (\n request: Request,\n env: Record<string, DurableObjectNamespace<McpAgent>>,\n ctx: ExecutionContext\n ) => {\n // Handle CORS preflight\n const corsResponse = handleCORS(request, corsOptions);\n if (corsResponse) return corsResponse;\n\n const url = new URL(request.url);\n const namespace = env[binding];\n\n // Handle SSE connections\n if (request.method === \"GET\" && basePattern.test(url)) {\n // Use a session ID if one is passed in, or create a unique\n // session ID for this connection\n const sessionId =\n url.searchParams.get(\"sessionId\") ||\n namespace.newUniqueId().toString();\n\n // Create a Transform Stream for SSE\n const { readable, writable } = new TransformStream();\n const writer = writable.getWriter();\n const encoder = new TextEncoder();\n\n // Send the endpoint event\n const endpointMessage = `event: endpoint\\ndata: ${encodeURI(`${path}/message`)}?sessionId=${sessionId}\\n\\n`;\n writer.write(encoder.encode(endpointMessage));\n\n // Get the Durable Object\n const id = namespace.idFromString(sessionId);\n const doStub = namespace.get(id);\n\n // Initialize the object\n // @ts-ignore\n await doStub._init(ctx.props);\n\n // Connect to the Durable Object via WebSocket\n const upgradeUrl = new URL(request.url);\n upgradeUrl.searchParams.set(\"sessionId\", sessionId);\n const response = await doStub.fetch(\n new Request(upgradeUrl, {\n headers: {\n Upgrade: \"websocket\",\n },\n })\n );\n\n // Get the WebSocket\n const ws = response.webSocket;\n if (!ws) {\n console.error(\"Failed to establish WebSocket connection\");\n await writer.close();\n return;\n }\n\n // Accept the WebSocket\n ws.accept();\n\n // Handle messages from the Durable Object\n ws.addEventListener(\"message\", async (event) => {\n try {\n const message = JSON.parse(event.data);\n\n // validate that the message is a valid JSONRPC message\n // https://www.jsonrpc.org/specification#response_object\n if (!(typeof message.id === \"number\" || message.id === null)) {\n throw new Error(\"Invalid jsonrpc message id\");\n }\n\n if (message.jsonrpc !== \"2.0\") {\n throw new Error(\"Invalid jsonrpc version\");\n }\n\n // must have either result or error field\n if (\n !Object.hasOwn(message, \"result\") &&\n !Object.hasOwn(message, \"error\")\n ) {\n throw new Error(\n \"Invalid jsonrpc message. Must have either result or error field\"\n );\n }\n\n // Send the message as an SSE event\n const messageText = `event: message\\ndata: ${event.data}\\n\\n`;\n await writer.write(encoder.encode(messageText));\n } catch (error) {\n console.error(\"Error forwarding message to SSE:\", error);\n }\n });\n\n // Handle WebSocket errors\n ws.addEventListener(\"error\", async (error) => {\n try {\n await writer.close();\n } catch (e) {\n // Ignore errors when closing\n }\n });\n\n // Handle WebSocket closure\n ws.addEventListener(\"close\", async () => {\n try {\n await writer.close();\n } catch (error) {\n console.error(\"Error closing SSE connection:\", error);\n }\n });\n\n // Return the SSE response\n return new Response(readable, {\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n \"Access-Control-Allow-Origin\": corsOptions?.origin || \"*\",\n },\n });\n }\n\n // Handle MCP messages\n if (request.method === \"POST\" && messagePattern.test(url)) {\n const sessionId = url.searchParams.get(\"sessionId\");\n if (!sessionId) {\n return new Response(\n `Missing sessionId. Expected POST to ${path} to initiate new one`,\n { status: 400 }\n );\n }\n\n // Get the Durable Object\n const object = namespace.get(namespace.idFromString(sessionId));\n\n // Forward the request to the Durable Object\n const response = await object.onMCPMessage(sessionId, request);\n\n // Add CORS headers\n const headers = new Headers();\n response.headers.forEach?.((value, key) => {\n headers.set(key, value);\n });\n headers.set(\n \"Access-Control-Allow-Origin\",\n corsOptions?.origin || \"*\"\n );\n\n return new Response(response.body as unknown as BodyInit, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n\n return new Response(\"Not Found\", { status: 404 });\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,qBAAqB;AAK9B,SAAS,4BAA4B;AAGrC,IAAM,uBAAuB,IAAI,OAAO;AAGxC,SAAS,WACP,SACA,aACiB;AACjB,QAAM,SAAS,QAAQ,QAAQ,IAAI,QAAQ,KAAK;AAChD,QAAM,cAAc;AAAA,IAClB,+BAA+B,aAAa,UAAU;AAAA,IACtD,gCACE,aAAa,WAAW;AAAA,IAC1B,gCAAgC,aAAa,WAAW;AAAA,IACxD,2BAA2B,aAAa,UAAU,OAAO,SAAS;AAAA,EACpE;AAEA,MAAI,QAAQ,WAAW,WAAW;AAChC,WAAO,IAAI,SAAS,MAAM,EAAE,SAAS,YAAY,CAAC;AAAA,EACpD;AAEA,SAAO;AACT;AA7BA;AAsCA,IAAM,eAAN,MAAwC;AAAA,EAQtC,YAAY,cAAsC;AAFlD;AACA,iCAAW;AAET,uBAAK,eAAgB;AAAA,EACvB;AAAA,EAEA,MAAM,QAAQ;AAGZ,QAAI,mBAAK,WAAU;AACjB,YAAM,IAAI,MAAM,2BAA2B;AAAA,IAC7C;AACA,uBAAK,UAAW;AAAA,EAClB;AAAA,EAEA,MAAM,KAAK,SAAyB;AAClC,QAAI,CAAC,mBAAK,WAAU;AAClB,YAAM,IAAI,MAAM,uBAAuB;AAAA,IACzC;AACA,UAAM,YAAY,mBAAK,eAAL;AAClB,QAAI,CAAC,WAAW;AACd,YAAM,IAAI,MAAM,yBAAyB;AAAA,IAC3C;AACA,QAAI;AACF,gBAAU,KAAK,KAAK,UAAU,OAAO,CAAC;AAAA,IACxC,SAAS,OAAO;AACd,WAAK,UAAU,KAAc;AAC7B,YAAM;AAAA,IACR;AAAA,EACF;AAAA,EAEA,MAAM,QAAQ;AAEZ,SAAK,UAAU;AAAA,EACjB;AACF;AAnCE;AACA;AA7CF;AA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G;AACzD,gBAAM,YAAY,IAAI,aAAa,IAAI,WAAW;AAClD,cAAI,CAAC,WAAW;AACd,mBAAO,IAAI;AAAA,cACT,uCAAuC,IAAI;AAAA,cAC3C,EAAE,QAAQ,IAAI;AAAA,YAChB;AAAA,UACF;AAGA,gBAAM,SAAS,UAAU,IAAI,UAAU,aAAa,SAAS,CAAC;AAG9D,gBAAM,WAAW,MAAM,OAAO,aAAa,WAAW,OAAO;AAG7D,gBAAM,UAAU,IAAI,QAAQ;AAC5B,mBAAS,QAAQ,UAAU,CAAC,OAAO,QAAQ;AACzC,oBAAQ,IAAI,KAAK,KAAK;AAAA,UACxB,CAAC;AACD,kBAAQ;AAAA,YACN;AAAA,YACA,aAAa,UAAU;AAAA,UACzB;AAEA,iBAAO,IAAI,SAAS,SAAS,MAA6B;AAAA,YACxD,QAAQ,SAAS;AAAA,YACjB,YAAY,SAAS;AAAA,YACrB;AAAA,UACF,CAAC;AAAA,QACH;AAEA,eAAO,IAAI,SAAS,aAAa,EAAE,QAAQ,IAAI,CAAC;AAAA,MAClD;AAAA,IACF;AAAA,EACF;AACF;AA9YE;AACA;AACA;AAOS;AAdJ;AAkFC,gBAAW,iBAAkB;AACjC,QAAM,KAAK,IAAI,sBAAsB,YAAY;AAC/C,uBAAK,SAAU;AACf,UAAM,KAAK,QAAQ;AACnB,uBAAK,SAAU;AAAA,EACjB,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../../src/mcp/index.ts"],"sourcesContent":["import { DurableObject } from \"cloudflare:workers\";\nimport { Agent } from \"../\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { Connection } from \"../\";\nimport type { JSONRPCMessage } from \"@modelcontextprotocol/sdk/types.js\";\nimport { JSONRPCMessageSchema } from \"@modelcontextprotocol/sdk/types.js\";\nimport type { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\n\nconst MAXIMUM_MESSAGE_SIZE = 4 * 1024 * 1024; // 4MB\n\n// CORS helper function\nfunction handleCORS(\n request: Request,\n corsOptions?: CORSOptions\n): Response | null {\n const origin = request.headers.get(\"Origin\") || \"*\";\n const corsHeaders = {\n \"Access-Control-Allow-Origin\": corsOptions?.origin || origin,\n \"Access-Control-Allow-Methods\":\n corsOptions?.methods || \"GET, POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": corsOptions?.headers || \"Content-Type\",\n \"Access-Control-Max-Age\": (corsOptions?.maxAge || 86400).toString(),\n };\n\n if (request.method === \"OPTIONS\") {\n return new Response(null, { headers: corsHeaders });\n }\n\n return null;\n}\n\ninterface CORSOptions {\n origin?: string;\n methods?: string;\n headers?: string;\n maxAge?: number;\n}\n\nclass McpTransport implements Transport {\n onclose?: () => void;\n onerror?: (error: Error) => void;\n onmessage?: (message: JSONRPCMessage) => void;\n sessionId?: string;\n\n #getWebSocket: () => WebSocket | null;\n #started = false;\n constructor(getWebSocket: () => WebSocket | null) {\n this.#getWebSocket = getWebSocket;\n }\n\n async start() {\n // The transport does not manage the WebSocket connection since it's terminated\n // by the Durable Object in order to allow hibernation. There's nothing to initialize.\n if (this.#started) {\n throw new Error(\"Transport already started\");\n }\n this.#started = true;\n }\n\n async send(message: JSONRPCMessage) {\n if (!this.#started) {\n throw new Error(\"Transport not started\");\n }\n const websocket = this.#getWebSocket();\n if (!websocket) {\n throw new Error(\"WebSocket not connected\");\n }\n try {\n websocket.send(JSON.stringify(message));\n } catch (error) {\n this.onerror?.(error as Error);\n throw error;\n }\n }\n\n async close() {\n // Similar to start, the only thing to do is to pass the event on to the server\n this.onclose?.();\n }\n}\n\nexport abstract class McpAgent<\n Env = unknown,\n State = unknown,\n Props extends Record<string, unknown> = Record<string, unknown>,\n> extends DurableObject<Env> {\n #status: \"zero\" | \"starting\" | \"started\" = \"zero\";\n #transport?: McpTransport;\n #connected = false;\n\n /**\n * Since McpAgent's _aren't_ yet real \"Agents\" (they route differently, don't support\n * websockets, don't support hibernation), let's only expose a couple of the methods\n * to the outer class: initialState/state/setState/onStateUpdate/sql\n */\n readonly #agent: Agent<Env, State>;\n\n protected constructor(ctx: DurableObjectState, env: Env) {\n super(ctx, env);\n const self = this;\n\n // Since McpAgent's _aren't_ yet real \"Agents\" (they route differently, they don't support\n // scheduling etc, let's only expose a couple of the methods\n // to the outer class for now.\n this.#agent = new (class extends Agent<Env, State> {\n static options = {\n hibernate: true,\n };\n\n onStateUpdate(state: State | undefined, source: Connection | \"server\") {\n return self.onStateUpdate(state, source);\n }\n })(ctx, env);\n }\n\n /**\n * Agents API allowlist\n */\n initialState!: State;\n get state() {\n if (this.initialState) this.#agent.initialState = this.initialState;\n return this.#agent.state;\n }\n sql<T = Record<string, string | number | boolean | null>>(\n strings: TemplateStringsArray,\n ...values: (string | number | boolean | null)[]\n ) {\n return this.#agent.sql<T>(strings, ...values);\n }\n\n setState(state: State) {\n return this.#agent.setState(state);\n }\n onStateUpdate(state: State | undefined, source: Connection | \"server\") {\n // override this to handle state updates\n }\n async onStart() {\n this.props = (await this.ctx.storage.get(\"props\")) as Props;\n this.init?.();\n\n // Connect to the MCP server\n this.#transport = new McpTransport(() => this.getWebSocket());\n await this.server.connect(this.#transport);\n }\n\n /**\n * McpAgent API\n */\n abstract server: McpServer;\n props!: Props;\n initRun = false;\n\n abstract init(): Promise<void>;\n\n async _init(props: Props) {\n await this.ctx.storage.put(\"props\", props);\n this.props = props;\n if (!this.initRun) {\n this.initRun = true;\n await this.init();\n }\n }\n\n async #initialize(): Promise<void> {\n await this.ctx.blockConcurrencyWhile(async () => {\n this.#status = \"starting\";\n await this.onStart();\n this.#status = \"started\";\n });\n }\n\n // Allow the worker to fetch a websocket connection to the agent\n async fetch(request: Request): Promise<Response> {\n if (this.#status !== \"started\") {\n // This means the server \"woke up\" after hibernation\n // so we need to hydrate it again\n await this.#initialize();\n }\n\n // Only handle WebSocket upgrade requests\n if (request.headers.get(\"Upgrade\") !== \"websocket\") {\n return new Response(\"Expected WebSocket Upgrade request\", {\n status: 400,\n });\n }\n\n const url = new URL(request.url);\n const sessionId = url.searchParams.get(\"sessionId\");\n if (!sessionId) {\n return new Response(\"Missing sessionId\", { status: 400 });\n }\n\n // Create a WebSocket pair\n const webSocketPair = new WebSocketPair();\n const [client, server] = Object.values(webSocketPair);\n\n // For now, each agent can only have one connection\n // If we get an upgrade while already connected, we should error\n if (this.#connected) {\n return new Response(\"WebSocket already connected\", { status: 400 });\n }\n this.ctx.acceptWebSocket(server);\n this.#connected = true;\n\n // Connect to the MCP server\n this.#transport = new McpTransport(() => this.getWebSocket());\n await this.server.connect(this.#transport);\n\n return new Response(null, {\n status: 101,\n webSocket: client,\n });\n }\n\n getWebSocket() {\n const websockets = this.ctx.getWebSockets();\n if (websockets.length === 0) {\n return null;\n }\n return websockets[0];\n }\n\n async onMCPMessage(sessionId: string, request: Request): Promise<Response> {\n if (this.#status !== \"started\") {\n // This means the server \"woke up\" after hibernation\n // so we need to hydrate it again\n await this.#initialize();\n }\n try {\n const contentType = request.headers.get(\"content-type\") || \"\";\n if (!contentType.includes(\"application/json\")) {\n return new Response(`Unsupported content-type: ${contentType}`, {\n status: 400,\n });\n }\n\n // check if the request body is too large\n const contentLength = Number.parseInt(\n request.headers.get(\"content-length\") || \"0\",\n 10\n );\n if (contentLength > MAXIMUM_MESSAGE_SIZE) {\n return new Response(`Request body too large: ${contentLength} bytes`, {\n status: 400,\n });\n }\n\n // Clone the request before reading the body to avoid stream issues\n const message = await request.json();\n let parsedMessage: JSONRPCMessage;\n try {\n parsedMessage = JSONRPCMessageSchema.parse(message);\n } catch (error) {\n this.#transport?.onerror?.(error as Error);\n throw error;\n }\n\n this.#transport?.onmessage?.(parsedMessage);\n return new Response(\"Accepted\", { status: 202 });\n } catch (error) {\n this.#transport?.onerror?.(error as Error);\n return new Response(String(error), { status: 400 });\n }\n }\n\n // This is unused since there are no incoming websocket messages\n async webSocketMessage(ws: WebSocket, event: ArrayBuffer | string) {\n let message: JSONRPCMessage;\n try {\n // Ensure event is a string\n const data =\n typeof event === \"string\" ? event : new TextDecoder().decode(event);\n message = JSONRPCMessageSchema.parse(JSON.parse(data));\n } catch (error) {\n this.#transport?.onerror?.(error as Error);\n return;\n }\n\n if (this.#status !== \"started\") {\n // This means the server \"woke up\" after hibernation\n // so we need to hydrate it again\n await this.#initialize();\n }\n\n this.#transport?.onmessage?.(message);\n }\n\n // WebSocket event handlers for hibernation support\n async webSocketError(ws: WebSocket, error: unknown): Promise<void> {\n if (this.#status !== \"started\") {\n // This means the server \"woke up\" after hibernation\n // so we need to hydrate it again\n await this.#initialize();\n }\n this.#transport?.onerror?.(error as Error);\n }\n\n async webSocketClose(\n ws: WebSocket,\n code: number,\n reason: string,\n wasClean: boolean\n ): Promise<void> {\n if (this.#status !== \"started\") {\n // This means the server \"woke up\" after hibernation\n // so we need to hydrate it again\n await this.#initialize();\n }\n this.#transport?.onclose?.();\n this.#connected = false;\n }\n\n static mount(\n path: string,\n {\n binding = \"MCP_OBJECT\",\n corsOptions,\n }: {\n binding?: string;\n corsOptions?: CORSOptions;\n } = {}\n ) {\n let pathname = path;\n if (path === \"/\") {\n pathname = \"/*\";\n }\n const basePattern = new URLPattern({ pathname });\n const messagePattern = new URLPattern({ pathname: `${pathname}/message` });\n\n return {\n fetch: async (\n request: Request,\n env: Record<string, DurableObjectNamespace<McpAgent>>,\n ctx: ExecutionContext\n ) => {\n // Handle CORS preflight\n const corsResponse = handleCORS(request, corsOptions);\n if (corsResponse) return corsResponse;\n\n const url = new URL(request.url);\n const namespace = env[binding];\n\n // Handle SSE connections\n if (request.method === \"GET\" && basePattern.test(url)) {\n // Use a session ID if one is passed in, or create a unique\n // session ID for this connection\n const sessionId =\n url.searchParams.get(\"sessionId\") ||\n namespace.newUniqueId().toString();\n\n // Create a Transform Stream for SSE\n const { readable, writable } = new TransformStream();\n const writer = writable.getWriter();\n const encoder = new TextEncoder();\n\n // Send the endpoint event\n const endpointMessage = `event: endpoint\\ndata: ${encodeURI(`${pathname}/message`)}?sessionId=${sessionId}\\n\\n`;\n writer.write(encoder.encode(endpointMessage));\n\n // Get the Durable Object\n const id = namespace.idFromString(sessionId);\n const doStub = namespace.get(id);\n\n // Initialize the object\n // @ts-ignore\n await doStub._init(ctx.props);\n\n // Connect to the Durable Object via WebSocket\n const upgradeUrl = new URL(request.url);\n upgradeUrl.searchParams.set(\"sessionId\", sessionId);\n const response = await doStub.fetch(\n new Request(upgradeUrl, {\n headers: {\n Upgrade: \"websocket\",\n },\n })\n );\n\n // Get the WebSocket\n const ws = response.webSocket;\n if (!ws) {\n console.error(\"Failed to establish WebSocket connection\");\n await writer.close();\n return;\n }\n\n // Accept the WebSocket\n ws.accept();\n\n // Handle messages from the Durable Object\n ws.addEventListener(\"message\", async (event) => {\n try {\n const message = JSON.parse(event.data);\n\n // validate that the message is a valid JSONRPC message\n // https://www.jsonrpc.org/specification#response_object\n if (!(typeof message.id === \"number\" || message.id === null)) {\n throw new Error(\"Invalid jsonrpc message id\");\n }\n\n if (message.jsonrpc !== \"2.0\") {\n throw new Error(\"Invalid jsonrpc version\");\n }\n\n // must have either result or error field\n if (\n !Object.hasOwn(message, \"result\") &&\n !Object.hasOwn(message, \"error\")\n ) {\n throw new Error(\n \"Invalid jsonrpc message. Must have either result or error field\"\n );\n }\n\n // Send the message as an SSE event\n const messageText = `event: message\\ndata: ${event.data}\\n\\n`;\n await writer.write(encoder.encode(messageText));\n } catch (error) {\n console.error(\"Error forwarding message to SSE:\", error);\n }\n });\n\n // Handle WebSocket errors\n ws.addEventListener(\"error\", async (error) => {\n try {\n await writer.close();\n } catch (e) {\n // Ignore errors when closing\n }\n });\n\n // Handle WebSocket closure\n ws.addEventListener(\"close\", async () => {\n try {\n await writer.close();\n } catch (error) {\n console.error(\"Error closing SSE connection:\", error);\n }\n });\n\n // Return the SSE response\n return new Response(readable, {\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n \"Access-Control-Allow-Origin\": corsOptions?.origin || \"*\",\n },\n });\n }\n\n // Handle MCP messages\n if (request.method === \"POST\" && messagePattern.test(url)) {\n const sessionId = url.searchParams.get(\"sessionId\");\n if (!sessionId) {\n return new Response(\n `Missing sessionId. Expected POST to ${pathname} to initiate new one`,\n { status: 400 }\n );\n }\n\n // Get the Durable Object\n const object = namespace.get(namespace.idFromString(sessionId));\n\n // Forward the request to the Durable Object\n const response = await object.onMCPMessage(sessionId, request);\n\n // Add CORS headers\n const headers = new Headers();\n response.headers.forEach?.((value, key) => {\n headers.set(key, value);\n });\n headers.set(\n \"Access-Control-Allow-Origin\",\n corsOptions?.origin || \"*\"\n );\n\n return new Response(response.body as unknown as BodyInit, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n\n return new Response(\"Not Found\", { status: 404 });\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,qBAAqB;AAK9B,SAAS,4BAA4B;AAGrC,IAAM,uBAAuB,IAAI,OAAO;AAGxC,SAAS,WACP,SACA,aACiB;AACjB,QAAM,SAAS,QAAQ,QAAQ,IAAI,QAAQ,KAAK;AAChD,QAAM,cAAc;AAAA,IAClB,+BAA+B,aAAa,UAAU;AAAA,IACtD,gCACE,aAAa,WAAW;AAAA,IAC1B,gCAAgC,aAAa,WAAW;AAAA,IACxD,2BAA2B,aAAa,UAAU,OAAO,SAAS;AAAA,EACpE;AAEA,MAAI,QAAQ,WAAW,WAAW;AAChC,WAAO,IAAI,SAAS,MAAM,EAAE,SAAS,YAAY,CAAC;AAAA,EACpD;AAEA,SAAO;AACT;AA7BA;AAsCA,IAAM,eAAN,MAAwC;AAAA,EAQtC,YAAY,cAAsC;AAFlD;AACA,iCAAW;AAET,uBAAK,eAAgB;AAAA,EACvB;AAAA,EAEA,MAAM,QAAQ;AAGZ,QAAI,mBAAK,WAAU;AACjB,YAAM,IAAI,MAAM,2BAA2B;AAAA,IAC7C;AACA,uBAAK,UAAW;AAAA,EAClB;AAAA,EAEA,MAAM,KAAK,SAAyB;AAClC,QAAI,CAAC,mBAAK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f,UAAM,KAAK,QAAQ;AACnB,uBAAK,SAAU;AAAA,EACjB,CAAC;AACH;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agents",
3
- "version": "0.0.52",
3
+ "version": "0.0.54",
4
4
  "main": "src/index.ts",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -52,6 +52,11 @@
52
52
  "types": "./dist/mcp/client.d.ts",
53
53
  "require": "./dist/mcp/client.js",
54
54
  "import": "./dist/mcp/client.js"
55
+ },
56
+ "./mcp/do-oauth-client-provider": {
57
+ "types": "./dist/mcp/do-oauth-client-provider.d.ts",
58
+ "require": "./dist/mcp/do-oauth-client-provider.js",
59
+ "import": "./dist/mcp/do-oauth-client-provider.js"
55
60
  }
56
61
  },
57
62
  "keywords": [],