agents 0.0.0-c3e8618 → 0.0.0-cebd0de
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.
- package/dist/ai-chat-agent.d.ts +28 -23
- package/dist/ai-chat-agent.js +168 -0
- package/dist/ai-chat-agent.js.map +1 -0
- package/dist/ai-react.d.ts +72 -44
- package/dist/ai-react.js +196 -0
- package/dist/ai-react.js.map +1 -0
- package/dist/ai-types.d.ts +60 -40
- package/dist/ai-types.js +1 -0
- package/dist/ai-types.js.map +1 -0
- package/dist/chunk-HMLY7DHA.js +16 -0
- package/dist/chunk-HMLY7DHA.js.map +1 -0
- package/dist/chunk-YMUU7QHV.js +595 -0
- package/dist/chunk-YMUU7QHV.js.map +1 -0
- package/dist/client.d.ts +57 -37
- package/dist/client.js +131 -0
- package/dist/client.js.map +1 -0
- package/dist/index.d.ts +223 -174
- package/dist/index.js +22 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp/client.d.ts +59 -20
- package/dist/mcp/client.js +471 -0
- package/dist/mcp/client.js.map +1 -0
- package/dist/mcp/index.d.ts +8 -5
- package/dist/mcp/index.js +340 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/react.d.ts +24 -15
- package/dist/react.js +104 -0
- package/dist/react.js.map +1 -0
- package/dist/schedule.d.ts +30 -20
- package/dist/schedule.js +73 -0
- package/dist/schedule.js.map +1 -0
- package/package.json +7 -4
|
@@ -0,0 +1,471 @@
|
|
|
1
|
+
import "../chunk-HMLY7DHA.js";
|
|
2
|
+
|
|
3
|
+
// src/mcp/sse-edge.ts
|
|
4
|
+
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
|
+
}
|
|
467
|
+
export {
|
|
468
|
+
MCPClientManager,
|
|
469
|
+
getNamespacedData
|
|
470
|
+
};
|
|
471
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/mcp/sse-edge.ts","../../src/mcp/client-connection.ts","../../src/mcp/do-oauth-client-provider.ts","../../src/mcp/client.ts"],"sourcesContent":["import {\n SSEClientTransport,\n type SSEClientTransportOptions,\n} from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\n\nexport class SSEEdgeClientTransport extends SSEClientTransport {\n private authProvider: OAuthClientProvider | undefined;\n /**\n * Creates a new EdgeSSEClientTransport, which overrides fetch to be compatible with the CF workers environment\n */\n constructor(url: URL, options: SSEClientTransportOptions) {\n const fetchOverride: typeof fetch = async (\n fetchUrl: RequestInfo | URL,\n fetchInit: RequestInit = {}\n ) => {\n // add auth headers\n const headers = await this.authHeaders();\n const workerOptions = {\n ...fetchInit,\n headers: {\n ...fetchInit?.headers,\n ...headers,\n },\n };\n\n // Remove unsupported properties\n // biome-ignore lint/performance/noDelete: workaround for workers environment\n delete workerOptions.mode;\n\n // Call the original fetch with fixed options\n return fetch(fetchUrl, workerOptions);\n };\n\n super(url, {\n ...options,\n eventSourceInit: {\n fetch: fetchOverride,\n },\n });\n this.authProvider = options.authProvider;\n }\n\n async authHeaders() {\n if (this.authProvider) {\n const tokens = await this.authProvider.tokens();\n if (tokens) {\n return {\n Authorization: `Bearer ${tokens.access_token}`,\n };\n }\n }\n }\n}\n","import { SSEEdgeClientTransport } from \"./sse-edge\";\n\nimport {\n ToolListChangedNotificationSchema,\n type ClientCapabilities,\n type Resource,\n type Tool,\n type Prompt,\n ResourceListChangedNotificationSchema,\n PromptListChangedNotificationSchema,\n type ListToolsResult,\n type ListResourcesResult,\n type ListPromptsResult,\n type ServerCapabilities,\n type ResourceTemplate,\n type ListResourceTemplatesResult,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\n\nexport class MCPClientConnection {\n client: Client;\n connectionState:\n | \"authenticating\"\n | \"connecting\"\n | \"ready\"\n | \"discovering\"\n | \"failed\" = \"connecting\";\n instructions?: string;\n tools: Tool[] = [];\n prompts: Prompt[] = [];\n resources: Resource[] = [];\n resourceTemplates: ResourceTemplate[] = [];\n serverCapabilities: ServerCapabilities | undefined;\n\n constructor(\n public url: URL,\n private info: ConstructorParameters<typeof Client>[0],\n private options: {\n transport: SSEClientTransportOptions;\n client: ConstructorParameters<typeof Client>[1];\n capabilities: ClientCapabilities;\n } = { transport: {}, client: {}, capabilities: {} }\n ) {\n this.client = new Client(info, options.client);\n this.client.registerCapabilities(options.capabilities);\n }\n\n /**\n * Initialize a client connection\n *\n * @param code Optional OAuth code to initialize the connection with if auth hasn't been initialized\n * @returns\n */\n async init(code?: string, clientId?: string) {\n try {\n const transport = new SSEEdgeClientTransport(\n this.url,\n this.options.transport\n );\n if (code) {\n await transport.finishAuth(code);\n }\n await this.client.connect(transport);\n // biome-ignore lint/suspicious/noExplicitAny: allow for the error check here\n } catch (e: any) {\n if (e.toString().includes(\"Unauthorized\")) {\n // unauthorized, we should wait for the user to authenticate\n this.connectionState = \"authenticating\";\n return;\n }\n this.connectionState = \"failed\";\n throw e;\n }\n\n this.connectionState = \"discovering\";\n\n this.serverCapabilities = await this.client.getServerCapabilities();\n if (!this.serverCapabilities) {\n throw new Error(\"The MCP Server failed to return server capabilities\");\n }\n\n const [instructions, tools, resources, prompts, resourceTemplates] =\n await Promise.all([\n this.client.getInstructions(),\n this.registerTools(),\n this.registerResources(),\n this.registerPrompts(),\n this.registerResourceTemplates(),\n ]);\n\n this.instructions = instructions;\n this.tools = tools;\n this.resources = resources;\n this.prompts = prompts;\n this.resourceTemplates = resourceTemplates;\n\n this.connectionState = \"ready\";\n }\n\n /**\n * Notification handler registration\n */\n async registerTools(): Promise<Tool[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.tools) {\n return [];\n }\n\n if (this.serverCapabilities.tools.listChanged) {\n this.client.setNotificationHandler(\n ToolListChangedNotificationSchema,\n async (_notification) => {\n this.tools = await this.fetchTools();\n }\n );\n }\n\n return this.fetchTools();\n }\n\n async registerResources(): Promise<Resource[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.resources) {\n return [];\n }\n\n if (this.serverCapabilities.resources.listChanged) {\n this.client.setNotificationHandler(\n ResourceListChangedNotificationSchema,\n async (_notification) => {\n this.resources = await this.fetchResources();\n }\n );\n }\n\n return this.fetchResources();\n }\n\n async registerPrompts(): Promise<Prompt[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.prompts) {\n return [];\n }\n\n if (this.serverCapabilities.prompts.listChanged) {\n this.client.setNotificationHandler(\n PromptListChangedNotificationSchema,\n async (_notification) => {\n this.prompts = await this.fetchPrompts();\n }\n );\n }\n\n return this.fetchPrompts();\n }\n\n async registerResourceTemplates(): Promise<ResourceTemplate[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.resources) {\n return [];\n }\n\n return this.fetchResourceTemplates();\n }\n\n async fetchTools() {\n let toolsAgg: Tool[] = [];\n let toolsResult: ListToolsResult = { tools: [] };\n do {\n toolsResult = await this.client.listTools({\n cursor: toolsResult.nextCursor,\n });\n toolsAgg = toolsAgg.concat(toolsResult.tools);\n } while (toolsResult.nextCursor);\n return toolsAgg;\n }\n\n async fetchResources() {\n let resourcesAgg: Resource[] = [];\n let resourcesResult: ListResourcesResult = { resources: [] };\n do {\n resourcesResult = await this.client.listResources({\n cursor: resourcesResult.nextCursor,\n });\n resourcesAgg = resourcesAgg.concat(resourcesResult.resources);\n } while (resourcesResult.nextCursor);\n return resourcesAgg;\n }\n\n async fetchPrompts() {\n let promptsAgg: Prompt[] = [];\n let promptsResult: ListPromptsResult = { prompts: [] };\n do {\n promptsResult = await this.client.listPrompts({\n cursor: promptsResult.nextCursor,\n });\n promptsAgg = promptsAgg.concat(promptsResult.prompts);\n } while (promptsResult.nextCursor);\n return promptsAgg;\n }\n\n async fetchResourceTemplates() {\n let templatesAgg: ResourceTemplate[] = [];\n let templatesResult: ListResourceTemplatesResult = {\n resourceTemplates: [],\n };\n do {\n templatesResult = await this.client.listResourceTemplates({\n cursor: templatesResult.nextCursor,\n });\n templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);\n } while (templatesResult.nextCursor);\n return templatesAgg;\n }\n}\n","import type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport type {\n OAuthTokens,\n OAuthClientMetadata,\n OAuthClientInformation,\n OAuthClientInformationFull,\n} from \"@modelcontextprotocol/sdk/shared/auth.js\";\n\n// A slight extension to the standard OAuthClientProvider interface because `redirectToAuthorization` doesn't give us the interface we need\nexport interface AgentsOAuthProvider extends OAuthClientProvider {\n authUrl: string | undefined;\n clientId: string | undefined;\n}\n\nexport class DurableObjectOAuthClientProvider implements AgentsOAuthProvider {\n private authUrl_: string | undefined;\n\n constructor(\n public storage: DurableObjectStorage,\n public clientName: string,\n public sessionId: string,\n public redirectUrl: string,\n private clientId_?: string\n ) {}\n\n get clientMetadata(): OAuthClientMetadata {\n return {\n redirect_uris: [this.redirectUrl],\n token_endpoint_auth_method: \"none\",\n grant_types: [\"authorization_code\", \"refresh_token\"],\n response_types: [\"code\"],\n client_name: this.clientName,\n client_uri: \"example.com\",\n };\n }\n\n get clientId() {\n if (!this.clientId_) {\n throw new Error(\"no clientId\");\n }\n return this.clientId_;\n }\n\n set clientId(clientId_: string) {\n this.clientId_ = clientId_;\n }\n\n keyPrefix(clientId: string) {\n return `/${this.clientName}/${this.sessionId}/${clientId}`;\n }\n\n clientInfoKey(clientId: string) {\n return `${this.keyPrefix(clientId)}/client_info/`;\n }\n\n async clientInformation(): Promise<OAuthClientInformation | undefined> {\n if (!this.clientId_) {\n return undefined;\n }\n return (\n (await this.storage.get<OAuthClientInformation>(\n this.clientInfoKey(this.clientId)\n )) ?? undefined\n );\n }\n\n async saveClientInformation(\n clientInformation: OAuthClientInformationFull\n ): Promise<void> {\n await this.storage.put(\n this.clientInfoKey(clientInformation.client_id),\n clientInformation\n );\n this.clientId = clientInformation.client_id;\n }\n\n tokenKey(clientId: string) {\n return `${this.keyPrefix(clientId)}/token`;\n }\n\n async tokens(): Promise<OAuthTokens | undefined> {\n if (!this.clientId_) {\n return undefined;\n }\n return (\n (await this.storage.get<OAuthTokens>(this.tokenKey(this.clientId))) ??\n undefined\n );\n }\n\n async saveTokens(tokens: OAuthTokens): Promise<void> {\n await this.storage.put(this.tokenKey(this.clientId), tokens);\n }\n\n get authUrl() {\n return this.authUrl_;\n }\n\n /**\n * Because this operates on the server side (but we need browser auth), we send this url back to the user\n * and require user interact to initiate the redirect flow\n */\n async redirectToAuthorization(authUrl: URL): Promise<void> {\n // We want to track the client ID in state here because the typescript SSE client sometimes does\n // a dynamic client registration AFTER generating this redirect URL.\n const client_id = authUrl.searchParams.get(\"client_id\");\n if (client_id) {\n authUrl.searchParams.append(\"state\", client_id);\n }\n this.authUrl_ = authUrl.toString();\n }\n\n codeVerifierKey(clientId: string) {\n return `${this.keyPrefix(clientId)}/code_verifier`;\n }\n\n async saveCodeVerifier(verifier: string): Promise<void> {\n await this.storage.put(this.codeVerifierKey(this.clientId), verifier);\n }\n\n async codeVerifier(): Promise<string> {\n const codeVerifier = await this.storage.get<string>(\n this.codeVerifierKey(this.clientId)\n );\n if (!codeVerifier) {\n throw new Error(\"No code verifier found\");\n }\n return codeVerifier;\n }\n}\n","import { MCPClientConnection } from \"./client-connection\";\n\nimport type {\n ClientCapabilities,\n CallToolRequest,\n CallToolResultSchema,\n CompatibilityCallToolResultSchema,\n ReadResourceRequest,\n GetPromptRequest,\n Tool,\n Resource,\n Prompt,\n ResourceTemplate,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { RequestOptions } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport {\n DurableObjectOAuthClientProvider,\n type AgentsOAuthProvider,\n} from \"./do-oauth-client-provider\";\n\n/**\n * Utility class that aggregates multiple MCP clients into one\n */\nexport class MCPClientManager {\n public mcpConnections: Record<string, MCPClientConnection> = {};\n\n /**\n * @param name Name of the MCP client\n * @param version Version of the MCP Client\n * @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider\n */\n constructor(\n private name: string,\n private version: string,\n private auth?: { baseCallbackUri: string; storage: DurableObjectStorage }\n ) {}\n\n /**\n * Connect to and register an MCP server\n *\n * @param transportConfig Transport config\n * @param clientConfig Client config\n * @param capabilities Client capabilities (i.e. if the client supports roots/sampling)\n */\n async connect(\n url: string,\n opts: {\n // Allows you to reconnect to a server (in the case of a auth reconnect)\n // Doesn't handle session reconnection\n reconnect?: {\n id: string;\n oauthClientId?: string;\n oauthCode?: string;\n };\n // we're overriding authProvider here because we want to be able to access the auth URL\n transport?: SSEClientTransportOptions & {\n authProvider: AgentsOAuthProvider;\n };\n client?: ConstructorParameters<typeof Client>[1];\n capabilities?: ClientCapabilities;\n } = {}\n ): Promise<{ id: string; authUrl: string | undefined }> {\n const id = opts.reconnect?.id ?? crypto.randomUUID();\n\n // if we have global auth for the manager AND there's no authProvider override\n // then let's setup an auth provider\n\n if (this.auth) {\n console.warn(\n \"Using .auth configuration to generate an oauth provider, this is temporary and will be removed in the next version. Instead use transport.authProvider to provide an auth provider\"\n );\n }\n\n const authProvider: AgentsOAuthProvider | undefined = this.auth\n ? new DurableObjectOAuthClientProvider(\n this.auth.storage,\n this.name,\n id,\n `${this.auth.baseCallbackUri}/${id}`,\n opts.reconnect?.oauthClientId\n )\n : opts.transport?.authProvider;\n\n this.mcpConnections[id] = new MCPClientConnection(\n new URL(url),\n {\n name: this.name,\n version: this.version,\n },\n {\n transport: {\n ...opts.transport,\n authProvider,\n },\n client: opts.client ?? {},\n capabilities: opts.client ?? {},\n }\n );\n\n await this.mcpConnections[id].init(\n opts.reconnect?.oauthCode,\n opts.reconnect?.oauthClientId\n );\n\n return {\n id,\n authUrl: authProvider?.authUrl,\n };\n }\n\n isCallbackRequest(req: Request): boolean {\n if (this.auth?.baseCallbackUri) {\n return (\n req.url.startsWith(this.auth.baseCallbackUri) && req.method === \"GET\"\n );\n }\n return false;\n }\n\n async handleCallbackRequest(req: Request) {\n const url = new URL(req.url);\n const code = url.searchParams.get(\"code\");\n const clientId = url.searchParams.get(\"state\");\n let serverId = req.url\n .replace(this.auth!.baseCallbackUri, \"\")\n .split(\"?\")[0];\n serverId = serverId.replaceAll(\"/\", \"\");\n if (!code) {\n throw new Error(\"Unauthorized: no code provided\");\n }\n if (!clientId) {\n throw new Error(\"Unauthorized: no state provided\");\n }\n\n if (this.mcpConnections[serverId] === undefined) {\n throw new Error(`Could not find serverId: ${serverId}`);\n }\n\n if (this.mcpConnections[serverId].connectionState !== \"authenticating\") {\n throw new Error(\n \"Failed to authenticate: the client isn't in the `authenticating` state\"\n );\n }\n\n // reconnect to server with authorization\n const serverUrl = this.mcpConnections[serverId].url.toString();\n await this.connect(serverUrl, {\n reconnect: {\n id: serverId,\n oauthClientId: clientId,\n oauthCode: code,\n },\n });\n\n if (this.mcpConnections[serverId].connectionState === \"authenticating\") {\n throw new Error(\"Failed to authenticate: client failed to initialize\");\n }\n\n return { serverId };\n }\n\n /**\n * @returns namespaced list of tools\n */\n listTools(): NamespacedData[\"tools\"] {\n return getNamespacedData(this.mcpConnections, \"tools\");\n }\n\n /**\n * @returns namespaced list of prompts\n */\n listPrompts(): NamespacedData[\"prompts\"] {\n return getNamespacedData(this.mcpConnections, \"prompts\");\n }\n\n /**\n * @returns namespaced list of tools\n */\n listResources(): NamespacedData[\"resources\"] {\n return getNamespacedData(this.mcpConnections, \"resources\");\n }\n\n /**\n * @returns namespaced list of resource templates\n */\n listResourceTemplates(): NamespacedData[\"resourceTemplates\"] {\n return getNamespacedData(this.mcpConnections, \"resourceTemplates\");\n }\n\n /**\n * Namespaced version of callTool\n */\n callTool(\n params: CallToolRequest[\"params\"] & { serverId: string },\n resultSchema:\n | typeof CallToolResultSchema\n | typeof CompatibilityCallToolResultSchema,\n options: RequestOptions\n ) {\n const unqualifiedName = params.name.replace(`${params.serverId}.`, \"\");\n return this.mcpConnections[params.serverId].client.callTool(\n {\n ...params,\n name: unqualifiedName,\n },\n resultSchema,\n options\n );\n }\n\n /**\n * Namespaced version of readResource\n */\n readResource(\n params: ReadResourceRequest[\"params\"] & { serverId: string },\n options: RequestOptions\n ) {\n return this.mcpConnections[params.serverId].client.readResource(\n params,\n options\n );\n }\n\n /**\n * Namespaced version of getPrompt\n */\n getPrompt(\n params: GetPromptRequest[\"params\"] & { serverId: string },\n options: RequestOptions\n ) {\n return this.mcpConnections[params.serverId].client.getPrompt(\n params,\n options\n );\n }\n}\n\ntype NamespacedData = {\n tools: (Tool & { serverId: string })[];\n prompts: (Prompt & { serverId: string })[];\n resources: (Resource & { serverId: string })[];\n resourceTemplates: (ResourceTemplate & { serverId: string })[];\n};\n\nexport function getNamespacedData<T extends keyof NamespacedData>(\n mcpClients: Record<string, MCPClientConnection>,\n type: T\n): NamespacedData[T] {\n const sets = Object.entries(mcpClients).map(([name, conn]) => {\n return { name, data: conn[type] };\n });\n\n const namespacedData = sets.flatMap(({ name: serverId, data }) => {\n return data.map((item) => {\n return {\n ...item,\n // we add a serverId so we can easily pull it out and send the tool call to the right server\n serverId,\n };\n });\n });\n\n return namespacedData as NamespacedData[T]; // Type assertion needed due to TS limitations with conditional return types\n}\n"],"mappings":";;;AAAA;AAAA,EACE;AAAA,OAEK;AAGA,IAAM,yBAAN,cAAqC,mBAAmB;AAAA;AAAA;AAAA;AAAA,EAK7D,YAAY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,WAAO,kBAAkB,KAAK,gBAAgB,WAAW;AAAA,EAC3D;AAAA;AAAA;AAAA;AAAA,EAKA,wBAA6D;AAC3D,WAAO,kBAAkB,KAAK,gBAAgB,mBAAmB;AAAA,EACnE;AAAA;AAAA;AAAA;AAAA,EAKA,SACE,QACA,cAGA,SACA;AACA,UAAM,kBAAkB,OAAO,KAAK,QAAQ,GAAG,OAAO,QAAQ,KAAK,EAAE;AACrE,WAAO,KAAK,eAAe,OAAO,QAAQ,EAAE,OAAO;AAAA,MACjD;AAAA,QACE,GAAG;AAAA,QACH,MAAM;AAAA,MACR;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,aACE,QACA,SACA;AACA,WAAO,KAAK,eAAe,OAAO,QAAQ,EAAE,OAAO;AAAA,MACjD;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,UACE,QACA,SACA;AACA,WAAO,KAAK,eAAe,OAAO,QAAQ,EAAE,OAAO;AAAA,MACjD;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AASO,SAAS,kBACd,YACA,MACmB;AACnB,QAAM,OAAO,OAAO,QAAQ,UAAU,EAAE,IAAI,CAAC,CAAC,MAAM,IAAI,MAAM;AAC5D,WAAO,EAAE,MAAM,MAAM,KAAK,IAAI,EAAE;AAAA,EAClC,CAAC;AAED,QAAM,iBAAiB,KAAK,QAAQ,CAAC,EAAE,MAAM,UAAU,KAAK,MAAM;AAChE,WAAO,KAAK,IAAI,CAAC,SAAS;AACxB,aAAO;AAAA,QACL,GAAG;AAAA;AAAA,QAEH;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AAED,SAAO;AACT;","names":[]}
|
package/dist/mcp/index.d.ts
CHANGED
|
@@ -10,7 +10,6 @@ interface CORSOptions {
|
|
|
10
10
|
}
|
|
11
11
|
declare abstract class McpAgent<Env = unknown, State = unknown, Props extends Record<string, unknown> = Record<string, unknown>> extends DurableObject<Env> {
|
|
12
12
|
#private;
|
|
13
|
-
protected constructor(ctx: DurableObjectState, env: Env);
|
|
14
13
|
/**
|
|
15
14
|
* Agents API allowlist
|
|
16
15
|
*/
|
|
@@ -19,22 +18,26 @@ declare abstract class McpAgent<Env = unknown, State = unknown, Props extends Re
|
|
|
19
18
|
sql<T = Record<string, string | number | boolean | null>>(strings: TemplateStringsArray, ...values: (string | number | boolean | null)[]): T[];
|
|
20
19
|
setState(state: State): void;
|
|
21
20
|
onStateUpdate(state: State | undefined, source: Connection | "server"): void;
|
|
21
|
+
onStart(): Promise<void>;
|
|
22
22
|
/**
|
|
23
23
|
* McpAgent API
|
|
24
24
|
*/
|
|
25
25
|
abstract server: McpServer;
|
|
26
|
-
private transport;
|
|
27
26
|
props: Props;
|
|
28
27
|
initRun: boolean;
|
|
29
28
|
abstract init(): Promise<void>;
|
|
30
29
|
_init(props: Props): Promise<void>;
|
|
31
|
-
|
|
32
|
-
|
|
30
|
+
fetch(request: Request): Promise<Response>;
|
|
31
|
+
getWebSocket(): WebSocket | null;
|
|
32
|
+
onMCPMessage(sessionId: string, request: Request): Promise<Response>;
|
|
33
|
+
webSocketMessage(ws: WebSocket, event: ArrayBuffer | string): Promise<void>;
|
|
34
|
+
webSocketError(ws: WebSocket, error: unknown): Promise<void>;
|
|
35
|
+
webSocketClose(ws: WebSocket, code: number, reason: string, wasClean: boolean): Promise<void>;
|
|
33
36
|
static mount(path: string, { binding, corsOptions, }?: {
|
|
34
37
|
binding?: string;
|
|
35
38
|
corsOptions?: CORSOptions;
|
|
36
39
|
}): {
|
|
37
|
-
fetch: (request: Request, env: Record<string, DurableObjectNamespace<McpAgent>>, ctx: ExecutionContext) => Promise<Response>;
|
|
40
|
+
fetch: (request: Request, env: Record<string, DurableObjectNamespace<McpAgent>>, ctx: ExecutionContext) => Promise<Response | undefined>;
|
|
38
41
|
};
|
|
39
42
|
}
|
|
40
43
|
|