agents 0.0.0-ee727ca → 0.0.0-eeb70e2

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 (43) hide show
  1. package/README.md +2 -6
  2. package/dist/ai-chat-agent.d.ts +49 -3
  3. package/dist/ai-chat-agent.js +129 -66
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-react.d.ts +13 -0
  6. package/dist/ai-react.js +38 -24
  7. package/dist/ai-react.js.map +1 -1
  8. package/dist/ai-types.d.ts +5 -0
  9. package/dist/chunk-BZXOAZUX.js +106 -0
  10. package/dist/chunk-BZXOAZUX.js.map +1 -0
  11. package/dist/chunk-OYJXQRRH.js +465 -0
  12. package/dist/chunk-OYJXQRRH.js.map +1 -0
  13. package/dist/chunk-P3RZJ72N.js +783 -0
  14. package/dist/chunk-P3RZJ72N.js.map +1 -0
  15. package/dist/chunk-VCSB47AK.js +116 -0
  16. package/dist/chunk-VCSB47AK.js.map +1 -0
  17. package/dist/client.d.ts +15 -1
  18. package/dist/client.js +6 -133
  19. package/dist/client.js.map +1 -1
  20. package/dist/index.d.ts +122 -13
  21. package/dist/index.js +6 -4
  22. package/dist/mcp/client.d.ts +783 -0
  23. package/dist/mcp/client.js +9 -0
  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/do-oauth-client-provider.js.map +1 -0
  27. package/dist/mcp/index.d.ts +84 -0
  28. package/dist/mcp/index.js +782 -0
  29. package/dist/mcp/index.js.map +1 -0
  30. package/dist/react.d.ts +85 -5
  31. package/dist/react.js +48 -29
  32. package/dist/react.js.map +1 -1
  33. package/dist/schedule.js +0 -2
  34. package/dist/schedule.js.map +1 -1
  35. package/dist/serializable.d.ts +32 -0
  36. package/dist/serializable.js +1 -0
  37. package/dist/serializable.js.map +1 -0
  38. package/package.json +41 -5
  39. package/src/index.ts +490 -126
  40. package/dist/chunk-HMLY7DHA.js +0 -16
  41. package/dist/chunk-X6BBKLSC.js +0 -568
  42. package/dist/chunk-X6BBKLSC.js.map +0 -1
  43. /package/dist/{chunk-HMLY7DHA.js.map → mcp/client.js.map} +0 -0
@@ -0,0 +1,106 @@
1
+ // src/mcp/do-oauth-client-provider.ts
2
+ var DurableObjectOAuthClientProvider = class {
3
+ constructor(storage, clientName, baseRedirectUrl) {
4
+ this.storage = storage;
5
+ this.clientName = clientName;
6
+ this.baseRedirectUrl = baseRedirectUrl;
7
+ }
8
+ get clientMetadata() {
9
+ return {
10
+ redirect_uris: [this.redirectUrl],
11
+ token_endpoint_auth_method: "none",
12
+ grant_types: ["authorization_code", "refresh_token"],
13
+ response_types: ["code"],
14
+ client_name: this.clientName,
15
+ client_uri: "example.com"
16
+ };
17
+ }
18
+ get redirectUrl() {
19
+ return `${this.baseRedirectUrl}/${this.serverId}`;
20
+ }
21
+ get clientId() {
22
+ if (!this._clientId_) {
23
+ throw new Error("Trying to access clientId before it was set");
24
+ }
25
+ return this._clientId_;
26
+ }
27
+ set clientId(clientId_) {
28
+ this._clientId_ = clientId_;
29
+ }
30
+ get serverId() {
31
+ if (!this._serverId_) {
32
+ throw new Error("Trying to access serverId before it was set");
33
+ }
34
+ return this._serverId_;
35
+ }
36
+ set serverId(serverId_) {
37
+ this._serverId_ = serverId_;
38
+ }
39
+ keyPrefix(clientId) {
40
+ return `/${this.clientName}/${this.serverId}/${clientId}`;
41
+ }
42
+ clientInfoKey(clientId) {
43
+ return `${this.keyPrefix(clientId)}/client_info/`;
44
+ }
45
+ async clientInformation() {
46
+ if (!this._clientId_) {
47
+ return void 0;
48
+ }
49
+ return await this.storage.get(
50
+ this.clientInfoKey(this.clientId)
51
+ ) ?? void 0;
52
+ }
53
+ async saveClientInformation(clientInformation) {
54
+ await this.storage.put(
55
+ this.clientInfoKey(clientInformation.client_id),
56
+ clientInformation
57
+ );
58
+ this.clientId = clientInformation.client_id;
59
+ }
60
+ tokenKey(clientId) {
61
+ return `${this.keyPrefix(clientId)}/token`;
62
+ }
63
+ async tokens() {
64
+ if (!this._clientId_) {
65
+ return void 0;
66
+ }
67
+ return await this.storage.get(this.tokenKey(this.clientId)) ?? void 0;
68
+ }
69
+ async saveTokens(tokens) {
70
+ await this.storage.put(this.tokenKey(this.clientId), tokens);
71
+ }
72
+ get authUrl() {
73
+ return this._authUrl_;
74
+ }
75
+ /**
76
+ * Because this operates on the server side (but we need browser auth), we send this url back to the user
77
+ * and require user interact to initiate the redirect flow
78
+ */
79
+ async redirectToAuthorization(authUrl) {
80
+ const client_id = authUrl.searchParams.get("client_id");
81
+ if (client_id) {
82
+ authUrl.searchParams.append("state", client_id);
83
+ }
84
+ this._authUrl_ = authUrl.toString();
85
+ }
86
+ codeVerifierKey(clientId) {
87
+ return `${this.keyPrefix(clientId)}/code_verifier`;
88
+ }
89
+ async saveCodeVerifier(verifier) {
90
+ await this.storage.put(this.codeVerifierKey(this.clientId), verifier);
91
+ }
92
+ async codeVerifier() {
93
+ const codeVerifier = await this.storage.get(
94
+ this.codeVerifierKey(this.clientId)
95
+ );
96
+ if (!codeVerifier) {
97
+ throw new Error("No code verifier found");
98
+ }
99
+ return codeVerifier;
100
+ }
101
+ };
102
+
103
+ export {
104
+ DurableObjectOAuthClientProvider
105
+ };
106
+ //# sourceMappingURL=chunk-BZXOAZUX.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,YAAY;AACpB,YAAM,IAAI,MAAM,6CAA6C;AAAA,IAC/D;AACA,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,IAAI,SAAS,WAAmB;AAC9B,SAAK,aAAa;AAAA,EACpB;AAAA,EAEA,IAAI,WAAW;AACb,QAAI,CAAC,KAAK,YAAY;A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A,SAAK,YAAY,QAAQ,SAAS;AAAA,EACpC;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":[]}
@@ -0,0 +1,465 @@
1
+ // src/mcp/sse-edge.ts
2
+ import {
3
+ SSEClientTransport
4
+ } from "@modelcontextprotocol/sdk/client/sse.js";
5
+ var SSEEdgeClientTransport = class extends SSEClientTransport {
6
+ /**
7
+ * Creates a new EdgeSSEClientTransport, which overrides fetch to be compatible with the CF workers environment
8
+ */
9
+ constructor(url, options) {
10
+ const fetchOverride = async (fetchUrl, fetchInit = {}) => {
11
+ const headers = await this.authHeaders();
12
+ const workerOptions = {
13
+ ...fetchInit,
14
+ headers: {
15
+ ...options.requestInit?.headers,
16
+ ...fetchInit?.headers,
17
+ ...headers
18
+ }
19
+ };
20
+ delete workerOptions.mode;
21
+ return options.eventSourceInit?.fetch?.(
22
+ fetchUrl,
23
+ // @ts-expect-error Expects FetchLikeInit from EventSource but is compatible with RequestInit
24
+ workerOptions
25
+ ) || fetch(fetchUrl, workerOptions);
26
+ };
27
+ super(url, {
28
+ ...options,
29
+ eventSourceInit: {
30
+ ...options.eventSourceInit,
31
+ fetch: fetchOverride
32
+ }
33
+ });
34
+ this.authProvider = options.authProvider;
35
+ }
36
+ async authHeaders() {
37
+ if (this.authProvider) {
38
+ const tokens = await this.authProvider.tokens();
39
+ if (tokens) {
40
+ return {
41
+ Authorization: `Bearer ${tokens.access_token}`
42
+ };
43
+ }
44
+ }
45
+ }
46
+ };
47
+
48
+ // src/mcp/client-connection.ts
49
+ import {
50
+ ToolListChangedNotificationSchema,
51
+ ResourceListChangedNotificationSchema,
52
+ PromptListChangedNotificationSchema
53
+ } from "@modelcontextprotocol/sdk/types.js";
54
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
55
+ var MCPClientConnection = class {
56
+ constructor(url, info, options = { transport: {}, client: {} }) {
57
+ this.url = url;
58
+ this.options = options;
59
+ this.connectionState = "connecting";
60
+ this.tools = [];
61
+ this.prompts = [];
62
+ this.resources = [];
63
+ this.resourceTemplates = [];
64
+ this.client = new Client(info, options.client);
65
+ }
66
+ /**
67
+ * Initialize a client connection
68
+ *
69
+ * @param code Optional OAuth code to initialize the connection with if auth hasn't been initialized
70
+ * @returns
71
+ */
72
+ async init(code) {
73
+ try {
74
+ const transport = new SSEEdgeClientTransport(
75
+ this.url,
76
+ this.options.transport
77
+ );
78
+ if (code) {
79
+ await transport.finishAuth(code);
80
+ }
81
+ await this.client.connect(transport);
82
+ } catch (e) {
83
+ if (e.toString().includes("Unauthorized")) {
84
+ this.connectionState = "authenticating";
85
+ return;
86
+ }
87
+ this.connectionState = "failed";
88
+ throw e;
89
+ }
90
+ this.connectionState = "discovering";
91
+ this.serverCapabilities = await this.client.getServerCapabilities();
92
+ if (!this.serverCapabilities) {
93
+ throw new Error("The MCP Server failed to return server capabilities");
94
+ }
95
+ const [instructions, tools, resources, prompts, resourceTemplates] = await Promise.all([
96
+ this.client.getInstructions(),
97
+ this.registerTools(),
98
+ this.registerResources(),
99
+ this.registerPrompts(),
100
+ this.registerResourceTemplates()
101
+ ]);
102
+ this.instructions = instructions;
103
+ this.tools = tools;
104
+ this.resources = resources;
105
+ this.prompts = prompts;
106
+ this.resourceTemplates = resourceTemplates;
107
+ this.connectionState = "ready";
108
+ }
109
+ /**
110
+ * Notification handler registration
111
+ */
112
+ async registerTools() {
113
+ if (!this.serverCapabilities || !this.serverCapabilities.tools) {
114
+ return [];
115
+ }
116
+ if (this.serverCapabilities.tools.listChanged) {
117
+ this.client.setNotificationHandler(
118
+ ToolListChangedNotificationSchema,
119
+ async (_notification) => {
120
+ this.tools = await this.fetchTools();
121
+ }
122
+ );
123
+ }
124
+ return this.fetchTools();
125
+ }
126
+ async registerResources() {
127
+ if (!this.serverCapabilities || !this.serverCapabilities.resources) {
128
+ return [];
129
+ }
130
+ if (this.serverCapabilities.resources.listChanged) {
131
+ this.client.setNotificationHandler(
132
+ ResourceListChangedNotificationSchema,
133
+ async (_notification) => {
134
+ this.resources = await this.fetchResources();
135
+ }
136
+ );
137
+ }
138
+ return this.fetchResources();
139
+ }
140
+ async registerPrompts() {
141
+ if (!this.serverCapabilities || !this.serverCapabilities.prompts) {
142
+ return [];
143
+ }
144
+ if (this.serverCapabilities.prompts.listChanged) {
145
+ this.client.setNotificationHandler(
146
+ PromptListChangedNotificationSchema,
147
+ async (_notification) => {
148
+ this.prompts = await this.fetchPrompts();
149
+ }
150
+ );
151
+ }
152
+ return this.fetchPrompts();
153
+ }
154
+ async registerResourceTemplates() {
155
+ if (!this.serverCapabilities || !this.serverCapabilities.resources) {
156
+ return [];
157
+ }
158
+ return this.fetchResourceTemplates();
159
+ }
160
+ async fetchTools() {
161
+ let toolsAgg = [];
162
+ let toolsResult = { tools: [] };
163
+ do {
164
+ toolsResult = await this.client.listTools({
165
+ cursor: toolsResult.nextCursor
166
+ }).catch(capabilityErrorHandler({ tools: [] }, "tools/list"));
167
+ toolsAgg = toolsAgg.concat(toolsResult.tools);
168
+ } while (toolsResult.nextCursor);
169
+ return toolsAgg;
170
+ }
171
+ async fetchResources() {
172
+ let resourcesAgg = [];
173
+ let resourcesResult = { resources: [] };
174
+ do {
175
+ resourcesResult = await this.client.listResources({
176
+ cursor: resourcesResult.nextCursor
177
+ }).catch(capabilityErrorHandler({ resources: [] }, "resources/list"));
178
+ resourcesAgg = resourcesAgg.concat(resourcesResult.resources);
179
+ } while (resourcesResult.nextCursor);
180
+ return resourcesAgg;
181
+ }
182
+ async fetchPrompts() {
183
+ let promptsAgg = [];
184
+ let promptsResult = { prompts: [] };
185
+ do {
186
+ promptsResult = await this.client.listPrompts({
187
+ cursor: promptsResult.nextCursor
188
+ }).catch(capabilityErrorHandler({ prompts: [] }, "prompts/list"));
189
+ promptsAgg = promptsAgg.concat(promptsResult.prompts);
190
+ } while (promptsResult.nextCursor);
191
+ return promptsAgg;
192
+ }
193
+ async fetchResourceTemplates() {
194
+ let templatesAgg = [];
195
+ let templatesResult = {
196
+ resourceTemplates: []
197
+ };
198
+ do {
199
+ templatesResult = await this.client.listResourceTemplates({
200
+ cursor: templatesResult.nextCursor
201
+ }).catch(
202
+ capabilityErrorHandler(
203
+ { resourceTemplates: [] },
204
+ "resources/templates/list"
205
+ )
206
+ );
207
+ templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);
208
+ } while (templatesResult.nextCursor);
209
+ return templatesAgg;
210
+ }
211
+ };
212
+ function capabilityErrorHandler(empty, method) {
213
+ return (e) => {
214
+ if (e.code === -32601) {
215
+ console.error(
216
+ `The server advertised support for the capability ${method.split("/")[0]}, but returned "Method not found" for '${method}'.`
217
+ );
218
+ return empty;
219
+ }
220
+ throw e;
221
+ };
222
+ }
223
+
224
+ // src/mcp/client.ts
225
+ import { jsonSchema } from "ai";
226
+ import { nanoid } from "nanoid";
227
+ var MCPClientManager = class {
228
+ /**
229
+ * @param _name Name of the MCP client
230
+ * @param _version Version of the MCP Client
231
+ * @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider
232
+ */
233
+ constructor(_name, _version) {
234
+ this._name = _name;
235
+ this._version = _version;
236
+ this.mcpConnections = {};
237
+ this._callbackUrls = [];
238
+ }
239
+ /**
240
+ * Connect to and register an MCP server
241
+ *
242
+ * @param transportConfig Transport config
243
+ * @param clientConfig Client config
244
+ * @param capabilities Client capabilities (i.e. if the client supports roots/sampling)
245
+ */
246
+ async connect(url, options = {}) {
247
+ const id = options.reconnect?.id ?? nanoid(8);
248
+ if (!options.transport?.authProvider) {
249
+ console.warn(
250
+ "No authProvider provided in the transport options. This client will only support unauthenticated remote MCP Servers"
251
+ );
252
+ } else {
253
+ options.transport.authProvider.serverId = id;
254
+ if (options.reconnect?.oauthClientId) {
255
+ options.transport.authProvider.clientId = options.reconnect?.oauthClientId;
256
+ }
257
+ }
258
+ this.mcpConnections[id] = new MCPClientConnection(
259
+ new URL(url),
260
+ {
261
+ name: this._name,
262
+ version: this._version
263
+ },
264
+ {
265
+ transport: options.transport ?? {},
266
+ client: options.client ?? {}
267
+ }
268
+ );
269
+ await this.mcpConnections[id].init(options.reconnect?.oauthCode);
270
+ const authUrl = options.transport?.authProvider?.authUrl;
271
+ if (authUrl && options.transport?.authProvider?.redirectUrl) {
272
+ this._callbackUrls.push(
273
+ options.transport.authProvider.redirectUrl.toString()
274
+ );
275
+ return {
276
+ id,
277
+ authUrl,
278
+ clientId: options.transport?.authProvider?.clientId
279
+ };
280
+ }
281
+ return {
282
+ id
283
+ };
284
+ }
285
+ isCallbackRequest(req) {
286
+ return req.method === "GET" && !!this._callbackUrls.find((url) => {
287
+ return req.url.startsWith(url);
288
+ });
289
+ }
290
+ async handleCallbackRequest(req) {
291
+ const url = new URL(req.url);
292
+ const urlMatch = this._callbackUrls.find((url2) => {
293
+ return req.url.startsWith(url2);
294
+ });
295
+ if (!urlMatch) {
296
+ throw new Error(
297
+ `No callback URI match found for the request url: ${req.url}. Was the request matched with \`isCallbackRequest()\`?`
298
+ );
299
+ }
300
+ const code = url.searchParams.get("code");
301
+ const clientId = url.searchParams.get("state");
302
+ const urlParams = urlMatch.split("/");
303
+ const serverId = urlParams[urlParams.length - 1];
304
+ if (!code) {
305
+ throw new Error("Unauthorized: no code provided");
306
+ }
307
+ if (!clientId) {
308
+ throw new Error("Unauthorized: no state provided");
309
+ }
310
+ if (this.mcpConnections[serverId] === void 0) {
311
+ throw new Error(`Could not find serverId: ${serverId}`);
312
+ }
313
+ if (this.mcpConnections[serverId].connectionState !== "authenticating") {
314
+ throw new Error(
315
+ "Failed to authenticate: the client isn't in the `authenticating` state"
316
+ );
317
+ }
318
+ const conn = this.mcpConnections[serverId];
319
+ if (!conn.options.transport.authProvider) {
320
+ throw new Error(
321
+ "Trying to finalize authentication for a server connection without an authProvider"
322
+ );
323
+ }
324
+ conn.options.transport.authProvider.clientId = clientId;
325
+ conn.options.transport.authProvider.serverId = serverId;
326
+ const serverUrl = conn.url.toString();
327
+ await this.connect(serverUrl, {
328
+ reconnect: {
329
+ id: serverId,
330
+ oauthClientId: clientId,
331
+ oauthCode: code
332
+ },
333
+ ...conn.options
334
+ });
335
+ if (this.mcpConnections[serverId].connectionState === "authenticating") {
336
+ throw new Error("Failed to authenticate: client failed to initialize");
337
+ }
338
+ return { serverId };
339
+ }
340
+ /**
341
+ * @returns namespaced list of tools
342
+ */
343
+ listTools() {
344
+ return getNamespacedData(this.mcpConnections, "tools");
345
+ }
346
+ /**
347
+ * @returns a set of tools that you can use with the AI SDK
348
+ */
349
+ unstable_getAITools() {
350
+ return Object.fromEntries(
351
+ getNamespacedData(this.mcpConnections, "tools").map((tool) => {
352
+ return [
353
+ `${tool.serverId}_${tool.name}`,
354
+ {
355
+ parameters: jsonSchema(tool.inputSchema),
356
+ description: tool.description,
357
+ execute: async (args) => {
358
+ const result = await this.callTool({
359
+ name: tool.name,
360
+ arguments: args,
361
+ serverId: tool.serverId
362
+ });
363
+ if (result.isError) {
364
+ throw new Error(result.content[0].text);
365
+ }
366
+ return result;
367
+ }
368
+ }
369
+ ];
370
+ })
371
+ );
372
+ }
373
+ /**
374
+ * Closes all connections to MCP servers
375
+ */
376
+ async closeAllConnections() {
377
+ return Promise.all(
378
+ Object.values(this.mcpConnections).map(async (connection) => {
379
+ await connection.client.close();
380
+ })
381
+ );
382
+ }
383
+ /**
384
+ * Closes a connection to an MCP server
385
+ * @param id The id of the connection to close
386
+ */
387
+ async closeConnection(id) {
388
+ if (!this.mcpConnections[id]) {
389
+ throw new Error(`Connection with id "${id}" does not exist.`);
390
+ }
391
+ await this.mcpConnections[id].client.close();
392
+ delete this.mcpConnections[id];
393
+ }
394
+ /**
395
+ * @returns namespaced list of prompts
396
+ */
397
+ listPrompts() {
398
+ return getNamespacedData(this.mcpConnections, "prompts");
399
+ }
400
+ /**
401
+ * @returns namespaced list of tools
402
+ */
403
+ listResources() {
404
+ return getNamespacedData(this.mcpConnections, "resources");
405
+ }
406
+ /**
407
+ * @returns namespaced list of resource templates
408
+ */
409
+ listResourceTemplates() {
410
+ return getNamespacedData(this.mcpConnections, "resourceTemplates");
411
+ }
412
+ /**
413
+ * Namespaced version of callTool
414
+ */
415
+ callTool(params, resultSchema, options) {
416
+ const unqualifiedName = params.name.replace(`${params.serverId}.`, "");
417
+ return this.mcpConnections[params.serverId].client.callTool(
418
+ {
419
+ ...params,
420
+ name: unqualifiedName
421
+ },
422
+ resultSchema,
423
+ options
424
+ );
425
+ }
426
+ /**
427
+ * Namespaced version of readResource
428
+ */
429
+ readResource(params, options) {
430
+ return this.mcpConnections[params.serverId].client.readResource(
431
+ params,
432
+ options
433
+ );
434
+ }
435
+ /**
436
+ * Namespaced version of getPrompt
437
+ */
438
+ getPrompt(params, options) {
439
+ return this.mcpConnections[params.serverId].client.getPrompt(
440
+ params,
441
+ options
442
+ );
443
+ }
444
+ };
445
+ function getNamespacedData(mcpClients, type) {
446
+ const sets = Object.entries(mcpClients).map(([name, conn]) => {
447
+ return { name, data: conn[type] };
448
+ });
449
+ const namespacedData = sets.flatMap(({ name: serverId, data }) => {
450
+ return data.map((item) => {
451
+ return {
452
+ ...item,
453
+ // we add a serverId so we can easily pull it out and send the tool call to the right server
454
+ serverId
455
+ };
456
+ });
457
+ });
458
+ return namespacedData;
459
+ }
460
+
461
+ export {
462
+ MCPClientManager,
463
+ getNamespacedData
464
+ };
465
+ //# sourceMappingURL=chunk-OYJXQRRH.js.map
@@ -0,0 +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\";\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 ...options.requestInit?.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 (\n (options.eventSourceInit?.fetch?.(\n fetchUrl as URL | string,\n // @ts-expect-error Expects FetchLikeInit from EventSource but is compatible with RequestInit\n workerOptions\n ) as Promise<Response>) || fetch(fetchUrl, workerOptions)\n );\n };\n\n super(url, {\n ...options,\n eventSourceInit: {\n ...options.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 type Notification,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { AgentsOAuthProvider } from \"./do-oauth-client-provider\";\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 info: ConstructorParameters<typeof Client>[0],\n public options: {\n transport: SSEClientTransportOptions & {\n authProvider?: AgentsOAuthProvider;\n };\n client: ConstructorParameters<typeof Client>[1];\n } = { transport: {}, client: {} }\n ) {\n this.client = new Client(info, options.client);\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) {\n try {\n const transport = new SSEEdgeClientTransport(\n this.url,\n this.options.transport\n );\n\n if (code) {\n await transport.finishAuth(code);\n }\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\n .listTools({\n cursor: toolsResult.nextCursor,\n })\n .catch(capabilityErrorHandler({ tools: [] }, \"tools/list\"));\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\n .listResources({\n cursor: resourcesResult.nextCursor,\n })\n .catch(capabilityErrorHandler({ resources: [] }, \"resources/list\"));\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\n .listPrompts({\n cursor: promptsResult.nextCursor,\n })\n .catch(capabilityErrorHandler({ prompts: [] }, \"prompts/list\"));\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\n .listResourceTemplates({\n cursor: templatesResult.nextCursor,\n })\n .catch(\n capabilityErrorHandler(\n { resourceTemplates: [] },\n \"resources/templates/list\"\n )\n );\n templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);\n } while (templatesResult.nextCursor);\n return templatesAgg;\n }\n}\n\nfunction capabilityErrorHandler<T>(empty: T, method: string) {\n return (e: { code: number }) => {\n // server is badly behaved and returning invalid capabilities. This commonly occurs for resource templates\n if (e.code === -32601) {\n console.error(\n `The server advertised support for the capability ${method.split(\"/\")[0]}, but returned \"Method not found\" for '${method}'.`\n );\n return empty;\n }\n throw e;\n };\n}\n","import { MCPClientConnection } from \"./client-connection\";\n\nimport type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { RequestOptions } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type {\n CallToolRequest,\n CallToolResultSchema,\n CompatibilityCallToolResultSchema,\n GetPromptRequest,\n Prompt,\n ReadResourceRequest,\n Resource,\n ResourceTemplate,\n Tool,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { jsonSchema, type ToolSet } from \"ai\";\nimport { nanoid } from \"nanoid\";\nimport type { AgentsOAuthProvider } 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 private _callbackUrls: string[] = [];\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 ) {}\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 options: {\n // Allows you to reconnect to a server (in the case of an auth reconnect)\n reconnect?: {\n // server id\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 } = {}\n ): Promise<{\n id: string;\n authUrl?: string;\n clientId?: string;\n }> {\n const id = options.reconnect?.id ?? nanoid(8);\n\n if (!options.transport?.authProvider) {\n console.warn(\n \"No authProvider provided in the transport options. This client will only support unauthenticated remote MCP Servers\"\n );\n } else {\n options.transport.authProvider.serverId = id;\n // reconnect with auth\n if (options.reconnect?.oauthClientId) {\n options.transport.authProvider.clientId =\n options.reconnect?.oauthClientId;\n }\n }\n\n this.mcpConnections[id] = new MCPClientConnection(\n new URL(url),\n {\n name: this._name,\n version: this._version,\n },\n {\n transport: options.transport ?? {},\n client: options.client ?? {},\n }\n );\n\n await this.mcpConnections[id].init(options.reconnect?.oauthCode);\n\n const authUrl = options.transport?.authProvider?.authUrl;\n if (authUrl && options.transport?.authProvider?.redirectUrl) {\n this._callbackUrls.push(\n options.transport.authProvider.redirectUrl.toString()\n );\n return {\n id,\n authUrl,\n clientId: options.transport?.authProvider?.clientId,\n };\n }\n\n return {\n id,\n };\n }\n\n isCallbackRequest(req: Request): boolean {\n return (\n req.method === \"GET\" &&\n !!this._callbackUrls.find((url) => {\n return req.url.startsWith(url);\n })\n );\n }\n\n async handleCallbackRequest(req: Request) {\n const url = new URL(req.url);\n const urlMatch = this._callbackUrls.find((url) => {\n return req.url.startsWith(url);\n });\n if (!urlMatch) {\n throw new Error(\n `No callback URI match found for the request url: ${req.url}. Was the request matched with \\`isCallbackRequest()\\`?`\n );\n }\n const code = url.searchParams.get(\"code\");\n const clientId = url.searchParams.get(\"state\");\n const urlParams = urlMatch.split(\"/\");\n const serverId = urlParams[urlParams.length - 1];\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 const conn = this.mcpConnections[serverId];\n if (!conn.options.transport.authProvider) {\n throw new Error(\n \"Trying to finalize authentication for a server connection without an authProvider\"\n );\n }\n\n conn.options.transport.authProvider.clientId = clientId;\n conn.options.transport.authProvider.serverId = serverId;\n\n // reconnect to server with authorization\n const serverUrl = conn.url.toString();\n await this.connect(serverUrl, {\n reconnect: {\n id: serverId,\n oauthClientId: clientId,\n oauthCode: code,\n },\n ...conn.options,\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 a set of tools that you can use with the AI SDK\n */\n unstable_getAITools(): ToolSet {\n return Object.fromEntries(\n getNamespacedData(this.mcpConnections, \"tools\").map((tool) => {\n return [\n `${tool.serverId}_${tool.name}`,\n {\n parameters: jsonSchema(tool.inputSchema),\n description: tool.description,\n execute: async (args) => {\n const result = await this.callTool({\n name: tool.name,\n arguments: args,\n serverId: tool.serverId,\n });\n if (result.isError) {\n // @ts-expect-error TODO we should fix this\n throw new Error(result.content[0].text);\n }\n return result;\n },\n },\n ];\n })\n );\n }\n\n /**\n * Closes all connections to MCP servers\n */\n async closeAllConnections() {\n return Promise.all(\n Object.values(this.mcpConnections).map(async (connection) => {\n await connection.client.close();\n })\n );\n }\n\n /**\n * Closes a connection to an MCP server\n * @param id The id of the connection to close\n */\n async closeConnection(id: string) {\n if (!this.mcpConnections[id]) {\n throw new Error(`Connection with id \"${id}\" does not exist.`);\n }\n await this.mcpConnections[id].client.close();\n delete this.mcpConnections[id];\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,GAAG;AAAA,QACH,SAAS;AAAA,UACP,GAAG,QAAQ,aAAa;AAAA,UACxB,GAAG,WAAW;AAAA,UACd,GAAG;AAAA,QACL;AAAA,MACF;AAIA,aAAO,cAAc;AAGrB,aACG,QAAQ,iBAAiB;AAAA,QACxB;AAAA;AAAA,QAEA;AAAA,MACF,KAA2B,MAAM,UAAU,aAAa;AAAA,IAE5D;AAEA,UAAM,KAAK;AAAA,MACT,GAAG;AAAA,MACH,iBAAiB;AAAA,QACf,GAAG,QAAQ;AAAA,QACX,OAAO;AAAA,MACT;AAAA,IACF,CAAC;AACD,SAAK,eAAe,QAAQ;AAAA,EAC9B;AAAA,EAEA,MAAM,cAAc;AAClB,QAAI,KAAK,cAAc;AACrB,YAAM,SAAS,MAAM,KAAK,aAAa,OAAO;AAC9C,UAAI,QAAQ;AACV,eAAO;AAAA,UACL,eAAe,UAAU,OAAO,YAAY;AAAA,QAC9C;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;;;AC3DA;AAAA,EACE;AAAA,EAKA;AAAA,EACA;AAAA,OAQK;AACP,SAAS,cAAc;AAIhB,IAAM,sBAAN,MAA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