agents 0.0.0-b342dcf → 0.0.0-b803d5e
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 +99 -103
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-react.d.ts +12 -0
- package/dist/ai-react.js +1 -2
- 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-UAKVEVG5.js → chunk-J6T74FUS.js} +313 -136
- package/dist/chunk-J6T74FUS.js.map +1 -0
- package/dist/chunk-QSGN3REV.js +123 -0
- package/dist/chunk-QSGN3REV.js.map +1 -0
- package/dist/{chunk-WNICV3OI.js → chunk-Y67CHZBI.js} +53 -25
- package/dist/chunk-Y67CHZBI.js.map +1 -0
- package/dist/client.d.ts +9 -1
- package/dist/client.js +6 -126
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +105 -8
- package/dist/index.js +4 -3
- package/dist/mcp/client.d.ts +30 -15
- package/dist/mcp/client.js +1 -2
- package/dist/mcp/do-oauth-client-provider.d.ts +3 -3
- package/dist/mcp/do-oauth-client-provider.js +3 -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 +106 -135
- package/dist/mcp/index.js.map +1 -1
- package/dist/react.d.ts +72 -0
- package/dist/react.js +14 -2
- package/dist/react.js.map +1 -1
- package/dist/schedule.js +0 -2
- package/dist/schedule.js.map +1 -1
- package/package.json +12 -8
- package/src/index.ts +360 -50
- package/dist/chunk-HMLY7DHA.js +0 -16
- package/dist/chunk-HMLY7DHA.js.map +0 -1
- package/dist/chunk-UAKVEVG5.js.map +0 -1
- package/dist/chunk-WNICV3OI.js.map +0 -1
package/src/index.ts
CHANGED
|
@@ -13,6 +13,21 @@ 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
|
+
ServerCapabilities,
|
|
25
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
26
|
+
|
|
27
|
+
import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
28
|
+
import type { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
29
|
+
|
|
30
|
+
import { camelCaseToKebabCase } from "./client";
|
|
16
31
|
|
|
17
32
|
export type { Connection, WSMessage, ConnectionContext } from "partyserver";
|
|
18
33
|
|
|
@@ -98,7 +113,6 @@ export type CallableMetadata = {
|
|
|
98
113
|
streaming?: boolean;
|
|
99
114
|
};
|
|
100
115
|
|
|
101
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
102
116
|
const callableMetadata = new Map<Function, CallableMetadata>();
|
|
103
117
|
|
|
104
118
|
/**
|
|
@@ -159,6 +173,45 @@ 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
|
+
instructions: string | null;
|
|
199
|
+
capabilities: ServerCapabilities | null;
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* MCP Server data stored in DO SQL for resuming MCP Server connections
|
|
204
|
+
*/
|
|
205
|
+
type MCPServerRow = {
|
|
206
|
+
id: string;
|
|
207
|
+
name: string;
|
|
208
|
+
server_url: string;
|
|
209
|
+
client_id: string | null;
|
|
210
|
+
auth_url: string | null;
|
|
211
|
+
callback_url: string;
|
|
212
|
+
server_options: string;
|
|
213
|
+
};
|
|
214
|
+
|
|
162
215
|
const STATE_ROW_ID = "cf_state_row_id";
|
|
163
216
|
const STATE_WAS_CHANGED = "cf_state_was_changed";
|
|
164
217
|
|
|
@@ -173,7 +226,7 @@ const agentContext = new AsyncLocalStorage<{
|
|
|
173
226
|
export function getCurrentAgent<
|
|
174
227
|
T extends Agent<unknown, unknown> = Agent<unknown, unknown>,
|
|
175
228
|
>(): {
|
|
176
|
-
agent: T;
|
|
229
|
+
agent: T | undefined;
|
|
177
230
|
connection: Connection | undefined;
|
|
178
231
|
request: Request<unknown, CfProperties<unknown>> | undefined;
|
|
179
232
|
} {
|
|
@@ -185,9 +238,11 @@ export function getCurrentAgent<
|
|
|
185
238
|
}
|
|
186
239
|
| undefined;
|
|
187
240
|
if (!store) {
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
241
|
+
return {
|
|
242
|
+
agent: undefined,
|
|
243
|
+
connection: undefined,
|
|
244
|
+
request: undefined,
|
|
245
|
+
};
|
|
191
246
|
}
|
|
192
247
|
return store;
|
|
193
248
|
}
|
|
@@ -198,12 +253,12 @@ export function getCurrentAgent<
|
|
|
198
253
|
* @template State State type to store within the Agent
|
|
199
254
|
*/
|
|
200
255
|
export class Agent<Env, State = unknown> extends Server<Env> {
|
|
201
|
-
|
|
256
|
+
private _state = DEFAULT_STATE as State;
|
|
202
257
|
|
|
203
|
-
|
|
258
|
+
private _ParentClass: typeof Agent<Env, State> =
|
|
204
259
|
Object.getPrototypeOf(this).constructor;
|
|
205
260
|
|
|
206
|
-
mcp: MCPClientManager = new MCPClientManager(this
|
|
261
|
+
mcp: MCPClientManager = new MCPClientManager(this._ParentClass.name, "0.0.1");
|
|
207
262
|
|
|
208
263
|
/**
|
|
209
264
|
* Initial state for the Agent
|
|
@@ -215,9 +270,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
215
270
|
* Current state of the Agent
|
|
216
271
|
*/
|
|
217
272
|
get state(): State {
|
|
218
|
-
if (this
|
|
273
|
+
if (this._state !== DEFAULT_STATE) {
|
|
219
274
|
// state was previously set, and populated internal state
|
|
220
|
-
return this
|
|
275
|
+
return this._state;
|
|
221
276
|
}
|
|
222
277
|
// looks like this is the first time the state is being accessed
|
|
223
278
|
// check if the state was set in a previous life
|
|
@@ -237,8 +292,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
237
292
|
) {
|
|
238
293
|
const state = result[0]?.state as string; // could be null?
|
|
239
294
|
|
|
240
|
-
this
|
|
241
|
-
return this
|
|
295
|
+
this._state = JSON.parse(state);
|
|
296
|
+
return this._state;
|
|
242
297
|
}
|
|
243
298
|
|
|
244
299
|
// ok, this is the first time the state is being accessed
|
|
@@ -299,7 +354,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
299
354
|
`;
|
|
300
355
|
|
|
301
356
|
void this.ctx.blockConcurrencyWhile(async () => {
|
|
302
|
-
return this
|
|
357
|
+
return this._tryCatch(async () => {
|
|
303
358
|
// Create alarms table if it doesn't exist
|
|
304
359
|
this.sql`
|
|
305
360
|
CREATE TABLE IF NOT EXISTS cf_agents_schedules (
|
|
@@ -319,13 +374,53 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
319
374
|
});
|
|
320
375
|
});
|
|
321
376
|
|
|
377
|
+
this.sql`
|
|
378
|
+
CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
|
|
379
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
380
|
+
name TEXT NOT NULL,
|
|
381
|
+
server_url TEXT NOT NULL,
|
|
382
|
+
callback_url TEXT NOT NULL,
|
|
383
|
+
client_id TEXT,
|
|
384
|
+
auth_url TEXT,
|
|
385
|
+
server_options TEXT
|
|
386
|
+
)
|
|
387
|
+
`;
|
|
388
|
+
|
|
389
|
+
const _onRequest = this.onRequest.bind(this);
|
|
390
|
+
this.onRequest = (request: Request) => {
|
|
391
|
+
return agentContext.run(
|
|
392
|
+
{ agent: this, connection: undefined, request },
|
|
393
|
+
async () => {
|
|
394
|
+
if (this.mcp.isCallbackRequest(request)) {
|
|
395
|
+
await this.mcp.handleCallbackRequest(request);
|
|
396
|
+
|
|
397
|
+
// after the MCP connection handshake, we can send updated mcp state
|
|
398
|
+
this.broadcast(
|
|
399
|
+
JSON.stringify({
|
|
400
|
+
type: "cf_agent_mcp_servers",
|
|
401
|
+
mcp: this.getMcpServers(),
|
|
402
|
+
})
|
|
403
|
+
);
|
|
404
|
+
|
|
405
|
+
// We probably should let the user configure this response/redirect, but this is fine for now.
|
|
406
|
+
return new Response("<script>window.close();</script>", {
|
|
407
|
+
status: 200,
|
|
408
|
+
headers: { "content-type": "text/html" },
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
return this._tryCatch(() => _onRequest(request));
|
|
413
|
+
}
|
|
414
|
+
);
|
|
415
|
+
};
|
|
416
|
+
|
|
322
417
|
const _onMessage = this.onMessage.bind(this);
|
|
323
418
|
this.onMessage = async (connection: Connection, message: WSMessage) => {
|
|
324
419
|
return agentContext.run(
|
|
325
420
|
{ agent: this, connection, request: undefined },
|
|
326
421
|
async () => {
|
|
327
422
|
if (typeof message !== "string") {
|
|
328
|
-
return this
|
|
423
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
329
424
|
}
|
|
330
425
|
|
|
331
426
|
let parsed: unknown;
|
|
@@ -333,11 +428,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
333
428
|
parsed = JSON.parse(message);
|
|
334
429
|
} catch (e) {
|
|
335
430
|
// silently fail and let the onMessage handler handle it
|
|
336
|
-
return this
|
|
431
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
337
432
|
}
|
|
338
433
|
|
|
339
434
|
if (isStateUpdateMessage(parsed)) {
|
|
340
|
-
this
|
|
435
|
+
this._setStateInternal(parsed.state as State, connection);
|
|
341
436
|
return;
|
|
342
437
|
}
|
|
343
438
|
|
|
@@ -351,11 +446,10 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
351
446
|
throw new Error(`Method ${method} does not exist`);
|
|
352
447
|
}
|
|
353
448
|
|
|
354
|
-
if (!this
|
|
449
|
+
if (!this._isCallable(method)) {
|
|
355
450
|
throw new Error(`Method ${method} is not callable`);
|
|
356
451
|
}
|
|
357
452
|
|
|
358
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
359
453
|
const metadata = callableMetadata.get(methodFn as Function);
|
|
360
454
|
|
|
361
455
|
// For streaming methods, pass a StreamingResponse object
|
|
@@ -390,7 +484,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
390
484
|
return;
|
|
391
485
|
}
|
|
392
486
|
|
|
393
|
-
return this
|
|
487
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
394
488
|
}
|
|
395
489
|
);
|
|
396
490
|
};
|
|
@@ -411,15 +505,65 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
411
505
|
})
|
|
412
506
|
);
|
|
413
507
|
}
|
|
414
|
-
|
|
508
|
+
|
|
509
|
+
connection.send(
|
|
510
|
+
JSON.stringify({
|
|
511
|
+
type: "cf_agent_mcp_servers",
|
|
512
|
+
mcp: this.getMcpServers(),
|
|
513
|
+
})
|
|
514
|
+
);
|
|
515
|
+
|
|
516
|
+
return this._tryCatch(() => _onConnect(connection, ctx));
|
|
415
517
|
}, 20);
|
|
416
518
|
}
|
|
417
519
|
);
|
|
418
520
|
};
|
|
521
|
+
|
|
522
|
+
const _onStart = this.onStart.bind(this);
|
|
523
|
+
this.onStart = async () => {
|
|
524
|
+
return agentContext.run(
|
|
525
|
+
{ agent: this, connection: undefined, request: undefined },
|
|
526
|
+
async () => {
|
|
527
|
+
const servers = this.sql<MCPServerRow>`
|
|
528
|
+
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
529
|
+
`;
|
|
530
|
+
|
|
531
|
+
// from DO storage, reconnect to all servers using our saved auth information
|
|
532
|
+
await Promise.allSettled(
|
|
533
|
+
servers.map((server) => {
|
|
534
|
+
return this._connectToMcpServerInternal(
|
|
535
|
+
server.name,
|
|
536
|
+
server.server_url,
|
|
537
|
+
server.callback_url,
|
|
538
|
+
server.server_options
|
|
539
|
+
? JSON.parse(server.server_options)
|
|
540
|
+
: undefined,
|
|
541
|
+
{
|
|
542
|
+
id: server.id,
|
|
543
|
+
oauthClientId: server.client_id ?? undefined,
|
|
544
|
+
}
|
|
545
|
+
);
|
|
546
|
+
})
|
|
547
|
+
);
|
|
548
|
+
|
|
549
|
+
this.broadcast(
|
|
550
|
+
JSON.stringify({
|
|
551
|
+
type: "cf_agent_mcp_servers",
|
|
552
|
+
mcp: this.getMcpServers(),
|
|
553
|
+
})
|
|
554
|
+
);
|
|
555
|
+
|
|
556
|
+
await this._tryCatch(() => _onStart());
|
|
557
|
+
}
|
|
558
|
+
);
|
|
559
|
+
};
|
|
419
560
|
}
|
|
420
561
|
|
|
421
|
-
|
|
422
|
-
|
|
562
|
+
private _setStateInternal(
|
|
563
|
+
state: State,
|
|
564
|
+
source: Connection | "server" = "server"
|
|
565
|
+
) {
|
|
566
|
+
this._state = state;
|
|
423
567
|
this.sql`
|
|
424
568
|
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
425
569
|
VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
|
|
@@ -435,7 +579,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
435
579
|
}),
|
|
436
580
|
source !== "server" ? [source.id] : []
|
|
437
581
|
);
|
|
438
|
-
return this
|
|
582
|
+
return this._tryCatch(() => {
|
|
439
583
|
const { connection, request } = agentContext.getStore() || {};
|
|
440
584
|
return agentContext.run(
|
|
441
585
|
{ agent: this, connection, request },
|
|
@@ -451,7 +595,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
451
595
|
* @param state New state to set
|
|
452
596
|
*/
|
|
453
597
|
setState(state: State) {
|
|
454
|
-
this
|
|
598
|
+
this._setStateInternal(state, "server");
|
|
455
599
|
}
|
|
456
600
|
|
|
457
601
|
/**
|
|
@@ -476,7 +620,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
476
620
|
);
|
|
477
621
|
}
|
|
478
622
|
|
|
479
|
-
async
|
|
623
|
+
private async _tryCatch<T>(fn: () => T | Promise<T>) {
|
|
480
624
|
try {
|
|
481
625
|
return await fn();
|
|
482
626
|
} catch (e) {
|
|
@@ -550,7 +694,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
550
694
|
)}, 'scheduled', ${timestamp})
|
|
551
695
|
`;
|
|
552
696
|
|
|
553
|
-
await this
|
|
697
|
+
await this._scheduleNextAlarm();
|
|
554
698
|
|
|
555
699
|
return {
|
|
556
700
|
id,
|
|
@@ -571,7 +715,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
571
715
|
)}, 'delayed', ${when}, ${timestamp})
|
|
572
716
|
`;
|
|
573
717
|
|
|
574
|
-
await this
|
|
718
|
+
await this._scheduleNextAlarm();
|
|
575
719
|
|
|
576
720
|
return {
|
|
577
721
|
id,
|
|
@@ -593,7 +737,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
593
737
|
)}, 'cron', ${when}, ${timestamp})
|
|
594
738
|
`;
|
|
595
739
|
|
|
596
|
-
await this
|
|
740
|
+
await this._scheduleNextAlarm();
|
|
597
741
|
|
|
598
742
|
return {
|
|
599
743
|
id,
|
|
@@ -680,11 +824,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
680
824
|
async cancelSchedule(id: string): Promise<boolean> {
|
|
681
825
|
this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
|
|
682
826
|
|
|
683
|
-
await this
|
|
827
|
+
await this._scheduleNextAlarm();
|
|
684
828
|
return true;
|
|
685
829
|
}
|
|
686
830
|
|
|
687
|
-
async
|
|
831
|
+
private async _scheduleNextAlarm() {
|
|
688
832
|
// Find the next schedule that needs to be executed
|
|
689
833
|
const result = this.sql`
|
|
690
834
|
SELECT time FROM cf_agents_schedules
|
|
@@ -701,10 +845,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
701
845
|
}
|
|
702
846
|
|
|
703
847
|
/**
|
|
704
|
-
* Method called when an alarm fires
|
|
705
|
-
* Executes any scheduled tasks that are due
|
|
848
|
+
* Method called when an alarm fires.
|
|
849
|
+
* Executes any scheduled tasks that are due.
|
|
850
|
+
*
|
|
851
|
+
* @remarks
|
|
852
|
+
* To schedule a task, please use the `this.schedule` method instead.
|
|
853
|
+
* See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
|
|
706
854
|
*/
|
|
707
|
-
async
|
|
855
|
+
public readonly alarm = async () => {
|
|
708
856
|
const now = Math.floor(Date.now() / 1000);
|
|
709
857
|
|
|
710
858
|
// Get all schedules that should be executed now
|
|
@@ -750,8 +898,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
750
898
|
}
|
|
751
899
|
|
|
752
900
|
// Schedule the next alarm
|
|
753
|
-
await this
|
|
754
|
-
}
|
|
901
|
+
await this._scheduleNextAlarm();
|
|
902
|
+
};
|
|
755
903
|
|
|
756
904
|
/**
|
|
757
905
|
* Destroy the Agent, removing all state and scheduled tasks
|
|
@@ -760,6 +908,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
760
908
|
// drop all tables
|
|
761
909
|
this.sql`DROP TABLE IF EXISTS cf_agents_state`;
|
|
762
910
|
this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
|
|
911
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
|
|
763
912
|
|
|
764
913
|
// delete all alarms
|
|
765
914
|
await this.ctx.storage.deleteAlarm();
|
|
@@ -770,10 +919,171 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
770
919
|
* Get all methods marked as callable on this Agent
|
|
771
920
|
* @returns A map of method names to their metadata
|
|
772
921
|
*/
|
|
773
|
-
|
|
774
|
-
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
922
|
+
private _isCallable(method: string): boolean {
|
|
775
923
|
return callableMetadata.has(this[method as keyof this] as Function);
|
|
776
924
|
}
|
|
925
|
+
|
|
926
|
+
/**
|
|
927
|
+
* Connect to a new MCP Server
|
|
928
|
+
*
|
|
929
|
+
* @param url MCP Server SSE URL
|
|
930
|
+
* @param callbackHost Base host for the agent, used for the redirect URI.
|
|
931
|
+
* @param agentsPrefix agents routing prefix if not using `agents`
|
|
932
|
+
* @param options MCP client and transport (header) options
|
|
933
|
+
* @returns authUrl
|
|
934
|
+
*/
|
|
935
|
+
async addMcpServer(
|
|
936
|
+
serverName: string,
|
|
937
|
+
url: string,
|
|
938
|
+
callbackHost: string,
|
|
939
|
+
agentsPrefix = "agents",
|
|
940
|
+
options?: {
|
|
941
|
+
client?: ConstructorParameters<typeof Client>[1];
|
|
942
|
+
transport?: {
|
|
943
|
+
headers: HeadersInit;
|
|
944
|
+
};
|
|
945
|
+
}
|
|
946
|
+
): Promise<{ id: string; authUrl: string | undefined }> {
|
|
947
|
+
const callbackUrl = `${callbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
|
|
948
|
+
|
|
949
|
+
const result = await this._connectToMcpServerInternal(
|
|
950
|
+
serverName,
|
|
951
|
+
url,
|
|
952
|
+
callbackUrl,
|
|
953
|
+
options
|
|
954
|
+
);
|
|
955
|
+
|
|
956
|
+
this.broadcast(
|
|
957
|
+
JSON.stringify({
|
|
958
|
+
type: "cf_agent_mcp_servers",
|
|
959
|
+
mcp: this.getMcpServers(),
|
|
960
|
+
})
|
|
961
|
+
);
|
|
962
|
+
|
|
963
|
+
return result;
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
async _connectToMcpServerInternal(
|
|
967
|
+
serverName: string,
|
|
968
|
+
url: string,
|
|
969
|
+
callbackUrl: string,
|
|
970
|
+
// it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes
|
|
971
|
+
options?: {
|
|
972
|
+
client?: ConstructorParameters<typeof Client>[1];
|
|
973
|
+
/**
|
|
974
|
+
* We don't expose the normal set of transport options because:
|
|
975
|
+
* 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
|
|
976
|
+
* 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
|
|
977
|
+
*
|
|
978
|
+
* 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).
|
|
979
|
+
*/
|
|
980
|
+
transport?: {
|
|
981
|
+
headers?: HeadersInit;
|
|
982
|
+
};
|
|
983
|
+
},
|
|
984
|
+
reconnect?: {
|
|
985
|
+
id: string;
|
|
986
|
+
oauthClientId?: string;
|
|
987
|
+
}
|
|
988
|
+
): Promise<{ id: string; authUrl: string | undefined }> {
|
|
989
|
+
const authProvider = new DurableObjectOAuthClientProvider(
|
|
990
|
+
this.ctx.storage,
|
|
991
|
+
this.name,
|
|
992
|
+
callbackUrl
|
|
993
|
+
);
|
|
994
|
+
|
|
995
|
+
if (reconnect) {
|
|
996
|
+
authProvider.serverId = reconnect.id;
|
|
997
|
+
if (reconnect.oauthClientId) {
|
|
998
|
+
authProvider.clientId = reconnect.oauthClientId;
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
// allows passing through transport headers if necessary
|
|
1003
|
+
// this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)
|
|
1004
|
+
let headerTransportOpts: SSEClientTransportOptions = {};
|
|
1005
|
+
if (options?.transport?.headers) {
|
|
1006
|
+
headerTransportOpts = {
|
|
1007
|
+
eventSourceInit: {
|
|
1008
|
+
fetch: (url, init) =>
|
|
1009
|
+
fetch(url, {
|
|
1010
|
+
...init,
|
|
1011
|
+
headers: options?.transport?.headers,
|
|
1012
|
+
}),
|
|
1013
|
+
},
|
|
1014
|
+
requestInit: {
|
|
1015
|
+
headers: options?.transport?.headers,
|
|
1016
|
+
},
|
|
1017
|
+
};
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
const { id, authUrl, clientId } = await this.mcp.connect(url, {
|
|
1021
|
+
reconnect,
|
|
1022
|
+
transport: {
|
|
1023
|
+
...headerTransportOpts,
|
|
1024
|
+
authProvider,
|
|
1025
|
+
},
|
|
1026
|
+
client: options?.client,
|
|
1027
|
+
});
|
|
1028
|
+
|
|
1029
|
+
this.sql`
|
|
1030
|
+
INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
|
|
1031
|
+
VALUES (
|
|
1032
|
+
${id},
|
|
1033
|
+
${serverName},
|
|
1034
|
+
${url},
|
|
1035
|
+
${clientId ?? null},
|
|
1036
|
+
${authUrl ?? null},
|
|
1037
|
+
${callbackUrl},
|
|
1038
|
+
${options ? JSON.stringify(options) : null}
|
|
1039
|
+
);
|
|
1040
|
+
`;
|
|
1041
|
+
|
|
1042
|
+
return {
|
|
1043
|
+
id,
|
|
1044
|
+
authUrl,
|
|
1045
|
+
};
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
async removeMcpServer(id: string) {
|
|
1049
|
+
this.mcp.closeConnection(id);
|
|
1050
|
+
this.sql`
|
|
1051
|
+
DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
|
|
1052
|
+
`;
|
|
1053
|
+
this.broadcast(
|
|
1054
|
+
JSON.stringify({
|
|
1055
|
+
type: "cf_agent_mcp_servers",
|
|
1056
|
+
mcp: this.getMcpServers(),
|
|
1057
|
+
})
|
|
1058
|
+
);
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
getMcpServers(): MCPServersState {
|
|
1062
|
+
const mcpState: MCPServersState = {
|
|
1063
|
+
servers: {},
|
|
1064
|
+
tools: this.mcp.listTools(),
|
|
1065
|
+
prompts: this.mcp.listPrompts(),
|
|
1066
|
+
resources: this.mcp.listResources(),
|
|
1067
|
+
};
|
|
1068
|
+
|
|
1069
|
+
const servers = this.sql<MCPServerRow>`
|
|
1070
|
+
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
|
|
1071
|
+
`;
|
|
1072
|
+
|
|
1073
|
+
for (const server of servers) {
|
|
1074
|
+
mcpState.servers[server.id] = {
|
|
1075
|
+
name: server.name,
|
|
1076
|
+
server_url: server.server_url,
|
|
1077
|
+
auth_url: server.auth_url,
|
|
1078
|
+
state: this.mcp.mcpConnections[server.id].connectionState,
|
|
1079
|
+
instructions: this.mcp.mcpConnections[server.id].instructions ?? null,
|
|
1080
|
+
capabilities:
|
|
1081
|
+
this.mcp.mcpConnections[server.id].serverCapabilities ?? null,
|
|
1082
|
+
};
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
return mcpState;
|
|
1086
|
+
}
|
|
777
1087
|
}
|
|
778
1088
|
|
|
779
1089
|
/**
|
|
@@ -877,7 +1187,7 @@ export async function routeAgentEmail<Env>(
|
|
|
877
1187
|
* @param options Options for Agent creation
|
|
878
1188
|
* @returns Promise resolving to an Agent instance stub
|
|
879
1189
|
*/
|
|
880
|
-
export function getAgentByName<Env, T extends Agent<Env>>(
|
|
1190
|
+
export async function getAgentByName<Env, T extends Agent<Env>>(
|
|
881
1191
|
namespace: AgentNamespace<T>,
|
|
882
1192
|
name: string,
|
|
883
1193
|
options?: {
|
|
@@ -892,13 +1202,13 @@ export function getAgentByName<Env, T extends Agent<Env>>(
|
|
|
892
1202
|
* A wrapper for streaming responses in callable methods
|
|
893
1203
|
*/
|
|
894
1204
|
export class StreamingResponse {
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
1205
|
+
private _connection: Connection;
|
|
1206
|
+
private _id: string;
|
|
1207
|
+
private _closed = false;
|
|
898
1208
|
|
|
899
1209
|
constructor(connection: Connection, id: string) {
|
|
900
|
-
this
|
|
901
|
-
this
|
|
1210
|
+
this._connection = connection;
|
|
1211
|
+
this._id = id;
|
|
902
1212
|
}
|
|
903
1213
|
|
|
904
1214
|
/**
|
|
@@ -906,17 +1216,17 @@ export class StreamingResponse {
|
|
|
906
1216
|
* @param chunk The data to send
|
|
907
1217
|
*/
|
|
908
1218
|
send(chunk: unknown) {
|
|
909
|
-
if (this
|
|
1219
|
+
if (this._closed) {
|
|
910
1220
|
throw new Error("StreamingResponse is already closed");
|
|
911
1221
|
}
|
|
912
1222
|
const response: RPCResponse = {
|
|
913
1223
|
type: "rpc",
|
|
914
|
-
id: this
|
|
1224
|
+
id: this._id,
|
|
915
1225
|
success: true,
|
|
916
1226
|
result: chunk,
|
|
917
1227
|
done: false,
|
|
918
1228
|
};
|
|
919
|
-
this
|
|
1229
|
+
this._connection.send(JSON.stringify(response));
|
|
920
1230
|
}
|
|
921
1231
|
|
|
922
1232
|
/**
|
|
@@ -924,17 +1234,17 @@ export class StreamingResponse {
|
|
|
924
1234
|
* @param finalChunk Optional final chunk of data to send
|
|
925
1235
|
*/
|
|
926
1236
|
end(finalChunk?: unknown) {
|
|
927
|
-
if (this
|
|
1237
|
+
if (this._closed) {
|
|
928
1238
|
throw new Error("StreamingResponse is already closed");
|
|
929
1239
|
}
|
|
930
|
-
this
|
|
1240
|
+
this._closed = true;
|
|
931
1241
|
const response: RPCResponse = {
|
|
932
1242
|
type: "rpc",
|
|
933
|
-
id: this
|
|
1243
|
+
id: this._id,
|
|
934
1244
|
success: true,
|
|
935
1245
|
result: finalChunk,
|
|
936
1246
|
done: true,
|
|
937
1247
|
};
|
|
938
|
-
this
|
|
1248
|
+
this._connection.send(JSON.stringify(response));
|
|
939
1249
|
}
|
|
940
1250
|
}
|
package/dist/chunk-HMLY7DHA.js
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
var __typeError = (msg) => {
|
|
2
|
-
throw TypeError(msg);
|
|
3
|
-
};
|
|
4
|
-
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
5
|
-
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
|
|
6
|
-
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
7
|
-
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
|
|
8
|
-
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
|
|
9
|
-
|
|
10
|
-
export {
|
|
11
|
-
__privateGet,
|
|
12
|
-
__privateAdd,
|
|
13
|
-
__privateSet,
|
|
14
|
-
__privateMethod
|
|
15
|
-
};
|
|
16
|
-
//# sourceMappingURL=chunk-HMLY7DHA.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|