agents 0.0.0-c3e8618 → 0.0.0-c8f53b8

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,50 @@
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 { ClientCapabilities, 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
- import { SSEClientTransport, SSEClientTransportOptions } from '@modelcontextprotocol/sdk/client/sse.js';
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';
7
+ import { ToolSet } from 'ai';
8
+ import '@modelcontextprotocol/sdk/client/auth.js';
9
+ import '@modelcontextprotocol/sdk/shared/auth.js';
6
10
 
7
11
  declare class MCPClientConnection {
8
- private info;
12
+ url: URL;
13
+ options: {
14
+ transport: SSEClientTransportOptions & {
15
+ authProvider?: AgentsOAuthProvider;
16
+ };
17
+ client: ConstructorParameters<typeof Client>[1];
18
+ capabilities: ClientCapabilities;
19
+ };
9
20
  client: Client;
10
- transport: SSEClientTransport;
11
- connected: boolean;
21
+ connectionState: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
12
22
  instructions?: string;
13
23
  tools: Tool[];
14
- prompts: Prompt$1[];
24
+ prompts: Prompt[];
15
25
  resources: Resource[];
16
26
  resourceTemplates: ResourceTemplate[];
17
27
  serverCapabilities: ServerCapabilities | undefined;
18
- constructor(url: URL, info: ConstructorParameters<typeof Client>[0], opts?: {
19
- transport: SSEClientTransportOptions;
28
+ constructor(url: URL, info: ConstructorParameters<typeof Client>[0], options?: {
29
+ transport: SSEClientTransportOptions & {
30
+ authProvider?: AgentsOAuthProvider;
31
+ };
20
32
  client: ConstructorParameters<typeof Client>[1];
21
33
  capabilities: ClientCapabilities;
22
34
  });
23
- init(): Promise<void>;
35
+ /**
36
+ * Initialize a client connection
37
+ *
38
+ * @param code Optional OAuth code to initialize the connection with if auth hasn't been initialized
39
+ * @returns
40
+ */
41
+ init(code?: string, clientId?: string): Promise<void>;
24
42
  /**
25
43
  * Notification handler registration
26
44
  */
27
45
  registerTools(): Promise<Tool[]>;
28
46
  registerResources(): Promise<Resource[]>;
29
- registerPrompts(): Promise<Prompt$1[]>;
47
+ registerPrompts(): Promise<Prompt[]>;
30
48
  registerResourceTemplates(): Promise<ResourceTemplate[]>;
31
49
  fetchTools(): Promise<{
32
50
  [x: string]: unknown;
@@ -42,10 +60,10 @@ declare class MCPClientConnection {
42
60
  }[]>;
43
61
  fetchResources(): Promise<{
44
62
  [x: string]: unknown;
45
- name: string;
46
63
  uri: string;
47
- description?: string | undefined;
64
+ name: string;
48
65
  mimeType?: string | undefined;
66
+ description?: string | undefined;
49
67
  }[]>;
50
68
  fetchPrompts(): Promise<{
51
69
  [x: string]: unknown;
@@ -62,8 +80,8 @@ declare class MCPClientConnection {
62
80
  [x: string]: unknown;
63
81
  name: string;
64
82
  uriTemplate: string;
65
- description?: string | undefined;
66
83
  mimeType?: string | undefined;
84
+ description?: string | undefined;
67
85
  }[]>;
68
86
  }
69
87
 
@@ -71,7 +89,16 @@ declare class MCPClientConnection {
71
89
  * Utility class that aggregates multiple MCP clients into one
72
90
  */
73
91
  declare class MCPClientManager {
92
+ private name;
93
+ private version;
74
94
  mcpConnections: Record<string, MCPClientConnection>;
95
+ private callbackUrls;
96
+ /**
97
+ * @param name Name of the MCP client
98
+ * @param version Version of the MCP Client
99
+ * @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider
100
+ */
101
+ constructor(name: string, version: string);
75
102
  /**
76
103
  * Connect to and register an MCP server
77
104
  *
@@ -79,15 +106,42 @@ declare class MCPClientManager {
79
106
  * @param clientConfig Client config
80
107
  * @param capabilities Client capabilities (i.e. if the client supports roots/sampling)
81
108
  */
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>;
109
+ connect(url: string, options?: {
110
+ reconnect?: {
111
+ id: string;
112
+ oauthClientId?: string;
113
+ oauthCode?: string;
114
+ };
115
+ transport?: SSEClientTransportOptions & {
116
+ authProvider?: AgentsOAuthProvider;
117
+ };
118
+ client?: ConstructorParameters<typeof Client>[1];
119
+ capabilities?: ClientCapabilities;
120
+ }): Promise<{
121
+ id: string;
122
+ authUrl: string | undefined;
123
+ }>;
124
+ isCallbackRequest(req: Request): boolean;
125
+ handleCallbackRequest(req: Request): Promise<{
126
+ serverId: string;
127
+ }>;
87
128
  /**
88
129
  * @returns namespaced list of tools
89
130
  */
90
131
  listTools(): NamespacedData["tools"];
132
+ /**
133
+ * @returns a set of tools that you can use with the AI SDK
134
+ */
135
+ unstable_getAITools(): ToolSet;
136
+ /**
137
+ * Closes all connections to MCP servers
138
+ */
139
+ closeAllConnections(): Promise<void[]>;
140
+ /**
141
+ * Closes a connection to an MCP server
142
+ * @param id The id of the connection to close
143
+ */
144
+ closeConnection(id: string): Promise<void>;
91
145
  /**
92
146
  * @returns namespaced list of prompts
93
147
  */
@@ -104,10 +158,10 @@ declare class MCPClientManager {
104
158
  * Namespaced version of callTool
105
159
  */
106
160
  callTool(params: CallToolRequest["params"] & {
107
- serverName: string;
108
- }, resultSchema: typeof CallToolResultSchema | typeof CompatibilityCallToolResultSchema, options: RequestOptions): Promise<zod.objectOutputType<zod.objectUtil.extendShape<{
161
+ serverId: string;
162
+ }, resultSchema?: typeof CallToolResultSchema | typeof CompatibilityCallToolResultSchema, options?: RequestOptions): Promise<zod.objectOutputType<{
109
163
  _meta: zod.ZodOptional<zod.ZodObject<{}, "passthrough", zod.ZodTypeAny, zod.objectOutputType<{}, zod.ZodTypeAny, "passthrough">, zod.objectInputType<{}, zod.ZodTypeAny, "passthrough">>>;
110
- }, {
164
+ } & {
111
165
  content: zod.ZodArray<zod.ZodUnion<[zod.ZodObject<{
112
166
  type: zod.ZodLiteral<"text">;
113
167
  text: zod.ZodString;
@@ -129,6 +183,18 @@ declare class MCPClientManager {
129
183
  type: zod.ZodLiteral<"image">;
130
184
  data: zod.ZodString;
131
185
  mimeType: zod.ZodString;
186
+ }, zod.ZodTypeAny, "passthrough">>, zod.ZodObject<{
187
+ type: zod.ZodLiteral<"audio">;
188
+ data: zod.ZodString;
189
+ mimeType: zod.ZodString;
190
+ }, "passthrough", zod.ZodTypeAny, zod.objectOutputType<{
191
+ type: zod.ZodLiteral<"audio">;
192
+ data: zod.ZodString;
193
+ mimeType: zod.ZodString;
194
+ }, zod.ZodTypeAny, "passthrough">, zod.objectInputType<{
195
+ type: zod.ZodLiteral<"audio">;
196
+ data: zod.ZodString;
197
+ mimeType: zod.ZodString;
132
198
  }, zod.ZodTypeAny, "passthrough">>, zod.ZodObject<{
133
199
  type: zod.ZodLiteral<"resource">;
134
200
  resource: zod.ZodUnion<[zod.ZodObject<zod.objectUtil.extendShape<{
@@ -230,19 +296,19 @@ declare class MCPClientManager {
230
296
  }>, zod.ZodTypeAny, "passthrough">>]>;
231
297
  }, zod.ZodTypeAny, "passthrough">>]>, "many">;
232
298
  isError: zod.ZodOptional<zod.ZodDefault<zod.ZodBoolean>>;
233
- }>, zod.ZodTypeAny, "passthrough"> | zod.objectOutputType<zod.objectUtil.extendShape<{
299
+ }, zod.ZodTypeAny, "passthrough"> | zod.objectOutputType<{
234
300
  _meta: zod.ZodOptional<zod.ZodObject<{}, "passthrough", zod.ZodTypeAny, zod.objectOutputType<{}, zod.ZodTypeAny, "passthrough">, zod.objectInputType<{}, zod.ZodTypeAny, "passthrough">>>;
235
- }, {
301
+ } & {
236
302
  toolResult: zod.ZodUnknown;
237
- }>, zod.ZodTypeAny, "passthrough">>;
303
+ }, zod.ZodTypeAny, "passthrough">>;
238
304
  /**
239
305
  * Namespaced version of readResource
240
306
  */
241
307
  readResource(params: ReadResourceRequest["params"] & {
242
- serverName: string;
243
- }, options: RequestOptions): Promise<zod.objectOutputType<zod.objectUtil.extendShape<{
308
+ serverId: string;
309
+ }, options: RequestOptions): Promise<zod.objectOutputType<{
244
310
  _meta: zod.ZodOptional<zod.ZodObject<{}, "passthrough", zod.ZodTypeAny, zod.objectOutputType<{}, zod.ZodTypeAny, "passthrough">, zod.objectInputType<{}, zod.ZodTypeAny, "passthrough">>>;
245
- }, {
311
+ } & {
246
312
  contents: zod.ZodArray<zod.ZodUnion<[zod.ZodObject<zod.objectUtil.extendShape<{
247
313
  uri: zod.ZodString;
248
314
  mimeType: zod.ZodOptional<zod.ZodString>;
@@ -274,15 +340,15 @@ declare class MCPClientManager {
274
340
  }, {
275
341
  blob: zod.ZodString;
276
342
  }>, zod.ZodTypeAny, "passthrough">>]>, "many">;
277
- }>, zod.ZodTypeAny, "passthrough">>;
343
+ }, zod.ZodTypeAny, "passthrough">>;
278
344
  /**
279
345
  * Namespaced version of getPrompt
280
346
  */
281
347
  getPrompt(params: GetPromptRequest["params"] & {
282
- serverName: string;
283
- }, options: RequestOptions): Promise<zod.objectOutputType<zod.objectUtil.extendShape<{
348
+ serverId: string;
349
+ }, options: RequestOptions): Promise<zod.objectOutputType<{
284
350
  _meta: zod.ZodOptional<zod.ZodObject<{}, "passthrough", zod.ZodTypeAny, zod.objectOutputType<{}, zod.ZodTypeAny, "passthrough">, zod.objectInputType<{}, zod.ZodTypeAny, "passthrough">>>;
285
- }, {
351
+ } & {
286
352
  description: zod.ZodOptional<zod.ZodString>;
287
353
  messages: zod.ZodArray<zod.ZodObject<{
288
354
  role: zod.ZodEnum<["user", "assistant"]>;
@@ -307,6 +373,18 @@ declare class MCPClientManager {
307
373
  type: zod.ZodLiteral<"image">;
308
374
  data: zod.ZodString;
309
375
  mimeType: zod.ZodString;
376
+ }, zod.ZodTypeAny, "passthrough">>, zod.ZodObject<{
377
+ type: zod.ZodLiteral<"audio">;
378
+ data: zod.ZodString;
379
+ mimeType: zod.ZodString;
380
+ }, "passthrough", zod.ZodTypeAny, zod.objectOutputType<{
381
+ type: zod.ZodLiteral<"audio">;
382
+ data: zod.ZodString;
383
+ mimeType: zod.ZodString;
384
+ }, zod.ZodTypeAny, "passthrough">, zod.objectInputType<{
385
+ type: zod.ZodLiteral<"audio">;
386
+ data: zod.ZodString;
387
+ mimeType: zod.ZodString;
310
388
  }, zod.ZodTypeAny, "passthrough">>, zod.ZodObject<{
311
389
  type: zod.ZodLiteral<"resource">;
312
390
  resource: zod.ZodUnion<[zod.ZodObject<zod.objectUtil.extendShape<{
@@ -430,6 +508,18 @@ declare class MCPClientManager {
430
508
  type: zod.ZodLiteral<"image">;
431
509
  data: zod.ZodString;
432
510
  mimeType: zod.ZodString;
511
+ }, zod.ZodTypeAny, "passthrough">>, zod.ZodObject<{
512
+ type: zod.ZodLiteral<"audio">;
513
+ data: zod.ZodString;
514
+ mimeType: zod.ZodString;
515
+ }, "passthrough", zod.ZodTypeAny, zod.objectOutputType<{
516
+ type: zod.ZodLiteral<"audio">;
517
+ data: zod.ZodString;
518
+ mimeType: zod.ZodString;
519
+ }, zod.ZodTypeAny, "passthrough">, zod.objectInputType<{
520
+ type: zod.ZodLiteral<"audio">;
521
+ data: zod.ZodString;
522
+ mimeType: zod.ZodString;
433
523
  }, zod.ZodTypeAny, "passthrough">>, zod.ZodObject<{
434
524
  type: zod.ZodLiteral<"resource">;
435
525
  resource: zod.ZodUnion<[zod.ZodObject<zod.objectUtil.extendShape<{
@@ -553,6 +643,18 @@ declare class MCPClientManager {
553
643
  type: zod.ZodLiteral<"image">;
554
644
  data: zod.ZodString;
555
645
  mimeType: zod.ZodString;
646
+ }, zod.ZodTypeAny, "passthrough">>, zod.ZodObject<{
647
+ type: zod.ZodLiteral<"audio">;
648
+ data: zod.ZodString;
649
+ mimeType: zod.ZodString;
650
+ }, "passthrough", zod.ZodTypeAny, zod.objectOutputType<{
651
+ type: zod.ZodLiteral<"audio">;
652
+ data: zod.ZodString;
653
+ mimeType: zod.ZodString;
654
+ }, zod.ZodTypeAny, "passthrough">, zod.objectInputType<{
655
+ type: zod.ZodLiteral<"audio">;
656
+ data: zod.ZodString;
657
+ mimeType: zod.ZodString;
556
658
  }, zod.ZodTypeAny, "passthrough">>, zod.ZodObject<{
557
659
  type: zod.ZodLiteral<"resource">;
558
660
  resource: zod.ZodUnion<[zod.ZodObject<zod.objectUtil.extendShape<{
@@ -654,20 +756,20 @@ declare class MCPClientManager {
654
756
  }>, zod.ZodTypeAny, "passthrough">>]>;
655
757
  }, zod.ZodTypeAny, "passthrough">>]>;
656
758
  }, zod.ZodTypeAny, "passthrough">>, "many">;
657
- }>, zod.ZodTypeAny, "passthrough">>;
759
+ }, zod.ZodTypeAny, "passthrough">>;
658
760
  }
659
761
  type NamespacedData = {
660
762
  tools: (Tool & {
661
- serverName: string;
763
+ serverId: string;
662
764
  })[];
663
765
  prompts: (Prompt & {
664
- serverName: string;
766
+ serverId: string;
665
767
  })[];
666
768
  resources: (Resource & {
667
- serverName: string;
769
+ serverId: string;
668
770
  })[];
669
771
  resourceTemplates: (ResourceTemplate & {
670
- serverName: string;
772
+ serverId: string;
671
773
  })[];
672
774
  };
673
775
  declare function getNamespacedData<T extends keyof NamespacedData>(mcpClients: Record<string, MCPClientConnection>, type: T): NamespacedData[T];
@@ -0,0 +1,10 @@
1
+ import {
2
+ MCPClientManager,
3
+ getNamespacedData
4
+ } from "../chunk-Q5ZBHY4Z.js";
5
+ import "../chunk-HMLY7DHA.js";
6
+ export {
7
+ MCPClientManager,
8
+ getNamespacedData
9
+ };
10
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,41 @@
1
+ import { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js';
2
+ import { OAuthClientMetadata, OAuthClientInformation, OAuthClientInformationFull, OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';
3
+
4
+ interface AgentsOAuthProvider extends OAuthClientProvider {
5
+ authUrl: string | undefined;
6
+ clientId: string | undefined;
7
+ serverId: string | undefined;
8
+ }
9
+ declare class DurableObjectOAuthClientProvider implements AgentsOAuthProvider {
10
+ storage: DurableObjectStorage;
11
+ clientName: string;
12
+ baseRedirectUrl: string;
13
+ private authUrl_;
14
+ private serverId_;
15
+ private clientId_;
16
+ constructor(storage: DurableObjectStorage, clientName: string, baseRedirectUrl: string);
17
+ get clientMetadata(): OAuthClientMetadata;
18
+ get redirectUrl(): string;
19
+ get clientId(): string;
20
+ set clientId(clientId_: string);
21
+ get serverId(): string;
22
+ set serverId(serverId_: string);
23
+ keyPrefix(clientId: string): string;
24
+ clientInfoKey(clientId: string): string;
25
+ clientInformation(): Promise<OAuthClientInformation | undefined>;
26
+ saveClientInformation(clientInformation: OAuthClientInformationFull): Promise<void>;
27
+ tokenKey(clientId: string): string;
28
+ tokens(): Promise<OAuthTokens | undefined>;
29
+ saveTokens(tokens: OAuthTokens): Promise<void>;
30
+ get authUrl(): string | undefined;
31
+ /**
32
+ * Because this operates on the server side (but we need browser auth), we send this url back to the user
33
+ * and require user interact to initiate the redirect flow
34
+ */
35
+ redirectToAuthorization(authUrl: URL): Promise<void>;
36
+ codeVerifierKey(clientId: string): string;
37
+ saveCodeVerifier(verifier: string): Promise<void>;
38
+ codeVerifier(): Promise<string>;
39
+ }
40
+
41
+ export { type AgentsOAuthProvider, DurableObjectOAuthClientProvider };
@@ -0,0 +1,107 @@
1
+ import "../chunk-HMLY7DHA.js";
2
+
3
+ // src/mcp/do-oauth-client-provider.ts
4
+ var DurableObjectOAuthClientProvider = class {
5
+ constructor(storage, clientName, baseRedirectUrl) {
6
+ this.storage = storage;
7
+ this.clientName = clientName;
8
+ this.baseRedirectUrl = baseRedirectUrl;
9
+ }
10
+ get clientMetadata() {
11
+ return {
12
+ redirect_uris: [this.redirectUrl],
13
+ token_endpoint_auth_method: "none",
14
+ grant_types: ["authorization_code", "refresh_token"],
15
+ response_types: ["code"],
16
+ client_name: this.clientName,
17
+ client_uri: "example.com"
18
+ };
19
+ }
20
+ get redirectUrl() {
21
+ return `${this.baseRedirectUrl}/${this.serverId}`;
22
+ }
23
+ get clientId() {
24
+ if (!this.clientId_) {
25
+ throw new Error("Trying to access clientId before it was set");
26
+ }
27
+ return this.clientId_;
28
+ }
29
+ set clientId(clientId_) {
30
+ this.clientId_ = clientId_;
31
+ }
32
+ get serverId() {
33
+ if (!this.serverId_) {
34
+ throw new Error("Trying to access serverId before it was set");
35
+ }
36
+ return this.serverId_;
37
+ }
38
+ set serverId(serverId_) {
39
+ this.serverId_ = serverId_;
40
+ }
41
+ keyPrefix(clientId) {
42
+ return `/${this.clientName}/${this.serverId}/${clientId}`;
43
+ }
44
+ clientInfoKey(clientId) {
45
+ return `${this.keyPrefix(clientId)}/client_info/`;
46
+ }
47
+ async clientInformation() {
48
+ if (!this.clientId_) {
49
+ return void 0;
50
+ }
51
+ return await this.storage.get(
52
+ this.clientInfoKey(this.clientId)
53
+ ) ?? void 0;
54
+ }
55
+ async saveClientInformation(clientInformation) {
56
+ await this.storage.put(
57
+ this.clientInfoKey(clientInformation.client_id),
58
+ clientInformation
59
+ );
60
+ this.clientId = clientInformation.client_id;
61
+ }
62
+ tokenKey(clientId) {
63
+ return `${this.keyPrefix(clientId)}/token`;
64
+ }
65
+ async tokens() {
66
+ if (!this.clientId_) {
67
+ return void 0;
68
+ }
69
+ return await this.storage.get(this.tokenKey(this.clientId)) ?? void 0;
70
+ }
71
+ async saveTokens(tokens) {
72
+ await this.storage.put(this.tokenKey(this.clientId), tokens);
73
+ }
74
+ get authUrl() {
75
+ return this.authUrl_;
76
+ }
77
+ /**
78
+ * Because this operates on the server side (but we need browser auth), we send this url back to the user
79
+ * and require user interact to initiate the redirect flow
80
+ */
81
+ async redirectToAuthorization(authUrl) {
82
+ const client_id = authUrl.searchParams.get("client_id");
83
+ if (client_id) {
84
+ authUrl.searchParams.append("state", client_id);
85
+ }
86
+ this.authUrl_ = authUrl.toString();
87
+ }
88
+ codeVerifierKey(clientId) {
89
+ return `${this.keyPrefix(clientId)}/code_verifier`;
90
+ }
91
+ async saveCodeVerifier(verifier) {
92
+ await this.storage.put(this.codeVerifierKey(this.clientId), verifier);
93
+ }
94
+ async codeVerifier() {
95
+ const codeVerifier = await this.storage.get(
96
+ this.codeVerifierKey(this.clientId)
97
+ );
98
+ if (!codeVerifier) {
99
+ throw new Error("No code verifier found");
100
+ }
101
+ return codeVerifier;
102
+ }
103
+ };
104
+ export {
105
+ DurableObjectOAuthClientProvider
106
+ };
107
+ //# sourceMappingURL=do-oauth-client-provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/mcp/do-oauth-client-provider.ts"],"sourcesContent":["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\n// This allows us to track authentication for a specific server and associated dynamic client registration\nexport interface AgentsOAuthProvider extends OAuthClientProvider {\n authUrl: string | undefined;\n clientId: string | undefined;\n serverId: string | undefined;\n}\n\nexport class DurableObjectOAuthClientProvider implements AgentsOAuthProvider {\n private authUrl_: string | undefined;\n private serverId_: string | undefined;\n private clientId_: string | undefined;\n\n constructor(\n public storage: DurableObjectStorage,\n public clientName: string,\n public baseRedirectUrl: 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 redirectUrl() {\n return `${this.baseRedirectUrl}/${this.serverId}`;\n }\n\n get clientId() {\n if (!this.clientId_) {\n throw new Error(\"Trying to access clientId before it was set\");\n }\n return this.clientId_;\n }\n\n set clientId(clientId_: string) {\n this.clientId_ = clientId_;\n }\n\n get serverId() {\n if (!this.serverId_) {\n throw new Error(\"Trying to access serverId before it was set\");\n }\n return this.serverId_;\n }\n\n set serverId(serverId_: string) {\n this.serverId_ = serverId_;\n }\n\n keyPrefix(clientId: string) {\n return `/${this.clientName}/${this.serverId}/${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"],"mappings":";;;AAgBO,IAAM,mCAAN,MAAsE;AAAA,EAK3E,YACS,SACA,YACA,iBACP;AAHO;AACA;AACA;AAAA,EACN;AAAA,EAEH,IAAI,iBAAsC;AACxC,WAAO;AAAA,MACL,eAAe,CAAC,KAAK,WAAW;AAAA,MAChC,4BAA4B;AAAA,MAC5B,aAAa,CAAC,sBAAsB,eAAe;AAAA,MACnD,gBAAgB,CAAC,MAAM;AAAA,MACvB,aAAa,KAAK;AAAA,MAClB,YAAY;AAAA,IACd;AAAA,EACF;AAAA,EAEA,IAAI,cAAc;AAChB,WAAO,GAAG,KAAK,eAAe,IAAI,KAAK,QAAQ;AAAA,EACjD;AAAA,EAEA,IAAI,WAAW;AACb,QAAI,CAAC,KAAK,WAAW;AACnB,YAAM,IAAI,MAAM,6CAA6C;AAAA,IAC/D;AACA,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,IAAI,SAAS,WAAmB;AAC9B,SAAK,YAAY;AAAA,EACnB;AAAA,EAEA,IAAI,WAAW;AACb,QAAI,CAAC,KAAK,WAAW;AACnB,YAAM,IAAI,MAAM,6CAA6C;AAAA,IAC/D;AACA,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,IAAI,SAAS,WAAmB;AAC9B,SAAK,YAAY;AAAA,EACnB;AAAA,EAEA,UAAU,UAAkB;AAC1B,WAAO,IAAI,KAAK,UAAU,IAAI,KAAK,QAAQ,IAAI,QAAQ;AAAA,EACzD;AAAA,EAEA,cAAc,UAAkB;AAC9B,WAAO,GAAG,KAAK,UAAU,QAAQ,CAAC;AAAA,EACpC;AAAA,EAEA,MAAM,oBAAiE;AACrE,QAAI,CAAC,KAAK,WAAW;AACnB,aAAO;AAAA,IACT;AACA,WACG,MAAM,KAAK,QAAQ;AAAA,MAClB,KAAK,cAAc,KAAK,QAAQ;AAAA,IAClC,KAAM;AAAA,EAEV;AAAA,EAEA,MAAM,sBACJ,mBACe;AACf,UAAM,KAAK,QAAQ;AAAA,MACjB,KAAK,cAAc,kBAAkB,SAAS;AAAA,MAC9C;AAAA,IACF;AACA,SAAK,WAAW,kBAAkB;AAAA,EACpC;AAAA,EAEA,SAAS,UAAkB;AACzB,WAAO,GAAG,KAAK,UAAU,QAAQ,CAAC;AAAA,EACpC;AAAA,EAEA,MAAM,SAA2C;AAC/C,QAAI,CAAC,KAAK,WAAW;AACnB,aAAO;AAAA,IACT;AACA,WACG,MAAM,KAAK,QAAQ,IAAiB,KAAK,SAAS,KAAK,QAAQ,CAAC,KACjE;AAAA,EAEJ;AAAA,EAEA,MAAM,WAAW,QAAoC;AACnD,UAAM,KAAK,QAAQ,IAAI,KAAK,SAAS,KAAK,QAAQ,GAAG,MAAM;AAAA,EAC7D;AAAA,EAEA,IAAI,UAAU;AACZ,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,wBAAwB,SAA6B;AAGzD,UAAM,YAAY,QAAQ,aAAa,IAAI,WAAW;AACtD,QAAI,WAAW;AACb,cAAQ,aAAa,OAAO,SAAS,SAAS;AAAA,IAChD;AACA,SAAK,WAAW,QAAQ,SAAS;AAAA,EACnC;AAAA,EAEA,gBAAgB,UAAkB;AAChC,WAAO,GAAG,KAAK,UAAU,QAAQ,CAAC;AAAA,EACpC;AAAA,EAEA,MAAM,iBAAiB,UAAiC;AACtD,UAAM,KAAK,QAAQ,IAAI,KAAK,gBAAgB,KAAK,QAAQ,GAAG,QAAQ;AAAA,EACtE;AAAA,EAEA,MAAM,eAAgC;AACpC,UAAM,eAAe,MAAM,KAAK,QAAQ;AAAA,MACtC,KAAK,gBAAgB,KAAK,QAAQ;AAAA,IACpC;AACA,QAAI,CAAC,cAAc;AACjB,YAAM,IAAI,MAAM,wBAAwB;AAAA,IAC1C;AACA,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -1,6 +1,17 @@
1
+ import { MCPClientManager } from './client.js';
1
2
  import { DurableObject } from 'cloudflare:workers';
3
+ import { Connection, WSMessage } from 'partyserver';
2
4
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
- import { Connection } from 'partyserver';
5
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
6
+ import 'zod';
7
+ import '@modelcontextprotocol/sdk/types.js';
8
+ import '@modelcontextprotocol/sdk/client/index.js';
9
+ import '@modelcontextprotocol/sdk/client/sse.js';
10
+ import './do-oauth-client-provider.js';
11
+ import '@modelcontextprotocol/sdk/client/auth.js';
12
+ import '@modelcontextprotocol/sdk/shared/auth.js';
13
+ import '@modelcontextprotocol/sdk/shared/protocol.js';
14
+ import 'ai';
4
15
 
5
16
  interface CORSOptions {
6
17
  origin?: string;
@@ -8,8 +19,10 @@ interface CORSOptions {
8
19
  headers?: string;
9
20
  maxAge?: number;
10
21
  }
22
+ type MaybePromise<T> = T | Promise<T>;
11
23
  declare abstract class McpAgent<Env = unknown, State = unknown, Props extends Record<string, unknown> = Record<string, unknown>> extends DurableObject<Env> {
12
24
  #private;
25
+ get mcp(): MCPClientManager;
13
26
  protected constructor(ctx: DurableObjectState, env: Env);
14
27
  /**
15
28
  * Agents API allowlist
@@ -19,22 +32,42 @@ declare abstract class McpAgent<Env = unknown, State = unknown, Props extends Re
19
32
  sql<T = Record<string, string | number | boolean | null>>(strings: TemplateStringsArray, ...values: (string | number | boolean | null)[]): T[];
20
33
  setState(state: State): void;
21
34
  onStateUpdate(state: State | undefined, source: Connection | "server"): void;
35
+ onStart(): Promise<void>;
22
36
  /**
23
37
  * McpAgent API
24
38
  */
25
- abstract server: McpServer;
26
- private transport;
39
+ abstract server: MaybePromise<McpServer | Server>;
27
40
  props: Props;
28
41
  initRun: boolean;
29
42
  abstract init(): Promise<void>;
30
43
  _init(props: Props): Promise<void>;
31
- onSSE(path: string): Promise<Response>;
32
- onMCPMessage(request: Request): Promise<Response>;
44
+ setInitialized(): Promise<void>;
45
+ isInitialized(): Promise<boolean>;
46
+ fetch(request: Request): Promise<Response>;
47
+ getWebSocket(): WebSocket | null;
48
+ getWebSocketForResponseID(id: string): WebSocket | null;
49
+ onMessage(connection: Connection, event: WSMessage): Promise<void>;
50
+ onSSEMcpMessage(sessionId: string, request: Request): Promise<Error | null>;
51
+ webSocketMessage(ws: WebSocket, event: ArrayBuffer | string): Promise<void>;
52
+ webSocketError(ws: WebSocket, error: unknown): Promise<void>;
53
+ webSocketClose(ws: WebSocket, code: number, reason: string, wasClean: boolean): Promise<void>;
33
54
  static mount(path: string, { binding, corsOptions, }?: {
34
55
  binding?: string;
35
56
  corsOptions?: CORSOptions;
36
57
  }): {
37
- fetch: (request: Request, env: Record<string, DurableObjectNamespace<McpAgent>>, ctx: ExecutionContext) => Promise<Response>;
58
+ fetch<Env>(this: void, request: Request, env: Env, ctx: ExecutionContext): Promise<Response>;
59
+ };
60
+ static serveSSE(path: string, { binding, corsOptions, }?: {
61
+ binding?: string;
62
+ corsOptions?: CORSOptions;
63
+ }): {
64
+ fetch<Env>(this: void, request: Request, env: Env, ctx: ExecutionContext): Promise<Response>;
65
+ };
66
+ static serve(path: string, { binding, corsOptions, }?: {
67
+ binding?: string;
68
+ corsOptions?: CORSOptions;
69
+ }): {
70
+ fetch<Env>(this: void, request: Request, env: Env, ctx: ExecutionContext): Promise<Response>;
38
71
  };
39
72
  }
40
73