agents 0.0.0-5342ce4 → 0.0.0-5b7f03e
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 +18 -2
- package/dist/ai-chat-agent.js +77 -11
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-react.js +8 -1
- package/dist/ai-react.js.map +1 -1
- package/dist/ai-types.d.ts +5 -0
- package/dist/chunk-I4YBFB7W.js +456 -0
- package/dist/chunk-I4YBFB7W.js.map +1 -0
- package/dist/{chunk-XG52S6YY.js → chunk-NFBE2RQ4.js} +25 -10
- package/dist/chunk-NFBE2RQ4.js.map +1 -0
- package/dist/index.d.ts +18 -6
- package/dist/index.js +6 -5
- package/dist/mcp/client.d.ts +17 -3
- package/dist/mcp/client.js +4 -402
- package/dist/mcp/client.js.map +1 -1
- package/dist/mcp/index.d.ts +16 -4
- package/dist/mcp/index.js +35 -9
- package/dist/mcp/index.js.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +35 -7
- package/dist/chunk-XG52S6YY.js.map +0 -1
|
@@ -0,0 +1,456 @@
|
|
|
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
|
+
...fetchInit?.headers,
|
|
16
|
+
...headers
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
delete workerOptions.mode;
|
|
20
|
+
return fetch(fetchUrl, workerOptions);
|
|
21
|
+
};
|
|
22
|
+
super(url, {
|
|
23
|
+
...options,
|
|
24
|
+
eventSourceInit: {
|
|
25
|
+
fetch: fetchOverride
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
this.authProvider = options.authProvider;
|
|
29
|
+
}
|
|
30
|
+
async authHeaders() {
|
|
31
|
+
if (this.authProvider) {
|
|
32
|
+
const tokens = await this.authProvider.tokens();
|
|
33
|
+
if (tokens) {
|
|
34
|
+
return {
|
|
35
|
+
Authorization: `Bearer ${tokens.access_token}`
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
// src/mcp/client-connection.ts
|
|
43
|
+
import {
|
|
44
|
+
ToolListChangedNotificationSchema,
|
|
45
|
+
ResourceListChangedNotificationSchema,
|
|
46
|
+
PromptListChangedNotificationSchema
|
|
47
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
48
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
49
|
+
var MCPClientConnection = class {
|
|
50
|
+
constructor(url, info, options = { transport: {}, client: {}, capabilities: {} }) {
|
|
51
|
+
this.url = url;
|
|
52
|
+
this.options = options;
|
|
53
|
+
this.connectionState = "connecting";
|
|
54
|
+
this.tools = [];
|
|
55
|
+
this.prompts = [];
|
|
56
|
+
this.resources = [];
|
|
57
|
+
this.resourceTemplates = [];
|
|
58
|
+
this.client = new Client(info, options.client);
|
|
59
|
+
this.client.registerCapabilities(options.capabilities);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Initialize a client connection
|
|
63
|
+
*
|
|
64
|
+
* @param code Optional OAuth code to initialize the connection with if auth hasn't been initialized
|
|
65
|
+
* @returns
|
|
66
|
+
*/
|
|
67
|
+
async init(code, clientId) {
|
|
68
|
+
try {
|
|
69
|
+
const transport = new SSEEdgeClientTransport(
|
|
70
|
+
this.url,
|
|
71
|
+
this.options.transport
|
|
72
|
+
);
|
|
73
|
+
if (code) {
|
|
74
|
+
await transport.finishAuth(code);
|
|
75
|
+
}
|
|
76
|
+
await this.client.connect(transport);
|
|
77
|
+
} catch (e) {
|
|
78
|
+
if (e.toString().includes("Unauthorized")) {
|
|
79
|
+
this.connectionState = "authenticating";
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
this.connectionState = "failed";
|
|
83
|
+
throw e;
|
|
84
|
+
}
|
|
85
|
+
this.connectionState = "discovering";
|
|
86
|
+
this.serverCapabilities = await this.client.getServerCapabilities();
|
|
87
|
+
if (!this.serverCapabilities) {
|
|
88
|
+
throw new Error("The MCP Server failed to return server capabilities");
|
|
89
|
+
}
|
|
90
|
+
const [instructions, tools, resources, prompts, resourceTemplates] = await Promise.all([
|
|
91
|
+
this.client.getInstructions(),
|
|
92
|
+
this.registerTools(),
|
|
93
|
+
this.registerResources(),
|
|
94
|
+
this.registerPrompts(),
|
|
95
|
+
this.registerResourceTemplates()
|
|
96
|
+
]);
|
|
97
|
+
this.instructions = instructions;
|
|
98
|
+
this.tools = tools;
|
|
99
|
+
this.resources = resources;
|
|
100
|
+
this.prompts = prompts;
|
|
101
|
+
this.resourceTemplates = resourceTemplates;
|
|
102
|
+
this.connectionState = "ready";
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Notification handler registration
|
|
106
|
+
*/
|
|
107
|
+
async registerTools() {
|
|
108
|
+
if (!this.serverCapabilities || !this.serverCapabilities.tools) {
|
|
109
|
+
return [];
|
|
110
|
+
}
|
|
111
|
+
if (this.serverCapabilities.tools.listChanged) {
|
|
112
|
+
this.client.setNotificationHandler(
|
|
113
|
+
ToolListChangedNotificationSchema,
|
|
114
|
+
async (_notification) => {
|
|
115
|
+
this.tools = await this.fetchTools();
|
|
116
|
+
}
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
return this.fetchTools();
|
|
120
|
+
}
|
|
121
|
+
async registerResources() {
|
|
122
|
+
if (!this.serverCapabilities || !this.serverCapabilities.resources) {
|
|
123
|
+
return [];
|
|
124
|
+
}
|
|
125
|
+
if (this.serverCapabilities.resources.listChanged) {
|
|
126
|
+
this.client.setNotificationHandler(
|
|
127
|
+
ResourceListChangedNotificationSchema,
|
|
128
|
+
async (_notification) => {
|
|
129
|
+
this.resources = await this.fetchResources();
|
|
130
|
+
}
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
return this.fetchResources();
|
|
134
|
+
}
|
|
135
|
+
async registerPrompts() {
|
|
136
|
+
if (!this.serverCapabilities || !this.serverCapabilities.prompts) {
|
|
137
|
+
return [];
|
|
138
|
+
}
|
|
139
|
+
if (this.serverCapabilities.prompts.listChanged) {
|
|
140
|
+
this.client.setNotificationHandler(
|
|
141
|
+
PromptListChangedNotificationSchema,
|
|
142
|
+
async (_notification) => {
|
|
143
|
+
this.prompts = await this.fetchPrompts();
|
|
144
|
+
}
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
return this.fetchPrompts();
|
|
148
|
+
}
|
|
149
|
+
async registerResourceTemplates() {
|
|
150
|
+
if (!this.serverCapabilities || !this.serverCapabilities.resources) {
|
|
151
|
+
return [];
|
|
152
|
+
}
|
|
153
|
+
return this.fetchResourceTemplates();
|
|
154
|
+
}
|
|
155
|
+
async fetchTools() {
|
|
156
|
+
let toolsAgg = [];
|
|
157
|
+
let toolsResult = { tools: [] };
|
|
158
|
+
do {
|
|
159
|
+
toolsResult = await this.client.listTools({
|
|
160
|
+
cursor: toolsResult.nextCursor
|
|
161
|
+
}).catch(capabilityErrorHandler({ tools: [] }, "tools/list"));
|
|
162
|
+
toolsAgg = toolsAgg.concat(toolsResult.tools);
|
|
163
|
+
} while (toolsResult.nextCursor);
|
|
164
|
+
return toolsAgg;
|
|
165
|
+
}
|
|
166
|
+
async fetchResources() {
|
|
167
|
+
let resourcesAgg = [];
|
|
168
|
+
let resourcesResult = { resources: [] };
|
|
169
|
+
do {
|
|
170
|
+
resourcesResult = await this.client.listResources({
|
|
171
|
+
cursor: resourcesResult.nextCursor
|
|
172
|
+
}).catch(capabilityErrorHandler({ resources: [] }, "resources/list"));
|
|
173
|
+
resourcesAgg = resourcesAgg.concat(resourcesResult.resources);
|
|
174
|
+
} while (resourcesResult.nextCursor);
|
|
175
|
+
return resourcesAgg;
|
|
176
|
+
}
|
|
177
|
+
async fetchPrompts() {
|
|
178
|
+
let promptsAgg = [];
|
|
179
|
+
let promptsResult = { prompts: [] };
|
|
180
|
+
do {
|
|
181
|
+
promptsResult = await this.client.listPrompts({
|
|
182
|
+
cursor: promptsResult.nextCursor
|
|
183
|
+
}).catch(capabilityErrorHandler({ prompts: [] }, "prompts/list"));
|
|
184
|
+
promptsAgg = promptsAgg.concat(promptsResult.prompts);
|
|
185
|
+
} while (promptsResult.nextCursor);
|
|
186
|
+
return promptsAgg;
|
|
187
|
+
}
|
|
188
|
+
async fetchResourceTemplates() {
|
|
189
|
+
let templatesAgg = [];
|
|
190
|
+
let templatesResult = {
|
|
191
|
+
resourceTemplates: []
|
|
192
|
+
};
|
|
193
|
+
do {
|
|
194
|
+
templatesResult = await this.client.listResourceTemplates({
|
|
195
|
+
cursor: templatesResult.nextCursor
|
|
196
|
+
}).catch(
|
|
197
|
+
capabilityErrorHandler(
|
|
198
|
+
{ resourceTemplates: [] },
|
|
199
|
+
"resources/templates/list"
|
|
200
|
+
)
|
|
201
|
+
);
|
|
202
|
+
templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);
|
|
203
|
+
} while (templatesResult.nextCursor);
|
|
204
|
+
return templatesAgg;
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
function capabilityErrorHandler(empty, method) {
|
|
208
|
+
return (e) => {
|
|
209
|
+
if (e.code === -32601) {
|
|
210
|
+
console.error(
|
|
211
|
+
`The server advertised support for the capability ${method.split("/")[0]}, but returned "Method not found" for '${method}'.`
|
|
212
|
+
);
|
|
213
|
+
return empty;
|
|
214
|
+
}
|
|
215
|
+
throw e;
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// src/mcp/client.ts
|
|
220
|
+
import { jsonSchema } from "ai";
|
|
221
|
+
import { nanoid } from "nanoid";
|
|
222
|
+
var MCPClientManager = class {
|
|
223
|
+
/**
|
|
224
|
+
* @param name Name of the MCP client
|
|
225
|
+
* @param version Version of the MCP Client
|
|
226
|
+
* @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider
|
|
227
|
+
*/
|
|
228
|
+
constructor(name, version) {
|
|
229
|
+
this.name = name;
|
|
230
|
+
this.version = version;
|
|
231
|
+
this.mcpConnections = {};
|
|
232
|
+
this.callbackUrls = [];
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Connect to and register an MCP server
|
|
236
|
+
*
|
|
237
|
+
* @param transportConfig Transport config
|
|
238
|
+
* @param clientConfig Client config
|
|
239
|
+
* @param capabilities Client capabilities (i.e. if the client supports roots/sampling)
|
|
240
|
+
*/
|
|
241
|
+
async connect(url, options = {}) {
|
|
242
|
+
const id = options.reconnect?.id ?? nanoid(8);
|
|
243
|
+
if (!options.transport?.authProvider) {
|
|
244
|
+
console.warn(
|
|
245
|
+
"No authProvider provided in the transport options. This client will only support unauthenticated remote MCP Servers"
|
|
246
|
+
);
|
|
247
|
+
} else {
|
|
248
|
+
options.transport.authProvider.serverId = id;
|
|
249
|
+
}
|
|
250
|
+
this.mcpConnections[id] = new MCPClientConnection(
|
|
251
|
+
new URL(url),
|
|
252
|
+
{
|
|
253
|
+
name: this.name,
|
|
254
|
+
version: this.version
|
|
255
|
+
},
|
|
256
|
+
{
|
|
257
|
+
transport: options.transport ?? {},
|
|
258
|
+
client: options.client ?? {},
|
|
259
|
+
capabilities: options.client ?? {}
|
|
260
|
+
}
|
|
261
|
+
);
|
|
262
|
+
await this.mcpConnections[id].init(
|
|
263
|
+
options.reconnect?.oauthCode,
|
|
264
|
+
options.reconnect?.oauthClientId
|
|
265
|
+
);
|
|
266
|
+
const authUrl = options.transport?.authProvider?.authUrl;
|
|
267
|
+
if (authUrl && options.transport?.authProvider?.redirectUrl) {
|
|
268
|
+
this.callbackUrls.push(
|
|
269
|
+
options.transport.authProvider.redirectUrl.toString()
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
return {
|
|
273
|
+
id,
|
|
274
|
+
authUrl
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
isCallbackRequest(req) {
|
|
278
|
+
return req.method === "GET" && !!this.callbackUrls.find((url) => {
|
|
279
|
+
return req.url.startsWith(url);
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
async handleCallbackRequest(req) {
|
|
283
|
+
const url = new URL(req.url);
|
|
284
|
+
const urlMatch = this.callbackUrls.find((url2) => {
|
|
285
|
+
return req.url.startsWith(url2);
|
|
286
|
+
});
|
|
287
|
+
if (!urlMatch) {
|
|
288
|
+
throw new Error(
|
|
289
|
+
`No callback URI match found for the request url: ${req.url}. Was the request matched with \`isCallbackRequest()\`?`
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
const code = url.searchParams.get("code");
|
|
293
|
+
const clientId = url.searchParams.get("state");
|
|
294
|
+
const urlParams = urlMatch.split("/");
|
|
295
|
+
const serverId = urlParams[urlParams.length - 1];
|
|
296
|
+
if (!code) {
|
|
297
|
+
throw new Error("Unauthorized: no code provided");
|
|
298
|
+
}
|
|
299
|
+
if (!clientId) {
|
|
300
|
+
throw new Error("Unauthorized: no state provided");
|
|
301
|
+
}
|
|
302
|
+
if (this.mcpConnections[serverId] === void 0) {
|
|
303
|
+
throw new Error(`Could not find serverId: ${serverId}`);
|
|
304
|
+
}
|
|
305
|
+
if (this.mcpConnections[serverId].connectionState !== "authenticating") {
|
|
306
|
+
throw new Error(
|
|
307
|
+
"Failed to authenticate: the client isn't in the `authenticating` state"
|
|
308
|
+
);
|
|
309
|
+
}
|
|
310
|
+
const conn = this.mcpConnections[serverId];
|
|
311
|
+
if (!conn.options.transport.authProvider) {
|
|
312
|
+
throw new Error(
|
|
313
|
+
"Trying to finalize authentication for a server connection without an authProvider"
|
|
314
|
+
);
|
|
315
|
+
}
|
|
316
|
+
conn.options.transport.authProvider.clientId = clientId;
|
|
317
|
+
conn.options.transport.authProvider.serverId = serverId;
|
|
318
|
+
const serverUrl = conn.url.toString();
|
|
319
|
+
await this.connect(serverUrl, {
|
|
320
|
+
reconnect: {
|
|
321
|
+
id: serverId,
|
|
322
|
+
oauthClientId: clientId,
|
|
323
|
+
oauthCode: code
|
|
324
|
+
},
|
|
325
|
+
...conn.options
|
|
326
|
+
});
|
|
327
|
+
if (this.mcpConnections[serverId].connectionState === "authenticating") {
|
|
328
|
+
throw new Error("Failed to authenticate: client failed to initialize");
|
|
329
|
+
}
|
|
330
|
+
return { serverId };
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* @returns namespaced list of tools
|
|
334
|
+
*/
|
|
335
|
+
listTools() {
|
|
336
|
+
return getNamespacedData(this.mcpConnections, "tools");
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* @returns a set of tools that you can use with the AI SDK
|
|
340
|
+
*/
|
|
341
|
+
unstable_getAITools() {
|
|
342
|
+
return Object.fromEntries(
|
|
343
|
+
getNamespacedData(this.mcpConnections, "tools").map((tool) => {
|
|
344
|
+
return [
|
|
345
|
+
`${tool.serverId}.${tool.name}`,
|
|
346
|
+
{
|
|
347
|
+
parameters: jsonSchema(tool.inputSchema),
|
|
348
|
+
description: tool.description,
|
|
349
|
+
execute: async (args) => {
|
|
350
|
+
const result = await this.callTool({
|
|
351
|
+
name: tool.name,
|
|
352
|
+
arguments: args,
|
|
353
|
+
serverId: tool.serverId
|
|
354
|
+
});
|
|
355
|
+
if (result.isError) {
|
|
356
|
+
throw new Error(result.content[0].text);
|
|
357
|
+
}
|
|
358
|
+
return result;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
];
|
|
362
|
+
})
|
|
363
|
+
);
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Closes all connections to MCP servers
|
|
367
|
+
*/
|
|
368
|
+
async closeAllConnections() {
|
|
369
|
+
return Promise.all(
|
|
370
|
+
Object.values(this.mcpConnections).map(async (connection) => {
|
|
371
|
+
await connection.client.close();
|
|
372
|
+
})
|
|
373
|
+
);
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* Closes a connection to an MCP server
|
|
377
|
+
* @param id The id of the connection to close
|
|
378
|
+
*/
|
|
379
|
+
async closeConnection(id) {
|
|
380
|
+
if (!this.mcpConnections[id]) {
|
|
381
|
+
throw new Error(`Connection with id "${id}" does not exist.`);
|
|
382
|
+
}
|
|
383
|
+
await this.mcpConnections[id].client.close();
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* @returns namespaced list of prompts
|
|
387
|
+
*/
|
|
388
|
+
listPrompts() {
|
|
389
|
+
return getNamespacedData(this.mcpConnections, "prompts");
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* @returns namespaced list of tools
|
|
393
|
+
*/
|
|
394
|
+
listResources() {
|
|
395
|
+
return getNamespacedData(this.mcpConnections, "resources");
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* @returns namespaced list of resource templates
|
|
399
|
+
*/
|
|
400
|
+
listResourceTemplates() {
|
|
401
|
+
return getNamespacedData(this.mcpConnections, "resourceTemplates");
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* Namespaced version of callTool
|
|
405
|
+
*/
|
|
406
|
+
callTool(params, resultSchema, options) {
|
|
407
|
+
const unqualifiedName = params.name.replace(`${params.serverId}.`, "");
|
|
408
|
+
return this.mcpConnections[params.serverId].client.callTool(
|
|
409
|
+
{
|
|
410
|
+
...params,
|
|
411
|
+
name: unqualifiedName
|
|
412
|
+
},
|
|
413
|
+
resultSchema,
|
|
414
|
+
options
|
|
415
|
+
);
|
|
416
|
+
}
|
|
417
|
+
/**
|
|
418
|
+
* Namespaced version of readResource
|
|
419
|
+
*/
|
|
420
|
+
readResource(params, options) {
|
|
421
|
+
return this.mcpConnections[params.serverId].client.readResource(
|
|
422
|
+
params,
|
|
423
|
+
options
|
|
424
|
+
);
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* Namespaced version of getPrompt
|
|
428
|
+
*/
|
|
429
|
+
getPrompt(params, options) {
|
|
430
|
+
return this.mcpConnections[params.serverId].client.getPrompt(
|
|
431
|
+
params,
|
|
432
|
+
options
|
|
433
|
+
);
|
|
434
|
+
}
|
|
435
|
+
};
|
|
436
|
+
function getNamespacedData(mcpClients, type) {
|
|
437
|
+
const sets = Object.entries(mcpClients).map(([name, conn]) => {
|
|
438
|
+
return { name, data: conn[type] };
|
|
439
|
+
});
|
|
440
|
+
const namespacedData = sets.flatMap(({ name: serverId, data }) => {
|
|
441
|
+
return data.map((item) => {
|
|
442
|
+
return {
|
|
443
|
+
...item,
|
|
444
|
+
// we add a serverId so we can easily pull it out and send the tool call to the right server
|
|
445
|
+
serverId
|
|
446
|
+
};
|
|
447
|
+
});
|
|
448
|
+
});
|
|
449
|
+
return namespacedData;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
export {
|
|
453
|
+
MCPClientManager,
|
|
454
|
+
getNamespacedData
|
|
455
|
+
};
|
|
456
|
+
//# sourceMappingURL=chunk-I4YBFB7W.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 ...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\";\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 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\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 {\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 type { AgentsOAuthProvider } from \"./do-oauth-client-provider\";\nimport { jsonSchema, type ToolSet } from \"ai\";\nimport { nanoid } from \"nanoid\";\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 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 = 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 }\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 capabilities: options.client ?? {},\n }\n );\n\n await this.mcpConnections[id].init(\n options.reconnect?.oauthCode,\n options.reconnect?.oauthClientId\n );\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 }\n\n return {\n id,\n authUrl,\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 }\n\n /**\n * @returns namespaced list of prompts\n */\n listPrompts(): NamespacedData[\"prompts\"] {\n return getNamespacedData(this.mcpConnections, \"prompts\");\n }\n\n /**\n * @returns namespaced list of tools\n */\n listResources(): NamespacedData[\"resources\"] {\n return getNamespacedData(this.mcpConnections, \"resources\");\n }\n\n /**\n * @returns namespaced list of resource templates\n */\n listResourceTemplates(): NamespacedData[\"resourceTemplates\"] {\n return getNamespacedData(this.mcpConnections, \"resourceTemplates\");\n }\n\n /**\n * Namespaced version of callTool\n */\n callTool(\n params: CallToolRequest[\"params\"] & { serverId: string },\n resultSchema?:\n | typeof CallToolResultSchema\n | typeof CompatibilityCallToolResultSchema,\n options?: RequestOptions\n ) {\n const unqualifiedName = params.name.replace(`${params.serverId}.`, \"\");\n return this.mcpConnections[params.serverId].client.callTool(\n {\n ...params,\n name: unqualifiedName,\n },\n resultSchema,\n options\n );\n }\n\n /**\n * Namespaced version of readResource\n */\n readResource(\n params: ReadResourceRequest[\"params\"] & { serverId: string },\n options: RequestOptions\n ) {\n return this.mcpConnections[params.serverId].client.readResource(\n params,\n options\n );\n }\n\n /**\n * Namespaced version of getPrompt\n */\n getPrompt(\n params: GetPromptRequest[\"params\"] & { serverId: string },\n options: RequestOptions\n ) {\n return this.mcpConnections[params.serverId].client.getPrompt(\n params,\n options\n );\n }\n}\n\ntype NamespacedData = {\n tools: (Tool & { serverId: string })[];\n prompts: (Prompt & { serverId: string })[];\n resources: (Resource & { serverId: string })[];\n resourceTemplates: (ResourceTemplate & { serverId: string })[];\n};\n\nexport function getNamespacedData<T extends keyof NamespacedData>(\n mcpClients: Record<string, MCPClientConnection>,\n type: T\n): NamespacedData[T] {\n const sets = Object.entries(mcpClients).map(([name, conn]) => {\n return { name, data: conn[type] };\n });\n\n const namespacedData = sets.flatMap(({ name: serverId, data }) => {\n return data.map((item) => {\n return {\n ...item,\n // we add a serverId so we can easily pull it out and send the tool call to the right server\n serverId,\n };\n });\n });\n\n return namespacedData as NamespacedData[T]; // Type assertion needed due to TS limitations with conditional return types\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,OAEK;AAGA,IAAM,yBAAN,cAAqC,mBAAmB;AAAA;AAAA;AAAA;AAAA,EAK7D,YAAY,KAAU,SAAoC;AACxD,UAAM,gBAA8B,OAClC,UACA,YAAyB,CAAC,MACvB;AAEH,YAAM,UAAU,MAAM,KAAK,YAAY;AACvC,YAAM,gBAAgB;AAAA,QACpB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AE;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":["url"]}
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import {
|
|
2
|
+
MCPClientManager
|
|
3
|
+
} from "./chunk-I4YBFB7W.js";
|
|
1
4
|
import {
|
|
2
5
|
__privateAdd,
|
|
3
6
|
__privateGet,
|
|
@@ -36,13 +39,24 @@ function getNextCronTime(cron) {
|
|
|
36
39
|
var STATE_ROW_ID = "cf_state_row_id";
|
|
37
40
|
var STATE_WAS_CHANGED = "cf_state_was_changed";
|
|
38
41
|
var DEFAULT_STATE = {};
|
|
39
|
-
var
|
|
40
|
-
|
|
42
|
+
var agentContext = new AsyncLocalStorage();
|
|
43
|
+
function getCurrentAgent() {
|
|
44
|
+
const store = agentContext.getStore();
|
|
45
|
+
if (!store) {
|
|
46
|
+
throw new Error(
|
|
47
|
+
"No agent context found, this means you're trying to access the current agent when none of them are running."
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
return store;
|
|
51
|
+
}
|
|
52
|
+
var _state, _ParentClass, _Agent_instances, setStateInternal_fn, tryCatch_fn, scheduleNextAlarm_fn, isCallable_fn;
|
|
41
53
|
var Agent = class extends Server {
|
|
42
54
|
constructor(ctx, env) {
|
|
43
55
|
super(ctx, env);
|
|
44
56
|
__privateAdd(this, _Agent_instances);
|
|
45
57
|
__privateAdd(this, _state, DEFAULT_STATE);
|
|
58
|
+
__privateAdd(this, _ParentClass, Object.getPrototypeOf(this).constructor);
|
|
59
|
+
this.mcp = new MCPClientManager(__privateGet(this, _ParentClass).name, "0.0.1");
|
|
46
60
|
/**
|
|
47
61
|
* Initial state for the Agent
|
|
48
62
|
* Override to provide default state values
|
|
@@ -73,7 +87,7 @@ var Agent = class extends Server {
|
|
|
73
87
|
});
|
|
74
88
|
const _onMessage = this.onMessage.bind(this);
|
|
75
89
|
this.onMessage = async (connection, message) => {
|
|
76
|
-
return
|
|
90
|
+
return agentContext.run(
|
|
77
91
|
{ agent: this, connection, request: void 0 },
|
|
78
92
|
async () => {
|
|
79
93
|
if (typeof message !== "string") {
|
|
@@ -132,7 +146,7 @@ var Agent = class extends Server {
|
|
|
132
146
|
};
|
|
133
147
|
const _onConnect = this.onConnect.bind(this);
|
|
134
148
|
this.onConnect = (connection, ctx2) => {
|
|
135
|
-
return
|
|
149
|
+
return agentContext.run(
|
|
136
150
|
{ agent: this, connection, request: ctx2.request },
|
|
137
151
|
async () => {
|
|
138
152
|
setTimeout(() => {
|
|
@@ -214,7 +228,7 @@ var Agent = class extends Server {
|
|
|
214
228
|
* @param email Email message to process
|
|
215
229
|
*/
|
|
216
230
|
onEmail(email) {
|
|
217
|
-
return
|
|
231
|
+
return agentContext.run(
|
|
218
232
|
{ agent: this, connection: void 0, request: void 0 },
|
|
219
233
|
async () => {
|
|
220
234
|
console.error("onEmail not implemented");
|
|
@@ -392,7 +406,7 @@ var Agent = class extends Server {
|
|
|
392
406
|
console.error(`callback ${row.callback} not found`);
|
|
393
407
|
continue;
|
|
394
408
|
}
|
|
395
|
-
await
|
|
409
|
+
await agentContext.run(
|
|
396
410
|
{ agent: this, connection: void 0, request: void 0 },
|
|
397
411
|
async () => {
|
|
398
412
|
try {
|
|
@@ -427,6 +441,7 @@ var Agent = class extends Server {
|
|
|
427
441
|
}
|
|
428
442
|
};
|
|
429
443
|
_state = new WeakMap();
|
|
444
|
+
_ParentClass = new WeakMap();
|
|
430
445
|
_Agent_instances = new WeakSet();
|
|
431
446
|
setStateInternal_fn = function(state, source = "server") {
|
|
432
447
|
__privateSet(this, _state, state);
|
|
@@ -446,8 +461,8 @@ setStateInternal_fn = function(state, source = "server") {
|
|
|
446
461
|
source !== "server" ? [source.id] : []
|
|
447
462
|
);
|
|
448
463
|
return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => {
|
|
449
|
-
const { connection, request } =
|
|
450
|
-
return
|
|
464
|
+
const { connection, request } = agentContext.getStore() || {};
|
|
465
|
+
return agentContext.run(
|
|
451
466
|
{ agent: this, connection, request },
|
|
452
467
|
async () => {
|
|
453
468
|
return this.onStateUpdate(state, source);
|
|
@@ -581,11 +596,11 @@ _closed = new WeakMap();
|
|
|
581
596
|
|
|
582
597
|
export {
|
|
583
598
|
unstable_callable,
|
|
584
|
-
|
|
599
|
+
getCurrentAgent,
|
|
585
600
|
Agent,
|
|
586
601
|
routeAgentRequest,
|
|
587
602
|
routeAgentEmail,
|
|
588
603
|
getAgentByName,
|
|
589
604
|
StreamingResponse
|
|
590
605
|
};
|
|
591
|
-
//# sourceMappingURL=chunk-
|
|
606
|
+
//# sourceMappingURL=chunk-NFBE2RQ4.js.map
|