agents 0.0.0-7c40201 → 0.0.0-7f84d28
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 +49 -4
- package/dist/ai-chat-agent.js +129 -66
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-react.d.ts +12 -0
- package/dist/ai-react.js +38 -24
- package/dist/ai-react.js.map +1 -1
- package/dist/ai-types.d.ts +5 -0
- package/dist/chunk-BZXOAZUX.js +106 -0
- package/dist/chunk-BZXOAZUX.js.map +1 -0
- package/dist/chunk-QSGN3REV.js +123 -0
- package/dist/chunk-QSGN3REV.js.map +1 -0
- package/dist/{chunk-KRBQHBPA.js → chunk-RIYR6FR6.js} +319 -141
- package/dist/chunk-RIYR6FR6.js.map +1 -0
- package/dist/chunk-Y67CHZBI.js +464 -0
- package/dist/chunk-Y67CHZBI.js.map +1 -0
- package/dist/client.d.ts +9 -1
- package/dist/client.js +6 -133
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +109 -18
- package/dist/index.js +8 -8
- package/dist/mcp/client.d.ts +783 -0
- package/dist/mcp/client.js +9 -0
- package/dist/mcp/do-oauth-client-provider.d.ts +41 -0
- package/dist/mcp/do-oauth-client-provider.js +7 -0
- package/dist/mcp/do-oauth-client-provider.js.map +1 -0
- package/dist/mcp/index.d.ts +84 -0
- package/dist/mcp/index.js +779 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/react.d.ts +14 -0
- package/dist/react.js +38 -29
- package/dist/react.js.map +1 -1
- package/dist/schedule.js +0 -2
- package/dist/schedule.js.map +1 -1
- package/package.json +36 -8
- package/src/index.ts +383 -65
- package/dist/chunk-HMLY7DHA.js +0 -16
- package/dist/chunk-KRBQHBPA.js.map +0 -1
- package/dist/mcp.d.ts +0 -58
- package/dist/mcp.js +0 -945
- package/dist/mcp.js.map +0 -1
- /package/dist/{chunk-HMLY7DHA.js.map → mcp/client.js.map} +0 -0
package/src/index.ts
CHANGED
|
@@ -12,10 +12,23 @@ import { parseCronExpression } from "cron-schedule";
|
|
|
12
12
|
import { nanoid } from "nanoid";
|
|
13
13
|
|
|
14
14
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
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";
|
|
15
25
|
|
|
16
|
-
|
|
26
|
+
import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
27
|
+
import type { SSEClientTransportOptions } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
17
28
|
|
|
18
|
-
import {
|
|
29
|
+
import { camelCaseToKebabCase } from "./client";
|
|
30
|
+
|
|
31
|
+
export type { Connection, WSMessage, ConnectionContext } from "partyserver";
|
|
19
32
|
|
|
20
33
|
/**
|
|
21
34
|
* RPC request message from client
|
|
@@ -119,11 +132,6 @@ export function unstable_callable(metadata: CallableMetadata = {}) {
|
|
|
119
132
|
};
|
|
120
133
|
}
|
|
121
134
|
|
|
122
|
-
/**
|
|
123
|
-
* A class for creating workflow entry points that can be used with Cloudflare Workers
|
|
124
|
-
*/
|
|
125
|
-
export class WorkflowEntrypoint extends CFWorkflowEntrypoint {}
|
|
126
|
-
|
|
127
135
|
/**
|
|
128
136
|
* Represents a scheduled task within an Agent
|
|
129
137
|
* @template T Type of the payload data
|
|
@@ -165,24 +173,90 @@ function getNextCronTime(cron: string) {
|
|
|
165
173
|
return interval.getNextDate();
|
|
166
174
|
}
|
|
167
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
|
+
|
|
168
213
|
const STATE_ROW_ID = "cf_state_row_id";
|
|
169
214
|
const STATE_WAS_CHANGED = "cf_state_was_changed";
|
|
170
215
|
|
|
171
216
|
const DEFAULT_STATE = {} as unknown;
|
|
172
217
|
|
|
173
|
-
|
|
218
|
+
const agentContext = new AsyncLocalStorage<{
|
|
174
219
|
agent: Agent<unknown>;
|
|
175
220
|
connection: Connection | undefined;
|
|
176
221
|
request: Request | undefined;
|
|
177
222
|
}>();
|
|
178
223
|
|
|
224
|
+
export function getCurrentAgent<
|
|
225
|
+
T extends Agent<unknown, unknown> = Agent<unknown, unknown>,
|
|
226
|
+
>(): {
|
|
227
|
+
agent: T | undefined;
|
|
228
|
+
connection: Connection | undefined;
|
|
229
|
+
request: Request<unknown, CfProperties<unknown>> | undefined;
|
|
230
|
+
} {
|
|
231
|
+
const store = agentContext.getStore() as
|
|
232
|
+
| {
|
|
233
|
+
agent: T;
|
|
234
|
+
connection: Connection | undefined;
|
|
235
|
+
request: Request<unknown, CfProperties<unknown>> | undefined;
|
|
236
|
+
}
|
|
237
|
+
| undefined;
|
|
238
|
+
if (!store) {
|
|
239
|
+
return {
|
|
240
|
+
agent: undefined,
|
|
241
|
+
connection: undefined,
|
|
242
|
+
request: undefined,
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
return store;
|
|
246
|
+
}
|
|
247
|
+
|
|
179
248
|
/**
|
|
180
249
|
* Base class for creating Agent implementations
|
|
181
250
|
* @template Env Environment type containing bindings
|
|
182
251
|
* @template State State type to store within the Agent
|
|
183
252
|
*/
|
|
184
253
|
export class Agent<Env, State = unknown> extends Server<Env> {
|
|
185
|
-
|
|
254
|
+
private _state = DEFAULT_STATE as State;
|
|
255
|
+
|
|
256
|
+
private _ParentClass: typeof Agent<Env, State> =
|
|
257
|
+
Object.getPrototypeOf(this).constructor;
|
|
258
|
+
|
|
259
|
+
mcp: MCPClientManager = new MCPClientManager(this._ParentClass.name, "0.0.1");
|
|
186
260
|
|
|
187
261
|
/**
|
|
188
262
|
* Initial state for the Agent
|
|
@@ -194,9 +268,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
194
268
|
* Current state of the Agent
|
|
195
269
|
*/
|
|
196
270
|
get state(): State {
|
|
197
|
-
if (this
|
|
271
|
+
if (this._state !== DEFAULT_STATE) {
|
|
198
272
|
// state was previously set, and populated internal state
|
|
199
|
-
return this
|
|
273
|
+
return this._state;
|
|
200
274
|
}
|
|
201
275
|
// looks like this is the first time the state is being accessed
|
|
202
276
|
// check if the state was set in a previous life
|
|
@@ -216,8 +290,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
216
290
|
) {
|
|
217
291
|
const state = result[0]?.state as string; // could be null?
|
|
218
292
|
|
|
219
|
-
this
|
|
220
|
-
return this
|
|
293
|
+
this._state = JSON.parse(state);
|
|
294
|
+
return this._state;
|
|
221
295
|
}
|
|
222
296
|
|
|
223
297
|
// ok, this is the first time the state is being accessed
|
|
@@ -278,7 +352,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
278
352
|
`;
|
|
279
353
|
|
|
280
354
|
void this.ctx.blockConcurrencyWhile(async () => {
|
|
281
|
-
return this
|
|
355
|
+
return this._tryCatch(async () => {
|
|
282
356
|
// Create alarms table if it doesn't exist
|
|
283
357
|
this.sql`
|
|
284
358
|
CREATE TABLE IF NOT EXISTS cf_agents_schedules (
|
|
@@ -298,13 +372,53 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
298
372
|
});
|
|
299
373
|
});
|
|
300
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
|
+
|
|
301
415
|
const _onMessage = this.onMessage.bind(this);
|
|
302
416
|
this.onMessage = async (connection: Connection, message: WSMessage) => {
|
|
303
|
-
return
|
|
417
|
+
return agentContext.run(
|
|
304
418
|
{ agent: this, connection, request: undefined },
|
|
305
419
|
async () => {
|
|
306
420
|
if (typeof message !== "string") {
|
|
307
|
-
return this
|
|
421
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
308
422
|
}
|
|
309
423
|
|
|
310
424
|
let parsed: unknown;
|
|
@@ -312,11 +426,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
312
426
|
parsed = JSON.parse(message);
|
|
313
427
|
} catch (e) {
|
|
314
428
|
// silently fail and let the onMessage handler handle it
|
|
315
|
-
return this
|
|
429
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
316
430
|
}
|
|
317
431
|
|
|
318
432
|
if (isStateUpdateMessage(parsed)) {
|
|
319
|
-
this
|
|
433
|
+
this._setStateInternal(parsed.state as State, connection);
|
|
320
434
|
return;
|
|
321
435
|
}
|
|
322
436
|
|
|
@@ -330,7 +444,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
330
444
|
throw new Error(`Method ${method} does not exist`);
|
|
331
445
|
}
|
|
332
446
|
|
|
333
|
-
if (!this
|
|
447
|
+
if (!this._isCallable(method)) {
|
|
334
448
|
throw new Error(`Method ${method} is not callable`);
|
|
335
449
|
}
|
|
336
450
|
|
|
@@ -369,7 +483,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
369
483
|
return;
|
|
370
484
|
}
|
|
371
485
|
|
|
372
|
-
return this
|
|
486
|
+
return this._tryCatch(() => _onMessage(connection, message));
|
|
373
487
|
}
|
|
374
488
|
);
|
|
375
489
|
};
|
|
@@ -378,7 +492,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
378
492
|
this.onConnect = (connection: Connection, ctx: ConnectionContext) => {
|
|
379
493
|
// TODO: This is a hack to ensure the state is sent after the connection is established
|
|
380
494
|
// must fix this
|
|
381
|
-
return
|
|
495
|
+
return agentContext.run(
|
|
382
496
|
{ agent: this, connection, request: ctx.request },
|
|
383
497
|
async () => {
|
|
384
498
|
setTimeout(() => {
|
|
@@ -390,15 +504,65 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
390
504
|
})
|
|
391
505
|
);
|
|
392
506
|
}
|
|
393
|
-
|
|
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));
|
|
394
516
|
}, 20);
|
|
395
517
|
}
|
|
396
518
|
);
|
|
397
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
|
+
};
|
|
398
559
|
}
|
|
399
560
|
|
|
400
|
-
|
|
401
|
-
|
|
561
|
+
private _setStateInternal(
|
|
562
|
+
state: State,
|
|
563
|
+
source: Connection | "server" = "server"
|
|
564
|
+
) {
|
|
565
|
+
this._state = state;
|
|
402
566
|
this.sql`
|
|
403
567
|
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
404
568
|
VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
|
|
@@ -414,9 +578,9 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
414
578
|
}),
|
|
415
579
|
source !== "server" ? [source.id] : []
|
|
416
580
|
);
|
|
417
|
-
return this
|
|
418
|
-
const { connection, request } =
|
|
419
|
-
return
|
|
581
|
+
return this._tryCatch(() => {
|
|
582
|
+
const { connection, request } = agentContext.getStore() || {};
|
|
583
|
+
return agentContext.run(
|
|
420
584
|
{ agent: this, connection, request },
|
|
421
585
|
async () => {
|
|
422
586
|
return this.onStateUpdate(state, source);
|
|
@@ -430,7 +594,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
430
594
|
* @param state New state to set
|
|
431
595
|
*/
|
|
432
596
|
setState(state: State) {
|
|
433
|
-
this
|
|
597
|
+
this._setStateInternal(state, "server");
|
|
434
598
|
}
|
|
435
599
|
|
|
436
600
|
/**
|
|
@@ -447,7 +611,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
447
611
|
* @param email Email message to process
|
|
448
612
|
*/
|
|
449
613
|
onEmail(email: ForwardableEmailMessage) {
|
|
450
|
-
return
|
|
614
|
+
return agentContext.run(
|
|
451
615
|
{ agent: this, connection: undefined, request: undefined },
|
|
452
616
|
async () => {
|
|
453
617
|
console.error("onEmail not implemented");
|
|
@@ -455,7 +619,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
455
619
|
);
|
|
456
620
|
}
|
|
457
621
|
|
|
458
|
-
async
|
|
622
|
+
private async _tryCatch<T>(fn: () => T | Promise<T>) {
|
|
459
623
|
try {
|
|
460
624
|
return await fn();
|
|
461
625
|
} catch (e) {
|
|
@@ -529,7 +693,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
529
693
|
)}, 'scheduled', ${timestamp})
|
|
530
694
|
`;
|
|
531
695
|
|
|
532
|
-
await this
|
|
696
|
+
await this._scheduleNextAlarm();
|
|
533
697
|
|
|
534
698
|
return {
|
|
535
699
|
id,
|
|
@@ -550,7 +714,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
550
714
|
)}, 'delayed', ${when}, ${timestamp})
|
|
551
715
|
`;
|
|
552
716
|
|
|
553
|
-
await this
|
|
717
|
+
await this._scheduleNextAlarm();
|
|
554
718
|
|
|
555
719
|
return {
|
|
556
720
|
id,
|
|
@@ -572,7 +736,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
572
736
|
)}, 'cron', ${when}, ${timestamp})
|
|
573
737
|
`;
|
|
574
738
|
|
|
575
|
-
await this
|
|
739
|
+
await this._scheduleNextAlarm();
|
|
576
740
|
|
|
577
741
|
return {
|
|
578
742
|
id,
|
|
@@ -612,7 +776,6 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
612
776
|
*/
|
|
613
777
|
getSchedules<T = string>(
|
|
614
778
|
criteria: {
|
|
615
|
-
description?: string;
|
|
616
779
|
id?: string;
|
|
617
780
|
type?: "scheduled" | "delayed" | "cron";
|
|
618
781
|
timeRange?: { start?: Date; end?: Date };
|
|
@@ -626,11 +789,6 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
626
789
|
params.push(criteria.id);
|
|
627
790
|
}
|
|
628
791
|
|
|
629
|
-
if (criteria.description) {
|
|
630
|
-
query += " AND description = ?";
|
|
631
|
-
params.push(criteria.description);
|
|
632
|
-
}
|
|
633
|
-
|
|
634
792
|
if (criteria.type) {
|
|
635
793
|
query += " AND type = ?";
|
|
636
794
|
params.push(criteria.type);
|
|
@@ -665,11 +823,11 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
665
823
|
async cancelSchedule(id: string): Promise<boolean> {
|
|
666
824
|
this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
|
|
667
825
|
|
|
668
|
-
await this
|
|
826
|
+
await this._scheduleNextAlarm();
|
|
669
827
|
return true;
|
|
670
828
|
}
|
|
671
829
|
|
|
672
|
-
async
|
|
830
|
+
private async _scheduleNextAlarm() {
|
|
673
831
|
// Find the next schedule that needs to be executed
|
|
674
832
|
const result = this.sql`
|
|
675
833
|
SELECT time FROM cf_agents_schedules
|
|
@@ -686,10 +844,14 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
686
844
|
}
|
|
687
845
|
|
|
688
846
|
/**
|
|
689
|
-
* Method called when an alarm fires
|
|
690
|
-
* 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/}
|
|
691
853
|
*/
|
|
692
|
-
async
|
|
854
|
+
public readonly alarm = async () => {
|
|
693
855
|
const now = Math.floor(Date.now() / 1000);
|
|
694
856
|
|
|
695
857
|
// Get all schedules that should be executed now
|
|
@@ -703,7 +865,7 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
703
865
|
console.error(`callback ${row.callback} not found`);
|
|
704
866
|
continue;
|
|
705
867
|
}
|
|
706
|
-
await
|
|
868
|
+
await agentContext.run(
|
|
707
869
|
{ agent: this, connection: undefined, request: undefined },
|
|
708
870
|
async () => {
|
|
709
871
|
try {
|
|
@@ -735,8 +897,8 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
735
897
|
}
|
|
736
898
|
|
|
737
899
|
// Schedule the next alarm
|
|
738
|
-
await this
|
|
739
|
-
}
|
|
900
|
+
await this._scheduleNextAlarm();
|
|
901
|
+
};
|
|
740
902
|
|
|
741
903
|
/**
|
|
742
904
|
* Destroy the Agent, removing all state and scheduled tasks
|
|
@@ -745,20 +907,176 @@ export class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
745
907
|
// drop all tables
|
|
746
908
|
this.sql`DROP TABLE IF EXISTS cf_agents_state`;
|
|
747
909
|
this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
|
|
910
|
+
this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
|
|
748
911
|
|
|
749
912
|
// delete all alarms
|
|
750
913
|
await this.ctx.storage.deleteAlarm();
|
|
751
914
|
await this.ctx.storage.deleteAll();
|
|
752
915
|
}
|
|
753
916
|
|
|
754
|
-
|
|
755
|
-
* Get all methods marked as callable on this Agent
|
|
756
|
-
* @returns A map of method names to their metadata
|
|
757
|
-
*/
|
|
758
|
-
#isCallable(method: string): boolean {
|
|
917
|
+
private _isCallable(method: string): boolean {
|
|
759
918
|
// biome-ignore lint/complexity/noBannedTypes: <explanation>
|
|
760
919
|
return callableMetadata.has(this[method as keyof this] as Function);
|
|
761
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
|
+
private _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
|
+
}
|
|
762
1080
|
}
|
|
763
1081
|
|
|
764
1082
|
/**
|
|
@@ -862,7 +1180,7 @@ export async function routeAgentEmail<Env>(
|
|
|
862
1180
|
* @param options Options for Agent creation
|
|
863
1181
|
* @returns Promise resolving to an Agent instance stub
|
|
864
1182
|
*/
|
|
865
|
-
export function getAgentByName<Env, T extends Agent<Env>>(
|
|
1183
|
+
export async function getAgentByName<Env, T extends Agent<Env>>(
|
|
866
1184
|
namespace: AgentNamespace<T>,
|
|
867
1185
|
name: string,
|
|
868
1186
|
options?: {
|
|
@@ -877,13 +1195,13 @@ export function getAgentByName<Env, T extends Agent<Env>>(
|
|
|
877
1195
|
* A wrapper for streaming responses in callable methods
|
|
878
1196
|
*/
|
|
879
1197
|
export class StreamingResponse {
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
1198
|
+
private _connection: Connection;
|
|
1199
|
+
private _id: string;
|
|
1200
|
+
private _closed = false;
|
|
883
1201
|
|
|
884
1202
|
constructor(connection: Connection, id: string) {
|
|
885
|
-
this
|
|
886
|
-
this
|
|
1203
|
+
this._connection = connection;
|
|
1204
|
+
this._id = id;
|
|
887
1205
|
}
|
|
888
1206
|
|
|
889
1207
|
/**
|
|
@@ -891,17 +1209,17 @@ export class StreamingResponse {
|
|
|
891
1209
|
* @param chunk The data to send
|
|
892
1210
|
*/
|
|
893
1211
|
send(chunk: unknown) {
|
|
894
|
-
if (this
|
|
1212
|
+
if (this._closed) {
|
|
895
1213
|
throw new Error("StreamingResponse is already closed");
|
|
896
1214
|
}
|
|
897
1215
|
const response: RPCResponse = {
|
|
898
1216
|
type: "rpc",
|
|
899
|
-
id: this
|
|
1217
|
+
id: this._id,
|
|
900
1218
|
success: true,
|
|
901
1219
|
result: chunk,
|
|
902
1220
|
done: false,
|
|
903
1221
|
};
|
|
904
|
-
this
|
|
1222
|
+
this._connection.send(JSON.stringify(response));
|
|
905
1223
|
}
|
|
906
1224
|
|
|
907
1225
|
/**
|
|
@@ -909,17 +1227,17 @@ export class StreamingResponse {
|
|
|
909
1227
|
* @param finalChunk Optional final chunk of data to send
|
|
910
1228
|
*/
|
|
911
1229
|
end(finalChunk?: unknown) {
|
|
912
|
-
if (this
|
|
1230
|
+
if (this._closed) {
|
|
913
1231
|
throw new Error("StreamingResponse is already closed");
|
|
914
1232
|
}
|
|
915
|
-
this
|
|
1233
|
+
this._closed = true;
|
|
916
1234
|
const response: RPCResponse = {
|
|
917
1235
|
type: "rpc",
|
|
918
|
-
id: this
|
|
1236
|
+
id: this._id,
|
|
919
1237
|
success: true,
|
|
920
1238
|
result: finalChunk,
|
|
921
1239
|
done: true,
|
|
922
1240
|
};
|
|
923
|
-
this
|
|
1241
|
+
this._connection.send(JSON.stringify(response));
|
|
924
1242
|
}
|
|
925
1243
|
}
|