agents 0.0.0-36d81b3 → 0.0.0-385f0b2
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 +27 -1
- package/dist/ai-chat-agent.js +100 -103
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-react.d.ts +12 -0
- package/dist/ai-react.js +2 -1
- package/dist/ai-react.js.map +1 -1
- package/dist/chunk-BZXOAZUX.js +106 -0
- package/dist/chunk-BZXOAZUX.js.map +1 -0
- package/dist/{chunk-HMLY7DHA.js → chunk-NOUFNU2O.js} +1 -5
- package/dist/{chunk-WNIGPPNB.js → chunk-NPGUKHFR.js} +292 -127
- package/dist/chunk-NPGUKHFR.js.map +1 -0
- package/dist/chunk-QSGN3REV.js +123 -0
- package/dist/chunk-QSGN3REV.js.map +1 -0
- package/dist/{chunk-Q5ZBHY4Z.js → chunk-Y67CHZBI.js} +32 -24
- package/dist/chunk-Y67CHZBI.js.map +1 -0
- package/dist/client.d.ts +9 -1
- package/dist/client.js +7 -126
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +67 -6
- package/dist/index.js +5 -3
- package/dist/mcp/client.d.ts +21 -15
- package/dist/mcp/client.js +2 -2
- package/dist/mcp/do-oauth-client-provider.d.ts +3 -3
- package/dist/mcp/do-oauth-client-provider.js +4 -103
- package/dist/mcp/do-oauth-client-provider.js.map +1 -1
- package/dist/mcp/index.d.ts +14 -4
- package/dist/mcp/index.js +107 -135
- package/dist/mcp/index.js.map +1 -1
- package/dist/react.d.ts +14 -0
- package/dist/react.js +5 -1
- package/dist/react.js.map +1 -1
- package/dist/schedule.js +1 -1
- package/package.json +9 -6
- package/src/index.ts +348 -47
- package/dist/chunk-Q5ZBHY4Z.js.map +0 -1
- package/dist/chunk-WNIGPPNB.js.map +0 -1
- /package/dist/{chunk-HMLY7DHA.js.map → chunk-NOUFNU2O.js.map} +0 -0
package/src/index.ts
CHANGED
|
@@ -13,6 +13,20 @@ import { nanoid } from "nanoid";
|
|
|
13
13
|
|
|
14
14
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
15
15
|
import { MCPClientManager } from "./mcp/client";
|
|
16
|
+
import {
|
|
17
|
+
DurableObjectOAuthClientProvider,
|
|
18
|
+
type AgentsOAuthProvider,
|
|
19
|
+
} from "./mcp/do-oauth-client-provider";
|
|
20
|
+
import type {
|
|
21
|
+
Tool,
|
|
22
|
+
Resource,
|
|
23
|
+
Prompt,
|
|
24
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
25
|
+
|
|
26
|
+
import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
27
|
+
import type { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
28
|
+
|
|
29
|
+
import { camelCaseToKebabCase } from "./client";
|
|
16
30
|
|
|
17
31
|
export type { Connection, WSMessage, ConnectionContext } from "partyserver";
|
|
18
32
|
|
|
@@ -159,6 +173,43 @@ function getNextCronTime(cron: string) {
|
|
|
159
173
|
return interval.getNextDate();
|
|
160
174
|
}
|
|
161
175
|
|
|
176
|
+
/**
|
|
177
|
+
* MCP Server state update message from server -> Client
|
|
178
|
+
*/
|
|
179
|
+
export type MCPServerMessage = {
|
|
180
|
+
type: "cf_agent_mcp_servers";
|
|
181
|
+
mcp: MCPServersState;
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
export type MCPServersState = {
|
|
185
|
+
servers: {
|
|
186
|
+
[id: string]: MCPServer;
|
|
187
|
+
};
|
|
188
|
+
tools: Tool[];
|
|
189
|
+
prompts: Prompt[];
|
|
190
|
+
resources: Resource[];
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
export type MCPServer = {
|
|
194
|
+
name: string;
|
|
195
|
+
server_url: string;
|
|
196
|
+
auth_url: string | null;
|
|
197
|
+
state: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* MCP Server data stored in DO SQL for resuming MCP Server connections
|
|
202
|
+
*/
|
|
203
|
+
type MCPServerRow = {
|
|
204
|
+
id: string;
|
|
205
|
+
name: string;
|
|
206
|
+
server_url: string;
|
|
207
|
+
client_id: string | null;
|
|
208
|
+
auth_url: string | null;
|
|
209
|
+
callback_url: string;
|
|
210
|
+
server_options: string;
|
|
211
|
+
};
|
|
212
|
+
|
|
162
213
|
const STATE_ROW_ID = "cf_state_row_id";
|
|
163
214
|
const STATE_WAS_CHANGED = "cf_state_was_changed";
|
|
164
215
|
|
|
@@ -200,12 +251,12 @@ export function getCurrentAgent<
|
|
|
200
251
|
* @template State State type to store within the Agent
|
|
201
252
|
*/
|
|
202
253
|
export class Agent<Env, State = unknown> extends Server<Env> {
|
|
203
|
-
|
|
254
|
+
private _state = DEFAULT_STATE as State;
|
|
204
255
|
|
|
205
|
-
|
|
256
|
+
private _ParentClass: typeof Agent<Env, State> =
|
|
206
257
|
Object.getPrototypeOf(this).constructor;
|
|
207
258
|
|
|
208
|
-
mcp: MCPClientManager = new MCPClientManager(this
|
|
259
|
+
mcp: MCPClientManager = new MCPClientManager(this._ParentClass.name, "0.0.1");
|
|
209
260
|
|
|
210
261
|
/**
|
|
211
262
|
* Initial state for the Agent
|
|
@@ -217,9 +268,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
217
268
|
* Current state of the Agent
|
|
218
269
|
*/
|
|
219
270
|
get state(): State {
|
|
220
|
-
if (this
|
|
271
|
+
if (this._state !== DEFAULT_STATE) {
|
|
221
272
|
// state was previously set, and populated internal state
|
|
222
|
-
return this
|
|
273
|
+
return this._state;
|
|
223
274
|
}
|
|
224
275
|
// looks like this is the first time the state is being accessed
|
|
225
276
|
// check if the state was set in a previous life
|
|
@@ -239,8 +290,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
239
290
|
) {
|
|
240
291
|
const state = result[0]?.state as string; // could be null?
|
|
241
292
|
|
|
242
|
-
this
|
|
243
|
-
return this
|
|
293
|
+
this._state = JSON.parse(state);
|
|
294
|
+
return this._state;
|
|
244
295
|
}
|
|
245
296
|
|
|
246
297
|
// ok, this is the first time the state is being accessed
|
|
@@ -301,7 +352,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
301
352
|
`;
|
|
302
353
|
|
|
303
354
|
void this.ctx.blockConcurrencyWhile(async () => {
|
|
304
|
-
return this
|
|
355
|
+
return this._tryCatch(async () => {
|
|
305
356
|
// Create alarms table if it doesn't exist
|
|
306
357
|
this.sql`
|
|
307
358
|
CREATE TABLE IF NOT EXISTS cf_agents_schedules (
|
|
@@ -321,13 +372,53 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
321
372
|
});
|
|
322
373
|
});
|
|
323
374
|
|
|
375
|
+
this.sql`
|
|
376
|
+
CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
|
|
377
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
378
|
+
name TEXT NOT NULL,
|
|
379
|
+
server_url TEXT NOT NULL,
|
|
380
|
+
callback_url TEXT NOT NULL,
|
|
381
|
+
client_id TEXT,
|
|
382
|
+
auth_url TEXT,
|
|
383
|
+
server_options TEXT
|
|
384
|
+
)
|
|
385
|
+
`;
|
|
386
|
+
|
|
387
|
+
const _onRequest = this.onRequest.bind(this);
|
|
388
|
+
this.onRequest = (request: Request) => {
|
|
389
|
+
return agentContext.run(
|
|
390
|
+
{ agent: this, connection: undefined, request },
|
|
391
|
+
async () => {
|
|
392
|
+
if (this.mcp.isCallbackRequest(request)) {
|
|
393
|
+
await this.mcp.handleCallbackRequest(request);
|
|
394
|
+
|
|
395
|
+
// after the MCP connection handshake, we can send updated mcp state
|
|
396
|
+
this.broadcast(
|
|
397
|
+
JSON.stringify({
|
|
398
|
+
type: "cf_agent_mcp_servers",
|
|
399
|
+
mcp: this.#getMcpServerStateInternal(),
|
|
400
|
+
})
|
|
401
|
+
);
|
|
402
|
+
|
|
403
|
+
// We probably should let the user configure this response/redirect, but this is fine for now.
|
|
404
|
+
return new Response("<script>window.close();</script>", {
|
|
405
|
+
status: 200,
|
|
406
|
+
headers: { "content-type": "text/html" },
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
return this._tryCatch(() => _onRequest(request));
|
|
411
|
+
}
|
|
412
|
+
);
|
|
413
|
+
};
|
|
414
|
+
|
|
324
415
|
const _onMessage = this.onMessage.bind(this);
|
|
325
416
|
this.onMessage = async (connection: Connection, message: WSMessage) => {
|
|
326
417
|
return agentContext.run(
|
|
327
418
|
{ agent: this, connection, request: undefined },
|
|
328
419
|
async () => {
|
|
329
420
|
if (typeof message !== "string") {
|
|
330
|
-
return this
|
|
421
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
331
422
|
}
|
|
332
423
|
|
|
333
424
|
let parsed: unknown;
|
|
@@ -335,11 +426,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
335
426
|
parsed = JSON.parse(message);
|
|
336
427
|
} catch (e) {
|
|
337
428
|
// silently fail and let the onMessage handler handle it
|
|
338
|
-
return this
|
|
429
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
339
430
|
}
|
|
340
431
|
|
|
341
432
|
if (isStateUpdateMessage(parsed)) {
|
|
342
|
-
this
|
|
433
|
+
this._setStateInternal(parsed.state as State, connection);
|
|
343
434
|
return;
|
|
344
435
|
}
|
|
345
436
|
|
|
@@ -353,7 +444,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
353
444
|
throw new Error(`Method ${method} does not exist`);
|
|
354
445
|
}
|
|
355
446
|
|
|
356
|
-
if (!this
|
|
447
|
+
if (!this._isCallable(method)) {
|
|
357
448
|
throw new Error(`Method ${method} is not callable`);
|
|
358
449
|
}
|
|
359
450
|
|
|
@@ -392,7 +483,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
392
483
|
return;
|
|
393
484
|
}
|
|
394
485
|
|
|
395
|
-
return this
|
|
486
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
396
487
|
}
|
|
397
488
|
);
|
|
398
489
|
};
|
|
@@ -413,15 +504,65 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
413
504
|
})
|
|
414
505
|
);
|
|
415
506
|
}
|
|
416
|
-
|
|
507
|
+
|
|
508
|
+
connection.send(
|
|
509
|
+
JSON.stringify({
|
|
510
|
+
type: "cf_agent_mcp_servers",
|
|
511
|
+
mcp: this.#getMcpServerStateInternal(),
|
|
512
|
+
})
|
|
513
|
+
);
|
|
514
|
+
|
|
515
|
+
return this._tryCatch(() => _onConnect(connection, ctx));
|
|
417
516
|
}, 20);
|
|
418
517
|
}
|
|
419
518
|
);
|
|
420
519
|
};
|
|
520
|
+
|
|
521
|
+
const _onStart = this.onStart.bind(this);
|
|
522
|
+
this.onStart = async () => {
|
|
523
|
+
return agentContext.run(
|
|
524
|
+
{ agent: this, connection: undefined, request: undefined },
|
|
525
|
+
async () => {
|
|
526
|
+
const servers = this.sql<MCPServerRow>`
|
|
527
|
+
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
528
|
+
`;
|
|
529
|
+
|
|
530
|
+
// from DO storage, reconnect to all servers using our saved auth information
|
|
531
|
+
await Promise.allSettled(
|
|
532
|
+
servers.map((server) => {
|
|
533
|
+
return this.#connectToMcpServerInternal(
|
|
534
|
+
server.name,
|
|
535
|
+
server.server_url,
|
|
536
|
+
server.callback_url,
|
|
537
|
+
server.server_options
|
|
538
|
+
? JSON.parse(server.server_options)
|
|
539
|
+
: undefined,
|
|
540
|
+
{
|
|
541
|
+
id: server.id,
|
|
542
|
+
oauthClientId: server.client_id ?? undefined,
|
|
543
|
+
}
|
|
544
|
+
);
|
|
545
|
+
})
|
|
546
|
+
);
|
|
547
|
+
|
|
548
|
+
this.broadcast(
|
|
549
|
+
JSON.stringify({
|
|
550
|
+
type: "cf_agent_mcp_servers",
|
|
551
|
+
mcp: this.#getMcpServerStateInternal(),
|
|
552
|
+
})
|
|
553
|
+
);
|
|
554
|
+
|
|
555
|
+
await this._tryCatch(() => _onStart());
|
|
556
|
+
}
|
|
557
|
+
);
|
|
558
|
+
};
|
|
421
559
|
}
|
|
422
560
|
|
|
423
|
-
|
|
424
|
-
|
|
561
|
+
private _setStateInternal(
|
|
562
|
+
state: State,
|
|
563
|
+
source: Connection | "server" = "server"
|
|
564
|
+
) {
|
|
565
|
+
this._state = state;
|
|
425
566
|
this.sql`
|
|
426
567
|
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
427
568
|
VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
|
|
@@ -437,7 +578,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
437
578
|
}),
|
|
438
579
|
source !== "server" ? [source.id] : []
|
|
439
580
|
);
|
|
440
|
-
return this
|
|
581
|
+
return this._tryCatch(() => {
|
|
441
582
|
const { connection, request } = agentContext.getStore() || {};
|
|
442
583
|
return agentContext.run(
|
|
443
584
|
{ agent: this, connection, request },
|
|
@@ -453,7 +594,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
453
594
|
* @param state New state to set
|
|
454
595
|
*/
|
|
455
596
|
setState(state: State) {
|
|
456
|
-
this
|
|
597
|
+
this._setStateInternal(state, "server");
|
|
457
598
|
}
|
|
458
599
|
|
|
459
600
|
/**
|
|
@@ -478,7 +619,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
478
619
|
);
|
|
479
620
|
}
|
|
480
621
|
|
|
481
|
-
async
|
|
622
|
+
private async _tryCatch<T>(fn: () => T | Promise<T>) {
|
|
482
623
|
try {
|
|
483
624
|
return await fn();
|
|
484
625
|
} catch (e) {
|
|
@@ -552,7 +693,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
552
693
|
)}, 'scheduled', ${timestamp})
|
|
553
694
|
`;
|
|
554
695
|
|
|
555
|
-
await this
|
|
696
|
+
await this._scheduleNextAlarm();
|
|
556
697
|
|
|
557
698
|
return {
|
|
558
699
|
id,
|
|
@@ -573,7 +714,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
573
714
|
)}, 'delayed', ${when}, ${timestamp})
|
|
574
715
|
`;
|
|
575
716
|
|
|
576
|
-
await this
|
|
717
|
+
await this._scheduleNextAlarm();
|
|
577
718
|
|
|
578
719
|
return {
|
|
579
720
|
id,
|
|
@@ -595,7 +736,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
595
736
|
)}, 'cron', ${when}, ${timestamp})
|
|
596
737
|
`;
|
|
597
738
|
|
|
598
|
-
await this
|
|
739
|
+
await this._scheduleNextAlarm();
|
|
599
740
|
|
|
600
741
|
return {
|
|
601
742
|
id,
|
|
@@ -682,11 +823,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
682
823
|
async cancelSchedule(id: string): Promise<boolean> {
|
|
683
824
|
this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
|
|
684
825
|
|
|
685
|
-
await this
|
|
826
|
+
await this._scheduleNextAlarm();
|
|
686
827
|
return true;
|
|
687
828
|
}
|
|
688
829
|
|
|
689
|
-
async
|
|
830
|
+
private async _scheduleNextAlarm() {
|
|
690
831
|
// Find the next schedule that needs to be executed
|
|
691
832
|
const result = this.sql`
|
|
692
833
|
SELECT time FROM cf_agents_schedules
|
|
@@ -703,10 +844,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
703
844
|
}
|
|
704
845
|
|
|
705
846
|
/**
|
|
706
|
-
* Method called when an alarm fires
|
|
707
|
-
* Executes any scheduled tasks that are due
|
|
847
|
+
* Method called when an alarm fires.
|
|
848
|
+
* Executes any scheduled tasks that are due.
|
|
849
|
+
*
|
|
850
|
+
* @remarks
|
|
851
|
+
* To schedule a task, please use the `this.schedule` method instead.
|
|
852
|
+
* See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
|
|
708
853
|
*/
|
|
709
|
-
async
|
|
854
|
+
public readonly alarm = async () => {
|
|
710
855
|
const now = Math.floor(Date.now() / 1000);
|
|
711
856
|
|
|
712
857
|
// Get all schedules that should be executed now
|
|
@@ -752,8 +897,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
752
897
|
}
|
|
753
898
|
|
|
754
899
|
// Schedule the next alarm
|
|
755
|
-
await this
|
|
756
|
-
}
|
|
900
|
+
await this._scheduleNextAlarm();
|
|
901
|
+
};
|
|
757
902
|
|
|
758
903
|
/**
|
|
759
904
|
* Destroy the Agent, removing all state and scheduled tasks
|
|
@@ -762,20 +907,176 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
762
907
|
// drop all tables
|
|
763
908
|
this.sql`DROP TABLE IF EXISTS cf_agents_state`;
|
|
764
909
|
this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
|
|
910
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
|
|
765
911
|
|
|
766
912
|
// delete all alarms
|
|
767
913
|
await this.ctx.storage.deleteAlarm();
|
|
768
914
|
await this.ctx.storage.deleteAll();
|
|
769
915
|
}
|
|
770
916
|
|
|
771
|
-
|
|
772
|
-
* Get all methods marked as callable on this Agent
|
|
773
|
-
* @returns A map of method names to their metadata
|
|
774
|
-
*/
|
|
775
|
-
#isCallable(method: string): boolean {
|
|
917
|
+
private _isCallable(method: string): boolean {
|
|
776
918
|
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
777
919
|
return callableMetadata.has(this[method as keyof this] as Function);
|
|
778
920
|
}
|
|
921
|
+
|
|
922
|
+
/**
|
|
923
|
+
* Connect to a new MCP Server
|
|
924
|
+
*
|
|
925
|
+
* @param url MCP Server SSE URL
|
|
926
|
+
* @param callbackHost Base host for the agent, used for the redirect URI.
|
|
927
|
+
* @param agentsPrefix agents routing prefix if not using `agents`
|
|
928
|
+
* @param options MCP client and transport (header) options
|
|
929
|
+
* @returns authUrl
|
|
930
|
+
*/
|
|
931
|
+
async addMcpServer(
|
|
932
|
+
serverName: string,
|
|
933
|
+
url: string,
|
|
934
|
+
callbackHost: string,
|
|
935
|
+
agentsPrefix = "agents",
|
|
936
|
+
options?: {
|
|
937
|
+
client?: ConstructorParameters<typeof Client>[1];
|
|
938
|
+
transport?: {
|
|
939
|
+
headers: HeadersInit;
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
): Promise<{ id: string; authUrl: string | undefined }> {
|
|
943
|
+
const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
|
|
944
|
+
|
|
945
|
+
const result = await this.#connectToMcpServerInternal(
|
|
946
|
+
serverName,
|
|
947
|
+
url,
|
|
948
|
+
callbackUrl,
|
|
949
|
+
options
|
|
950
|
+
);
|
|
951
|
+
|
|
952
|
+
this.broadcast(
|
|
953
|
+
JSON.stringify({
|
|
954
|
+
type: "cf_agent_mcp_servers",
|
|
955
|
+
mcp: this.#getMcpServerStateInternal(),
|
|
956
|
+
})
|
|
957
|
+
);
|
|
958
|
+
|
|
959
|
+
return result;
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
async #connectToMcpServerInternal(
|
|
963
|
+
serverName: string,
|
|
964
|
+
url: string,
|
|
965
|
+
callbackUrl: string,
|
|
966
|
+
// it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
|
|
967
|
+
options?: {
|
|
968
|
+
client?: ConstructorParameters<typeof Client>[1];
|
|
969
|
+
/**
|
|
970
|
+
* We don't expose the normal set of transport options because:
|
|
971
|
+
* 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
|
|
972
|
+
* 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
|
|
973
|
+
*
|
|
974
|
+
* This has the limitation that you can't override fetch, but I think headers should handle nearly all cases needed (i.e. non-standard bearer auth).
|
|
975
|
+
*/
|
|
976
|
+
transport?: {
|
|
977
|
+
headers?: HeadersInit;
|
|
978
|
+
};
|
|
979
|
+
},
|
|
980
|
+
reconnect?: {
|
|
981
|
+
id: string;
|
|
982
|
+
oauthClientId?: string;
|
|
983
|
+
}
|
|
984
|
+
): Promise<{ id: string; authUrl: string | undefined }> {
|
|
985
|
+
const authProvider = new DurableObjectOAuthClientProvider(
|
|
986
|
+
this.ctx.storage,
|
|
987
|
+
this.name,
|
|
988
|
+
callbackUrl
|
|
989
|
+
);
|
|
990
|
+
|
|
991
|
+
if (reconnect) {
|
|
992
|
+
authProvider.serverId = reconnect.id;
|
|
993
|
+
if (reconnect.oauthClientId) {
|
|
994
|
+
authProvider.clientId = reconnect.oauthClientId;
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
// allows passing through transport headers if necessary
|
|
999
|
+
// this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)
|
|
1000
|
+
let headerTransportOpts: SSEClientTransportOptions = {};
|
|
1001
|
+
if (options?.transport?.headers) {
|
|
1002
|
+
headerTransportOpts = {
|
|
1003
|
+
eventSourceInit: {
|
|
1004
|
+
fetch: (url, init) =>
|
|
1005
|
+
fetch(url, {
|
|
1006
|
+
...init,
|
|
1007
|
+
headers: options?.transport?.headers,
|
|
1008
|
+
}),
|
|
1009
|
+
},
|
|
1010
|
+
requestInit: {
|
|
1011
|
+
headers: options?.transport?.headers,
|
|
1012
|
+
},
|
|
1013
|
+
};
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
const { id, authUrl, clientId } = await this.mcp.connect(url, {
|
|
1017
|
+
reconnect,
|
|
1018
|
+
transport: {
|
|
1019
|
+
...headerTransportOpts,
|
|
1020
|
+
authProvider,
|
|
1021
|
+
},
|
|
1022
|
+
client: options?.client,
|
|
1023
|
+
});
|
|
1024
|
+
|
|
1025
|
+
this.sql`
|
|
1026
|
+
INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
|
|
1027
|
+
VALUES (
|
|
1028
|
+
${id},
|
|
1029
|
+
${serverName},
|
|
1030
|
+
${url},
|
|
1031
|
+
${clientId ?? null},
|
|
1032
|
+
${authUrl ?? null},
|
|
1033
|
+
${callbackUrl},
|
|
1034
|
+
${options ? JSON.stringify(options) : null}
|
|
1035
|
+
);
|
|
1036
|
+
`;
|
|
1037
|
+
|
|
1038
|
+
return {
|
|
1039
|
+
id,
|
|
1040
|
+
authUrl,
|
|
1041
|
+
};
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
async removeMcpServer(id: string) {
|
|
1045
|
+
this.mcp.closeConnection(id);
|
|
1046
|
+
this.sql`
|
|
1047
|
+
DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
|
|
1048
|
+
`;
|
|
1049
|
+
this.broadcast(
|
|
1050
|
+
JSON.stringify({
|
|
1051
|
+
type: "cf_agent_mcp_servers",
|
|
1052
|
+
mcp: this.#getMcpServerStateInternal(),
|
|
1053
|
+
})
|
|
1054
|
+
);
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
#getMcpServerStateInternal(): MCPServersState {
|
|
1058
|
+
const mcpState: MCPServersState = {
|
|
1059
|
+
servers: {},
|
|
1060
|
+
tools: this.mcp.listTools(),
|
|
1061
|
+
prompts: this.mcp.listPrompts(),
|
|
1062
|
+
resources: this.mcp.listResources(),
|
|
1063
|
+
};
|
|
1064
|
+
|
|
1065
|
+
const servers = this.sql<MCPServerRow>`
|
|
1066
|
+
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
1067
|
+
`;
|
|
1068
|
+
|
|
1069
|
+
for (const server of servers) {
|
|
1070
|
+
mcpState.servers[server.id] = {
|
|
1071
|
+
name: server.name,
|
|
1072
|
+
server_url: server.server_url,
|
|
1073
|
+
auth_url: server.auth_url,
|
|
1074
|
+
state: this.mcp.mcpConnections[server.id].connectionState,
|
|
1075
|
+
};
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
return mcpState;
|
|
1079
|
+
}
|
|
779
1080
|
}
|
|
780
1081
|
|
|
781
1082
|
/**
|
|
@@ -879,7 +1180,7 @@ export async function routeAgentEmail<Env>(
|
|
|
879
1180
|
* @param options Options for Agent creation
|
|
880
1181
|
* @returns Promise resolving to an Agent instance stub
|
|
881
1182
|
*/
|
|
882
|
-
export function getAgentByName<Env, T extends Agent<Env>>(
|
|
1183
|
+
export async function getAgentByName<Env, T extends Agent<Env>>(
|
|
883
1184
|
namespace: AgentNamespace<T>,
|
|
884
1185
|
name: string,
|
|
885
1186
|
options?: {
|
|
@@ -894,13 +1195,13 @@ export function getAgentByName<Env, T extends Agent<Env>>(
|
|
|
894
1195
|
* A wrapper for streaming responses in callable methods
|
|
895
1196
|
*/
|
|
896
1197
|
export class StreamingResponse {
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
1198
|
+
private _connection: Connection;
|
|
1199
|
+
private _id: string;
|
|
1200
|
+
private _closed = false;
|
|
900
1201
|
|
|
901
1202
|
constructor(connection: Connection, id: string) {
|
|
902
|
-
this
|
|
903
|
-
this
|
|
1203
|
+
this._connection = connection;
|
|
1204
|
+
this._id = id;
|
|
904
1205
|
}
|
|
905
1206
|
|
|
906
1207
|
/**
|
|
@@ -908,17 +1209,17 @@ export class StreamingResponse {
|
|
|
908
1209
|
* @param chunk The data to send
|
|
909
1210
|
*/
|
|
910
1211
|
send(chunk: unknown) {
|
|
911
|
-
if (this
|
|
1212
|
+
if (this._closed) {
|
|
912
1213
|
throw new Error("StreamingResponse is already closed");
|
|
913
1214
|
}
|
|
914
1215
|
const response: RPCResponse = {
|
|
915
1216
|
type: "rpc",
|
|
916
|
-
id: this
|
|
1217
|
+
id: this._id,
|
|
917
1218
|
success: true,
|
|
918
1219
|
result: chunk,
|
|
919
1220
|
done: false,
|
|
920
1221
|
};
|
|
921
|
-
this
|
|
1222
|
+
this._connection.send(JSON.stringify(response));
|
|
922
1223
|
}
|
|
923
1224
|
|
|
924
1225
|
/**
|
|
@@ -926,17 +1227,17 @@ export class StreamingResponse {
|
|
|
926
1227
|
* @param finalChunk Optional final chunk of data to send
|
|
927
1228
|
*/
|
|
928
1229
|
end(finalChunk?: unknown) {
|
|
929
|
-
if (this
|
|
1230
|
+
if (this._closed) {
|
|
930
1231
|
throw new Error("StreamingResponse is already closed");
|
|
931
1232
|
}
|
|
932
|
-
this
|
|
1233
|
+
this._closed = true;
|
|
933
1234
|
const response: RPCResponse = {
|
|
934
1235
|
type: "rpc",
|
|
935
|
-
id: this
|
|
1236
|
+
id: this._id,
|
|
936
1237
|
success: true,
|
|
937
1238
|
result: finalChunk,
|
|
938
1239
|
done: true,
|
|
939
1240
|
};
|
|
940
|
-
this
|
|
1241
|
+
this._connection.send(JSON.stringify(response));
|
|
941
1242
|
}
|
|
942
1243
|
}
|
|
@@ -1 +0,0 @@
|
|
|
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,GAAG;AAAA,QACH,SAAS;AAAA,UACP,GAAG,WAAW;AAAA,UACd,GAAG;AAAA,QACL;AAAA,MACF;AAIA,aAAO,cAAc;AAGrB,aAAO,MAAM,UAAU,aAAa;AAAA,IACtC;AAEA,UAAM,KAAK;AAAA,MACT,GAAG;AAAA,MACH,iBAAiB;AAAA,QACf,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;A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