agents 0.0.0-21cc416 → 0.0.0-2662748

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/ai-chat-agent.d.ts +49 -3
  2. package/dist/ai-chat-agent.js +127 -65
  3. package/dist/ai-chat-agent.js.map +1 -1
  4. package/dist/ai-react.d.ts +13 -0
  5. package/dist/ai-react.js +25 -18
  6. package/dist/ai-react.js.map +1 -1
  7. package/dist/ai-types.d.ts +5 -0
  8. package/dist/chunk-BZXOAZUX.js +106 -0
  9. package/dist/chunk-BZXOAZUX.js.map +1 -0
  10. package/dist/chunk-OYJXQRRH.js +465 -0
  11. package/dist/chunk-OYJXQRRH.js.map +1 -0
  12. package/dist/{chunk-XG52S6YY.js → chunk-P3RZJ72N.js} +328 -136
  13. package/dist/chunk-P3RZJ72N.js.map +1 -0
  14. package/dist/chunk-VCSB47AK.js +116 -0
  15. package/dist/chunk-VCSB47AK.js.map +1 -0
  16. package/dist/client.d.ts +15 -1
  17. package/dist/client.js +6 -126
  18. package/dist/client.js.map +1 -1
  19. package/dist/index.d.ts +120 -11
  20. package/dist/index.js +8 -6
  21. package/dist/mcp/client.d.ts +57 -36
  22. package/dist/mcp/client.js +3 -465
  23. package/dist/mcp/client.js.map +1 -1
  24. package/dist/mcp/do-oauth-client-provider.d.ts +41 -0
  25. package/dist/mcp/do-oauth-client-provider.js +7 -0
  26. package/dist/mcp/index.d.ts +44 -5
  27. package/dist/mcp/index.js +591 -158
  28. package/dist/mcp/index.js.map +1 -1
  29. package/dist/react.d.ts +85 -5
  30. package/dist/react.js +14 -2
  31. package/dist/react.js.map +1 -1
  32. package/dist/schedule.js +0 -2
  33. package/dist/schedule.js.map +1 -1
  34. package/dist/serializable.d.ts +32 -0
  35. package/dist/serializable.js +1 -0
  36. package/dist/serializable.js.map +1 -0
  37. package/package.json +25 -5
  38. package/src/index.ts +394 -54
  39. package/dist/chunk-HMLY7DHA.js +0 -16
  40. package/dist/chunk-XG52S6YY.js.map +0 -1
  41. /package/dist/{chunk-HMLY7DHA.js.map → mcp/do-oauth-client-provider.js.map} +0 -0
package/dist/index.js CHANGED
@@ -2,19 +2,21 @@ import {
2
2
  Agent,
3
3
  StreamingResponse,
4
4
  getAgentByName,
5
+ getCurrentAgent,
5
6
  routeAgentEmail,
6
7
  routeAgentRequest,
7
- unstable_callable,
8
- unstable_context
9
- } from "./chunk-XG52S6YY.js";
10
- import "./chunk-HMLY7DHA.js";
8
+ unstable_callable
9
+ } from "./chunk-P3RZJ72N.js";
10
+ import "./chunk-OYJXQRRH.js";
11
+ import "./chunk-BZXOAZUX.js";
12
+ import "./chunk-VCSB47AK.js";
11
13
  export {
12
14
  Agent,
13
15
  StreamingResponse,
14
16
  getAgentByName,
17
+ getCurrentAgent,
15
18
  routeAgentEmail,
16
19
  routeAgentRequest,
17
- unstable_callable,
18
- unstable_context
20
+ unstable_callable
19
21
  };
20
22
  //# sourceMappingURL=index.js.map
@@ -1,14 +1,21 @@
1
1
  import * as zod from 'zod';
2
- import { Tool, Prompt, Resource, ResourceTemplate, ServerCapabilities, ClientCapabilities, CallToolRequest, CallToolResultSchema, CompatibilityCallToolResultSchema, ReadResourceRequest, GetPromptRequest } from '@modelcontextprotocol/sdk/types.js';
2
+ import { Tool, Prompt, Resource, ResourceTemplate, ServerCapabilities, CallToolRequest, CallToolResultSchema, CompatibilityCallToolResultSchema, ReadResourceRequest, GetPromptRequest } from '@modelcontextprotocol/sdk/types.js';
3
3
  import { Client } from '@modelcontextprotocol/sdk/client/index.js';
4
4
  import { SSEClientTransportOptions } from '@modelcontextprotocol/sdk/client/sse.js';
5
+ import { AgentsOAuthProvider } from './do-oauth-client-provider.js';
5
6
  import { RequestOptions } from '@modelcontextprotocol/sdk/shared/protocol.js';
6
- import { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js';
7
+ import { ToolSet } from 'ai';
8
+ import '@modelcontextprotocol/sdk/client/auth.js';
9
+ import '@modelcontextprotocol/sdk/shared/auth.js';
7
10
 
8
11
  declare class MCPClientConnection {
9
12
  url: URL;
10
- private info;
11
- private options;
13
+ options: {
14
+ transport: SSEClientTransportOptions & {
15
+ authProvider?: AgentsOAuthProvider;
16
+ };
17
+ client: ConstructorParameters<typeof Client>[1];
18
+ };
12
19
  client: Client;
13
20
  connectionState: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
14
21
  instructions?: string;
@@ -18,9 +25,10 @@ declare class MCPClientConnection {
18
25
  resourceTemplates: ResourceTemplate[];
19
26
  serverCapabilities: ServerCapabilities | undefined;
20
27
  constructor(url: URL, info: ConstructorParameters<typeof Client>[0], options?: {
21
- transport: SSEClientTransportOptions;
28
+ transport: SSEClientTransportOptions & {
29
+ authProvider?: AgentsOAuthProvider;
30
+ };
22
31
  client: ConstructorParameters<typeof Client>[1];
23
- capabilities: ClientCapabilities;
24
32
  });
25
33
  /**
26
34
  * Initialize a client connection
@@ -28,7 +36,7 @@ declare class MCPClientConnection {
28
36
  * @param code Optional OAuth code to initialize the connection with if auth hasn't been initialized
29
37
  * @returns
30
38
  */
31
- init(code?: string, clientId?: string): Promise<void>;
39
+ init(code?: string): Promise<void>;
32
40
  /**
33
41
  * Notification handler registration
34
42
  */
@@ -47,6 +55,14 @@ declare class MCPClientConnection {
47
55
  } | undefined;
48
56
  };
49
57
  description?: string | undefined;
58
+ annotations?: {
59
+ [x: string]: unknown;
60
+ title?: string | undefined;
61
+ readOnlyHint?: boolean | undefined;
62
+ destructiveHint?: boolean | undefined;
63
+ idempotentHint?: boolean | undefined;
64
+ openWorldHint?: boolean | undefined;
65
+ } | undefined;
50
66
  }[]>;
51
67
  fetchResources(): Promise<{
52
68
  [x: string]: unknown;
@@ -75,28 +91,20 @@ declare class MCPClientConnection {
75
91
  }[]>;
76
92
  }
77
93
 
78
- interface AgentsOAuthProvider extends OAuthClientProvider {
79
- authUrl: string | undefined;
80
- clientId: string | undefined;
81
- }
82
-
83
94
  /**
84
95
  * Utility class that aggregates multiple MCP clients into one
85
96
  */
86
97
  declare class MCPClientManager {
87
- private name;
88
- private version;
89
- private auth?;
98
+ private _name;
99
+ private _version;
90
100
  mcpConnections: Record<string, MCPClientConnection>;
101
+ private _callbackUrls;
91
102
  /**
92
- * @param name Name of the MCP client
93
- * @param version Version of the MCP Client
103
+ * @param _name Name of the MCP client
104
+ * @param _version Version of the MCP Client
94
105
  * @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider
95
106
  */
96
- constructor(name: string, version: string, auth?: {
97
- baseCallbackUri: string;
98
- storage: DurableObjectStorage;
99
- } | undefined);
107
+ constructor(_name: string, _version: string);
100
108
  /**
101
109
  * Connect to and register an MCP server
102
110
  *
@@ -104,20 +112,20 @@ declare class MCPClientManager {
104
112
  * @param clientConfig Client config
105
113
  * @param capabilities Client capabilities (i.e. if the client supports roots/sampling)
106
114
  */
107
- connect(url: string, opts?: {
115
+ connect(url: string, options?: {
108
116
  reconnect?: {
109
117
  id: string;
110
118
  oauthClientId?: string;
111
119
  oauthCode?: string;
112
120
  };
113
121
  transport?: SSEClientTransportOptions & {
114
- authProvider: AgentsOAuthProvider;
122
+ authProvider?: AgentsOAuthProvider;
115
123
  };
116
124
  client?: ConstructorParameters<typeof Client>[1];
117
- capabilities?: ClientCapabilities;
118
125
  }): Promise<{
119
126
  id: string;
120
- authUrl: string | undefined;
127
+ authUrl?: string;
128
+ clientId?: string;
121
129
  }>;
122
130
  isCallbackRequest(req: Request): boolean;
123
131
  handleCallbackRequest(req: Request): Promise<{
@@ -127,6 +135,19 @@ declare class MCPClientManager {
127
135
  * @returns namespaced list of tools
128
136
  */
129
137
  listTools(): NamespacedData["tools"];
138
+ /**
139
+ * @returns a set of tools that you can use with the AI SDK
140
+ */
141
+ unstable_getAITools(): ToolSet;
142
+ /**
143
+ * Closes all connections to MCP servers
144
+ */
145
+ closeAllConnections(): Promise<void[]>;
146
+ /**
147
+ * Closes a connection to an MCP server
148
+ * @param id The id of the connection to close
149
+ */
150
+ closeConnection(id: string): Promise<void>;
130
151
  /**
131
152
  * @returns namespaced list of prompts
132
153
  */
@@ -144,9 +165,9 @@ declare class MCPClientManager {
144
165
  */
145
166
  callTool(params: CallToolRequest["params"] & {
146
167
  serverId: string;
147
- }, resultSchema: typeof CallToolResultSchema | typeof CompatibilityCallToolResultSchema, options: RequestOptions): Promise<zod.objectOutputType<zod.objectUtil.extendShape<{
168
+ }, resultSchema?: typeof CallToolResultSchema | typeof CompatibilityCallToolResultSchema, options?: RequestOptions): Promise<zod.objectOutputType<{
148
169
  _meta: zod.ZodOptional<zod.ZodObject<{}, "passthrough", zod.ZodTypeAny, zod.objectOutputType<{}, zod.ZodTypeAny, "passthrough">, zod.objectInputType<{}, zod.ZodTypeAny, "passthrough">>>;
149
- }, {
170
+ } & {
150
171
  content: zod.ZodArray<zod.ZodUnion<[zod.ZodObject<{
151
172
  type: zod.ZodLiteral<"text">;
152
173
  text: zod.ZodString;
@@ -281,19 +302,19 @@ declare class MCPClientManager {
281
302
  }>, zod.ZodTypeAny, "passthrough">>]>;
282
303
  }, zod.ZodTypeAny, "passthrough">>]>, "many">;
283
304
  isError: zod.ZodOptional<zod.ZodDefault<zod.ZodBoolean>>;
284
- }>, zod.ZodTypeAny, "passthrough"> | zod.objectOutputType<zod.objectUtil.extendShape<{
305
+ }, zod.ZodTypeAny, "passthrough"> | zod.objectOutputType<{
285
306
  _meta: zod.ZodOptional<zod.ZodObject<{}, "passthrough", zod.ZodTypeAny, zod.objectOutputType<{}, zod.ZodTypeAny, "passthrough">, zod.objectInputType<{}, zod.ZodTypeAny, "passthrough">>>;
286
- }, {
307
+ } & {
287
308
  toolResult: zod.ZodUnknown;
288
- }>, zod.ZodTypeAny, "passthrough">>;
309
+ }, zod.ZodTypeAny, "passthrough">>;
289
310
  /**
290
311
  * Namespaced version of readResource
291
312
  */
292
313
  readResource(params: ReadResourceRequest["params"] & {
293
314
  serverId: string;
294
- }, options: RequestOptions): Promise<zod.objectOutputType<zod.objectUtil.extendShape<{
315
+ }, options: RequestOptions): Promise<zod.objectOutputType<{
295
316
  _meta: zod.ZodOptional<zod.ZodObject<{}, "passthrough", zod.ZodTypeAny, zod.objectOutputType<{}, zod.ZodTypeAny, "passthrough">, zod.objectInputType<{}, zod.ZodTypeAny, "passthrough">>>;
296
- }, {
317
+ } & {
297
318
  contents: zod.ZodArray<zod.ZodUnion<[zod.ZodObject<zod.objectUtil.extendShape<{
298
319
  uri: zod.ZodString;
299
320
  mimeType: zod.ZodOptional<zod.ZodString>;
@@ -325,15 +346,15 @@ declare class MCPClientManager {
325
346
  }, {
326
347
  blob: zod.ZodString;
327
348
  }>, zod.ZodTypeAny, "passthrough">>]>, "many">;
328
- }>, zod.ZodTypeAny, "passthrough">>;
349
+ }, zod.ZodTypeAny, "passthrough">>;
329
350
  /**
330
351
  * Namespaced version of getPrompt
331
352
  */
332
353
  getPrompt(params: GetPromptRequest["params"] & {
333
354
  serverId: string;
334
- }, options: RequestOptions): Promise<zod.objectOutputType<zod.objectUtil.extendShape<{
355
+ }, options: RequestOptions): Promise<zod.objectOutputType<{
335
356
  _meta: zod.ZodOptional<zod.ZodObject<{}, "passthrough", zod.ZodTypeAny, zod.objectOutputType<{}, zod.ZodTypeAny, "passthrough">, zod.objectInputType<{}, zod.ZodTypeAny, "passthrough">>>;
336
- }, {
357
+ } & {
337
358
  description: zod.ZodOptional<zod.ZodString>;
338
359
  messages: zod.ZodArray<zod.ZodObject<{
339
360
  role: zod.ZodEnum<["user", "assistant"]>;
@@ -741,7 +762,7 @@ declare class MCPClientManager {
741
762
  }>, zod.ZodTypeAny, "passthrough">>]>;
742
763
  }, zod.ZodTypeAny, "passthrough">>]>;
743
764
  }, zod.ZodTypeAny, "passthrough">>, "many">;
744
- }>, zod.ZodTypeAny, "passthrough">>;
765
+ }, zod.ZodTypeAny, "passthrough">>;
745
766
  }
746
767
  type NamespacedData = {
747
768
  tools: (Tool & {
@@ -1,469 +1,7 @@
1
- import "../chunk-HMLY7DHA.js";
2
-
3
- // src/mcp/sse-edge.ts
4
1
  import {
5
- SSEClientTransport
6
- } from "@modelcontextprotocol/sdk/client/sse.js";
7
- var SSEEdgeClientTransport = class extends SSEClientTransport {
8
- /**
9
- * Creates a new EdgeSSEClientTransport, which overrides fetch to be compatible with the CF workers environment
10
- */
11
- constructor(url, options) {
12
- const fetchOverride = async (fetchUrl, fetchInit = {}) => {
13
- const headers = await this.authHeaders();
14
- const workerOptions = {
15
- ...fetchInit,
16
- headers: {
17
- ...fetchInit?.headers,
18
- ...headers
19
- }
20
- };
21
- delete workerOptions.mode;
22
- return fetch(fetchUrl, workerOptions);
23
- };
24
- super(url, {
25
- ...options,
26
- eventSourceInit: {
27
- fetch: fetchOverride
28
- }
29
- });
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
- }
41
- }
42
- };
43
-
44
- // src/mcp/client-connection.ts
45
- import {
46
- ToolListChangedNotificationSchema,
47
- ResourceListChangedNotificationSchema,
48
- PromptListChangedNotificationSchema
49
- } from "@modelcontextprotocol/sdk/types.js";
50
- import { Client } from "@modelcontextprotocol/sdk/client/index.js";
51
- var MCPClientConnection = class {
52
- constructor(url, info, options = { transport: {}, client: {}, capabilities: {} }) {
53
- this.url = url;
54
- this.info = info;
55
- this.options = options;
56
- this.connectionState = "connecting";
57
- this.tools = [];
58
- this.prompts = [];
59
- this.resources = [];
60
- this.resourceTemplates = [];
61
- this.client = new Client(info, options.client);
62
- this.client.registerCapabilities(options.capabilities);
63
- }
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";
89
- this.serverCapabilities = await this.client.getServerCapabilities();
90
- if (!this.serverCapabilities) {
91
- throw new Error("The MCP Server failed to return server capabilities");
92
- }
93
- const [instructions, tools, resources, prompts, resourceTemplates] = await Promise.all([
94
- this.client.getInstructions(),
95
- this.registerTools(),
96
- this.registerResources(),
97
- this.registerPrompts(),
98
- this.registerResourceTemplates()
99
- ]);
100
- this.instructions = instructions;
101
- this.tools = tools;
102
- this.resources = resources;
103
- this.prompts = prompts;
104
- this.resourceTemplates = resourceTemplates;
105
- this.connectionState = "ready";
106
- }
107
- /**
108
- * Notification handler registration
109
- */
110
- async registerTools() {
111
- if (!this.serverCapabilities || !this.serverCapabilities.tools) {
112
- return [];
113
- }
114
- if (this.serverCapabilities.tools.listChanged) {
115
- this.client.setNotificationHandler(
116
- ToolListChangedNotificationSchema,
117
- async (_notification) => {
118
- this.tools = await this.fetchTools();
119
- }
120
- );
121
- }
122
- return this.fetchTools();
123
- }
124
- async registerResources() {
125
- if (!this.serverCapabilities || !this.serverCapabilities.resources) {
126
- return [];
127
- }
128
- if (this.serverCapabilities.resources.listChanged) {
129
- this.client.setNotificationHandler(
130
- ResourceListChangedNotificationSchema,
131
- async (_notification) => {
132
- this.resources = await this.fetchResources();
133
- }
134
- );
135
- }
136
- return this.fetchResources();
137
- }
138
- async registerPrompts() {
139
- if (!this.serverCapabilities || !this.serverCapabilities.prompts) {
140
- return [];
141
- }
142
- if (this.serverCapabilities.prompts.listChanged) {
143
- this.client.setNotificationHandler(
144
- PromptListChangedNotificationSchema,
145
- async (_notification) => {
146
- this.prompts = await this.fetchPrompts();
147
- }
148
- );
149
- }
150
- return this.fetchPrompts();
151
- }
152
- async registerResourceTemplates() {
153
- if (!this.serverCapabilities || !this.serverCapabilities.resources) {
154
- return [];
155
- }
156
- return this.fetchResourceTemplates();
157
- }
158
- async fetchTools() {
159
- let toolsAgg = [];
160
- let toolsResult = { tools: [] };
161
- do {
162
- toolsResult = await this.client.listTools({
163
- cursor: toolsResult.nextCursor
164
- });
165
- toolsAgg = toolsAgg.concat(toolsResult.tools);
166
- } while (toolsResult.nextCursor);
167
- return toolsAgg;
168
- }
169
- async fetchResources() {
170
- let resourcesAgg = [];
171
- let resourcesResult = { resources: [] };
172
- do {
173
- resourcesResult = await this.client.listResources({
174
- cursor: resourcesResult.nextCursor
175
- });
176
- resourcesAgg = resourcesAgg.concat(resourcesResult.resources);
177
- } while (resourcesResult.nextCursor);
178
- return resourcesAgg;
179
- }
180
- async fetchPrompts() {
181
- let promptsAgg = [];
182
- let promptsResult = { prompts: [] };
183
- do {
184
- promptsResult = await this.client.listPrompts({
185
- cursor: promptsResult.nextCursor
186
- });
187
- promptsAgg = promptsAgg.concat(promptsResult.prompts);
188
- } while (promptsResult.nextCursor);
189
- return promptsAgg;
190
- }
191
- async fetchResourceTemplates() {
192
- let templatesAgg = [];
193
- let templatesResult = {
194
- resourceTemplates: []
195
- };
196
- do {
197
- templatesResult = await this.client.listResourceTemplates({
198
- cursor: templatesResult.nextCursor
199
- });
200
- templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);
201
- } while (templatesResult.nextCursor);
202
- return templatesAgg;
203
- }
204
- };
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
-
298
- // src/mcp/client.ts
299
- var MCPClientManager = class {
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;
309
- this.mcpConnections = {};
310
- }
311
- /**
312
- * Connect to and register an MCP server
313
- *
314
- * @param transportConfig Transport config
315
- * @param clientConfig Client config
316
- * @param capabilities Client capabilities (i.e. if the client supports roots/sampling)
317
- */
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") {
378
- throw new Error(
379
- "Failed to authenticate: the client isn't in the `authenticating` state"
380
- );
381
- }
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 };
394
- }
395
- /**
396
- * @returns namespaced list of tools
397
- */
398
- listTools() {
399
- return getNamespacedData(this.mcpConnections, "tools");
400
- }
401
- /**
402
- * @returns namespaced list of prompts
403
- */
404
- listPrompts() {
405
- return getNamespacedData(this.mcpConnections, "prompts");
406
- }
407
- /**
408
- * @returns namespaced list of tools
409
- */
410
- listResources() {
411
- return getNamespacedData(this.mcpConnections, "resources");
412
- }
413
- /**
414
- * @returns namespaced list of resource templates
415
- */
416
- listResourceTemplates() {
417
- return getNamespacedData(this.mcpConnections, "resourceTemplates");
418
- }
419
- /**
420
- * Namespaced version of callTool
421
- */
422
- callTool(params, resultSchema, options) {
423
- const unqualifiedName = params.name.replace(`${params.serverId}.`, "");
424
- return this.mcpConnections[params.serverId].client.callTool(
425
- {
426
- ...params,
427
- name: unqualifiedName
428
- },
429
- resultSchema,
430
- options
431
- );
432
- }
433
- /**
434
- * Namespaced version of readResource
435
- */
436
- readResource(params, options) {
437
- return this.mcpConnections[params.serverId].client.readResource(
438
- params,
439
- options
440
- );
441
- }
442
- /**
443
- * Namespaced version of getPrompt
444
- */
445
- getPrompt(params, options) {
446
- return this.mcpConnections[params.serverId].client.getPrompt(
447
- params,
448
- options
449
- );
450
- }
451
- };
452
- function getNamespacedData(mcpClients, type) {
453
- const sets = Object.entries(mcpClients).map(([name, conn]) => {
454
- return { name, data: conn[type] };
455
- });
456
- const namespacedData = sets.flatMap(({ name: serverId, data }) => {
457
- return data.map((item) => {
458
- return {
459
- ...item,
460
- // we add a serverId so we can easily pull it out and send the tool call to the right server
461
- serverId
462
- };
463
- });
464
- });
465
- return namespacedData;
466
- }
2
+ MCPClientManager,
3
+ getNamespacedData
4
+ } from "../chunk-OYJXQRRH.js";
467
5
  export {
468
6
  MCPClientManager,
469
7
  getNamespacedData